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 |
|---|---|---|---|---|
conf.py | All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
import sphinx.environment
from docutils.utils import get_source_line
def _warn_node(self, msg, node):
if not msg.startswith('nonlocal image URI found:'):
|
sphinx.environment.BuildEnvironment.warn_node = _warn_node
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, o... | self._warnfunc(msg, '%s:%s' % get_source_line(node)) | conditional_block |
conf.py | All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
import sphinx.environment
from docutils.utils import get_source_line
def _warn_node(self, msg, node):
|
sphinx.environment.BuildEnvironment.warn_node = _warn_node
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, o... | if not msg.startswith('nonlocal image URI found:'):
self._warnfunc(msg, '%s:%s' % get_source_line(node)) | identifier_body |
conf.py | All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
import sphinx.environment
from docutils.utils import get_source_line
def | (self, msg, node):
if not msg.startswith('nonlocal image URI found:'):
self._warnfunc(msg, '%s:%s' % get_source_line(node))
sphinx.environment.BuildEnvironment.warn_node = _warn_node
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. I... | _warn_node | identifier_name |
triangle.rs | // Copyright 2015 Brendan Zabarauskas and the gl-rs developers
//
// 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 b... |
}
shader
}
fn link_program(vs: GLuint, fs: GLuint) -> GLuint {
unsafe {
let program = gl::CreateProgram();
gl::AttachShader(program, vs);
gl::AttachShader(program, fs);
gl::LinkProgram(program);
// Get the link status
let mut status = gl::FALSE as GLint;
... | {
let mut len = 0;
gl::GetShaderiv(shader, gl::INFO_LOG_LENGTH, &mut len);
let mut buf = Vec::with_capacity(len as usize);
buf.set_len((len as usize) - 1); // subtract 1 to skip the trailing null character
gl::GetShaderInfoLog(
shader,
... | conditional_block |
triangle.rs | // Copyright 2015 Brendan Zabarauskas and the gl-rs developers
//
// 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 b... | (vs: GLuint, fs: GLuint) -> GLuint {
unsafe {
let program = gl::CreateProgram();
gl::AttachShader(program, vs);
gl::AttachShader(program, fs);
gl::LinkProgram(program);
// Get the link status
let mut status = gl::FALSE as GLint;
gl::GetProgramiv(program, gl::L... | link_program | identifier_name |
triangle.rs | // Copyright 2015 Brendan Zabarauskas and the gl-rs developers
//
// 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 b... | gl::DeleteVertexArrays(1, &vao);
}
*control_flow = ControlFlow::Exit
},
_ => (),
},
Event::RedrawRequested(_) => {
unsafe {
// Clear the screen to black
... | gl::DeleteBuffers(1, &vbo); | random_line_split |
triangle.rs | // Copyright 2015 Brendan Zabarauskas and the gl-rs developers
//
// 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 b... |
unsafe {
// Create Vertex Array Object
gl::GenVertexArrays(1, &mut vao);
gl::BindVertexArray(vao);
// Create a Vertex Buffer Object and copy the vertex data to it
gl::GenBuffers(1, &mut vbo);
gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
gl::BufferData(
... | {
let event_loop = glutin::event_loop::EventLoop::new();
let window = glutin::window::WindowBuilder::new();
let gl_window = glutin::ContextBuilder::new()
.build_windowed(window, &event_loop)
.unwrap();
// It is essential to make the context current before calling `gl::load_with`.
le... | identifier_body |
notify.py | # Copyright 2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | (self, result, context):
num_iterations = sum(context.job_iteration_counts.values())
counter = collections.Counter()
for result in result.iteration_results:
counter[result.status] += 1
score_board = []
for status in IterationResult.values:
if status in c... | process_run_result | identifier_name |
notify.py | # Copyright 2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
counter = collections.Counter()
for result in result.iteration_results:
counter[result.status] += 1
score_board = []
for status in IterationResult.values:
if status in counter:
score_board.append('{} {}'.format(counter[status], status))
... | name = 'notify'
description = '''Display a desktop notification when the run finishes
Notifications only work in linux systems. It uses the generic
freedesktop notification specification. For this results processor
to work, you need to have python-notify installed in your system.
'''
def init... | identifier_body |
notify.py | # Copyright 2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
score_board = []
for status in IterationResult.values:
if status in counter:
score_board.append('{} {}'.format(counter[status], status))
summary = 'Workload Automation run finised'
body = 'Ran a total of {} iterations: '.format(num_iterations)
body ... | counter[result.status] += 1 | conditional_block |
notify.py | # Copyright 2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | self.logger.warning('Notification failed to show') | if not notification.show(): | random_line_split |
evenOddRepeat.test.js | var should = require('should');
var vm = require('vm');
var fs = require('fs');
var filename = __filename.replace(/\.test\.js$/, '.js');
vm.runInThisContext(fs.readFileSync(filename), filename);
describe('evenOddRepeat', function() {
it('should exist', function(){
should.exist(evenOddRepeat);
});
... | it('should have the right answer', function(){
var result = evenOddRepeat('12333224');
result.should.be.eql('123x3x32y2y4');
});
it('should handle long numbers with no repeats', function() {
var result = evenOddRepeat('123456789');
result.should.be.eql('123456789');
});
... | });
| random_line_split |
wamnclient.py | #!/usr/bin/python
import pygeoip
import json
from logsparser.lognormalizer import LogNormalizer as LN
import gzip
import glob
import socket
import urllib2
IP = 'IP.Of,Your.Server'
normalizer = LN('/usr/local/share/logsparser/normalizers')
gi = pygeoip.GeoIP('../GeoLiteCity.dat')
def complete(text, state):
return (gl... | ():
attacks = {}
users = {}
try:
import readline, rlcompleter
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(complete)
except ImportError:
print 'No Tab Completion'
LOGs = raw_input('Enter the path to the log file: ')
for LOG in LO... | sshcheck | identifier_name |
wamnclient.py | #!/usr/bin/python
import pygeoip
import json
from logsparser.lognormalizer import LogNormalizer as LN
import gzip
import glob
import socket
import urllib2
IP = 'IP.Of,Your.Server'
normalizer = LN('/usr/local/share/logsparser/normalizers')
gi = pygeoip.GeoIP('../GeoLiteCity.dat')
def complete(text, state):
return (gl... | print '\nCtrl+C Exiting...'
exit(0) | s.close()
try:
sshcheck()
except KeyboardInterrupt: | random_line_split |
wamnclient.py | #!/usr/bin/python
import pygeoip
import json
from logsparser.lognormalizer import LogNormalizer as LN
import gzip
import glob
import socket
import urllib2
IP = 'IP.Of,Your.Server'
normalizer = LN('/usr/local/share/logsparser/normalizers')
gi = pygeoip.GeoIP('../GeoLiteCity.dat')
def complete(text, state):
return (gl... |
newdata = data
newjson = json.dumps(newdata)
print json.loads(newjson)
send(newjson)
def send(data):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('Ip.Of.Your.Server', 9999))
s.sendall(data)
s.close()
try:
sshcheck()
except KeyboardInterrupt:
print '\nCtrl+C Exiting...'
exit(0... | datalist = [{ 'ip': a, 'attacks': p, 'local_ip': IP }]
data[i] = datalist | conditional_block |
wamnclient.py | #!/usr/bin/python
import pygeoip
import json
from logsparser.lognormalizer import LogNormalizer as LN
import gzip
import glob
import socket
import urllib2
IP = 'IP.Of,Your.Server'
normalizer = LN('/usr/local/share/logsparser/normalizers')
gi = pygeoip.GeoIP('../GeoLiteCity.dat')
def complete(text, state):
return (gl... |
try:
sshcheck()
except KeyboardInterrupt:
print '\nCtrl+C Exiting...'
exit(0)
| s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('Ip.Of.Your.Server', 9999))
s.sendall(data)
s.close() | identifier_body |
mapDataStatistic.js |
var zrUtil = require('zrender/lib/core/util');
// FIXME 公用?
/**
* @param {Array.<module:echarts/data/List>} datas
* @param {string} statisticType 'average' 'sum'
* @inner
*/
function dataStatistics(datas, statisticType) {
| for (var i = 0; i < len; i++) {
min = Math.min(min, dataNameMap[mapKey][i]);
max = Math.max(max, dataNameMap[mapKey][i]);
sum += dataNameMap[mapKey][i];
}
var result;
if (statisticType === 'min') {
result = m... | var dataNameMap = {};
var dims = ['value'];
zrUtil.each(datas, function (data) {
data.each(dims, function (value, idx) {
// Add prefix to avoid conflict with Object.prototype.
var mapKey = 'ec-' + data.getName(idx);
dataNameMap[mapKey] = d... | identifier_body |
mapDataStatistic.js |
var zrUtil = require('zrender/lib/core/util');
// FIXME 公用?
/**
* @param {Array.<module:echarts/data/List>} datas
* @param {string} statisticType 'average' 'sum'
* @inner
*/
function dataStatistics(datas, statisticType) {
var dataNameMap = {};
var dims = ['value'];... | // FIXME Put where?
for (var i = 0; i < seriesList.length; i++) {
seriesList[i].seriesGroup = seriesList;
seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
seriesList[i].setData(data.cloneShallow());
seriesList[... | seriesList[i].originalData = seriesList[i].getData();
}
| conditional_block |
mapDataStatistic.js |
var zrUtil = require('zrender/lib/core/util');
// FIXME 公用?
/**
* @param {Array.<module:echarts/data/List>} datas
* @param {string} statisticType 'average' 'sum'
* @inner
*/
function dataSt | , statisticType) {
var dataNameMap = {};
var dims = ['value'];
zrUtil.each(datas, function (data) {
data.each(dims, function (value, idx) {
// Add prefix to avoid conflict with Object.prototype.
var mapKey = 'ec-' + data.getName(idx);
... | atistics(datas | identifier_name |
mapDataStatistic.js | var zrUtil = require('zrender/lib/core/util');
// FIXME 公用?
/**
* @param {Array.<module:echarts/data/List>} datas
* @param {string} statisticType 'average' 'sum'
* @inner
*/
function dataStatistics(datas, statisticType) {
var dataNameMap = {};
var dims = ['value'];
... | for (var i = 0; i < len; i++) {
min = Math.min(min, dataNameMap[mapKey][i]);
max = Math.max(max, dataNameMap[mapKey][i]);
sum += dataNameMap[mapKey][i];
}
var result;
if (statisticType === 'min') {
result = m... | var min = Infinity;
var max = -Infinity;
var len = dataNameMap[mapKey].length; | random_line_split |
Components.js | /**
* Most of this code is adapated from https://github.com/qimingweng/react-modal-dialog
*/
import React from 'react';
import ReactDOM from 'react-dom';
import EventStack from './EventStack';
import PropTypes from 'prop-types';
const ESCAPE = 27;
/**
* Get the keycode from an event
* @param {Event} event The bro... | render() {
const { transparent } = this.state;
const overlayStyle = {
opacity: transparent ? 0 : 0.6
};
const containerStyle = {
opacity: transparent ? 0 : 1
};
return (
<div
className={'liq_modal-background'}
... | callback();
}, this.props.duration);
} | random_line_split |
Components.js | /**
* Most of this code is adapated from https://github.com/qimingweng/react-modal-dialog
*/
import React from 'react';
import ReactDOM from 'react-dom';
import EventStack from './EventStack';
import PropTypes from 'prop-types';
const ESCAPE = 27;
/**
* Get the keycode from an event
* @param {Event} event The bro... | }
render() {
return null;
} // This doesn't actually return anything to render
}
ModalPortal.propTypes = {
onClose: PropTypes.func, // This is called when the dialog should close
children: PropTypes.node,
onModalDidMount: PropTypes.func, // optional, called on mount
onModalWillUnmou... |
// Call completion immediately
done();
}
| conditional_block |
Components.js | /**
* Most of this code is adapated from https://github.com/qimingweng/react-modal-dialog
*/
import React from 'react';
import ReactDOM from 'react-dom';
import EventStack from './EventStack';
import PropTypes from 'prop-types';
const ESCAPE = 27;
/**
* Get the keycode from an event
* @param {Event} event The bro... | }
ModalContent.propTypes = {
showButton: PropTypes.bool,
onClose: PropTypes.func, // required for the close button
className: PropTypes.string,
children: PropTypes.node,
dismissOnBackgroundClick: PropTypes.bool
};
ModalContent.defaultProps = {
dismissOnBackgroundClick: true,
showButton: tr... | {
return (
<div ref="self" className={'liq_modal-content'}>
{this.props.showButton && this.props.onClose ? (
<button
onClick={this.props.onClose}
className={'liq_modal-close'}
data-test="close... | identifier_body |
Components.js | /**
* Most of this code is adapated from https://github.com/qimingweng/react-modal-dialog
*/
import React from 'react';
import ReactDOM from 'react-dom';
import EventStack from './EventStack';
import PropTypes from 'prop-types';
const ESCAPE = 27;
/**
* Get the keycode from an event
* @param {Event} event The bro... | (event) {
if (getKeyCodeFromEvent(event) === ESCAPE) {
if (typeof this.props.onClose === 'function') {
this.props.onClose(event);
}
}
}
render() {
return (
<div ref="self" className={'liq_modal-content'}>
{this.props.sho... | handleGlobalKeydown | identifier_name |
COLT2015.py | # coding=utf-8
"""
This file is used to make a crawl
"""
import __init__
import os
import re
import urllib
from utility import prgbar
def get_html(url):
|
def get_pdf(html):
""" xxx"""
reg = r'href="(.+?\.pdf)">pdf'
pdfre = re.compile(reg)
pdflist = re.findall(pdfre, html)
dir_name = 'COLT2015'
maxrows = len(pdflist)
pbar = prgbar.ProgressBar(total=maxrows)
if os.path.exists(dir_name) is False:
os.mkdir(dir_name)
for idx, ... | """Get the html """
page = urllib.urlopen(url)
html = page.read()
return html | identifier_body |
COLT2015.py | # coding=utf-8
"""
This file is used to make a crawl
"""
import __init__
import os
import re
import urllib
from utility import prgbar
def get_html(url):
"""Get the html """
page = urllib.urlopen(url)
html = page.read()
return html
def get_pdf(html):
""" xxx"""
reg = r'href="(.+?\.pdf)">pdf'... | if os.path.exists(filename) is True:
pbar.log('Exist')
else:
urllib.urlretrieve(
'http://jmlr.org/proceedings/papers/v40/' + pdfurl, filename)
pbar.update(index=(idx + 1))
pbar.finish()
if __name__ == '__main__':
HTML = get_html("http://jmlr.org... | random_line_split | |
COLT2015.py | # coding=utf-8
"""
This file is used to make a crawl
"""
import __init__
import os
import re
import urllib
from utility import prgbar
def get_html(url):
"""Get the html """
page = urllib.urlopen(url)
html = page.read()
return html
def get_pdf(html):
""" xxx"""
reg = r'href="(.+?\.pdf)">pdf'... |
else:
urllib.urlretrieve(
'http://jmlr.org/proceedings/papers/v40/' + pdfurl, filename)
pbar.update(index=(idx + 1))
pbar.finish()
if __name__ == '__main__':
HTML = get_html("http://jmlr.org/proceedings/papers/v40/")
print(get_pdf(HTML))
| pbar.log('Exist') | conditional_block |
COLT2015.py | # coding=utf-8
"""
This file is used to make a crawl
"""
import __init__
import os
import re
import urllib
from utility import prgbar
def get_html(url):
"""Get the html """
page = urllib.urlopen(url)
html = page.read()
return html
def | (html):
""" xxx"""
reg = r'href="(.+?\.pdf)">pdf'
pdfre = re.compile(reg)
pdflist = re.findall(pdfre, html)
dir_name = 'COLT2015'
maxrows = len(pdflist)
pbar = prgbar.ProgressBar(total=maxrows)
if os.path.exists(dir_name) is False:
os.mkdir(dir_name)
for idx, pdfurl in enum... | get_pdf | identifier_name |
pipeP.js | var assert = require('assert');
var Q = require('q');
var R = require('..');
describe('pipeP', function() {
function a(x) {return x + 'A';}
function b(x) {return x + 'B';}
it('handles promises', function() {
var plusOne = function(a) {return a + 1;};
var multAsync = function(a, b) {return Q.when(a * ... | (x, y) { void y; return 'A2'; }
function a3(x, y) { void y; return Q.when('A2'); }
function a4(x, y) { void y; return 'A2'; }
var f1 = R.pipeP(a, b);
assert.strictEqual(f1.length, a.length);
var f2 = R.pipeP(a2, b);
assert.strictEqual(f2.length, a2.length);
var f3 = R.pipeP(a3, b);
asse... | a2 | identifier_name |
pipeP.js | var assert = require('assert');
var Q = require('q');
var R = require('..');
describe('pipeP', function() {
function a(x) {return x + 'A';}
function b(x) {return x + 'B';}
it('handles promises', function() {
var plusOne = function(a) {return a + 1;};
var multAsync = function(a, b) {return Q.when(a * ... | });
});
it('returns a function with arity == leftmost argument', function() {
function a2(x, y) { void y; return 'A2'; }
function a3(x, y) { void y; return Q.when('A2'); }
function a4(x, y) { void y; return 'A2'; }
var f1 = R.pipeP(a, b);
assert.strictEqual(f1.length, a.length);
var ... | .then(function(result) {
assert.strictEqual(result, 7); | random_line_split |
pipeP.js | var assert = require('assert');
var Q = require('q');
var R = require('..');
describe('pipeP', function() {
function a(x) {return x + 'A';}
function b(x) {return x + 'B';}
it('handles promises', function() {
var plusOne = function(a) {return a + 1;};
var multAsync = function(a, b) {return Q.when(a * ... |
function a3(x, y) { void y; return Q.when('A2'); }
function a4(x, y) { void y; return 'A2'; }
var f1 = R.pipeP(a, b);
assert.strictEqual(f1.length, a.length);
var f2 = R.pipeP(a2, b);
assert.strictEqual(f2.length, a2.length);
var f3 = R.pipeP(a3, b);
assert.strictEqual(f3.length, a3.le... | { void y; return 'A2'; } | identifier_body |
zookeeper_example.rs | #![deny(unused_mut)]
extern crate zookeeper;
#[macro_use]
extern crate log;
extern crate env_logger;
use std::io;
use std::sync::Arc;
use std::time::Duration;
use std::thread;
use std::env;
use std::sync::mpsc;
use zookeeper::{CreateMode, Watcher, WatchedEvent, ZooKeeper};
use zookeeper::acls;
use zookeeper::recipes::... | () {
env_logger::init().unwrap();
zk_example();
}
| main | identifier_name |
zookeeper_example.rs | #![deny(unused_mut)]
extern crate zookeeper;
#[macro_use]
extern crate log;
extern crate env_logger;
use std::io;
use std::sync::Arc;
use std::time::Duration;
use std::thread;
use std::env;
use std::sync::mpsc;
use zookeeper::{CreateMode, Watcher, WatchedEvent, ZooKeeper};
use zookeeper::acls;
use zookeeper::recipes::... | }
}
fn zk_example() {
let zk_urls = zk_server_urls();
println!("connecting to {}", zk_urls);
let zk = ZooKeeper::connect(&*zk_urls, Duration::from_secs(5), LoggingWatcher).unwrap();
let mut tmp = String::new();
let auth = zk.add_auth("digest", vec![1, 2, 3, 4]);
println!("authenticated... | fn zk_server_urls() -> String {
let key = "ZOOKEEPER_SERVERS";
match env::var(key) {
Ok(val) => val,
Err(_) => "localhost:2181".to_string(), | random_line_split |
zookeeper_example.rs | #![deny(unused_mut)]
extern crate zookeeper;
#[macro_use]
extern crate log;
extern crate env_logger;
use std::io;
use std::sync::Arc;
use std::time::Duration;
use std::thread;
use std::env;
use std::sync::mpsc;
use zookeeper::{CreateMode, Watcher, WatchedEvent, ZooKeeper};
use zookeeper::acls;
use zookeeper::recipes::... |
println!("exists -> {:?}", exists);
let doesnt_exist = zk.exists("/blabla", true);
println!("don't exists path -> {:?}", doesnt_exist);
let get_acl = zk.get_acl("/test");
println!("get_acl -> {:?}", get_acl);
let set_acl = zk.set_acl("/test", acls::OPEN_ACL_UNSAFE.clone(), -1);
printl... | {
let zk_urls = zk_server_urls();
println!("connecting to {}", zk_urls);
let zk = ZooKeeper::connect(&*zk_urls, Duration::from_secs(5), LoggingWatcher).unwrap();
let mut tmp = String::new();
let auth = zk.add_auth("digest", vec![1, 2, 3, 4]);
println!("authenticated -> {:?}", auth);
let... | identifier_body |
exceptions.py |
import sys
import traceback
# ------------------------------------------------------------------------------
#
class MyEx (Exception) :
# --------------------------------------------------------------------------
#
# the exception constructor always needs a message (no need complaining if
# there is ... | (MyEx) : pass
# ------------------------------------------------------------------------------
#
# This is the interesting part -- that call triggers a couple of exceptions.
# Run like this:
#
# 0) run as is
# 1) comment out #1 -- run again
# 2) comment out #2 -- run again
# 3) comment out #3 -- run agai... | MyEx_3 | identifier_name |
exceptions.py | import sys
import traceback
# ------------------------------------------------------------------------------
#
class MyEx (Exception) :
# --------------------------------------------------------------------------
#
# the exception constructor always needs a message (no need complaining if
# there is n... | # i.e. a reaction to some genuine code error. Thus we extract the
# traceback from exactly where we are in the code (the last stack
# frame will be the call to this exception constructor), and we
# create the original exception message from 'stype' and 'msg'.
... |
else :
# if we don't have a parent, we are a 1st principle exception, | random_line_split |
exceptions.py |
import sys
import traceback
# ------------------------------------------------------------------------------
#
class MyEx (Exception) :
# --------------------------------------------------------------------------
#
# the exception constructor always needs a message (no need complaining if
# there is ... | frame = traceback.extract_stack ()[-2]
line = "%s +%s (%s) : %s" % frame
self.msg = " %-20s: %s (%s)\n %-20s: %s" % (stype, msg, line, ptype, parent)
else :
# if we don't have a parent, we are a 1st principle exception,... | if isinstance (parent, MyEx) :
# that all works nicely when parent is our own exception type...
self.traceback = parent.traceback
frame = traceback.extract_stack ()[-2]
line = "%s +%s (%s) : %s" % frame
self.msg ... | conditional_block |
exceptions.py |
import sys
import traceback
# ------------------------------------------------------------------------------
#
class MyEx (Exception) :
# --------------------------------------------------------------------------
#
# the exception constructor always needs a message (no need complaining if
# there is ... |
else :
# ... but if parent is a native (or any other) exception type,
# we don't have a traceback really -- so we dig it out of
# sys.exc_info.
trace = sys.exc_info ()[2]
stack = traceback.extract_tb (trace)
... | ptype = type(parent).__name__ # exception type for parent
stype = type(self).__name__ # exception type for self, useful for
# inherited exceptions
# did we get a parent exception?
if parent :
# if so, then this exception is likely crea... | identifier_body |
tree_graph.js | function transformPath(decisionPath) {
var path = []
for (var i=1; i<decisionPath.length; i++) {
var node = {
feature: decisionPath[i-1].feature,
side: decisionPath[i].side == 'left' ? "<=" : ">",
threshold: decisionPath[i-1].threshold.toPrecision(5),
featureIdx: decisionPath[i-1].featureIdx,
level:... | }
path.push(node)
}
return path;
}
var tip_features = {
feature: function(d) { return 'Feature: ' + d.feature },
count: function(d) { return d.count + ' samples' },
dataPercentage: function(d) { return d.dataPercentage + '% of the data'},
impurity: function(d) { return 'Impurity: ' + d.impurity}
} | if (node[attrname] == null)
node[attrname] = decisionPath[i][attrname]; | random_line_split |
tree_graph.js | function transformPath(decisionPath) | }
var tip_features = {
feature: function(d) { return 'Feature: ' + d.feature },
count: function(d) { return d.count + ' samples' },
dataPercentage: function(d) { return d.dataPercentage + '% of the data'},
impurity: function(d) { return 'Impurity: ' + d.impurity}
} | {
var path = []
for (var i=1; i<decisionPath.length; i++) {
var node = {
feature: decisionPath[i-1].feature,
side: decisionPath[i].side == 'left' ? "<=" : ">",
threshold: decisionPath[i-1].threshold.toPrecision(5),
featureIdx: decisionPath[i-1].featureIdx,
level: i
}
//copy all properties of dec... | identifier_body |
tree_graph.js | function | (decisionPath) {
var path = []
for (var i=1; i<decisionPath.length; i++) {
var node = {
feature: decisionPath[i-1].feature,
side: decisionPath[i].side == 'left' ? "<=" : ">",
threshold: decisionPath[i-1].threshold.toPrecision(5),
featureIdx: decisionPath[i-1].featureIdx,
level: i
}
//copy all pr... | transformPath | identifier_name |
typelint.js | var traverseScope = require('../lib/traverse');
var validation = require('../lib/validation');
var config = require('../lib/config');
var rule;
/**
* @param {Object} context
* @param {settings} settings
* @return {Function}
*/
function | (context, settings) {
return function (node) {
var scope;
if (node.object && node.object.name) {
// memoize settings
config.settings = settings;
scope = traverseScope(node, {
init: {
start: node.start,
end: node.end
},
props: [],
typedVars:... | handleMemberExpressions | identifier_name |
typelint.js | var traverseScope = require('../lib/traverse');
var validation = require('../lib/validation');
var config = require('../lib/config');
var rule;
/**
* @param {Object} context
* @param {settings} settings
* @return {Function}
*/
function handleMemberExpressions(context, settings) {
return function (node) {
var ... | });
}
}
};
}
/**
* @param {Object} context
* @returns {{MemberExpression: (function)}}
*/
rule = function (context) {
return {
MemberExpression: handleMemberExpressions(context, context.settings.typelint),
};
};
rule.handleMemberExpressions = handleMemberExpressions;
module.exports = ru... | validation.validate(param, scope, node, context);
return true;
}
return false; | random_line_split |
typelint.js | var traverseScope = require('../lib/traverse');
var validation = require('../lib/validation');
var config = require('../lib/config');
var rule;
/**
* @param {Object} context
* @param {settings} settings
* @return {Function}
*/
function handleMemberExpressions(context, settings) {
return function (node) {
var ... |
}
};
}
/**
* @param {Object} context
* @returns {{MemberExpression: (function)}}
*/
rule = function (context) {
return {
MemberExpression: handleMemberExpressions(context, context.settings.typelint),
};
};
rule.handleMemberExpressions = handleMemberExpressions;
module.exports = rule; | {
scope.typedVars.some(function (param) {
if (param.varName === node.object.name) {
validation.validate(param, scope, node, context);
return true;
}
return false;
});
} | conditional_block |
typelint.js | var traverseScope = require('../lib/traverse');
var validation = require('../lib/validation');
var config = require('../lib/config');
var rule;
/**
* @param {Object} context
* @param {settings} settings
* @return {Function}
*/
function handleMemberExpressions(context, settings) | return true;
}
return false;
});
}
}
};
}
/**
* @param {Object} context
* @returns {{MemberExpression: (function)}}
*/
rule = function (context) {
return {
MemberExpression: handleMemberExpressions(context, context.settings.typelint),
};
};
rule.handleMe... | {
return function (node) {
var scope;
if (node.object && node.object.name) {
// memoize settings
config.settings = settings;
scope = traverseScope(node, {
init: {
start: node.start,
end: node.end
},
props: [],
typedVars: [],
nativeV... | identifier_body |
iterator.py | #!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (division, absolute_import, print_function)
__license__ = 'GPL v3'
__copyright__ = '2014, Derek Broughton <auspex@pointerstop.ca>'
__docformat__ = 'restructuredtext en'
from calibre.ebooks.oeb.iterator.book import EbookI... |
bookmark = "%s#point(%s)" % filename, '/'.join(pos)
return bookmark | random_line_split | |
iterator.py | #!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (division, absolute_import, print_function)
__license__ = 'GPL v3'
__copyright__ = '2014, Derek Broughton <auspex@pointerstop.ca>'
__docformat__ = 'restructuredtext en'
from calibre.ebooks.oeb.iterator.book import EbookI... |
def convert_to_sony_bookmark(self, bm):
prefix = self._tdir.tdir+'/'
filename = self.spine[bm['spine']].rpartition(prefix)[2]
pos = bm['pos'].split('/')
# ADE doesn't count the <HEAD> tag
if pos[1] == '2':
pos[1] = '1'
... | filename,pos = bookmark.split('#point')
pos = pos.strip(u'(\x00)').split('/')
# Adobe Digital Editions doesn't count the tags correctly
if pos[1] == '1':
pos[1] = '2'
pos = '/'.join(pos)
prefix = self._tdir.tdir
path = os.path.join(prefi... | identifier_body |
iterator.py | #!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (division, absolute_import, print_function)
__license__ = 'GPL v3'
__copyright__ = '2014, Derek Broughton <auspex@pointerstop.ca>'
__docformat__ = 'restructuredtext en'
from calibre.ebooks.oeb.iterator.book import EbookI... |
pos = '/'.join(pos)
prefix = self._tdir.tdir
path = os.path.join(prefix,filename)
spine_num = self.spine.index(path)
bm = dict(title=title, type='cfi', spine=spine_num, pos=pos)
return bm
def convert_to_sony_bookmark(self, bm):
... | pos[1] = '2' | conditional_block |
iterator.py | #!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (division, absolute_import, print_function)
__license__ = 'GPL v3'
__copyright__ = '2014, Derek Broughton <auspex@pointerstop.ca>'
__docformat__ = 'restructuredtext en'
from calibre.ebooks.oeb.iterator.book import EbookI... | (self, bookmark, title=''):
filename,pos = bookmark.split('#point')
pos = pos.strip(u'(\x00)').split('/')
# Adobe Digital Editions doesn't count the tags correctly
if pos[1] == '1':
pos[1] = '2'
pos = '/'.join(pos)
prefix = self._tdir.tdir
... | convert_from_sony_bookmark | identifier_name |
index.tsx | import * as Container from '../../util/container'
import * as Constants from '../../constants/profile'
import * as ProfileGen from '../profile-gen'
import * as RPCTypes from '../../constants/types/rpc-gen'
import * as RouteTreeGen from '../route-tree-gen'
import * as Saga from '../../util/saga'
import * as TrackerConst... |
const submitUnblockUser = async (action: ProfileGen.SubmitUnblockUserPayload) => {
try {
await RPCTypes.userUnblockUserRpcPromise(
{username: action.payload.username},
Constants.blockUserWaitingKey
)
return Tracker2Gen.createLoad({
assertion: action.payload.username,
guiID: Tracke... | error: error.desc || `There was an error blocking ${action.payload.username}.`,
})
}
} | random_line_split |
macro_parser.rs | item)
next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b]
- - - Advance over an `a`. - - - (this looks exactly like the last step)
Remaining input: `b`
cur: [a $( a · )* a b] next: [a $( a )* a · b]
Finish/Repeat (first item)
next: [a $( a )* · a b] [a $( · a )* a b]
- - - Advance over a `b`. - - -
Rem... | of_eis.push(ei);
}
} else {
| conditional_block | |
macro_parser.rs | rateConfig,
rdr: TtReader,
ms: Vec<Matcher> )
-> HashMap<Ident, Rc<NamedMatch>> {
match parse(sess, cfg, rdr, ms.as_slice()) {
Success(m) => m,
Failure(sp, str) => {
sess.span_diagnostic.span_fatal(sp, str.as_slice())
... | "item" => match p.parse_item(Vec::new()) {
Some(i) => token::NtItem(i),
None => p.fatal("expected an item keyword")
},
"block" => token::NtBlock(p.parse_block()),
"stmt" => token::NtStmt(p.parse_stmt(Vec::new())),
"pat" => token::NtPat(p.parse_pat()),
"expr" => token::NtE... | identifier_body | |
macro_parser.rs | [· a $( a )* a b].
Remaining input: `a a a a b`
next_eis: [· a $( a )* a b]
- - - Advance over an `a`. - - -
Remaining input: `a a a b`
cur: [a · $( a )* a b]
Descend/Skip (first item).
next: [a $( · a )* a b] [a $( a )* · a b].
- - - Advance over an `a`. - - -
Remaining input: `a a b`
cur: [a $( a · )* a b] ne... | Ident, Rc<NamedMatch>>),
Failure(codemap::Span, String),
Error(codemap::Span, String)
}
pub fn parse_or_else(sess: &ParseSess,
cfg: ast::CrateConfig,
rdr: TtReader,
ms: Vec<Matcher> )
-> HashMap<Ident, Rc<NamedMatch>> {
mat... | ss(HashMap< | identifier_name |
macro_parser.rs | [· a $( a )* a b].
Remaining input: `a a a a b`
next_eis: [· a $( a )* a b]
- - - Advance over an `a`. - - -
Remaining input: `a a a b`
cur: [a · $( a )* a b]
Descend/Skip (first item).
next: [a $( · a )* a b] [a $( a )* · a b].
- - - Advance over an `a`. - - -
Remaining input: `a a b`
cur: [a $( a · )* a b] ne... | -> HashMap<Ident, Rc<NamedMatch>> {
match parse(sess, cfg, rdr, ms.as_slice()) {
Success(m) => m,
Failure(sp, str) => {
sess.span_diagnostic.span_fatal(sp, str.as_slice())
}
Error(sp, str) => {
sess.span_diagnostic.span_fatal(sp, str.as_sl... | ms: Vec<Matcher> ) | random_line_split |
P06_RankIt.py | # You have been given an array A consisting of N integers. All the elements in this array A are unique. You have to
# answer some queries based on the elements of this array. Each query will consist of a single integer x. You need to
# print the rank based position of this element in this array considering that the arr... | for i in range(q):
number = int(input())
print(binarySearch(0,len(array), number)) | random_line_split | |
P06_RankIt.py | # You have been given an array A consisting of N integers. All the elements in this array A are unique. You have to
# answer some queries based on the elements of this array. Each query will consist of a single integer x. You need to
# print the rank based position of this element in this array considering that the arr... | < element:
low = mid + 1
else:
high = mid - 1
for i in range(q):
number = int(input())
print(binarySearch(0,len(array), number))
| array[mid] | conditional_block |
P06_RankIt.py | # You have been given an array A consisting of N integers. All the elements in this array A are unique. You have to
# answer some queries based on the elements of this array. Each query will consist of a single integer x. You need to
# print the rank based position of this element in this array considering that the arr... | :
while(low <= high):
mid = (low + high) // 2
if array[mid] == element:
return mid
elif array[mid] < element:
low = mid + 1
else:
high = mid - 1
for i in range(q):
number = int(input())
print(binarySearch(0,len(array), number))
| gh, element) | identifier_name |
P06_RankIt.py | # You have been given an array A consisting of N integers. All the elements in this array A are unique. You have to
# answer some queries based on the elements of this array. Each query will consist of a single integer x. You need to
# print the rank based position of this element in this array considering that the arr... |
number = int(input())
print(binarySearch(0,len(array), number))
| mid = (low + high) // 2
if array[mid] == element:
return mid
elif array[mid] < element:
low = mid + 1
else:
high = mid - 1
for i in range(q): | identifier_body |
conf.py | # -*- coding: utf-8 -*-
#
# burrahobbit documentation build configuration file, created by
# sphinx-quickstart on Mon Apr 4 14:01:59 2011.
#
# 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 file.
#
#... | # -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc']
# Add any paths that contain templates here, relative t... | # If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../'))
| random_line_split |
time.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 https://mozilla.org/MPL/2.0/. */
//! Computed time values.
use crate::values::CSSFloat;
use std::fmt::{self, Write};
use style_traits::{CssWriter... | (&self) -> CSSFloat {
self.seconds
}
}
impl ToCss for Time {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
self.seconds().to_css(dest)?;
dest.write_str("s")
}
}
| seconds | identifier_name |
time.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 https://mozilla.org/MPL/2.0/. */
//! Computed time values. | use std::fmt::{self, Write};
use style_traits::{CssWriter, ToCss};
/// A computed `<time>` value.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, PartialOrd, ToResolvedValue)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
pub struct Time {
seconds: CSSFloat,
}
impl Time {
/// Creates a ... |
use crate::values::CSSFloat; | random_line_split |
time.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 https://mozilla.org/MPL/2.0/. */
//! Computed time values.
use crate::values::CSSFloat;
use std::fmt::{self, Write};
use style_traits::{CssWriter... |
/// Returns the amount of seconds this time represents.
#[inline]
pub fn seconds(&self) -> CSSFloat {
self.seconds
}
}
impl ToCss for Time {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
self.seconds().to_css(dest)?;
dest.wri... | {
Self::from_seconds(0.0)
} | identifier_body |
main.rs | #![feature(asm, const_fn, const_size_of, fn_traits)]
extern crate glutin;
extern crate cgmath;
extern crate frame_timer;
extern crate gl;
extern crate image;
#[macro_use]
extern crate lazy_static;
extern crate threadpool;
extern crate rand;
extern crate rusttype;
#[macro_use]
mod macros;
pub mod game;
pub mod graphi... |
//буря-engine
fn main() {
//this is for assets that have been loaded by their threads
//and then for the content manifest to keep track of them
let (load_subthread_sender, content_manifest_asset_receiver): (Sender<EContentType>, Receiver<EContentType>) =
mpsc::channel();
//this is for the ga... | use content::{ContentManifest, LoadContent};
use game::World;
use graphics::renderer::{RenderFrame, Renderer}; | random_line_split |
main.rs | #![feature(asm, const_fn, const_size_of, fn_traits)]
extern crate glutin;
extern crate cgmath;
extern crate frame_timer;
extern crate gl;
extern crate image;
#[macro_use]
extern crate lazy_static;
extern crate threadpool;
extern crate rand;
extern crate rusttype;
#[macro_use]
mod macros;
pub mod game;
pub mod graphi... |
//this is for assets that have been loaded by their threads
//and then for the content manifest to keep track of them
let (load_subthread_sender, content_manifest_asset_receiver): (Sender<EContentType>, Receiver<EContentType>) =
mpsc::channel();
//this is for the game thread to ask for an as... | () { | identifier_name |
main.rs | #![feature(asm, const_fn, const_size_of, fn_traits)]
extern crate glutin;
extern crate cgmath;
extern crate frame_timer;
extern crate gl;
extern crate image;
#[macro_use]
extern crate lazy_static;
extern crate threadpool;
extern crate rand;
extern crate rusttype;
#[macro_use]
mod macros;
pub mod game;
pub mod graphi... | //this is for the loading thread to send back the content id associated with the asset that the
//game just asked for
let (loading_thread_content_id, game_thread_content_id): (Sender<EContentRequestResult>, Receiver<EContentRequestResult>) =
mpsc::channel();
//this is for the game thread to use... | //this is for assets that have been loaded by their threads
//and then for the content manifest to keep track of them
let (load_subthread_sender, content_manifest_asset_receiver): (Sender<EContentType>, Receiver<EContentType>) =
mpsc::channel();
//this is for the game thread to ask for an asset... | identifier_body |
pin.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Lionel Flandrin <lionel@svkt.org>
//
// 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/LICENS... | (pid: PortId,
pin_index: u8,
dir: GpioDirection,
function: u8) -> Pin {
// Retrieve GPIO port peripheral to enable it
let (periph, regs) = match pid {
PortId::PortA => (sysctl::periph::gpio::PORT_A, reg::PORT_A),
PortId::PortB => (sysctl::periph::... | new | identifier_name |
pin.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Lionel Flandrin <lionel@svkt.org>
//
// 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/LICENS... | //! Pin configuration
//! Allows GPIO configuration
//! Pin muxing not implemented yet.
use hal::pin::{Gpio, GpioDirection, In, Out, GpioLevel, High, Low};
use hal::tiva_c::sysctl;
use util::support::get_reg_ref;
/// The pins are accessed through ports. Each port has 8 pins and are identified
/// by a letter (PortA, ... | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
| random_line_split |
pythonicos.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from random import shuffle
class Carta():
def __init__(self, numero, naipe):
self.numero = numero
self.naipe = naipe
def __repr__(self):
return '%s de %s' % (self.numero, self.naipe)
class Baralho():
... | return self.x==other.x and self.y==other.y
vetor1 = Vetor(1, 1)
vetor2 = Vetor(1, 1)
print vetor1 + vetor2
print vetor1 == vetor2 |
def __eq__(self, other): | random_line_split |
pythonicos.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from random import shuffle
class Carta():
def __init__(self, numero, naipe):
self.numero = numero
self.naipe = naipe
def __repr__(self):
return '%s de %s' % (self.numero, self.naipe)
class Baralho():
... | (self, other):
return self.x==other.x and self.y==other.y
vetor1 = Vetor(1, 1)
vetor2 = Vetor(1, 1)
print vetor1 + vetor2
print vetor1 == vetor2 | __eq__ | identifier_name |
pythonicos.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from random import shuffle
class Carta():
def __init__(self, numero, naipe):
self.numero = numero
self.naipe = naipe
def __repr__(self):
return '%s de %s' % (self.numero, self.naipe)
class Baralho():
... |
print Carta('As', 'Paus')
baralho = Baralho()
baralho[55] = Carta('As', 'Paus')
shuffle(baralho)
for carta in baralho:
print carta
print baralho[0]
class Vetor():
def __init__(self, x, y):
self.y = y
self.x = x
def __repr__(self):
return '(%s, %s)' % (self.x, self.y)
def ... | def __init__(self):
self._cartas = [Carta(numero, naipe) for numero in 'As 1 2 3 4 5 6 7 8 9 10 Q J K'.split()
for naipe in 'Ouros Espadas Copas Paus'.split()]
def __getitem__(self, index):
return self._cartas[index]
def __setitem__(self, key, value):
self._cart... | identifier_body |
pythonicos.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from random import shuffle
class Carta():
def __init__(self, numero, naipe):
self.numero = numero
self.naipe = naipe
def __repr__(self):
return '%s de %s' % (self.numero, self.naipe)
class Baralho():
... |
print baralho[0]
class Vetor():
def __init__(self, x, y):
self.y = y
self.x = x
def __repr__(self):
return '(%s, %s)' % (self.x, self.y)
def __add__(self, other):
return Vetor(self.x + other.x, self.y + other.y)
def __eq__(self, other):
return self.x==other... | print carta | conditional_block |
serve.ts | import * as denodeify from 'denodeify';
const assign = require('lodash/assign');
const SilentError = require('silent-error');
const PortFinder = require('portfinder');
const Command = require('../ember-cli/lib/models/command');
import ServeWebpackTask from '../tasks/serve-webpack';
import {Version} from '../upgrade/ver... | export default ServeCommand; | random_line_split | |
serve.ts | import * as denodeify from 'denodeify';
const assign = require('lodash/assign');
const SilentError = require('silent-error');
const PortFinder = require('portfinder');
const Command = require('../ember-cli/lib/models/command');
import ServeWebpackTask from '../tasks/serve-webpack';
import {Version} from '../upgrade/ver... |
}
// Check angular version.
Version.assertAngularVersionIs2_3_1OrHigher(this.project.root);
commandOptions.liveReloadHost = commandOptions.liveReloadHost || commandOptions.host;
return this._checkExpressPort(commandOptions)
.then(this._autoFindLiveReloadPort.bind(this))
.then((opts: S... | {
commandOptions.environment = 'prod';
} | conditional_block |
lib.rs | // Copyright 2014 Michael Yang. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#![feature(concat_idents)]
//! BLAS bindings and wrappers.
//!
//! Bindings are split by BLAS level and contained in a module named `ll`
//! (stands for low level... | pub use vector::VectorOperations;
pub use matrix::Matrix;
pub use vector::ops::*;
pub use matrix_vector::ops::*;
pub use matrix::ops::*;
#[macro_use]
mod prefix;
mod pointer;
mod scalar;
pub mod attribute;
pub mod default;
pub mod vector;
pub mod matrix_vector;
pub mod matrix;
pub mod math; |
pub use vector::Vector; | random_line_split |
strategy.js | var passport = require('passport'),
jwt = require('jsonwebtoken'),
extend = require('json-extend'),
common = require('./common'),
Client = require('./client');
function | (identifier, config) {
if(typeof(identifier) === 'object') {
config = identifier;
identifier = 'identity3-oidc';
}
if(!config || !config.client_id || !config.client_secret || !config.callback_url) {
throw new Error('The required config settings are not present [client_id, client_sec... | Strategy | identifier_name |
strategy.js | var passport = require('passport'),
jwt = require('jsonwebtoken'),
extend = require('json-extend'),
common = require('./common'),
Client = require('./client');
function Strategy(identifier, config) |
this.name = identifier;
this.config = config;
this.client = new Client(config);
if(config.configuration_endpoint) {
this.discover(config);
}
}
require('util').inherits(Strategy, passport.Strategy);
/*********** Passport Strategy Impl ***********/
Strategy.prototype.authenticate = funct... | {
if(typeof(identifier) === 'object') {
config = identifier;
identifier = 'identity3-oidc';
}
if(!config || !config.client_id || !config.client_secret || !config.callback_url) {
throw new Error('The required config settings are not present [client_id, client_secret, callback_url]');... | identifier_body |
strategy.js | var passport = require('passport'),
jwt = require('jsonwebtoken'),
extend = require('json-extend'),
common = require('./common'),
Client = require('./client');
function Strategy(identifier, config) {
if(typeof(identifier) === 'object') {
config = identifier;
identifier = 'identity3-... | else {
self.success(user);
}
} else {
req.session.tokens = null;
}
});
} else {
var state = common.randomHex(16);
req.session.tokens = {
state: state
};
this.redirect(this.client.author... | {
if(config.transformIdentity.length === 1) {
user = config.transformIdentity(user);
self.success(user);
} else {
config.transformIdentity(user, self.success, self.error);
}
... | conditional_block |
strategy.js | var passport = require('passport'),
jwt = require('jsonwebtoken'),
extend = require('json-extend'),
common = require('./common'),
Client = require('./client');
function Strategy(identifier, config) {
if(typeof(identifier) === 'object') {
config = identifier;
identifier = 'identity3-... |
/*********** End Passport Strategy Impl ***********/
// 5.3. UserInfo Endpoint [http://openid.net/specs/openid-connect-core-1_0.html#UserInfo]
Strategy.prototype.profile = function(req, scopes, claims, callback) {
this.client.getProfile(req, scopes, claims, callback);
};
// 5. RP-Initiated Logout [http://openi... |
this.redirect(this.client.authorizationUrl(req, state));
}
}; | random_line_split |
plot-nb-posts-per-day.mongo.js | /* globals db, load, makeMapWith, emit, renderDate */
load('./mongo-helpers/period-aggregator.mongo.js'); // exports makeMapWith()
// notice: MongoDB will not call the reduce function for a key that has only a single value
const map = makeMapWith(renderDate, function mapTemplate() {
// => emit same kind of output a... | res.results
.sort((a, b) => new Date(a._id) - new Date(b._id))
.map((res) => [res._id, res.value])
.join('\n')
); | var res = db.post.mapReduce(map, reduce, opts);
//print(res.results.map(res => [ res._id, res.value ]).join('\n'));
print( | random_line_split |
plot-nb-posts-per-day.mongo.js | /* globals db, load, makeMapWith, emit, renderDate */
load('./mongo-helpers/period-aggregator.mongo.js'); // exports makeMapWith()
// notice: MongoDB will not call the reduce function for a key that has only a single value
const map = makeMapWith(renderDate, function mapTemplate() {
// => emit same kind of output a... |
var opts = {
out: { inline: 1 },
//limit: 1000
};
var res = db.post.mapReduce(map, reduce, opts);
//print(res.results.map(res => [ res._id, res.value ]).join('\n'));
print(
res.results
.sort((a, b) => new Date(a._id) - new Date(b._id))
.map((res) => [res._id, res.value])
.join('\n')
);
| {
// notice: MongoDB can invoke the reduce function more than once for the same key
var sum = (a, b) => a + b;
return count.reduce(sum);
} | identifier_body |
plot-nb-posts-per-day.mongo.js | /* globals db, load, makeMapWith, emit, renderDate */
load('./mongo-helpers/period-aggregator.mongo.js'); // exports makeMapWith()
// notice: MongoDB will not call the reduce function for a key that has only a single value
const map = makeMapWith(renderDate, function mapTemplate() {
// => emit same kind of output a... | (day, count) {
// notice: MongoDB can invoke the reduce function more than once for the same key
var sum = (a, b) => a + b;
return count.reduce(sum);
}
var opts = {
out: { inline: 1 },
//limit: 1000
};
var res = db.post.mapReduce(map, reduce, opts);
//print(res.results.map(res => [ res._id, res.value ]).joi... | reduce | identifier_name |
kangrouter.py | import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv... | self.validateReply(req)
return req.text
def delete(self,solverId):
path = "{base}/{solverId}".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.delete(path,
params=self.params,
headers=se... | req = self.session.post(path,
params=params,
headers=self.headers,
data=payload) | random_line_split |
kangrouter.py | import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv... |
if timeout == 0:
raise exception.InternalError("Timed out waiting for solver")
raise exception.UserCancelled()
| status = self.getStatus(solverId)
if status["execStatus"] =="invalid":
raise exception.solverError(json.dumps(status["errors"]))
if status["execStatus"] =="completed":
return self.getSolution(solverId)
time.sleep(1)
timeout -= 1 | conditional_block |
kangrouter.py | import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class | :
pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/solvers"
def __init__(self,apiKey,licenseId):
self.headers = {"content-type": "application/json",
"Authorization": apiKey}
self.params = {"licenseId" : licenseId }
retries = Retry(total=5,
backoff_f... | KangRouterClient | identifier_name |
kangrouter.py | import time
from tsm.common.app import exception
import requests
import json
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1"
class KangRouterClient:
pathbase = "https://thesolvingmachine.com/kangrouter/srv... |
def getStatus(self,solverId):
path = "{base}/{solverId}/status".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.get(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
re... | path = "{base}/{solverId}/stop".format(base=self.pathbase,
solverId=str(solverId))
req = self.session.put(path,
params=self.params,
headers=self.headers)
self.validateReply(req)
return True | identifier_body |
post_list.js | // Generated by CoffeeScript 1.3.3
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() | ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
app.views.PostList = (function(_super) {
__extends(PostList, _super);
function PostList() {
this.render = __bind(this.render, this);
return PostList.__super__.constructor.apply... | { this.constructor = child; } | identifier_body |
post_list.js | // Generated by CoffeeScript 1.3.3
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() {... | else {
_results.push(void 0);
}
}
return _results;
};
return PostList;
})(Backbone.View);
}).call(this);
| {
_results.push($view.appendTo(this.el));
} | conditional_block |
post_list.js | // Generated by CoffeeScript 1.3.3
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() {... | }).call(this); | return PostList;
})(Backbone.View);
| random_line_split |
post_list.js | // Generated by CoffeeScript 1.3.3
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() {... | () {
this.render = __bind(this.render, this);
return PostList.__super__.constructor.apply(this, arguments);
}
PostList.prototype.el = function() {
return document.getElementById('content');
};
PostList.prototype.render = function() {
var $view, model, _i, _len, _ref, _results;
... | PostList | identifier_name |
check_json.py | # Copyright 2017 NeuStar, Inc.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/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | if self.key not in self.obj:
raise KeyError(self.key_error)
else:
return self.obj[self.key] | self.key_error = 'No IP info returned.'
self.key = key
self.obj = obj
def key_valid(self): | random_line_split |
check_json.py | # Copyright 2017 NeuStar, Inc.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/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | if self.key not in self.obj:
raise KeyError(self.key_error)
else:
return self.obj[self.key] | identifier_body | |
check_json.py | # Copyright 2017 NeuStar, Inc.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/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
self.key = key
self.obj = obj
def key_valid(self):
if self.key not in self.obj:
raise KeyError(self.key_error)
else:
return self.obj[self.key] | self.key_error = 'No IP info returned.' | conditional_block |
check_json.py | # Copyright 2017 NeuStar, Inc.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/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | (self):
if self.key not in self.obj:
raise KeyError(self.key_error)
else:
return self.obj[self.key] | key_valid | identifier_name |
vis.py |
"""
Visualize possible stitches with the outcome of the validator.
"""
import math
import random
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import stitcher
SPACE = 25
TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'}
def show(graphs, request, title... | (graphs, request, titles, prog='neato', filename=None):
"""
Show the candidates in 3d - the request elevated above the container.
"""
fig = plt.figure(figsize=(18, 10))
fig.set_facecolor('white')
i = 0
size = _get_size(len(graphs))
for graph in graphs:
axes = fig.add_subplot(si... | show_3d | identifier_name |
vis.py |
"""
Visualize possible stitches with the outcome of the validator.
"""
import math
import random
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import stitcher
SPACE = 25
TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'}
def show(graphs, request, title... |
for src, trg in tmp.edges():
axes.plot([pos[src][0], pos[trg][0]],
[pos[src][1], pos[trg][1]],
[0, 0], color='gray')
# the new nodes
for item in graph.nodes():
if item in request.nodes():
for nghb in graph.neighbors(item):
if... | axes.plot([pos[item][0]], [pos[item][1]], [0], linestyle="None",
marker="o", color='gray')
axes.text(pos[item][0], pos[item][1], 0, item) | conditional_block |
vis.py | """
Visualize possible stitches with the outcome of the validator.
"""
import math
import random
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import stitcher
SPACE = 25
TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'}
def show(graphs, request, titles... | y_val = pos[nghb][0] + random.randint(10, SPACE)
cache[item] = (x_val, y_val)
# edge
axes.plot([x_val, pos[nghb][0]],
[y_val, pos[nghb][1]],
[SPACE, 0], color='blue')
... | if (x_val, y_val) in list(cache.values()):
x_val = pos[nghb][0] + random.randint(10, SPACE) | random_line_split |
vis.py |
"""
Visualize possible stitches with the outcome of the validator.
"""
import math
import random
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import stitcher
SPACE = 25
TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'}
def show(graphs, request, title... | axarr[x_val, y_val].set_title(titles[index])
# axarr[x_val, y_val].set_axis_bgcolor("white")
if not type_format:
type_format = TYPE_FORMAT
_plot_subplot(candidate, request.nodes(), prog, type_format,
axarr[x_val, y_val])
y_val += 1
if y_va... | """
Display the results using matplotlib.
"""
if not size:
size = _get_size(len(graphs))
fig, axarr = plt.subplots(size[0], size[1], figsize=(18, 10))
fig.set_facecolor('white')
x_val = 0
y_val = 0
index = 0
if size[0] == 1:
axarr = np.array(axarr).reshape((1, size[1... | identifier_body |
NavList.tsx | import React, { useState } from 'react';
import styled from 'styled-components';
import { MainLi, MainUl } from '../Utils';
const NavBarDiv = styled.div`
margin-bottom: 0.25em;
text-align: center;
transition: all 0.4s ease-in-out, transform 0.2s ease-in-out;
&.Open {
margin-top: 0.5em;
max-height: 100... | <ExpandIcon />
</ExpandIconButton>
</ExpandIconDiv>
)}
</>
);
} | className={openClass}
onClick={toggleOpen}
data-testid='navlist-expand-button'
> | random_line_split |
pagers.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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... |
@property
def pages(self) -> Iterator[compute.PublicDelegatedPrefixList]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
self._response = self._method(self._request, metadata=self._metadata)
... | return getattr(self._response, name) | identifier_body |
pagers.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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... |
def __iter__(self) -> Iterator[compute.PublicDelegatedPrefix]:
for page in self.pages:
yield from page.items
def __repr__(self) -> str:
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
| self._request.page_token = self._response.next_page_token
self._response = self._method(self._request, metadata=self._metadata)
yield self._response | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.