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
htmlbrelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLBRElementBinding; use dom::bindings::codegen::InheritTypes::HTMLBRElemen...
}
{ let element = HTMLBRElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLBRElementBinding::Wrap) }
identifier_body
htmlbrelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLBRElementBinding; use dom::bindings::codegen::InheritTypes::HTMLBRElemen...
{ htmlelement: HTMLElement, } impl HTMLBRElementDerived for EventTarget { fn is_htmlbrelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node( NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBRElement))) } } impl HTMLBRElement { fn...
HTMLBRElement
identifier_name
mongo.js
const MongoClient = require('mongodb').MongoClient; const config = require('./../config'); const dbName = config.DB_NAME; let currentConnection = null; async function connect() { if (currentConnection === null) { currentConnection = await MongoClient.connect(config.DB_URL, { useNewUrlParser: true, ...
(collectionName) { const collections = await currentConnection.db(dbName).listCollections().toArray(); return collections.some((collection) => collection.name === collectionName); } module.exports = { isCollectionExists, dropIfExists, findAll, insertMany, close, connect, }
isCollectionExists
identifier_name
mongo.js
const MongoClient = require('mongodb').MongoClient; const config = require('./../config'); const dbName = config.DB_NAME; let currentConnection = null; async function connect() { if (currentConnection === null)
return currentConnection; } async function close() { if (currentConnection !== null) { currentConnection.close(); currentConnection = null; } } async function insertMany(collectionName, items) { const collection = currentConnection.db(dbName).collection(collectionName); const queryResult = await ...
{ currentConnection = await MongoClient.connect(config.DB_URL, { useNewUrlParser: true, useUnifiedTopology: true, }); }
conditional_block
mongo.js
const MongoClient = require('mongodb').MongoClient; const config = require('./../config'); const dbName = config.DB_NAME; let currentConnection = null; async function connect()
async function close() { if (currentConnection !== null) { currentConnection.close(); currentConnection = null; } } async function insertMany(collectionName, items) { const collection = currentConnection.db(dbName).collection(collectionName); const queryResult = await collection.insertMany(items); ...
{ if (currentConnection === null) { currentConnection = await MongoClient.connect(config.DB_URL, { useNewUrlParser: true, useUnifiedTopology: true, }); } return currentConnection; }
identifier_body
mongo.js
const MongoClient = require('mongodb').MongoClient; const config = require('./../config'); const dbName = config.DB_NAME; let currentConnection = null; async function connect() { if (currentConnection === null) { currentConnection = await MongoClient.connect(config.DB_URL, { useNewUrlParser: true, ...
currentConnection = null; } } async function insertMany(collectionName, items) { const collection = currentConnection.db(dbName).collection(collectionName); const queryResult = await collection.insertMany(items); return queryResult; } async function findAll(collectionName) { const collections = await ...
if (currentConnection !== null) { currentConnection.close();
random_line_split
customize.py
# # Collective Knowledge (individual environment - setup) # # See CK LICENSE.txt for licensing details # See CK COPYRIGHT.txt for copyright details # # Developer: Grigori Fursin, Grigori.Fursin@cTuning.org, http://fursin.net # ############################################################################## # setup envir...
deps - resolved dependencies for this soft interactive - if 'yes', can ask questions, otherwise quiet } Output: { return - return code = 0, if successful > 0, if error (error) ...
""" Input: { cfg - meta of this soft entry self_cfg - meta of module soft ck_kernel - import CK kernel module (to reuse functions) host_os_uoa - host OS UOA host_os_uid - host OS UID host_os_d...
identifier_body
customize.py
# # Collective Knowledge (individual environment - setup) # # See CK LICENSE.txt for licensing details # See CK COPYRIGHT.txt for copyright details # # Developer: Grigori Fursin, Grigori.Fursin@cTuning.org, http://fursin.net #
############################################################################## # setup environment setup def setup(i): """ Input: { cfg - meta of this soft entry self_cfg - meta of module soft ck_kernel - import CK kernel module (to reuse ...
random_line_split
customize.py
# # Collective Knowledge (individual environment - setup) # # See CK LICENSE.txt for licensing details # See CK COPYRIGHT.txt for copyright details # # Developer: Grigori Fursin, Grigori.Fursin@cTuning.org, http://fursin.net # ############################################################################## # setup envir...
else: dext='.dll' else: dext='.so' r = ck.access({'action': 'lib_path_export_script', 'module_uoa': 'os', 'host_os_dict': host_d, 'dynamic_lib_path': cus.get('path_lib','')}) if r['return']>0: return r s += r['script'] cus['dynamic_plugin']='plugin-openme-ctuning-1....
dext='.so'
conditional_block
customize.py
# # Collective Knowledge (individual environment - setup) # # See CK LICENSE.txt for licensing details # See CK COPYRIGHT.txt for copyright details # # Developer: Grigori Fursin, Grigori.Fursin@cTuning.org, http://fursin.net # ############################################################################## # setup envir...
(i): """ Input: { cfg - meta of this soft entry self_cfg - meta of module soft ck_kernel - import CK kernel module (to reuse functions) host_os_uoa - host OS UOA host_os_uid - host OS UID ...
setup
identifier_name
LoLN_convergence_examples_ch04.py
import numpy as np import matplotlib.pyplot as plt import pymc as pm def main(): sample_size = 100000 expected_value = lambda_ = 4.5 N_samples = range(1, sample_size, 100) for k in range(3): samples = pm.rpoisson(lambda_, size=sample_size) partial_average = [samples[:i].mean() for i i...
main()
conditional_block
LoLN_convergence_examples_ch04.py
import numpy as np import matplotlib.pyplot as plt import pymc as pm def main(): sample_size = 100000 expected_value = lambda_ = 4.5 N_samples = range(1, sample_size, 100)
for k in range(3): samples = pm.rpoisson(lambda_, size=sample_size) partial_average = [samples[:i].mean() for i in N_samples] label = "average of $n$ samples; seq. %d" % k plt.plot(N_samples, partial_average, lw=1.5, label=label) plt.plot(N_samples, expected_value * np.ones_lik...
random_line_split
LoLN_convergence_examples_ch04.py
import numpy as np import matplotlib.pyplot as plt import pymc as pm def
(): sample_size = 100000 expected_value = lambda_ = 4.5 N_samples = range(1, sample_size, 100) for k in range(3): samples = pm.rpoisson(lambda_, size=sample_size) partial_average = [samples[:i].mean() for i in N_samples] label = "average of $n$ samples; seq. %d" % k plt...
main
identifier_name
LoLN_convergence_examples_ch04.py
import numpy as np import matplotlib.pyplot as plt import pymc as pm def main():
if __name__ == '__main__': main()
sample_size = 100000 expected_value = lambda_ = 4.5 N_samples = range(1, sample_size, 100) for k in range(3): samples = pm.rpoisson(lambda_, size=sample_size) partial_average = [samples[:i].mean() for i in N_samples] label = "average of $n$ samples; seq. %d" % k plt.plot(N_...
identifier_body
urlfetcher.py
############################################################################### # # file: urlfetcher.py # # Purpose: refer to module documentation for details # # Note: This file is part of Termsaver application, and should not be used # or executed separately. # #####################################...
* `UrlFetcherScreen` """ # # Internal modules # from termsaverlib.screen.base.urlfetcher import UrlFetcherBase from termsaverlib import constants from termsaverlib.i18n import _ class UrlFetcherScreen(UrlFetcherBase): """ Simple screensaver that displays data from a URL. """ def __init__(self): ...
See additional information in the class itself. The screen class available here is:
random_line_split
urlfetcher.py
############################################################################### # # file: urlfetcher.py # # Purpose: refer to module documentation for details # # Note: This file is part of Termsaver application, and should not be used # or executed separately. # #####################################...
def _message_no_url(self): """ """ return _(""" You just need to provide the URL from where %(app_title)s will read and display on screen. If you do not have any idea which URL to use, check out some examples here: RFC RFC-1034 - http://tools.ietf.org/rfc/rfc1034.txt ...
""" Creates a new instance of this class. """ UrlFetcherBase.__init__(self, "urlfetcher", _("displays url contents with typing animation"))
identifier_body
urlfetcher.py
############################################################################### # # file: urlfetcher.py # # Purpose: refer to module documentation for details # # Note: This file is part of Termsaver application, and should not be used # or executed separately. # #####################################...
(self): """ Creates a new instance of this class. """ UrlFetcherBase.__init__(self, "urlfetcher", _("displays url contents with typing animation")) def _message_no_url(self): """ """ return _(""" You just need to provide the URL from w...
__init__
identifier_name
summary.ts
import {all, call, fork, put, race, take, takeEvery} from "redux-saga/effects"; import {LOGIN_SUCCESS} from './auth'; import history from '../appHistory'; import {client} from "../client"; export const QUERY_SUMMARY = 'QUERY_SUMMARY'; export const QUERY_SUMMARY_SUCCESS = 'QUERY_SUMMARY_SUCCESS'; export const QUERY_SUM...
}
fork(refreshSummaryDeal), ]);
random_line_split
summary.ts
import {all, call, fork, put, race, take, takeEvery} from "redux-saga/effects"; import {LOGIN_SUCCESS} from './auth'; import history from '../appHistory'; import {client} from "../client"; export const QUERY_SUMMARY = 'QUERY_SUMMARY'; export const QUERY_SUMMARY_SUCCESS = 'QUERY_SUMMARY_SUCCESS'; export const QUERY_SUM...
function* querySummaryDeal(action: any): any { try { // 发送请求查询 const result = yield call(() => { return client.get('/api/summary'); }); if (result.rt !== 1) { yield put({type: QUERY_SUMMARY_FAILED}); } else { yield put({type: QUERY_SUMMARY_SUCCESS, payload: result.data}); } } catch (e) { yi...
{ return { type: QUERY_SUMMARY, }; }
identifier_body
summary.ts
import {all, call, fork, put, race, take, takeEvery} from "redux-saga/effects"; import {LOGIN_SUCCESS} from './auth'; import history from '../appHistory'; import {client} from "../client"; export const QUERY_SUMMARY = 'QUERY_SUMMARY'; export const QUERY_SUMMARY_SUCCESS = 'QUERY_SUMMARY_SUCCESS'; export const QUERY_SUM...
ring): any { return { type: MODIFY_SUMMARY, payload: { summary, }, }; } function* modifySummaryDeal(action: any): any { try { // 发送请求查询 const result = yield call(() => { return client.put('/api/summary', { data: action.payload, }); }); if (result.rt !== 1) { yield put({type: MODIFY_SU...
y(summary: st
identifier_name
summary.ts
import {all, call, fork, put, race, take, takeEvery} from "redux-saga/effects"; import {LOGIN_SUCCESS} from './auth'; import history from '../appHistory'; import {client} from "../client"; export const QUERY_SUMMARY = 'QUERY_SUMMARY'; export const QUERY_SUMMARY_SUCCESS = 'QUERY_SUMMARY_SUCCESS'; export const QUERY_SUM...
ield put({type: QUERY_SUMMARY_SUCCESS, payload: result.data}); } } catch (e) { yield put({type: QUERY_SUMMARY_FAILED}); } } export function modifySummary(summary: string): any { return { type: MODIFY_SUMMARY, payload: { summary, }, }; } function* modifySummaryDeal(action: any): any { try { // 发送请...
ut({type: QUERY_SUMMARY_FAILED}); } else { y
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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-pretty /...
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 ...
{x:()} fn test(slot: &mut Option<Thunk<(),Thunk>>) -> () { let a = slot.take(); let _a = match a { // `{let .. a(); }` would break Some(a) => { let _a = a(); }, None => (), }; } fn not(b: bool) -> bool { if b { !b } else { // `panic!(...)` would break panic!("Break t...
S
identifier_name
StandardView.tsx
import React, { useEffect, useMemo, useRef } from 'react' import styled from 'styled-components' import { Box, Button, Dialog, extend, Paragraph, Progress, RefreshIcon, themeGet, } from '../../components' import { useFullSizeMode } from '../FullSizeView' import { useIntersection } from '../IntersectionO...
position: 'sticky', top: 'calc(50vh - var(--caption-height))', width: '48px', height: '48px', mx: 2, borderRadius: '50%', bg: 'surface', opacity: themeGet('opacities.inactive'), transform: 'translateY(-50%)', ':hover': { opacity: 1, }, }) ) if (__DEV__) { Loader.di...
) const Circle = styled.div( extend({ pointerEvents: 'auto',
random_line_split
test_bufio.py
import unittest from test import support import io # C implementation. import _pyio as pyio # Python implementation. # Simple test to ensure that optimizations in the IO library deliver the # expected results. For best testing, run this under a debug-build Python too # (to exercise asserts in the C code). lengths =...
(BufferSizeTest): open = staticmethod(pyio.open) def test_main(): support.run_unittest(CBufferSizeTest, PyBufferSizeTest) if __name__ == "__main__": test_main()
PyBufferSizeTest
identifier_name
test_bufio.py
import unittest from test import support import io # C implementation. import _pyio as pyio # Python implementation. # Simple test to ensure that optimizations in the IO library deliver the # expected results. For best testing, run this under a debug-build Python too # (to exercise asserts in the C code). lengths =...
def test_primepat(self): # A pattern with prime length, to avoid simple relationships with # stdio buffer sizes. self.drive_one(b"1234567890\00\01\02\03\04\05\06") def test_nullpat(self): self.drive_one(bytes(1000)) class CBufferSizeTest(BufferSizeTest): open = io.open ...
q, r = divmod(length, len(pattern)) teststring = pattern * q + pattern[:r] self.assertEqual(len(teststring), length) self.try_one(teststring) self.try_one(teststring + b"x") self.try_one(teststring[:-1])
conditional_block
test_bufio.py
import unittest from test import support import io # C implementation. import _pyio as pyio # Python implementation. # Simple test to ensure that optimizations in the IO library deliver the # expected results. For best testing, run this under a debug-build Python too # (to exercise asserts in the C code). lengths =...
self.assertEqual(line, s) line = f.readline() self.assertTrue(not line) # Must be at EOF f.close() finally: support.unlink(support.TESTFN) def drive_one(self, pattern): for length in lengths: # Repeat string 'pattern' as often ...
def try_one(self, s): # Write s + "\n" + s to file, then open it and ensure that successive # .readline()s deliver what we wrote. # Ensure we can open TESTFN for writing. support.unlink(support.TESTFN) # Since C doesn't guarantee we can write/read arbitrary bytes in text ...
identifier_body
test_bufio.py
import unittest from test import support import io # C implementation. import _pyio as pyio # Python implementation. # Simple test to ensure that optimizations in the IO library deliver the # expected results. For best testing, run this under a debug-build Python too # (to exercise asserts in the C code). lengths =...
def test_main(): support.run_unittest(CBufferSizeTest, PyBufferSizeTest) if __name__ == "__main__": test_main()
class PyBufferSizeTest(BufferSizeTest): open = staticmethod(pyio.open)
random_line_split
routeErrorPosition.js
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ '...
class RouteErrorPosition { /** * Create a RouteErrorPosition. * @member {number} [line] Line where the route error happened * @member {number} [column] Column where the route error happened */ constructor() { } /** * Defines the metadata of RouteErrorPosition * * @returns {object} metadata...
* */
random_line_split
routeErrorPosition.js
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ '...
{ /** * Create a RouteErrorPosition. * @member {number} [line] Line where the route error happened * @member {number} [column] Column where the route error happened */ constructor() { } /** * Defines the metadata of RouteErrorPosition * * @returns {object} metadata of RouteErrorPosition ...
RouteErrorPosition
identifier_name
routeErrorPosition.js
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ '...
} } } } }; } } module.exports = RouteErrorPosition;
{ return { required: false, serializedName: 'RouteErrorPosition', type: { name: 'Composite', className: 'RouteErrorPosition', modelProperties: { line: { required: false, serializedName: 'line', type: { name: 'Numbe...
identifier_body
cursor.py
from .util.deb import deb from .util.nrange import nrange from .cell import Cell #F,e,Cursor from .grid import spoint CURSOR_POS=None def gcp(): #get cursor position global CURSOR_POS deb('gcp',CURSOR_POS) return CURSOR_POS def
(x,y): deb('scp',gcp(),x,y) cxc=0 #todo, normalize in cursor... global CURSOR_POS CURSOR_POS=(x,y) assert (x,y)==gcp() #todo cpget and cpset cpget=gcp cpset=scp def cursor(HG,x,y,f,X,Y): deb('make an a cursor in the empty space around point in cell x,y',x,y) #x,y=x-1,y-1 assert len(f)==4 #HG=_clearcursor(HG...
scp
identifier_name
cursor.py
from .util.deb import deb from .util.nrange import nrange from .cell import Cell #F,e,Cursor from .grid import spoint CURSOR_POS=None def gcp(): #get cursor position
def scp(x,y): deb('scp',gcp(),x,y) cxc=0 #todo, normalize in cursor... global CURSOR_POS CURSOR_POS=(x,y) assert (x,y)==gcp() #todo cpget and cpset cpget=gcp cpset=scp def cursor(HG,x,y,f,X,Y): deb('make an a cursor in the empty space around point in cell x,y',x,y) #x,y=x-1,y-1 assert len(f)==4 #HG=_clear...
global CURSOR_POS deb('gcp',CURSOR_POS) return CURSOR_POS
identifier_body
cursor.py
from .util.deb import deb
from .util.nrange import nrange from .cell import Cell #F,e,Cursor from .grid import spoint CURSOR_POS=None def gcp(): #get cursor position global CURSOR_POS deb('gcp',CURSOR_POS) return CURSOR_POS def scp(x,y): deb('scp',gcp(),x,y) cxc=0 #todo, normalize in cursor... global CURSOR_POS CURSOR_POS=(x,y) asse...
random_line_split
cursor.py
from .util.deb import deb from .util.nrange import nrange from .cell import Cell #F,e,Cursor from .grid import spoint CURSOR_POS=None def gcp(): #get cursor position global CURSOR_POS deb('gcp',CURSOR_POS) return CURSOR_POS def scp(x,y): deb('scp',gcp(),x,y) cxc=0 #todo, normalize in cursor... global CURSOR_P...
i,j=cp HG=spoint(i-1,j,HG,r1) HG=spoint(i,j-1,HG,r2) HG=spoint(i+1,j,HG,r3) HG=spoint(i,j+1,HG,r4) return HG
return HG
conditional_block
__init__.py
from __future__ import absolute_import # What follows is part of a hack to make control breaking work on windows even # if scipy.stats ims imported. See: # http://stackoverflow.com/questions/15457786/ctrl-c-crashes-python-after-importing-scipy-stats import sys import os import imp import ctypes if sys.platform == 'wi...
from .rmsprop import RmsProp from .rprop import Rprop from .smd import Smd from radagrad import Radagrad from adagrad import Adagrad from adagrad_full import AdagradFull
random_line_split
__init__.py
from __future__ import absolute_import # What follows is part of a hack to make control breaking work on windows even # if scipy.stats ims imported. See: # http://stackoverflow.com/questions/15457786/ctrl-c-crashes-python-after-importing-scipy-stats import sys import os import imp import ctypes if sys.platform == 'wi...
from .adadelta import Adadelta from .adam import Adam from .asgd import Asgd from .bfgs import Bfgs, Lbfgs, Sbfgs from .cg import ConjugateGradient, NonlinearConjugateGradient from .gd import GradientDescent from .nes import Xnes from .rmsprop import RmsProp from .rprop import Rprop from .smd import Smd from radagrad...
basepath = imp.find_module('numpy')[1] ctypes.CDLL(os.path.join(basepath, 'core', 'libmmd.dll')) ctypes.CDLL(os.path.join(basepath, 'core', 'libifcoremd.dll'))
conditional_block
rcdom.rs
parent: Option<WeakHandle>, pub children: Vec<Handle>, } impl Node { fn new(node: NodeEnum) -> Node { Node { node: node, parent: None, children: vec!(), } } } /// Reference to a DOM node. #[derive(Clone, Debug)] pub struct Handle(Rc<RefCell<Node>>); im...
{ let node = self.borrow(); match (traversal_scope, &node.node) { (_, &Element(ref name, _, ref attrs)) => { if traversal_scope == IncludeNode { try!(serializer.start_elem(name.clone(), attrs.iter().map(|at| (&at.name, &at.value[..]...
identifier_body
rcdom.rs
::StrTendril; use tokenizer::Attribute; use tree_builder::{TreeSink, QuirksMode, NodeOrText, AppendNode, AppendText}; use tree_builder; use serialize::{Serializable, Serializer}; use serialize::TraversalScope; use serialize::TraversalScope::{IncludeNode, ChildrenOnly}; pub use self::ElementEnum::{AnnotationXml, Norma...
pub children: Vec<Handle>, } impl Node { fn new(node: NodeEnum) -> Node { Node { node: node, parent: None, children: vec!(), } } } /// Reference to a DOM node. #[derive(Clone, Debug)] pub struct Handle(Rc<RefCell<Node>>); impl Deref for Handle { typ...
#[derive(Debug)] pub struct Node { pub node: NodeEnum, pub parent: Option<WeakHandle>,
random_line_split
rcdom.rs
::StrTendril; use tokenizer::Attribute; use tree_builder::{TreeSink, QuirksMode, NodeOrText, AppendNode, AppendText}; use tree_builder; use serialize::{Serializable, Serializer}; use serialize::TraversalScope; use serialize::TraversalScope::{IncludeNode, ChildrenOnly}; pub use self::ElementEnum::{AnnotationXml, Norma...
(Rc<RefCell<Node>>); impl Deref for Handle { type Target = Rc<RefCell<Node>>; fn deref(&self) -> &Rc<RefCell<Node>> { &self.0 } } /// Weak reference to a DOM node, used for parent pointers. pub type WeakHandle = Weak<RefCell<Node>>; #[allow(trivial_casts)] fn same_node(x: &Handle, y: &Handle) -> bool { /...
Handle
identifier_name
main.rs
extern crate time; use time::Duration; fn main() { let duration = Duration::span(|| { let n: i32 = 10000000; let mut h: Vec<i32> = (0..n).collect(); make_heap(&mut *h); for i in (1..n as usize).rev() { h.swap(0, i); push_down(0, i, &mut *h); } ...
if h[pos] > h[vic] { break; } h.swap(pos, vic); pos = vic; } }
{ vic += 1; }
conditional_block
main.rs
extern crate time; use time::Duration; fn main() { let duration = Duration::span(|| { let n: i32 = 10000000; let mut h: Vec<i32> = (0..n).collect(); make_heap(&mut *h); for i in (1..n as usize).rev() { h.swap(0, i); push_down(0, i, &mut *h); } ...
} fn make_heap(h: &mut [i32]) { for i in (0..h.len() / 2).rev() { push_down(i, h.len(), h); } } fn push_down(mut pos: usize, size: usize, h: &mut [i32]) { while 2 * pos + 1 < size { let mut vic = 2 * pos + 1; if vic + 1 < size && h[vic + 1] > h[vic] { vic += 1; ...
random_line_split
main.rs
extern crate time; use time::Duration; fn main() { let duration = Duration::span(|| { let n: i32 = 10000000; let mut h: Vec<i32> = (0..n).collect(); make_heap(&mut *h); for i in (1..n as usize).rev() { h.swap(0, i); push_down(0, i, &mut *h); } ...
fn push_down(mut pos: usize, size: usize, h: &mut [i32]) { while 2 * pos + 1 < size { let mut vic = 2 * pos + 1; if vic + 1 < size && h[vic + 1] > h[vic] { vic += 1; } if h[pos] > h[vic] { break; } h.swap(pos, vic); pos = vic; }...
{ for i in (0..h.len() / 2).rev() { push_down(i, h.len(), h); } }
identifier_body
main.rs
extern crate time; use time::Duration; fn main() { let duration = Duration::span(|| { let n: i32 = 10000000; let mut h: Vec<i32> = (0..n).collect(); make_heap(&mut *h); for i in (1..n as usize).rev() { h.swap(0, i); push_down(0, i, &mut *h); } ...
(h: &mut [i32]) { for i in (0..h.len() / 2).rev() { push_down(i, h.len(), h); } } fn push_down(mut pos: usize, size: usize, h: &mut [i32]) { while 2 * pos + 1 < size { let mut vic = 2 * pos + 1; if vic + 1 < size && h[vic + 1] > h[vic] { vic += 1; } if h...
make_heap
identifier_name
demo05.component.ts
import { Component, OnInit ,ViewChild} from '@angular/core'; import {TestService} from '../test.service' import {Demo06Component} from '../demo06_son/demo06.component' @Component({ moduleId: module.id, selector: 'demo05', templateUrl: 'demo05.component.html', providers:[TestService] }) export class Dem...
return this.testService.count; } set = function(){ console.log(this.demo6Com); this.testService.add(); } }
n(){
identifier_name
demo05.component.ts
import { Component, OnInit ,ViewChild} from '@angular/core'; import {TestService} from '../test.service' import {Demo06Component} from '../demo06_son/demo06.component' @Component({ moduleId: module.id, selector: 'demo05', templateUrl: 'demo05.component.html', providers:[TestService] }) export class Dem...
constructor(private testService:TestService) { } ngOnInit() { } getSonMsg = function(){ alert(this.demo6Com.msg); } get = function(){ return this.testService.count; } set = function(){ console.log(this.demo6Com); this.testService.add(); } }
//从子组件到父组件数据交互的目的 @ViewChild(Demo06Component) private demo6Com:Demo06Component;
random_line_split
utils.py
() # override the arch to not be 'any' new_g['arch'] = arch arch_groups[grp['name']] = new_g # now transform it back into a sorted list, including only the specified # architectures if we got a list groups = [] for key, val in group_mapping.it...
from a template.''' if user is None:
random_line_split
utils.py
def get_group_info(include_arches=None): raw_groups = PackageGroup.objects.values_list( 'name', 'pkg__arch__name').order_by('name').annotate( cnt=Count('pkg'), last_update=Max('pkg__last_update')) # now for post_processing. we need to separate things out and add # the count in for 'any' t...
match = VERSION_RE.match(version) if not match: return None, None, 0 ver = match.group(3) rel = match.group(4) if match.group(2): epoch = int(match.group(2)) else: epoch = 0 return ver, rel, epoch
identifier_body
utils.py
# override the arch to not be 'any' new_g['arch'] = arch arch_groups[grp['name']] = new_g # now transform it back into a sorted list, including only the specified # architectures if we got a list groups = [] for key, val in group_mapping.items...
return sorted(groups, key=itemgetter('name', 'arch')) def get_split_packages_info(): '''Return info on split packages that do not have an actual package name matching the split pkgbase.''' pkgnames = Package.objects.values('pkgname') split_pkgs = Package.objects.exclude(pkgname=F('pkgbase')).excl...
if not include_arches or key in include_arches: groups.extend(iter(val.values()))
conditional_block
utils.py
# override the arch to not be 'any' new_g['arch'] = arch arch_groups[grp['name']] = new_g # now transform it back into a sorted list, including only the specified # architectures if we got a list groups = [] for key, val in group_mapping.items...
(): # Query for checking multilib out of date-ness if database_vendor(Package) == 'sqlite': pkgname_sql = """ CASE WHEN ml.pkgname LIKE %s THEN SUBSTR(ml.pkgname, 7) WHEN ml.pkgname LIKE %s THEN SUBSTR(ml.pkgname, 1, LENGTH(ml.pkgname) - 9) ...
multilib_differences
identifier_name
cmsilicate.py
import numpy as np from scipy.interpolate import interp1d from astropy.io import ascii from astropy import units as u from newdust import constants as c from newdust.graindist.composition import _find_cmfile __all__ = ['CmSilicate'] RHO_SIL = 3.8 # g cm^-3 class CmSilicate(object): """ | **ATTRIBUTES...
| cm(lam, unit='kev') : Complex index of refraction of dtype='complex' | plot(lam=None, unit='kev') : Plots Re(m-1) and Im(m) | if lam is *None*, plots the original interp objects | otherwise, plots with user defined wavelength (lam) """ def __init__(self, rho=RHO_SIL): self.cmtype =...
| interps : A tuple containing scipy.interp1d objects (rp, ip) | | *functions* | rp(lam, unit='kev') : Returns real part (unit='kev'|'angs') | ip(lam, unit='kev') : Returns imaginary part (unit='kev'|'angs')
random_line_split
cmsilicate.py
import numpy as np from scipy.interpolate import interp1d from astropy.io import ascii from astropy import units as u from newdust import constants as c from newdust.graindist.composition import _find_cmfile __all__ = ['CmSilicate'] RHO_SIL = 3.8 # g cm^-3 class CmSilicate(object): """ | **ATTRIBUTES...
(self, lam_cm, interp, rp=False): # Returns zero for wavelengths not covered by the interpolation object # If the real part is needed, returns 1 (consistent with vacuum) result = np.zeros(np.size(lam_cm)) if rp: result += 1 if np.size(lam_cm) == 1: if (lam_cm >= np.m...
_interp_helper
identifier_name
cmsilicate.py
import numpy as np from scipy.interpolate import interp1d from astropy.io import ascii from astropy import units as u from newdust import constants as c from newdust.graindist.composition import _find_cmfile __all__ = ['CmSilicate'] RHO_SIL = 3.8 # g cm^-3 class CmSilicate(object): """ | **ATTRIBUTES...
def rp(self, lam, unit='kev'): lam_cm = c._lam_cm(lam, unit) return self._interp_helper(lam_cm, self.interps[0], rp=True) def ip(self, lam, unit='kev'): lam_cm = c._lam_cm(lam, unit) return self._interp_helper(lam_cm, self.interps[1]) def cm(self, lam, unit='kev'): ...
result = np.zeros(np.size(lam_cm)) if rp: result += 1 if np.size(lam_cm) == 1: if (lam_cm >= np.min(interp.x)) & (lam_cm <= np.max(interp.x)): result = interp(lam_cm) else: ii = (lam_cm >= np.min(interp.x)) & (lam_cm <= np.max(interp.x)) resul...
identifier_body
cmsilicate.py
import numpy as np from scipy.interpolate import interp1d from astropy.io import ascii from astropy import units as u from newdust import constants as c from newdust.graindist.composition import _find_cmfile __all__ = ['CmSilicate'] RHO_SIL = 3.8 # g cm^-3 class CmSilicate(object): """ | **ATTRIBUTES...
else: ii = (lam_cm >= np.min(interp.x)) & (lam_cm <= np.max(interp.x)) result[ii] = interp(lam_cm[ii]) return result def rp(self, lam, unit='kev'): lam_cm = c._lam_cm(lam, unit) return self._interp_helper(lam_cm, self.interps[0], rp=True) def ip(self, l...
if (lam_cm >= np.min(interp.x)) & (lam_cm <= np.max(interp.x)): result = interp(lam_cm)
conditional_block
cards-visible.spec.ts
import { DummyAction, HideCardsAction, LeaveGameAction, SetGameStateAction, ShowCardsAction } from '../actions'; import { cardsVisibleReducer } from './cards-visible'; describe('Cards Visible reducer', () => { it('should default to false', () => { expect(cardsVisibleReducer(undefined, new DummyAction())).toBe(fa...
expect(cardsVisibleReducer(false, new SetGameStateAction(state))).toBe(true); expect(cardsVisibleReducer(true, new SetGameStateAction(state))).toBe(true); state.cardsVisible = false; expect(cardsVisibleReducer(false, new SetGameStateAction(state))).toBe(false); expect(cardsVisibleReducer(true, new ...
players: [], phase: 'VOTING', votes: {} };
random_line_split
n0run.py
. Copyright (C) 2012, Adrian Ratnapala, under the ISC license. See file LICENSE. """ import sys # errors ----------------------------------------------------- def warn(msg, x = None , errno=1, txt='warning') : ERROR="\033[31m\033[1m0run {}: \033[0m".format(txt) if x :
else : sys.stderr.write(ERROR+"{}\n".format(msg)) return errno def die(msg, x = None , errno=1) : warn("[%d] %s" % (errno, msg), x, errno, 'error') sys.exit(errno) class Error(Exception) : pass class Fail( Error ) : def __init__( s, msg, errno, command ) : Erro...
sys.stderr.write(ERROR+"{}: {}\n".format(msg, x))
conditional_block
n0run.py
program. Copyright (C) 2012, Adrian Ratnapala, under the ISC license. See file LICENSE. """ import sys # errors ----------------------------------------------------- def warn(msg, x = None , errno=1, txt='warning') : ERROR="\033[31m\033[1m0run {}: \033[0m".format(txt) if x : sys.stderr.write(ERRO...
try : return r.scan_source() except IOError as x : die("Error reading source file", x, -x.args[0]) def cli_scan_output(r) : try: err_ck = list( r.check_output() ) out, err_sc= r.scan_output() err = err_ck + err_sc ...
assert(len(command) >= 1) return command, source def cli_scan_source(r) :
random_line_split
n0run.py
if x : sys.stderr.write(ERROR+"{}: {}\n".format(msg, x)) else : sys.stderr.write(ERROR+"{}\n".format(msg)) return errno def die(msg, x = None , errno=1) : warn("[%d] %s" % (errno, msg), x, errno, 'error') sys.exit(errno) class Error(Exception) : pass class Fail( Error ) : ...
check_matched
identifier_name
n0run.py
program. Copyright (C) 2012, Adrian Ratnapala, under the ISC license. See file LICENSE. """ import sys # errors ----------------------------------------------------- def warn(msg, x = None , errno=1, txt='warning') : ERROR="\033[31m\033[1m0run {}: \033[0m".format(txt) if x : sys.stderr.write(ERRO...
match_passed = compile_matchers([ ('passed', b'^passed: (?P<n>test\S*)'), ]) match_failed = compile_matchers([ ('FAILED', b'^FAILED: [^:]+:[0-9]+:(?P<n>test\S*)') ]) match_allpassed = compile_matchers([ (None, b'^All [0-9]+ tests passed$')]) def scan_output(po, matchers = match_passed ) : out = {} e...
def showok(name, line) : from sys import stdout stdout.buffer.write(b'\033[32m\033[1mOK:\033[0m '+line+b'\n') def compile_one(s) : from re import compile if type(s) != tuple : raise Exception('match spec must be a tuple of'...
identifier_body
issue-5688.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 ...
{ for &v in V.iter() { println!("{}", v.vec); } }
identifier_body
issue-5688.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 ...
for &v in V.iter() { println!("{}", v.vec); } }
struct X { vec: &'static [int] } static V: &'static [X] = &[X { vec: &[1, 2, 3] }]; pub fn main() {
random_line_split
issue-5688.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 ...
() { for &v in V.iter() { println!("{}", v.vec); } }
main
identifier_name
get_all_labels.py
#!/usr/bin/python # # Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
print '\nNumber of results found: %s' % response['totalResultSetSize'] if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() main(dfp_client)
break
conditional_block
get_all_labels.py
#!/usr/bin/python # # Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() main(dfp_client)
label_service = client.GetService('LabelService', version='v201502') # Create statement to get all labels statement = dfp.FilterStatement() # Get labels by statement. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) if 'results' in response: # Display results. ...
identifier_body
get_all_labels.py
#!/usr/bin/python # # Copyright 2015 Google Inc. All Rights Reserved. #
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
random_line_split
get_all_labels.py
#!/usr/bin/python # # Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
(client): # Initialize appropriate service. label_service = client.GetService('LabelService', version='v201502') # Create statement to get all labels statement = dfp.FilterStatement() # Get labels by statement. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) if '...
main
identifier_name
mmOrders.js
'use strict'; angular.module( 'mmOrders', [] ) .provider( '$mmOrdersConfig', function() { this.$get = function() { return { 'itemFind': '/Shop/Parts/Search', }; }; } ) .config( [ '$mmApiProvider', function($mmApiProvider) { $mmApiProvider.addRoute( 'website', 'shop', '/Shop' ); }, ] ) .run...
}, ] ) .directive( 'mmOrdersList', [ 'mmOrders', function(mmOrders) { return { restrict : 'EA', transclude: true, link : function(scope) { scope.items = mmOrders.store.cart.items; scope.cartTotalUniqueItems = function() { return mmOrders.cartTotalUniqueItems(); }; ...
{ mmOrders.init(); }
conditional_block
mmOrders.js
'use strict'; angular.module( 'mmOrders', [] ) .provider( '$mmOrdersConfig', function() { this.$get = function() { return { 'itemFind': '/Shop/Parts/Search', }; }; } ) .config( [ '$mmApiProvider', function($mmApiProvider) { $mmApiProvider.addRoute( 'website', 'shop', '/Shop' ); }, ] ) .run...
] ) .directive( 'mmOrdersList', [ 'mmOrders', function(mmOrders) { return { restrict : 'EA', transclude: true, link : function(scope) { scope.items = mmOrders.store.cart.items; scope.cartTotalUniqueItems = function() { return mmOrders.cartTotalUniqueItems(); }; }, ...
},
random_line_split
AdminContainer.js
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as actions from '../actions/index'; import Admin from '../../components/Admin/index.jsx'; // include actions as they are needed by each component // they are called via disp...
extends Component { componentDidMount () { const { dispatch, componentContent } = this.props; } render () { return ( <Admin {...this.props} /> ); } } AdminContainer.propTypes = propTypes; function mapStateToProps(state) { const componentContent = state.content.project.components; con...
AdminContainer
identifier_name
AdminContainer.js
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as actions from '../actions/index'; import Admin from '../../components/Admin/index.jsx'; // include actions as they are needed by each component // they are called via disp...
} AdminContainer.propTypes = propTypes; function mapStateToProps(state) { const componentContent = state.content.project.components; const projectName = state.content.projectName; const loadedAdminComponents = state.admin.loadedAdminComponents; const componentsLoaded = state.admin.componentsLoaded; const...
{ return ( <Admin {...this.props} /> ); }
identifier_body
AdminContainer.js
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as actions from '../actions/index'; import Admin from '../../components/Admin/index.jsx'; // include actions as they are needed by each component // they are called via disp...
dispatch(actions.logout()) } } } export default connect(mapStateToProps, mapDispatchToProps)(AdminContainer);
}, dispatchLogout: () => {
random_line_split
time-extension.js
/** * @fileOverview An extension to Exhibit adding a view using SIMILE Timeline. * @author David Huynh * @author <a href="mailto:ryanlee@zepheira.com">Ryan Lee</a> * @example Load this file like so: * <script src="http://host/exhibit/3.0.0/exhibit-api.js"></script> * <script src="http://host/exhibit/3.0.0/extensi...
Exhibit.Debug.exception(new Error("Failed to derive URL prefix for SIMILE Exhibit Time Extension files")); return; } Exhibit.TimeExtension.urlPrefix = url.substr(0, url.indexOf("time-extension.js")); Exhibit.parseURLParameters(url, Exhibit...
random_line_split
time-extension.js
/** * @fileOverview An extension to Exhibit adding a view using SIMILE Timeline. * @author David Huynh * @author <a href="mailto:ryanlee@zepheira.com">Ryan Lee</a> * @example Load this file like so: * <script src="http://host/exhibit/3.0.0/exhibit-api.js"></script> * <script src="http://host/exhibit/3.0.0/extensi...
localesToLoad = Exhibit.Localization.getLoadableLocales(Exhibit.TimeExtension.locales); for (i = 0; i < localesToLoad.length; i++) { scriptURLs.push(Exhibit.TimeExtension.urlPrefix + "locales/" + localesToLoad[i] + "/locale.js"); } Exhibit.includeCssFiles(docum...
{ Exhibit.prefixURLs(scriptURLs, Exhibit.TimeExtension.urlPrefix + "scripts/", javascriptFiles); Exhibit.prefixURLs(cssURLs, Exhibit.TimeExtension.urlPrefix + "styles/", cssFiles); }
conditional_block
app.component.ts
// #docregion import {Component} from 'angular2/core'; import {HTTP_PROVIDERS} from 'angular2/http'; import {FlyingHeroesComponent, FlyingHeroesImpureComponent} from './flying-heroes.component'; import {HeroAsyncMessageComponent} from './hero-async-message.component'; import {HeroBirthday} from './hero-birt...
{ birthday = new Date(1988,3,15); // April 15, 1988 }
AppComponent
identifier_name
app.component.ts
// #docregion import {Component} from 'angular2/core'; import {HTTP_PROVIDERS} from 'angular2/http'; import {FlyingHeroesComponent, FlyingHeroesImpureComponent} from './flying-heroes.component'; import {HeroAsyncMessageComponent} from './hero-async-message.component'; import {HeroBirthday} from './hero-birt...
HeroAsyncMessageComponent, HeroBirthday, HeroBirthday2, HeroListComponent, PowerBooster, PowerBoostCalculator, RandomPipeComponent ], providers:[HTTP_PROVIDERS] }) export class AppComponent { birthday = new Date(1988,3,15); // April 15, 1988 }
@Component({ selector: 'my-app', templateUrl: 'app/app.component.html', directives:[ FlyingHeroesComponent, FlyingHeroesImpureComponent,
random_line_split
input-component.component.ts
import {Component, Input, OnChanges} from "@angular/core"; import {TranslateService, TranslateServiceEvent, TranslateServiceEventType} from "../services/translate.service"; @Component({ selector: 'input-component', templateUrl: 'input-component.html' }) export class InputComponent implements OnChanges { @I...
(): void { if (this.errorKey) { var translated = this.translateService.translate("error." + this.errorKey); this.errorMessage = this.translateService.replacePlaceholders(translated, this.errorValue); } else { this.errorMessage = null; } } getFirstErro...
updateErrorMessage
identifier_name
input-component.component.ts
import {Component, Input, OnChanges} from "@angular/core"; import {TranslateService, TranslateServiceEvent, TranslateServiceEventType} from "../services/translate.service"; @Component({ selector: 'input-component', templateUrl: 'input-component.html' }) export class InputComponent implements OnChanges { @I...
} getFirstErrorMessageKey(errors: any): string { if (!errors) { return null; } for (let key of Object.keys(errors)) { return key; } } }
{ this.errorMessage = null; }
conditional_block
input-component.component.ts
import {Component, Input, OnChanges} from "@angular/core"; import {TranslateService, TranslateServiceEvent, TranslateServiceEventType} from "../services/translate.service"; @Component({ selector: 'input-component', templateUrl: 'input-component.html' }) export class InputComponent implements OnChanges { @I...
} this.updateErrorMessage(); }); } ngOnChanges(changes: any): void { var errors: any = changes.errors.currentValue; var key: string = this.getFirstErrorMessageKey(errors); this.errorKey = key; this.errorValue = key ? errors[key] : null; t...
if (event.type === TranslateServiceEventType.LANGUAGE_CHANGED) { console.log("Language changed: " + event.data);
random_line_split
input-component.component.ts
import {Component, Input, OnChanges} from "@angular/core"; import {TranslateService, TranslateServiceEvent, TranslateServiceEventType} from "../services/translate.service"; @Component({ selector: 'input-component', templateUrl: 'input-component.html' }) export class InputComponent implements OnChanges { @I...
private updateErrorMessage(): void { if (this.errorKey) { var translated = this.translateService.translate("error." + this.errorKey); this.errorMessage = this.translateService.replacePlaceholders(translated, this.errorValue); } else { this.errorMessage = null; ...
{ var errors: any = changes.errors.currentValue; var key: string = this.getFirstErrorMessageKey(errors); this.errorKey = key; this.errorValue = key ? errors[key] : null; this.updateErrorMessage(); }
identifier_body
webpack.config.dev.js
CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin'); var getClientEnvironment = require('./env'); var paths = require('./path...
new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" }), // Makes the public URL available as %PUBLIC_URL% in index.html, e.g.: // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> // In development, this will be an empty string. n...
plugins: [
random_line_split
buffer.rs
use std::iter::FromIterator; use std::io::{ BufRead, Write }; use std::vec::IntoIter; use std::ops; use Result; #[derive(Debug)] pub struct Buffer { lines: Vec<String>, cached_num_lines: usize, modified: bool } trait InsertAll { type Item; fn insert_all<I: IntoIterator<Item=Self::Item>>...
self.is_out_of_bounds(range.start) || self.is_out_of_bounds(range.end) } pub fn get_lines(&self, range: &ops::Range<usize>) -> &[String] { assert!(! self.is_out_of_bounds( range.start ), format!("Out of bounds: {}/0", range.start) ); assert!(! self.is_out_of_bounds( range.end ), format!...
} pub fn is_range_out_of_bounds(&self, range: &ops::Range<usize>) -> bool {
random_line_split
buffer.rs
use std::iter::FromIterator; use std::io::{ BufRead, Write }; use std::vec::IntoIter; use std::ops; use Result; #[derive(Debug)] pub struct Buffer { lines: Vec<String>, cached_num_lines: usize, modified: bool } trait InsertAll { type Item; fn insert_all<I: IntoIterator<Item=Self::Item>...
<R: BufRead + Sized> (buf_read: R) -> Result<Buffer> { let lines = buf_read.lines(); let lines_vec = lines.map(|r| r.unwrap()).collect::<Vec<String>>(); let cached_len = lines_vec.len(); Ok(Buffer { lines: lines_vec, cached_num_lines: cached_len, mo...
from_buf_read
identifier_name
buffer.rs
use std::iter::FromIterator; use std::io::{ BufRead, Write }; use std::vec::IntoIter; use std::ops; use Result; #[derive(Debug)] pub struct Buffer { lines: Vec<String>, cached_num_lines: usize, modified: bool } trait InsertAll { type Item; fn insert_all<I: IntoIterator<Item=Self::Item>...
pub fn get_lines(&self, range: &ops::Range<usize>) -> &[String] { assert!(! self.is_out_of_bounds( range.start ), format!("Out of bounds: {}/0", range.start) ); assert!(! self.is_out_of_bounds( range.end ), format!("Out of bounds: {}/{}", range.end, self.len()) ); &self.lines[ range.star...
{ self.is_out_of_bounds(range.start) || self.is_out_of_bounds(range.end) }
identifier_body
float_macros.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 ...
} // If we are not yet at the exponent parse the fractional // part of the significand if exp_info.is_none() { let mut power = 1.0; for (i, c) in cs.by_ref() { match c.to_digit(radix) { Some(digi...
}, }, }
random_line_split
0011_auto_20170605_0507.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-06-05 05:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
), ]
dependencies = [ ('topics', '0010_auto_20170531_1439'), ] operations = [ migrations.CreateModel( name='YearTopicRank', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('year', mod...
identifier_body
0011_auto_20170605_0507.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-06-05 05:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class
(migrations.Migration): dependencies = [ ('topics', '0010_auto_20170531_1439'), ] operations = [ migrations.CreateModel( name='YearTopicRank', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),...
Migration
identifier_name
0011_auto_20170605_0507.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-06-05 05:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('topics', '0010_auto_20170531_1439'), ] operations ...
name='yeartopicrank', unique_together=set([('year', 'topic')]), ), ]
options={ 'ordering': ('year', 'score'), }, ), migrations.AlterUniqueTogether(
random_line_split
tutorial_etl_dag.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...
#### Extract task A simple Extract task to get data ready for the rest of the data pipeline. In this case, getting data is simulated by reading from a hardcoded JSON string. This data is then put into xcom, so that it can be processed by the next task. """ ) transform_task = PythonOperator(...
extract_task.doc_md = dedent( """\
random_line_split
tutorial_etl_dag.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...
total_value = {"total_order_value": total_order_value} total_value_json_string = json.dumps(total_value) ti.xcom_push('total_order_value', total_value_json_string) # [END transform_function] # [START load_function] def load(**kwargs): ti = kwargs['ti'] total_value...
total_order_value += value
conditional_block
tutorial_etl_dag.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...
(**kwargs): ti = kwargs['ti'] extract_data_string = ti.xcom_pull(task_ids='extract', key='order_data') order_data = json.loads(extract_data_string) total_order_value = 0 for value in order_data.values(): total_order_value += value total_value = {"total_order...
transform
identifier_name
tutorial_etl_dag.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...
# [END transform_function] # [START load_function] def load(**kwargs): ti = kwargs['ti'] total_value_string = ti.xcom_pull(task_ids='transform', key='total_order_value') total_order_value = json.loads(total_value_string) print(total_order_value) # [END load_function]...
ti = kwargs['ti'] extract_data_string = ti.xcom_pull(task_ids='extract', key='order_data') order_data = json.loads(extract_data_string) total_order_value = 0 for value in order_data.values(): total_order_value += value total_value = {"total_order_value": total_order...
identifier_body
htmltablecellelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; use dom::attr::{Attr, AttrValue}; use dom::bindings::codegen::Bindings::HTMLTableCellElementB...
(&self) -> Option<u32> { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &atom!("colspan")) .map(AttrValue::as_uint) } } fn get_width(&self) -> LengthOrPercentageOrAuto { unsafe { (*self.unsafe_get()...
get_colspan
identifier_name
htmltablecellelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; use dom::attr::{Attr, AttrValue}; use dom::bindings::codegen::Bindings::HTMLTableCellElementB...
} pub trait HTMLTableCellElementLayoutHelpers { fn get_background_color(&self) -> Option<RGBA>; fn get_colspan(&self) -> Option<u32>; fn get_width(&self) -> LengthOrPercentageOrAuto; } #[allow(unsafe_code)] impl HTMLTableCellElementLayoutHelpers for LayoutJS<HTMLTableCellElement> { fn get_background...
{ let self_node = self.upcast::<Node>(); let parent_children = match self_node.GetParentNode() { Some(ref parent_node) if parent_node.is::<HTMLTableRowElement>() => { parent_node.children() }, _ => return -1, }; parent_children.filter...
identifier_body
htmltablecellelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; use dom::attr::{Attr, AttrValue}; use dom::bindings::codegen::Bindings::HTMLTableCellElementB...
match *attr.local_name() { atom!("width") => { let width = mutation.new_value(attr).map(|value| { str::parse_length(&value) }); self.width.set(width.unwrap_or(LengthOrPercentageOrAuto::Auto)); }, _ => {}, ...
self.super_type().unwrap().attribute_mutated(attr, mutation);
random_line_split
conference-data.ts
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import { UserData } from './user-data'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/observable/of'; @Injectable() export class
{ data: any; constructor(public http: Http, public user: UserData) { } load(): any { if (this.data) { return Observable.of(this.data); } else { return this.http.get('assets/data/data.json') .map(this.processData, this); } } processData(data: any) { // just some good 'ol...
ConferenceData
identifier_name
conference-data.ts
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import { UserData } from './user-data'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/observable/of'; @Injectable() export class ConferenceData { data: any; constructor(public htt...
}); }); }); return this.data; } getTimeline(dayIndex: number, queryText = '', excludeTracks: any[] = [], segment = 'all') { return this.load().map((data: any) => { let day = data.schedule[dayIndex]; day.shownSessions = 0; queryText = queryText.toLowerCase().replace(/,...
{ session.tracks.forEach((track: any) => { if (this.data.tracks.indexOf(track) < 0) { this.data.tracks.push(track); } }); }
conditional_block
conference-data.ts
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import { UserData } from './user-data'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/observable/of'; @Injectable() export class ConferenceData { data: any; constructor(public htt...
processData(data: any) { // just some good 'ol JS fun with objects and arrays // build up the data by linking employees to sessions this.data = data.json(); this.data.tracks = []; // loop through each day in the schedule this.data.schedule.forEach((day: any) => { // loop through each...
{ if (this.data) { return Observable.of(this.data); } else { return this.http.get('assets/data/data.json') .map(this.processData, this); } }
identifier_body
conference-data.ts
import { Injectable } from '@angular/core'; import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/observable/of'; @Injectable() export class ConferenceData { data: any; constructor(public http: Http, public user: UserData) { } load(): any { if (this.data) { return Observable.of(this.data); } else ...
import { UserData } from './user-data';
random_line_split
ckeditor.js
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Contains the third and last part of the {@link CKEDITOR} object * definition. */ // Remove the CKEDITOR.loadFullCore reference defined on ...
}); }; /** * Removes an editor instance from the global {@link CKEDITOR} object. This function * is available for internal use only. External code must use {@link CKEDITOR.editor.prototype.destroy} * to avoid memory leaks. * @param {CKEDITOR.editor} editor The editor instance to be removed. * @example ...
CKEDITOR.currentInstance = null; CKEDITOR.fire( 'currentInstance' ); }
conditional_block
ckeditor.js
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Contains the third and last part of the {@link CKEDITOR} object * definition. */ // Remove the CKEDITOR.loadFullCore reference defined on ...
* Used to indicate DISABLED state. * @constant * @example */ CKEDITOR.TRISTATE_DISABLED = 0; /** * The editor which is currently active (have user focus). * @name CKEDITOR.currentInstance * @type CKEDITOR.editor * @see CKEDITOR#currentInstance * @example * function showCurrentEditorName() * { ...
/**
random_line_split