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 |
|---|---|---|---|---|
core.js | (function() {
var URL, URL_PATTERN, defaults, urllite,
__hasProp = {}.hasOwnProperty;
URL_PATTERN = /^(?:(?:([^:\/?\#]+:)\/+|(\/\/))(?:([a-z0-9-\._~%]+)(?::([a-z0-9-\._~%]+))?@)?(([a-z0-9-\._~%!$&'()*+,;=]+)(?::([0-9]+))?)?)?([^?\#]*?)(\?[^\#]*)?(\#.*)?$/;
urllite = function(raw, opts) {
return urllite.... | (props) {
var k, v, _ref;
for (k in defaults) {
if (!__hasProp.call(defaults, k)) continue;
v = defaults[k];
this[k] = (_ref = props[k]) != null ? _ref : v;
}
this.host || (this.host = this.hostname && this.port ? "" + this.hostname + ":" + this.port : this.hostname ? thi... | URL | identifier_name |
core.js | (function() {
var URL, URL_PATTERN, defaults, urllite, |
urllite = function(raw, opts) {
return urllite.URL.parse(raw, opts);
};
urllite.URL = URL = (function() {
function URL(props) {
var k, v, _ref;
for (k in defaults) {
if (!__hasProp.call(defaults, k)) continue;
v = defaults[k];
this[k] = (_ref = props[k]) != null ? _re... | __hasProp = {}.hasOwnProperty;
URL_PATTERN = /^(?:(?:([^:\/?\#]+:)\/+|(\/\/))(?:([a-z0-9-\._~%]+)(?::([a-z0-9-\._~%]+))?@)?(([a-z0-9-\._~%!$&'()*+,;=]+)(?::([0-9]+))?)?)?([^?\#]*?)(\?[^\#]*)?(\#.*)?$/; | random_line_split |
core.js | (function() {
var URL, URL_PATTERN, defaults, urllite,
__hasProp = {}.hasOwnProperty;
URL_PATTERN = /^(?:(?:([^:\/?\#]+:)\/+|(\/\/))(?:([a-z0-9-\._~%]+)(?::([a-z0-9-\._~%]+))?@)?(([a-z0-9-\._~%!$&'()*+,;=]+)(?::([0-9]+))?)?)?([^?\#]*?)(\?[^\#]*)?(\#.*)?$/;
urllite = function(raw, opts) {
return urllite.... |
URL.parse = function(raw) {
var m, pathname, protocol;
m = raw.toString().match(URL_PATTERN);
pathname = m[8] || '';
protocol = m[1];
return new urllite.URL({
protocol: protocol,
username: m[3],
password: m[4],
hostname: m[6],
port: m[7],
... | {
var k, v, _ref;
for (k in defaults) {
if (!__hasProp.call(defaults, k)) continue;
v = defaults[k];
this[k] = (_ref = props[k]) != null ? _ref : v;
}
this.host || (this.host = this.hostname && this.port ? "" + this.hostname + ":" + this.port : this.hostname ? this.hostna... | identifier_body |
streaming.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | pub struct StreamingHandler<R: io::Read> {
buffer: [u8; BUFFER_SIZE],
buffer_leftover: usize,
status: StatusCode,
content: io::BufReader<R>,
mimetype: Mime,
safe_to_embed_on: Option<(String, u16)>,
}
impl<R: io::Read> StreamingHandler<R> {
pub fn new(content: R, status: StatusCode, mimetype: Mime, embeddable_on... | const BUFFER_SIZE: usize = 1024;
| random_line_split |
streaming.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | (content: R, status: StatusCode, mimetype: Mime, embeddable_on: Option<(String, u16)>) -> Self {
StreamingHandler {
buffer: [0; BUFFER_SIZE],
buffer_leftover: 0,
status: status,
content: io::BufReader::new(content),
mimetype: mimetype,
safe_to_embed_on: embeddable_on,
}
}
pub fn set_initial_con... | new | identifier_name |
scatter_profile.py | #!/usr/bin/env python
# -*- noplot -*-
"""
N Classic Base renderer Ext renderer
20 0.22 0.14 0.14
100 0.16 0.14 0.13
1000 0.45 0.26 0.17
10000 3.30 1.31 0.53
50000 19.30 6.53 1.98 |
import time
for N in (20,100,1000,10000,50000):
tstart = time.time()
x = 0.9*rand(N)
y = 0.9*rand(N)
s = 20*rand(N)
scatter(x,y,s)
print '%d symbols in %1.2f s' % (N, time.time()-tstart) | """
from pylab import * | random_line_split |
scatter_profile.py | #!/usr/bin/env python
# -*- noplot -*-
"""
N Classic Base renderer Ext renderer
20 0.22 0.14 0.14
100 0.16 0.14 0.13
1000 0.45 0.26 0.17
10000 3.30 1.31 0.53
50000 19.30 6.53 1.98
""... | tstart = time.time()
x = 0.9*rand(N)
y = 0.9*rand(N)
s = 20*rand(N)
scatter(x,y,s)
print '%d symbols in %1.2f s' % (N, time.time()-tstart) | conditional_block | |
test.js | /* ---------------------------------------------------------------------------- *
* General Notes *
* ---------------------------------------------------------------------------- *
* This is NOT intended to be a thorough or automatic testing script -- th... | /* ---------------------------------------------------------------------------- *
* SafeContract Testing *
* ---------------------------------------------------------------------------- */
// deposit the ether coins from RewardDAO: mints ERC20 wrappers and trac... | random_line_split | |
test.js | /* ---------------------------------------------------------------------------- *
* General Notes *
* ---------------------------------------------------------------------------- *
* This is NOT intended to be a thorough or automatic testing script -- th... | });
/* ---------------------------------------------------------------------------- *
* Deploys Vault *
* ---------------------------------------------------------------------------- */
rewardDao.deployVault(); // deploys the vault for our user
rewardD... | { console.log(result.args); } | conditional_block |
VWindowItem.ts | // Components
import VWindow from './VWindow'
// Mixins
import Bootable from '../../mixins/bootable'
import { factory as GroupableFactory } from '../../mixins/groupable'
// Directives
import Touch from '../../directives/touch'
// Utilities
import { convertToUnit } from '../../util/helpers'
import mixins, { ExtractVu... | (): object {
return this.groupClasses
},
computedTransition (): string | boolean {
if (!this.windowGroup.internalReverse) {
return typeof this.transition !== 'undefined'
? this.transition || ''
: this.windowGroup.computedTransition
}
return typeof this.rever... | classes | identifier_name |
VWindowItem.ts | // Components
import VWindow from './VWindow'
// Mixins
import Bootable from '../../mixins/bootable'
import { factory as GroupableFactory } from '../../mixins/groupable'
// Directives
import Touch from '../../directives/touch'
// Utilities
import { convertToUnit } from '../../util/helpers'
import mixins, { ExtractVu... | ,
onAfterTransition () {
if (!this.inTransition) {
return
}
// Finalize transition state.
this.inTransition = false
if (this.windowGroup.transitionCount > 0) {
this.windowGroup.transitionCount--
// Remove container height if we are out of transition.
i... | {
return this.$createElement('div', {
staticClass: 'v-window-item',
class: this.classes,
directives: [{
name: 'show',
value: this.isActive,
}],
on: this.$listeners,
}, this.genDefaultSlot())
} | identifier_body |
VWindowItem.ts | // Components
import VWindow from './VWindow'
// Mixins
import Bootable from '../../mixins/bootable'
import { factory as GroupableFactory } from '../../mixins/groupable'
// Directives
import Touch from '../../directives/touch'
// Utilities
import { convertToUnit } from '../../util/helpers'
import mixins, { ExtractVu... |
}
},
onBeforeTransition () {
if (this.inTransition) {
return
}
// Initialize transition state here.
this.inTransition = true
if (this.windowGroup.transitionCount === 0) {
// Set initial height for height transition.
this.windowGroup.transitionHeight ... | {
this.windowGroup.transitionHeight = undefined
} | conditional_block |
VWindowItem.ts | // Components
import VWindow from './VWindow'
// Mixins
import Bootable from '../../mixins/bootable'
import { factory as GroupableFactory } from '../../mixins/groupable'
// Directives
import Touch from '../../directives/touch'
// Utilities
import { convertToUnit } from '../../util/helpers'
import mixins, { ExtractVu... | beforeLeave: this.onBeforeTransition,
afterLeave: this.onAfterTransition,
leaveCancelled: this.onTransitionCancelled,
// Enter handler for height transition.
enter: this.onEnter,
},
}, this.showLazyContent(() => [this.genWindowItem()]))
},
}) | enterCancelled: this.onTransitionCancelled,
// Handlers for leave windows. | random_line_split |
multiple.rs | // rustfmt-normalize_comments: true
// rustfmt-wrap_comments: true
// rustfmt-format_strings: true
// Test of lots of random stuff.
// FIXME split this into multiple, self-contained tests.
#[attr1]
extern crate foo;
#[attr2]
#[attr3]
extern crate foo;
#[attr1]
extern crate foo;
#[attr2]
#[attr3]
extern crate foo;
use... | HttpVersion,
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA,
) {
}
fn deconstruct(
foo: Bar,
) -> (
SocketAddr,
Method,
Headers,
RequestUri,
HttpVersion,
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA,
) {
}
#[rustfmt::skip]
mod a{
fn foo(x: T) {
let x: ... | RequestUri, | random_line_split |
multiple.rs | // rustfmt-normalize_comments: true
// rustfmt-wrap_comments: true
// rustfmt-format_strings: true
// Test of lots of random stuff.
// FIXME split this into multiple, self-contained tests.
#[attr1]
extern crate foo;
#[attr2]
#[attr3]
extern crate foo;
#[attr1]
extern crate foo;
#[attr2]
#[attr3]
extern crate foo;
use... |
}
| {
let x: T = dfasdf;
} | identifier_body |
multiple.rs | // rustfmt-normalize_comments: true
// rustfmt-wrap_comments: true
// rustfmt-format_strings: true
// Test of lots of random stuff.
// FIXME split this into multiple, self-contained tests.
#[attr1]
extern crate foo;
#[attr2]
#[attr3]
extern crate foo;
#[attr1]
extern crate foo;
#[attr2]
#[attr3]
extern crate foo;
use... | (self) -> Dog {}
}
/// The `nodes` and `edges` method each return instantiations of
/// `Cow<[T]>` to leave implementers the freedom to create
/// entirely new vectors or to pass back slices into internally owned
/// vectors.
pub trait GraphWalk<'a, N, E> {
/// Returns all the nodes in this graph.
fn nodes(&'... | f3 | identifier_name |
unmatchedStageTypeStage.controller.ts | import { module, IController, IScope, isDefined } from 'angular';
import { cloneDeep, isEqual } from 'lodash';
import { JsonUtils } from 'core/utils';
import { IStage } from 'core/domain/IStage';
export class UnmatchedStageTypeStageCtrl implements IController {
public stageJson: string;
public errorMessage: string... |
public updateStage(): void {
let parsedStage: IStage;
this.errorMessage = null;
try {
parsedStage = JSON.parse(this.stageJson);
} catch (e) {
this.errorMessage = e.message;
}
if (parsedStage && !parsedStage.type) {
this.errorMessage = 'Cannot delete property <em>type</em>.... | {
this.stageJson = JsonUtils.makeSortedStringFromObject(this.makeCleanStageCopy(this.$scope.stage || {}));
this.textareaRows = this.stageJson.split('\n').length;
} | identifier_body |
unmatchedStageTypeStage.controller.ts | import { module, IController, IScope, isDefined } from 'angular';
import { cloneDeep, isEqual } from 'lodash';
import { JsonUtils } from 'core/utils';
import { IStage } from 'core/domain/IStage';
export class UnmatchedStageTypeStageCtrl implements IController {
public stageJson: string;
public errorMessage: string... |
});
return stageCopy;
}
}
export const UNMATCHED_STAGE_TYPE_STAGE_CTRL = 'spinnaker.core.pipeline.stage.unmatchedStageTypeStage.controller';
module(UNMATCHED_STAGE_TYPE_STAGE_CTRL, []).controller('UnmatchedStageTypeStageCtrl', UnmatchedStageTypeStageCtrl);
| {
delete stageCopy[key];
} | conditional_block |
unmatchedStageTypeStage.controller.ts | import { module, IController, IScope, isDefined } from 'angular';
import { cloneDeep, isEqual } from 'lodash';
import { JsonUtils } from 'core/utils';
import { IStage } from 'core/domain/IStage';
export class UnmatchedStageTypeStageCtrl implements IController {
public stageJson: string;
public errorMessage: string... | export const UNMATCHED_STAGE_TYPE_STAGE_CTRL = 'spinnaker.core.pipeline.stage.unmatchedStageTypeStage.controller';
module(UNMATCHED_STAGE_TYPE_STAGE_CTRL, []).controller('UnmatchedStageTypeStageCtrl', UnmatchedStageTypeStageCtrl); | return stageCopy;
}
}
| random_line_split |
unmatchedStageTypeStage.controller.ts | import { module, IController, IScope, isDefined } from 'angular';
import { cloneDeep, isEqual } from 'lodash';
import { JsonUtils } from 'core/utils';
import { IStage } from 'core/domain/IStage';
export class UnmatchedStageTypeStageCtrl implements IController {
public stageJson: string;
public errorMessage: string... | (public $scope: IScope) {}
public $onInit(): void {
this.stageJson = JsonUtils.makeSortedStringFromObject(this.makeCleanStageCopy(this.$scope.stage || {}));
this.textareaRows = this.stageJson.split('\n').length;
}
public updateStage(): void {
let parsedStage: IStage;
this.errorMessage = null;
... | constructor | identifier_name |
managed_process.rs | Child;
use std::io::{Error, ErrorKind, Result};
use std::time::{Duration, Instant};
/// Unix exit statuses
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub struct ExitStatus(c_int);
const RESTART_TIME_THRESHOLD: u64 = 5; // seconds
pub struct ManagedProcess {
kill_signal: Arc<Mutex<u32>>,
pid: Arc<Mutex<Opti... | else {
Ok(t)
}
}
/// Check the return value of a libc function, but, retry the given function if
/// the returned error is EINTR (Interrupted)
fn c_rv_retry<F>(mut f: F) -> Result<c_int>
where F: FnMut() -> c_int
{
loop {
match c_rv(f()) {
Err(ref e) if e.kind() == ErrorKind::I... | {
Err(Error::last_os_error())
} | conditional_block |
managed_process.rs | Child;
use std::io::{Error, ErrorKind, Result};
use std::time::{Duration, Instant};
/// Unix exit statuses
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub struct ExitStatus(c_int);
const RESTART_TIME_THRESHOLD: u64 = 5; // seconds
pub struct ManagedProcess {
kill_signal: Arc<Mutex<u32>>,
pid: Arc<Mutex<Opti... | (restart_threshold_secs: u64) -> Self {
Backoff::new(Duration::from_secs(restart_threshold_secs))
}
fn next_backoff(&mut self) -> Duration {
let end_time = Instant::now();
let duration_to_backoff = if let Some(start_time) = self.start_time {
if (end_time - start_time) < sel... | from_secs | identifier_name |
managed_process.rs | ::Child;
use std::io::{Error, ErrorKind, Result};
use std::time::{Duration, Instant};
/// Unix exit statuses
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub struct ExitStatus(c_int);
const RESTART_TIME_THRESHOLD: u64 = 5; // seconds
pub struct ManagedProcess {
kill_signal: Arc<Mutex<u32>>,
pid: Arc<Mutex<Op... | /// Create a new ManagedProcess and start it.
///
/// # Examples
///
/// use tunnel_controller::ManagedProcess;
/// use std::process::Command;
///
/// let process = ManagedProcess::start(|| {
/// Command::new("echo")
/// .arg("Hello")
/// .arg("Wor... | }
impl ManagedProcess { | random_line_split |
multiModuleFundule1.ts | /// <reference path='fourslash.ts'/>
////function C(x: number) { }
////
////module C {
//// export var x = 1;
////}
////module C {
//// export function foo() { }
////}
////
////var /*2*/r = C(/*1*/
////var /*4*/r2 = new C(/*3*/ // using void returning function as constructor
////var r3 = C./*5*/
goTo.marker('1'... |
goTo.marker('3');
verify.completionListContains('C');
edit.insert('C.x);');
goTo.marker('4');
verify.quickInfoIs('var r2: any');
goTo.marker('5');
verify.completionListContains('x');
verify.completionListContains('foo');
edit.insert('x;');
verify.numberOfErrorsInCurrentFile(0); | random_line_split | |
sayingEdit.ts | /// <reference path="../_references.d.ts" />
module controllers {
"use strict";
var controllerId = "sayingEdit";
interface sayingEditRouteParams extends ng.route.IRouteParamsService {
id: string;
}
interface sayingEditScope extends ng.IScope {
form: ng.IFormController;
}
... | if (id) {
dataPromises.push(this.datacontext.saying.getById(id, true).then(saying => this.saying = saying));
title = "Saying Edit";
}
else {
title = "Saying Add";
}
this.common.activateController(dataPromises, c... | var id = parseInt(this.$routeParams.id, 10);
var dataPromises: ng.IPromise<any>[] = [this.datacontext.sage.getAll().then(data => this.sages = data)];
var title: string;
| random_line_split |
sayingEdit.ts | /// <reference path="../_references.d.ts" />
module controllers {
"use strict";
var controllerId = "sayingEdit";
interface sayingEditRouteParams extends ng.route.IRouteParamsService {
id: string;
}
interface sayingEditScope extends ng.IScope {
form: ng.IFormController;
}
... | // Prototype methods
activate() {
var id = parseInt(this.$routeParams.id, 10);
var dataPromises: ng.IPromise<any>[] = [this.datacontext.sage.getAll().then(data => this.sages = data)];
var title: string;
if (id) {
dataPromises.push(this.d... |
this.errors = {};
this.log = common.logger.getLoggers(controllerId);
this.sages = [];
this.saying = undefined;
this._isSavingOrRemoving = false;
this.activate();
}
| identifier_body |
sayingEdit.ts | /// <reference path="../_references.d.ts" />
module controllers {
"use strict";
var controllerId = "sayingEdit";
interface sayingEditRouteParams extends ng.route.IRouteParamsService {
id: string;
}
interface sayingEditScope extends ng.IScope {
form: ng.IFormController;
}
... | private $location: ng.ILocationService,
private $routeParams: sayingEditRouteParams,
private $scope: sayingEditScope,
private _: UnderscoreStatic,
private bsDialog: bootstrapDialog,
private common: common,
private datacontext: dataconte... | nstructor(
| identifier_name |
sayingEdit.ts | /// <reference path="../_references.d.ts" />
module controllers {
"use strict";
var controllerId = "sayingEdit";
interface sayingEditRouteParams extends ng.route.IRouteParamsService {
id: string;
}
interface sayingEditScope extends ng.IScope {
form: ng.IFormController;
}
... | else {
sayingToSave.sageId = 0;
}
sayingToSave.sage = null;
this.common.waiter(this.datacontext.saying.save(sayingToSave), controllerId, "Saving saying")
.then(sayingId => {
this.log.success("Saved saying");
... | sayingToSave.sageId = sayingToSave.sage.id;
}
| conditional_block |
regions-close-object-into-object.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 ... | <'a, T: 'static>(v: Box<A<T>>) -> Box<X+'static> {
box B(&*v) as Box<X> //~ ERROR cannot infer
}
fn h<'a, T, U>(v: Box<A<U>+'static>) -> Box<X+'static> {
box B(&*v) as Box<X>
}
fn i<'a, T, U>(v: Box<A<U>>) -> Box<X+'static> {
box B(&*v) as Box<X> //~ ERROR cannot infer
}
fn main() {}
| g | identifier_name |
regions-close-object-into-object.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 ... |
fn i<'a, T, U>(v: Box<A<U>>) -> Box<X+'static> {
box B(&*v) as Box<X> //~ ERROR cannot infer
}
fn main() {} | fn h<'a, T, U>(v: Box<A<U>+'static>) -> Box<X+'static> {
box B(&*v) as Box<X>
} | random_line_split |
regions-close-object-into-object.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 ... |
fn h<'a, T, U>(v: Box<A<U>+'static>) -> Box<X+'static> {
box B(&*v) as Box<X>
}
fn i<'a, T, U>(v: Box<A<U>>) -> Box<X+'static> {
box B(&*v) as Box<X> //~ ERROR cannot infer
}
fn main() {}
| {
box B(&*v) as Box<X> //~ ERROR cannot infer
} | identifier_body |
nntplib.py |
class NNTPReplyError(NNTPError):
"""Unexpected [123]xx reply"""
pass
class NNTPTemporaryError(NNTPError):
"""4xx errors"""
pass
class NNTPPermanentError(NNTPError):
"""5xx errors"""
pass
class NNTPProtocolError(NNTPError):
"""Response does not begin with [1-5]"""
pass
class NNTPDat... | """Base class for all nntplib exceptions"""
def __init__(self, *args):
apply(Exception.__init__, (self,)+args)
try:
self.response = args[0]
except IndexError:
self.response = 'No response given' | identifier_body | |
nntplib.py | self, host, port=NNTP_PORT, user=None, password=None,
readermode=None):
"""Initialize an instance. Arguments:
- host: hostname to connect to
- port: port to connect to (default the standard NNTP port)
- user: username to authenticate with
- password: password to... |
self.putline(line)
def getline(self):
"""Internal: return one line from the server, stripping CRLF.
Raise EOFError if the connection is closed."""
line = self.file.readline()
if self.debugging > 1:
print '*get*', `line`
if not line: raise EOFError
... | print '*cmd*', `line` | conditional_block |
nntplib.py | =None):
"""Initialize an instance. Arguments:
- host: hostname to connect to
- port: port to connect to (default the standard NNTP port)
- user: username to authenticate with
- password: password to use with username
- readermode: if true, send 'mode reader' command afte... | head | identifier_name | |
nntplib.py | self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((self.host, self.port))
self.file = self.sock.makefile('rb')
self.debugging = 0
self.welcome = self.getresp()
# 'mode reader' is sometimes necessary to enable 'reader' mode.
# However... | random_line_split | ||
lineartist.py | from typing import Any
from typing import List
from typing import Optional
from typing import Union
import bpy
import compas_blender
from compas.artists import PrimitiveArtist
from compas.geometry import Line
from compas.colors import Color
from compas_blender.artists import BlenderArtist
class LineArtist(BlenderAr... | def draw(self, color: Optional[Color] = None, show_points: bool = False) -> List[bpy.types.Object]:
"""Draw the line.
Parameters
----------
color : tuple[int, int, int] | tuple[float, float, float] | :class:`~compas.colors.Color`, optional
The RGB color of the box.
... | random_line_split | |
lineartist.py | from typing import Any
from typing import List
from typing import Optional
from typing import Union
import bpy
import compas_blender
from compas.artists import PrimitiveArtist
from compas.geometry import Line
from compas.colors import Color
from compas_blender.artists import BlenderArtist
class LineArtist(BlenderAr... |
lines = [
{'start': start, 'end': end, 'color': color, 'name': f"{self.primitive.name}"},
]
objects += compas_blender.draw_lines(lines, collection=self.collection)
return objects
| points = [
{'pos': start, 'name': f"{self.primitive.name}.start", 'color': color, 'radius': 0.01},
{'pos': end, 'name': f"{self.primitive.name}.end", 'color': color, 'radius': 0.01},
]
objects += compas_blender.draw_points(points, collection=self.collection) | conditional_block |
lineartist.py | from typing import Any
from typing import List
from typing import Optional
from typing import Union
import bpy
import compas_blender
from compas.artists import PrimitiveArtist
from compas.geometry import Line
from compas.colors import Color
from compas_blender.artists import BlenderArtist
class LineArtist(BlenderAr... | from compas_blender.artists import LineArtist
line = Line([0, 0, 0], [1, 1, 1])
artist = LineArtist(line)
artist.draw()
Or, use the artist through the plugin mechanism.
.. code-block:: python
from compas.geometry import Line
from compas.artists import Artist
... | """Artist for drawing lines in Blender.
Parameters
----------
line : :class:`~compas.geometry.Line`
A COMPAS line.
collection : str | :blender:`bpy.types.Collection`
The Blender scene collection the object(s) created by this artist belong to.
**kwargs : dict, optional
Additi... | identifier_body |
lineartist.py | from typing import Any
from typing import List
from typing import Optional
from typing import Union
import bpy
import compas_blender
from compas.artists import PrimitiveArtist
from compas.geometry import Line
from compas.colors import Color
from compas_blender.artists import BlenderArtist
class LineArtist(BlenderAr... | (self, color: Optional[Color] = None, show_points: bool = False) -> List[bpy.types.Object]:
"""Draw the line.
Parameters
----------
color : tuple[int, int, int] | tuple[float, float, float] | :class:`~compas.colors.Color`, optional
The RGB color of the box.
The d... | draw | identifier_name |
mod.rs | // Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
pub mod device;
pub mod event_handler;
pub mod persist;
pub mod test_utils;
mod utils;
use vm_memory::GuestMemoryError;
pub use self::device::Balloon;
pub use self::device::BalloonConfig;
pub use self::d... | {
AddressTranslation,
MalformedRange,
MadviseFail(std::io::Error),
MmapFail(std::io::Error),
RegionNotFound,
}
pub type Result<T> = std::result::Result<T, Error>;
| RemoveRegionError | identifier_name |
mod.rs | // Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
pub mod device;
pub mod event_handler;
pub mod persist;
pub mod test_utils;
mod utils;
use vm_memory::GuestMemoryError;
pub use self::device::Balloon;
pub use self::device::BalloonConfig;
pub use self::d... | const VIRTIO_BALLOON_S_MINFLT: u16 = 3;
const VIRTIO_BALLOON_S_MEMFREE: u16 = 4;
const VIRTIO_BALLOON_S_MEMTOT: u16 = 5;
const VIRTIO_BALLOON_S_AVAIL: u16 = 6;
const VIRTIO_BALLOON_S_CACHES: u16 = 7;
const VIRTIO_BALLOON_S_HTLB_PGALLOC: u16 = 8;
const VIRTIO_BALLOON_S_HTLB_PGFAIL: u16 = 9;
#[derive(Debug)]
pub enum Er... | // The statistics tags.
const VIRTIO_BALLOON_S_SWAP_IN: u16 = 0;
const VIRTIO_BALLOON_S_SWAP_OUT: u16 = 1;
const VIRTIO_BALLOON_S_MAJFLT: u16 = 2; | random_line_split |
return.js | 'use strict';
/*!
* Snakeskin
* https://github.com/SnakeskinTpl/Snakeskin
*
* Released under the MIT license
* https://github.com/SnakeskinTpl/Snakeskin/blob/master/LICENSE
*/
import Snakeskin from '../core';
import { ws } from '../helpers/string';
import { any } from '../helpers/gcc';
Snakeskin.addDirective(
... | str += 'return false;';
}
this.append(str);
}
); | str += def;
this.deferReturn = 1;
}
| random_line_split |
return.js | 'use strict';
/*!
* Snakeskin
* https://github.com/SnakeskinTpl/Snakeskin
*
* Released under the MIT license
* https://github.com/SnakeskinTpl/Snakeskin/blob/master/LICENSE
*/
import Snakeskin from '../core';
import { ws } from '../helpers/string';
import { any } from '../helpers/gcc';
Snakeskin.addDirective(
... |
} else {
str += 'return false;';
}
} else {
if (parent && !this.getGroup('async')[parent.target.name]) {
str += def;
this.deferReturn = 1;
}
str += 'return false;';
}
this.append(str);
}
);
| {
str += ws`
if (typeof arguments[0] === 'function') {
return arguments[0](__RETURN_VAL__);
}
return false;
`;
} | conditional_block |
syncedgetputdelete.js | const log = require('./log');
function shareFirst(path) {
return ( this.backend === 'dropbox' &&
path.match(/^\/public\/.*[^\/]$/) );
}
function maxAgeInvalid(maxAge) {
return maxAge !== false && typeof(maxAge) !== 'number';
}
var SyncedGetPutDelete = {
get: function (path, maxAge) {
if (this.lo... | self._emit('wire-done', { success: true });
return Promise.resolve(r);
}, function (err) {
self._emit('wire-done', { success: false });
return Promise.reject(err);
});
}
};
module.exports = SyncedGetPutDelete; | random_line_split | |
syncedgetputdelete.js | const log = require('./log');
function shareFirst(path) {
return ( this.backend === 'dropbox' &&
path.match(/^\/public\/.*[^\/]$/) );
}
function maxAgeInvalid(maxAge) {
return maxAge !== false && typeof(maxAge) !== 'number';
}
var SyncedGetPutDelete = {
get: function (path, maxAge) {
if (this.lo... | else {
return SyncedGetPutDelete._wrapBusyDone.call(this, this.remote.delete(path));
}
},
_wrapBusyDone: function (result) {
var self = this;
this._emit('wire-busy');
return result.then(function (r) {
self._emit('wire-done', { success: true });
return Promise.resolve(r);
}, f... | {
return this.local.delete(path);
} | conditional_block |
syncedgetputdelete.js | const log = require('./log');
function shareFirst(path) |
function maxAgeInvalid(maxAge) {
return maxAge !== false && typeof(maxAge) !== 'number';
}
var SyncedGetPutDelete = {
get: function (path, maxAge) {
if (this.local) {
if (maxAge === undefined) {
if ((typeof this.remote === 'object') &&
this.remote.connected && this.remote.online) {... | {
return ( this.backend === 'dropbox' &&
path.match(/^\/public\/.*[^\/]$/) );
} | identifier_body |
syncedgetputdelete.js | const log = require('./log');
function | (path) {
return ( this.backend === 'dropbox' &&
path.match(/^\/public\/.*[^\/]$/) );
}
function maxAgeInvalid(maxAge) {
return maxAge !== false && typeof(maxAge) !== 'number';
}
var SyncedGetPutDelete = {
get: function (path, maxAge) {
if (this.local) {
if (maxAge === undefined) {
i... | shareFirst | identifier_name |
webpack.config.js | const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
'vanilla-counter': [
'webpack-hot-middleware/client',
'./example/vanilla-counter/index.js'
],
'react-counter': [
'webpack-hot-middleware/client',
'./... | 'react-user': [
'webpack-hot-middleware/client',
'./example/react-user/index.js'
],
},
output: {
path: path.join(__dirname, 'example'),
filename: '[name]/bundle.[name].js',
publicPath: '/'
},
plugins: [
new webpack.HotModuleReplacem... | 'react-todo': [
'webpack-hot-middleware/client',
'./example/react-todo/index.js'
], | random_line_split |
render.py | pygments.lexer import RegexLexer
from pygments.formatters import *
except ImportError:
logger.info("pygments package not found, no renderer defined")
has_pygments = False
class TokenType(type):
def __getattr__(cls,key):
return key
class Token:
__metaclass__ = TokenType
... |
cz = max(cz,self.rows[i].colsize(c))
return cz
@property
def width(self):
sep = self.rowparams.get('sep','')
cs = self.ncols*len(sep)
return sum(self.colsize.values(),cs)
def setcolsize(self,c,value):
self.colsize[c] = value
def addrow(self,toks):
... | if squash: continue | conditional_block |
render.py | pygments.lexer import RegexLexer
from pygments.formatters import *
except ImportError:
logger.info("pygments package not found, no renderer defined")
has_pygments = False
class TokenType(type):
def __getattr__(cls,key):
return key
class Token:
__metaclass__ = TokenType
... | self.maxwidth = float('inf')
self.align = '<'
self.fill = ' '
self.separator = ''
self.cols = self.cut()
def cut(self):
C = []
c = []
for t in self.toks:
c.append(t)
if t[0]==Token.Column:
C.appen... | self.toks = [(t,unicode(s)) for (t,s) in toks] | random_line_split |
render.py | pygments.lexer import RegexLexer
from pygments.formatters import *
except ImportError:
logger.info("pygments package not found, no renderer defined")
has_pygments = False
class TokenType(type):
def __getattr__(cls,key):
return key
class Token:
__metaclass__ = TokenType
... | (self,*rr):
for c in range(self.ncols):
cz = self.colsize.get(c,0) if len(rr)>0 else 0
self.colsize[c] = max(cz,self.getcolsize(c,rr,squash=False))
def getcolsize(self,c,rr=None,squash=True):
cz = 0
if not rr: rr = range(self.nrows)
for i in rr:
i... | update | identifier_name |
render.py | pygments.lexer import RegexLexer
from pygments.formatters import *
except ImportError:
logger.info("pygments package not found, no renderer defined")
has_pygments = False
class TokenType(type):
def __getattr__(cls,key):
return key
class Token:
__metaclass__ = TokenType
... |
def showall(self):
self.hidden_r = set()
self.rowparams['hidden_c'] = set()
self.hidden_c = self.rowparams['hidden_c']
return self
def grep(self,regex,col=None,invert=False):
L = set()
R = range(self.nrows)
for i in R:
if i in self.hidden_r:... | self.hidden_c.remove(n) | identifier_body |
datastream.py | import energykit
import tornado.web
class _Handler(tornado.web.RequestHandler):
def initialize(self, stream):
self.stream = stream
def get(self):
self.write_form()
def post(self):
value = self.get_argument('value', '50')
if value: self.stream.set_value(value)
self.write_form()
def write_... | (self, value):
self._value = value
self._time = energykit.Time.now()
self.publish(self.get_datapoint(), self)
def get_datapoint(self):
return energykit.DataPoint(self._time, self._value)
| set_value | identifier_name |
datastream.py | import energykit
import tornado.web
class _Handler(tornado.web.RequestHandler):
def initialize(self, stream):
self.stream = stream
def get(self):
self.write_form()
def post(self):
value = self.get_argument('value', '50')
if value: self.stream.set_value(value)
self.write_form()
def write_... |
class DataStream(energykit.DataStream):
def __init__(self, source, port, type=energykit.ValueType.POWER):
super(DataStream, self).__init__(source, port, type)
self._value = '50'
self._time = energykit.Time.now()
app = tornado.web.Application([
(r'/', _Handler, dict(stream=self)),
(r'/f... | def get(self):
pass | identifier_body |
datastream.py | import energykit
import tornado.web
class _Handler(tornado.web.RequestHandler):
def initialize(self, stream):
self.stream = stream
def get(self):
self.write_form()
def post(self):
value = self.get_argument('value', '50')
if value: |
self.write_form()
def write_form(self):
self.write('''
<!doctype html>
<title>Fake DataStream %d</title>
<form method=post>
<p><i>P</i> = <input name=value type=number min=0 step=.5 value="%s" autofocus> W
</form>
''' % (self.stream.key, self.stream._value))
class _Ignorer(tornado.web.RequestHandler):
... | self.stream.set_value(value) | conditional_block |
datastream.py | import energykit
import tornado.web
class _Handler(tornado.web.RequestHandler):
def initialize(self, stream):
self.stream = stream
def get(self):
self.write_form()
def post(self):
value = self.get_argument('value', '50')
if value: self.stream.set_value(value)
self.write_form()
def write_... | pass
class DataStream(energykit.DataStream):
def __init__(self, source, port, type=energykit.ValueType.POWER):
super(DataStream, self).__init__(source, port, type)
self._value = '50'
self._time = energykit.Time.now()
app = tornado.web.Application([
(r'/', _Handler, dict(stream=self)),
... | </form>
''' % (self.stream.key, self.stream._value))
class _Ignorer(tornado.web.RequestHandler):
def get(self): | random_line_split |
renderer.rs | use crate::papers::{DocumentSpec, Workspace};
use crate::prelude::*;
use futures::{compat::*, StreamExt};
use slog::{debug, error};
use std::process::Command;
use tokio::{fs::File, io::AsyncWrite};
use tokio_process::CommandExt;
/// The name of the downloaded template inside our Tera instance.
const TEMPLATE_NAME: &st... |
debug!(&self.workspace.logger(), "LaTeX succeeded. Stdout:\n{}", stdout);
Ok(())
}
/// Report failure and move on.
async fn report_failure(&self, error: failure::Error) -> Result<(), ()> {
error!(
self.workspace.logger(),
"Error rendering document: {:?}.",... | {
return Err(format_err!("LaTeX failed. Stdout:\n{}", stdout));
} | conditional_block |
renderer.rs | use crate::papers::{DocumentSpec, Workspace};
use crate::prelude::*;
use futures::{compat::*, StreamExt};
use slog::{debug, error};
use std::process::Command;
use tokio::{fs::File, io::AsyncWrite};
use tokio_process::CommandExt;
/// The name of the downloaded template inside our Tera instance.
const TEMPLATE_NAME: &st... | (&self) -> Result<(), failure::Error> {
let rendered_template = self
.tera
.render(TEMPLATE_NAME, &self.document_spec.variables())
.map_err(|err| format_err!("Rendering error: {}.", err))?;
debug!(
self.workspace.logger(),
"Writing template to... | render_template | identifier_name |
renderer.rs | use crate::papers::{DocumentSpec, Workspace};
use crate::prelude::*;
use futures::{compat::*, StreamExt};
use slog::{debug, error};
use std::process::Command;
use tokio::{fs::File, io::AsyncWrite};
use tokio_process::CommandExt;
/// The name of the downloaded template inside our Tera instance.
const TEMPLATE_NAME: &st... |
debug!(
self.workspace.logger(),
"Template successfully written to {:?}.",
&self.template_path()
);
Ok(())
}
async fn run_latex(&self) -> Result<(), failure::Error> {
debug!(
&self.workspace.logger(),
"Value of templ... | {
let rendered_template = self
.tera
.render(TEMPLATE_NAME, &self.document_spec.variables())
.map_err(|err| format_err!("Rendering error: {}.", err))?;
debug!(
self.workspace.logger(),
"Writing template to {:?}.",
&self.template_pa... | identifier_body |
renderer.rs | use crate::papers::{DocumentSpec, Workspace};
use crate::prelude::*;
use futures::{compat::*, StreamExt};
use slog::{debug, error};
use std::process::Command;
use tokio::{fs::File, io::AsyncWrite};
use tokio_process::CommandExt;
/// The name of the downloaded template inside our Tera instance.
const TEMPLATE_NAME: &st... | "Value of template_path: {:?}.",
self.template_path()
);
debug!(
&self.workspace.logger(),
"Rendered template exists: {:?}.",
self.template_path().exists()
);
debug!(&self.workspace.logger(), "Spawning latex.");
let lat... | async fn run_latex(&self) -> Result<(), failure::Error> {
debug!(
&self.workspace.logger(), | random_line_split |
libp2pserver.ts | import PeerId from 'peer-id'
import crypto from 'libp2p-crypto'
import multiaddr from 'multiaddr'
import { Libp2pConnection as Connection } from '../../types'
import { Libp2pNode } from '../peer/libp2pnode'
import { Libp2pPeer } from '../peer'
import { Server, ServerOptions } from './server'
export interface Libp2pSer... |
getPeerInfo(connection: Connection): [PeerId, multiaddr] {
return [connection.remotePeer, connection.remoteAddr]
}
createPeer(peerId: PeerId, multiaddrs?: multiaddr[]) {
const peer = new Libp2pPeer({
config: this.config,
id: peerId.toB58String(),
multiaddrs,
protocols: Array.fro... | {
const privKey = await crypto.keys.generateKeyPairFromSeed('ed25519', this.key, 512)
const protoBuf = crypto.keys.marshalPrivateKey(privKey)
return PeerId.createFromPrivKey(protoBuf)
} | identifier_body |
libp2pserver.ts | import PeerId from 'peer-id'
import crypto from 'libp2p-crypto'
import multiaddr from 'multiaddr'
import { Libp2pConnection as Connection } from '../../types'
import { Libp2pNode } from '../peer/libp2pnode'
import { Libp2pPeer } from '../peer'
import { Server, ServerOptions } from './server'
export interface Libp2pSer... | (peerId: string, maxAge = 60000): boolean {
if (!this.started) {
return false
}
this.banned.set(peerId, Date.now() + maxAge)
return true
}
/**
* Check if peer is currently banned
* @param peerId id of peer
* @return true if banned
*/
isBanned(peerId: string): boolean {
cons... | ban | identifier_name |
libp2pserver.ts | import PeerId from 'peer-id'
import crypto from 'libp2p-crypto'
import multiaddr from 'multiaddr'
import { Libp2pConnection as Connection } from '../../types'
import { Libp2pNode } from '../peer/libp2pnode'
import { Libp2pPeer } from '../peer'
import { Server, ServerOptions } from './server'
export interface Libp2pSer... | * Server name
* @type {string}
*/
get name() {
return 'libp2p'
}
/**
* Start Libp2p server. Returns a promise that resolves once server has been started.
* @return Resolves with true if server successfully started
*/
async start(): Promise<boolean> {
if (this.started) {
return f... |
/** | random_line_split |
libp2pserver.ts | import PeerId from 'peer-id'
import crypto from 'libp2p-crypto'
import multiaddr from 'multiaddr'
import { Libp2pConnection as Connection } from '../../types'
import { Libp2pNode } from '../peer/libp2pnode'
import { Libp2pPeer } from '../peer'
import { Server, ServerOptions } from './server'
export interface Libp2pSer... |
let peerId: PeerId
await super.start()
if (!this.node) {
peerId = await this.getPeerId()
const addresses = { listen: this.multiaddrs.map((ma) => ma.toString()) }
this.node = new Libp2pNode({
peerId,
addresses,
bootnodes: this.bootnodes,
})
this.protocol... | {
return false
} | conditional_block |
ClientListComponent.js | import React from 'react';
import _ from 'lodash';
import moment from 'moment';
import ClientListFilterComponent from './ClientListFilterComponent';
import ClientListItemComponent from './ClientListItemComponent';
class ClientListComponent extends React.Component {
constructor() {
super();
this.state = {
... | () {
return (
<div>
<ClientListFilterComponent
gridView={this.state.gridView}
changeToGridView={boolean => this.setGridView(boolean)}
orderByDate={this.state.orderByDate}
handleClick={boolean => this.setSortedByDateState(boolean)}
/>
<ul classNa... | render | identifier_name |
ClientListComponent.js | import React from 'react';
import _ from 'lodash';
import moment from 'moment';
import ClientListFilterComponent from './ClientListFilterComponent';
import ClientListItemComponent from './ClientListItemComponent';
class ClientListComponent extends React.Component {
constructor() {
super();
this.state = {
... |
setSortedByDateState(boolean) {
this.setState({
orderByDate: boolean
})
}
chooseOrderByType() {
return this.state.orderByDate ? this.orderByDate() : this.orderByAlphabet();
}
orderByAlphabet() {
return _.orderBy(this.props.clientlist, 'clientName', 'asc');
}
orderByDate() {
r... | setGridView(boolean) {
this.setState({
gridView: boolean
})
} | random_line_split |
ClientListComponent.js | import React from 'react';
import _ from 'lodash';
import moment from 'moment';
import ClientListFilterComponent from './ClientListFilterComponent';
import ClientListItemComponent from './ClientListItemComponent';
class ClientListComponent extends React.Component {
constructor() {
super();
this.state = {
... |
chooseOrderByType() {
return this.state.orderByDate ? this.orderByDate() : this.orderByAlphabet();
}
orderByAlphabet() {
return _.orderBy(this.props.clientlist, 'clientName', 'asc');
}
orderByDate() {
return _.orderBy(this.props.clientlist, 'submitDate', 'desc');
}
render() {
return (... | {
this.setState({
orderByDate: boolean
})
} | identifier_body |
batchutils.py | import plugins, datetime, time, os
class BatchVersionFilter:
def __init__(self, batchSession):
self.batchSession = batchSession
def verifyVersions(self, app):
badVersion = self.findUnacceptableVersion(app) | return
allowedVersions = app.getCompositeConfigValue("batch_version", self.batchSession)
for version in app.versions:
if len(version) > 0 and version not in allowedVersions and not version.startswith("copy_"):
return version
def calculateBatchDate():
... | if badVersion is not None:
raise plugins.TextTestError, "unregistered version '" + badVersion + "' for " + self.batchSession + " session."
def findUnacceptableVersion(self, app):
if app.getCompositeConfigValue("batch_use_version_filtering", self.batchSession) != "true": | random_line_split |
batchutils.py | import plugins, datetime, time, os
class BatchVersionFilter:
|
def calculateBatchDate():
# Batch mode uses a standardised date that give a consistent answer for night-jobs.
# Hence midnight is a bad cutover point. The day therefore starts and ends at 8am :)
timeToUse = plugins.globalStartTime - datetime.timedelta(hours=8)
return timeToUse.strftime("%d%b%Y")
def... | def __init__(self, batchSession):
self.batchSession = batchSession
def verifyVersions(self, app):
badVersion = self.findUnacceptableVersion(app)
if badVersion is not None:
raise plugins.TextTestError, "unregistered version '" + badVersion + "' for " + self.batchSession + " sessi... | identifier_body |
batchutils.py | import plugins, datetime, time, os
class BatchVersionFilter:
def __init__(self, batchSession):
self.batchSession = batchSession
def | (self, app):
badVersion = self.findUnacceptableVersion(app)
if badVersion is not None:
raise plugins.TextTestError, "unregistered version '" + badVersion + "' for " + self.batchSession + " session."
def findUnacceptableVersion(self, app):
if app.getCompositeConfigValue("batch_us... | verifyVersions | identifier_name |
batchutils.py | import plugins, datetime, time, os
class BatchVersionFilter:
def __init__(self, batchSession):
self.batchSession = batchSession
def verifyVersions(self, app):
badVersion = self.findUnacceptableVersion(app)
if badVersion is not None:
|
def findUnacceptableVersion(self, app):
if app.getCompositeConfigValue("batch_use_version_filtering", self.batchSession) != "true":
return
allowedVersions = app.getCompositeConfigValue("batch_version", self.batchSession)
for version in app.versions:
if len(... | raise plugins.TextTestError, "unregistered version '" + badVersion + "' for " + self.batchSession + " session." | conditional_block |
main.rs | #![feature(slicing_syntax)]
#![feature(box_syntax)]
extern crate getopts;
#[macro_use]
extern crate linked_list;
use std::io;
use std::mem;
use std::iter::repeat;
use lib::{
SEle,
Env,
LamOrFn,
ScmAlert,
ScmAlertMode,
scheme_alert,
scheme_stdlib};
use lib::scm_macro::PrecompileEnv;
mod input;
mod lib;
mod pa... |
/// How many more closing parens there are than opening parens
fn close_paren_surplus(ts: &[parse::Token]) -> i32 {
use parse::Token::{OpenParen, CloseParen};
ts.iter().fold(0i32, |acc, t| match *t {
OpenParen => acc-1,
CloseParen => acc+1,
_ => acc })
}
fn interactive_shell(env: &mut Env, macro_env: &... | {
slc.iter().map(|s| s.to_string()).collect()
} | identifier_body |
main.rs | #![feature(slicing_syntax)]
#![feature(box_syntax)]
extern crate getopts;
#[macro_use]
extern crate linked_list;
use std::io;
use std::mem;
use std::iter::repeat;
use lib::{
SEle,
Env,
LamOrFn,
ScmAlert,
ScmAlertMode,
scheme_alert,
scheme_stdlib};
use lib::scm_macro::PrecompileEnv;
mod input;
mod lib;
mod pa... | (ts: &[parse::Token]) -> i32 {
use parse::Token::{OpenParen, CloseParen};
ts.iter().fold(0i32, |acc, t| match *t {
OpenParen => acc-1,
CloseParen => acc+1,
_ => acc })
}
fn interactive_shell(env: &mut Env, macro_env: &mut PrecompileEnv) {
print!("scheme-rs interactive shell. Copyright (C) 2014 Johan Jo... | close_paren_surplus | identifier_name |
main.rs | #![feature(slicing_syntax)]
#![feature(box_syntax)]
extern crate getopts;
#[macro_use]
extern crate linked_list;
use std::io;
use std::mem;
use std::iter::repeat;
use lib::{
SEle,
Env,
LamOrFn,
ScmAlert,
ScmAlertMode,
scheme_alert,
scheme_stdlib};
use lib::scm_macro::PrecompileEnv;
mod input;
mod lib;
mod pa... |
/// How many more closing parens there are than opening parens
fn close_paren_surplus(ts: &[parse::Token]) -> i32 {
use parse::Token::{OpenParen, CloseParen};
ts.iter().fold(0i32, |acc, t| match *t {
OpenParen => acc-1,
CloseParen => acc+1,
_ => acc })
}
fn interactive_shell(env: &mut Env, macro_env: &m... | slc.iter().map(|s| s.to_string()).collect()
} | random_line_split |
main.rs | #![feature(slicing_syntax)]
#![feature(box_syntax)]
extern crate getopts;
#[macro_use]
extern crate linked_list;
use std::io;
use std::mem;
use std::iter::repeat;
use lib::{
SEle,
Env,
LamOrFn,
ScmAlert,
ScmAlertMode,
scheme_alert,
scheme_stdlib};
use lib::scm_macro::PrecompileEnv;
mod input;
mod lib;
mod pa... | else {
token_buf.push((line_n, tokens));
{
let parsed_and_expanded = parse::parse_token_lines(
mem::replace(&mut token_buf, Vec::with_capacity(3)))
.into_iter().map(|e| macro_env.expand(e)).collect();
print!("{}\n>> ", env.eval_sequence(parsed_and_expanded));
}
line_n = 1;
rparen_surp... | {
scheme_alert(ScmAlert::Unexp(")"), &ScmAlertMode::Warn);
token_buf.clear();
line_n = 1;
rparen_surplus = 0;
print!(">> ");
} | conditional_block |
grove_sound_sensor.py | #!/usr/bin/env python
#
# Jetduino Example for using the Grove Sound Sensor and the Grove LED
#
# The Jetduino connects the Jetson and Grove sensors. You can learn more about the Jetduino here: http://www.NeuroRoboticTech.com/Projects/Jetduino
#
# Modules:
# http://www.seeedstudio.com/wiki/Grove_-_Sound_Sensor
# ht... |
except IOError:
print ("Error") | random_line_split | |
grove_sound_sensor.py | #!/usr/bin/env python
#
# Jetduino Example for using the Grove Sound Sensor and the Grove LED
#
# The Jetduino connects the Jetson and Grove sensors. You can learn more about the Jetduino here: http://www.NeuroRoboticTech.com/Projects/Jetduino
#
# Modules:
# http://www.seeedstudio.com/wiki/Grove_-_Sound_Sensor
# ht... | try:
# Read the sound level
sensor_value = jetduino.analogRead(sound_sensor)
# If loud, illuminate LED, otherwise dim
if sensor_value > threshold_value:
jetduino.digitalWrite(led, HIGH)
else:
jetduino.digitalWrite(led, LOW)
print ("sensor_value =... | conditional_block | |
groupby.js | /* */
"format cjs";
/**
* Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function.
*
* @example
* var res = observable.groupBy(function (x) { return x.id; });
* 2 - observable.groupBy(... | return this.groupByUntil(keySelector, elementSelector, observableNever, comparer);
}; | random_line_split | |
move_raw_cmip5_tas_pr.py | # # # # #
# MOVE THE NEWLY DOWNLOADED TAS / PR CMIP5 data from work desktop to /Shared
# # # # #
def move_new_dir( fn, output_dir ):
dirname, basename = os.path.split( fn )
elems = basename.split('.')[0].split( '_' )
variable, cmor_table, model, scenario, experiment, years = elems
new_dir = os.path.join( output_... |
out = [ move_new_dir( fn, output_dir ) for fn in filelist ]
# # # # # # # #
# # CHECK FOR DUPLICATES and remove by hand. this is tedious.
# GFDL - OK
# CCSM4 - FIXED OK
# GISS-E2-R - OK
# IPSL - OK
# MRI - OK | filelist = filelist + [ os.path.join( root, i ) for i in files if i.endswith( '.nc' ) ] | conditional_block |
move_raw_cmip5_tas_pr.py | # # # # #
# MOVE THE NEWLY DOWNLOADED TAS / PR CMIP5 data from work desktop to /Shared
# # # # #
def move_new_dir( fn, output_dir ):
|
if __name__ == '__main__':
import os, glob, shutil
path = '/srv/synda/sdt/data'
output_dir = '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/raw_cmip5_tas_pr'
filelist = []
for root, subs, files in os.walk( path ):
if len( files ) > 0:
filelist = filelist + [ os.path.join( root, i ) for i... | dirname, basename = os.path.split( fn )
elems = basename.split('.')[0].split( '_' )
variable, cmor_table, model, scenario, experiment, years = elems
new_dir = os.path.join( output_dir, model, scenario, variable )
try:
if not os.path.exists( new_dir ):
os.makedirs( new_dir )
except:
pass
return shutil.copy(... | identifier_body |
move_raw_cmip5_tas_pr.py | # # # # #
# MOVE THE NEWLY DOWNLOADED TAS / PR CMIP5 data from work desktop to /Shared
# # # # #
def | ( fn, output_dir ):
dirname, basename = os.path.split( fn )
elems = basename.split('.')[0].split( '_' )
variable, cmor_table, model, scenario, experiment, years = elems
new_dir = os.path.join( output_dir, model, scenario, variable )
try:
if not os.path.exists( new_dir ):
os.makedirs( new_dir )
except:
pass... | move_new_dir | identifier_name |
move_raw_cmip5_tas_pr.py | # # # # #
# MOVE THE NEWLY DOWNLOADED TAS / PR CMIP5 data from work desktop to /Shared | elems = basename.split('.')[0].split( '_' )
variable, cmor_table, model, scenario, experiment, years = elems
new_dir = os.path.join( output_dir, model, scenario, variable )
try:
if not os.path.exists( new_dir ):
os.makedirs( new_dir )
except:
pass
return shutil.copy( fn, new_dir )
if __name__ == '__main__... | # # # # #
def move_new_dir( fn, output_dir ):
dirname, basename = os.path.split( fn ) | random_line_split |
person.ts | import angular from 'angular';
import { cloneDeep } from 'lodash';
export default function(app) {
app.service('personService', class personService {
static $inject = ['authService', 'peopleApi'];
| (public authService, public peopleApi) {}
emailAdd(personId, email, setAsDefault) {
return this.peopleApi.emailAdd(
personId,
email,
setAsDefault,
this.authService.frontendUrl,
this.authService.returnPath,
);
}
update(person) {
const id = person.id... | constructor | identifier_name |
person.ts | import angular from 'angular';
import { cloneDeep } from 'lodash';
export default function(app) {
app.service('personService', class personService {
static $inject = ['authService', 'peopleApi'];
constructor(public authService, public peopleApi) {}
emailAdd(personId, email, setAsDefault) |
update(person) {
const id = person.id;
const _person = cloneDeep(person);
['id', 'gravatarMd5', 'firstSignin', 'createdAt', 'updatedAt', 'externalIds']
.forEach(key => delete _person[key]);
delete _person.account.createdAt;
delete _person.account.featureFlags;
return t... | {
return this.peopleApi.emailAdd(
personId,
email,
setAsDefault,
this.authService.frontendUrl,
this.authService.returnPath,
);
} | identifier_body |
person.ts | import angular from 'angular';
import { cloneDeep } from 'lodash';
export default function(app) {
app.service('personService', class personService {
static $inject = ['authService', 'peopleApi'];
constructor(public authService, public peopleApi) {}
emailAdd(personId, email, setAsDefault) {
return... | this.authService.returnPath,
);
}
update(person) {
const id = person.id;
const _person = cloneDeep(person);
['id', 'gravatarMd5', 'firstSignin', 'createdAt', 'updatedAt', 'externalIds']
.forEach(key => delete _person[key]);
delete _person.account.createdAt;
d... | random_line_split | |
interface.js | var assert = require('./assert');
var isTypeName = require('./isTypeName');
var String = require('./String');
var Function = require('./Function');
var isBoolean = require('./isBoolean');
var isObject = require('./isObject');
var isNil = require('./isNil');
var create = require('./create');
var getTypeName = require('.... | return true;
};
Interface.update = function (instance, patch) {
return Interface(assert.update(instance, patch));
};
Interface.extend = function (xs, name) {
return extendInterface([Interface].concat(xs), name);
};
return Interface;
}
inter.strict = false;
inter.getOptions = getOptions;
inte... | for (var prop in props) {
if (!is(x[prop], props[prop])) {
return false;
}
} | random_line_split |
interface.js | var assert = require('./assert');
var isTypeName = require('./isTypeName');
var String = require('./String');
var Function = require('./Function');
var isBoolean = require('./isBoolean');
var isObject = require('./isObject');
var isNil = require('./isNil');
var create = require('./create');
var getTypeName = require('.... | }
}
if (process.env.NODE_ENV !== 'production') {
path = path || [displayName];
assert(!isNil(value), function () { return 'Invalid value ' + value + ' supplied to ' + path.join('/'); });
// strictness
if (strict) {
for (var k in value) {
assert(props.hasOwnProper... | {
options = getOptions(options);
var name = options.name;
var strict = options.strict;
if (process.env.NODE_ENV !== 'production') {
assert(dict(String, Function).is(props), function () { return 'Invalid argument props ' + assert.stringify(props) + ' supplied to interface(props, [options]) combinator (expe... | identifier_body |
interface.js | var assert = require('./assert');
var isTypeName = require('./isTypeName');
var String = require('./String');
var Function = require('./Function');
var isBoolean = require('./isBoolean');
var isObject = require('./isObject');
var isNil = require('./isNil');
var create = require('./create');
var getTypeName = require('.... |
if (process.env.NODE_ENV !== 'production') {
Object.freeze(ret);
}
return ret;
}
Interface.meta = {
kind: 'interface',
props: props,
name: name,
identity: identity,
strict: strict
};
Interface.displayName = displayName;
Interface.is = function (x) {
if (strict)... | { // implements idempotency
ret = value;
} | conditional_block |
interface.js | var assert = require('./assert');
var isTypeName = require('./isTypeName');
var String = require('./String');
var Function = require('./Function');
var isBoolean = require('./isBoolean');
var isObject = require('./isObject');
var isNil = require('./isNil');
var create = require('./create');
var getTypeName = require('.... | (mixins, name) {
return extend(inter, mixins, name);
}
function getOptions(options) {
if (!isObject(options)) {
options = isNil(options) ? {} : { name: options };
}
if (!options.hasOwnProperty('strict')) {
options.strict = inter.strict;
}
return options;
}
function inter(props, options) {
optio... | extendInterface | identifier_name |
settings.py | """
Django settings for SimpleChat project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)... | except ImportError:
pass | random_line_split | |
inst.apk.py | #!/usr/bin/env python
import os
import shutil
import glob
import time
import sys
import subprocess
from optparse import OptionParser, make_option
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PARAMETERS = None
ADB_CMD = "adb"
def doCMD(cmd):
# Do not need handle timeout in this short script, let tool... |
def uninstPKGs():
action_status = True
for root, dirs, files in os.walk(SCRIPT_DIR):
for file in files:
if file.endswith(".apk"):
cmd = "%s -s %s uninstall org.xwalk.%s" % (
ADB_CMD, PARAMETERS.device, os.path.basename(os.path.splitext(file)[0]))
... | print "-->> \"%s\"" % cmd
output = []
cmd_return_code = 1
cmd_proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
while True:
output_line = cmd_proc.stdout.readline().strip("\r\n")
cmd_return_code = cmd_proc.poll()
if output_line =... | identifier_body |
inst.apk.py | #!/usr/bin/env python
import os
import shutil
import glob
import time
import sys
import subprocess
from optparse import OptionParser, make_option
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PARAMETERS = None
ADB_CMD = "adb"
def doCMD(cmd):
# Do not need handle timeout in this short script, let tool... |
os.system("chmod 777 %s/stablonglast2d/*.sh" % SCRIPT_DIR)
return action_status
def main():
try:
usage = "usage: inst.py -i"
opts_parser = OptionParser(usage=usage)
opts_parser.add_option(
"-s", dest="device", action="store", help="Specify device")
opts_parser.... | for file in files:
if file.endswith(".apk"):
cmd = "%s -s %s install %s" % (ADB_CMD,
PARAMETERS.device, os.path.join(root, file))
(return_code, output) = doCMD(cmd)
for line in output:
if "Fail... | conditional_block |
inst.apk.py | #!/usr/bin/env python
import os
import shutil
import glob
import time
import sys
import subprocess
from optparse import OptionParser, make_option
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PARAMETERS = None
ADB_CMD = "adb"
def doCMD(cmd):
# Do not need handle timeout in this short script, let tool... | ():
try:
usage = "usage: inst.py -i"
opts_parser = OptionParser(usage=usage)
opts_parser.add_option(
"-s", dest="device", action="store", help="Specify device")
opts_parser.add_option(
"-i", dest="binstpkg", action="store_true", help="Install package")
... | main | identifier_name |
inst.apk.py | #!/usr/bin/env python
import os
import shutil
import glob
import time
import sys
import subprocess
from optparse import OptionParser, make_option
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PARAMETERS = None
ADB_CMD = "adb"
def doCMD(cmd):
# Do not need handle timeout in this short script, let tool... | cmd_return_code = cmd_proc.poll()
if output_line == '' and cmd_return_code != None:
break
sys.stdout.write("%s\n" % output_line)
sys.stdout.flush()
output.append(output_line)
return (cmd_return_code, output)
def uninstPKGs():
action_status = True
for ro... | while True:
output_line = cmd_proc.stdout.readline().strip("\r\n") | random_line_split |
documenttype.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::DocumentTypeBinding;
use dom::bindings::codegen::Bindings::DocumentTypeBindi... |
fn SystemId(self) -> DOMString {
self.system_id.clone()
}
// http://dom.spec.whatwg.org/#dom-childnode-remove
fn Remove(self) {
let node: JSRef<Node> = NodeCast::from_ref(self);
node.remove_self();
}
}
| {
self.public_id.clone()
} | identifier_body |
documenttype.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::DocumentTypeBinding;
use dom::bindings::codegen::Bindings::DocumentTypeBindi... | (&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::DocumentType)
}
}
impl DocumentType {
fn new_inherited(name: DOMString,
public_id: Option<DOMString>,
system_id: Option<DOMString>,
document: JSRef<Documen... | is_documenttype | identifier_name |
documenttype.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::DocumentTypeBinding;
use dom::bindings::codegen::Bindings::DocumentTypeBindi... | fn PublicId(self) -> DOMString {
self.public_id.clone()
}
fn SystemId(self) -> DOMString {
self.system_id.clone()
}
// http://dom.spec.whatwg.org/#dom-childnode-remove
fn Remove(self) {
let node: JSRef<Node> = NodeCast::from_ref(self);
node.remove_self();
}
... | self.name.clone()
}
| random_line_split |
osxrelocator.py | #!/usr/bin/env python3
# cerbero - a multi-platform build system for Open Source software
# Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free S... | def list_shared_libraries(object_file):
res = shell.check_output([OTOOL_CMD, '-L', object_file]).splitlines()
# We don't use the first line
libs = res[1:]
# Remove the first character tabulation
libs = [x[1:] for x in libs]
# Remove the version info
libs = [x.... |
@staticmethod | random_line_split |
osxrelocator.py | #!/usr/bin/env python3
# cerbero - a multi-platform build system for Open Source software
# Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free S... |
for lib in self.list_shared_libraries(object_file):
if self.lib_prefix in lib:
new_lib = lib.replace(self.lib_prefix, '@rpath')
cmd = [INT_CMD, '-change', lib, new_lib, object_file]
shell.new_call(cmd, fail=False, logfile=self.logfile)
def change... | cmd = [INT_CMD, '-add_rpath', p, object_file]
shell.new_call(cmd, fail=False) | conditional_block |
osxrelocator.py | #!/usr/bin/env python3
# cerbero - a multi-platform build system for Open Source software
# Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free S... |
def _is_mach_o_file(self, filename):
return os.path.splitext(filename)[1] in ['.dylib', '.so'] or \
shell.check_output(['file', '-bh', filename]).startswith('Mach-O')
class Main(object):
def run(self):
# We use OptionParser instead of ArgumentsParse because this script
... | if path.endswith('/'):
return path[:-1]
return path | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.