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
update.py
from git import Repo from util import hook, web @hook.command def
(inp, bot=None): repo = Repo() git = repo.git try: pull = git.pull() except Exception as e: return e if "\n" in pull: return web.haste(pull) else: return pull @hook.command def version(inp, bot=None): repo = Repo() # get origin and fetch it origin =...
update
identifier_name
NodesRegionDSLFilter.tsx
import PropTypes from "prop-types"; import * as React from "react"; import { Trans } from "@lingui/macro"; import DSLCombinerTypes from "#SRC/js/constants/DSLCombinerTypes"; import DSLExpression from "#SRC/js/structs/DSLExpression"; import DSLExpressionPart from "#SRC/js/structs/DSLExpressionPart"; import DSLFormWithE...
, expression: new DSLExpression(""), defaultData: { regions: [] }, }; NodeRegionDSLSection.propTypes = { onChange: PropTypes.func.isRequired, expression: PropTypes.instanceOf(DSLExpression).isRequired, defaultData: PropTypes.object.isRequired, }; export default NodeRegionDSLSection;
{}
identifier_body
NodesRegionDSLFilter.tsx
import PropTypes from "prop-types"; import * as React from "react"; import { Trans } from "@lingui/macro"; import DSLCombinerTypes from "#SRC/js/constants/DSLCombinerTypes"; import DSLExpression from "#SRC/js/structs/DSLExpression"; import DSLExpressionPart from "#SRC/js/structs/DSLExpressionPart"; import DSLFormWithE...
</div> </DSLFormWithExpressionUpdates> ); }; NodeRegionDSLSection.defaultProps = { onChange() {}, expression: new DSLExpression(""), defaultData: { regions: [] }, }; NodeRegionDSLSection.propTypes = { onChange: PropTypes.func.isRequired, expression: PropTypes.instanceOf(DSLExpression).isRequired...
})} </div>
random_line_split
NodesRegionDSLFilter.tsx
import PropTypes from "prop-types"; import * as React from "react"; import { Trans } from "@lingui/macro"; import DSLCombinerTypes from "#SRC/js/constants/DSLCombinerTypes"; import DSLExpression from "#SRC/js/structs/DSLExpression"; import DSLExpressionPart from "#SRC/js/structs/DSLExpressionPart"; import DSLFormWithE...
regions.forEach((region) => { EXPRESSION_PARTS[`region_${region}`] = DSLExpressionPart.attribute( "region", region ); }, this); const enabled = DSLUtil.canProcessParts(expression, EXPRESSION_PARTS); const data = DSLUtil.getPartValues(expression, EXPRESSION_PARTS); return ( <DSLForm...
{ return null; }
conditional_block
NodesRegionDSLFilter.tsx
import PropTypes from "prop-types"; import * as React from "react"; import { Trans } from "@lingui/macro"; import DSLCombinerTypes from "#SRC/js/constants/DSLCombinerTypes"; import DSLExpression from "#SRC/js/structs/DSLExpression"; import DSLExpressionPart from "#SRC/js/structs/DSLExpressionPart"; import DSLFormWithE...
() {}, expression: new DSLExpression(""), defaultData: { regions: [] }, }; NodeRegionDSLSection.propTypes = { onChange: PropTypes.func.isRequired, expression: PropTypes.instanceOf(DSLExpression).isRequired, defaultData: PropTypes.object.isRequired, }; export default NodeRegionDSLSection;
onChange
identifier_name
point.ts
import Utilities from './utilities' import Size from './size' import Scale from './scale' type Point = { x: number y: number } namespace Point { export function diff(point1: Point, point2: Point): Size
export function offset(point: Point, offset: Size | number): Point { const size = Utilities.ensureSize(offset) return { x: point.x + size.width, y: point.y + size.height } } export function equals(point1: Point, point2: Point): boolean { return Utilities.propsEqual(point1, point2, ['x', 'y']) } e...
{ return { width: point2.x - point1.x, height: point2.y - point1.y } }
identifier_body
point.ts
import Utilities from './utilities' import Size from './size' import Scale from './scale' type Point = { x: number y: number } namespace Point { export function diff(point1: Point, point2: Point): Size { return { width: point2.x - point1.x, height: point2.y - point1.y } } export function offset(point:...
(point1: Point, point2: Point): boolean { return Utilities.propsEqual(point1, point2, ['x', 'y']) } export function scale({ x, y }: Point, scale: Scale) { const { x: scaleX, y: scaleY } = Scale.forceXY(scale) return { x: x * scaleX, y: y * scaleY } } export const Zero: Point = Object.freeze({ x: 0, ...
equals
identifier_name
point.ts
import Utilities from './utilities' import Size from './size' import Scale from './scale' type Point = { x: number y: number } namespace Point { export function diff(point1: Point, point2: Point): Size { return { width: point2.x - point1.x, height: point2.y - point1.y } } export function offset(point:...
export function scale({ x, y }: Point, scale: Scale) { const { x: scaleX, y: scaleY } = Scale.forceXY(scale) return { x: x * scaleX, y: y * scaleY } } export const Zero: Point = Object.freeze({ x: 0, y: 0 }) } export default Point
} export function equals(point1: Point, point2: Point): boolean { return Utilities.propsEqual(point1, point2, ['x', 'y']) }
random_line_split
__init__.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
PidHandler, JstackHandler, MemoryHistogramHandler, JmapHandler )
TopologySchedulerLocationJsonHandler, TopologyExecutionStateJsonHandler, TopologyExceptionsJsonHandler,
random_line_split
type-ascription-precedence.rs
// Copyright 2015 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 ...
(self) -> Z { panic!() } } impl Deref for S { type Target = Z; fn deref(&self) -> &Z { panic!() } } fn main() { &S: &S; // OK (&S): &S; // OK &(S: &S); //~ ERROR mismatched types *S: Z; // OK (*S): Z; // OK *(S: Z); //~ ERROR mismatched types //~^ ERROR type `Z` cannot be dereferen...
neg
identifier_name
type-ascription-precedence.rs
// Copyright 2015 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 ...
} fn main() { &S: &S; // OK (&S): &S; // OK &(S: &S); //~ ERROR mismatched types *S: Z; // OK (*S): Z; // OK *(S: Z); //~ ERROR mismatched types //~^ ERROR type `Z` cannot be dereferenced -S: Z; // OK (-S): Z; // OK -(S: Z); //~ ERROR mismatched types //~^ ERROR cannot ap...
{ panic!() }
identifier_body
type-ascription-precedence.rs
// Copyright 2015 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 ...
#![feature(type_ascription)] use std::ops::*; struct S; struct Z; impl Add<Z> for S { type Output = S; fn add(self, _rhs: Z) -> S { panic!() } } impl Mul<Z> for S { type Output = S; fn mul(self, _rhs: Z) -> S { panic!() } } impl Neg for S { type Output = Z; fn neg(self) -> Z { panic!() } } im...
// Operator precedence of type ascription // Type ascription has very high precedence, the same as operator `as`
random_line_split
connect.js
const ircFramework = require('irc-framework') const store = require('../store') const attachEvents = require('./attachEvents') const connect = connection => { const state = store.getState() let ircClient = state.ircClients[connection.id] if (!ircClient) { ircClient = new ircFramework.Client({ nick: ...
store.dispatch({ type: 'SET_IRC_CLIENT', payload: { connectionId: connection.id, ircClient, }, }) } ircClient.connect() } module.exports = connect
attachEvents(ircClient, connection.id)
random_line_split
connect.js
const ircFramework = require('irc-framework') const store = require('../store') const attachEvents = require('./attachEvents') const connect = connection => { const state = store.getState() let ircClient = state.ircClients[connection.id] if (!ircClient)
ircClient, }, }) } ircClient.connect() } module.exports = connect
{ ircClient = new ircFramework.Client({ nick: connection.nick, host: connection.host, port: connection.port, tls: connection.tls, username: connection.username || connection.nick, password: connection.password, // "Not enough parameters" with empty gecos so a space is used....
conditional_block
orderController.js
'use strict'; app.controller('orderController', ['$scope', '$rootScope', 'toastrService', 'orderService', function ($scope, $rootScope, toastrService, orderService) { $scope.paging = 1; $scope.disabledMore = false; $scope.data = []; $scope.getOrders = function () { order...
lse { $scope.disabledMore = true; } }); } $scope.more = function () { $scope.paging++; $scope.getOrders(); }; $scope.refresh = function () { $scope.paging = 1; $scope.data = []; $s...
$scope.data.push.apply($scope.data, data); } e
conditional_block
orderController.js
'use strict'; app.controller('orderController', ['$scope', '$rootScope', 'toastrService', 'orderService', function ($scope, $rootScope, toastrService, orderService) { $scope.paging = 1; $scope.disabledMore = false; $scope.data = []; $scope.getOrders = function () { order...
$scope.disabledMore = true; } }); } $scope.more = function () { $scope.paging++; $scope.getOrders(); }; $scope.refresh = function () { $scope.paging = 1; $scope.data = []; $scope.g...
if (data.length > 0) { $scope.data.push.apply($scope.data, data); } else {
random_line_split
impact_function.py
on Population for Continuous Hazard.** Contact : ole.moller.nielsen@gmail.com .. note:: 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 o...
[ tr('Needs should be provided %s' % frequency), tr('Total') ], header=True)) for resource in needs: table_body.append(TableRow([ tr(resource['table name']), format...
table_body.extend([ TableRow(tr('Notes'), header=True), tr('Map shows population count in high, medium, and low hazard ' 'area.'), tr('Total population: %s') % format_int(total), TableRow(tr( 'Table below shows the minimum needs for all ' ...
identifier_body
impact_function.py
Function on Population for Continuous Hazard.** Contact : ole.moller.nielsen@gmail.com .. note:: 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 (...
total_impact, no_data_warning): # Extend impact report for on-screen display table_body.extend([ TableRow(tr('Notes'), header=True), tr('Map shows population count in high, medium, and low hazard ' 'area.'), tr('Total population:...
random_line_split
impact_function.py
on Population for Continuous Hazard.** Contact : ole.moller.nielsen@gmail.com .. note:: 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 o...
# Calculate impact as population exposed to each category exposure_data = self.exposure.layer.get_data(nan=True, scaling=True) if has_no_data(exposure_data): no_data_warning = True # Make 3 data for each zone. Get the value of the exposure if the # exposure is in t...
no_data_warning = True
conditional_block
impact_function.py
on Population for Continuous Hazard.** Contact : ole.moller.nielsen@gmail.com .. note:: 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 o...
(ContinuousRHContinuousRE): # noinspection PyUnresolvedReferences """Plugin for impact of population as derived by continuous hazard.""" _metadata = ContinuousHazardPopulationMetadata() def __init__(self): super(ContinuousHazardPopulationFunction, self).__init__() self.impact_function_m...
ContinuousHazardPopulationFunction
identifier_name
11.py
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 # 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 # 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 # 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 # 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 # 88 36 68 8...
tmp = nums[j - 3 + i * size] * nums[j - 2 + i * size] \ * nums[j - 1 + i * size] * nums[j + i * size] ans = max(ans, tmp) tmp = nums[i + (j - 3) * size] * nums[i + (j - 2) * size] \ * nums[i + (j - 1) * size] * nums[i + j * size] ans = max(ans, tmp)
conditional_block
11.py
53 78 36 84 20 35 17 12 50 # 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 # 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 # 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 # 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 # 78 17 53 28 22 75 31 67 15 94 03 80 04 62 1...
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 \
random_line_split
register.tsx
import React from 'react'; import { addons, types } from '@storybook/addons';
addons.register(ADDON_ID, () => { addons.add(PANEL_ID, { title: '', type: types.TOOL, match: ({ viewMode }) => viewMode === 'story', render: () => <VisionSimulator />, }); addons.add(PANEL_ID, { title: 'Accessibility', type: types.PANEL, render: ({ active = true, key }) => ( <A1...
import { ADDON_ID, PANEL_ID, PARAM_KEY } from './constants'; import { VisionSimulator } from './components/VisionSimulator'; import { A11YPanel } from './components/A11YPanel'; import { A11yContextProvider } from './components/A11yContext';
random_line_split
toPromise.ts
import { Observable } from '../Observable'; import { root } from '../util/root'; /* tslint:disable:max-line-length */ export function toPromise<T>(this: Observable<T>): Promise<T>; export function toPromise<T>(this: Observable<T>, PromiseCtor: typeof Promise): Promise<T>; /* tslint:enable:max-line-length */ /** * 将 ...
if (root.Rx && root.Rx.config && root.Rx.config.Promise) { PromiseCtor = root.Rx.config.Promise; } else if (root.Promise) { PromiseCtor = root.Promise; } } if (!PromiseCtor) { throw new Error('no Promise impl found'); } return new PromiseCtor((resolve, reject) => { let value: a...
*/ export function toPromise<T>(this: Observable<T>, PromiseCtor?: typeof Promise): Promise<T> { if (!PromiseCtor) {
random_line_split
toPromise.ts
import { Observable } from '../Observable'; import { root } from '../util/root'; /* tslint:disable:max-line-length */ export function toPromise<T>(this: Observable<T>): Promise<T>; export function toPromise<T>(this: Observable<T>, PromiseCtor: typeof Promise): Promise<T>; /* tslint:enable:max-line-length */ /** * 将 ...
if (!PromiseCtor) { throw new Error('no Promise impl found'); } return new PromiseCtor((resolve, reject) => { let value: any; this.subscribe((x: T) => value = x, (err: any) => reject(err), () => resolve(value)); }); }
identifier_body
toPromise.ts
import { Observable } from '../Observable'; import { root } from '../util/root'; /* tslint:disable:max-line-length */ export function toPromise<T>(this: Observable<T>): Promise<T>; export function toPromise<T>(this: Observable<T>, PromiseCtor: typeof Promise): Promise<T>; /* tslint:enable:max-line-length */ /** * 将 ...
if (root.Promise) { PromiseCtor = root.Promise; } } if (!PromiseCtor) { throw new Error('no Promise impl found'); } return new PromiseCtor((resolve, reject) => { let value: any; this.subscribe((x: T) => value = x, (err: any) => reject(err), () => resolve(value)); }); }
} else
identifier_name
toPromise.ts
import { Observable } from '../Observable'; import { root } from '../util/root'; /* tslint:disable:max-line-length */ export function toPromise<T>(this: Observable<T>): Promise<T>; export function toPromise<T>(this: Observable<T>, PromiseCtor: typeof Promise): Promise<T>; /* tslint:enable:max-line-length */ /** * 将 ...
, () => resolve(value)); }); }
throw new Error('no Promise impl found'); } return new PromiseCtor((resolve, reject) => { let value: any; this.subscribe((x: T) => value = x, (err: any) => reject(err)
conditional_block
gridSearch.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "Ponzoni, Nelson" __copyright__ = "Copyright 2015" __credits__ = ["Ponzoni Nelson"] __maintainer__ = "Ponzoni Nelson" __contact__ = "npcuadra@gmail.com" __email__ = "npcuadra@gmail.com" __license__ = "GPL" __version__ = "1.0.0" _...
return out raise IndexError('ParameterGrid index out of range') if __name__ == '__main__': param_grid = {'a': [1, 2], 'b': [True, False]} a = ParameterGrid(param_grid) print(list(a)) print(len(a)) print(a[1]) print(a)
if not sub_grid: if ind == 0: return {} else: ind -= 1 continue # Reverse so most frequent cycling parameter comes first keys, values_lists = zip(*sorted(sub_grid.items())[::-1]) sizes = [len...
conditional_block
gridSearch.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "Ponzoni, Nelson" __copyright__ = "Copyright 2015" __credits__ = ["Ponzoni Nelson"] __maintainer__ = "Ponzoni Nelson" __contact__ = "npcuadra@gmail.com" __email__ = "npcuadra@gmail.com" __license__ = "GPL" __version__ = "1.0.0" _...
# Reverse so most frequent cycling parameter comes first keys, values_lists = zip(*sorted(sub_grid.items())[::-1]) sizes = [len(v_list) for v_list in values_lists] total = np.product(sizes) if ind >= total: # Try the next grid ...
"""Get the parameters that would be ``ind``th in iteration Parameters ---------- ind : int The iteration index Returns ------- params : dict of string to any Equal to list(self)[ind] """ # This is used to make discrete sampling with...
identifier_body
gridSearch.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "Ponzoni, Nelson" __copyright__ = "Copyright 2015" __credits__ = ["Ponzoni Nelson"] __maintainer__ = "Ponzoni Nelson" __contact__ = "npcuadra@gmail.com" __email__ = "npcuadra@gmail.com" __license__ = "GPL" __version__ = "1.0.0" _...
class ParameterGrid(object): """Grid of parameters with a discrete number of values for each. Can be used to iterate over parameter value combinations with the Python built-in function iter. Read more in the :ref:`User Guide <grid_search>`. Parameters ---------- param_grid : dict of string ...
import numpy as np
random_line_split
gridSearch.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "Ponzoni, Nelson" __copyright__ = "Copyright 2015" __credits__ = ["Ponzoni Nelson"] __maintainer__ = "Ponzoni Nelson" __contact__ = "npcuadra@gmail.com" __email__ = "npcuadra@gmail.com" __license__ = "GPL" __version__ = "1.0.0" _...
(self, param_grid): if isinstance(param_grid, Mapping): # wrap dictionary in a singleton list to support either dict # or list of dicts param_grid = [param_grid] self.param_grid = param_grid def __iter__(self): """Iterate over the points in the grid. ...
__init__
identifier_name
template.js
// The loader should handle relative and git url var BookLoader = nunjucks.Loader.extend({ async: true, init: function(book) { this.book = book; }, getSource: function(fileurl, callback) { var that = this; git.resolveFile(fileurl) .then(function(filepath) { ...
{ if (_.isString(blk)) blk = { body: blk }; return blk; }
identifier_body
template.js
(blk) { if (_.isString(blk)) blk = { body: blk }; return blk; } // The loader should handle relative and git url var BookLoader = nunjucks.Loader.extend({ async: true, init: function(book) { this.book = book; }, getSource: function(fileurl, callback) { var that = this; ...
normBlockResult
identifier_name
template.js
Read file from absolute path return fs.readFile(filepath) .then(function(source) { return { src: source.toString(), path: filepath } }); }) .nodeify(callback); }, resolve: function(from,...
args: [], kwargs: {}, blocks: [] }); // Bind and call block processor func = this.bindContext(block.process); r = func.call(context, blk); if (Q.isPromise(r)) return r.then(normBlockResult); else return normBlockResult(r); }; // Apply a shortcut to a string TemplateEng...
random_line_split
template.js
Read file from absolute path return fs.readFile(filepath) .then(function(source) { return { src: source.toString(), path: filepath } }); }) .nodeify(callback); }, resolve: function(from,...
blk = _.defaults(blk, { args: [], kwargs: {}, blocks: [] }); // Bind and call block processor func = this.bindContext(block.process); r = func.call(context, blk); if (Q.isPromise(r)) return r.then(normBlockResult); else return normBlockResult(r); }; // Apply a sh...
{ blk = { body: blk }; }
conditional_block
process.py
# # Copyright (C) 2011 by Brian Weck # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php # import pymongo, time from . import log, config, reddit, queue import utils # # match configured magic words by author or by mod # class Matcher: matched_items = [] # def __init__(se...
# if the comment has replies, _walk_ds that next. if "replies" in thing["data"]: return self._walk_ds(thing["data"]["replies"], authorized_authors) return False # otherwise, say no. self.log.debug("skipping %s", thing) return False # # # def che...
return True
conditional_block
process.py
# # Copyright (C) 2011 by Brian Weck # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php # import pymongo, time from . import log, config, reddit, queue import utils # # match configured magic words by author or by mod # class Matcher: matched_items = [] # def __init__(se...
(self, thing): #print "%s..." % (thing["data"]["selftext"])[0:25] return self._magic_word_in(thing["data"]["selftext"]) # # check to see if a comment is matched # def _is_matched_t1(self, thing, authorized_authors): #print "%s..." % (thing["data"]["body"])[0:25] is_mw = self._magic...
_is_matched_t3
identifier_name
process.py
# # Copyright (C) 2011 by Brian Weck # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php # import pymongo, time from . import log, config, reddit, queue import utils # # match configured magic words by author or by mod # class Matcher: matched_items = [] # def __init__(se...
# # # def run(self): threads = self.queue.next({"data.subreddit":self.subreddit}) #, "data.matched":"N"}) #matched items are dequeued, no need to filter. self.check_items(threads)
if self.matched_items: return True return False
identifier_body
process.py
# # Copyright (C) 2011 by Brian Weck # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php # import pymongo, time from . import log, config, reddit, queue import utils # # match configured magic words by author or by mod # class Matcher: matched_items = [] # def __init__(sel...
# check for matched/unmatched if self._walk_ds(resp[0], authorized_authors) or self._walk_ds(resp[1], authorized_authors): self.log.info("id:%s MATCHED", thread["data"]["id"]) # thread["data"]["matched"] = "Y" thread["data"]["matched_ts"] = int(time.time()) sel...
return False
random_line_split
streamingfreetv.py
# -*- coding: utf-8 -*- #------------------------------------------------------------ # MonsterTV Regex de streamingfreetv # Version 0.1 (17.10.2014) #------------------------------------------------------------ # License: GPL (http://www.gnu.org/licenses/gpl-3.0.html) # Gracias a la librería plugintools de Jesús (www....
def gethttp_referer_headers(url_user): pageurl = url_user.get("pageurl") referer = url_user.get("referer") print 'referer',referer request_headers=[] request_headers.append(["User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safar...
est_headers=[] request_headers.append(["User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31"]) request_headers.append(["Referer", pageurl]) body,response_headers = plugintools.read_body_and_headers(pageurl, headers=request_head...
identifier_body
streamingfreetv.py
# -*- coding: utf-8 -*- #------------------------------------------------------------ # MonsterTV Regex de streamingfreetv # Version 0.1 (17.10.2014) #------------------------------------------------------------ # License: GPL (http://www.gnu.org/licenses/gpl-3.0.html) # Gracias a la librería plugintools de Jesús (www....
plugintools.log("URL_user dict= "+repr(url_user)) pageurl = url_user.get("pageurl") body = gethttp_headers(pageurl) plugintools.log("body= "+body) #<script type='text/javascript'> width=650, height=400, channel='sysf', e='1';</script><script type='text/javascript' src='http://privado.streaming...
entry.startswith("rtmp"): entry = entry.replace("rtmp=", "") url_user["rtmp"]=entry elif entry.startswith("playpath"): entry = entry.replace("playpath=", "") url_user["playpath"]=entry elif entry.startswith("swfUrl"): entr...
conditional_block
streamingfreetv.py
# -*- coding: utf-8 -*- #------------------------------------------------------------ # MonsterTV Regex de streamingfreetv # Version 0.1 (17.10.2014) #------------------------------------------------------------ # License: GPL (http://www.gnu.org/licenses/gpl-3.0.html) # Gracias a la librería plugintools de Jesús (www....
src=plugintools.find_single_match(pattern, 'src=(.*?) ') #http://privado.streamingfreetv.net/embed/embed.php?channel=sysf&w=650&h=400 pageurl = 'http://privado.streamingfreetv.net/embed/embed.php?channel='+playpath+'&w='+width+'&h='+height plugintools.log("pageurl= "+pageurl) url_user["pageurl"...
playpath = url_user.get("playpath")
random_line_split
streamingfreetv.py
# -*- coding: utf-8 -*- #------------------------------------------------------------ # MonsterTV Regex de streamingfreetv # Version 0.1 (17.10.2014) #------------------------------------------------------------ # License: GPL (http://www.gnu.org/licenses/gpl-3.0.html) # Gracias a la librería plugintools de Jesús (www....
_user): pageurl = url_user.get("pageurl") referer = url_user.get("referer") print 'referer',referer request_headers=[] request_headers.append(["User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31"]) request_headers...
ttp_referer_headers(url
identifier_name
rita.py
# coding: utf-8 """ rita Pipeline .. module:: rita :synopsis: rita pipeline .. moduleauthor:: Adolfo De Unánue <nanounanue@gmail.com> """ import os import subprocess from pathlib import Path import boto3 import zipfile import io import csv import datetime import luigi import luigi.s3 import pandas as pd ...
: return RawData() def run(self): cmd = ''' docker run --rm -v rita_store:/rita/data rita/test-r ''' logger.debug(cmd) out = subprocess.check_output(cmd, shell=True) logger.debug(out) def output(self): return luigi.LocalTarget(os.path....
es(self)
identifier_name
rita.py
# coding: utf-8 """ rita Pipeline .. module:: rita :synopsis: rita pipeline .. moduleauthor:: Adolfo De Unánue <nanounanue@gmail.com> """ import os import subprocess from pathlib import Path import boto3 import zipfile import io import csv import datetime import luigi import luigi.s3 import pandas as pd ...
def output(self): output_path = '{}/catalogs/{}.csv'.format(self.root_path, self.catalog_name) return luigi.s3.S3Target(path=output_path) class DownloadRITAData(luigi.WrapperTask): """ """ start_year=luigi.IntParameter() def requi...
tput_file.write(chunk.decode('utf-8') + '\n')
conditional_block
rita.py
# coding: utf-8 """ rita Pipeline .. module:: rita :synopsis: rita pipeline .. moduleauthor:: Adolfo De Unánue <nanounanue@gmail.com> """ import os import subprocess from pathlib import Path import boto3 import zipfile import io import csv import datetime import luigi import luigi.s3 import pandas as pd ...
logger.debug("Guardando en {} el catálogo {}".format(self.output().path, self.catalog_name)) with closing(requests.get(self.catalog_url, stream= True)) as response, \ self.output().open('w') as output_file: for chunk in response.iter_lines(chunk_size=1024*8): if...
random_line_split
rita.py
# coding: utf-8 """ rita Pipeline .. module:: rita :synopsis: rita pipeline .. moduleauthor:: Adolfo De Unánue <nanounanue@gmail.com> """ import os import subprocess from pathlib import Path import boto3 import zipfile import io import csv import datetime import luigi import luigi.s3 import pandas as pd ...
class DownloadRITACatalogs(luigi.WrapperTask): """ """ def requires(self): baseurl = "https://www.transtats.bts.gov" url = "https://www.transtats.bts.gov/DL_SelectFields.asp?Table_ID=236" page = requests.get(url) soup = BeautifulSoup(page.content, "lxml") for link...
ield DownloadRITACatalogs() yield DownloadRITAData()
identifier_body
axios-interceptor.ts
import { sproutApiSvc } from '../core/services/sproutApiSvc'; const setupAxiosInterceptors = (onUnauthenticated: any) => { const onRequestSuccess = (config: any) => { // moved JWT out - only need to send it once now, and get a signed session cookie, instead of passing it with every request. // This makes it ...
export default setupAxiosInterceptors;
sproutApiSvc.interceptors.response.use(onResponseSuccess, onResponseError); sproutApiSvc.interceptors.request.use(onRequestSuccess); };
random_line_split
axios-interceptor.ts
import { sproutApiSvc } from '../core/services/sproutApiSvc'; const setupAxiosInterceptors = (onUnauthenticated: any) => { const onRequestSuccess = (config: any) => { // moved JWT out - only need to send it once now, and get a signed session cookie, instead of passing it with every request. // This makes it ...
return Promise.reject(err); }; sproutApiSvc.interceptors.response.use(onResponseSuccess, onResponseError); sproutApiSvc.interceptors.request.use(onRequestSuccess); }; export default setupAxiosInterceptors;
{ console.log('unauthenticated request', err); onUnauthenticated(); }
conditional_block
start.js
learConsole'); var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); var openBrowser = require('react-dev-utils/openBrowser'); var prompt = require('react-dev-utils/prompt'); var config = require('../config/webpack.config.de...
(proxy) { return function(err, req, res){ var host = req.headers && req.headers.host; console.log( chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url) + ' from ' + chalk.cyan(host) + ' to ' + chalk.cyan(proxy) + '.' ); console.log( 'See https://nodejs.org/ap...
onProxyError
identifier_name
start.js
Console'); var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); var openBrowser = require('react-dev-utils/openBrowser'); var prompt = require('react-dev-utils/prompt'); var config = require('../config/webpack.config.dev');...
}); } // We need to provide a custom onError function for httpProxyMiddleware. // It allows us to log custom error messages on the console. function onProxyError(proxy) { return function(err, req, res){ var host = req.headers && req.headers.host; console.log( chalk.red('Proxy error:') + ' Could not ...
{ console.log(chalk.yellow('Compiled with warnings.')); console.log(); messages.warnings.forEach(message => { console.log(message); console.log(); }); // Teach some ESLint tricks. console.log('You may use special comments to disable some warnings.'); console.log...
conditional_block
start.js
Console'); var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); var openBrowser = require('react-dev-utils/openBrowser'); var prompt = require('react-dev-utils/prompt'); var config = require('../config/webpack.config.dev');...
// for the WebpackDevServer client so it can learn when the files were // updated. The WebpackDevServer client is included as an entry point // in the Webpack development configuration. Note that only changes // to CSS are currently hot reloaded. JS changes will refresh the browser. hot: true, /...
r devServer = new WebpackDevServer(compiler, { // Silence WebpackDevServer's own logs since they're generally not useful. // It will still show compile warnings and errors with this setting. clientLogLevel: 'none', // By default WebpackDevServer serves physical files from current directory // in add...
identifier_body
start.js
learConsole'); var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); var openBrowser = require('react-dev-utils/openBrowser'); var prompt = require('react-dev-utils/prompt'); var config = require('../config/webpack.config.de...
// Otherwise, if proxy is specified, we will let it handle any request. // There are a few exceptions which we won't send to the proxy: // - /index.html (served as HTML5 history API fallback) // - /*.hot-update.json (WebpackDevServer uses this too for hot reloading) // - /sockjs-node/* (WebpackDevS...
console.log(chalk.red('When specified, "proxy" in package.json must be a string.')); console.log(chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".')); console.log(chalk.red('Either remove "proxy" from package.json, or make it a string.')); process.exit(1); }
random_line_split
employees.js
function randomEmpoyees() { var rdm = []; var allTeams = ["business", "tech", "admin", "com", "integ", "presta"]; function
(start, end) { return new Date( start.getTime() + Math.random() * (end.getTime() - start.getTime()) ); } function randomTeam() { return allTeams[Math.floor(Math.random() * allTeams.length)]; } function randomName() { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcd...
randomDate
identifier_name
employees.js
function randomEmpoyees() { var rdm = []; var allTeams = ["business", "tech", "admin", "com", "integ", "presta"]; function randomDate(start, end) { return new Date( start.getTime() + Math.random() * (end.getTime() - start.getTime()) ); } function randomTeam() { return allTeams[Math.floor(...
var today = new Date(); var turnoverRatio = 0.6; for (i = 0; i < 50; i++) { var randomStart = randomDate(new Date(2012, 01, 01), today); var randomEnd = randomDate(randomStart, today); if (Math.random() > turnoverRatio) { randomEnd = null; } rdm.push({ name: randomName(), ...
{ var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < 6; i++) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; }
identifier_body
employees.js
function randomEmpoyees() { var rdm = []; var allTeams = ["business", "tech", "admin", "com", "integ", "presta"]; function randomDate(start, end) { return new Date( start.getTime() + Math.random() * (end.getTime() - start.getTime()) ); } function randomTeam() { return allTeams[Math.floor(...
rdm.push({ name: randomName(), team: randomTeam(), from: randomStart, to: randomEnd }); } return rdm; } var mainURL = getParameterByName("url"); //retreive data from url if (mainURL && window.fetch) { var url = atob(mainURL) + "/people.json"; fetch(url) .then(function(respo...
{ randomEnd = null; }
conditional_block
employees.js
function randomEmpoyees() { var rdm = []; var allTeams = ["business", "tech", "admin", "com", "integ", "presta"]; function randomDate(start, end) { return new Date( start.getTime() + Math.random() * (end.getTime() - start.getTime()) ); } function randomTeam() { return allTeams[Math.floor(...
} else { //default : display random displayLazy(randomEmpoyees()); }
console.log("Parsing failed", ex); display(randomEmpoyees()); });
random_line_split
util.js
// @flow // noinspection JSUnusedGlobalSymbols export function replaceLn(text: string): Promise<void> { const CLEAR = '\r\x1B[2K\x1B[?7l'; return print(CLEAR + text); } export function printLn(text: string = ''): Promise<void> { return print(text + '\n'); } function print(text: string): Promise<void> { retur...
}, delayMs); await func(); clearInterval(id); await loop(); } let nextCid = 1; export function newCid(): number { return nextCid++; } // noinspection JSUnusedGlobalSymbols export function groupBy<Tk, Tv>( items: Iterable<Tv>, fn: Tv => Tk, ): Map<Tk, Tv[]> { let map = new Map(); for (let item of it...
{ running = true; await loop(); running = false; }
conditional_block
util.js
// @flow // noinspection JSUnusedGlobalSymbols export function replaceLn(text: string): Promise<void> { const CLEAR = '\r\x1B[2K\x1B[?7l'; return print(CLEAR + text); } export function printLn(text: string = ''): Promise<void> { return print(text + '\n'); } function print(text: string): Promise<void> { retur...
let nextCid = 1; export function newCid(): number { return nextCid++; } // noinspection JSUnusedGlobalSymbols export function groupBy<Tk, Tv>( items: Iterable<Tv>, fn: Tv => Tk, ): Map<Tk, Tv[]> { let map = new Map(); for (let item of items) { let key = fn(item); let arr = map.get(key); if (arr...
{ let running = false; let id = setInterval(async () => { if (!running) { running = true; await loop(); running = false; } }, delayMs); await func(); clearInterval(id); await loop(); }
identifier_body
util.js
// @flow // noinspection JSUnusedGlobalSymbols export function replaceLn(text: string): Promise<void> { const CLEAR = '\r\x1B[2K\x1B[?7l'; return print(CLEAR + text); } export function printLn(text: string = ''): Promise<void> { return print(text + '\n'); } function print(text: string): Promise<void> { retur...
(): number { return nextCid++; } // noinspection JSUnusedGlobalSymbols export function groupBy<Tk, Tv>( items: Iterable<Tv>, fn: Tv => Tk, ): Map<Tk, Tv[]> { let map = new Map(); for (let item of items) { let key = fn(item); let arr = map.get(key); if (arr === undefined) { map.set(key, [ite...
newCid
identifier_name
util.js
// @flow // noinspection JSUnusedGlobalSymbols export function replaceLn(text: string): Promise<void> { const CLEAR = '\r\x1B[2K\x1B[?7l'; return print(CLEAR + text); } export function printLn(text: string = ''): Promise<void> { return print(text + '\n'); } function print(text: string): Promise<void> { retur...
}); } export function formatBytes(n: number): string { const {floor, pow, max, abs, log} = Math; let i = floor(log(max(abs(n), 1)) / log(1000)); return i === 0 ? formatNumber(n, 0) + ' B' : formatNumber(n / pow(1000, i), 2) + ' ' + ' KMGTPEZY'[i] + 'B'; } function roundDown(number: number, precision: ...
random_line_split
jquery.centershow.js
/*! jQuery centershow - v1.0.0 - 2014-12-19 * Copyright (c) 2014 kssfilo; Licensed MIT */ (function($){ $.fn.centershow=function(){ var back=$('<div onclick="$(this).hide()" style="position:fixed;top:0;left:0;width:100%;height:100%;background-color:rgba(0,0,0,0.8);">'); $('body').append(back); var close=$('<...
'top':'50%', 'left':'50%', 'margin-left':-self.width()/2, 'margin-top':-self.height()/2, 'z-index':1, }); self.appendTo(back); }); }; })(jQuery);
random_line_split
my-page.component.ts
import { Component, OnInit } from '@angular/core'; import { User, UserService, Profile } from '../shared'; import { ActivatedRoute, Route, Router } from "@angular/router"; import { ProfilesService } from "../shared/services/profiles.service"; import { ArticlesService } from "../shared/services/articles.service"; import...
implements OnInit { profile: Profile = new Profile(); currentUser: User; isUser: boolean; username: String; query: ArticleListConfig; articles: Article[]; constructor(private router: Router, private route: ActivatedRoute, private userService: UserService, private profilesService: ProfilesService, private art...
MyPageComponent
identifier_name
my-page.component.ts
import { Component, OnInit } from '@angular/core'; import { User, UserService, Profile } from '../shared'; import { ActivatedRoute, Route, Router } from "@angular/router"; import { ProfilesService } from "../shared/services/profiles.service"; import { ArticlesService } from "../shared/services/articles.service"; import...
.subscribe( data => { console.log( 'data', data ); this.articles = data.articles; } ) }, err => { console.log( 'ERROR!' ); this.router.navigateByUrl( '/' ) } ); }); } }
{ this.route.params.subscribe((params:any) => { this.username = params['username']; console.log('this.username', params.username); this.profilesService .get(params.username) .subscribe( data => { console.log('got profile', data); this.profile = data; this.query = ne...
identifier_body
my-page.component.ts
import { Component, OnInit } from '@angular/core'; import { User, UserService, Profile } from '../shared'; import { ActivatedRoute, Route, Router } from "@angular/router"; import { ProfilesService } from "../shared/services/profiles.service"; import { ArticlesService } from "../shared/services/articles.service"; import...
console.log('this.username', params.username); this.profilesService .get(params.username) .subscribe( data => { console.log('got profile', data); this.profile = data; this.query = new ArticleListConfig(); this.query.type = 'all'; this.query.filters = { ...
ngOnInit() { this.route.params.subscribe((params:any) => { this.username = params['username'];
random_line_split
app.component.spec.ts
import { Component, Injectable } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing'; import { Router } from '@angular/router'; import { RouterTestingModule } from '@angular/rout...
else if (route.component === NotificationComponent) { route.component = MockNotificationComponent; } return route; })); router.initialNavigation(); fixture.detectChanges(); })); beforeEach(() => { fixture.detectChanges(); }); it('should create the app', () => { expect...
{ route.component = MockLoginComponent; }
conditional_block
app.component.spec.ts
import { Component, Injectable } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing'; import { Router } from '@angular/router'; import { RouterTestingModule } from '@angular/rout...
{} @Injectable() class MockAuthGuard { canActivate() { return true; } }; describe('AppComponent', () => { let fixture: ComponentFixture<AppComponent>; let app: AppComponent; let router: Router; let store: jasmine.SpyObj<Store>; beforeEach(fakeAsync(() => { store = jasmine.createSpyObj('Store', ['di...
MockNotificationComponent
identifier_name
app.component.spec.ts
import { Component, Injectable } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing'; import { Router } from '@angular/router'; import { RouterTestingModule } from '@angular/rout...
expect(links.map(link => link.pathname)).toEqual([ '/projects', '/datasets', '/analyses', '/api', ]); }); it('should display LoginComponent if the route starts with /login', fakeAsync(() => { router.navigateByUrl('/login#test'); tick(); const component = debugComponent(fixture, MockLoginC...
const links = selectElements(fixture, 'nav a'); expect(links.map(link => link.textContent.trim())).toEqual([ 'Projects', 'Datasets', 'Analyses', 'API', ]);
random_line_split
_helper.js
.appInfo.ID == "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}") { this.usingCUI = true; } }, log: function (ex) { if (this.prefService.getBranch("extensions.aios.").getBoolPref("logging")) this.consoleService.logStringMessage("TGS: " + ex); }, rememberAppInfo: function...
} // If the tab is empty if (emptyTab != null) { // Open URL and select tab browser.getBrowserAtIndex(emptyTab).contentWindow.document.location.href = aUrl; browser.selectedTab = browser.tabContainer.childNodes[emptyTab]; browser.selectedTab.setAttribute("openBy", "aios"); ...
random_line_split
_helper.js
var isPermaTab = (browser.tabContainer.childNodes[i].getAttribute("isPermaTab")) ? true : false; // If the tab is empty if (browserDoc.location.href == "about:blank" && browser.selectedTab.getAttribute("openBy") != "aios" && !isPermaTab && emptyTab == null) emptyTab = i; //...
{ var child_str, child; if (childElems != "") { var childElems_arr = childElems.split(","); for (var i = 0; i < childElems_arr.length; i++) { child_str = childElems_arr[i].replace(/ /, ""); var idChilds_arr = document.getElementsByAttribute("id", child_str); ...
identifier_body
_helper.js
.appInfo.ID == "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}") { this.usingCUI = true; } }, log: function (ex) { if (this.prefService.getBranch("extensions.aios.").getBoolPref("logging")) this.consoleService.logStringMessage("TGS: " + ex); }, rememberAppInfo: function...
(aURI, aBefore) { var path = "chrome://aios/skin/"; var elem = (typeof aBefore == "object") ? aBefore : document.getElementById(aBefore); var css = document.createProcessingInstruction("xml-stylesheet", "href=\"" + path + aURI + "\" type=\"text/css\""); document.insertBefore(css, elem); } /* * Calcu...
aios_addCSS
identifier_name
_helper.js
Info.ID == "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}") { this.usingCUI = true; } }, log: function (ex) { if (this.prefService.getBranch("extensions.aios.").getBoolPref("logging")) this.consoleService.logStringMessage("TGS: " + ex); }, rememberAppInfo: function (aO...
// If the tab is empty if (emptyTab != null) { // Open URL and select tab browser.getBrowserAtIndex(emptyTab).contentWindow.document.location.href = aUrl; browser.selectedTab = browser.tabContainer.childNodes[emptyTab]; browser.selectedTab.setAttribute("openBy", "aios"); ...
{ browser.selectedTab = browser.tabContainer.childNodes[existTab]; return browser.selectedTab; }
conditional_block
compare.js
import Ember from "ember-metal/core"; // for Ember.ORDER_DEFINITION import {typeOf} from "ember-metal/utils"; import Comparable from "ember-runtime/mixins/comparable"; // Used by Ember.compare Ember.ORDER_DEFINITION = Ember.ENV.ORDER_DEFINITION || [ 'undefined', 'null', 'boolean', 'number', 'string', 'arr...
// If we haven't yet generated a reverse-mapping of Ember.ORDER_DEFINITION, // do so now. var mapping = Ember.ORDER_DEFINITION_MAPPING; if (!mapping) { var order = Ember.ORDER_DEFINITION; mapping = Ember.ORDER_DEFINITION_MAPPING = {}; var idx, len; for (idx = 0, len = order.length; idx < len; ...
{ if (type1==='instance' && Comparable.detect(v.constructor)) { return v.constructor.compare(v, w); } if (type2 === 'instance' && Comparable.detect(w.constructor)) { return 1-w.constructor.compare(w, v); } }
conditional_block
compare.js
import Ember from "ember-metal/core"; // for Ember.ORDER_DEFINITION import {typeOf} from "ember-metal/utils"; import Comparable from "ember-runtime/mixins/comparable"; // Used by Ember.compare Ember.ORDER_DEFINITION = Ember.ENV.ORDER_DEFINITION || [ 'undefined', 'null', 'boolean', 'number', 'string', 'arr...
(v, w) { if (v === w) { return 0; } var type1 = typeOf(v); var type2 = typeOf(w); if (Comparable) { if (type1==='instance' && Comparable.detect(v.constructor)) { return v.constructor.compare(v, w); } if (type2 === 'instance' && Comparable.detect(w.constructor)) { return 1-w.constructo...
compare
identifier_name
compare.js
import Ember from "ember-metal/core"; // for Ember.ORDER_DEFINITION import {typeOf} from "ember-metal/utils"; import Comparable from "ember-runtime/mixins/comparable"; // Used by Ember.compare Ember.ORDER_DEFINITION = Ember.ENV.ORDER_DEFINITION || [ 'undefined', 'null', 'boolean', 'number', 'string', 'arr...
var order = Ember.ORDER_DEFINITION; mapping = Ember.ORDER_DEFINITION_MAPPING = {}; var idx, len; for (idx = 0, len = order.length; idx < len; ++idx) { mapping[order[idx]] = idx; } // We no longer need Ember.ORDER_DEFINITION. delete Ember.ORDER_DEFINITION; } var type1Index = mapp...
{ if (v === w) { return 0; } var type1 = typeOf(v); var type2 = typeOf(w); if (Comparable) { if (type1==='instance' && Comparable.detect(v.constructor)) { return v.constructor.compare(v, w); } if (type2 === 'instance' && Comparable.detect(w.constructor)) { return 1-w.constructor.compa...
identifier_body
compare.js
import Ember from "ember-metal/core"; // for Ember.ORDER_DEFINITION import {typeOf} from "ember-metal/utils"; import Comparable from "ember-runtime/mixins/comparable"; // Used by Ember.compare Ember.ORDER_DEFINITION = Ember.ENV.ORDER_DEFINITION || [ 'undefined', 'null', 'boolean', 'number', 'string', 'arr...
if (type1Index > type2Index) { return 1; } // types are equal - so we have to check values now switch (type1) { case 'boolean': case 'number': if (v < w) { return -1; } if (v > w) { return 1; } return 0; case 'string': var comp = v.localeCompare(w); if (comp < 0) { retu...
var type1Index = mapping[type1]; var type2Index = mapping[type2]; if (type1Index < type2Index) { return -1; }
random_line_split
split.js
var _ = typeof Frame5 === 'object' if (!_) { /*** * Node modules */ var EventEmitter = require('events').EventEmitter; var Stream = require('stream'); var inherits = require('util').inherits; // exports = module.exports = {} } else { var EventEmitter = Frame5.EventEmitter; var Stream = Frame5.Stream; v...
} else { this.buffer.push(str); } } /** * */ Read.prototype.end = function(str) { if (str) { this.write(str) } this.emit('end') }; /** * */ var Write = exports.Write = function() { Stream.call(this); this.buffer = [] this.readable = this.writable = true; } /*** * Make it an event */ inherits(Write...
{ this.write(data); }
conditional_block
split.js
var _ = typeof Frame5 === 'object' if (!_) { /*** * Node modules */ var EventEmitter = require('events').EventEmitter; var Stream = require('stream'); var inherits = require('util').inherits; // exports = module.exports = {} } else { var EventEmitter = Frame5.EventEmitter; var Stream = Frame5.Stream; v...
* */ var Read = exports.Read = function() { Stream.call(this); this.buffer = [] this.readable = this.writable = true; } /*** * Make it an event */ inherits(Read, Stream); /** * */ Read.prototype.write = function(str) { ////console.log('split.Read', str) if (str.indexOf('\n') > -1) { var message = this....
random_line_split
types.rs
use vecmath::{self, vec2_sub, vec2_len}; pub type Scalar = f64; /// [width, height] pub type Extent = vecmath::Vector2<Scalar>; /// [x, y] pub type Position = vecmath::Vector2<Scalar>; pub type Velocity = vecmath::Vector2<Scalar>; use transition::Transition; /// Points on screen. Usually they correspond to pixels, ...
_ => { self.left() <= other.right() && self.right() >= other.left() && self.top() <= other.bottom() && self.bottom() >= other.top() } } } } #[derive(Debug, Clone, PartialEq)] pub enum ObstacleKind { /// Enables a temporary attractive force At...
{ vec2_len(vec2_sub(self.pos, other.pos)) <= self.half_size + other.half_size }
conditional_block
types.rs
use vecmath::{self, vec2_sub, vec2_len}; pub type Scalar = f64; /// [width, height] pub type Extent = vecmath::Vector2<Scalar>; /// [x, y] pub type Position = vecmath::Vector2<Scalar>; pub type Velocity = vecmath::Vector2<Scalar>; use transition::Transition; /// Points on screen. Usually they correspond to pixels, ...
{ /// Enables a temporary attractive force AttractiveForceSwitch, /// Causes all other obstacles to hide themselves for a while InvisibiltySwitch, /// Kills the player Deadly, } /// An obstacle the hunter can collide with #[derive(Debug, Clone, PartialEq)] pub struct Obstacle { pub kind: O...
ObstacleKind
identifier_name
types.rs
use vecmath::{self, vec2_sub, vec2_len}; pub type Scalar = f64; /// [width, height] pub type Extent = vecmath::Vector2<Scalar>; /// [x, y] pub type Position = vecmath::Vector2<Scalar>; pub type Velocity = vecmath::Vector2<Scalar>; use transition::Transition; /// Points on screen. Usually they correspond to pixels, ...
pub fn top(&self) -> Scalar { self.pos[1] - self.half_size } pub fn bottom(&self) -> Scalar { self.pos[1] + self.half_size } /// Returns true if both objects intersect pub fn intersects(&self, other: &Object) -> bool { match (&self.shape, &other.shape) { (&...
}
random_line_split
gallery_generator.py
image:: {img_file} **Python source code:** :download:`[download source: {fname}]<{fname}>` .. raw:: html <div class="col-md-9"> .. literalinclude:: {fname} :lines: {end_line}- .. raw:: html </div> """ INDEX_TEMPLATE = """ .. raw:: html <style type="text/css"> .figure {{ position:...
@property def modulename(self): return op.splitext(self.fname)[0] @property def pyfilename(self): return self.modulename + '.py' @property def rstfilename(self): return self.modulename + ".rst" @property def htmlfilename(self): return self.modulename ...
return op.split(self.filename)[1]
identifier_body
gallery_generator.py
image:: {img_file} **Python source code:** :download:`[download source: {fname}]<{fname}>` .. raw:: html <div class="col-md-9"> .. literalinclude:: {fname} :lines: {end_line}- .. raw:: html </div> """ INDEX_TEMPLATE = """ .. raw:: html <style type="text/css"> .figure {{ position:...
Example gallery =============== {toctree} {contents} .. raw:: html <div style="clear: both"></div> """ def create_thumbnail(infile, thumbfile, width=275, height=275, cx=0.5, cy=0.5, border=4): baseout, extout = op.splitext(thumbfile) im = image.imread(infile...
.. _{sphinx_tag}:
random_line_split
gallery_generator.py
image:: {img_file} **Python source code:** :download:`[download source: {fname}]<{fname}>` .. raw:: html <div class="col-md-9"> .. literalinclude:: {fname} :lines: {end_line}- .. raw:: html </div> """ INDEX_TEMPLATE = """ .. raw:: html <style type="text/css"> .figure {{ position:...
(self): return self.modulename + '.py' @property def rstfilename(self): return self.modulename + ".rst" @property def htmlfilename(self): return self.modulename + '.html' @property def pngfilename(self): pngfile = self.modulename + '.png' return "_image...
pyfilename
identifier_name
gallery_generator.py
image:: {img_file} **Python source code:** :download:`[download source: {fname}]<{fname}>` .. raw:: html <div class="col-md-9"> .. literalinclude:: {fname} :lines: {end_line}- .. raw:: html </div> """ INDEX_TEMPLATE = """ .. raw:: html <style type="text/css"> .figure {{ position:...
self.docstring = docstring self.short_desc = first_par self.end_line = erow + 1 + start_row def exec_file(self): print("running {0}".format(self.filename)) plt.close('all') my_globals = {'pl': plt, 'plt': plt} execfile(self.filename, ...
self.thumbloc = thumbloc docstring = "\n".join([l for l in docstring.split("\n") if not l.startswith("_thumb")])
conditional_block
lib.rs
Error(..) => (), } expr } fn transform_errors<'a, Iter>( source_span: Span<BytePos>, errors: Iter, ) -> Errors<Spanned<Error, BytePos>> where Iter: IntoIterator<Item = LalrpopError<'a>>, { errors .into_iter() .map(|err| Error::from_lalrpop(source_span, err)) .collect() }...
ExtraToken { token: (lpos, token, rpos), } => pos::spanned2(lpos, rpos, Error::ExtraToken(token.map(|s| s.into()))), User { error } => error, } } } #[derive(Debug)] pub enum FieldExpr<'ast, Id> { Type( BaseMetadata<'ast>, Spanned<Id, B...
}
random_line_split
lib.rs
for $ty { fn select<'a>(vecs: &'a mut TempVecs<'ast, Id>) -> &'a mut Vec<Self> { &mut vecs.$field } } )* }; } impl_temp_vec! { SpannedExpr<'ast, Id> => exprs, SpannedPattern<'ast, Id> => patterns, ast::PatternField<'ast, Id> => pat...
{ let mut iter = s.splitn(2, ","); let fixity = match iter.next().ok_or(InfixError::InvalidFixity)?.trim() { "left" => Fixity::Left, "right" => Fixity::Right, _ => { ...
identifier_body
lib.rs
(..) => (), } expr } fn transform_errors<'a, Iter>( source_span: Span<BytePos>, errors: Iter, ) -> Errors<Spanned<Error, BytePos>> where Iter: IntoIterator<Item = LalrpopError<'a>>, { errors .into_iter() .map(|err| Error::from_lalrpop(source_span, err)) .collect() } str...
ExtraToken { token: (lpos, token, rpos), } => pos::spanned2(lpos, rpos, Error::ExtraToken(token.map(|s| s.into()))), User { error } => error, } } } #[derive(Debug)] pub enum FieldExpr<'ast, Id> { Type( BaseMetadata<'ast>, Spanned<Id, ...
{ // LALRPOP will use `Default::default()` as the location if it is unable to find // one. This is not correct for codespan as that represents "nil" so we must grab // the end from the current source instead let location = if location == BytePos::default()...
conditional_block
lib.rs
Error(..) => (), } expr } fn
<'a, Iter>( source_span: Span<BytePos>, errors: Iter, ) -> Errors<Spanned<Error, BytePos>> where Iter: IntoIterator<Item = LalrpopError<'a>>, { errors .into_iter() .map(|err| Error::from_lalrpop(source_span, err)) .collect() } struct Expected<'a>(&'a [String]); impl<'a> fmt::Di...
transform_errors
identifier_name
topic.py
""" Author: Keith Bourgoin, Emmett Butler """ __license__ = """ Copyright 2015 Parse.ly, Inc. 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 ...
def get_simple_consumer(self, consumer_group=None, use_rdkafka=False, **kwargs): """Return a SimpleConsumer of this topic :param consumer_group: The name of the consumer group to join :type consumer_group:...
if meta.leader not in brokers: raise LeaderNotAvailable() if meta.id not in self._partitions: log.debug('Adding partition %s/%s', self.name, meta.id) self._partitions[meta.id] = Partition( self, meta.id, brokers[meta.lea...
conditional_block
topic.py
""" Author: Keith Bourgoin, Emmett Butler """ __license__ = """ Copyright 2015 Parse.ly, Inc. 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 ...
def latest_available_offsets(self): """Get the latest offset for each partition of this topic.""" return self.fetch_offset_limits(OffsetType.LATEST) def update(self, metadata): """Update the Partitions with metadata about the cluster. :param metadata: Metadata for all topics ...
"""Get the earliest offset for each partition of this topic.""" return self.fetch_offset_limits(OffsetType.EARLIEST)
identifier_body
topic.py
""" Author: Keith Bourgoin, Emmett Butler """ __license__ = """ Copyright 2015 Parse.ly, Inc. 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 ...
(self): """A dictionary containing all known partitions for this topic""" return self._partitions def get_producer(self, use_rdkafka=False, **kwargs): """Create a :class:`pykafka.producer.Producer` for this topic. For a description of all available `kwargs`, see the Producer docstr...
partitions
identifier_name
topic.py
""" Author: Keith Bourgoin, Emmett Butler """ __license__ = """ Copyright 2015 Parse.ly, Inc. 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 ...
""" if not rdkafka and use_rdkafka: raise ImportError("use_rdkafka requires rdkafka to be installed") if isinstance(self._cluster.handler, GEventHandler) and use_rdkafka: raise ImportError("use_rdkafka cannot be used with gevent") Cls = rdkafka.RdKafkaProducer if ...
def get_producer(self, use_rdkafka=False, **kwargs): """Create a :class:`pykafka.producer.Producer` for this topic. For a description of all available `kwargs`, see the Producer docstring.
random_line_split
fao-api.py
VERSION='1.0' def _json_from_url(url): r = requests.get(url) if r.ok: return r.json() r.raise_for_status() def walkit(items=None,indent=0): if items is None: j = resources() items = j['result']['list']['items'] for i in items: j = resources(parentType=i['type']) ...
import requests from urllib import urlencode
random_line_split
fao-api.py
import requests from urllib import urlencode VERSION='1.0' def _json_from_url(url):
def walkit(items=None,indent=0): if items is None: j = resources() items = j['result']['list']['items'] for i in items: j = resources(parentType=i['type']) print (' '*indent) + i['label'] + " [%s] (%i)" % (i['type'],len(j['result']['list']['items'])) if len(j['result']...
r = requests.get(url) if r.ok: return r.json() r.raise_for_status()
identifier_body
fao-api.py
import requests from urllib import urlencode VERSION='1.0' def _json_from_url(url): r = requests.get(url) if r.ok: return r.json() r.raise_for_status() def walkit(items=None,indent=0): if items is None: j = resources() items = j['result']['list']['items'] for i in items: ...
def resources(**kwargs): """Make a call to the resources API. Returns a JSON object where the good stuff is at j['result']['list']['items'] """ kwargs['version'] = VERSION return _json_from_url('http://data.fao.org/developers/api/resources?' + urlencode(kwargs))
walkit(j['result']['list']['items'],indent+2)
conditional_block
fao-api.py
import requests from urllib import urlencode VERSION='1.0' def _json_from_url(url): r = requests.get(url) if r.ok: return r.json() r.raise_for_status() def walkit(items=None,indent=0): if items is None: j = resources() items = j['result']['list']['items'] for i in items: ...
(**kwargs): """Make a call to the resources API. Returns a JSON object where the good stuff is at j['result']['list']['items'] """ kwargs['version'] = VERSION return _json_from_url('http://data.fao.org/developers/api/resources?' + urlencode(kwargs))
resources
identifier_name
issue-4252.rs
// Copyright 2013 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 ...
// xfail-test trait X { fn call(&self); } struct Y; struct Z<T> { x: T } impl X for Y { fn call(&self) { } } impl<T: X> Drop for Z<T> { fn drop(&mut self) { self.x.call(); // Adding this statement causes an ICE. } } fn main() { let y = Y; let _z = Z{x: y}; }
random_line_split
issue-4252.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let y = Y; let _z = Z{x: y}; }
main
identifier_name
issue-4252.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} impl<T: X> Drop for Z<T> { fn drop(&mut self) { self.x.call(); // Adding this statement causes an ICE. } } fn main() { let y = Y; let _z = Z{x: y}; }
{ }
identifier_body