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
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...
Examples -------- Using predictNOE(peaklist,"N15","H1",10,12) where peaklist is of the type xpktools.peaklist would generate a .xpk file entry for a crosspeak that originated on N15 of residue 10 and ended up as magnetization detected on the H1 nucleus of residue 12 Notes ====...
"""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
specify the values at 0% and 100%, the start and ending values. There is also a {@link #keyframe} * event that fires after each key frame is reached. * * ## Example * * In the example below, we modify the values of the element at each fifth throughout the animation. * * @example * Ext.create('Ext.fx.An...
* 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
an instantiated Animator, or subclass thereof. */ isAnimator: true, /** * @cfg {Number} duration * Time in milliseconds for the animation to last. Defaults to 250. */ duration: 250, /** * @cfg {Number} delay * Time to delay before starting the animation. Defaults to 0. ...
{ 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...
// Check for oic.if.a XOR oic.if.s t.true( (resource.if.indexOf('oic.if.a') > -1) != (resource.if.indexOf('oic.if.s') > -1), `Resource ${i},${j} requires an interface be either an actuator or a sensor (if)` ...
{ 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)
t.is(typeof translator, 'object') && t.truthy(translator); }); /** * Verify that the ouput from GetPlatform includes all of the required properties */ test.serial('GetPlatform', t => { return helpers.runTest(settings, t, () => { return opent2t.invokeMethodAsync(transla...
{ 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
// 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
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. # ----------------------------------------------------------------------------- """Declarator for registering drivers. """ from atom.api import Str, Dict, Prop...
(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
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. # ----------------------------------------------------------------------------- """Declarator for registering drivers. """ from atom.api import Str, Dict, Prop...
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
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. # ----------------------------------------------------------------------------- """Declarator for registering drivers. """ from atom.api import Str, Dict, Prop...
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
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. # ----------------------------------------------------------------------------- """Declarator for registering drivers. """ from atom.api import Str, Dict, Prop...
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
= (sa+prev)*0.5 buckets.append((s,e)) s = e prev = sa #else buckets.append((s,s+40)) return [buckets,[i for i,y in enumerate(buckets)]] def create_frame(pnodes,mptbl,mptbltxt,lftmrkr): ''' For a given page, here I use the position to tag it with a column num...
''' 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
1094,1199)] # This provides a mapping to the column with the text mptbltxt = ['RD','MURDER','MANSLTR','FORCED_RAPE','ROBBERY','AGGRAV_ASSAULT', 'BURGLARY_RES','BURGLARY_COM','AUTO_BURG','GRAND_THEFT','PETTY_THEFT', 'BIKE_THEFT','AUTO_THEFT','ARSON','TOTAL_PART1','TOTAL_PART2','GRAND_TOTAL'] #this a truncate version I ...
''' 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
094,1199)] # This provides a mapping to the column with the text mptbltxt = ['RD','MURDER','MANSLTR','FORCED_RAPE','ROBBERY','AGGRAV_ASSAULT', 'BURGLARY_RES','BURGLARY_COM','AUTO_BURG','GRAND_THEFT','PETTY_THEFT', 'BIKE_THEFT','AUTO_THEFT','ARSON','TOTAL_PART1','TOTAL_PART2','GRAND_TOTAL'] #this a truncate version I f...
(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
1094,1199)] # This provides a mapping to the column with the text mptbltxt = ['RD','MURDER','MANSLTR','FORCED_RAPE','ROBBERY','AGGRAV_ASSAULT', 'BURGLARY_RES','BURGLARY_COM','AUTO_BURG','GRAND_THEFT','PETTY_THEFT', 'BIKE_THEFT','AUTO_THEFT','ARSON','TOTAL_PART1','TOTAL_PART2','GRAND_TOTAL'] #this a truncate version I ...
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
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):
for name, setting in settings_names_dict.items(): msg += "{} (from {}) - {}".format(name, setting[1], setting[0]) log_printer.err(msg) raise AssertionError
""" 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...
product.apiResources = [] if(opts.apiResources){ 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()!= '') { ...
{ 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
None, 'mult', 'augment', 'sign', 'zero', 'less')) def test_split_gof_basic(mod): """Test splitting the goodness of fit.""" # first a trivial case gain = np.array([[0., 1., 1.], [1., 1., 0.]]).T M = np.ones((3, 1)) X = np.ones((2, 1)) M_est = gain @ X assert_allclose(M_est, np.array([[1.,...
test_mxne_inverse_empty
identifier_name
test_mxne_inverse.py
=True) dip_mxne = mixed_norm(evoked_dip, fwd, cov, alpha=80, n_mxne_iter=1, maxit=30, tol=1e-8, active_set_size=10, return_as_dipoles=True) amp_max = [np.max(d.amplitude) for d in dip_mxne] dip_mxne = dip_mxne[np.argmax(amp_max)] assert dip_mxne.pos[...
info = mne.io.read_info(fname_data) with info._unlock(): info['projs'] = []
random_line_split
test_mxne_inverse.py
loose=loose, depth=depth, fixed=True, use_cps=True) stc_dspm = apply_inverse(evoked_l21, inverse_operator, lambda2=1. / 9., method='dSPM') stc_dspm.data[np.abs(stc_dspm.data) < 12] = 0.0 st...
"""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
c, residual = mixed_norm( evoked_l21, forward, cov, alpha, n_mxne_iter=5, loose=0.0001, depth=depth, maxit=300, tol=1e-8, active_set_size=10, solver='cd', return_residual=True, pick_ori='vector', verbose=True) assert_array_almost_equal(stc.times, evoked_l21.times, 5) assert s...
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
/react'; import { Props, UnthemedDashboardPage } from './DashboardPage'; import { Props as LazyLoaderProps } from '../dashgrid/LazyLoader'; import { Router } from 'react-router-dom'; import { locationService, setDataSourceSrv } from '@grafana/runtime'; import { DashboardModel } from '../state'; import { configureStore ...
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
/react'; import { Props, UnthemedDashboardPage } from './DashboardPage'; import { Props as LazyLoaderProps } from '../dashgrid/LazyLoader'; import { Router } from 'react-router-dom'; import { locationService, setDataSourceSrv } from '@grafana/runtime'; import { DashboardModel } from '../state'; import { configureStore ...
(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
/react'; import { Props, UnthemedDashboardPage } from './DashboardPage'; import { Props as LazyLoaderProps } from '../dashgrid/LazyLoader'; import { Router } from 'react-router-dom'; import { locationService, setDataSourceSrv } from '@grafana/runtime'; import { DashboardModel } from '../state'; import { configureStore ...
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...
schema } #[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...
{ 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...
{name: '--cwd', desc: 'Specify the CWD'}, {name: '--debug', desc: 'Display all verbose messages in the terminal'}, {name: '--draft', desc: 'Display draft posts'}, {name: '--safe', desc: 'Disable all plugins and scripts'}, {name: '--silent', desc: 'Hide output on console'} ]); console.log('For m...
{ 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
handler.js
const config = require('../../../server/config'), Manager = require('./manager'), manager = new Manager(); // Responsible for handling requests for sitemap files module.exports = function handler(siteApp) { const verifyResourceType = function verifyResourceType(req, res, next) { if (!Object.prototy...
next(); }; siteApp.get('/sitemap.xml', function sitemapXML(req, res) { res.set({ 'Cache-Control': 'public, max-age=' + config.get('caching:sitemap:maxAge'), 'Content-Type': 'text/xml' }); res.send(manager.getIndexXml()); }); siteApp.get('/site...
{ return res.sendStatus(404); }
conditional_block