file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
netio.js | var etc=require("./etc.js"),
msgtype=require("./msgtype.js");
function constructMessage(type,args){
var len=6+args.map(function(a){return 4+a.length;}).reduce(function(a,b){return a+b;},0);
var buf=new Buffer(len);
//console.log("constructing message with len",len)
buf.writeUInt32BE(len,0);
buf.writeUInt8(typ... | (buf){
var buflen=buf.length;
if(buflen<4)return false;
var len=buf.readUInt32BE(0);
if(buflen<len)return false;
console.log(buf.slice(0,len));
var type=buf.readUInt8(4);
var numargs=buf.readUInt8(5);
var cursor=6;
var args=new Array(numargs),arglen;
for(var i=0;i<numargs;i++){
//console.log("pM: i="+i);
... | parseMessage | identifier_name |
netio.js | var etc=require("./etc.js"),
msgtype=require("./msgtype.js");
function constructMessage(type,args){
var len=6+args.map(function(a){return 4+a.length;}).reduce(function(a,b){return a+b;},0);
var buf=new Buffer(len); | var cursor=6;
for(var i=0;i<args.length;i++){
if(!(args[i] instanceof Buffer))args[i]=new Buffer(""+args[i]);
buf.writeUInt32BE(args[i].length,cursor);
cursor+=4;
args[i].copy(buf,cursor);
cursor+=args[i].length;
}
//console.log("constructing message with len",len,"result:",buf);
return buf;
}
function ... | //console.log("constructing message with len",len)
buf.writeUInt32BE(len,0);
buf.writeUInt8(type,4);
buf.writeUInt8(args.length,5); | random_line_split |
netio.js | var etc=require("./etc.js"),
msgtype=require("./msgtype.js");
function constructMessage(type,args) |
function parseMessage(buf){
var buflen=buf.length;
if(buflen<4)return false;
var len=buf.readUInt32BE(0);
if(buflen<len)return false;
console.log(buf.slice(0,len));
var type=buf.readUInt8(4);
var numargs=buf.readUInt8(5);
var cursor=6;
var args=new Array(numargs),arglen;
for(var i=0;i<numargs;i++){
//cons... | {
var len=6+args.map(function(a){return 4+a.length;}).reduce(function(a,b){return a+b;},0);
var buf=new Buffer(len);
//console.log("constructing message with len",len)
buf.writeUInt32BE(len,0);
buf.writeUInt8(type,4);
buf.writeUInt8(args.length,5);
var cursor=6;
for(var i=0;i<args.length;i++){
if(!(args[i] in... | identifier_body |
create-connection-pool.mock.ts | export const request = {
"headers": {
"Content-Type": "application/json",
},
"body": {
"name": "backend-pool",
"mode": "transaction",
"size": 10,
"db": "defaultdb",
"user": "doadmin"
},
};
export const response = {
"body": {
"pool": {
"user": "doadmin",
"name": ... | "status": 200,
"ratelimit-limit": 1200,
"ratelimit-remaining": 1137,
"ratelimit-reset": 1415984218
},
}; | "headers": {
"content-type": "application/json; charset=utf-8", | random_line_split |
NOEtools.py | # Copyright 2004 by Bob Bussell. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""NOEtools: For predicting NOE coordinates from assignment data.
The input and output are model... | (peaklist, originNuc, detectedNuc, originResNum, toResNum):
"""Predict the i->j NOE position based on self peak (diagonal) assignments
Parameters
----------
peaklist : xprtools.Peaklist
List of peaks from which to derive predictions
originNuc : str
Name of originating nucleus.
o... | predictNOE | identifier_name |
NOEtools.py | # Copyright 2004 by Bob Bussell. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""NOEtools: For predicting NOE coordinates from assignment data.
The input and output are model... | Name of detected nucleus.
toResNum : int
Index of detected residue.
Returns
-------
returnLine : str
The .xpk file entry for the predicted crosspeak.
Examples
--------
Using predictNOE(peaklist,"N15","H1",10,12)
where peaklist is of the type xpktools.peaklist
... | originNuc : str
Name of originating nucleus.
originResNum : int
Index of originating residue.
detectedNuc : str | random_line_split |
NOEtools.py | # Copyright 2004 by Bob Bussell. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""NOEtools: For predicting NOE coordinates from assignment data.
The input and output are model... |
def _data_map(labelline):
# Generate a map between datalabels and column number
# based on a labelline
i = 0 # A counter
datamap = {} # The data map dictionary
labelList = labelline.split() # Get the label line
# Get the column number for each label
for i in range(len(labelList)):
... | """Predict the i->j NOE position based on self peak (diagonal) assignments
Parameters
----------
peaklist : xprtools.Peaklist
List of peaks from which to derive predictions
originNuc : str
Name of originating nucleus.
originResNum : int
Index of originating residue.
dete... | identifier_body |
NOEtools.py | # Copyright 2004 by Bob Bussell. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""NOEtools: For predicting NOE coordinates from assignment data.
The input and output are model... |
returnLine = xpktools.replace_entry(returnLine, originAssCol + 1, originAss)
returnLine = xpktools.replace_entry(returnLine, originPPMCol + 1, aveOriginPPM)
return returnLine
def _data_map(labelline):
# Generate a map between datalabels and column number
# based on a labelline
i =... | aveDetectedPPM = _col_ave(detectedList, detectedPPMCol)
aveOriginPPM = _col_ave(originList, originPPMCol)
originAss = originList[0].split()[originAssCol] | conditional_block |
upload-service.ts | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { EmptyObservable } from 'rxjs/observable/EmptyObservable';
import { Entry } from '../models/entry'; | import { ImsHeaders } from '../models/ims-headers';
import { Token } from '../models/token';
import { AuthService } from './auth-service';
import { ContainerUploadService } from './container-upload-service';
import { ImsService } from './ims-service';
import { TokenService } from './token-service';
@Injectable()
expor... | import { Image } from '../models/image'; | random_line_split |
upload-service.ts | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { EmptyObservable } from 'rxjs/observable/EmptyObservable';
import { Entry } from '../models/entry';
... | (url: string, token: Token, imageEntry: Entry): Observable<Response> {
return this.http.post(url, imageEntry.json(), { headers: new ImsHeaders(this.authService.currentCredential, token) });
}
}
| createImageEntry | identifier_name |
upload-service.ts | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { EmptyObservable } from 'rxjs/observable/EmptyObservable';
import { Entry } from '../models/entry';
... |
public uploadImages(filterId: number, imageEntry: Entry, images: Image[]): Observable<Response> {
let observables: Observable<Response> = new EmptyObservable();
for (const image of images) {
observables = Observable.concat(observables, this.uploadImage(this.authService.filterId, imageEntry, image));
... | { } | identifier_body |
model_support.py | from cuescience_shop.models import Client, Address, Order
from natspec_utils.decorators import TextSyntax
from cart.cart import Cart
from django.test.client import Client as TestClient
class ClientTestSupport(object):
def __init__(self, test_case):
self.test_case = test_case
self.client = TestClie... | @TextSyntax("Create order", types=["Client"], return_type="Order")
def create_order(self, client):
cart = Cart(self.client)
cart.create_cart()
cart = cart.cart
order = Order(client=client, cart=cart)
order.save()
return order
@TextSyntax("Assert client nu... | def create_client(self, first_name, last_name, address):
client = Client(first_name=first_name, last_name=last_name, shipping_address=address, billing_address=address)
client.save()
return client
| random_line_split |
model_support.py | from cuescience_shop.models import Client, Address, Order
from natspec_utils.decorators import TextSyntax
from cart.cart import Cart
from django.test.client import Client as TestClient
class ClientTestSupport(object):
def __init__(self, test_case):
self.test_case = test_case
self.client = TestClie... | (self, order_number, order):
self.test_case.assertEqual(order_number, order.order_number)
| assert_order_number | identifier_name |
model_support.py | from cuescience_shop.models import Client, Address, Order
from natspec_utils.decorators import TextSyntax
from cart.cart import Cart
from django.test.client import Client as TestClient
class ClientTestSupport(object):
def __init__(self, test_case):
self.test_case = test_case
self.client = TestClie... |
@TextSyntax("Create order", types=["Client"], return_type="Order")
def create_order(self, client):
cart = Cart(self.client)
cart.create_cart()
cart = cart.cart
order = Order(client=client, cart=cart)
order.save()
return order
@TextSyntax("Assert cli... | client = Client(first_name=first_name, last_name=last_name, shipping_address=address, billing_address=address)
client.save()
return client | identifier_body |
Animator.js | /*
This file is part of Ext JS 4.2
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
Commercial Usage
Licensees holding valid commercial licenses may use this file in accordance with the Commercial
Software License Agreement provided with the Software or, alternatively, in accordance with th... | * is considered '100%'.<b>Every keyframe declaration must have a keyframe rule for 0% and 100%, possibly defined using
* "from" or "to"</b>. A keyframe declaration without these keyframe selectors is invalid and will not be available for
* animation. The keyframe declaration for a keyframe rule cons... | random_line_split | |
Animator.js | /*
This file is part of Ext JS 4.2
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
Commercial Usage
Licensees holding valid commercial licenses may use this file in accordance with the Commercial
Software License Agreement provided with the Software or, alternatively, in accordance with th... |
else {
// Compensate for frame delay;
startTime = new Date(delayStart.getTime() + delay);
}
}
}
if (me.fireEvent('beforeanimate', me) !== false) {
me.startTime = startTime;
me.running = true;
... | {
return;
} | conditional_block |
Two arrays.py | """
ou are given two integer arrays, A and B, each containing N integers. The size of the array is less than or equal to
1000. You are free to permute the order of the elements in the arrays.
Now here's the real question: Is there an permutation A', B' possible of A and B, such that, A'i+B'i >= K for all i,
where A'i ... | import sys
f = open("1.in", "r")
# f = sys.stdin
testcases = int(f.readline().strip())
for t in xrange(testcases):
# construct cipher
N, K = map(int, f.readline().strip().split(" "))
A = map(int, f.readline().strip().split(' '))
B = map(int, f.readline().strip().split('... | conditional_block | |
Two arrays.py | Now here's the real question: Is there an permutation A', B' possible of A and B, such that, A'i+B'i >= K for all i,
where A'i denotes the ith element in the array A' and B'i denotes ith element in the array B'.
Input Format
The first line contains an integer, T, the number of test-cases. T test cases follow. Each te... | """
ou are given two integer arrays, A and B, each containing N integers. The size of the array is less than or equal to
1000. You are free to permute the order of the elements in the arrays.
| random_line_split | |
Two arrays.py | """
ou are given two integer arrays, A and B, each containing N integers. The size of the array is less than or equal to
1000. You are free to permute the order of the elements in the arrays.
Now here's the real question: Is there an permutation A', B' possible of A and B, such that, A'i+B'i >= K for all i,
where A'i ... | (self, cipher):
"""
main solution function
:param cipher: the cipher
"""
N, K, A, B = cipher
A.sort()
B.sort(reverse=True) # dynamic typed, then cannot detect list()
for i in xrange(N):
if not A[i] + B[i] >= K:
return "NO"
... | solve | identifier_name |
Two arrays.py | """
ou are given two integer arrays, A and B, each containing N integers. The size of the array is less than or equal to
1000. You are free to permute the order of the elements in the arrays.
Now here's the real question: Is there an permutation A', B' possible of A and B, such that, A'i+B'i >= K for all i,
where A'i ... |
if __name__ == "__main__":
import sys
f = open("1.in", "r")
# f = sys.stdin
testcases = int(f.readline().strip())
for t in xrange(testcases):
# construct cipher
N, K = map(int, f.readline().strip().split(" "))
A = map(int, f.readline().strip().split(' '))
B = map... | """
main solution function
:param cipher: the cipher
"""
N, K, A, B = cipher
A.sort()
B.sort(reverse=True) # dynamic typed, then cannot detect list()
for i in xrange(N):
if not A[i] + B[i] >= K:
return "NO"
return "YES" | identifier_body |
StringSpecialization.ts | /**
* Based on taint analysis, could check how input strings are used,
* and inform the search about it
*/
export enum StringSpecialization {
/**
* String used as a Date with unknown format
*/
DATE_FORMAT_UNKNOWN_PATTERN = "DATE_FORMAT_UNKNOWN_PATTERN",
/**
* String used as a Date with n... | /**
* String parsed to long
*/
LONG = "LONG",
/**
* String parsed to boolean
*/
BOOLEAN = "BOOLEAN",
/**
* String parsed to float
*/
FLOAT = "FLOAT",
/**
* String should be equal to another string variable,
* ie 2 (or more) different variables sho... | random_line_split | |
tests.js | 'use strict';
var helpers = require('opent2t-testcase-helpers');
var uuidRegExMatch = /[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i;
function runTranslatorTests(settings) {
helpers.updateSettings(settings);
var test = settings.test;
var opent2t = settings.opent2t;
var SchemaName = settings.s... | t.true(Array.isArray(resource.if), `Resource ${i},${j} requires an array of interfaces (if)`);
t.true(resource.if.length > 0, `Resource ${i},${j} requires an array of interfaces (if)`);
// Check for oic.if.a XOR oic.if.s
t.... | t.true(resource.rt.length > 0, `Resource ${i},${j} requires an array of schemas (rt)`);
t.truthy(resource.if, `Resource ${i},${j} requires an array of interfaces (if)`); | random_line_split |
tests.js | 'use strict';
var helpers = require('opent2t-testcase-helpers');
var uuidRegExMatch = /[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i;
function runTranslatorTests(settings) {
helpers.updateSettings(settings);
var test = settings.test;
var opent2t = settings.opent2t;
var SchemaName = settings.s... |
t.snapshot(response);
});
});
});
test.serial('GetPlatformExpanded', t => {
return helpers.runTest(settings, t, () => {
return opent2t.invokeMethodAsync(translator, SchemaName, 'get', [true])
.then((response) => {
// ... | {
let entity = response.entities[i];
t.truthy(entity.icv, `Entity ${i} requires a core version (icv)`);
t.truthy(entity.dmv, `Entity ${i} requires a device model version (dmv)`);
t.truthy(entity.n, `Entity ${i} requires a friendly name (n)`... | conditional_block |
tests.js | 'use strict';
var helpers = require('opent2t-testcase-helpers');
var uuidRegExMatch = /[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i;
function runTranslatorTests(settings) |
module.exports = runTranslatorTests; | {
helpers.updateSettings(settings);
var test = settings.test;
var opent2t = settings.opent2t;
var SchemaName = settings.schemaName;
var deviceId = settings.deviceId;
var translator;
test.before(() => {
return opent2t.createTranslatorAsync(settings.translatorPath, 'thingTranslator', setti... | identifier_body |
tests.js | 'use strict';
var helpers = require('opent2t-testcase-helpers');
var uuidRegExMatch = /[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i;
function | (settings) {
helpers.updateSettings(settings);
var test = settings.test;
var opent2t = settings.opent2t;
var SchemaName = settings.schemaName;
var deviceId = settings.deviceId;
var translator;
test.before(() => {
return opent2t.createTranslatorAsync(settings.translatorPath, 'thingTransla... | runTranslatorTests | identifier_name |
_state-storage.service.ts | <%#
Copyright 2013-2017 the original author or authors from the StackStack project.
This file is part of the StackStack project, see http://www.jhipster.tech/
for more information.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Yo... | }
storeDestinationState(destinationState, destinationStateParams, fromState) {
const destinationInfo = {
'destination': {
'name': destinationState.name,
'data': destinationState.data,
},
'params': destinationStateParams,
'f... | random_line_split | |
_state-storage.service.ts | <%#
Copyright 2013-2017 the original author or authors from the StackStack project.
This file is part of the StackStack project, see http://www.jhipster.tech/
for more information.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Yo... | () {
return this.$sessionStorage.retrieve('destinationState');
}
storeUrl(url: string) {
this.$sessionStorage.store('previousUrl', url);
}
getUrl() {
return this.$sessionStorage.retrieve('previousUrl');
}
storeDestinationState(destinationState, destinationStateParams, ... | getDestinationState | identifier_name |
_state-storage.service.ts | <%#
Copyright 2013-2017 the original author or authors from the StackStack project.
This file is part of the StackStack project, see http://www.jhipster.tech/
for more information.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Yo... |
storeUrl(url: string) {
this.$sessionStorage.store('previousUrl', url);
}
getUrl() {
return this.$sessionStorage.retrieve('previousUrl');
}
storeDestinationState(destinationState, destinationStateParams, fromState) {
const destinationInfo = {
'destination': {
... | {
return this.$sessionStorage.retrieve('destinationState');
} | identifier_body |
jsonInterfaces.ts | // The current version of this file can be retrieved by:
// GET /api/language/webast
module TDev.AST.Json
{
// This module describes an AST for TouchDevelop scripts. The documentation
// is severely lacking, so the best way to figure things out is to write a
// TouchDevelop script, and type (in the console... |
// This corresponds to the [operator] syntactic class defined in the
// OOPSLA'15 submission. When adopting the "hybrid AST" point of view,
// an expression is decomposed as a series of tokens. The [JOperator]
// interface covers operators (assignment, comparison, boolean and
// arithmetic operator... | /*abstract*/ export interface JExpr extends JToken { } | random_line_split |
util.py | from __future__ import absolute_import, division, print_function
import contextlib
import os
import platform
import socket
import sys
import textwrap
from tornado.testing import bind_unused_port
# Delegate the choice of unittest or unittest2 to tornado.testing.
from tornado.testing import unittest
skipIfNonUnix = u... | ():
"""Return whether coverage is currently running.
"""
if 'coverage' not in sys.modules:
return False
tracer = sys.gettrace()
if tracer is None:
return False
try:
mod = tracer.__module__
except AttributeError:
try:
mod = tracer.__class__.__module... | is_coverage_running | identifier_name |
util.py | from __future__ import absolute_import, division, print_function
import contextlib
import os
import platform
import socket
import sys
import textwrap
from tornado.testing import bind_unused_port
# Delegate the choice of unittest or unittest2 to tornado.testing.
from tornado.testing import unittest
skipIfNonUnix = u... |
def subTest(test, *args, **kwargs):
"""Compatibility shim for unittest.TestCase.subTest.
Usage: ``with tornado.test.util.subTest(self, x=x):``
"""
try:
subTest = test.subTest # py34+
except AttributeError:
subTest = contextlib.contextmanager(lambda *a, **kw: (yield))
return ... | """Return whether coverage is currently running.
"""
if 'coverage' not in sys.modules:
return False
tracer = sys.gettrace()
if tracer is None:
return False
try:
mod = tracer.__module__
except AttributeError:
try:
mod = tracer.__class__.__module__
... | identifier_body |
util.py | from __future__ import absolute_import, division, print_function
import contextlib
import os
import platform
import socket
import sys
import textwrap
from tornado.testing import bind_unused_port
# Delegate the choice of unittest or unittest2 to tornado.testing.
from tornado.testing import unittest
skipIfNonUnix = u... | sock = socket.socket(socket.AF_INET6)
sock.bind(('::1', 0))
except socket.error:
return False
finally:
if sock is not None:
sock.close()
return True
skipIfNoIPv6 = unittest.skipIf(not _detect_ipv6(), 'ipv6 support not present')
def refusing_port():
"""Retur... | # time. It's usually true even when ipv6 doesn't work for other reasons.
return False
sock = None
try: | random_line_split |
util.py | from __future__ import absolute_import, division, print_function
import contextlib
import os
import platform
import socket
import sys
import textwrap
from tornado.testing import bind_unused_port
# Delegate the choice of unittest or unittest2 to tornado.testing.
from tornado.testing import unittest
skipIfNonUnix = u... |
tracer = sys.gettrace()
if tracer is None:
return False
try:
mod = tracer.__module__
except AttributeError:
try:
mod = tracer.__class__.__module__
except AttributeError:
return False
return mod.startswith('coverage')
def subTest(test, *args,... | return False | conditional_block |
driver_decl.py | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015-2018 by Exopy Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# ---------------... | (self):
"""Identify the decl by its members.
"""
members = ('driver', 'architecture', 'manufacturer', 'serie', 'model',
'kind', 'starter', 'connections', 'settings')
st = '{} whose known members are :\n{}'
st_m = '\n'.join(' - {} : {}'.format(m, v)
... | __str__ | identifier_name |
driver_decl.py | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015-2018 by Exopy Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# ---------------... |
class Drivers(GroupDeclarator):
"""Declarator to group driver declarations.
For the full documentation of the members values please the Driver class.
"""
#: Name identifying the system the driver is built on top of for the
#: declared children.
architecture = d_(Str())
#: Instrument ma... | """Create the unique identifier of the driver using the top level
package the architecture and the class name.
"""
if ':' in self.driver:
path = self.get_path()
d_path, d = (path + '.' + self.driver
if path else self.driver).split(':')
... | identifier_body |
driver_decl.py | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015-2018 by Exopy Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# ---------------... | path = self.get_path()
try:
d_path, driver = (path + '.' + self.driver
if path else self.driver).split(':')
except ValueError:
msg = 'Incorrect %s (%s), path must be of the form a.b.c:Class'
traceback[driver_id] = msg % (driver_id... | return
# Determine the path to the driver. | random_line_split |
driver_decl.py | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015-2018 by Exopy Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# ---------------... |
try:
infos.cls = d_cls
except TypeError:
msg = '{} should be a callable.\n{}'
traceback[driver_id] = msg.format(d_cls, format_exc())
return
collector.contributions[driver_id] = infos
self.is_registered = True
def unregister(self, c... | return | conditional_block |
http-driver.ts | import xs, {Stream, MemoryStream} from 'xstream';
import {Driver} from '@cycle/run';
import {adapt} from '@cycle/run/lib/adapt';
import {MainHTTPSource} from './MainHTTPSource';
import * as superagent from 'superagent';
import {
HTTPSource,
ResponseStream,
RequestOptions,
RequestInput,
Response,
} from './int... |
export function optionsToSuperagent(rawReqOptions: RequestOptions) {
const reqOptions = preprocessReqOptions(rawReqOptions);
if (typeof reqOptions.url !== `string`) {
throw new Error(
`Please provide a \`url\` property in the request options.`
);
}
const lowerCaseMethod = (reqOptions.method || '... | {
reqOptions.withCredentials = reqOptions.withCredentials || false;
reqOptions.redirects =
typeof reqOptions.redirects === 'number' ? reqOptions.redirects : 5;
reqOptions.method = reqOptions.method || `get`;
return reqOptions;
} | identifier_body |
http-driver.ts | import xs, {Stream, MemoryStream} from 'xstream';
import {Driver} from '@cycle/run';
import {adapt} from '@cycle/run/lib/adapt';
import {MainHTTPSource} from './MainHTTPSource';
import * as superagent from 'superagent';
import {
HTTPSource,
ResponseStream,
RequestOptions,
RequestInput,
Response,
} from './int... |
response$ = adapt(response$);
Object.defineProperty(response$, 'request', {
value: reqOptions,
writable: false,
});
return response$ as ResponseMemoryStream;
}
export function makeHTTPDriver(): Driver<Stream<RequestInput>, HTTPSource> {
function httpDriver(
request$: Stream<RequestInput>,
na... | {
response$.addListener({
next: () => {},
error: () => {},
complete: () => {},
});
} | conditional_block |
http-driver.ts | import xs, {Stream, MemoryStream} from 'xstream';
import {Driver} from '@cycle/run';
import {adapt} from '@cycle/run/lib/adapt';
import {MainHTTPSource} from './MainHTTPSource';
import * as superagent from 'superagent';
import {
HTTPSource,
ResponseStream,
RequestOptions,
RequestInput,
Response,
} from './int... | }
}
if (reqOptions.field) {
for (const key in reqOptions.field) {
if (reqOptions.field.hasOwnProperty(key)) {
request = request.field(key, reqOptions.field[key]);
}
}
}
if (reqOptions.attach) {
for (let i = reqOptions.attach.length - 1; i >= 0; i--) {
const a = reqOptio... | if (reqOptions.headers) {
for (const key in reqOptions.headers) {
if (reqOptions.headers.hasOwnProperty(key)) {
request = request.set(key, reqOptions.headers[key]);
} | random_line_split |
http-driver.ts | import xs, {Stream, MemoryStream} from 'xstream';
import {Driver} from '@cycle/run';
import {adapt} from '@cycle/run/lib/adapt';
import {MainHTTPSource} from './MainHTTPSource';
import * as superagent from 'superagent';
import {
HTTPSource,
ResponseStream,
RequestOptions,
RequestInput,
Response,
} from './int... | (reqInput: RequestInput): RequestOptions {
if (typeof reqInput === 'string') {
return {url: reqInput};
} else if (typeof reqInput === 'object') {
return reqInput;
} else {
throw new Error(
`Observable of requests given to HTTP Driver must emit ` +
`either URL strings or objects with para... | normalizeRequestInput | identifier_name |
longbeach_crime_stats.py | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 22 12:07:53 2014
@author: Gouthaman Balaraman
"""
import requests
import pandas as pd
from bs4 import BeautifulSoup
import re
import numpy as np
import os
#####################################################
# A bunch of constants used throught the script. #
########... |
if __name__=='__main__':
'''
Here is a complete example to loop over all pdfs and create all csvs.
>>>pdfdir = "D:\\Development\\Python\\CrimeData\\files\\PDF"
>>>convert_all_pdfs(pdfdir)
>>>htmldir = "D:\\Development\\Python\\CrimeData\\files\\HTML"
>>>convert_all_htmls(htmldir)
... | '''
This is a top leve driver which calls create_csv in a loop
'''
for f in os.listdir(htmldir):
if f.endswith('.html'):
create_csv(os.path.join(htmldir,f))
#break | identifier_body |
longbeach_crime_stats.py | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 22 12:07:53 2014
@author: Gouthaman Balaraman
"""
import requests
import pandas as pd
from bs4 import BeautifulSoup
import re
import numpy as np
import os
#####################################################
# A bunch of constants used throught the script. #
########... |
'''
df = pd.DataFrame(pnodes)
[tmptbl,tmptblval] = create_buckets(df.top.unique()) # buckets for top
dval = []
for t in tmptbl:
dvlst = df[(df["top"]>=t[0])&(df["top"]<=t[1])&(df['left']<lftmrkr)]['content'].values
#dval.append(dvlst[0] if len(dvlst)>0 else u'RD')
cval ... | For a given page, here I use the position to tag it with a column number.
Then a data frame is created and the pivot_table option is construct back
a proper table to resemble the actual data set. | random_line_split |
longbeach_crime_stats.py | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 22 12:07:53 2014
@author: Gouthaman Balaraman
"""
import requests
import pandas as pd
from bs4 import BeautifulSoup
import re
import numpy as np
import os
#####################################################
# A bunch of constants used throught the script. #
########... | (pdfdir):
'''
Convenient method to loop over all the pdf files. Calls create_html
file in a loop.
'''
for f in os.listdir(pdfdir):
if f.endswith('.pdf'):
create_html(os.path.join(pdfdir,f))
def _finalize_dataframe(ddf):
'''
Does some clean-up, check sums to validate the ... | convert_all_pdfs | identifier_name |
longbeach_crime_stats.py | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 22 12:07:53 2014
@author: Gouthaman Balaraman
"""
import requests
import pandas as pd
from bs4 import BeautifulSoup
import re
import numpy as np
import os
#####################################################
# A bunch of constants used throught the script. #
########... |
else:
ddf = ddf[mptbltxt[:15]]
del ddf['RD']
ddf.index.name = 'RD'
return ddf
def create_csv(htmlfile):
'''
This creates the csv file given a html file
'''
try:
print "Converting "+htmlfile
soup = load_html(htmlfile)
pages = grab_pages(soup)
nu... | ddf = ddf[mptbltxt] | conditional_block |
arm_Redis_Cache_create_cache_with_same_name_should_fail.nock.js | // This file has been autogenerated.
var profile = require('../../../lib/util/profile');
exports.getMockedProfile = function () {
var newProfile = new profile.Profile();
newProfile.addSubscription(new profile.Subscription({
id: '00977cdb-163f-435f-9c32-39ec8ae61f4d',
name: 'node',
user: {
name:... | 'x-ms-ratelimit-remaining-subscription-reads': '14999',
'x-ms-correlation-request-id': 'c19c7d3b-16e5-4dd8-ae9d-e752158e9eb6',
'x-ms-routing-request-id': 'WESTUS:20151106T043332Z:c19c7d3b-16e5-4dd8-ae9d-e752158e9eb6',
date: 'Fri, 06 Nov 2015 04:33:32 GMT',
connection: 'close' });
return result; }]]; | 'x-rp-server-mvid': '34bb3c7e-5d41-4769-9a39-f21a2e547245',
'strict-transport-security': 'max-age=31536000; includeSubDomains',
server: 'Microsoft-HTTPAPI/2.0', | random_line_split |
ts-errores.ts | interface User{
name: string
userName: string
id: number
date: object
UserInfoObject()
RegisterUserData(info: object)
}
let db : any[] = []
class User implements User{
name: string
userName: string
id: number
date: object
constructor(name: string, userName: st... |
RegisterUserData(info?: object){
db.push(info || this.UserInfoObject())
}
}
class premiumUser extends User{
premium: boolean
constructor(name: string, userName: string, id:number, date:Object = new Date(), premium: boolean = true){
super(name,userName,id,date)
this.pr... | {
return {id: this.id, name: this.name, userName: this.userName, date: this.date }
} | identifier_body |
ts-errores.ts | interface User{
name: string
userName: string
id: number
date: object
UserInfoObject()
RegisterUserData(info: object)
}
let db : any[] = []
class User implements User{
name: string
userName: string
id: number
date: object
constructor(name: string, userName: st... | this.id = id
this.date = date
}
UserInfoObject(){
return {id: this.id, name: this.name, userName: this.userName, date: this.date }
}
RegisterUserData(info?: object){
db.push(info || this.UserInfoObject())
}
}
class premiumUser extends User{
premium: b... | this.name = name
this.userName = userName
| random_line_split |
ts-errores.ts | interface User{
name: string
userName: string
id: number
date: object
UserInfoObject()
RegisterUserData(info: object)
}
let db : any[] = []
class | implements User{
name: string
userName: string
id: number
date: object
constructor(name: string, userName: string, id: number, date: object = new Date()){
this.name = name
this.userName = userName
this.id = id
this.date = date
}
UserInfoObject(){
... | User | identifier_name |
attempts.js | import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { connect } from 'react-redux';
import styles from '../styles';
export const Attempts = (props) => {
const { attempts } = props;
const renderLetter = (letterWithScore, idx) => {
let style = styles.attemptLetter;
i... | return (
<View style={ styles.attempts }>
{ attempts.map(renderAttempt) }
</View>
);
};
const mapStateToProps = (state) => {
return {
attempts: state.game.attempts
};
};
const mapDispatchToProps = (dispatch) => {
return { };
};
/**
* Props:
* attempts: [{
* word: string
* }]
*/
... | };
| random_line_split |
Interactions.py | def fail_acquire_settings(log_printer, settings_names_dict):
"""
This method throws an exception if any setting needs to be acquired.
:param log_printer: Printer responsible for logging the messages.
:param settings: A dictionary with the settings name as key and
... |
log_printer.err(msg)
raise AssertionError
| msg += "{} (from {}) - {}".format(name, setting[1], setting[0]) | conditional_block |
Interactions.py | def fail_acquire_settings(log_printer, settings_names_dict):
| """
This method throws an exception if any setting needs to be acquired.
:param log_printer: Printer responsible for logging the messages.
:param settings: A dictionary with the settings name as key and
a list containing a description in [0] and the
... | identifier_body | |
Interactions.py | def | (log_printer, settings_names_dict):
"""
This method throws an exception if any setting needs to be acquired.
:param log_printer: Printer responsible for logging the messages.
:param settings: A dictionary with the settings name as key and
a list containing a descr... | fail_acquire_settings | identifier_name |
Interactions.py | def fail_acquire_settings(log_printer, settings_names_dict):
"""
This method throws an exception if any setting needs to be acquired.
:param log_printer: Printer responsible for logging the messages.
:param settings: A dictionary with the settings name as key and
... | log_printer.err(msg)
raise AssertionError | random_line_split | |
issue-11709.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
pub fn main() {
// {} would break
let _r = {};
let mut slot = None;
// `{ test(...); }` would break
let _s : S = S{ x: { test(&mut slot); } };
let _b = not(true);
}
| {
// `panic!(...)` would break
panic!("Break the compiler");
} | conditional_block |
issue-11709.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
// {} would break
let _r = {};
let mut slot = None;
// `{ test(...); }` would break
let _s : S = S{ x: { test(&mut slot); } };
let _b = not(true);
}
| main | identifier_name |
issue-11709.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
// {} would break
let _r = {};
let mut slot = None;
// `{ test(...); }` would break
let _s : S = S{ x: { test(&mut slot); } };
let _b = not(true);
} | identifier_body | |
issue-11709.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // `{ test(...); }` would break
let _s : S = S{ x: { test(&mut slot); } };
let _b = not(true);
} | random_line_split | |
recommendation.rs | //! Project Gutenberg etext recommendation utilities.
/*
* ashurbanipal.web: Rust Rustful-based interface to Ashurbanipal data
* Copyright 2015 Tommy M. McGuire
*
* 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 F... | (&self, etext_no : Etext) -> Option<Vec<(Etext,Score)>> {
self.scored_results(etext_no).map( |mut results| {
results.sort_by( |&(_,l),&(_,r)| panic_unless!("recommendation results",
option: l.partial_cmp(&r)) );
results
}... | sorted_results | identifier_name |
recommendation.rs | //! Project Gutenberg etext recommendation utilities.
/*
* ashurbanipal.web: Rust Rustful-based interface to Ashurbanipal data
* Copyright 2015 Tommy M. McGuire
* | * This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
... | * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
* | random_line_split |
recommendation.rs | //! Project Gutenberg etext recommendation utilities.
/*
* ashurbanipal.web: Rust Rustful-based interface to Ashurbanipal data
* Copyright 2015 Tommy M. McGuire
*
* 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 F... |
}
| {
self.scored_results(etext_no).map( |mut results| {
results.sort_by( |&(_,l),&(_,r)| panic_unless!("recommendation results",
option: l.partial_cmp(&r)) );
results
})
} | identifier_body |
on_conflict_target_decorations.rs | use crate::backend::{Backend, SupportsOnConflictClause, SupportsOnConflictTargetDecorations};
use crate::expression::Expression;
use crate::query_builder::upsert::on_conflict_target::{ConflictTarget, NoConflictTarget};
use crate::query_builder::where_clause::{NoWhereClause, WhereAnd, WhereClause};
use crate::query_buil... | DB: Backend + SupportsOnConflictClause + SupportsOnConflictTargetDecorations,
{
fn walk_ast(&self, mut out: AstPass<DB>) -> QueryResult<()> {
self.target.walk_ast(out.reborrow())?;
self.where_clause.walk_ast(out.reborrow())?;
Ok(())
}
} | random_line_split | |
on_conflict_target_decorations.rs | use crate::backend::{Backend, SupportsOnConflictClause, SupportsOnConflictTargetDecorations};
use crate::expression::Expression;
use crate::query_builder::upsert::on_conflict_target::{ConflictTarget, NoConflictTarget};
use crate::query_builder::where_clause::{NoWhereClause, WhereAnd, WhereClause};
use crate::query_buil... | <T, U> {
target: T,
where_clause: U,
}
impl<T, P> DecoratableTarget<P> for T
where
P: Expression,
P::SqlType: BoolOrNullableBool,
T: UndecoratedConflictTarget,
{
type FilterOutput = DecoratedConflictTarget<T, WhereClause<P>>;
fn filter_target(self, predicate: P) -> Self::FilterOutput {
... | DecoratedConflictTarget | identifier_name |
on_conflict_target_decorations.rs | use crate::backend::{Backend, SupportsOnConflictClause, SupportsOnConflictTargetDecorations};
use crate::expression::Expression;
use crate::query_builder::upsert::on_conflict_target::{ConflictTarget, NoConflictTarget};
use crate::query_builder::where_clause::{NoWhereClause, WhereAnd, WhereClause};
use crate::query_buil... |
}
| {
self.target.walk_ast(out.reborrow())?;
self.where_clause.walk_ast(out.reborrow())?;
Ok(())
} | identifier_body |
node-loaders.js | 'use strict';
var fs = require('fs');
var path = require('path');
var lib = require('./lib');
var Loader = require('./loader');
var chokidar = require('chokidar');
// Node <0.7.1 compatibility
var existsSync = fs.existsSync || path.existsSync;
var FileSystemLoader = Loader.extend({
init: function(searchPaths, no... | FileSystemLoader: FileSystemLoader
}; | }
});
module.exports = { | random_line_split |
node-loaders.js | 'use strict';
var fs = require('fs');
var path = require('path');
var lib = require('./lib');
var Loader = require('./loader');
var chokidar = require('chokidar');
// Node <0.7.1 compatibility
var existsSync = fs.existsSync || path.existsSync;
var FileSystemLoader = Loader.extend({
init: function(searchPaths, no... |
}.bind(this));
}
},
getSource: function(name) {
var fullpath = null;
var paths = this.searchPaths;
for(var i=0; i<paths.length; i++) {
var basePath = path.resolve(paths[i]);
var p = path.resolve(paths[i], name);
// Only allow th... | {
var watcher = chokidar.watch(p);
watcher.on('all', function(event, fullname) {
fullname = path.resolve(fullname);
if(event === 'change' && fullname in this.pathsToNames) {
this.emit('update', this.path... | conditional_block |
visualstudio_multi.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from conans.model import Generator
from conans.client.generators import VisualStudioGenerator
from xml.dom import minidom
from conans.util.files import load
class VisualStudioMultiGenerator(Generator):
template = """<?xml version="1.0" encoding="utf-8"?>
<P... |
@property
def content(self):
configuration = str(self.conanfile.settings.build_type)
platform = {'x86': 'Win32', 'x86_64': 'x64'}.get(str(self.conanfile.settings.arch))
vsversion = str(self.settings.compiler.version)
# there is also ClCompile.RuntimeLibrary, but it's handling ... | pass | identifier_body |
visualstudio_multi.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from conans.model import Generator
from conans.client.generators import VisualStudioGenerator
from xml.dom import minidom
from conans.util.files import load
class VisualStudioMultiGenerator(Generator):
template = """<?xml version="1.0" encoding="utf-8"?>
<P... |
name_multi = 'conanbuildinfo_multi.props'
name_current = ('conanbuildinfo_%s_%s_%s.props' % (configuration, platform, vsversion)).lower()
multi_path = os.path.join(self.output_path, name_multi)
if os.path.isfile(multi_path):
content_multi = load(multi_path)
else:
... | random_line_split | |
visualstudio_multi.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from conans.model import Generator
from conans.client.generators import VisualStudioGenerator
from xml.dom import minidom
from conans.util.files import load
class VisualStudioMultiGenerator(Generator):
template = """<?xml version="1.0" encoding="utf-8"?>
<P... |
else:
import_group.appendChild(import_node)
content_multi = dom.toprettyxml()
content_multi = "\n".join(line for line in content_multi.splitlines() if line.strip())
vs_generator = VisualStudioGenerator(self.conanfile)
content_current = vs_generator.content
... | break | conditional_block |
visualstudio_multi.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from conans.model import Generator
from conans.client.generators import VisualStudioGenerator
from xml.dom import minidom
from conans.util.files import load
class VisualStudioMultiGenerator(Generator):
template = """<?xml version="1.0" encoding="utf-8"?>
<P... | (self):
pass
@property
def content(self):
configuration = str(self.conanfile.settings.build_type)
platform = {'x86': 'Win32', 'x86_64': 'x64'}.get(str(self.conanfile.settings.arch))
vsversion = str(self.settings.compiler.version)
# there is also ClCompile.RuntimeLibrary... | filename | identifier_name |
createproduct.js | /* jshint node: true */
'use strict';
var util = require('util');
var _ = require('underscore');
var defaults = require('../defaults');
var options = require('../options');
var descriptor = defaults.defaultDescriptor({
'productName': {
name: 'Product Name',
required: true
},
'productDesc': {
na... |
var uri = util.format('%s/v1/o/%s/apiproducts', opts.baseuri, opts.organization);
request({
uri: uri,
method:'POST',
body: product,
json:true
},function(err,res,body){
var jsonBody = body
if(err){
if (opts.debug) {
console.log('Error occured %s', err);
}
done(err)
}else if (res.s... | {
product.quota = opts.quota
product.quotaInterval = opts.quotaInterval
product.quotaTimeUnit = opts.quotaTimeUnit
} | conditional_block |
createproduct.js | /* jshint node: true */
'use strict';
var util = require('util');
var _ = require('underscore');
var defaults = require('../defaults');
var options = require('../options');
var descriptor = defaults.defaultDescriptor({
'productName': {
name: 'Product Name',
required: true
},
'productDesc': {
na... | (opts,request,done){
var product = {
"approvalType": "auto",
"attributes":
[ {"name": "access", "value": "public"} ],
"scopes": []
}
product.name = opts.productName
product.displayName = opts.productName
product.description = opts.productDesc
product.proxies = []
if(opts.proxies){
var spli... | createProduct | identifier_name |
createproduct.js | /* jshint node: true */
'use strict';
var util = require('util');
var _ = require('underscore');
var defaults = require('../defaults');
var options = require('../options');
var descriptor = defaults.defaultDescriptor({
'productName': {
name: 'Product Name',
required: true
},
'productDesc': {
na... | {
var product = {
"approvalType": "auto",
"attributes":
[ {"name": "access", "value": "public"} ],
"scopes": []
}
product.name = opts.productName
product.displayName = opts.productName
product.description = opts.productDesc
product.proxies = []
if(opts.proxies){
var split = opts.proxies.sp... | identifier_body | |
createproduct.js | /* jshint node: true */
'use strict';
var util = require('util');
var _ = require('underscore');
var defaults = require('../defaults');
var options = require('../options');
var descriptor = defaults.defaultDescriptor({
'productName': {
name: 'Product Name',
required: true
},
'productDesc': {
na... | var split = opts.apiResources.split(',')
split.forEach(function(s){
if(s && s.trim()!= '') {
product.apiResources.push(s.trim())
}
})
}
if(opts.scopes){
var split = opts.scopes.split(',')
split.forEach(function(s){
if(s && s.trim()!= '') {
product.scopes.push(s.trim())
}
})
}
product... | })
}
product.apiResources = []
if(opts.apiResources){ | random_line_split |
test_mxne_inverse.py | # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
#
# License: Simplified BSD
import os.path as op
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_allclose,
assert_array_less, assert_array... | ():
"""Tests solver with too high alpha."""
evoked = read_evokeds(fname_data, condition=0, baseline=(None, 0))
evoked.pick("grad", exclude="bads")
fname_fwd = op.join(data_path, 'MEG', 'sample',
'sample_audvis_trunc-meg-eeg-oct-4-fwd.fif')
forward = mne.read_forward_solution(... | test_mxne_inverse_empty | identifier_name |
test_mxne_inverse.py | # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
#
# License: Simplified BSD
import os.path as op
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_allclose,
assert_array_less, assert_array... | noise_cov = mne.make_ad_hoc_cov(info)
label_names = ['Aud-lh', 'Aud-rh']
labels = [
mne.read_label(data_path / 'MEG' / 'sample' / 'labels' / f'{ln}.label')
for ln in label_names]
fname_fwd = op.join(data_path, 'MEG', 'sample',
'sample_audvis_trunc-meg-eeg-oct-4-fw... | info = mne.io.read_info(fname_data)
with info._unlock():
info['projs'] = [] | random_line_split |
test_mxne_inverse.py | # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
#
# License: Simplified BSD
import os.path as op
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_allclose,
assert_array_less, assert_array... |
@pytest.mark.slowtest
@testing.requires_testing_data
def test_mxne_vol_sphere():
"""Test (TF-)MxNE with a sphere forward and volumic source space."""
evoked = read_evokeds(fname_data, condition=0, baseline=(None, 0))
evoked.crop(tmin=-0.05, tmax=0.2)
cov = read_cov(fname_cov)
evoked_l21 = evoked... | """Test (TF-)MxNE inverse computation."""
# Read noise covariance matrix
cov = read_cov(fname_cov)
# Handling average file
loose = 0.0
depth = 0.9
evoked = read_evokeds(fname_data, condition=0, baseline=(None, 0))
evoked.crop(tmin=-0.05, tmax=0.2)
evoked_l21 = evoked.copy()
evoked... | identifier_body |
test_mxne_inverse.py | # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
#
# License: Simplified BSD
import os.path as op
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_allclose,
assert_array_less, assert_array... |
@testing.requires_testing_data
@pytest.mark.parametrize('idx, weights', [
# empirically determined approximately orthogonal columns: 0, 15157, 19448
([0], [1]),
([0, 15157], [1, 1]),
([0, 15157], [1, 3]),
([0, 15157], [5, -1]),
([0, 15157, 19448], [1, 1, 1]),
([0, 15157, 19448], [1e-2, 1,... | assert_allclose(gof_split, want, atol=1e-12) | conditional_block |
server.js | var _ = require('lodash');
var express = require('express');
var path = require('path');
var httpProxy = require('http-proxy');
var http = require('http');
var proxy = httpProxy.createProxyServer({
changeOrigin: true,
ws: true
});
var app = express();
var isProduction = process.env.NODE_ENV === 'production';
va... |
var data = [{
"quote_collateral_bp": 5000,
"denom_asset": "~BTC:SATOSHIS",
"base_asset": "USLV",
"base_principal": 50000000,
"quote_multiplier": 1.00,
"base_collateral_bp": 5000,
"base_principal_hi": 52500000,
"quote_principal": 50000000,
"quote_principal_hi": 52500000,
"princip... | random_line_split | |
server.js | var _ = require('lodash');
var express = require('express');
var path = require('path');
var httpProxy = require('http-proxy');
var http = require('http');
var proxy = httpProxy.createProxyServer({
changeOrigin: true,
ws: true
});
var app = express();
var isProduction = process.env.NODE_ENV === 'production';
va... | {
// And run the server
app.listen(port, function() {
console.log('Server running on port ' + port);
});
} | conditional_block | |
adminPickupBase.ts | 'use strict';
export class | {
protected $http: ng.IHttpService;
PickupUtils: IPickupUtilsService;
PickupOptionsService: IPickupOptionsService;
season: ISeason;
pickup: IPickupEvent;
pickupOptions: IPickupOption[];
userEvents: IPickupUserEvent[];
pickupEventAlternatives: IPickupEvent[];
extraInformation: {};
constructor($htt... | AdminPickupBase | identifier_name |
adminPickupBase.ts | 'use strict';
export class AdminPickupBase {
protected $http: ng.IHttpService;
PickupUtils: IPickupUtilsService;
PickupOptionsService: IPickupOptionsService;
season: ISeason;
pickup: IPickupEvent;
pickupOptions: IPickupOption[];
userEvents: IPickupUserEvent[];
pickupEventAlternatives: IPickupEvent[];
... | }
public getExtraInformation() {
let extraInfo = {};
let scope = this;
_.each(scope.pickup.availableExtras, extra => {
let fullExtra = _.find(scope.season.availableExtras, candidate => {
return (candidate._id == extra);
});
if (fullExtra) {
extraInfo[fullExtra._i... | }
public hasExtraInformation() {
return this.pickup.availableExtras.length>0; | random_line_split |
adminPickupBase.ts | 'use strict';
export class AdminPickupBase {
protected $http: ng.IHttpService;
PickupUtils: IPickupUtilsService;
PickupOptionsService: IPickupOptionsService;
season: ISeason;
pickup: IPickupEvent;
pickupOptions: IPickupOption[];
userEvents: IPickupUserEvent[];
pickupEventAlternatives: IPickupEvent[];
... |
}) != null;
});
userEvent.$extras = result;
}
public ok() {
(this as any).close({$value: 'ok'});
};
public cancel() {
(this as any).dismiss({$value: 'cancel'});
};
}
| {
result.push(
{
'quantity': child.quantity,
'unit': candidate.unit,
'name': candidate.name
});
} | conditional_block |
DashboardPage.test.tsx | import React from 'react';
import { Provider } from 'react-redux';
import { render, screen } from '@testing-library/react';
import { Props, UnthemedDashboardPage } from './DashboardPage';
import { Props as LazyLoaderProps } from '../dashgrid/LazyLoader';
import { Router } from 'react-router-dom';
import { locationServi... | getCurrent: () => getTestDashboard(),
} as any);
ctx.mount({
dashboard: getTestDashboard(),
queryParams: { viewPanel: '1' },
});
});
it('Should render panel in view mode', () => {
expect(ctx.dashboard?.panelInView).toBeDefined();
expect(ctx.dashboard?.panel... | getInstanceSettings: jest.fn().mockReturnValue({ meta: {} }),
getList: jest.fn(),
reload: jest.fn(),
});
setDashboardSrv({ | random_line_split |
DashboardPage.test.tsx | import React from 'react';
import { Provider } from 'react-redux';
import { render, screen } from '@testing-library/react';
import { Props, UnthemedDashboardPage } from './DashboardPage';
import { Props as LazyLoaderProps } from '../dashgrid/LazyLoader';
import { Router } from 'react-router-dom';
import { locationServi... | (description: string, scenarioFn: (ctx: ScenarioContext) => void) {
describe(description, () => {
let setupFn: () => void;
const ctx: ScenarioContext = {
setup: (fn) => {
setupFn = fn;
},
mount: (propOverrides?: Partial<Props>) => {
const store = configureStore();
co... | dashboardPageScenario | identifier_name |
DashboardPage.test.tsx | import React from 'react';
import { Provider } from 'react-redux';
import { render, screen } from '@testing-library/react';
import { Props, UnthemedDashboardPage } from './DashboardPage';
import { Props as LazyLoaderProps } from '../dashgrid/LazyLoader';
import { Router } from 'react-router-dom';
import { locationServi... |
function dashboardPageScenario(description: string, scenarioFn: (ctx: ScenarioContext) => void) {
describe(description, () => {
let setupFn: () => void;
const ctx: ScenarioContext = {
setup: (fn) => {
setupFn = fn;
},
mount: (propOverrides?: Partial<Props>) => {
const stor... | {
const data = Object.assign(
{
title: 'My dashboard',
panels: [
{
id: 1,
type: 'timeseries',
title: 'My panel title',
gridPos: { x: 0, y: 0, w: 1, h: 1 },
},
],
},
overrides
);
const meta = Object.assign({ canSave: true, canEd... | identifier_body |
autocomplete.py | """Customized autocomplete widgets"""
# Standard Library
import re
# Third Party
from dal import autocomplete
# MuckRock
from muckrock.jurisdiction.models import Jurisdiction
class MRSelect2Mixin:
"""MuckRock Model Select2 mixin"""
def __init__(self, *args, **kwargs):
attrs = {
"data-h... |
pk, include_local = choice.split("-")
jurisdiction = Jurisdiction.objects.get(pk=pk)
label = str(jurisdiction)
if include_local == "True":
label += " (include local)"
self.choices.append((choice, label))
| continue | conditional_block |
autocomplete.py | """Customized autocomplete widgets"""
# Standard Library
import re
# Third Party
from dal import autocomplete
# MuckRock
from muckrock.jurisdiction.models import Jurisdiction
class MRSelect2Mixin:
"""MuckRock Model Select2 mixin"""
def __init__(self, *args, **kwargs):
attrs = {
"data-h... |
class ModelSelect2Multiple(MRSelect2Mixin, autocomplete.ModelSelect2Multiple):
"""MuckRock Model Select2"""
class Select2MultipleSI(MRSelect2Mixin, autocomplete.Select2Multiple):
"""MuckRock Select2 for state inclusive jurisdiction autocomplete"""
value_format = re.compile(r"\d+-(True|False)")
de... | """MuckRock Model Select2""" | identifier_body |
autocomplete.py | """Customized autocomplete widgets"""
# Standard Library
import re
# Third Party
from dal import autocomplete
# MuckRock
from muckrock.jurisdiction.models import Jurisdiction
class MRSelect2Mixin:
"""MuckRock Model Select2 mixin"""
def __init__(self, *args, **kwargs):
attrs = {
"data-h... | (MRSelect2Mixin, autocomplete.Select2Multiple):
"""MuckRock Select2 for state inclusive jurisdiction autocomplete"""
value_format = re.compile(r"\d+-(True|False)")
def filter_choices_to_render(self, selected_choices):
"""Replace self.choices with selected_choices."""
self.choices = []
... | Select2MultipleSI | identifier_name |
autocomplete.py | """Customized autocomplete widgets"""
# Standard Library
import re
# Third Party
from dal import autocomplete
# MuckRock
from muckrock.jurisdiction.models import Jurisdiction
| attrs = {
"data-html": True,
"data-dropdown-css-class": "select2-dropdown",
"data-width": "100%",
}
attrs.update(kwargs.pop("attrs", {}))
super().__init__(*args, attrs=attrs, **kwargs)
def filter_choices_to_render(self, selected_choices):
... |
class MRSelect2Mixin:
"""MuckRock Model Select2 mixin"""
def __init__(self, *args, **kwargs): | random_line_split |
aggregates.rs | // Copyright 2016 Mozilla | // this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY... | //
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use | random_line_split |
aggregates.rs | // Copyright 2016 Mozilla
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software... |
let schema = prepopulated_schema();
let query = r#"[:find (the ?e) ?a
:where
[?e :foo/age ?a]]"#;
// While the query itself algebrizes and parses…
let parsed = parse_find_string(query).expect("query input to have parsed");
let algebrized = algebrize(Known::... | _the_without_max_or_min() { | identifier_name |
aggregates.rs | // Copyright 2016 Mozilla
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software... |
#[test]
fn test_aggregate_unsuitable_type() {
let schema = prepopulated_schema();
let query = r#"[:find (avg ?e)
:where
[?e :foo/age ?a]]"#;
// While the query itself algebrizes and parses…
let parsed = parse_find_string(query).expect("query input to have pars... | {
let mut schema = Schema::default();
associate_ident(&mut schema, Keyword::namespaced("foo", "name"), 65);
associate_ident(&mut schema, Keyword::namespaced("foo", "age"), 68);
associate_ident(&mut schema, Keyword::namespaced("foo", "height"), 69);
add_attribute(&mut schema, 65, Attribute {
... | identifier_body |
__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# === django_pgmp ---------------------------------------------------------===
# This file is part of django-pgpm. django-pgpm is copyright © 2012, RokuSigma
# Inc. and contributors. See AUTHORS and LICENSE for more details.
#
# django-pgpm is free software: you can redist... |
# ===----------------------------------------------------------------------===
# End of File
# ===----------------------------------------------------------------------===
| ersion = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%spre-alpha' % version
else:
if VERSION[3] != 'final':
version = "%s%s" % (version, VERSION[3])
if VERSION[4] != 0:
version = '%s%s' % (ve... | identifier_body |
__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# === django_pgmp ---------------------------------------------------------===
# This file is part of django-pgpm. django-pgpm is copyright © 2012, RokuSigma
# Inc. and contributors. See AUTHORS and LICENSE for more details.
#
# django-pgpm is free software: you can redist... | ):
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%spre-alpha' % version
else:
if VERSION[3] != 'final':
version = "%s%s" % (version, VERSION[3])
if VERSION[4] != 0:
version = '%s%s'... | et_version( | identifier_name |
__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# === django_pgmp ---------------------------------------------------------===
# This file is part of django-pgpm. django-pgpm is copyright © 2012, RokuSigma
# Inc. and contributors. See AUTHORS and LICENSE for more details.
#
# django-pgpm is free software: you can redist... | return version
# ===----------------------------------------------------------------------===
# End of File
# ===----------------------------------------------------------------------===
| f VERSION[3] != 'final':
version = "%s%s" % (version, VERSION[3])
if VERSION[4] != 0:
version = '%s%s' % (version, VERSION[4])
| conditional_block |
__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# === django_pgmp ---------------------------------------------------------===
# This file is part of django-pgpm. django-pgpm is copyright © 2012, RokuSigma
# Inc. and contributors. See AUTHORS and LICENSE for more details. | # any later version.
#
# django-pgpm is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
#
# You should have received a copy of the GNU Les... | #
# django-pgpm is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) | random_line_split |
help.js | 'use strict';
const chalk = require('chalk');
const fs = require('hexo-fs');
const pathFn = require('path');
const Promise = require('bluebird');
const COMPLETION_DIR = pathFn.join(__dirname, '../../completion');
function helpConsole(args) {
if (args.v || args.version) {
return this.call('version');
} else i... | (title, list) {
list.sort((a, b) => {
const nameA = a.name;
const nameB = b.name;
if (nameA < nameB) return -1;
if (nameA > nameB) return 1;
return 0;
});
const lengths = list.map(item => item.name.length);
const maxLen = lengths.reduce((prev, current) => Math.max(prev, current));
let ... | printList | identifier_name |
help.js | 'use strict';
const chalk = require('chalk');
const fs = require('hexo-fs');
const pathFn = require('path');
const Promise = require('bluebird');
const COMPLETION_DIR = pathFn.join(__dirname, '../../completion');
function helpConsole(args) {
if (args.v || args.version) {
return this.call('version');
} else i... |
function printList(title, list) {
list.sort((a, b) => {
const nameA = a.name;
const nameB = b.name;
if (nameA < nameB) return -1;
if (nameA > nameB) return 1;
return 0;
});
const lengths = list.map(item => item.name.length);
const maxLen = lengths.reduce((prev, current) => Math.max(prev... | {
const keys = Object.keys(list);
const commands = [];
const { length } = keys;
for (let i = 0; i < length; i++) {
const key = keys[i];
commands.push({
name: key,
desc: list[key].desc
});
}
console.log('Usage: hexo <command>\n');
printList('Commands', commands);
printList('G... | identifier_body |
help.js | 'use strict';
const chalk = require('chalk');
const fs = require('hexo-fs');
const pathFn = require('path');
const Promise = require('bluebird');
const COMPLETION_DIR = pathFn.join(__dirname, '../../completion');
function helpConsole(args) {
if (args.v || args.version) {
return this.call('version');
} else i... | {name: '--silent', desc: 'Hide output on console'}
]);
console.log('For more help, you can use \'hexo help [command]\' for the detailed information');
console.log('or you can check the docs:', chalk.underline('http://hexo.io/docs/'));
return Promise.resolve();
}
function printList(title, list) {
list.s... | {name: '--draft', desc: 'Display draft posts'},
{name: '--safe', desc: 'Disable all plugins and scripts'}, | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.