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_wait4.py | """This test checks for correct wait4() behavior.
"""
import os
import time
from test.fork_wait import ForkWait
from test.test_support import run_unittest, reap_children, get_attribute
# If either of these do not exist, skip this test.
get_attribute(os, 'fork')
get_attribute(os, 'wait4')
class Wait4Test(ForkWait):
... |
if __name__ == "__main__":
test_main()
| run_unittest(Wait4Test)
reap_children() | identifier_body |
test_wait4.py | """This test checks for correct wait4() behavior.
"""
import os
import time
from test.fork_wait import ForkWait
from test.test_support import run_unittest, reap_children, get_attribute
# If either of these do not exist, skip this test.
get_attribute(os, 'fork')
get_attribute(os, 'wait4')
class Wait4Test(ForkWait):
... | self.assertTrue(rusage)
def test_main():
run_unittest(Wait4Test)
reap_children()
if __name__ == "__main__":
test_main() | time.sleep(1.0)
self.assertEqual(spid, cpid)
self.assertEqual(status, 0, "cause = %d, exit = %d" % (status&0xff, status>>8)) | random_line_split |
test_wait4.py | """This test checks for correct wait4() behavior.
"""
import os
import time
from test.fork_wait import ForkWait
from test.test_support import run_unittest, reap_children, get_attribute
# If either of these do not exist, skip this test.
get_attribute(os, 'fork')
get_attribute(os, 'wait4')
class Wait4Test(ForkWait):
... | ():
run_unittest(Wait4Test)
reap_children()
if __name__ == "__main__":
test_main()
| test_main | identifier_name |
lib.rs | 32, i32) {
self.glfw.with_primary_monitor(|_, display| {
let display = display.expect("Could not get primnay display");
display.get_pos()
})
}
#[cfg(target_os="linux")]
fn create_hmd_window(&mut self, hmd: &ovr::HmdDescription) -> Option<(glfw::Window, Receiver<(f64,... | {
self.size = (x, y);
} | conditional_block | |
lib.rs | (glfw :&mut Glfw, width: u32, height: u32, name: &str, mode: glfw::WindowMode)
-> Option<(glfw::Window, Receiver<(f64, glfw::WindowEvent)>)> {
nice_glfw::WindowBuilder::new(glfw)
.try_modern_context_hints()
.size(width, height)
.title(name)
.mode(mode)
.create()
}
i... | create_window_context | identifier_name | |
lib.rs | glfw: glfw,
ovr: None,
windows: TrieMap::new(),
window_id: 0
}
}
fn add_window(&mut self, window: glfw::Window, recv: Receiver<(f64, glfw::WindowEvent)>) -> InputHandle {
let id = self.window_id;
self.window_id += 1;
let (w, h) = ... |
pub fn set_window_position(&mut self, window: &Window, pos: (i32, i32)) {
let (w, h) = pos;
match self.windows.get_mut(&window.handle.handle) {
Some(win) => win.window.set_pos(w, h),
None => ()
}
}
pub fn get_framebuffer_size(&mut self, window: &Window) -> ... | {
if self.ovr.is_some() &&
self.ovr.as_ref().unwrap().detect() > 0 {
return true;
}
if self.ovr.is_none() {
self.ovr = ovr::Ovr::init();
}
self.ovr.is_some() && self.ovr.as_ref().unwrap().detect() > 0
} | identifier_body |
lib.rs | glfw: glfw,
ovr: None,
windows: TrieMap::new(),
window_id: 0
}
}
fn add_window(&mut self, window: glfw::Window, recv: Receiver<(f64, glfw::WindowEvent)>) -> InputHandle {
let id = self.window_id;
self.window_id += 1;
let (w, h) = ... | return Some((window, events));
}
None
})
}
pub fn hmd(&mut self) -> Option<Window> {
if !self.setup_ovr() {
return None;
}
let (window, events, rc, hmd) = {
let hmd = match self.ovr.as_ref().unwrap().first_hmd() {
... | Some((window, events)) => (window, events),
None => return None
};
| random_line_split |
type_annotator.js | // Copyright 2011 Google Inc. All Rights Reserved.
/**
* @fileoverview Description of this file.
* @author rowillia@google.com (Roy Williams)
*/
goog.provide('glslunit.TypeAnnotator');
goog.require('glslunit.VariableScopeVisitor');
/**
* @param {!Object} rootNode
* @constructor
* @extends {glslunit.Variable... | else {
typeName = declaration.typeAttribute.name;
declaration = goog.array.find(declaration.declarators,
function(elem, i, arr) {
return elem.name.name == node.name;
});
}
if (declaration.arraySize || declaration.isArray) {
typeName += '[';
... | {
typeName = declaration.type_name;
} | conditional_block |
type_annotator.js | // Copyright 2011 Google Inc. All Rights Reserved.
/**
* @fileoverview Description of this file.
* @author rowillia@google.com (Roy Williams)
*/
goog.provide('glslunit.TypeAnnotator');
goog.require('glslunit.VariableScopeVisitor');
/**
* @param {!Object} rootNode
* @constructor
* @extends {glslunit.Variable... | glslunit.TypeAnnotator.prototype.visitIdentifier = function(node) {
var declaration = this.getCurrentVariableMap()[node.name];
var typeName = '';
if (declaration) {
if (declaration.type == 'parameter') {
typeName = declaration.type_name;
} else {
typeName = declaration.typeAttribute.name;
... | this.typeMap_ = {}''
};
goog.inherits(glslunit.TypeAnnotator, glslunit.VariableScopeVisitor);
| random_line_split |
index.ts | import * as walkSync from 'walk-sync';
import * as fs from 'fs';
import create from './offers';
import db from '../';
function mockup() {
const path = `${__dirname}`;
const paths = walkSync(`${path}`, { globs: ['*.json'] });
const promises = [];
paths.forEach((file) => {
const json = fs.readFileSync(`${... | () {
if (process.env.NODE_ENV !== 'test') return false;
return db['sequelize'].sync({ force: true })
.then(mockup)
.then(create);
}
createAll();
| createAll | identifier_name |
index.ts | import * as walkSync from 'walk-sync';
import * as fs from 'fs';
import create from './offers';
import db from '../';
function mockup() {
const path = `${__dirname}`;
const paths = walkSync(`${path}`, { globs: ['*.json'] });
const promises = [];
paths.forEach((file) => {
const json = fs.readFileSync(`${... |
createAll();
| {
if (process.env.NODE_ENV !== 'test') return false;
return db['sequelize'].sync({ force: true })
.then(mockup)
.then(create);
} | identifier_body |
index.ts | import * as walkSync from 'walk-sync';
import * as fs from 'fs';
import create from './offers';
import db from '../';
| const path = `${__dirname}`;
const paths = walkSync(`${path}`, { globs: ['*.json'] });
const promises = [];
paths.forEach((file) => {
const json = fs.readFileSync(`${path}/${file}`, 'utf-8');
try {
const data = JSON.parse(json);
const model = file.replace('.json', '');
promises.push(d... |
function mockup() { | random_line_split |
gulpfile.js | 'use strict';
var _ = require('lodash');
var del = require('del');
var gulp = require('gulp');
var argv = require('minimist')(process.argv.slice(2));
var webpack = require('webpack');
var browserSync = require('browser-sync');
var htmlcompress = require('gulp-minify-html');
var gutil = require('gulp-util');
var gif = ... |
if (!started) {
started = true;
cb();
}
}
var compiler = webpack(config);
if (config.watch) {
compiler.watch(200, processResult);
} else {
compiler.run(processResult);
}
});
gulp.task('pages', function () {
return gulp.src(settings.ind... | {
browserSync.reload(settings.entry);
} | conditional_block |
gulpfile.js | 'use strict';
var _ = require('lodash');
var del = require('del');
var gulp = require('gulp');
var argv = require('minimist')(process.argv.slice(2));
var webpack = require('webpack');
var browserSync = require('browser-sync');
var htmlcompress = require('gulp-minify-html');
var gutil = require('gulp-util');
var gif = ... | (err, stats) {
gutil.log('Webpack\n' + stats.toString(config.log));
if (config.watch) {
browserSync.reload(settings.entry);
}
if (!started) {
started = true;
cb();
}
}
var compiler = webpack(config);
if (config.watch) {
c... | processResult | identifier_name |
gulpfile.js | 'use strict';
var _ = require('lodash');
var del = require('del');
var gulp = require('gulp');
var argv = require('minimist')(process.argv.slice(2));
var webpack = require('webpack');
var browserSync = require('browser-sync');
var htmlcompress = require('gulp-minify-html');
var gutil = require('gulp-util');
var gif = ... | }
});
cb();
});
gulp.task('dev', function (cb) {
WATCH = true;
runSequence('build-dev', 'server', cb);
});
gulp.task('prod', function (cb) {
WATCH = true;
runSequence('build-prod', 'server', cb);
});
gulp.task('ci', ['build-ci'], function () {
return gulp.src(['dist/**', '!dist... |
gulp.task('server', function (cb) {
browserSync({
server: {
baseDir: [settings.server] | random_line_split |
gulpfile.js | 'use strict';
var _ = require('lodash');
var del = require('del');
var gulp = require('gulp');
var argv = require('minimist')(process.argv.slice(2));
var webpack = require('webpack');
var browserSync = require('browser-sync');
var htmlcompress = require('gulp-minify-html');
var gutil = require('gulp-util');
var gif = ... | if (!RELEASE || DEBUG) {
config.devtool = '#inline-source-map';
}
return config;
}
gulp.task('bundle', function (cb) {
var started = false;
var config = getBundleConfig();
function processResult(err, stats) {
gutil.log('Webpack\n' + stats.toString(config.log));
if (co... | {
var config = _.defaultsDeep({}, require('./webpack.config'));
config.entry = settings.entry;
config.output.path = settings.output;
if (WATCH) {
// config.chunkModules = false;
config.watch = true;
}
if (RELEASE) {
config.plugins = config.plugins.concat(
n... | identifier_body |
threaded_task_manager.py | of your app with
# several values. For Socorro, we've found that setting this value to the
# number of processor cores in the system gives the best throughput.
required_config.add_option(
'number_of_threads',
default=4,
doc='the number of threads'
)
# there is wisdom is setting t... |
#--------------------------------------------------------------------------
def wait_for_completion(self, waiting_func=None):
"""This is a blocking function call that will wait for the queuing
thread to complete.
parameters:
waiting_func - this function will be called ever... | """this function will start the queing thread that executes the
iterator and feeds jobs into the queue. It also starts the worker
threads that just sit and wait for items to appear on the queue. This
is a non blocking call, so the executing thread is free to do other
things while the ot... | identifier_body |
threaded_task_manager.py | (TaskManager):
"""Given an iterator over a sequence of job parameters and a function,
this class will execute the function in a set of threads."""
required_config = Namespace()
required_config.add_option(
'idle_delay',
default=7,
doc='the delay in seconds if no job is found'
)
... | ThreadedTaskManager | identifier_name | |
threaded_task_manager.py | put of your app with
# several values. For Socorro, we've found that setting this value to the
# number of processor cores in the system gives the best throughput.
required_config.add_option(
'number_of_threads',
default=4,
doc='the number of threads'
)
# there is wisdom is setti... | self.start()
self.wait_for_completion(waiting_func)
# it only ends if someone hits ^C or sends SIGHUP or SIGTERM -
# any of which will get translated into a KeyboardInterrupt
except KeyboardInterrupt:
while True:
try:
... | random_line_split | |
threaded_task_manager.py | of your app with
# several values. For Socorro, we've found that setting this value to the
# number of processor cores in the system gives the best throughput.
required_config.add_option(
'number_of_threads',
default=4,
doc='the number of threads'
)
# there is wisdom is setting t... |
else:
self.logger.debug("the loop didn't actually loop")
except Exception:
self.logger.error('queuing jobs has failed', exc_info=True)
except KeyboardInterrupt:
self.logger.debug('queuingThread gets quit request')
finally:
self.qui... | if job_params is None:
self.logger.info("there is nothing to do. Sleeping "
"for %d seconds" %
self.config.idle_delay)
self._responsive_sleep(self.config.idle_delay)
continue
... | conditional_block |
timedmute.py | # Timed mute: !tm <player> <seconds> <reason>
# default time 5 minutes, default reason None
# by topologist June 30th 2012
from scheduler import Scheduler
from commands import add, admin, get_player, join_arguments, name
@name('tm')
@admin
def timed_mute(connection, *args):
protocol = connection.protocol
... |
def end(self):
self.player.mute = False
message = '%s was unmuted after %s seconds' % (self.player.name, self.time)
self.player.protocol.send_chat(message, irc = True)
def apply_script(protocol, connection, config):
class TimedMuteConnection(connection):
mute_schedule = None
def o... | player.name, time, reason), irc = True)
player.mute = True
self.player = player
self.time = time
| random_line_split |
timedmute.py | # Timed mute: !tm <player> <seconds> <reason>
# default time 5 minutes, default reason None
# by topologist June 30th 2012
from scheduler import Scheduler
from commands import add, admin, get_player, join_arguments, name
@name('tm')
@admin
def timed_mute(connection, *args):
|
add(timed_mute)
class TimedMute(object):
player = None
time = None
def __init__(self, player, time = 300, reason = 'None'):
if time == 0:
player.mute = True
player.protocol.send_chat('%s was muted indefinitely (Reason: %s)' % (
player.name, reason), irc = True)
ret... | protocol = connection.protocol
nick = args[0]
time = int(args[1])
reason = join_arguments(args[2:])
player = get_player(protocol, nick)
if time < 0:
raise ValueError()
if not player.mute:
TimedMute(player, time, reason)
else:
return '%s is already muted!' % nick | identifier_body |
timedmute.py | # Timed mute: !tm <player> <seconds> <reason>
# default time 5 minutes, default reason None
# by topologist June 30th 2012
from scheduler import Scheduler
from commands import add, admin, get_player, join_arguments, name
@name('tm')
@admin
def timed_mute(connection, *args):
protocol = connection.protocol
... |
connection.on_disconnect(self)
return protocol, TimedMuteConnection
| del self.mute_schedule | conditional_block |
timedmute.py | # Timed mute: !tm <player> <seconds> <reason>
# default time 5 minutes, default reason None
# by topologist June 30th 2012
from scheduler import Scheduler
from commands import add, admin, get_player, join_arguments, name
@name('tm')
@admin
def | (connection, *args):
protocol = connection.protocol
nick = args[0]
time = int(args[1])
reason = join_arguments(args[2:])
player = get_player(protocol, nick)
if time < 0:
raise ValueError()
if not player.mute:
TimedMute(player, time, reason)
else:
return '%s is already mu... | timed_mute | identifier_name |
synth.rs | use std::i16;
use std::mem;
pub trait Generator {
fn amp(&self, t: f64) -> f64;
fn map<'r>(self, f: |f64|: 'static -> f64) -> MappedGenerator<Self> {
MappedGenerator { g: self, f: f }
}
}
pub struct MappedGenerator<G> {
g: G,
f: |f64|: 'static -> f64
}
impl<'r, G: Generator> Generator for MappedGenera... | {
notes: Vec<Note>
}
impl Melody {
pub fn new(notes: Vec<Note>) -> Melody {
Melody { notes: notes }
}
pub fn duration(&self) -> f64 {
self.notes.iter().fold(0.0, |a, &Note(_,d)| { a + d })
}
}
impl ::Generator for Melody {
fn amp(&self, t: f64) -> f64 {
let mut a = ... | Melody | identifier_name |
synth.rs | use std::i16;
use std::mem;
pub trait Generator {
fn amp(&self, t: f64) -> f64;
fn map<'r>(self, f: |f64|: 'static -> f64) -> MappedGenerator<Self> {
MappedGenerator { g: self, f: f }
}
}
pub struct MappedGenerator<G> {
g: G,
f: |f64|: 'static -> f64
}
impl<'r, G: Generator> Generator for MappedGenera... | (generator.amp(t) * (i16::MAX - 1) as f64) as i16
})
} | random_line_split | |
synth.rs | use std::i16;
use std::mem;
pub trait Generator {
fn amp(&self, t: f64) -> f64;
fn map<'r>(self, f: |f64|: 'static -> f64) -> MappedGenerator<Self> |
}
pub struct MappedGenerator<G> {
g: G,
f: |f64|: 'static -> f64
}
impl<'r, G: Generator> Generator for MappedGenerator<G> {
fn amp(&self, t: f64) -> f64 {
let f: &mut |f64|: 'static -> f64 = unsafe { mem::transmute(&self.f) };
(*f)(self.g.amp(t))
}
}
pub mod waves {
use std::f64::consts::PI;
p... | {
MappedGenerator { g: self, f: f }
} | identifier_body |
performance_timeline.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/. */
// XXX The spec says that the performance timeline task source should be
// a low priority task and it should ... |
}
impl TaskSource for PerformanceTimelineTaskSource {
fn queue_with_canceller<T>(
&self,
task: T,
canceller: &TaskCanceller,
) -> Result<(), ()>
where
T: TaskOnce + 'static,
{
let msg = CommonScriptMsg::Task(
ScriptThreadEventCategory::PerformanceTim... | {
write!(f, "PerformanceTimelineTaskSource(...)")
} | identifier_body |
performance_timeline.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/. */
// XXX The spec says that the performance timeline task source should be
// a low priority task and it should ... | (&self) -> PerformanceTimelineTaskSource {
PerformanceTimelineTaskSource(self.0.clone())
}
}
impl fmt::Debug for PerformanceTimelineTaskSource {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "PerformanceTimelineTaskSource(...)")
}
}
impl TaskSource for PerformanceTimelin... | clone | identifier_name |
performance_timeline.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/. */
// XXX The spec says that the performance timeline task source should be
// a low priority task and it should ... | {
let msg = CommonScriptMsg::Task(
ScriptThreadEventCategory::PerformanceTimelineTask,
Box::new(canceller.wrap_task(task))
);
self.0.send(msg).map_err(|_| ())
}
}
impl PerformanceTimelineTaskSource {
pub fn queue_notification(&self, global: &GlobalScope) {
... | random_line_split | |
home.js | 'use strict';
angular.module('myApp.home', ['ngRoute','firebase'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/home', {
templateUrl: 'home/home.html',
controller: 'HomeCtrl'
});
}])
.controller('HomeCtrl', ['$scope','$location','CommonProp','$firebaseAuth',function($scope,$l... | //Failure callback
console.log('Authentication failure');
});
}
}])
.service('CommonProp', function() {
var user = '';
return {
getUser: function() {
return user;
},
setUser: function(value) {
user = value;
}
};
}); | }, function(error) { | random_line_split |
index.ios.js | import React, {
Component,
View,
StyleSheet,
Text,
TouchableHighlight,
PropTypes,
NativeModules,
DeviceEventEmitter
} from 'react-native';
import { login, logout, getCredentials, liEvents} from './util';
import styles from './theme/style';
const Icon = require('react-native-vector-icons/FontAwesome');
... |
prepareStyle() {
const { style ={} } = this.props;
const LILMText = style.LILMText || styles.LILMText;
const LILMTextLoggedIn = style.LILMTextLoggedIn || styles.LILMTextLoggedIn;
const LILMTextLoggedOut = style.LILMTextLoggedOut || styles.LILMTextLoggedOut;
return {
LILMButton: style.LILM... | {
getCredentials().then((data)=>{
this.setState({ credentials : data });
}).catch((err) =>{
this.setState({ credentials : null });
console.log('Request failed: ', err);
});
} | identifier_body |
index.ios.js | import React, {
Component,
View,
StyleSheet,
Text,
TouchableHighlight,
PropTypes,
NativeModules,
DeviceEventEmitter
} from 'react-native';
import { login, logout, getCredentials, liEvents} from './util';
import styles from './theme/style';
const Icon = require('react-native-vector-icons/FontAwesome');
... | const { LILMButton, LILMButtonContent, LILMIconWrap, LILMIcon, LILMTextWrap, LILMText} = this.prepareStyle();
return (
<TouchableHighlight style={ LILMButton } onPress={this.onPress.bind(this)}>
<View style={LILMButtonContent}>
<View style={ LILMIconWrap }>
<Icon name="linked... | const text = this.state.credentials ? logoutText : loginText; | random_line_split |
index.ios.js | import React, {
Component,
View,
StyleSheet,
Text,
TouchableHighlight,
PropTypes,
NativeModules,
DeviceEventEmitter
} from 'react-native';
import { login, logout, getCredentials, liEvents} from './util';
import styles from './theme/style';
const Icon = require('react-native-vector-icons/FontAwesome');
... | extends Component {
constructor(props) {
super(props);
this.willUnmountSoon = false;
this.state = {
credentials: null,
subscriptions: []
};
}
handleLogin() {
login(this.props.appDetails).then((data) => {
if (!this.willUnmountSoon) this.setState({ credentials : data });
... | LILoginMock | identifier_name |
procurement.py | pickings that represent the sale order.
Used in: sales order (to group delivery order lines like the so), pull/push
rules (to pack like the delivery order), on orderpoints (e.g. for wave picking
all the similar products together).
Grouping is made only if the source and the destination is the same.
... | (self):
return self.write({'state': 'confirmed'})
@api.multi
def run(self, autocommit=False):
# TDE FIXME: avoid browsing everything -> avoid prefetching ?
for procurement in self:
# we intentionnaly do the browse under the for loop to avoid caching all ids which would be re... | reset_to_confirmed | identifier_name |
procurement.py | into pickings that represent the sale order.
Used in: sales order (to group delivery order lines like the so), pull/push
rules (to pack like the delivery order), on orderpoints (e.g. for wave picking
all the similar products together).
Grouping is made only if the source and the destination is the sa... |
@api.multi
def _check(self):
'''Returns True if the given procurement is fulfilled, False otherwise
:rtype: boolean
'''
return False
#
# Scheduler
#
@api.model
def run_scheduler(self, use_new_cursor=False | '''This method implements the resolution of the given procurement
:returns: True if the resolution of the procurement was a success, False otherwise to set it in exception
'''
return True | identifier_body |
procurement.py | into pickings that represent the sale order.
Used in: sales order (to group delivery order lines like the so), pull/push
rules (to pack like the delivery order), on orderpoints (e.g. for wave picking
all the similar products together).
Grouping is made only if the source and the destination is the sa... |
return True
@api.multi
@api.returns('self', lambda procurements: [procurement.id for procurement in procurements])
def check(self, autocommit=False):
# TDE FIXME: check should not do something, just check
procurements_done = self.env['procurement.order']
for procurement in ... | raise | conditional_block |
procurement.py | into pickings that represent the sale order.
Used in: sales order (to group delivery order lines like the so), pull/push
rules (to pack like the delivery order), on orderpoints (e.g. for wave picking
all the similar products together).
Grouping is made only if the source and the destination is the sa... | return procurement
@api.multi
def unlink(self):
if any(procurement.state == 'cancel' for procurement in self):
raise UserError(_('You cannot delete procurements that are in cancel state.'))
return super(ProcurementOrder, self).unlink()
@api.multi
def do_view_procure... | procurement = super(ProcurementOrder, self).create(vals)
if not self._context.get('procurement_autorun_defer'):
procurement.run() | random_line_split |
StdpCtrlTemplate.py | # -*- coding: utf-8 -*-
from __future__ import print_function
# Form implementation generated from reading ui file './acq4/analysis/old/StdpCtrlTemplate.ui'
#
# Created: Tue Dec 24 01:49:15 2013
# by: PyQt4 UI code generator 4.10
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, ... |
class Ui_StdpCtrlWidget(object):
def setupUi(self, StdpCtrlWidget):
StdpCtrlWidget.setObjectName(_fromUtf8("StdpCtrlWidget"))
StdpCtrlWidget.resize(227, 321)
self.gridLayout = QtGui.QGridLayout(StdpCtrlWidget)
self.gridLayout.setMargin(0)
self.gridLayout.setSpacing(0)
... | return QtGui.QApplication.translate(context, text, disambig) | identifier_body |
StdpCtrlTemplate.py | # -*- coding: utf-8 -*-
from __future__ import print_function
| # by: PyQt4 UI code generator 4.10
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, t... | # Form implementation generated from reading ui file './acq4/analysis/old/StdpCtrlTemplate.ui'
#
# Created: Tue Dec 24 01:49:15 2013 | random_line_split |
StdpCtrlTemplate.py | # -*- coding: utf-8 -*-
from __future__ import print_function
# Form implementation generated from reading ui file './acq4/analysis/old/StdpCtrlTemplate.ui'
#
# Created: Tue Dec 24 01:49:15 2013
# by: PyQt4 UI code generator 4.10
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, ... | (context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_StdpCtrlWidget(object):
def setupUi(self, StdpCtrlWidget):
StdpCtrlWidget.setObjectName(_fromUtf8("StdpCtrlWidget"))
StdpCtrlWidget.resize(227, 321)
self.gridLayout = QtGui.QGridLayout(S... | _translate | identifier_name |
Gruntfile.js | module.exports = function(grunt) {
"use strict";
var jsFiles = ["Gruntfile.js", "src/**/*.js"];
var htmlfiles = ["src/view/todoList.html", "src/view/todoFooter.html", "src/view/todoCreater.html"];
grunt.initConfig({
jshint: { | jshintignore: ".jshintignore"
}
},
watch: {
css: {
options: {
livereload: true
},
files: ["src/**/*.css"]
},
js: {
options: {
livereload: true
},
files: ["src/**/*.js"]
},
html: {
options: {
... | all: jsFiles,
options: {
jshintrc: ".jshintrc", | random_line_split |
app.routing.ts | import { AuthGuard } from './common/auth.guard';
import { CanDeactivateGuard } from './common/canDeactivate.guard';
import { RouterModule, Routes } from '@angular/router';
import { capitalizeURL } from './common/utils';
import { AlertDebugComponent } from './components/alert-debug/alert-debug.component';
import { Quo... | (url: string) {
return `MyMICDS - ${capitalizeURL(url)}`;
}
/**
* Router Config
*/
export const appRoutes: Routes = [
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
},
{
path: 'quote',
component: QuotesComponent
},
{
path: 'alert-debug',
component: AlertDebugComponent
},
{
path: 'about',
... | defaultTitleFunction | identifier_name |
app.routing.ts | import { AuthGuard } from './common/auth.guard';
import { CanDeactivateGuard } from './common/canDeactivate.guard';
import { RouterModule, Routes } from '@angular/router';
import { capitalizeURL } from './common/utils';
import { AlertDebugComponent } from './components/alert-debug/alert-debug.component';
import { Quo... | path: 'daily-bulletin',
loadChildren: () =>
import('./daily-bulletin/daily-bulletin.module').then(m => m.DailyBulletinModule)
}
];
export const appRoutingProviders = [AuthGuard, CanDeactivateGuard];
export const routing = RouterModule.forRoot(appRoutes, { relativeLinkResolution: 'legacy' }); | path: 'unsubscribe',
loadChildren: () =>
import('./unsubscribe/unsubscribe.module').then(m => m.UnsubscribeModule)
},
{ | random_line_split |
app.routing.ts | import { AuthGuard } from './common/auth.guard';
import { CanDeactivateGuard } from './common/canDeactivate.guard';
import { RouterModule, Routes } from '@angular/router';
import { capitalizeURL } from './common/utils';
import { AlertDebugComponent } from './components/alert-debug/alert-debug.component';
import { Quo... |
/**
* Router Config
*/
export const appRoutes: Routes = [
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
},
{
path: 'quote',
component: QuotesComponent
},
{
path: 'alert-debug',
component: AlertDebugComponent
},
{
path: 'about',
loadChildren: () => import('./about/about.module').then(m ... | {
return `MyMICDS - ${capitalizeURL(url)}`;
} | identifier_body |
wrapper_head_tail.py | import sys
import petsc4py
petsc4py.init(sys.argv)
from ecoli_in_pipe import head_tail
# import numpy as np
# from scipy.interpolate import interp1d
# from petsc4py import PETSc
# from ecoli_in_pipe import single_ecoli, ecoliInPipe, head_tail, ecoli_U
# from codeStore import ecoli_common
#
#
# def call_head_tial(uz_f... | # # C1 = t_head_U[5] - t_tail_U[5]
# # C2 = t_head_U[5] / t_tail_U[5]
# # t_head_U[5] = wz_factor * C1 * C2 / (wz_factor * C2 - 1)
# # t_tail_U[5] = C1 / (wz_factor * C2 - 1)
# t_head_U[5] = wz_factor * t_head_U[5]
# t_kwargs = {'head_U': t_head_U,
# 'tail_U': t_tail_U, }
# t... | # t_head_U = head_U.copy()
# t_tail_U = tail_U.copy()
# t_head_U[2] = t_head_U[2] * uz_factor
# t_tail_U[2] = t_tail_U[2] * uz_factor | random_line_split |
copyspecial.py | #!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
import os
import shutil
import commands
"""Copy Special exercise
"""
#... | ():
# This basic command line argument parsing code is provided.
# Add code to call your functions below.
# Make a list of command line arguments, omitting the [0] element
# which is the script itself.
args = sys.argv[1:]
if not args:
print "usage: [--todir dir][--tozip zipfile] dir [dir ...]";
sys... | main | identifier_name |
copyspecial.py | #!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
import os
import shutil
import commands
"""Copy Special exercise
"""
#... |
def zip_to(paths, zippath):
"""Given a list of paths, zip those files up into the given zipfile"""
cmd = 'zip -j ' + zippath + ' ' + ' '.join(paths)
(status, output) = commands.getstatusoutput(cmd)
if status: ## Error case, print the command's output to stderr and exit
sys.stderr.write(output)
sys.... | """Given a list of paths, copies those files into the given directory"""
dest = os.path.abspath(dirname)
if not os.path.exists(dest):
os.makedirs(dest)
for path in paths:
shutil.copy(path, dest) | identifier_body |
copyspecial.py | #!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
import os
import shutil
import commands
"""Copy Special exercise
"""
#... |
if __name__ == "__main__":
main()
| for path in paths:
print path | conditional_block |
copyspecial.py | #!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
import os
import shutil
import commands
"""Copy Special exercise
"""
#... | dest = os.path.abspath(dirname)
if not os.path.exists(dest):
os.makedirs(dest)
for path in paths:
shutil.copy(path, dest)
def zip_to(paths, zippath):
"""Given a list of paths, zip those files up into the given zipfile"""
cmd = 'zip -j ' + zippath + ' ' + ' '.join(paths)
(status, output) = commands.... | def copy_to(paths, dirname):
"""Given a list of paths, copies those files into the given directory""" | random_line_split |
core.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use fnv::FnvHasher;
use std::ops::Deref;
use std::sync::Arc;
use std::{fmt, hash};
use crate::externs;
use crate::handles::Handle;
use smallvec::{smallvec, SmallVec};
pub type FNV = ... | (pub Key);
impl Function {
fn pretty_print(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Function(key) = self;
let name = externs::project_str(&externs::val_for(&key), "__name__");
write!(f, "{}()", name)
}
}
impl fmt::Display for Function {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt... | Function | identifier_name |
core.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use fnv::FnvHasher;
use std::ops::Deref;
use std::sync::Arc;
use std::{fmt, hash};
use crate::externs;
use crate::handles::Handle;
use smallvec::{smallvec, SmallVec};
pub type FNV = ... |
fn binary_search(&self, type_id: TypeId) -> Result<usize, usize> {
self
.0
.binary_search_by(|probe| probe.type_id().cmp(&type_id))
}
pub fn type_ids<'a>(&'a self) -> impl Iterator<Item = TypeId> + 'a {
self.0.iter().map(|k| *k.type_id())
}
///
/// Given a set of either param type or ... | pub fn find(&self, type_id: TypeId) -> Option<&Key> {
self.binary_search(type_id).ok().map(|idx| &self.0[idx])
} | random_line_split |
core.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use fnv::FnvHasher;
use std::ops::Deref;
use std::sync::Arc;
use std::{fmt, hash};
use crate::externs;
use crate::handles::Handle;
use smallvec::{smallvec, SmallVec};
pub type FNV = ... |
}
impl Deref for Value {
type Target = Handle;
fn deref(&self) -> &Handle {
&self.0
}
}
impl fmt::Debug for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", externs::val_to_str(&self))
}
}
///
/// Creates a Handle (which represents exclusive access) from a Value ... | {
Value(Arc::new(handle))
} | identifier_body |
mod.rs | use std::collections::BTreeMap;
use std::error;
use std::fmt;
use std::mem;
use {Value, Table};
#[cfg(feature = "rustc-serialize")] mod rustc_serialize;
#[cfg(feature = "serde")] mod serde;
/// A structure to transform Rust values into TOML values.
///
/// This encoder implements the serialization `Encoder` interfac... | <T: ::serde::Serialize>(t: &T) -> Value {
let mut e = Encoder::new();
t.serialize(&mut e).unwrap();
Value::Table(e.toml)
}
/// Encodes an encodable value into a TOML string.
///
/// This function expects the type given to represent a TOML table in some form.
/// If encoding encounters an error, then this f... | encode | identifier_name |
mod.rs | use std::collections::BTreeMap;
use std::error;
use std::fmt;
use std::mem;
use {Value, Table};
#[cfg(feature = "rustc-serialize")] mod rustc_serialize;
#[cfg(feature = "serde")] mod serde;
/// A structure to transform Rust values into TOML values.
///
/// This encoder implements the serialization `Encoder` interfac... | /// If encoding encounters an error, then this function will fail the task.
#[cfg(feature = "rustc-serialize")]
pub fn encode<T: ::rustc_serialize::Encodable>(t: &T) -> Value {
let mut e = Encoder::new();
t.encode(&mut e).unwrap();
Value::Table(e.toml)
}
/// Encodes an encodable value into a TOML value.
//... | ///
/// This function expects the type given to represent a TOML table in some form. | random_line_split |
mod.rs | use std::collections::BTreeMap;
use std::error;
use std::fmt;
use std::mem;
use {Value, Table};
#[cfg(feature = "rustc-serialize")] mod rustc_serialize;
#[cfg(feature = "serde")] mod serde;
/// A structure to transform Rust values into TOML values.
///
/// This encoder implements the serialization `Encoder` interfac... |
State::Start => f(self),
State::NextMapKey => Err(Error::InvalidMapKeyLocation),
}
}
fn table_key<F>(&mut self, f: F) -> Result<(), Error>
where F: FnOnce(&mut Encoder) -> Result<(), Error>
{
match mem::replace(&mut self.state, State::NextMapKey) {
... | {
let mut nested = Encoder::new();
try!(f(&mut nested));
arr.push(Value::Table(nested.toml));
self.state = State::NextArray(arr);
Ok(())
} | conditional_block |
mod.rs | use std::collections::BTreeMap;
use std::error;
use std::fmt;
use std::mem;
use {Value, Table};
#[cfg(feature = "rustc-serialize")] mod rustc_serialize;
#[cfg(feature = "serde")] mod serde;
/// A structure to transform Rust values into TOML values.
///
/// This encoder implements the serialization `Encoder` interfac... |
}
| { "TOML encoding error" } | identifier_body |
animate_particles_2d_labframe.py | from numpy import *
from matplotlib import pyplot
import scripts.skewtools as st
import sys
X,Y,t,Pe = st.importDatasets(sys.argv[1],'X','Y','Time','Peclet')
figscale = 5.
fig,ax = pyplot.subplots(1,1,figsize=(4*figscale,figscale))
uwall = 2./3.
xmax = X.max() + uwall*Pe*t[-1]
for i in range(len(t)):
#for i in [5... |
# end for
#pyplot.tight_layout()
| ax.cla()
# ax.hold(True)
ax.plot([0,xmax],[1,1],linewidth=0.5,color='k')
ax.plot([0,xmax],[-1,-1],linewidth=0.5,color='k')
subset1 = ((Y[:,i]<1.)*(Y[:,i] > -1.))
subset2 = ~subset1
ax.scatter(X[subset1,i],Y[subset1,i],facecolor=[0,0,0.9],edgecolor=[0,0,0,0],s=1,alpha=0.2)
ax.scatter(... | conditional_block |
animate_particles_2d_labframe.py | from numpy import *
from matplotlib import pyplot
import scripts.skewtools as st
import sys
X,Y,t,Pe = st.importDatasets(sys.argv[1],'X','Y','Time','Peclet')
figscale = 5.
fig,ax = pyplot.subplots(1,1,figsize=(4*figscale,figscale))
uwall = 2./3.
xmax = X.max() + uwall*Pe*t[-1]
for i in range(len(t)):
#for i in [5... | ax.set_ylim([-1.05,1.05])
print '%i active particles, %i of %i frames'%(sum(subset1),i,len(t)-1)
pyplot.savefig('cloudframe_'+str(i).zfill(4)+'.png',dpi=80,bbox_inches='tight')
# end for
#pyplot.tight_layout() | ax.scatter(X[subset2,i],Y[subset2,i],facecolor=[0.9,0,0],edgecolor=[0,0,0,0],s=1,alpha=0.2)
# ax.hist2d(X[subset,i] + uwall*Pe*t[i],Y[subset,i],cmap=pyplot.cm.inferno,)
# ax.hold(False)
ax.set_xlim([0.,xmax]) | random_line_split |
FBrowserBase.py | #
# FBrowserBase.py -- Base class for file browser plugin for fits viewer
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import os, glob
import stat, time
from ging... |
if os.path.isdir(path):
path = os.path.join(path, '*')
self.browse(path)
elif os.path.exists(path):
#self.fv.load_file(path)
uri = "file://%s" % (path)
self.fitsimage.make_callback('drag-drop', [uri])
else:
s... | curdir, curglob = os.path.split(self.curpath)
path = os.path.join(curdir, path, curglob) | conditional_block |
FBrowserBase.py | #
# FBrowserBase.py -- Base class for file browser plugin for fits viewer
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import os, glob
import stat, time
from ging... | self.logger.info("Generating thumbnails for '%s'..." % (
path))
filelist = glob.glob(path)
filelist.sort(key=str.lower)
# find out our channel
chname = self.fv.get_channelName(self.fitsimage)
# Invoke the method in this channel's Thumbs plugin
... | def make_thumbs(self):
path = self.curpath | random_line_split |
FBrowserBase.py | #
# FBrowserBase.py -- Base class for file browser plugin for fits viewer
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import os, glob
import stat, time
from ging... | (self, path):
dirname, filename = os.path.split(path)
name, ext = os.path.splitext(filename)
ftype = 'file'
if os.path.isdir(path):
ftype = 'dir'
elif os.path.islink(path):
ftype = 'link'
elif ext.lower() == '.fits':
ftype = 'fits'
... | get_info | identifier_name |
FBrowserBase.py | #
# FBrowserBase.py -- Base class for file browser plugin for fits viewer
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import os, glob
import stat, time
from ging... |
def resume(self):
pass
def stop(self):
pass
def redo(self):
return True
#END
| pass | identifier_body |
Frame-onStep-14.js | // Test how stepping interacts with switch statements.
var g = newGlobal();
g.eval('function bob() { return "bob"; }');
// Stepping into a sparse switch should not stop on literal cases.
evaluate(`function lit(x) { // 1
debugger; // 2
switch(x) { // 3
case "nope": ... |
test("lit('bob');", 7);
test("nonlit('bob');", 4);
| {
dbg.onDebuggerStatement = function(frame) {
frame.onStep = function() {
let thisLine = this.script.getOffsetLocation(this.offset).lineNumber;
// The stop at line 3 is the switch.
if (thisLine > 3) {
assertEq(thisLine, okLine)
frame.onStep = undefined;
}
};
};
g.ev... | identifier_body |
Frame-onStep-14.js | // Test how stepping interacts with switch statements.
var g = newGlobal();
g.eval('function bob() { return "bob"; }');
// Stepping into a sparse switch should not stop on literal cases.
evaluate(`function lit(x) { // 1
debugger; // 2
switch(x) { // 3
case "nope": ... |
var dbg = Debugger(g);
var badStep = false;
function test(s, okLine) {
dbg.onDebuggerStatement = function(frame) {
frame.onStep = function() {
let thisLine = this.script.getOffsetLocation(this.offset).lineNumber;
// The stop at line 3 is the switch.
if (thisLine > 3) {
assertEq(thisLin... | case bob(): // 4
break; // 5
} // 6
}`, {lineNumber: 1, global: g}); | random_line_split |
Frame-onStep-14.js | // Test how stepping interacts with switch statements.
var g = newGlobal();
g.eval('function bob() { return "bob"; }');
// Stepping into a sparse switch should not stop on literal cases.
evaluate(`function lit(x) { // 1
debugger; // 2
switch(x) { // 3
case "nope": ... |
};
};
g.eval(s);
}
test("lit('bob');", 7);
test("nonlit('bob');", 4);
| {
assertEq(thisLine, okLine)
frame.onStep = undefined;
} | conditional_block |
Frame-onStep-14.js | // Test how stepping interacts with switch statements.
var g = newGlobal();
g.eval('function bob() { return "bob"; }');
// Stepping into a sparse switch should not stop on literal cases.
evaluate(`function lit(x) { // 1
debugger; // 2
switch(x) { // 3
case "nope": ... | (s, okLine) {
dbg.onDebuggerStatement = function(frame) {
frame.onStep = function() {
let thisLine = this.script.getOffsetLocation(this.offset).lineNumber;
// The stop at line 3 is the switch.
if (thisLine > 3) {
assertEq(thisLine, okLine)
frame.onStep = undefined;
}
};... | test | identifier_name |
option-pager.component.ts | import { ChangeDetectionStrategy, Component, forwardRef } from '@angular/core';
import { ALuOnScrollBottomSubscriber, ILuOnScrollBottomSubscriber } from '@lucca-front/ng/core';
import { BehaviorSubject, combineLatest, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ALuOptionOperator, ILuOptionO... |
paging$ = new BehaviorSubject<number>(MAGIC_STEP);
next() {
this.paging$.next(this.paging$.value + MAGIC_STEP);
}
onScrollBottom() {
this.next();
}
}
| {
this.outOptions$ = combineLatest([in$, this.paging$]).pipe(
map(([options, paging]) => {
return (options || []).slice(0, paging);
}),
);
} | identifier_body |
option-pager.component.ts | import { ChangeDetectionStrategy, Component, forwardRef } from '@angular/core';
import { ALuOnScrollBottomSubscriber, ILuOnScrollBottomSubscriber } from '@lucca-front/ng/core';
import { BehaviorSubject, combineLatest, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ALuOptionOperator, ILuOptionO... | () {
this.paging$.next(this.paging$.value + MAGIC_STEP);
}
onScrollBottom() {
this.next();
}
}
| next | identifier_name |
option-pager.component.ts | import { ChangeDetectionStrategy, Component, forwardRef } from '@angular/core';
import { ALuOnScrollBottomSubscriber, ILuOnScrollBottomSubscriber } from '@lucca-front/ng/core';
import { BehaviorSubject, combineLatest, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ALuOptionOperator, ILuOptionO... | set inOptions$(in$: Observable<T[]>) {
this.outOptions$ = combineLatest([in$, this.paging$]).pipe(
map(([options, paging]) => {
return (options || []).slice(0, paging);
}),
);
}
paging$ = new BehaviorSubject<number>(MAGIC_STEP);
next() {
this.paging$.next(this.paging$.value + MAGIC_STEP);
}
onScro... | outOptions$: Observable<T[]>; | random_line_split |
keyword.py | #! /usr/bin/env python
"""Keywords (from "graminit.c")
This file is automatically generated; please don't muck it up!
To update the symbols in this file, 'cd' to the top directory of
the python source tree after building the interpreter and run:
python Lib/keyword.py
"""
__all__ = ["iskeyword", "kw... | main() | conditional_block | |
keyword.py | #! /usr/bin/env python
"""Keywords (from "graminit.c")
This file is automatically generated; please don't muck it up!
To update the symbols in this file, 'cd' to the top directory of
the python source tree after building the interpreter and run:
python Lib/keyword.py
"""
__all__ = ["iskeyword", "kw... | ():
import sys, re
args = sys.argv[1:]
iptfile = args and args[0] or "Python/graminit.c"
if len(args) > 1: optfile = args[1]
else: optfile = "Lib/keyword.py"
# scan the source file for keywords
fp = open(iptfile)
strprog = re.compile('"([^"]+)"')
lines = []
while 1:... | main | identifier_name |
keyword.py | #! /usr/bin/env python
"""Keywords (from "graminit.c")
This file is automatically generated; please don't muck it up!
To update the symbols in this file, 'cd' to the top directory of
the python source tree after building the interpreter and run:
python Lib/keyword.py
"""
__all__ = ["iskeyword", "kw... |
# scan the source file for keywords
fp = open(iptfile)
strprog = re.compile('"([^"]+)"')
lines = []
while 1:
line = fp.readline()
if not line: break
if line.find('{1, "') > -1:
match = strprog.search(line)
if match:
lines.ap... |
args = sys.argv[1:]
iptfile = args and args[0] or "Python/graminit.c"
if len(args) > 1: optfile = args[1]
else: optfile = "Lib/keyword.py"
| random_line_split |
keyword.py | #! /usr/bin/env python
"""Keywords (from "graminit.c")
This file is automatically generated; please don't muck it up!
To update the symbols in this file, 'cd' to the top directory of
the python source tree after building the interpreter and run:
python Lib/keyword.py
"""
__all__ = ["iskeyword", "kw... |
# load the output skeleton from the target
fp = open(optfile)
format = fp.readlines()
fp.close()
# insert the lines of keywords
try:
start = format.index("#--start keywords--\n") + 1
end = format.index("#--end keywords--\n")
format[start:end] = lines
exce... | import sys, re
args = sys.argv[1:]
iptfile = args and args[0] or "Python/graminit.c"
if len(args) > 1: optfile = args[1]
else: optfile = "Lib/keyword.py"
# scan the source file for keywords
fp = open(iptfile)
strprog = re.compile('"([^"]+)"')
lines = []
while 1:
... | identifier_body |
validateEmails.js | // eslint-disable-next-line
const regex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[... | .map(email => email.trim())
.filter(email => email.length && !regex.test(email));
if (invalidEmails.length) {
return `These emails are invalid: ${invalidEmails.join(', ')}`;
}
// return nothing if no invalid emails are found
return;
}; | .split(',') | random_line_split |
validateEmails.js | // eslint-disable-next-line
const regex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[... |
// return nothing if no invalid emails are found
return;
}; | {
return `These emails are invalid: ${invalidEmails.join(', ')}`;
} | conditional_block |
generate-key.py |
from random import randrange
import fractions
def get_primes(n):
numbers = set(range(n, 1, -1))
primes = []
while numbers:
p = numbers.pop()
primes.append(p)
numbers.difference_update(set(range(p*2, n+1, p)))
return primes
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x =... |
for _ in range(k):
a = randrange(2, n - 1)
x = pow(a, s, n)
if x == 1 or x == n - 1:
continue
for _ in range(r - 1):
x = pow(x, 2, n)
if x == n - 1:
break
else:
return False
return True
### main ##########... | r += 1
s //= 2 | conditional_block |
generate-key.py |
from random import randrange
import fractions
def get_primes(n):
numbers = set(range(n, 1, -1))
primes = []
while numbers:
p = numbers.pop()
primes.append(p)
numbers.difference_update(set(range(p*2, n+1, p)))
return primes
def egcd(a, b):
|
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
def miller_rabin(n, k):
r, s = 0, n - 1
while s % 2 == 0:
r += 1
s //= 2
for _ in range(k):
a = randrange(2, n - 1)
x = pow(a,... | if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y) | identifier_body |
generate-key.py | from random import randrange
import fractions
def get_primes(n):
numbers = set(range(n, 1, -1))
primes = []
while numbers:
p = numbers.pop()
primes.append(p)
numbers.difference_update(set(range(p*2, n+1, p)))
return primes
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = ... |
def miller_rabin(n, k):
r, s = 0, n - 1
while s % 2 == 0:
r += 1
s //= 2
for _ in range(k):
a = randrange(2, n - 1)
x = pow(a, s, n)
if x == 1 or x == n - 1:
continue
for _ in range(r - 1):
x = pow(x, 2, n)
if x == n - 1:
... | random_line_split | |
generate-key.py |
from random import randrange
import fractions
def get_primes(n):
numbers = set(range(n, 1, -1))
primes = []
while numbers:
p = numbers.pop()
primes.append(p)
numbers.difference_update(set(range(p*2, n+1, p)))
return primes
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x =... | (n, k):
r, s = 0, n - 1
while s % 2 == 0:
r += 1
s //= 2
for _ in range(k):
a = randrange(2, n - 1)
x = pow(a, s, n)
if x == 1 or x == n - 1:
continue
for _ in range(r - 1):
x = pow(x, 2, n)
if x == n - 1:
br... | miller_rabin | identifier_name |
action_aliases.py | # Licensed to the StackStorm, Inc ('StackStorm') 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 th... |
if len(matched_format_strings) == 0:
msg = ('Command "%s" didn\'t match any of the provided format strings' % (command))
raise AssertionError(msg)
elif len(matched_format_strings) > 1:
msg = ('Command "%s" matched multiple format strings: %s' %
(c... | try:
extract_parameters(format_str=format_string,
param_stream=command)
except ParseException:
continue
matched_format_strings.append(format_string) | conditional_block |
action_aliases.py | # Licensed to the StackStorm, Inc ('StackStorm') 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 th... | def assertCommandMatchesExactlyOneFormatString(self, format_strings, command):
"""
Assert that the provided command matches exactly one format string from the provided list.
"""
matched_format_strings = []
for format_string in format_strings:
try:
... | raise ValueError('"action_alias_name" class attribute needs to be provided')
self.action_alias_db = self._get_action_alias_db_by_name(name=self.action_alias_name)
| random_line_split |
action_aliases.py | # Licensed to the StackStorm, Inc ('StackStorm') 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 th... | (self):
super(BaseActionAliasTestCase, self).setUp()
if not self.action_alias_name:
raise ValueError('"action_alias_name" class attribute needs to be provided')
self.action_alias_db = self._get_action_alias_db_by_name(name=self.action_alias_name)
def assertCommandMatchesExactl... | setUp | identifier_name |
action_aliases.py | # Licensed to the StackStorm, Inc ('StackStorm') 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 th... | raise AssertionError(msg)
def assertExtractedParametersMatch(self, format_string, command, parameters):
"""
Assert that the provided command matches the format string.
In addition to that, also assert that the parameters which have been extracted from the
user input (c... | """
Assert that the provided command matches exactly one format string from the provided list.
"""
matched_format_strings = []
for format_string in format_strings:
try:
extract_parameters(format_str=format_string,
param_stre... | identifier_body |
__init__.py | import os
import json
import collections
import datetime
from flask import Flask, request, current_app, make_response, session, escape, Response, jsonify
from flask_jwt_extended import JWTManager, jwt_required, create_access_token, get_jwt_identity
from flask_socketio import SocketIO
from neo4j.v1 import GraphDatabase,... | ():
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = config['auth_secret']
app.config['JWT_BLACKLIST_ENABLED'] = False
app.config['JWT_BLACKLIST_STORE'] = simplekv.memory.DictStore()
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = 'all'
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = da... | create_app | identifier_name |
__init__.py | import os
import json
import collections
import datetime
from flask import Flask, request, current_app, make_response, session, escape, Response, jsonify
from flask_jwt_extended import JWTManager, jwt_required, create_access_token, get_jwt_identity
from flask_socketio import SocketIO
from neo4j.v1 import GraphDatabase,... |
config = json.load(open('./config.json'));
# Init
UPLOAD_FOLDER = os.path.dirname(os.path.realpath(__file__)) + "/uploads"
x_socketio = SocketIO()
def create_app():
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = config['auth_secret']
app.config['JWT_BLACKLIST_ENABLED'] = False
... | random_line_split | |
__init__.py | import os
import json
import collections
import datetime
from flask import Flask, request, current_app, make_response, session, escape, Response, jsonify
from flask_jwt_extended import JWTManager, jwt_required, create_access_token, get_jwt_identity
from flask_socketio import SocketIO
from neo4j.v1 import GraphDatabase,... | from organizations import organizations_blueprint
from repos import repositories_blueprint
from schema import schema_blueprint
from data import data_blueprint
from search import search_blueprint
from upload import upload_blueprint
from export import export_blueprint
from list import list... | app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = config['auth_secret']
app.config['JWT_BLACKLIST_ENABLED'] = False
app.config['JWT_BLACKLIST_STORE'] = simplekv.memory.DictStore()
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = 'all'
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = datetime.t... | identifier_body |
lookupCodingSystem.js | 'use strict';
const _ = require('lodash');
const serviceUtils = require('../serviceUtils');
/**
* @summary Retrieve a Coding System object.
* @param {String} source Abbreviation of the source coding system under test.
* @param {Function} callback Function called on process completion, with standard (err, resu... | cb(null, codingSystem);
});
}
module.exports = {
lookupCodingSystem,
};
| {
if (!source) {
return cb(this.error('INVALID_CODING_SYSTEM_SOURCE_VALUE'));
}
const findObject = {
query: { sourceAbbreviation: source },
projection: serviceUtils.createProjection(['sourceAbbreviation', 'implementationDate']),
};
this.find('CodingSystems', findObject, (err,... | identifier_body |
lookupCodingSystem.js | 'use strict';
const _ = require('lodash');
const serviceUtils = require('../serviceUtils');
/**
* @summary Retrieve a Coding System object.
* @param {String} source Abbreviation of the source coding system under test.
* @param {Function} callback Function called on process completion, with standard (err, resu... |
cb(null, codingSystem);
});
}
module.exports = {
lookupCodingSystem,
};
| {
_.set(codingSystem, 'implementationDate', impDate.toISOString());
} | conditional_block |
lookupCodingSystem.js | 'use strict';
const _ = require('lodash');
const serviceUtils = require('../serviceUtils');
/**
* @summary Retrieve a Coding System object.
* @param {String} source Abbreviation of the source coding system under test.
* @param {Function} callback Function called on process completion, with standard (err, resu... | (source, cb) {
if (!source) {
return cb(this.error('INVALID_CODING_SYSTEM_SOURCE_VALUE'));
}
const findObject = {
query: { sourceAbbreviation: source },
projection: serviceUtils.createProjection(['sourceAbbreviation', 'implementationDate']),
};
this.find('CodingSystems', find... | lookupCodingSystem | identifier_name |
lookupCodingSystem.js | 'use strict';
const _ = require('lodash');
const serviceUtils = require('../serviceUtils');
/**
* @summary Retrieve a Coding System object.
* @param {String} source Abbreviation of the source coding system under test.
* @param {Function} callback Function called on process completion, with standard (err, resu... | }; | });
}
module.exports = {
lookupCodingSystem, | random_line_split |
RPSOM_animal.py | #!/usr/local/bin python
# -*- coding: utf-8 -*-
from RPSOM import Model
from RPSOM.transition_graph import output_graph
if __name__=='__main__':
# learning rate alpha setup
| filename="example_animal"
rpsom.map_output2wrl_gray_squ(filename)
# Output transition graph
output_graph(rpsom)
rpsom.weight_output_csv ("rpsom_weight")
| alpha_max = [0.1, 0.5, 0.7]
alpha_min = [0.01, 0.1, 0.2]
# neighborhood radius sigma setup
sigma_max = [5, 7, 10]
sigma_min = [1, 2, 3]
epochs = 10
# RPSOM model setup
rpsom=Model.RPSOM(epochs, 15, 20, input_file="animal.csv", alpha_max=alpha_max, alpha_min=alpha_min, sigma_max=sigma_max, sigma_min=sigma_min, lo... | conditional_block |
RPSOM_animal.py | #!/usr/local/bin python
# -*- coding: utf-8 -*-
from RPSOM import Model
from RPSOM.transition_graph import output_graph
if __name__=='__main__':
# learning rate alpha setup
alpha_max = [0.1, 0.5, 0.7]
alpha_min = [0.01, 0.1, 0.2]
# neighborhood radius sigma setup
sigma_max = [5, 7, 10]
sigma_min = [1, 2, 3]
ep... | cb = None
# RPSOM train
rpsom.fit (trainX=rpsom.input_x, epochs=rpsom.epochs, verbose=0, callbacks=cb)
# Output Map
# Output thickness map
rpsom.map_output2wrl_squ(grad=100, filename="test")
# Output grayscale 2D map
filename="example_animal"
rpsom.map_output2wrl_gray_squ(filename)
# Output transition graph
ou... |
# RPSOM model setup
rpsom=Model.RPSOM(epochs, 15, 20, input_file="animal.csv", alpha_max=alpha_max, alpha_min=alpha_min, sigma_max=sigma_max, sigma_min=sigma_min, log_file="test.log")
#cb = [som.write_BMU for som in rpsom.som] | random_line_split |
lib.rs | use std::collections::{HashMap, /* VecMap,*/ BTreeMap};
use std::hash::Hash;
use std::iter::FromIterator;
/// Conversion from an `Iterator` of pairs.
pub trait Groupable<K, V> {
/// Loops through the entire iterator, grouping all keys into a container
/// implementing `FromKeyedIterator` with a container of v... | <B: FromKeyedIterator<K, V>>(&mut self) -> B {
FromKeyedIterator::from_keyed_iter(self.by_ref())
}
}
/// Conversion from an `Iterator` of key-value pairs.
pub trait FromKeyedIterator<K, V> {
/// Build a container with groups of elements from an external iterator.
fn from_keyed_iter<I: Iterator<Item... | group | identifier_name |
lib.rs | use std::collections::{HashMap, /* VecMap,*/ BTreeMap};
use std::hash::Hash;
use std::iter::FromIterator;
/// Conversion from an `Iterator` of pairs.
pub trait Groupable<K, V> {
/// Loops through the entire iterator, grouping all keys into a container
/// implementing `FromKeyedIterator` with a container of v... | ///
/// ```rust
/// use std::collections::HashMap;
/// use groupable::Groupable;
///
/// let evens = (0..10).map(|i| (i % 2 == 0, i))
/// .group::<HashMap<bool, Vec<usize>>>();
///
/// assert_eq!(evens[&true], [0, 2, 4, 6, 8]);
/// assert_eq!(evens[&false], [1,... | /// The values will be aggregated per key into a container implementing
/// `Extend` for the value type.
///
/// # Example | random_line_split |
lib.rs | use std::collections::{HashMap, /* VecMap,*/ BTreeMap};
use std::hash::Hash;
use std::iter::FromIterator;
/// Conversion from an `Iterator` of pairs.
pub trait Groupable<K, V> {
/// Loops through the entire iterator, grouping all keys into a container
/// implementing `FromKeyedIterator` with a container of v... |
}
/// Conversion from an `Iterator` of key-value pairs.
pub trait FromKeyedIterator<K, V> {
/// Build a container with groups of elements from an external iterator.
fn from_keyed_iter<I: Iterator<Item=(K, V)>>(I) -> Self;
}
macro_rules! group_into(
($iter:ident, $map:ident) => (
for (key, val) in... | {
FromKeyedIterator::from_keyed_iter(self.by_ref())
} | identifier_body |
filter.module.ts | // (C) Copyright 2015 Moodle Pty Ltd.
//
// 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 agree... | import { AddonFilterMediaPluginModule } from './mediaplugin/mediaplugin.module';
import { AddonFilterMultilangModule } from './multilang/multilang.module';
import { AddonFilterTexModule } from './tex/tex.module';
import { AddonFilterTidyModule } from './tidy/tidy.module';
import { AddonFilterUrlToLinkModule } from './u... | random_line_split | |
filter.module.ts | // (C) Copyright 2015 Moodle Pty Ltd.
//
// 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 agree... | { }
| AddonFilterModule | identifier_name |
PocketOAuthRouter.js | 'use strict';
var express = require('express');
var router = express.Router();
var Keys = require('../services/KeysService');
var Urls = require('../services/UrlsService');
var PocketOAuth = require('../services/PocketOAuthService');
var logger = require('../logger').logger;
router.get('/api/requestToken', function (... | });
});
module.exports = router; | router.get('/api/isAuthorized', function (req, res) {
res.charset = 'utf-8';
return res.json({
'status': 'success',
'payload': { isAuthorized: PocketOAuth.isAuthorized() } | random_line_split |
lcd_display.py | init__()
self.device_path = device_path
from serial import Serial
self._device = Serial(device_path, baud, timeout=0)
self._unprocessed = ""
@classmethod
def get_crc(cls, buf):
# This seed makes the output of this shift based algorithm match
# the table based al... | """
super(CF635Screen, self).__init__(device_path, baud) | random_line_split |