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 |
|---|---|---|---|---|
distinct.ts | import { Observable } from '../Observable';
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { TeardownLogic } from '../Subscription';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '... | (private keySelector: (value: T) => K, private flushes: Observable<any>) {
}
call(subscriber: Subscriber<T>, source: any): TeardownLogic {
return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @ex... | constructor | identifier_name |
distinct.ts | import { Observable } from '../Observable';
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { TeardownLogic } from '../Subscription';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '... | innerSub: InnerSubscriber<T, T>): void {
this.values.clear();
}
notifyError(error: any, innerSub: InnerSubscriber<T, T>): void {
this._error(error);
}
protected _next(value: T): void {
if (this.keySelector) {
this._useKeySelector(value);
} else {
this._finalizeNext(val... | }
}
notifyNext(outerValue: T, innerValue: T,
outerIndex: number, innerIndex: number, | random_line_split |
distinct.ts | import { Observable } from '../Observable';
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { TeardownLogic } from '../Subscription';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '... |
}
private _useKeySelector(value: T): void {
let key: K;
const { destination } = this;
try {
key = this.keySelector(value);
} catch (err) {
destination.error(err);
return;
}
this._finalizeNext(key, value);
}
private _finalizeNext(key: K|T, value: T) {
const { valu... | {
this._finalizeNext(value, value);
} | conditional_block |
distinct.ts | import { Observable } from '../Observable';
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { TeardownLogic } from '../Subscription';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '... |
notifyError(error: any, innerSub: InnerSubscriber<T, T>): void {
this._error(error);
}
protected _next(value: T): void {
if (this.keySelector) {
this._useKeySelector(value);
} else {
this._finalizeNext(value, value);
}
}
private _useKeySelector(value: T): void {
let key: K;... | {
this.values.clear();
} | identifier_body |
all.rs | use std::collections::HashMap;
use protobuf::descriptor::FileDescriptorProto;
use protobuf::reflect::FileDescriptor;
use protobuf_parse::ProtoPath;
use protobuf_parse::ProtoPathBuf;
use crate::compiler_plugin;
use crate::customize::ctx::CustomizeElemCtx;
use crate::customize::CustomizeCallback;
use crate::gen::file::... | (
file_descriptors: &[FileDescriptorProto],
parser: &str,
files_to_generate: &[ProtoPathBuf],
customize: &Customize,
customize_callback: &dyn CustomizeCallback,
) -> anyhow::Result<Vec<compiler_plugin::GenResult>> {
let file_descriptors = FileDescriptor::new_dynamic_fds(file_descriptors.to_vec()... | gen_all | identifier_name |
all.rs | use std::collections::HashMap;
use protobuf::descriptor::FileDescriptorProto;
use protobuf::reflect::FileDescriptor;
use protobuf_parse::ProtoPath;
use protobuf_parse::ProtoPathBuf;
use crate::compiler_plugin;
use crate::customize::ctx::CustomizeElemCtx;
use crate::customize::CustomizeCallback;
use crate::gen::file::... |
Ok(results)
}
| {
results.push(gen_mod_rs(&mods));
} | conditional_block |
all.rs | use std::collections::HashMap;
use protobuf::descriptor::FileDescriptorProto;
use protobuf::reflect::FileDescriptor;
use protobuf_parse::ProtoPath;
use protobuf_parse::ProtoPathBuf;
use crate::compiler_plugin;
use crate::customize::ctx::CustomizeElemCtx;
use crate::customize::CustomizeCallback;
use crate::gen::file::... |
for file_name in files_to_generate {
let file = files_map.get(file_name.as_path()).expect(&format!(
"file not found in file descriptors: {:?}, files: {:?}",
file_name,
files_map.keys()
));
let gen_file_result = gen_file(file, &files_map, &root_scope, &cus... | {
let file_descriptors = FileDescriptor::new_dynamic_fds(file_descriptors.to_vec())?;
let root_scope = RootScope {
file_descriptors: &file_descriptors,
};
let mut results: Vec<compiler_plugin::GenResult> = Vec::new();
let files_map: HashMap<&ProtoPath, &FileDescriptor> = file_descriptors
... | identifier_body |
all.rs | use std::collections::HashMap;
use protobuf::descriptor::FileDescriptorProto;
use protobuf::reflect::FileDescriptor;
use protobuf_parse::ProtoPath;
use protobuf_parse::ProtoPathBuf;
use crate::compiler_plugin;
use crate::customize::ctx::CustomizeElemCtx;
use crate::customize::CustomizeCallback;
use crate::gen::file::... | callback: customize_callback,
};
for file_name in files_to_generate {
let file = files_map.get(file_name.as_path()).expect(&format!(
"file not found in file descriptors: {:?}, files: {:?}",
file_name,
files_map.keys()
));
let gen_file_result =... | for_children: customize.clone(), | random_line_split |
event-attendance.ts | import {
ATTENDANCE_STATUS_CONFIG_ID,
AttendanceStatusType,
NullAttendanceStatusType,
} from "./attendance-status";
import { DatabaseField } from "../../../core/entity/database-field.decorator";
/**
* Simple relationship object to represent an individual child's status at an event including context information.... | }
} | this.remarks = remarks; | random_line_split |
event-attendance.ts | import {
ATTENDANCE_STATUS_CONFIG_ID,
AttendanceStatusType,
NullAttendanceStatusType,
} from "./attendance-status";
import { DatabaseField } from "../../../core/entity/database-field.decorator";
/**
* Simple relationship object to represent an individual child's status at an event including context information.... |
set status(value) {
if (typeof value === "object") {
this._status = value;
} else {
this._status = NullAttendanceStatusType;
}
}
@DatabaseField() remarks: string;
constructor(
status: AttendanceStatusType = NullAttendanceStatusType,
remarks: string = ""
) {
this.status =... | {
return this._status;
} | identifier_body |
event-attendance.ts | import {
ATTENDANCE_STATUS_CONFIG_ID,
AttendanceStatusType,
NullAttendanceStatusType,
} from "./attendance-status";
import { DatabaseField } from "../../../core/entity/database-field.decorator";
/**
* Simple relationship object to represent an individual child's status at an event including context information.... | else {
this._status = NullAttendanceStatusType;
}
}
@DatabaseField() remarks: string;
constructor(
status: AttendanceStatusType = NullAttendanceStatusType,
remarks: string = ""
) {
this.status = status;
this.remarks = remarks;
}
}
| {
this._status = value;
} | conditional_block |
event-attendance.ts | import {
ATTENDANCE_STATUS_CONFIG_ID,
AttendanceStatusType,
NullAttendanceStatusType,
} from "./attendance-status";
import { DatabaseField } from "../../../core/entity/database-field.decorator";
/**
* Simple relationship object to represent an individual child's status at an event including context information.... | (value) {
if (typeof value === "object") {
this._status = value;
} else {
this._status = NullAttendanceStatusType;
}
}
@DatabaseField() remarks: string;
constructor(
status: AttendanceStatusType = NullAttendanceStatusType,
remarks: string = ""
) {
this.status = status;
... | status | identifier_name |
scheduler.py | #!/usr/bin/python
AGO_SCHEDULER_VERSION = '0.0.1'
############################################
"""
Basic class for device and device group schedule
"""
__author__ = "Joakim Lindbom"
__copyright__ = "Copyright 2017, Joakim Lindbom"
__date__ = "2017-01-27"
__credits__ = ["Joakim Lindbom", "The ago control ... | self.rules = None
self.schedules = []
self.log = None
self.app = app
try:
self.log = app.log
except AttributeError:
#We seem to be in test mode, need a local logger
self.log = llog()
def parseJSON(self, filename):
with op... | class Scheduler:
def __init__(self, app): | random_line_split |
scheduler.py | #!/usr/bin/python
AGO_SCHEDULER_VERSION = '0.0.1'
############################################
"""
Basic class for device and device group schedule
"""
__author__ = "Joakim Lindbom"
__copyright__ = "Copyright 2017, Joakim Lindbom"
__date__ = "2017-01-27"
__credits__ = ["Joakim Lindbom", "The ago control ... | if a["days"] == "weekdays":
x["days"] = ["mo", "tu", "we", "th", "fr"]
elif a["days"] == "weekends":
x["days"] = ["sa", "su"]
elif a["days"] == "all":
x["days"] = ["mo", "tu", "we", "th", "fr", "sa", "su"]
... | def __init__(self, jsonstr, rules=None):
self.device = None
self.scenario = None
self.group = None
if "device" in jsonstr:
self.device= jsonstr["device"]
if "scenario" in jsonstr:
self.scenario = jsonstr["scenario"]
if "group-uuid" in jsonstr:
... | identifier_body |
scheduler.py | #!/usr/bin/python
AGO_SCHEDULER_VERSION = '0.0.1'
############################################
"""
Basic class for device and device group schedule
"""
__author__ = "Joakim Lindbom"
__copyright__ = "Copyright 2017, Joakim Lindbom"
__date__ = "2017-01-27"
__credits__ = ["Joakim Lindbom", "The ago control ... | (self, log):
self.log = log
class Days:
def __init__(self):
pass
class llog:
def __init__(self):
pass
def info(self, msg):
print ("INFO: %s" % msg)
def trace(self, msg):
print ("TRACE: %s" % msg)
def debug(self, msg):
print ("DEBUG: %s" % msg)
... | addlog | identifier_name |
scheduler.py | #!/usr/bin/python
AGO_SCHEDULER_VERSION = '0.0.1'
############################################
"""
Basic class for device and device group schedule
"""
__author__ = "Joakim Lindbom"
__copyright__ = "Copyright 2017, Joakim Lindbom"
__date__ = "2017-01-27"
__credits__ = ["Joakim Lindbom", "The ago control ... |
return True
return True
def addlog(self, log):
self.log = log
class Days:
def __init__(self):
pass
class llog:
def __init__(self):
pass
def info(self, msg):
print ("INFO: %s" % msg)
def trace(self, msg):
print ("TRACE: %s" % msg)
... | if r["type"] == "variable check":
if r["variable"] == "HouseMode":
vv = "At home" # TODO: Get variable from inventory using r["variable"]
if r["variable"] == "test":
vv = "True"
if r["operator"] == 'eq':
if vv ... | conditional_block |
LatitudePlot.py | #!/usr/bin/env python
# LatitudePlot.py
# Created 30 July 2013
# Created by snowdonjames@googlemail.com
import os, time, math
from datetime import datetime
from time import mktime
import xml.etree.ElementTree as ET
from PIL import Image, ImageDraw
def GetKmlFiles():
"""Locates and reads local .kml files, returns... |
return ((((float(inputv) - float(minv)) / (float(maxv) -float(minv))) * float(size)));
def ParseImageFile():
"""Reads SatelliteImageData.csv containing:
<File name of image to draw data on>,
<image top latitude>,
<image bottom lattitude>,
<image left longitude>,
<image right longitude>,
... | return 0 | conditional_block |
LatitudePlot.py | #!/usr/bin/env python
# LatitudePlot.py
# Created 30 July 2013
# Created by snowdonjames@googlemail.com
import os, time, math
from datetime import datetime
from time import mktime
import xml.etree.ElementTree as ET
from PIL import Image, ImageDraw
def GetKmlFiles():
"""Locates and reads local .kml files, returns... |
def LongToX(InputLong, LeftLong, RightLong, ImWidth):
"""Converts a longitude value in to an x coordinate"""
return ScalingFunc(InputLong+360, LeftLong+360, RightLong+360, ImWidth);
def LatToY(InputLat, TopLat, BottomLat, ImHeight):
"""Converts a latitude value in to a y coordinate"""
return ScalingF... | """Draws kml line data on top of the specified image"""
im = Image.open(InputImage)
draw = ImageDraw.Draw(im)
cnt =0
for KmlD in KmlData:
for d in range(len(KmlD[0])-1):
#Get points x and y coordinates and draw line
x1=(LongToX(KmlD[0][d],ileft,iright,im.size[0]))+xnudge
... | identifier_body |
LatitudePlot.py | #!/usr/bin/env python
# LatitudePlot.py | # Created 30 July 2013
# Created by snowdonjames@googlemail.com
import os, time, math
from datetime import datetime
from time import mktime
import xml.etree.ElementTree as ET
from PIL import Image, ImageDraw
def GetKmlFiles():
"""Locates and reads local .kml files, returns a list of kml dictionary data"""
Kml... | random_line_split | |
LatitudePlot.py | #!/usr/bin/env python
# LatitudePlot.py
# Created 30 July 2013
# Created by snowdonjames@googlemail.com
import os, time, math
from datetime import datetime
from time import mktime
import xml.etree.ElementTree as ET
from PIL import Image, ImageDraw
def GetKmlFiles():
"""Locates and reads local .kml files, returns... | (dirname, filename):
"""Parses a single kml file, returns a dict of format {time: [lat, long]}"""
KmlData = {}
kmltime = datetime.time
latlist = []
longlist = []
timelist = []
cnt =0
f = open(filename)
line = f.readline()
while line:
if 'when' in line:
timelis... | ReadKmlFile | identifier_name |
test_prototype_module_export.py | # #############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2010 - 2014 Savoir-faire Linux
# (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... |
def test_action_export_update_wizard(self):
"""Test if the wizard is updated during the process."""
exporter = self.main_model.with_context(
active_model=self.prototype_model._name,
active_id=self.prototype.id,
).create({})
exporter.action_export()
s... | """Test if the assertion raises."""
exporter = self.main_model.with_context(active_model="t_active_model").create(
{}
)
self.assertRaises(AssertionError, exporter.action_export) | identifier_body |
test_prototype_module_export.py | # #############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2010 - 2014 Savoir-faire Linux
# (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... | self.assertEqual(exporter.name, "{}.zip".format(self.prototype.name))
def test_zip_files_returns_tuple(self):
"""Test the method return of the method that generate the zip file."""
ret = self.main_model.zip_files(self.exporter, [self.prototype])
self.assertIsInstance(ret, tuple)
... | active_model=self.prototype_model._name,
active_id=self.prototype.id,
).create({})
exporter.action_export()
self.assertEqual(exporter.state, "get") | random_line_split |
test_prototype_module_export.py | # #############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2010 - 2014 Savoir-faire Linux
# (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... | (common.TransactionCase):
def setUp(self):
super(TestPrototypeModuleExport, self).setUp()
self.main_model = self.env["module_prototyper.module.export"]
self.prototype_model = self.env["module_prototyper"]
self.module_category_model = self.env["ir.module.category"]
self.proto... | TestPrototypeModuleExport | identifier_name |
htmltitleelement.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::HTMLTitleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTitleElem... | }
}
content
}
// http://www.whatwg.org/html/#dom-title-text
fn SetText(self, value: DOMString) {
let node: JSRef<Node> = NodeCast::from_ref(self);
node.SetTextContent(Some(value))
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLTitleElement> {
fn super_typ... | Some(text) => content.push_str(text.characterdata().data().as_slice()),
None => (), | random_line_split |
htmltitleelement.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::HTMLTitleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTitleElem... | <'b>(&'b self) -> Option<&'b VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn bind_to_tree(&self, is_in_doc: bool) {
let node: JSRef<Node> = NodeCast::from_ref(*self);
if is_in_doc {
... | super_type | identifier_name |
htmltitleelement.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::HTMLTitleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTitleElem... |
}
}
| {
let document = node.owner_doc().root();
document.r().send_title_to_compositor()
} | conditional_block |
htmltitleelement.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::HTMLTitleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTitleElem... |
}
impl HTMLTitleElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTitleElement {
HTMLTitleElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTitleElement, localName, prefix, document)
}
}
#[allow... | {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTitleElement)))
} | identifier_body |
exposure.js | /*
Copyright: © 2011 Thomas Stein, CodeLounge.de
<mailto:info@codelounge.de> <http://www.codelounge.de/>
Released under the terms of the GNU General Public License.
You should have received a copy of the GNU General Public License,
along with this software. In the main directory, see: licence.txt
If not, see: <http://... |
} );
jQuery('body').bind( 'swiperight', function( e ) {
var next_url = $('.ui-page-active #next_post_link').attr('href');
var previous_url = $('.ui-page-active #previous_post_link').attr('href');
console.log("Swiped Right: " + next_url + ' --- ' + previous_url);
if (undefined != next_url)... |
//$.mobile.changePage( previous_url,"slide", true);
$.mobile.changePage( previous_url, {
transition: "slide",
reverse: false,
changeHash: true
});
e.stopImmediatePropagation();
return false;
}
| conditional_block |
exposure.js | /*
Copyright: © 2011 Thomas Stein, CodeLounge.de
<mailto:info@codelounge.de> <http://www.codelounge.de/>
Released under the terms of the GNU General Public License.
You should have received a copy of the GNU General Public License,
along with this software. In the main directory, see: licence.txt
If not, see: <http://... | $.mobile.changePage( previous_url, {
transition: "slide",
reverse: false,
changeHash: true
});
e.stopImmediatePropagation();
return false;
}
} );
jQuery('body').bind( 'swiperight', function( e ) {
var next_url = $('.ui-page-active #next_post_li... | random_line_split | |
login.js | const Browser = require('zombie')
const mocha = require('mocha')
const describe = mocha.describe
const beforeEach = mocha.beforeEach |
Browser.localhost('localhost', 3000)
describe('User visits login page', () => {
const browser = new Browser()
beforeEach(() => browser.visit('/'))
describe('enters valid credentials', () => {
beforeEach(() => {
browser.fill('username', 'admin')
.fill('password', 'admin')
return browser... | const it = mocha.it | random_line_split |
CCDirectorWebGL.js | GL) {
(function () {
/**
* OpenGL projection protocol
* @class
* @extends cc.Class
*/
cc.DirectorDelegate = cc.Class.extend(/** @lends cc.DirectorDelegate# */{
/**
* Called by CCDirector when the projection is updated, and "custom" projec... | default:
cc.log(cc._LogInfos.Director_setProjection);
break;
}
_t._projection = projection;
cc.eventManager.dispatchEvent(_t._eventProjectionChanged);
cc.setProjectionMatrixDirty();
cc.renderer.childrenOr... | _t._projectionDelegate.updateProjection();
break; | random_line_split |
CCDirectorWebGL.js | ) {
(function () {
/**
* OpenGL projection protocol
* @class
* @extends cc.Class
*/
cc.DirectorDelegate = cc.Class.extend(/** @lends cc.DirectorDelegate# */{
/**
* Called by CCDirector when the projection is updated, and "custom" projecti... |
if ((cc.Director._fpsImageLoaded == null) || (cc.Director._fpsImageLoaded === false))
return;
var texture = new cc.Texture2D();
texture.initWithElement(cc.Director._fpsImage);
texture.handleLoadedTexture();
/*
We want to use an... | {
_t._createStatsLabelForCanvas();
return
} | conditional_block |
index.js | /**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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 a... |
console.log( x );
console.log( y );
scumax( x.length, x, 1, y, -1 );
console.log( y );
| {
x[ i ] = round( randu()*100.0 );
} | conditional_block |
index.js | /**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* 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 a... | 'use strict';
var randu = require( '@stdlib/random/base/randu' );
var round = require( '@stdlib/math/base/special/round' );
var Float32Array = require( '@stdlib/array/float32' );
var scumax = require( './../lib' );
var y;
var x;
var i;
x = new Float32Array( 10 );
y = new Float32Array( x.length );
for ( i = 0; i < x.... | * See the License for the specific language governing permissions and
* limitations under the License.
*/
| random_line_split |
TDEMPlanewave.py | from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import division
import numpy as np
from scipy.constants import mu_0, pi, epsilon_0
import numpy as np
from SimPEG import Utils
def E_field_from_SheetCurruent(XYZ, srcLoc, sig, t, E0=1., ... |
if __name__ == '__main__':
pass
| raise NotImplementedError() | conditional_block |
TDEMPlanewave.py | from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import division
import numpy as np
from scipy.constants import mu_0, pi, epsilon_0
import numpy as np
from SimPEG import Utils
def E_field_from_SheetCurruent(XYZ, srcLoc, sig, t, E0=1., ... | (XYZ, srcLoc, sig, t, E0=1., orientation='X', kappa=0., epsr=1.):
"""
Plane wave propagating downward (negative z (depth))
"""
XYZ = Utils.asArray_N_x_Dim(XYZ, 3)
# Check
if XYZ.shape[0] > 1 & t.shape[0] > 1:
raise Exception("I/O type error: For multiple field locations only a singl... | H_field_from_SheetCurruent | identifier_name |
TDEMPlanewave.py | from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import division
import numpy as np
from scipy.constants import mu_0, pi, epsilon_0
import numpy as np
from SimPEG import Utils
def E_field_from_SheetCurruent(XYZ, srcLoc, sig, t, E0=1., ... | return Ex, Ey, Ez
else:
raise NotImplementedError()
def H_field_from_SheetCurruent(XYZ, srcLoc, sig, t, E0=1., orientation='X', kappa=0., epsr=1.):
"""
Plane wave propagating downward (negative z (depth))
"""
XYZ = Utils.asArray_N_x_Dim(XYZ, 3)
# Check
if XYZ.shape[0] ... | """
Computing Analytic Electric fields from Plane wave in a Wholespace
TODO:
Add description of parameters
"""
XYZ = Utils.asArray_N_x_Dim(XYZ, 3)
# Check
if XYZ.shape[0] > 1 & t.shape[0] > 1:
raise Exception("I/O type error: For multiple field locations only a singl... | identifier_body |
TDEMPlanewave.py | from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import division
import numpy as np
from scipy.constants import mu_0, pi, epsilon_0
import numpy as np
from SimPEG import Utils
def E_field_from_SheetCurruent(XYZ, srcLoc, sig, t, E0=1., ... | XYZ = Utils.asArray_N_x_Dim(XYZ, 3)
# Check
if XYZ.shape[0] > 1 & t.shape[0] > 1:
raise Exception("I/O type error: For multiple field locations only a single frequency can be specified.")
mu = mu_0*(1+kappa)
if orientation == "X":
z = XYZ[:, 2]
Hx = np.zeros_like(z)
... | def H_field_from_SheetCurruent(XYZ, srcLoc, sig, t, E0=1., orientation='X', kappa=0., epsr=1.):
"""
Plane wave propagating downward (negative z (depth))
"""
| random_line_split |
synoptic-to-org.py | import sys
import re
def import_file(lines):
tags_label = "TAGS: "
separator = 60*"-"
idx = 0
while idx < len(lines):
assert lines[idx].startswith(tags_label)
tags = lines[idx][len(tags_label):].split(",")
tags = [t.strip() for t in tags if t.strip()]
idx += 1
... | import pypandoc
body = "\n".join(body)
body = pypandoc.convert(body, "org", format="markdown_phpextra")
if tags:
lineend = body.find("\n")
if lineend == -1:
lineend = len(body)
tags_str = " " + ":%s:" % (":".join(tags))
... | random_line_split | |
synoptic-to-org.py | import sys
import re
def import_file(lines):
tags_label = "TAGS: "
separator = 60*"-"
idx = 0
while idx < len(lines):
assert lines[idx].startswith(tags_label)
tags = lines[idx][len(tags_label):].split(",")
tags = [t.strip() for t in tags if t.strip()]
idx += 1
... |
idx += 1 # skip separator
import pypandoc
body = "\n".join(body)
body = pypandoc.convert(body, "org", format="markdown_phpextra")
if tags:
lineend = body.find("\n")
if lineend == -1:
lineend = len(body)
tags_str = " " + ... | body.append(lines[idx])
idx += 1 | conditional_block |
synoptic-to-org.py | import sys
import re
def import_file(lines):
tags_label = "TAGS: "
separator = 60*"-"
idx = 0
while idx < len(lines):
assert lines[idx].startswith(tags_label)
tags = lines[idx][len(tags_label):].split(",")
tags = [t.strip() for t in tags if t.strip()]
idx += 1
... | ():
with open(sys.argv[1], "r") as inf:
lines = list(inf)
import_file(lines)
if __name__ == "__main__":
main()
| main | identifier_name |
synoptic-to-org.py | import sys
import re
def import_file(lines):
tags_label = "TAGS: "
separator = 60*"-"
idx = 0
while idx < len(lines):
assert lines[idx].startswith(tags_label)
tags = lines[idx][len(tags_label):].split(",")
tags = [t.strip() for t in tags if t.strip()]
idx += 1
... |
if __name__ == "__main__":
main()
| with open(sys.argv[1], "r") as inf:
lines = list(inf)
import_file(lines) | identifier_body |
sum_roof_to_leaf.py | #! /usr/bin/python
'''
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path 1->2 represen... | (self, root):
path = list()
self.inOrderTraversal(root, 0, path)
return sum(path)
if __name__ == '__main__':
solution = Solution()
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.right = TreeNode(4)
root.left.left = TreeNode(5)
print sol... | sumNumbers | identifier_name |
sum_roof_to_leaf.py | #! /usr/bin/python
'''
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path 1->2 represen... |
if __name__ == '__main__':
solution = Solution()
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.right = TreeNode(4)
root.left.left = TreeNode(5)
print solution.sumNumbers(root)
print solution.sumNumbers(None)
| path = list()
self.inOrderTraversal(root, 0, path)
return sum(path) | identifier_body |
sum_roof_to_leaf.py | #! /usr/bin/python
'''
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path 1->2 represen... |
return False
def inOrderTraversal(self, root, currentPath, path):
if not root:
return
# visit()
currentPath = 10 * currentPath + root.val
if self.leafNode(root):
path.append(currentPath)
else:
self.inOrderTraversal(root.left, curr... | return True | conditional_block |
sum_roof_to_leaf.py | #! /usr/bin/python
'''
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path 1->2 represen... | '''
from node_struct import TreeNode
class Solution:
def leafNode(self, root):
if not root.left and not root.right:
return True
return False
def inOrderTraversal(self, root, currentPath, path):
if not root:
return
# visit()
currentPath = 10 * cur... | random_line_split | |
auth-guard.service.spec.ts | import { async, inject, TestBed } from '@angular/core/testing';
import { MockBackend } from '@angular/http/testing';
import { HttpModule, XHRBackend } from '@angular/http';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { ApiService } from './api.service'... |
it('can instantiate service when inject service', inject([AuthGuard], (service: AuthGuard) => {
expect(service instanceof AuthGuard).toBe(true);
}));
describe('Auth Guard Service', () => {
let service: AuthGuard;
beforeEach(inject([ApiService, AuthService, Router], (api: ApiService, auth: AuthServi... | { provide: XHRBackend, useClass: MockBackend }
]
})
.compileComponents();
})); | random_line_split |
lib.rs | //! Backend API for wayland crates
#![warn(missing_docs, missing_debug_implementations)]
#![forbid(improper_ctypes, unsafe_op_in_unsafe_fn)]
pub extern crate smallvec;
/// Helper macro for quickly making a [`Message`](crate::protocol::Message)
#[macro_export]
macro_rules! message {
($sender_id: expr, $opcode: ex... | {
let cstr = unsafe { std::ffi::CStr::from_ptr(msg) };
let text = cstr.to_string_lossy();
log::error!("{}", text);
} | identifier_body | |
lib.rs | //! Backend API for wayland crates | #![forbid(improper_ctypes, unsafe_op_in_unsafe_fn)]
pub extern crate smallvec;
/// Helper macro for quickly making a [`Message`](crate::protocol::Message)
#[macro_export]
macro_rules! message {
($sender_id: expr, $opcode: expr, [$($args: expr),* $(,)?] $(,)?) => {
$crate::protocol::Message {
s... |
#![warn(missing_docs, missing_debug_implementations)] | random_line_split |
lib.rs | //! Backend API for wayland crates
#![warn(missing_docs, missing_debug_implementations)]
#![forbid(improper_ctypes, unsafe_op_in_unsafe_fn)]
pub extern crate smallvec;
/// Helper macro for quickly making a [`Message`](crate::protocol::Message)
#[macro_export]
macro_rules! message {
($sender_id: expr, $opcode: ex... | (msg: *const std::os::raw::c_char) {
let cstr = unsafe { std::ffi::CStr::from_ptr(msg) };
let text = cstr.to_string_lossy();
log::error!("{}", text);
}
#[no_mangle]
extern "C" fn wl_log_rust_logger_server(msg: *const std::os::raw::c_char) {
let cstr = unsafe { std::ffi::CStr::from_ptr(msg) };
let t... | wl_log_rust_logger_client | identifier_name |
test_analysis.py | # Licensed under GPL version 3 - see LICENSE.rst
import numpy as np
import transforms3d
from astropy.table import Table
from astropy.coordinates import SkyCoord
import astropy.units as u
from ..analysis import (find_best_detector_position,
resolvingpower_per_order)
from ..math.utils import e2h
... | ():
'''Compare different methods to measure the resolving power.
This test only ensures consistency, not correctness. However, most of the
underlying statistical functions are implemented in other packages and\
tested there.
This test requires a full pipeline to set up the input photons correctly
... | test_resolvingpower_consistency | identifier_name |
test_analysis.py | # Licensed under GPL version 3 - see LICENSE.rst
import numpy as np
import transforms3d
from astropy.table import Table
from astropy.coordinates import SkyCoord
import astropy.units as u
from ..analysis import (find_best_detector_position,
resolvingpower_per_order)
from ..math.utils import e2h
... | assert np.isclose(res1[1][0], res2[1][0], atol=0.1)
assert np.isclose(res1[1][1], res2[1][1], atol=0.2) # differs stronger here if fit not good
assert np.isclose(res2[1][0], 1.8, rtol=0.1, atol=0.1)
# Resolution of 0th order is essentially 0
assert np.isclose(res1[0][0], 0, atol=0.5)
assert np.... | # FWHM is similar | random_line_split |
test_analysis.py | # Licensed under GPL version 3 - see LICENSE.rst
import numpy as np
import transforms3d
from astropy.table import Table
from astropy.coordinates import SkyCoord
import astropy.units as u
from ..analysis import (find_best_detector_position,
resolvingpower_per_order)
from ..math.utils import e2h
... |
def test_resolvingpower_consistency():
'''Compare different methods to measure the resolving power.
This test only ensures consistency, not correctness. However, most of the
underlying statistical functions are implemented in other packages and\
tested there.
This test requires a full pipeline t... | '''Check that the optimal detector position is found at the convergent point.'''
n = 1000
convergent_point = np.array([3., 5., 7.])
pos = np.random.rand(n, 3) * 100. + 10.
dir = - pos + convergent_point[np.newaxis, :]
photons = Table({'pos': e2h(pos, 1), 'dir': e2h(dir, 0),
'ene... | identifier_body |
dateFieldController.ts | /// <reference path="./dateFieldMetadataModel.ts" />
/// <reference path="../baseFieldController.ts" />
/// <reference path="../../../models/core/entityModel.ts" />
module Components.FieldTypes {
'use strict';
export class DateFieldController extends BaseFieldController<Models.DateFieldMetadata> {
//@... |
public Opened:boolean;
public LocalDate:any;
//Bound methods
public ToggleOpen($event:any):void {
this.StopEventPropagation($event);
this.Opened = !this.Opened;
}
public IsDisabled(date:Date, mode:string):boolean {
var minDate:numbe... | {
super($scope);
this.EntityValueChangedEvent = this.EntityValueChanged.bind(this);
this.EntityValueChanged();
} | identifier_body |
dateFieldController.ts | /// <reference path="./dateFieldMetadataModel.ts" />
/// <reference path="../baseFieldController.ts" />
/// <reference path="../../../models/core/entityModel.ts" />
module Components.FieldTypes {
'use strict';
export class DateFieldController extends BaseFieldController<Models.DateFieldMetadata> {
//@... | ():void {
var utcTime:number = this.GetBoundFieldValue();
var localDate:Date = this.ConvertToLocalDate(utcTime);
var currentLocalDate:Date = this.LocalDate;
if (!this.AreSameDate(currentLocalDate, localDate)) {
this.LocalDate = localDate ? localDate.toISOS... | EntityValueChanged | identifier_name |
dateFieldController.ts | /// <reference path="./dateFieldMetadataModel.ts" />
/// <reference path="../baseFieldController.ts" />
/// <reference path="../../../models/core/entityModel.ts" />
module Components.FieldTypes {
'use strict';
export class DateFieldController extends BaseFieldController<Models.DateFieldMetadata> {
//@... | private EntityValueChanged():void {
var utcTime:number = this.GetBoundFieldValue();
var localDate:Date = this.ConvertToLocalDate(utcTime);
var currentLocalDate:Date = this.LocalDate;
if (!this.AreSameDate(currentLocalDate, localDate)) {
this.LocalD... | }
}
//Helper methods | random_line_split |
theme.ts | import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { StorageService } from '../../provider/storage.service';
import { ThemeService } from '../../provider/theme.service';
import { InformService } from '../../provider/inform.service';
/**
* Generated cl... | name:'少女',
color:'indianred',
},
]
}
changeTheme(color){
var theme='theme-'+color;
console.log('传入的主题是:'+theme);
this.is.createL('设置中...',1000,()=>{
this.navCtrl.pop();
});
this.global.set('theme', theme);
this.sto.save('theme',theme);
}
}
| {
console.log('ionViewDidLoad ThemePage');
this.list=[
{
name:'新桥',
color:'blue',
},{
name:'葡萄',
color:'purple',
}, {
name:'原谅',
color:'darkgray',
}, {
name:'纯白',
color:'white',
textColor:'#488aff',
}, {
... | identifier_body |
theme.ts | import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { StorageService } from '../../provider/storage.service';
import { ThemeService } from '../../provider/theme.service';
import { InformService } from '../../provider/inform.service';
/**
* Generated cl... | ='theme-'+color;
console.log('传入的主题是:'+theme);
this.is.createL('设置中...',1000,()=>{
this.navCtrl.pop();
});
this.global.set('theme', theme);
this.sto.save('theme',theme);
}
}
| var theme | identifier_name |
theme.ts | import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { StorageService } from '../../provider/storage.service';
import { ThemeService } from '../../provider/theme.service';
import { InformService } from '../../provider/inform.service'; | *
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-theme',
templateUrl: 'theme.html',
})
export class ThemePage {
constructor(public navCtrl: NavController,
public navParams: NavParams,
public st... | /**
* Generated class for the ThemePage page. | random_line_split |
settings.py | # Django settings for django_http_api project.
import os
import dj_database_url
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
| # ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': dj_database_url.config(
default='postgres://jojjen:Mehran460@localhost:5432/vms'
)
}
# COMMENTED OUT FOR DEVELOPMENT
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.',
# Add 'postgre... | ADMINS = ( | random_line_split |
tasks.js | import {Button} from 'widget/button'
import {ButtonGroup} from 'widget/buttonGroup'
import {Content, SectionLayout, TopBar} from 'widget/sectionLayout'
import {HoverDetector, HoverOverlay} from 'widget/hover'
import {Progress} from 'widget/progress'
import {Scrollable, ScrollableContainer} from 'widget/scrollable'
impo... | }
inactiveTasks() {
const {tasks} = this.state
return tasks.filter(({status}) => !['PENDING', 'ACTIVE'].includes(status))
}
stopTask(task) {
const {stream} = this.props
this.updateTaskInState(task, () => ({
...task,
status: 'CANCELED',
... | activeTasks() {
const {tasks} = this.state
return tasks.filter(({status}) => ['PENDING', 'ACTIVE'].includes(status)) | random_line_split |
tasks.js | import {Button} from 'widget/button'
import {ButtonGroup} from 'widget/buttonGroup'
import {Content, SectionLayout, TopBar} from 'widget/sectionLayout'
import {HoverDetector, HoverOverlay} from 'widget/hover'
import {Progress} from 'widget/progress'
import {Scrollable, ScrollableContainer} from 'widget/scrollable'
impo... |
updateTaskInState(task, onUpdate) {
const {tasks} = this.state
this.setState({
tasks: tasks.map(t =>
t.id === task.id ? onUpdate() : t
)
})
}
}
export default compose(
Tasks,
connect(mapStateToProps)
)
| {
const {stream} = this.props
this.updateTaskInState(task, () => ({
...task,
status: 'CANCELED',
statusDescription: 'Stopping...'
}))
stream('STOP_TASK',
api.tasks.cancel$(task.id)
)
} | identifier_body |
tasks.js | import {Button} from 'widget/button'
import {ButtonGroup} from 'widget/buttonGroup'
import {Content, SectionLayout, TopBar} from 'widget/sectionLayout'
import {HoverDetector, HoverOverlay} from 'widget/hover'
import {Progress} from 'widget/progress'
import {Scrollable, ScrollableContainer} from 'widget/scrollable'
impo... | else if (description.defaultMessage) {
return description.defaultMessage
} else {
return msg('tasks.status.executing')
}
}
componentDidUpdate(prevProps) {
const {stream} = this.props
const notActive = !['REMOVE_TASK', 'REMOVE_ALL_TASKS', 'STOP_TASK']
... | {
return msg(description.messageKey, description.messageArgs, description.defaultMessage)
} | conditional_block |
tasks.js | import {Button} from 'widget/button'
import {ButtonGroup} from 'widget/buttonGroup'
import {Content, SectionLayout, TopBar} from 'widget/sectionLayout'
import {HoverDetector, HoverOverlay} from 'widget/hover'
import {Progress} from 'widget/progress'
import {Scrollable, ScrollableContainer} from 'widget/scrollable'
impo... | extends React.Component {
constructor(props) {
super(props)
this.state = {tasks: props.tasks || []}
}
renderOverlay(task) {
return (
<div className={styles.overlay}>
{['FAILED', 'COMPLETED', 'CANCELED'].includes(task.status) ? (
<Butt... | Tasks | identifier_name |
dir.rs | use std::io;
use std::fs;
use std::path::{Path, PathBuf};
use std::slice::Iter as SliceIter;
use feature::Git;
use file::{File, fields};
/// A **Dir** provides a cached list of the file paths in a directory that's
/// being listed.
///
/// This object gets passed to the Files themselves, in order for them to
/// che... |
} | {
self.inner.next().map(|path| File::from_path(path, Some(self.dir)).map_err(|t| (path.clone(), t)))
} | identifier_body |
dir.rs | use std::io;
use std::fs;
use std::path::{Path, PathBuf};
use std::slice::Iter as SliceIter;
use feature::Git;
use file::{File, fields};
/// A **Dir** provides a cached list of the file paths in a directory that's
/// being listed. | /// accordingly. (See `File#get_source_files`)
pub struct Dir {
/// A vector of the files that have been read from this directory.
contents: Vec<PathBuf>,
/// The path that was read.
pub path: PathBuf,
/// Holds a `Git` object if scanning for Git repositories is switched on,
/// and this dire... | ///
/// This object gets passed to the Files themselves, in order for them to
/// check the existence of surrounding files, then highlight themselves | random_line_split |
dir.rs | use std::io;
use std::fs;
use std::path::{Path, PathBuf};
use std::slice::Iter as SliceIter;
use feature::Git;
use file::{File, fields};
/// A **Dir** provides a cached list of the file paths in a directory that's
/// being listed.
///
/// This object gets passed to the Files themselves, in order for them to
/// che... | ,
})
}
/// Produce an iterator of IO results of trying to read all the files in
/// this directory.
pub fn files<'dir>(&'dir self) -> Files<'dir> {
Files {
inner: self.contents.iter(),
dir: &self,
}
}
/// Whether this directory contains a file wi... | { None } | conditional_block |
dir.rs | use std::io;
use std::fs;
use std::path::{Path, PathBuf};
use std::slice::Iter as SliceIter;
use feature::Git;
use file::{File, fields};
/// A **Dir** provides a cached list of the file paths in a directory that's
/// being listed.
///
/// This object gets passed to the Files themselves, in order for them to
/// che... | <'dir>(&'dir self) -> Files<'dir> {
Files {
inner: self.contents.iter(),
dir: &self,
}
}
/// Whether this directory contains a file with the given path.
pub fn contains(&self, path: &Path) -> bool {
self.contents.iter().any(|ref p| p.as_path() == path)
}
... | files | identifier_name |
configure.js | import 'babel-polyfill';
import EdgeGrid from 'edgegrid';
import dotenv from 'dotenv';
import inquirer from 'inquirer';
import formatJson from 'format-json';
import fs from 'fs';
(async function() {
// load .env vars
dotenv.config();
let papiResponses = new Map();
const edgegrid = new EdgeGrid({
... | return answers[valueField];
});
}
async function callPapi(type, papiUrl) {
return new Promise(
(resolve, reject) => {
console.log('calling papi url: ' + papiUrl + '\n');
edgegrid.auth({
path: papiUrl,
... | {
let choices = await callPapi(containerField, papiUrl).then((data) => {
return data[containerField].items.map((item) => {
let choice = {};
choice.name = item[valueField] + ' ' + item[nameField];
choice.value = item[valueField];
return ... | identifier_body |
configure.js | import 'babel-polyfill';
import EdgeGrid from 'edgegrid';
import dotenv from 'dotenv';
import inquirer from 'inquirer';
import formatJson from 'format-json';
import fs from 'fs';
(async function() {
// load .env vars
dotenv.config();
let papiResponses = new Map();
const edgegrid = new EdgeGrid({
... | );
async function papiChoice(message, papiUrl, containerField, valueField, nameField) {
let choices = await callPapi(containerField, papiUrl).then((data) => {
return data[containerField].items.map((item) => {
let choice = {};
choice.name = item[valueField] + ... | 'AKA_GROUP_ID=' + groupId + '\n' +
'AKA_PROPERTY_ID=' + propertyId + '\n' +
'AKA_PROPERTY_VERSION=' + version + '\n' | random_line_split |
configure.js | import 'babel-polyfill';
import EdgeGrid from 'edgegrid';
import dotenv from 'dotenv';
import inquirer from 'inquirer';
import formatJson from 'format-json';
import fs from 'fs';
(async function() {
// load .env vars
dotenv.config();
let papiResponses = new Map();
const edgegrid = new EdgeGrid({
... |
let jsonResult = JSON.parse(body);
papiResponses.set(type, jsonResult);
return resolve(jsonResult);
});
});
}
})(); | {
return reject(error);
} | conditional_block |
configure.js | import 'babel-polyfill';
import EdgeGrid from 'edgegrid';
import dotenv from 'dotenv';
import inquirer from 'inquirer';
import formatJson from 'format-json';
import fs from 'fs';
(async function() {
// load .env vars
dotenv.config();
let papiResponses = new Map();
const edgegrid = new EdgeGrid({
... | (type, papiUrl) {
return new Promise(
(resolve, reject) => {
console.log('calling papi url: ' + papiUrl + '\n');
edgegrid.auth({
path: papiUrl,
method: 'GET'
}).send((error, response, body) => {
... | callPapi | identifier_name |
bigbob9_c.py | #/* bigbob9.py - demo ranger interface
# * K. Nickels 7/24/13
# */
# Check with "locate playerc.py"
import sys,os
sys.path.append('/usr/local/lib/python2.7/site-packages/')
sys.path.append('/usr/local/lib64/python2.7/site-packages/')
import math
from playerc import *
# /* Create a client and connect it to the serve... | print "%.3f, " % laserProxy.ranges[i],
print "."
# Clean up
sonarProxy.unsubscribe()
toothProxy.unsubscribe()
laserProxy.unsubscribe()
robot.disconnect() | print "%d laser ranges: "% laserProxy.ranges_count
for i in range(laserProxy.ranges_count): | random_line_split |
bigbob9_c.py | #/* bigbob9.py - demo ranger interface
# * K. Nickels 7/24/13
# */
# Check with "locate playerc.py"
import sys,os
sys.path.append('/usr/local/lib/python2.7/site-packages/')
sys.path.append('/usr/local/lib64/python2.7/site-packages/')
import math
from playerc import *
# /* Create a client and connect it to the serve... |
print "."
print "%d laser ranges: "% laserProxy.ranges_count
for i in range(laserProxy.ranges_count):
print "%.3f, " % laserProxy.ranges[i],
print "."
# Clean up
sonarProxy.unsubscribe()
toothProxy.unsubscribe()
laserProxy.unsubscribe()
robot.disconnect()
| print "%.3f, " % laserProxy.ranges[i], | conditional_block |
orchid.py | # -*- coding: utf-8 -*-
"""
Data preprocessing for ORCHID corpus
"""
from typing import List, Tuple
# defined strings for special characters,
# from Table 4 in ORCHID paper
CHAR_TO_ESCAPE = {
" ": "<space>",
"+": "<plus>",
"-": "<minus>",
"=": "<equal>",
",": "<comma>",
"$": "<dollar>",
"."... |
def pre_process(words: List[str]) -> List[str]:
"""
Convert signs and symbols with their defined strings.
This function is to be used as a preprocessing step,
before the actual POS tagging.
"""
keys = CHAR_TO_ESCAPE.keys()
words = [CHAR_TO_ESCAPE[word] if word in keys else word for word i... | return tag | conditional_block |
orchid.py | # -*- coding: utf-8 -*-
"""
Data preprocessing for ORCHID corpus
"""
from typing import List, Tuple
# defined strings for special characters,
# from Table 4 in ORCHID paper
CHAR_TO_ESCAPE = {
" ": "<space>",
"+": "<plus>",
"-": "<minus>",
"=": "<equal>",
",": "<comma>",
"$": "<dollar>",
"."... | ess(
word_tags: List[Tuple[str, str]], to_ud: bool = False
) -> List[Tuple[str, str]]:
"""
Convert defined strings back to corresponding signs and symbols.
This function is to be used as a post-processing step,
after the actual POS tagging.
"""
keys = ESCAPE_TO_CHAR.keys()
if not to_ud:... | signs and symbols with their defined strings.
This function is to be used as a preprocessing step,
before the actual POS tagging.
"""
keys = CHAR_TO_ESCAPE.keys()
words = [CHAR_TO_ESCAPE[word] if word in keys else word for word in words]
return words
def post_proc | identifier_body |
orchid.py | # -*- coding: utf-8 -*-
"""
Data preprocessing for ORCHID corpus
"""
from typing import List, Tuple
# defined strings for special characters,
# from Table 4 in ORCHID paper
CHAR_TO_ESCAPE = {
" ": "<space>",
"+": "<plus>",
"-": "<minus>",
"=": "<equal>",
",": "<comma>",
"$": "<dollar>",
"."... | List[Tuple[str, str]], to_ud: bool = False
) -> List[Tuple[str, str]]:
"""
Convert defined strings back to corresponding signs and symbols.
This function is to be used as a post-processing step,
after the actual POS tagging.
"""
keys = ESCAPE_TO_CHAR.keys()
if not to_ud:
word_tags ... | word_tags: | identifier_name |
orchid.py | # -*- coding: utf-8 -*-
"""
Data preprocessing for ORCHID corpus
"""
from typing import List, Tuple
# defined strings for special characters,
# from Table 4 in ORCHID paper
CHAR_TO_ESCAPE = {
" ": "<space>",
"+": "<plus>",
"-": "<minus>",
"=": "<equal>",
",": "<comma>",
"$": "<dollar>",
"."... | keys = CHAR_TO_ESCAPE.keys()
words = [CHAR_TO_ESCAPE[word] if word in keys else word for word in words]
return words
def post_process(
word_tags: List[Tuple[str, str]], to_ud: bool = False
) -> List[Tuple[str, str]]:
"""
Convert defined strings back to corresponding signs and symbols.
This... | """
Convert signs and symbols with their defined strings.
This function is to be used as a preprocessing step,
before the actual POS tagging.
""" | random_line_split |
highlightable.ts | /* playground-fold */
import {LitElement, css, html} from 'lit';
import {classMap} from 'lit/directives/class-map.js';
import {property} from 'lit/decorators/property.js';
type Constructor<T> = new (...args: any[]) => T;
export declare class HighlightableInterface {
highlight: boolean;
renderHighlight(content: un... | ${content}
</div>`;
}
}
return HighlightableElement as Constructor<HighlightableInterface> & T;
}; | random_line_split | |
highlightable.ts | /* playground-fold */
import {LitElement, css, html} from 'lit';
import {classMap} from 'lit/directives/class-map.js';
import {property} from 'lit/decorators/property.js';
type Constructor<T> = new (...args: any[]) => T;
export declare class HighlightableInterface {
highlight: boolean;
renderHighlight(content: un... | extends superClass {
// Adds some styles...
static styles = css`.highlight { background: yellow; }`
// ...a public `highlight` property/attribute...
@property({type: Boolean}) highlight = false;
// ...and a helper render method:
renderHighlight(content: unknown) {
return h... | HighlightableElement | identifier_name |
highlightable.ts | /* playground-fold */
import {LitElement, css, html} from 'lit';
import {classMap} from 'lit/directives/class-map.js';
import {property} from 'lit/decorators/property.js';
type Constructor<T> = new (...args: any[]) => T;
export declare class HighlightableInterface {
highlight: boolean;
renderHighlight(content: un... |
}
return HighlightableElement as Constructor<HighlightableInterface> & T;
};
| {
return html`
<div class=${classMap({highlight: this.highlight})}>
${content}
</div>`;
} | identifier_body |
test_numpyfilereader.py | # Copyright (c) 2015, 2014 Computational Molecular Biology Group, Free University
# Berlin, 14195 Berlin, Germany.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source ... |
chunks = np.vstack(chunks)
np.testing.assert_equal(chunks, self.d[lag::stride])
def test_lagged_stridden_access_multiple_files(self):
reader = NumPyFileReader(self.files2d)
print reader.trajectory_lengths()
strides = [2, 3, 5, 7, 15]
lags = [1, 3, 7,... | chunks.append(Y) | conditional_block |
test_numpyfilereader.py | # Copyright (c) 2015, 2014 Computational Molecular Biology Group, Free University
# Berlin, 14195 Berlin, Germany.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source ... |
def test_only_npy(self):
reader = NumPyFileReader(self.npy_files)
from_files = [np.load(f) for f in self.npy_files]
concatenated = np.vstack(from_files)
output = reader.get_output()
self.assertEqual(reader.number_of_trajectories(), len(self.npy_files))
self.asser... | shutil.rmtree(cls.dir, ignore_errors=True) | identifier_body |
test_numpyfilereader.py | # Copyright (c) 2015, 2014 Computational Molecular Biology Group, Free University
# Berlin, 14195 Berlin, Germany.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source ... | (self):
reader = NumPyFileReader(self.npy_files)
reader.chunksize = 30
from_files = [np.load(f) for f in self.npy_files]
concatenated = np.vstack(from_files)
output = reader.get_output()
self.assertEqual(reader.number_of_trajectories(), len(self.npy_files))
sel... | test_small_chunks | identifier_name |
test_numpyfilereader.py | # Copyright (c) 2015, 2014 Computational Molecular Biology Group, Free University
# Berlin, 14195 Berlin, Germany.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source ... | unittest.main() | random_line_split | |
test_loadbalancer.py | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | (self):
managed_outbound_ip_count = 5
outbound_ips = None
outbound_ip_prefixes = None
outbound_ports = 80
idle_timeout = 3600
# load models directly (instead of through the `get_sdk` method provided by the cli component)
from azure.cli.core.profiles._shared impor... | test_configure_load_balancer_profile | identifier_name |
test_loadbalancer.py | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved. |
from azure.cli.core.profiles import ResourceType
from azure.cli.command_modules.acs import _loadbalancer as loadbalancer
class TestLoadBalancer(unittest.TestCase):
def test_configure_load_balancer_profile(self):
managed_outbound_ip_count = 5
outbound_ips = None
outbound_ip_prefixes = Non... | # Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
import importlib
import unittest
from unittest import mock | random_line_split |
test_loadbalancer.py | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | unittest.main() | conditional_block | |
test_loadbalancer.py | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | ManagedClusterLoadBalancerProfileManagedOutboundIPs = getattr(
module, "ManagedClusterLoadBalancerProfileManagedOutboundIPs"
)
ManagedClusterLoadBalancerProfileOutboundIPs = getattr(
module, "ManagedClusterLoadBalancerProfileOutboundIPs"
)
ManagedClusterLo... | managed_outbound_ip_count = 5
outbound_ips = None
outbound_ip_prefixes = None
outbound_ports = 80
idle_timeout = 3600
# load models directly (instead of through the `get_sdk` method provided by the cli component)
from azure.cli.core.profiles._shared import AZURE_API_PROF... | identifier_body |
normalize.js | import { toTitleCase } from 'utils';
export default values => {
let newValues = { ...values };
// Add a sourceType if no source (i.e. not scraped) and no sourceType
if (!newValues['source'] && !newValues['sourceType']) {
newValues['sourceType'] = 'user';
}
switch (newValues['sourceType']) {
case 'u... | };
}
return {
public: true,
...newValues,
title: toTitleCase(values['title']),
};
}; | ...ingredient,
text: ingredient.text.trim(),
})), | random_line_split |
ReqProxyHandler.py | ########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: Krzysztof.Ciba@NOSPAMgmail.com
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:syn... | ( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request mana... | cacheDir | identifier_name |
ReqProxyHandler.py | ########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: Krzysztof.Ciba@NOSPAMgmail.com
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:syn... | """ save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( ... | gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ): | random_line_split |
ReqProxyHandler.py | ########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: Krzysztof.Ciba@NOSPAMgmail.com
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:syn... | requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogg... | """ move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cach... | identifier_body |
ReqProxyHandler.py | ########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: Krzysztof.Ciba@NOSPAMgmail.com
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:syn... |
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( se... | try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
... | conditional_block |
liveness-unused.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 f5a() {
for x in 1..10 { }
//~^ ERROR unused variable: `x`
}
fn f5b() {
for (x, _) in [1, 2, 3].iter().enumerate() { }
//~^ ERROR unused variable: `x`
}
fn f5c() {
for (_, x) in [1, 2, 3].iter().enumerate() {
//~^ ERROR unused variable: `x`
continue;
drop(*x as i32... | {
i
} | conditional_block |
liveness-unused.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 f3() {
let mut x = 3;
//~^ ERROR variable `x` is assigned to, but never used
x += 4;
//~^ ERROR value assigned to `x` is never read
}
fn f3b() {
let mut z = 3;
//~^ ERROR variable `z` is assigned to, but never used
loop {
z += 4;
}
}
#[allow(unused_variables)]
fn f3c() {
... | {
let x = 3;
//~^ ERROR unused variable: `x`
} | identifier_body |
liveness-unused.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 main() {
} | //~^ ERROR unused variable: `x`
continue;
drop(*x as i32); //~ WARNING unreachable statement | random_line_split |
liveness-unused.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(isize), b(isize), c(isize)
}
fn f4b() -> isize {
match tri::a(3) {
tri::a(i) | tri::b(i) | tri::c(i) => {
i
}
}
}
fn f5a() {
for x in 1..10 { }
//~^ ERROR unused variable: `x`
}
fn f5b() {
for (x, _) in [1, 2, 3].iter().enumerate() { }
//~^ ERROR unused variable: ... | tri | identifier_name |
TabNote.ts | import { Note } from "./Note";
import { Fraction } from "../../Common/DataObjects/Fraction";
import { VoiceEntry } from "./VoiceEntry";
import { SourceStaffEntry } from "./SourceStaffEntry";
import { Pitch } from "../../Common/DataObjects/Pitch";
import { SourceMeasure } from "./SourceMeasure";
export class TabNote ex... | (): number {
return this.fretNumber;
}
public get BendArray(): { bendalter: number, direction: string }[] {
return this.bendArray;
}
public get VibratoStroke(): boolean {
return this.vibratoStroke;
}
}
| FretNumber | identifier_name |
TabNote.ts | import { Note } from "./Note";
import { Fraction } from "../../Common/DataObjects/Fraction";
import { VoiceEntry } from "./VoiceEntry";
import { SourceStaffEntry } from "./SourceStaffEntry";
import { Pitch } from "../../Common/DataObjects/Pitch";
import { SourceMeasure } from "./SourceMeasure";
export class TabNote ex... | this.vibratoStroke = vibratoStroke;
}
private stringNumberTab: number; // there can also be string numbers for e.g. violin in treble clef.
private fretNumber: number;
private bendArray: { bendalter: number, direction: string }[];
private vibratoStroke: boolean;
/** Returns the string n... | this.stringNumberTab = stringNumber;
this.fretNumber = fretNumber;
this.bendArray = bendArray; | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.