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 |
|---|---|---|---|---|
webInterface.js | = require('co'),
compress = require('compression');
const packageJson = require('../package.json');
const MAX_CONTENT_SIZE = 1024 * 2000; // 2000kb
/**
*
*
* @class webInterface
* @extends {events.EventEmitter}
*/
class webInterface extends events.EventEmitter {
/**
* Creates an instance of webInterface... | (config, recorder) {
if (!recorder) {
throw new Error('recorder is required for web interface');
}
super();
const self = this;
self.webPort = config.webPort || DEFAULT_WEB_PORT;
self.recorder = recorder;
self.config = config || {};
self.app = null;
self.server = null;
self... | constructor | identifier_name |
webInterface.js | require('co'),
compress = require('compression');
const packageJson = require('../package.json');
const MAX_CONTENT_SIZE = 1024 * 2000; // 2000kb
/**
*
*
* @class webInterface
* @extends {events.EventEmitter}
*/
class webInterface extends events.EventEmitter {
/**
* Creates an instance of webInterface.
... | const myAbsAddress = 'http://' + ipAddress + ':' + self.webPort + '/',
staticDir = path.join(__dirname, '../', webBasePath);
const app = express();
app.use(compress()); //invoke gzip
app.use((req, res, next) => {
res.setHeader('note', 'THIS IS A REQUEST FROM ANYPROXY WEB INTERFA... | {
const self = this;
const recorder = self.recorder;
let wsPort;
return co(function *() {
// determine ws port
wsPort = self.config.wsPort ? self.config.wsPort : yield util.getFreePort();
}).then(() => {
const ipAddress = ip.address(),
// userRule = proxyInstance.proxyRule... | identifier_body |
webInterface.js | = require('co'),
compress = require('compression');
const packageJson = require('../package.json');
const MAX_CONTENT_SIZE = 1024 * 2000; // 2000kb
/**
*
*
* @class webInterface
* @extends {events.EventEmitter}
*/
class webInterface extends events.EventEmitter {
/**
* Creates an instance of webInterface... |
super();
const self = this;
self.webPort = config.webPort || DEFAULT_WEB_PORT;
self.recorder = recorder;
self.config = config || {};
self.app = null;
self.server = null;
self.wsServer = null;
}
start() {
const self = this;
const recorder = self.recorder;
let wsPort;
... | {
throw new Error('recorder is required for web interface');
} | conditional_block |
run_on.py | import sys
import os
import files.io
from StringIO import StringIO
from constants import *
added_path = os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))), "script")
sys.path.append(added_path)
import script
import mess
sys.path.pop()
def full_file(pointer):
pointer.seek(0)
return pointe... |
if "constants" in input_files:
kwargs["constants"] = StringIO(input_files["constants"])
success = script.run_script(
StringIO(input_files["template"]),
StringIO(input_files["spreadsheet"]),
output=output_location,
actually_send=actually_send,
**kwargs
)
s... | kwargs["send_confirmation_to"] = None | conditional_block |
run_on.py | import sys
import os
import files.io
from StringIO import StringIO
from constants import *
added_path = os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))), "script")
sys.path.append(added_path)
import script
import mess
sys.path.pop()
def full_file(pointer):
pointer.seek(0)
return pointe... | send_confirmation_email(confirmation_email, script_results)
return script_results, success
| input_files = files.io.get(key)
assert "template" in input_files, "Need to submit non-empty template"
assert "spreadsheet" in input_files, "Need to submit non-empty spreadsheet"
output_location = StringIO()
kwargs = {}
if send_default_confirmation:
pass
else:
kwargs["send_confirm... | identifier_body |
run_on.py | import sys
import os
import files.io
from StringIO import StringIO
from constants import *
added_path = os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))), "script")
sys.path.append(added_path)
import script
import mess
sys.path.pop()
def full_file(pointer):
pointer.seek(0)
return pointe... | "To": recipient,
"From": CONFIRMATION_EMAIL_FROM
}
mess.Message(email_headers, contents).send(connection)
connection.quit()
def run_on(key, actually_send=False, confirmation_email=CONFIRMATION_EMAIL_FROM, confirmation_email_on_success=True, confirmation_email_on_fail=True, special_text="", ... | def send_confirmation_email(recipient, contents):
connection = script.get_mailserver_connection()
email_headers = {
"Subject": CONFIRMATION_EMAIL_SUBJECT, | random_line_split |
run_on.py | import sys
import os
import files.io
from StringIO import StringIO
from constants import *
added_path = os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))), "script")
sys.path.append(added_path)
import script
import mess
sys.path.pop()
def | (pointer):
pointer.seek(0)
return pointer.read()
def send_confirmation_email(recipient, contents):
connection = script.get_mailserver_connection()
email_headers = {
"Subject": CONFIRMATION_EMAIL_SUBJECT,
"To": recipient,
"From": CONFIRMATION_EMAIL_FROM
}
mess.Message(ema... | full_file | identifier_name |
mod.rs | use super::Path;
use super::connector::Connector;
use super::resolver::Resolve;
use futures::{Async, Future, Poll, unsync};
use ordermap::OrderMap;
use std::{cmp, io, net};
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use tacho;
use tokio_core::reactor::Handle;
use tokio_timer::Timer;
mod dispat... |
}
pub fn new(
reactor: &Handle,
timer: &Timer,
dst: &Path,
connector: Connector,
resolve: Resolve,
metrics: &tacho::Scope,
) -> Balancer {
let (tx, rx) = unsync::mpsc::unbounded();
let dispatcher = dispatcher::new(
reactor.clone(),
timer.clone(),
dst.clone(),
... | {
WeightedAddr { addr, weight }
} | identifier_body |
mod.rs | use super::Path;
use super::connector::Connector;
use super::resolver::Resolve;
use futures::{Async, Future, Poll, unsync};
use ordermap::OrderMap;
use std::{cmp, io, net};
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use tacho;
use tokio_core::reactor::Handle;
use tokio_timer::Timer;
mod dispat... | (unsync::mpsc::UnboundedSender<Waiter>);
impl Balancer {
/// Obtains a connection to the destination.
pub fn connect(&self) -> Connect {
let (tx, rx) = unsync::oneshot::channel();
let result = unsync::mpsc::UnboundedSender::unbounded_send(&self.0, tx)
.map_err(|_| io::Error::new(io::... | Balancer | identifier_name |
mod.rs | use super::Path;
use super::connector::Connector;
use super::resolver::Resolve;
use futures::{Async, Future, Poll, unsync};
use ordermap::OrderMap;
use std::{cmp, io, net};
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use tacho;
use tokio_core::reactor::Handle;
use tokio_timer::Timer;
mod dispat... | }
#[derive(Clone)]
pub struct Balancer(unsync::mpsc::UnboundedSender<Waiter>);
impl Balancer {
/// Obtains a connection to the destination.
pub fn connect(&self) -> Connect {
let (tx, rx) = unsync::oneshot::channel();
let result = unsync::mpsc::UnboundedSender::unbounded_send(&self.0, tx)
... | Endpoints::default(),
metrics,
);
reactor.spawn(dispatcher.map_err(|_| {}));
Balancer(tx) | random_line_split |
installer.py | import os, psycopg2, rsa
from urllib.parse import urlparse
class Installer:
def connect(self):
self.url = urlparse(os.environ["DATABASE_URL"])
self.db = psycopg2.connect(database=self.url.path[1:],
user=self.url.username,
... |
if __name__ == '__main__':
Installer().install()
| self.connect()
self.create_database()
self.seed_database() | identifier_body |
installer.py | import os, psycopg2, rsa
from urllib.parse import urlparse
class Installer:
def connect(self):
self.url = urlparse(os.environ["DATABASE_URL"])
self.db = psycopg2.connect(database=self.url.path[1:],
user=self.url.username,
... | (self):
self.connect()
self.create_database()
self.seed_database()
if __name__ == '__main__':
Installer().install()
| install | identifier_name |
installer.py | import os, psycopg2, rsa
from urllib.parse import urlparse
class Installer:
def connect(self):
self.url = urlparse(os.environ["DATABASE_URL"])
self.db = psycopg2.connect(database=self.url.path[1:],
user=self.url.username,
... |
status text,
email text,
birthday bigint,
about text,
image bytea)''')
c.execute(''... |
c.execute('''CREATE TABLE profiles (name text PRIMARY KEY
REFERENCES users(name),
| random_line_split |
installer.py | import os, psycopg2, rsa
from urllib.parse import urlparse
class Installer:
def connect(self):
self.url = urlparse(os.environ["DATABASE_URL"])
self.db = psycopg2.connect(database=self.url.path[1:],
user=self.url.username,
... | Installer().install() | conditional_block | |
dsstore_scanner.py | from ds_store import DSStore, DSStoreEntry
from burp import IBurpExtender
from burp import IScannerCheck
from burp import IExtensionStateListener
from burp import IScanIssue
import StringIO
from urlparse import urlparse
def traverse_ds_store_file(d):
"""
Traverse a DSStore object from the node and yeld each ... | self.scan_issues.append(ScanIssue(self._requestResponse.getHttpService(),
self._helpers.analyzeRequest(
self._requestResponse).getUrl(),
issuename,
... | filename = path.split("/")[-1].split("?")[0]
# it's a .DS_Store file
if filename == ".DS_Store":
host = self._requestResponse.getHttpService().getHost()
protocol = self._requestResponse.getHttpService().getProtocol()
response = self._requestRespons... | conditional_block |
dsstore_scanner.py | from ds_store import DSStore, DSStoreEntry
from burp import IBurpExtender
from burp import IScannerCheck
from burp import IExtensionStateListener
from burp import IScanIssue
import StringIO
from urlparse import urlparse
def | (d):
"""
Traverse a DSStore object from the node and yeld each entry.
:param d: DSStore object
:return: None
"""
node = d._rootnode
with d._get_block(node) as block:
next_node, count = block.read(b'>II')
if next_node:
for n in range(count):
ptr = b... | traverse_ds_store_file | identifier_name |
dsstore_scanner.py | from ds_store import DSStore, DSStoreEntry
from burp import IBurpExtender
from burp import IScannerCheck
from burp import IExtensionStateListener
from burp import IScanIssue
import StringIO
from urlparse import urlparse
def traverse_ds_store_file(d):
"""
Traverse a DSStore object from the node and yeld each ... |
# Create a ScanIssue object and append it to our list of issues
self.scan_issues.append(ScanIssue(self._requestResponse.getHttpService(),
self._helpers.analyzeRequest(
self._requestRe... | issuedetail = """<p>The .DS_Store file was found to contain the following entries: <br><ul><li>%s</li></ul></p>""" %\
"</li><li>".join(str(x) for x in ds_store_content)
issueremediation = """Some remediation""" | random_line_split |
dsstore_scanner.py | from ds_store import DSStore, DSStoreEntry
from burp import IBurpExtender
from burp import IScannerCheck
from burp import IExtensionStateListener
from burp import IScanIssue
import StringIO
from urlparse import urlparse
def traverse_ds_store_file(d):
"""
Traverse a DSStore object from the node and yeld each ... |
def extensionUnloaded(self):
print(".DS_Store Scanner unloaded")
return
# Implementation of the IScanIssue interface with simple constructor and getter methods
class ScanIssue(IScanIssue):
def __init__(self, httpservice, url, name, severity, detailmsg, remediationmsg):
self._url = ur... | if existingIssue.getUrl() == newIssue.getUrl() and \
existingIssue.getIssueDetail() == newIssue.getIssueDetail():
return -1
else:
return 0 | identifier_body |
TeamArcher.js | game.TeamArcher = me.Entity.extend({
init: function(x, y, settings){
this._super(me.Entity, 'init', [x, y, {
image: "archer",
width: 64,
height: 64,
spritewidth: "64",
spriteheight: "64",
getShap... | else if(response.b.type==='EnemyWizard'){
var xdif = this.pos.x - response.b.pos.x;
}
this.attacking=true;
if(xdif>0){
this.pos.x = this.pos.x + 1;
this.body.vel.x = 0;
}
if((this.now-t... | {
var xdif = this.pos.x - response.b.pos.x;
} | conditional_block |
TeamArcher.js | game.TeamArcher = me.Entity.extend({
init: function(x, y, settings){
this._super(me.Entity, 'init', [x, y, {
image: "archer",
width: 64,
height: 64,
spritewidth: "64",
spriteheight: "64",
getShap... |
if(xdif>0){
this.pos.x = this.pos.x + 1;
this.body.vel.x = 0;
}
if((this.now-this.lastHit >=1000) && xdif>0){
this.lastHit = this.now;
response.b.loseHealth(game.data.teamArcherAttack);
}
}
}
... | random_line_split | |
test_PerFieldAnalyzerWrapper.py | # ====================================================================
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | (self):
text = "Qwerty"
analyzer = PerFieldAnalyzerWrapper(WhitespaceAnalyzer())
analyzer.addAnalyzer("special", SimpleAnalyzer())
tokenStream = analyzer.tokenStream("field", StringReader(text))
termAtt = tokenStream.getAttribute(CharTermAttribute.class_)
self.assert_(... | testPerField | identifier_name |
test_PerFieldAnalyzerWrapper.py | # ====================================================================
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | # limitations under the License.
# ====================================================================
from unittest import TestCase, main
from lucene import *
class PerFieldAnalyzerTestCase(TestCase):
"""
Unit tests ported from Java Lucene
"""
def testPerField(self):
text = "Qwerty"
... | # See the License for the specific language governing permissions and | random_line_split |
test_PerFieldAnalyzerWrapper.py | # ====================================================================
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... |
if __name__ == "__main__":
import sys, lucene
lucene.initVM()
if '-loop' in sys.argv:
sys.argv.remove('-loop')
while True:
try:
main()
except:
pass
else:
main()
| text = "Qwerty"
analyzer = PerFieldAnalyzerWrapper(WhitespaceAnalyzer())
analyzer.addAnalyzer("special", SimpleAnalyzer())
tokenStream = analyzer.tokenStream("field", StringReader(text))
termAtt = tokenStream.getAttribute(CharTermAttribute.class_)
self.assert_(tokenStream.incre... | identifier_body |
test_PerFieldAnalyzerWrapper.py | # ====================================================================
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | main() | conditional_block | |
NodeAnchor.ts | import { FieldSchema } from '@ephox/boulder';
import { Option } from '@ephox/katamari';
import { AlloyComponent } from '../../api/component/ComponentApi';
import * as Fields from '../../data/Fields';
import * as Origins from '../layout/Origins';
import { NodeAnchor, Anchoring } from './Anchoring';
import * as Containe... | export default [
FieldSchema.strict('node'),
FieldSchema.strict('root'),
FieldSchema.option('bubble'),
AnchorLayouts.schema(),
// chiefly MaxHeight.expandable()
FieldSchema.defaulted('overrides', {}),
FieldSchema.defaulted('showAbove', false),
Fields.output('placement', placement)
]; | };
| random_line_split |
tracker.ts | import { isProduction } from '../utility';
declare const ga: any;
export function track(
category:
| 'Home-New'
| 'Recording'
| 'Listening'
| 'Profile'
| 'Languages'
| 'Data'
| 'Sharing'
| 'Dashboard'
| 'Global'
| 'Nav'
| 'Landing'
| 'Challenge'
| 'voice-avatar',
... |
}
export function trackGlobal(
action:
| 'change-language'
| 'github'
| 'discourse'
| 'contact'
| 'footer-newsletter'
| 'slack',
locale: string
) {
track('Global', action, locale);
}
export function trackNav(route: string, locale: string) {
track('Nav', route, locale);
}
export funct... | {
console.debug('analytics event (not tracked here)', {
category,
action,
locale,
});
} | conditional_block |
tracker.ts | import { isProduction } from '../utility';
declare const ga: any;
export function track(
category:
| 'Home-New'
| 'Recording'
| 'Listening'
| 'Profile'
| 'Languages'
| 'Data'
| 'Sharing'
| 'Dashboard'
| 'Global'
| 'Nav'
| 'Landing'
| 'Challenge'
| 'voice-avatar',
... |
export function trackHome(
action:
| 'speak'
| 'speak-mars'
| 'listen'
| 'read-more'
| 'metric-locale-change'
| 'change-benefits-tabs'
| 'click-whats-public-item'
| 'click-benefits-item'
| 'click-benefits-register',
locale: string
) {
track('Home-New', action, locale);
}
expo... |
export function trackNav(route: string, locale: string) {
track('Nav', route, locale);
} | random_line_split |
tracker.ts | import { isProduction } from '../utility';
declare const ga: any;
export function track(
category:
| 'Home-New'
| 'Recording'
| 'Listening'
| 'Profile'
| 'Languages'
| 'Data'
| 'Sharing'
| 'Dashboard'
| 'Global'
| 'Nav'
| 'Landing'
| 'Challenge'
| 'voice-avatar',
... | (action: string, locale: string) {
track('Data', action, locale);
}
export function trackSharing(
channel: 'facebook' | 'twitter' | 'link',
locale: string
) {
track('Sharing', channel, locale);
}
export function trackDashboard(
action:
| 'speak-cta'
| 'listen-cta'
| 'change-language'
| 'lead... | trackDataset | identifier_name |
tracker.ts | import { isProduction } from '../utility';
declare const ga: any;
export function track(
category:
| 'Home-New'
| 'Recording'
| 'Listening'
| 'Profile'
| 'Languages'
| 'Data'
| 'Sharing'
| 'Dashboard'
| 'Global'
| 'Nav'
| 'Landing'
| 'Challenge'
| 'voice-avatar',
... |
export function trackRecording(
action:
| 'record'
| 'submit'
| 'rerecord'
| 'view-shortcuts'
| 'shortcut'
| 'skip'
| 'listen',
locale: string
) {
track('Recording', action, locale);
}
export function trackListening(
action:
| 'listen'
| 'listen-home'
| 'vote-yes'
... | {
track('Home-New', action, locale);
} | identifier_body |
callee.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
let llfn = if let Some(llfn) = cx.get_declared_value(&sym) {
// This is subtle and surprising, but sometimes we have to bitcast
// the resulting fn pointer. The reason has to do with external
// functions. If you have two crates that both bind the same C
// library, they may not u... | {
let tcx = cx.tcx();
debug!("get_fn(instance={:?})", instance);
assert!(!instance.substs.needs_infer());
assert!(!instance.substs.has_escaping_bound_vars());
assert!(!instance.substs.has_param_types());
let sig = instance.fn_sig(cx.tcx());
if let Some(&llfn) = cx.instances().borrow().get... | identifier_body |
callee.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | } else {
debug!("get_fn: not casting pointer!");
llfn
}
} else {
let llfn = cx.declare_fn(&sym, sig);
assert_eq!(cx.val_ty(llfn), llptrty);
debug!("get_fn: not casting pointer!");
if instance.def.is_inline(tcx) {
attributes::inline... | // reference. It also occurs when testing libcore and in some
// other weird situations. Annoying.
if cx.val_ty(llfn) != llptrty {
debug!("get_fn: casting {:?} to {:?}", llfn, llptrty);
cx.const_ptrcast(llfn, llptrty) | random_line_split |
callee.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
}
}
if cx.use_dll_storage_attrs &&
tcx.is_dllimport_foreign_item(instance_def_id)
{
unsafe {
llvm::LLVMSetDLLStorageClass(llfn, llvm::DLLStorageClass::DllImport);
}
}
llfn
};
cx.instance... | {
// This is a function from an upstream crate that has
// been instantiated here. These are always hidden.
llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden);
} | conditional_block |
callee.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (
cx: &CodegenCx<'ll, 'tcx>,
instance: Instance<'tcx>,
) -> &'ll Value {
let tcx = cx.tcx();
debug!("get_fn(instance={:?})", instance);
assert!(!instance.substs.needs_infer());
assert!(!instance.substs.has_escaping_bound_vars());
assert!(!instance.substs.has_param_types());
let sig = ... | get_fn | identifier_name |
pipelines.js | const log = require('../logger').gateway;
const policies = require('../policies');
const EgContextBase = require('./context');
const express = require('express');
const vhost = require('vhost');
const ConfigurationError = require('../errors').ConfigurationError;
/*
* A pipeline consists of an apiEndpoint and a set of... | (policies, config) {
const policiesConfig = config.gatewayConfig.policies || [];
policies.forEach(policyObj => {
const policyNames = Object.keys(policyObj);
if (policyNames.length !== 1) {
throw new ConfigurationError('there should be one and only one policy per policy-object in pipeline configurat... | validatePipelinePolicies | identifier_name |
pipelines.js | const log = require('../logger').gateway;
const policies = require('../policies');
const EgContextBase = require('./context');
const express = require('express');
const vhost = require('vhost');
const ConfigurationError = require('../errors').ConfigurationError;
/*
* A pipeline consists of an apiEndpoint and a set of... | }
});
} | throw new ConfigurationError('there should be one and only one policy per policy-object in pipeline configuration');
}
if (policiesConfig.indexOf(policyNames[0]) === -1) {
throw new ConfigurationError(`${policyNames[0]} policy not declared`); | random_line_split |
pipelines.js | const log = require('../logger').gateway;
const policies = require('../policies');
const EgContextBase = require('./context');
const express = require('express');
const vhost = require('vhost');
const ConfigurationError = require('../errors').ConfigurationError;
/*
* A pipeline consists of an apiEndpoint and a set of... |
}
if (!gatewayConfig.apiEndpoints) {
if (gatewayConfig.apiEndpoint) {
gatewayConfig.apiEndpoints = Array.isArray(gatewayConfig.apiEndpoint) ? gatewayConfig.apiEndpoint : [ gatewayConfig.apiEndpoint ];
} else {
return false;
}
}
for (const name in gatewayConfig.pipelines) {
const pi... | {
return false;
} | conditional_block |
pipelines.js | const log = require('../logger').gateway;
const policies = require('../policies');
const EgContextBase = require('./context');
const express = require('express');
const vhost = require('vhost');
const ConfigurationError = require('../errors').ConfigurationError;
/*
* A pipeline consists of an apiEndpoint and a set of... | {
const policiesConfig = config.gatewayConfig.policies || [];
policies.forEach(policyObj => {
const policyNames = Object.keys(policyObj);
if (policyNames.length !== 1) {
throw new ConfigurationError('there should be one and only one policy per policy-object in pipeline configuration');
}
if... | identifier_body | |
AddWorkRequestSource.js | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
Ext.define('sisprod.view.WorkRequestSource.AddWorkRequestSource', {
extend: 'sisprod.view.base.BaseDataWindow',
alias: 'widget.addWorkRequestSource',
require: [
'sisprod.view.ba... | fieldLabel: me.messages.labels.workRequestSourceAcronym,
anchor: '40%',
maxLength: 6,
fieldStyle: {textTransform: 'uppercase'}
}
]
};
me.callParent(arguments);
}
}); | name: 'workRequestSourceAcronym',
| random_line_split |
conf.py | # -*- coding: utf-8 -*-
#
# Clawpack documentation build configuration file, created by
# sphinx-quickstart on Wed Mar 25 12:07:14 2009.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickle... |
# The encoding of source files.
#source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Clawpack'
copyright = u'2009, Randall J. LeVeque and others'
# The version info for the project you're documenting, acts as replacement for
# |version| ... | # The suffix of source filenames.
source_suffix = '.rst' | random_line_split |
feature-api-test.js | var apiTester = require('./api-crud-executor.js');
apiTester({
name: 'FeatureAPI',
baseurl: 'http://localhost:3000',
baseapi: '/api/feature',
resCacheData: [],
resCacheKeys: function (response) {
return {'id': response.id, 'name': response.name};
},
t... | find: function () {
return [
this.resCacheData[0],
this.resCacheData[Math.floor(this.resCacheData.length / 2)],
this.resCacheData[this.resCacheData.length - 1]
];
},
patch: function () {
return {
... | {send: {name: 'javascript'}},
{send: {name: 'superagent'}},
{send: {name: 'require'}}
]
}, | random_line_split |
Component.tsx | import { ChecklistProps } from 'parser/shared/modules/features/Checklist/ChecklistTypes';
import Requirement from 'parser/shared/modules/features/Checklist/Requirement';
import Rule from 'parser/shared/modules/features/Checklist/Rule';
import PreparationRule from 'parser/tbc/modules/features/Checklist/PreparationRule';... | import RESOURCE_TYPES from 'game/RESOURCE_TYPES';
import { ResourceLink } from 'interface';
import { TooltipElement } from 'interface/Tooltip';
import Checklist from 'parser/shared/modules/features/Checklist'; | random_line_split | |
debugPanel.js | function panel() | {
ctx.fillStyle = 'rgb(0,0,0)';
ctx.font = "10px serif";
ctx.fillText("y-Velocity: " + charictar.vY, scrWidth - 100, 10);
ctx.fillText("y position: " + charictar.y, scrWidth - 100, 20);
ctx.fillText("scrHeight: " + scrHeight/2, scrWidth - 100, 30);
ctx.fillText("up key: " + keyPress[38], scrWidth - 1... | identifier_body | |
debugPanel.js | function panel(){
ctx.fillStyle = 'rgb(0,0,0)';
ctx.font = "10px serif"; | ctx.fillText("slimy y-boundry: " + yBoundryActive[3], scrWidth - 100, 50);
ctx.fillText("rainbow y-boundry: " + yBoundryActive[4], scrWidth - 100, 60);
} | ctx.fillText("y-Velocity: " + charictar.vY, scrWidth - 100, 10);
ctx.fillText("y position: " + charictar.y, scrWidth - 100, 20);
ctx.fillText("scrHeight: " + scrHeight/2, scrWidth - 100, 30);
ctx.fillText("up key: " + keyPress[38], scrWidth - 100, 40); | random_line_split |
debugPanel.js | function | (){
ctx.fillStyle = 'rgb(0,0,0)';
ctx.font = "10px serif";
ctx.fillText("y-Velocity: " + charictar.vY, scrWidth - 100, 10);
ctx.fillText("y position: " + charictar.y, scrWidth - 100, 20);
ctx.fillText("scrHeight: " + scrHeight/2, scrWidth - 100, 30);
ctx.fillText("up key: " + keyPress[38], scrWidth -... | panel | identifier_name |
macro-comma-behavior.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
unimplemented!("{}",);
//[core]~^ ERROR no arguments
//[std]~^^ ERROR no arguments
// if falsum() { unreachable!("{}",); } // see run-pass
struct S;
impl fmt::Display for S {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}",)?;
//[cor... | // FIXME: compile-fail says "expected error not found" even though
// rustc does emit an error
// println!("{}",);
// <DISABLED> [std]~^ ERROR no arguments | random_line_split |
macro-comma-behavior.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {} | identifier_body | |
macro-comma-behavior.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | ;
impl fmt::Display for S {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}",)?;
//[core]~^ ERROR no arguments
//[std]~^^ ERROR no arguments
// FIXME: compile-fail says "expected error not found" even though
// rustc do... | S | identifier_name |
main.rs | /*
Rust - Std Misc Path
Licence : GNU GPL v3 or later
Author : Aurélien DESBRIÈRES
Mail : aurelien(at)hackers(dot)camp
Created on : June 2017
Write with Emacs-nox ───────────────┐
Rust ───────────────────────────────┘
*/
use std::path::Path;
fn main() {
// Create a `Path` from a `&'static str`
... | // windows::Path | // posix::Path | random_line_split |
main.rs | /*
Rust - Std Misc Path
Licence : GNU GPL v3 or later
Author : Aurélien DESBRIÈRES
Mail : aurelien(at)hackers(dot)camp
Created on : June 2017
Write with Emacs-nox ───────────────┐
Rust ───────────────────────────────┘
*/
use std::path::Path;
fn main() {
// Create a `Path` from a `&'static str`
... | ` method returns a `Show`able structure
//let display = path.display();
println!("{}", path.display());
// `join` merges a path with a byte container using the OS specific
// separator, and returns the new path
let new_path = path.join("a").join("b");
// Convert the path into a string slice
... | identifier_body | |
main.rs | /*
Rust - Std Misc Path
Licence : GNU GPL v3 or later
Author : Aurélien DESBRIÈRES
Mail : aurelien(at)hackers(dot)camp
Created on : June 2017
Write with Emacs-nox ───────────────┐
Rust ───────────────────────────────┘
*/
use std::path::Path;
fn main() {
// Create a `Path` from a `&'static str`
... | lay` method returns a `Show`able structure
//let display = path.display();
println!("{}", path.display());
// `join` merges a path with a byte container using the OS specific
// separator, and returns the new path
let new_path = path.join("a").join("b");
// Convert the path into a string slice... | disp | identifier_name |
yaml_object.py |
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governin... |
def BuildObjects(default_class, stream, loader=yaml.loader.SafeLoader):
"""Build objects from stream.
Handles the basic case of loading all the objects from a stream.
Args:
default_class: Class that is instantiated upon the detection of a new
document. An instance of this class will act as the doc... | subject.value.append(value) | conditional_block |
yaml_object.py |
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governin... | (object):
"""Wrapper used for building sequences from a yaml file to a list.
This wrapper is required because objects do not know what property they are
associated with a creation time, and therefore can not be instantiated
with the correct class until they are mapped to their parents.
"""
def __init__(se... | _ObjectSequencer | identifier_name |
yaml_object.py |
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governin... |
def EndMapping(self, top_value, mapping):
"""When leaving scope, makes sure new object is initialized.
This method is mainly for picking up on any missing required attributes.
Args:
top_value: Parent of closing mapping object.
mapping: _ObjectMapper instance that is leaving scope.
"""
... | """New instance of object mapper for opening map scope.
Args:
top_value: Parent of nested object.
Returns:
New instance of object mapper.
"""
result = _ObjectMapper()
# The first map encountered must be mapped directly to the
# main document instance.
if isinstance(top_value, s... | identifier_body |
yaml_object.py |
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governin... |
For a YAML map to be compatible with a class, the class must have a
constructor that can be called with no parameters. If the provided type
does not have such a constructor a parse time error will occur.
"""
def __init__(self, default_class):
"""Initialize validated object builder.
Args:
def... | validated.Type properties. | random_line_split |
views.py | from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from oauth_access.access import OAuthAccess
from oauth_access.exceptions import MissingToken
def oauth_login(request, service,
redirect_field_name="next", redirect_to_sessio... | ctx = RequestContext(request)
access = OAuthAccess(service)
unauth_token = request.session.get("%s_unauth_token" % service, None)
try:
#print "oauth_callback unauth_token = %s" % unauth_token
#print "oauth_callback request.GET = %s" % request.GET
auth_token = access.check_token(u... | return HttpResponseRedirect(access.authorization_url(token))
def oauth_callback(request, service): | random_line_split |
views.py | from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from oauth_access.access import OAuthAccess
from oauth_access.exceptions import MissingToken
def oauth_login(request, service,
redirect_field_name="next", redirect_to_sessio... |
else:
token = None
if hasattr(request, "session"):
request.session[redirect_to_session_key] = request.GET.get(redirect_field_name)
return HttpResponseRedirect(access.authorization_url(token))
def oauth_callback(request, service):
ctx = RequestContext(request)
access = OAuthAccess(... | token = access.unauthorized_token()
request.session["%s_unauth_token" % service] = token.to_string() | conditional_block |
views.py | from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from oauth_access.access import OAuthAccess
from oauth_access.exceptions import MissingToken
def oauth_login(request, service,
redirect_field_name="next", redirect_to_sessio... |
def oauth_callback(request, service):
ctx = RequestContext(request)
access = OAuthAccess(service)
unauth_token = request.session.get("%s_unauth_token" % service, None)
try:
#print "oauth_callback unauth_token = %s" % unauth_token
#print "oauth_callback request.GET = %s" % request.GET
... | access = OAuthAccess(service)
if not service == "facebook":
token = access.unauthorized_token()
request.session["%s_unauth_token" % service] = token.to_string()
else:
token = None
if hasattr(request, "session"):
request.session[redirect_to_session_key] = request.GET.get(redir... | identifier_body |
views.py | from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from oauth_access.access import OAuthAccess
from oauth_access.exceptions import MissingToken
def | (request, service,
redirect_field_name="next", redirect_to_session_key="redirect_to"):
access = OAuthAccess(service)
if not service == "facebook":
token = access.unauthorized_token()
request.session["%s_unauth_token" % service] = token.to_string()
else:
token = None
if ha... | oauth_login | identifier_name |
activity_list_resources.py | # Django specific
from django.db.models import Q
# Tastypie specific
from tastypie import fields
from tastypie.constants import ALL
from tastypie.resources import ModelResource
from tastypie.serializers import Serializer
# Data specific
from iati.models import Activity
from api.v3.resources.helper_resources import Ti... |
def get_list(self, request, **kwargs):
# check if call is cached using validator.is_cached
# check if call contains flush, if it does the call comes from the cache updater and shouldn't return cached results
validator = Validator()
cururl = request.META['PATH_INFO'] + "?" + reques... | base_object_list = super(ActivityListResource, self).apply_filters(request, applicable_filters)
query = request.GET.get('query', None)
filters = {}
if query:
qset = (
Q(id__in=query, **filters) |
Q(activity_recipient_country__country__name__in=query, ... | identifier_body |
activity_list_resources.py | # Django specific
from django.db.models import Q
# Tastypie specific
from tastypie import fields
from tastypie.constants import ALL
from tastypie.resources import ModelResource
from tastypie.serializers import Serializer
# Data specific
from iati.models import Activity
from api.v3.resources.helper_resources import Ti... | :
queryset = Activity.objects.all()
resource_name = 'activity-list'
max_limit = 100
serializer = Serializer(formats=['xml', 'json'])
excludes = ['date_created']
ordering = ['start_actual', 'start_planned', 'end_actual', 'end_planned', 'sectors', 'total_budget']
fi... | Meta | identifier_name |
activity_list_resources.py | # Django specific
from django.db.models import Q
# Tastypie specific
from tastypie import fields
from tastypie.constants import ALL
from tastypie.resources import ModelResource
from tastypie.serializers import Serializer
# Data specific
from iati.models import Activity
from api.v3.resources.helper_resources import Ti... | return super(ActivityListResource, self).get_list(request, **kwargs) | conditional_block | |
activity_list_resources.py | # Django specific
from django.db.models import Q
# Tastypie specific
from tastypie import fields
from tastypie.constants import ALL
from tastypie.resources import ModelResource
from tastypie.serializers import Serializer
# Data specific
from iati.models import Activity
from api.v3.resources.helper_resources import Ti... | return super(ActivityListResource, self).get_list(request, **kwargs) | cururl = request.META['PATH_INFO'] + "?" + request.META['QUERY_STRING']
if not 'flush' in cururl and validator.is_cached(cururl):
return HttpResponse(validator.get_cached_call(cururl), mimetype='application/json')
else: | random_line_split |
services.ts | module app.teacherlists {
'use strict';
interface ITeacherListResourceClass<T> extends ng.resource.IResourceClass<ng.resource.IResource<T>> {
GetStudentList(data: T): T;
}
interface ITeacherRemoveStdResourceClass<T> extends ng.resource.IResourceClass<ng.resource.IResource<T>> {
Remove... | } | .service('app.teacherlists.TeacherListService', TeacherListService); | random_line_split |
services.ts | module app.teacherlists {
'use strict';
interface ITeacherListResourceClass<T> extends ng.resource.IResourceClass<ng.resource.IResource<T>> {
GetStudentList(data: T): T;
}
interface ITeacherRemoveStdResourceClass<T> extends ng.resource.IResourceClass<ng.resource.IResource<T>> {
Remove... | lassRoomId: string): ng.IPromise<any> {
var userId = this.userprofileSvc.GetClientUserProfile().UserProfileId;
return this.GetStudentListsvc.query(new GetStudentListRequest(userId, classRoomId)).$promise;
}
public RemoveStudent(classRoomId: string, removeId: string): ng.IPromise... | tStudentList(c | identifier_name |
services.ts | module app.teacherlists {
'use strict';
interface ITeacherListResourceClass<T> extends ng.resource.IResourceClass<ng.resource.IResource<T>> {
GetStudentList(data: T): T;
}
interface ITeacherRemoveStdResourceClass<T> extends ng.resource.IResourceClass<ng.resource.IResource<T>> {
Remove... | public GetStudentList(classRoomId: string): ng.IPromise<any> {
var userId = this.userprofileSvc.GetClientUserProfile().UserProfileId;
return this.GetStudentListsvc.query(new GetStudentListRequest(userId, classRoomId)).$promise;
}
public RemoveStudent(classRoomId: string,... | this.GetStudentListsvc = <ITeacherListResourceClass<any>>$resource(appConfig.TeacherListUrl, { 'userId': '@userId', 'classRoomId': '@classRoomId' });
this.RemoveStudentsvc = <ITeacherRemoveStdResourceClass<any>>$resource(appConfig.TeacherRemoveStdUrl,
{ 'classRoomId': '@classRoom... | identifier_body |
GraphQLIRVisitor.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
const visit = require('graphql').visit;
import type {
Argument,
Condition,
Directive,... | const NodeKeys = {
Argument: ['value'],
Condition: ['condition', 'selections'],
Directive: ['args'],
Fragment: ['argumentDefinitions', 'directives', 'selections'],
FragmentSpread: ['args', 'directives'],
InlineFragment: ['directives', 'selections'],
LinkedField: ['args', 'directives', 'selections'],
Lit... | ScalarField,
SplitOperation,
Variable,
} from './GraphQLIR';
| random_line_split |
ng-gc-status-code-service.js | (function(){ 'use strict';
'use strict';
angular.module('gc.statusCodeService', [
]).factory('StatusCodeService', [
function StatusCodeServiceFactory() {
var statuses = {
'1': 'info',
'2': 'success',
'3': 'redirect',
'4': 'client-error',
'5': 'server-error'
};
var EMPTY = ... |
var service = {
isError: function isError(statusCode) {
statusCode = safeString(statusCode);
return !!statusCode.match(/^[4-5]\d{2}$/);
},
isSuccess: function isSuccess(statusCode) {
return !service.isError(statusCode);
},
getLabel: function getLabel(statusCod... | {
if (maybeString == null) return '';
return (maybeString).toString();
} | identifier_body |
ng-gc-status-code-service.js | (function(){ 'use strict';
'use strict';
angular.module('gc.statusCodeService', [
]).factory('StatusCodeService', [
function StatusCodeServiceFactory() {
var statuses = {
'1': 'info',
'2': 'success',
'3': 'redirect',
'4': 'client-error',
'5': 'server-error'
};
var EMPTY = ... | (code, status) {
var matcher = new RegExp('^' + code + '\\d{2}$');
return status.match(matcher);
}
function safeString(maybeString) {
if (maybeString == null) return '';
return (maybeString).toString();
}
var service = {
isError: function isError(statusCode) {
sta... | matchStatus | identifier_name |
ng-gc-status-code-service.js | (function(){ 'use strict';
'use strict';
angular.module('gc.statusCodeService', [
]).factory('StatusCodeService', [
function StatusCodeServiceFactory() {
| '3': 'redirect',
'4': 'client-error',
'5': 'server-error'
};
var EMPTY = '';
function matchStatus(code, status) {
var matcher = new RegExp('^' + code + '\\d{2}$');
return status.match(matcher);
}
function safeString(maybeString) {
if (maybeString == null) retur... | var statuses = {
'1': 'info',
'2': 'success', | random_line_split |
build.rs | // build.rs
use std::process::Command;
use std::env;
macro_rules! t {
($e:expr) => (match $e {
Ok(t) => t,
Err(e) => panic!("{} return the error {}", stringify!($e), e),
})
}
fn run(cmd: &mut Command) {
println!("running: {:?}", cmd);
assert!(t!(cmd.status()).success());
}
fn make() ... | () {
let proj_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let out_dir = env::var("OUT_DIR").unwrap();
run(Command::new(make())
.arg("-j4")
.current_dir("3rdparty/FreeImage"));
run(Command::new("cp")
.arg("3rdparty/FreeImage/Dist/libfreeimage.a")
.arg(format!("{}/", ou... | main | identifier_name |
build.rs | // build.rs
use std::process::Command;
use std::env;
macro_rules! t {
($e:expr) => (match $e {
Ok(t) => t,
Err(e) => panic!("{} return the error {}", stringify!($e), e),
})
}
fn run(cmd: &mut Command) {
println!("running: {:?}", cmd);
assert!(t!(cmd.status()).success());
}
fn make() ... |
fn main() {
let proj_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let out_dir = env::var("OUT_DIR").unwrap();
run(Command::new(make())
.arg("-j4")
.current_dir("3rdparty/FreeImage"));
run(Command::new("cp")
.arg("3rdparty/FreeImage/Dist/libfreeimage.a")
.arg(format!(... | {
if cfg!(target_os = "freebsd") {"gmake"} else {"make"}
} | identifier_body |
build.rs | // build.rs
use std::process::Command;
use std::env;
macro_rules! t {
($e:expr) => (match $e {
Ok(t) => t,
Err(e) => panic!("{} return the error {}", stringify!($e), e),
})
}
fn run(cmd: &mut Command) {
println!("running: {:?}", cmd);
assert!(t!(cmd.status()).success());
}
fn make() ... | let out_dir = env::var("OUT_DIR").unwrap();
run(Command::new(make())
.arg("-j4")
.current_dir("3rdparty/FreeImage"));
run(Command::new("cp")
.arg("3rdparty/FreeImage/Dist/libfreeimage.a")
.arg(format!("{}/", out_dir)));
println!("cargo:rustc-link-search=native={}", out_... | if cfg!(target_os = "freebsd") {"gmake"} else {"make"}
}
fn main() {
let proj_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); | random_line_split |
build.rs | // build.rs
use std::process::Command;
use std::env;
macro_rules! t {
($e:expr) => (match $e {
Ok(t) => t,
Err(e) => panic!("{} return the error {}", stringify!($e), e),
})
}
fn run(cmd: &mut Command) {
println!("running: {:?}", cmd);
assert!(t!(cmd.status()).success());
}
fn make() ... |
}
fn main() {
let proj_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let out_dir = env::var("OUT_DIR").unwrap();
run(Command::new(make())
.arg("-j4")
.current_dir("3rdparty/FreeImage"));
run(Command::new("cp")
.arg("3rdparty/FreeImage/Dist/libfreeimage.a")
.arg(format... | {"make"} | conditional_block |
test_package.py | from biokit.rtools import package
import pytest
try:
import create_dummy_package as dun
except:
from . import create_dummy_package as dun
def | ():
d = dun.CreateDummy()
d()
package.install_package('./dummy/dummytest_1.0.0.tar.gz', verbose=True)
d._clean()
def test_install_packages():
package.install_package("truncnorm")
def test_get_r_version():
package.get_R_version()
def test_pm():
pm = package.RPackageManager()
pm.p... | test_install_packages | identifier_name |
test_package.py | from biokit.rtools import package
import pytest
try:
import create_dummy_package as dun
except:
from . import create_dummy_package as dun
def test_install_packages():
d = dun.CreateDummy()
d()
package.install_package('./dummy/dummytest_1.0.0.tar.gz', verbose=True)
d._clean()
def test_instal... | pm.install('truncnorm')
pm.install('truncnorm') # trying again with required version | pm.remove('truncnorm') | random_line_split |
test_package.py | from biokit.rtools import package
import pytest
try:
import create_dummy_package as dun
except:
from . import create_dummy_package as dun
def test_install_packages():
d = dun.CreateDummy()
d()
package.install_package('./dummy/dummytest_1.0.0.tar.gz', verbose=True)
d._clean()
def test_instal... |
def test_get_r_version():
package.get_R_version()
def test_pm():
pm = package.RPackageManager()
pm.packages
pm.installed
pm.available
pm.get_package_version('base')
try:
pm.get_package_version('whatever_is_not_installed')
assert False
except:
assert True
... | package.install_package("truncnorm") | identifier_body |
make.js | import getDevTool from './devtool'
import getTarget from './target'
import getEntry from './entry'
import getOutput from './output'
import getResolve from './resolve'
import getResolveLoader from './resolveLoader'
import getModule from './module'
import getExternals from './externals'
import getPlugins from './... | , output: getOutput(name)
, resolve: getResolve(name)
, resolveLoader: getResolveLoader(name)
, module: getModule(name)
, externals: getExternals(name)
, plugins: getPlugins(name)
, node: getNode(name)
, postcss: getPostcss(name)
... | , cache: true
, target: getTarget(name)
, devtool: getDevTool(name)
, entry: getEntry(name)
| random_line_split |
make.js | import getDevTool from './devtool'
import getTarget from './target'
import getEntry from './entry'
import getOutput from './output'
import getResolve from './resolve'
import getResolveLoader from './resolveLoader'
import getModule from './module'
import getExternals from './externals'
import getPlugins from './... | {
if(typeof name !== 'string')
throw new Error('Name is required.')
return { name
, context: __dirname
, cache: true
, target: getTarget(name)
, devtool: getDevTool(name)
, entry: getEntry(name)
, output: getOutput(name)
, resolve... | identifier_body | |
make.js | import getDevTool from './devtool'
import getTarget from './target'
import getEntry from './entry'
import getOutput from './output'
import getResolve from './resolve'
import getResolveLoader from './resolveLoader'
import getModule from './module'
import getExternals from './externals'
import getPlugins from './... | (name) {
if(typeof name !== 'string')
throw new Error('Name is required.')
return { name
, context: __dirname
, cache: true
, target: getTarget(name)
, devtool: getDevTool(name)
, entry: getEntry(name)
, output: getOutput(name)
, ... | make | identifier_name |
leaflet-freehandshapes-tests.ts | import * as L from 'leaflet';
import * as geojson from 'geojson';
const map = new L.Map('#id');
const layer = new L.Layer();
const polygonOptions: L.PolylineOptions = {
color: '#FFFFFF',
weight: 2,
opacity: 0.75,
fillColor: '#000000'
};
const polylineOptions: L.PolylineOptions = {
smoothFactor: 1... | concave_polygons: undefined
};
const leafletMouseEvent: L.LeafletMouseEvent = {} as unknown as L.LeafletMouseEvent;
const simplePolygonLatLngs: L.LatLngExpression[] = [[37, -109.05], [41, -109.03], [41, -102.05], [37, -102.04]];
const polygon = new L.Polygon(simplePolygonLatLngs);
polygon.getGroup();
polygon.dest... | const freehandOptions: L.FreeHandShapesOptions = {
polygon: polygonOptions,
polyline: polylineOptions,
simplify_tolerance: 0.01,
merge_polygons: false, | random_line_split |
field_image.js | /**
* @license
* Visual Blocks Editor
*
* Copyright 2012 Google Inc.
* https://developers.google.com/blockly/
*
* 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.apach... | Blockly.FieldImage.prototype.EDITABLE = false;
/**
* Install this image on a block.
*/
Blockly.FieldImage.prototype.init = function() {
if (this.fieldGroup_) {
// Image has already been initialized once.
return;
}
// Build the DOM.
/** @type {SVGElement} */
this.fieldGroup_ = Blockly.utils.createSv... | /**
* Editable fields are saved by the XML renderer, non-editable fields are not.
*/ | random_line_split |
field_image.js | /**
* @license
* Visual Blocks Editor
*
* Copyright 2012 Google Inc.
* https://developers.google.com/blockly/
*
* 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.apach... |
/** @type {SVGElement} */
this.imageElement_ = Blockly.utils.createSvgElement(
'image',
{
'height': this.height_ + 'px',
'width': this.width_ + 'px'
},
this.fieldGroup_);
this.setValue(this.src_);
this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_);
// Config... | {
this.fieldGroup_.style.display = 'none';
} | conditional_block |
admin.py | __author__ = 'thatcher'
from django.contrib import admin
# from django.contrib.auth.models import User
# from django.contrib.auth.admin import UserAdmin
# from django.contrib.sessions.
from django.contrib.sessions.models import Session
from .models import *
from base.forms import *
def images_thubmnail(self):
ret... |
admin.site.register(Event, EventAdmin)
class PostAdmin(admin.ModelAdmin):
model = GenericPost
list_display = ['title', 'category', 'publication_date']
admin.site.register(GenericPost, PostAdmin)
class CategoryAdmin(admin.ModelAdmin):
model = PostCategory
list_display = ['name', 'added_date']
admin.si... | model = Event
list_display = ['title', 'location', 'date_and_time'] | identifier_body |
admin.py | __author__ = 'thatcher'
from django.contrib import admin
# from django.contrib.auth.models import User
# from django.contrib.auth.admin import UserAdmin
# from django.contrib.sessions.
from django.contrib.sessions.models import Session
from .models import *
from base.forms import *
def | (self):
return '<img style="max-height: 80px; width: auto;" src="{}" alt="{}" >'.format(self.uri(), self.alt)
# return self.uri()
images_thubmnail.short_description = 'Thumbnail'
images_thubmnail.allow_tags = True
class TeamMemberAdmin(admin.ModelAdmin):
model = TeamMember
list_display = ['full_name', 's... | images_thubmnail | identifier_name |
admin.py | __author__ = 'thatcher'
from django.contrib import admin
# from django.contrib.auth.models import User
# from django.contrib.auth.admin import UserAdmin
# from django.contrib.sessions.
from django.contrib.sessions.models import Session
from .models import *
from base.forms import *
def images_thubmnail(self):
ret... | list_display = ['name', 'added_date']
admin.site.register(Tag, TagAdmin) | class TagAdmin(admin.ModelAdmin):
model = Tag | random_line_split |
delete.rs | // Copyright (c) 2016-2018 Chef Software Inc. and/or applicable contributors
//
// 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
//
// Unl... | .map_err(Error::DepotClient)?;
ui.status(Status::Deleted, format!("secret {}.", key))?;
Ok(())
} | depot_client
.delete_origin_secret(origin, token, key) | random_line_split |
delete.rs | // Copyright (c) 2016-2018 Chef Software Inc. and/or applicable contributors
//
// 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
//
// Unl... | {
let depot_client =
DepotClient::new(bldr_url, PRODUCT, VERSION, None).map_err(Error::DepotClient)?;
ui.status(Status::Deleting, format!("secret {}.", key))?;
depot_client
.delete_origin_secret(origin, token, key)
.map_err(Error::DepotClient)?;
ui.status(Status::Deleted, form... | identifier_body | |
delete.rs | // Copyright (c) 2016-2018 Chef Software Inc. and/or applicable contributors
//
// 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
//
// Unl... | (ui: &mut UI, bldr_url: &str, token: &str, origin: &str, key: &str) -> Result<()> {
let depot_client =
DepotClient::new(bldr_url, PRODUCT, VERSION, None).map_err(Error::DepotClient)?;
ui.status(Status::Deleting, format!("secret {}.", key))?;
depot_client
.delete_origin_secret(origin, token... | start | identifier_name |
rn.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# rn.py - load network of routes from OSM
#
# Copyright (C) 2012, Stefan Schramm <mail@stefanschramm.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Fou... |
def get_sortkey(self, relation):
rid, tags, members = relation
key = ""
if "route_master" in tags:
key += tags["route_master"]
elif "route" in tags:
key += tags["route"]
key += "_"
if "ref" in tags:
ref = tags["ref"]
for number in set(re.findall("[0-9]+", ref)):
# append a lot of leading ... | for node in nodes:
nid, tags, coords = node
if nid in self.nodes and self.nodes[nid] == None:
self.nodes[nid] = node | identifier_body |
rn.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# rn.py - load network of routes from OSM
#
# Copyright (C) 2012, Stefan Schramm <mail@stefanschramm.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Fou... | (self, pbf, filterfunction=lambda r: True):
# read data of public transport network
# required for validating and displaying
self.relation_filter = filterfunction
# get modification time of data source
# TODO: how to determine time when reading from multiple sources?
self.mtime = datetime.datetime.fromti... | load_network | identifier_name |
rn.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# rn.py - load network of routes from OSM
#
# Copyright (C) 2012, Stefan Schramm <mail@stefanschramm.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Fou... |
def nodes_cb(self, nodes):
# callback: collect interesting nodes
for node in nodes:
nid, tags, coords = node
if nid in self.nodes and self.nodes[nid] == None:
self.nodes[nid] = node
def get_sortkey(self, relation):
rid, tags, members = relation
key = ""
if "route_master" in tags:
key += tags... | wid, tags, nodes = way
if wid in self.ways and self.ways[wid] == None:
self.ways[wid] = way
for nid in nodes:
self.nodes[nid] = None | conditional_block |
rn.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# rn.py - load network of routes from OSM | #
# Copyright (C) 2012, Stefan Schramm <mail@stefanschramm.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Th... | random_line_split | |
ao_memory.py | #!/usr/bin/env python
"""
Copyright (c) 2004-Present Pivotal Software, Inc.
This program and the accompanying materials are made available under
the terms of the 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... | gpfaultinjector.run()
res ={'rc':0, 'stdout':'', 'stderr':''}
PSQL.run_sql_command(sql_cmd='select count(*) from ao_read_malloc', results=res)
logger.info(res)
self.assertTrue("ERROR: fault triggered" in res['stderr'])
self.assertFalse("ERROR: could not temporarily connect to one or more segments" in r... | def tearDown(self):
gpfaultinjector = Command('fault injector',
'source $GPHOME/greenplum_path.sh; '
'gpfaultinjector -f malloc_failure '
'-y reset -H ALL -r primary')
gpfaultinjector.run()
def test_ao_m... | identifier_body |
ao_memory.py | #!/usr/bin/env python
"""
Copyright (c) 2004-Present Pivotal Software, Inc.
This program and the accompanying materials are made available under
the terms of the 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... |
gpfaultinjector = Command('fault injector',
'source $GPHOME/greenplum_path.sh; '
'gpfaultinjector -f malloc_failure '
'-y error -H ALL -r primary')
gpfaultinjector.run()
res ={'rc':0, 'stdout':'', 'stderr':... | PSQL.run_sql_command('insert into ao_read_malloc '
'select * from generate_series(1, 1000)') | random_line_split |
ao_memory.py | #!/usr/bin/env python
"""
Copyright (c) 2004-Present Pivotal Software, Inc.
This program and the accompanying materials are made available under
the terms of the 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... | (self):
"""
@product_version gpdb: [4.3.5.1 -]
"""
PSQL.run_sql_command('DROP table if exists ao_read_malloc')
PSQL.run_sql_command('create table ao_read_malloc (a int) with (appendonly=true, compresstype=quicklz)')
PSQL.run_sql_command('insert into ao_read_malloc '
... | test_ao_malloc_failure | identifier_name |
corrmm.py | """
GpuCorrMM-based convolutional layers
"""
import theano
from .. import init
from .. import nonlinearities
from .base import Layer
from .conv import conv_output_length
from theano.sandbox.cuda.basic_ops import gpu_contiguous
from theano.sandbox.cuda.blas import GpuCorrMM
__all__ = [
"MMLayer",
"Conv2DM... |
def get_output_for(self, input, **kwargs):
filters = self.W
if self.flip_filters:
filters = filters[:, :, ::-1, ::-1] # flip top-down, left-right
contiguous_filters = gpu_contiguous(filters)
contiguous_input = gpu_contiguous(input)
conved = self.corr_mm_op(con... | batch_size = input_shape[0]
output_rows = conv_output_length(input_shape[2],
self.filter_size[0],
self.strides[0],
'pad', self.pad[0])
output_columns = conv_output_length(input_sh... | identifier_body |
corrmm.py | """
GpuCorrMM-based convolutional layers
"""
import theano
from .. import init
from .. import nonlinearities
from .base import Layer
from .conv import conv_output_length
from theano.sandbox.cuda.basic_ops import gpu_contiguous
from theano.sandbox.cuda.blas import GpuCorrMM
__all__ = [
"MMLayer",
"Conv2DM... | def get_params(self):
return [self.W] + self.get_bias_params()
def get_bias_params(self):
return [self.b] if self.b is not None else []
def get_output_shape_for(self, input_shape):
batch_size = input_shape[0]
output_rows = conv_output_length(input_shape[2],
... | random_line_split | |
corrmm.py | """
GpuCorrMM-based convolutional layers
"""
import theano
from .. import init
from .. import nonlinearities
from .base import Layer
from .conv import conv_output_length
from theano.sandbox.cuda.basic_ops import gpu_contiguous
from theano.sandbox.cuda.blas import GpuCorrMM
__all__ = [
"MMLayer",
"Conv2DM... |
self.W = self.create_param(W, self.get_W_shape(), name="W")
if b is None:
self.b = None
elif self.untie_biases:
output_shape = self.get_output_shape()
self.b = self.create_param(b, (num_filters, output_shape[2],
out... | self.pad = pad | conditional_block |
corrmm.py | """
GpuCorrMM-based convolutional layers
"""
import theano
from .. import init
from .. import nonlinearities
from .base import Layer
from .conv import conv_output_length
from theano.sandbox.cuda.basic_ops import gpu_contiguous
from theano.sandbox.cuda.blas import GpuCorrMM
__all__ = [
"MMLayer",
"Conv2DM... | (self):
return [self.W] + self.get_bias_params()
def get_bias_params(self):
return [self.b] if self.b is not None else []
def get_output_shape_for(self, input_shape):
batch_size = input_shape[0]
output_rows = conv_output_length(input_shape[2],
... | get_params | identifier_name |
index.js | // External Dependencies
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
| import { track } from '../../util/analytics';
import * as BooksAPI from '../../BooksAPI';
import { getSuggetions } from '../../util/search';
// Our Components
import BookList from '../BookList';
export default class Search extends Component {
static propTypes = {
onBackClick: PropTypes.func.isRequired,
isFe... | // Our Dependencies | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.