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 |
|---|---|---|---|---|
pane2.js | ((bbn) => {
let script = document.createElement('script');
script.innerHTML = `<div :class="[componentClass, 'bbn-background', 'bbn-border-box']"
:style="currentStyle"
>
<div :class="['bbn-overlay', $parent.currentOrientation === 'vertical' ? 'bbn-flex-height' : 'bbn-flex-width']">
<div v-if="title"
... | resizable: {
type: Boolean,
default: undefined
},
collapsible: {
type: Boolean,
default: undefined
},
collapsed: {
type: Boolean,
default: false
},
scrollable: {
type: Boolean,
default: false
},
min: {
... | },
size: {
type: [String, Number],
default: ''
}, | random_line_split |
pane2.js | ((bbn) => {
let script = document.createElement('script');
script.innerHTML = `<div :class="[componentClass, 'bbn-background', 'bbn-border-box']"
:style="currentStyle"
>
<div :class="['bbn-overlay', $parent.currentOrientation === 'vertical' ? 'bbn-flex-height' : 'bbn-flex-width']">
<div v-if="title"
... | this.splitter.setSize(size, this);
}
},
hide(){
this.isCollapsed = true;
},
show(){
this.isCollapsed = false;
},
toggleCollapsed(){
this.isCollapsed = !this.isCollapsed;
},
setStyle(){
let s = {};
if ( this.min ){
... | size = this.max;
}
| conditional_block |
pane2.js | ((bbn) => {
let script = document.createElement('script');
script.innerHTML = `<div :class="[componentClass, 'bbn-background', 'bbn-border-box']"
:style="currentStyle"
>
<div :class="['bbn-overlay', $parent.currentOrientation === 'vertical' ? 'bbn-flex-height' : 'bbn-flex-width']">
<div v-if="title"
... | computed: {
splitter(){
return this.$parent.$vnode.componentOptions.tag === 'bbn-splitter2' ? this.$parent : false;
}
},
methods: {
getRealSize(){
let rect = this.$el.getBoundingClientRect();
return this.splitter ?
(this.splitter.isVertical ? rect.height : r... | return {
checker: false,
isCollapsed: this.collapsed,
isResizable: this.resizable,
realSize: 0,
lastRealSize: 0,
originalSize: this.size || 'auto',
currentStyle: {}
};
},
| identifier_body |
test.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2019 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 ap... | isAnagram( ( x: number ): number => x, 'a' ); // $ExpectError
}
// The compiler throws an error if the function is provided an unsupported number of arguments...
{
isAnagram(); // $ExpectError
isAnagram( 'bat' ); // $ExpectError
} | isAnagram( false, 'a' ); // $ExpectError
isAnagram( null, 'a' ); // $ExpectError
isAnagram( {}, 'a' ); // $ExpectError
isAnagram( [], 'a' ); // $ExpectError | random_line_split |
four_bit_adder.rs | // http://rosettacode.org/wiki/Four_bit_adder
use std::ops::Deref;
use std::fmt;
// primitive gates
fn not(a: bool) -> bool {
!a
}
fn or(a: bool, b: bool) -> bool {
a || b
}
fn and(a: bool, b: bool) -> bool {
a && b
}
/// xor gate [2x not, 2x and, 1x or]
/// (A & !B) | (B & !A)
fn xor(a: bool, b: bool) ->... |
#[test]
fn test_not() {
assert_eq!(true, not(false));
assert_eq!(false, not(true));
}
#[test]
fn test_or() {
assert_eq!(false, or(false, false));
assert_eq!(true, or(true, false));
assert_eq!(true, or(false, true));
assert_eq!(true, or(true, true));
}
#[test]
fn test_and() {
assert_eq!(fa... | nib_b,
result,
carry)
} | random_line_split |
four_bit_adder.rs | // http://rosettacode.org/wiki/Four_bit_adder
use std::ops::Deref;
use std::fmt;
// primitive gates
fn not(a: bool) -> bool {
!a
}
fn or(a: bool, b: bool) -> bool {
a || b
}
fn and(a: bool, b: bool) -> bool {
a && b
}
/// xor gate [2x not, 2x and, 1x or]
/// (A & !B) | (B & !A)
fn xor(a: bool, b: bool) ->... | ([bool; 4]);
impl Nibble {
fn new(arr: [u8; 4]) -> Nibble {
Nibble([arr[0] != 0, arr[1] != 0, arr[2] != 0, arr[3] != 0])
}
fn from_u8(n: u8) -> Nibble {
Nibble::new([n & 8, n & 4, n & 2, n & 1])
}
fn to_u8(&self, carry: bool) -> u8 {
match u8::from_str_radix(&(format!("{}",... | Nibble | identifier_name |
four_bit_adder.rs | // http://rosettacode.org/wiki/Four_bit_adder
use std::ops::Deref;
use std::fmt;
// primitive gates
fn not(a: bool) -> bool {
!a
}
fn or(a: bool, b: bool) -> bool {
a || b
}
fn and(a: bool, b: bool) -> bool {
a && b
}
/// xor gate [2x not, 2x and, 1x or]
/// (A & !B) | (B & !A)
fn xor(a: bool, b: bool) ->... |
#[test]
fn test_four_bit_adder() {
for (a, b) in (0..std::u8::MAX).map(|n| (n >> 4, n & 15)) {
let nib_a = Nibble::from_u8(a);
let nib_b = Nibble::from_u8(b);
let (result, carry) = four_bit_adder(nib_a, nib_b, false);
assert_eq!(a + b, result.to_u8(carry));
let (result, ca... | {
assert_eq!((false, false), full_adder(false, false, false));
assert_eq!((true, false), full_adder(false, false, true));
assert_eq!((true, false), full_adder(false, true, false));
assert_eq!((true, false), full_adder(true, false, false));
assert_eq!((false, true), full_adder(false, true, true));
... | identifier_body |
DialogAdd.py | # dialog_add.py.in - dialog to add a new repository
#
# Copyright (c) 2004-2005 Canonical
# 2005 Michiel Sikkes
#
# Authors:
# Michael Vogt <mvo@debian.org>
# Michiel Sikkes <michiels@gnome.org>
# Sebastian Heinlein <glatzor@ubuntu.com>
#
# This program is free softw... |
return line
def check_line(self, *args):
"""
Check for a valid apt line and set the sensitiveness of the
button 'add' accordingly
"""
line = self.entry.get_text() + "\n"
if line.startswith("ppa:"):
self.button_add.set_sensitive(True)
return
source_entry = SourceEntry(line... | line = None | conditional_block |
DialogAdd.py | # dialog_add.py.in - dialog to add a new repository
#
# Copyright (c) 2004-2005 Canonical
# 2005 Michiel Sikkes
#
# Authors:
# Michael Vogt <mvo@debian.org>
# Michiel Sikkes <michiels@gnome.org>
# Sebastian Heinlein <glatzor@ubuntu.com>
#
# This program is free softw... | """
Check for a valid apt line and set the sensitiveness of the
button 'add' accordingly
"""
line = self.entry.get_text() + "\n"
if line.startswith("ppa:"):
self.button_add.set_sensitive(True)
return
source_entry = SourceEntry(line)
if source_entry.invalid == True or source_entry... | identifier_body | |
DialogAdd.py | # dialog_add.py.in - dialog to add a new repository
#
# Copyright (c) 2004-2005 Canonical
# 2005 Michiel Sikkes
#
# Authors:
# Michael Vogt <mvo@debian.org>
# Michiel Sikkes <michiels@gnome.org>
# Sebastian Heinlein <glatzor@ubuntu.com>
#
# This program is free softw... | :
def __init__(self, parent, sourceslist, datadir, distro):
"""
Initialize the dialog that allows to add a new source entering the
raw apt line
"""
self.sourceslist = sourceslist
self.parent = parent
self.datadir = datadir
# gtk stuff
setup_ui(self, os.path.join(datadir, "gtkbuilde... | DialogAdd | identifier_name |
DialogAdd.py | # dialog_add.py.in - dialog to add a new repository
#
# Copyright (c) 2004-2005 Canonical
# 2005 Michiel Sikkes
#
# Authors:
# Michael Vogt <mvo@debian.org>
# Michiel Sikkes <michiels@gnome.org>
# Sebastian Heinlein <glatzor@ubuntu.com>
#
# This program is free softw... | # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
import os
from gi.repository import Gtk
from gettext import gettext as _
from aptsources.sourceslist import ... | # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# | random_line_split |
cadmio.py | from statistics import *
from scipy.constants import *
import getpass
users={"candi": "C:\\Users\\candi\\Documents\\GitHub\\Lab3.2\\",
"silvanamorreale":"C:\\Users\\silvanamorreale\\Documents\\GitHub\\Lab3.2\\" ,
"Studenti": "C:\\Users\\Studenti\\Desktop\\Lab3\\",
"User":"C:\\Users\\User\\Documents\\GitHub\\Lab3.2\\"
... | from lab import *
from pylab import *
from uncertainties import *
from uncertainties import unumpy | random_line_split | |
cadmio.py | from lab import *
from pylab import *
from uncertainties import *
from uncertainties import unumpy
from statistics import *
from scipy.constants import *
import getpass
users={"candi": "C:\\Users\\candi\\Documents\\GitHub\\Lab3.2\\",
"silvanamorreale":"C:\\Users\\silvanamorreale\\Documents\\GitHub\\Lab3.2\\" ,
"Studen... | rint(colorname[i],": ",c/(color[i]*a + b)*(h/physical_constants['electron volt'][0]))
| conditional_block | |
parse5_adapter.ts | else {
el[name] = value;
}
}
// TODO(tbosch): don't even call this method when we run the tests on server side
// by not using the DomRenderer in tests. Keeping this for now to make tests happy...
getProperty(el: /*element*/ any, name: string): any { return el[name]; }
logError(error) { console.er... | {
this.setInnerHTML(el, value);
} | conditional_block | |
parse5_adapter.ts | i < content.childNodes.length; i++) {
treeAdapter.appendChild(el, content.childNodes[i]);
}
}
getText(el): string {
if (this.isTextNode(el)) {
return el.data;
} else if (isBlank(el.childNodes) || el.childNodes.length == 0) {
return "";
} else {
var textContent = "";
fo... | isPageRule | identifier_name | |
parse5_adapter.ts | .contains(this.classList(element), classname);
}
_readStyleAttribute(element) {
var styleMap = {};
var attributes = element.attribs;
if (attributes && attributes.hasOwnProperty("style")) {
var styleAttrValue = attributes["style"];
var styleList = styleAttrValue.split(/;+/g);
for (var i... | "checked",
"defaultChecked",
"autofocus",
"autocomplete",
"alt", | random_line_split | |
parse5_adapter.ts | ListenersMap)) {
var listeners: any = StringMapWrapper.get(el._eventListenersMap, evt.type);
if (isPresent(listeners)) {
for (var i = 0; i < listeners.length; i++) {
listeners[i](evt);
}
}
}
if (isPresent(el.parent)) {
this.dispatchEvent(el.parent, evt);
}
... | }
});
var cNodes = node.children;
if (cNodes) {
var cNodesClone = new Array(cNodes.length);
for (var i = 0; i < cNodes.length; i++) {
var childNode = cNodes[i];
var childNodeClone = _recursive(childNode);
cNodesClone[i] = childNodeClone;
... | {
var _recursive = (node) => {
var nodeClone = Object.create(Object.getPrototypeOf(node));
for (var prop in node) {
var desc = Object.getOwnPropertyDescriptor(node, prop);
if (desc && 'value' in desc && typeof desc.value !== 'object') {
nodeClone[prop] = node[prop];
}
... | identifier_body |
logger.rs | extern crate env_logger;
extern crate log_panics;
extern crate log;
#[cfg(target_os = "android")]
extern crate android_logger;
extern crate libc;
use self::env_logger::Builder as EnvLoggerBuilder;
use self::log::{LevelFilter, Level};
use std::env;
use std::io::Write;
#[cfg(target_os = "android")]
use self::android_log... |
#[macro_export]
macro_rules! try_log {
($expr:expr) => (match $expr {
Ok(val) => val,
Err(err) => {
error!("try_log! | {}", err);
return Err(From::from(err))
}
})
}
macro_rules! _map_err {
($lvl:expr, $expr:expr) => (
|err| {
log!($lvl, ... | {
match level {
1 => Level::Error,
2 => Level::Warn,
3 => Level::Info,
4 => Level::Debug,
5 => Level::Trace,
_ => unreachable!(),
}
} | identifier_body |
logger.rs | extern crate env_logger;
extern crate log_panics;
extern crate log;
#[cfg(target_os = "android")]
extern crate android_logger;
extern crate libc;
use self::env_logger::Builder as EnvLoggerBuilder;
use self::log::{LevelFilter, Level};
use std::env;
use std::io::Write;
#[cfg(target_os = "android")]
use self::android_log... | static mut LOG_CB: Option<LogCB> = None;
static mut FLUSH_CB: Option<FlushCB> = None;
pub struct LibindyLogger {
context: *const c_void,
enabled: Option<EnabledCB>,
log: LogCB,
flush: Option<FlushCB>,
}
impl LibindyLogger {
fn new(context: *const c_void, enabled: Option<EnabledCB>, log: LogCB, flu... | static mut CONTEXT: *const c_void = ptr::null();
static mut ENABLED_CB: Option<EnabledCB> = None; | random_line_split |
logger.rs | extern crate env_logger;
extern crate log_panics;
extern crate log;
#[cfg(target_os = "android")]
extern crate android_logger;
extern crate libc;
use self::env_logger::Builder as EnvLoggerBuilder;
use self::log::{LevelFilter, Level};
use std::env;
use std::io::Write;
#[cfg(target_os = "android")]
use self::android_log... | (&self) -> (*const c_void, Option<EnabledCB>, Option<LogCB>, Option<FlushCB>) {
match self {
LoggerState::Default => (ptr::null(), Some(LibindyDefaultLogger::enabled), Some(LibindyDefaultLogger::log), Some(LibindyDefaultLogger::flush)),
LoggerState::Custom => unsafe { (CONTEXT, ENABLED_C... | get | identifier_name |
logger.rs | extern crate env_logger;
extern crate log_panics;
extern crate log;
#[cfg(target_os = "android")]
extern crate android_logger;
extern crate libc;
use self::env_logger::Builder as EnvLoggerBuilder;
use self::log::{LevelFilter, Level};
use std::env;
use std::io::Write;
#[cfg(target_os = "android")]
use self::android_log... |
}
fn log(&self, record: &Record) {
let log_cb = self.log;
let level = record.level() as u32;
let target = CString::new(record.target()).unwrap();
let message = CString::new(record.args().to_string()).unwrap();
let module_path = record.module_path().map(|a| CString::ne... | { true } | conditional_block |
graph_models.py | import six
import sys
from optparse import make_option, NO_DEFAULT
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django_extensions.management.modelviz import generate_dot
try:
import pygraphviz
HAS_PYGRAPHVIZ = True
except ImportError:
HAS_PYGRAPHV... |
version = pygraphviz.__version__.rstrip("-svn")
try:
if tuple(int(v) for v in version.split('.')) < (0, 36):
# HACK around old/broken AGraph before version 0.36 (ubuntu ships with this old version)
import tempfile
tmpfile = tempfile.NamedTempo... | random_line_split | |
graph_models.py | import six
import sys
from optparse import make_option, NO_DEFAULT
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django_extensions.management.modelviz import generate_dot
try:
import pygraphviz
HAS_PYGRAPHVIZ = True
except ImportError:
HAS_PYGRAPHV... |
def print_output(self, dotdata):
if six.PY3 and isinstance(dotdata, six.binary_type):
dotdata = dotdata.decode()
print(dotdata)
def render_output_pygraphviz(self, dotdata, **kwargs):
"""Renders the image using pygraphviz"""
if not HAS_PYGRAPHVIZ:
raise... | defaults = getattr(settings, 'GRAPH_MODELS', None)
if defaults:
for option in self.graph_models_options:
long_opt = option._long_opts[0]
if long_opt:
long_opt = long_opt.lstrip("-").replace("-", "_")
if long_opt in defaults:
... | identifier_body |
graph_models.py | import six
import sys
from optparse import make_option, NO_DEFAULT
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django_extensions.management.modelviz import generate_dot
try:
import pygraphviz
HAS_PYGRAPHVIZ = True
except ImportError:
HAS_PYGRAPHV... | (self, dotdata):
if six.PY3 and isinstance(dotdata, six.binary_type):
dotdata = dotdata.decode()
print(dotdata)
def render_output_pygraphviz(self, dotdata, **kwargs):
"""Renders the image using pygraphviz"""
if not HAS_PYGRAPHVIZ:
raise CommandError("You nee... | print_output | identifier_name |
graph_models.py | import six
import sys
from optparse import make_option, NO_DEFAULT
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django_extensions.management.modelviz import generate_dot
try:
import pygraphviz
HAS_PYGRAPHVIZ = True
except ImportError:
HAS_PYGRAPHV... |
except ValueError:
pass
graph = pygraphviz.AGraph(dotdata)
graph.layout(prog=kwargs['layout'])
graph.draw(kwargs['outputfile'])
def render_output_pydot(self, dotdata, **kwargs):
"""Renders the image using pydot"""
if not HAS_PYDOT:
raise Com... | import tempfile
tmpfile = tempfile.NamedTemporaryFile()
tmpfile.write(dotdata)
tmpfile.seek(0)
dotdata = tmpfile.name | conditional_block |
union-const-eval-field.rs | // Copyright 2018 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 ... | () -> Field1 {
const FIELD1: Field1 = unsafe { UNION.field1 };
FIELD1
}
const fn read_field2() -> Field2 {
const FIELD2: Field2 = unsafe { UNION.field2 };
FIELD2
}
const fn read_field3() -> Field3 {
const FIELD3: Field3 = unsafe { UNION.field3 };
//~^ ERROR it is undefined behavior to use this... | read_field1 | identifier_name |
union-const-eval-field.rs | // Copyright 2018 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 ... |
const fn read_field2() -> Field2 {
const FIELD2: Field2 = unsafe { UNION.field2 };
FIELD2
}
const fn read_field3() -> Field3 {
const FIELD3: Field3 = unsafe { UNION.field3 };
//~^ ERROR it is undefined behavior to use this value
FIELD3
}
fn main() {
assert_eq!(read_field1(), FLOAT1_AS_I32);
... | {
const FIELD1: Field1 = unsafe { UNION.field1 };
FIELD1
} | identifier_body |
union-const-eval-field.rs | // Copyright 2018 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 ... |
const fn read_field2() -> Field2 {
const FIELD2: Field2 = unsafe { UNION.field2 };
FIELD2
}
const fn read_field3() -> Field3 {
const FIELD3: Field3 = unsafe { UNION.field3 };
//~^ ERROR it is undefined behavior to use this value
FIELD3
}
fn main() {
assert_eq!(read_field1(), FLOAT1_AS_I32);
... | const fn read_field1() -> Field1 {
const FIELD1: Field1 = unsafe { UNION.field1 };
FIELD1
} | random_line_split |
RestroomMen.js | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = ... |
Icon.displayName = 'RestroomMen';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
}; | }; | random_line_split |
RestroomMen.js | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = ... | extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-restroom-men`,
className,
{
[`${CLASS_ROOT}--${size}`]: ... | Icon | identifier_name |
RestroomMen.js | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = ... | }
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'RestroomMen';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['small', 'medium', 'large', 'xlarge', 'huge']),
resp... | {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-restroom-men`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--re... | identifier_body |
01-document.py | import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
import codecs
from pattern.vector import Document, PORTER, LEMMA
# A Document is a "bag-of-words" that splits a string into words and counts them.
# A list of words or dictionary of (word, count)-items can also be given.
# Words ... |
# Document vectors can be bundled into a Model (next example). | print feature, weight | conditional_block |
01-document.py | import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
import codecs
from pattern.vector import Document, PORTER, LEMMA
# A Document is a "bag-of-words" that splits a string into words and counts them.
# A list of words or dictionary of (word, count)-items can also be given.
# Words ... | # With threshold=1, only words that occur more than once are counted.
# With stopwords=False, words like "the", "and", "I", "is" are ignored.
document = Document(s, threshold=1, stopwords=False)
print document.words
print
# The /corpus folder contains texts mined from Wikipedia.
# Below is the mining script (we alread... | random_line_split | |
QuickSelectButtons.tsx | import * as React from 'react';
import _ from 'lodash';
import { observer } from 'mobx-react';
import { CategorizedConfigItems } from '../../../config/IAppConfig';
import { DefaultTooltip } from 'cbioportal-frontend-commons';
@observer
export default class QuickSelectButtons extends React.Component<
{
butt... | );
return tooltipText ? (
<DefaultTooltip overlay={tooltipEl}>
{buttonEl}
</DefaultTooltip>
) : (
buttonEl
);
})}
... | </span> | random_line_split |
Trait.js | /**
* Trait class
*/
function Trait(methods, allTraits) |
Trait.prototype = {
constructor: Trait,
use: function (trait) {
if (trait) {
this.traits = this.traits.concat(trait.traits);
}
return this;
},
useBy: function (obj) {
for (var i = 0, c = this.traits.length; i < c; i++) {
var metho... | {
allTraits = allTraits || [];
this.traits = [methods];
var extraTraits = methods.$traits;
if (extraTraits) {
if (typeof extraTraits === "string") {
extraTraits = extraTraits.replace(/ /g, '').split(',');
}
for (var i = 0, c = extraTraits.length; i < c; i++) {... | identifier_body |
Trait.js | /**
* Trait class
*/
function Trait(methods, allTraits) {
allTraits = allTraits || [];
this.traits = [methods];
var extraTraits = methods.$traits;
if (extraTraits) {
if (typeof extraTraits === "string") {
extraTraits = extraTraits.replace(/ /g, '').split(',');
}... |
module.exports = Trait; | }
}
}
}
};
| random_line_split |
Trait.js | /**
* Trait class
*/
function | (methods, allTraits) {
allTraits = allTraits || [];
this.traits = [methods];
var extraTraits = methods.$traits;
if (extraTraits) {
if (typeof extraTraits === "string") {
extraTraits = extraTraits.replace(/ /g, '').split(',');
}
for (var i = 0, c = extraTraits.... | Trait | identifier_name |
Trait.js | /**
* Trait class
*/
function Trait(methods, allTraits) {
allTraits = allTraits || [];
this.traits = [methods];
var extraTraits = methods.$traits;
if (extraTraits) {
if (typeof extraTraits === "string") {
extraTraits = extraTraits.replace(/ /g, '').split(',');
}... |
}
}
Trait.prototype = {
constructor: Trait,
use: function (trait) {
if (trait) {
this.traits = this.traits.concat(trait.traits);
}
return this;
},
useBy: function (obj) {
for (var i = 0, c = this.traits.length; i < c; i++) {
... | {
this.use(allTraits[extraTraits[i]]);
} | conditional_block |
Slider.tsx | import React, { FunctionComponent } from 'react';
import { Range, createSliderWithTooltip } from 'rc-slider';
import { cx, css } from 'emotion';
import { Global, css as cssCore } from '@emotion/core';
import { stylesFactory } from '../../themes';
import { GrafanaTheme } from '@savantly/sprout-api';
import { useTheme } ... |
.rc-slider-tooltip-placement-top .rc-slider-tooltip-arrow {
display: none;
}
.rc-slider-tooltip-placement-top {
padding: 0;
}
}
`,
};
});
export const Slider: FunctionComponent<Props> = ({
min,
max,
onChange,
onAfterChange,
orientation = 'horizontal',
rever... | random_line_split | |
class_method.rs | // Copyright 2016-17 Alexander Reece
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accord... | (&self) -> &Self::Target {
self.method
}
} | deref | identifier_name |
class_method.rs | // Copyright 2016-17 Alexander Reece
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accord... | &self.pascal_case
}
pub fn has_lifetimes(&self) -> bool {
self.has_lifetimes
}
pub fn has_usable_fields(&self) -> bool {
self.has_usable_fields
}
}
impl Deref for ClassMethod {
type Target = specs::ClassMethod;
fn deref(&self) -> &Self::Target {
self.metho... | pub fn pascal_case(&self) -> &str { | random_line_split |
class_method.rs | // Copyright 2016-17 Alexander Reece
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accord... |
}
impl Deref for ClassMethod {
type Target = specs::ClassMethod;
fn deref(&self) -> &Self::Target {
self.method
}
} | {
self.has_usable_fields
} | identifier_body |
ex3.py | """
example with 'calls_expected' in addtoBatch used
"""
import batchOpenMPI
def f_mult(x) :
|
f = batchOpenMPI.batchFunction(f_mult) #creating function wrapper
batchOpenMPI.begin_MPI_loop() # both the workers and the master process run the same code up until here
f.addtoBatch(4,calls_expected=4)
batchOpenMPI.processBatch() #get the workers to calculate all the inputs
res = [f(4),f(4),f(4)]
print(res)
#anoth... | return x*2.0 | identifier_body |
ex3.py | """
example with 'calls_expected' in addtoBatch used
"""
import batchOpenMPI
def f_mult(x) :
return x*2.0
f = batchOpenMPI.batchFunction(f_mult) #creating function wrapper
batchOpenMPI.begin_MPI_loop() # both the workers and the master process run the same code up until here
f.addtoBatch(4,calls_expected=4)
bat... |
print("*** jobs executed by workers should be 2 ,(5 calls made),jobs uncollected should = 1, jobs_master=1") | batchOpenMPI.end_MPI_loop(print_stats=True) #releases workers | random_line_split |
ex3.py | """
example with 'calls_expected' in addtoBatch used
"""
import batchOpenMPI
def | (x) :
return x*2.0
f = batchOpenMPI.batchFunction(f_mult) #creating function wrapper
batchOpenMPI.begin_MPI_loop() # both the workers and the master process run the same code up until here
f.addtoBatch(4,calls_expected=4)
batchOpenMPI.processBatch() #get the workers to calculate all the inputs
res = [f(4),f(4),f(... | f_mult | identifier_name |
GridSelectionTest.ts | import { Assertions, GeneralSteps, Logger, Pipeline, Step } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { LegacyUnit, TinyLoader } from '@ephox/mcagar';
import Tools from 'tinymce/core/api/util/Tools';
import Plugin from 'tinymce/plugins/table/Plugin';
import Theme from 'tinymce/themes/modern... | assertTableSelection(editor, '<table><tr><td>1</td><td>2</td></tr><tr><td>3</td><td>4</td></tr></table>', ['1', '3'], ['1', '3']);
assertTableSelection(editor,
'<table><tr><td>1</td><td>2</td></tr><tr><td>3</td><td>4</td></tr></table>', ['1', '4'], ['1', '2', '3', '4']);
assertTableSelection(editor,
... | };
suite.test('Table grid selection', function (editor) {
assertTableSelection(editor, '<table><tr><td>1</td><td>2</td></tr><tr><td>3</td><td>4</td></tr></table>', ['1', '2'], ['1', '2']); | random_line_split |
GridSelectionTest.ts | import { Assertions, GeneralSteps, Logger, Pipeline, Step } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { LegacyUnit, TinyLoader } from '@ephox/mcagar';
import Tools from 'tinymce/core/api/util/Tools';
import Plugin from 'tinymce/plugins/table/Plugin';
import Theme from 'tinymce/themes/modern... | (table, startTd, endTd) {
editor.fire('mousedown', { target: startTd, button: 0 });
editor.fire('mouseover', { target: endTd, button: 0 });
editor.fire('mouseup', { target: endTd, button: 0 });
}
function getCells(table) {
return editor.$(table).find('td').toArray();
}
function... | selectRangeXY | identifier_name |
GridSelectionTest.ts | import { Assertions, GeneralSteps, Logger, Pipeline, Step } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { LegacyUnit, TinyLoader } from '@ephox/mcagar';
import Tools from 'tinymce/core/api/util/Tools';
import Plugin from 'tinymce/plugins/table/Plugin';
import Theme from 'tinymce/themes/modern... |
editor.setContent(tableHtml);
const table = editor.$('table')[0];
const cells = getCells(table);
const startTd = Tools.grep(cells, function (elm) {
return elm.innerHTML === selectCells[0];
})[0];
const endTd = Tools.grep(cells, function (elm) {
return elm.innerHTML === selectCel... | {
return editor.$(table).find('td[data-mce-selected]').toArray();
} | identifier_body |
utils.js | /**
* utility library
*/
var basicAuth = require('basic-auth');
var fs = require('fs');
/**
* Simple basic auth middleware for use with Express 4.x.
*
* @example
* app.use('/api-requiring-auth', utils.basicAuth('username', 'password'));
*
* @param {string} username Expected username
* @param {string}... |
next();
};
};
exports.cpuTemp = function() {
var cputemp = Math.round(((parseFloat(fs.readFileSync("/sys/class/thermal/thermal_zone0/temp"))/1000) * (9/5) + 32)*100)/100;
return cputemp;
};
exports.w1Temp = function(serial) {
var temp;
var re=/t=(\d+)/;
try {
var text=fs.readFileSync('/sys/bus/w... | {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.sendStatus(401);
} | conditional_block |
utils.js | /**
* utility library
*/
var basicAuth = require('basic-auth');
var fs = require('fs');
/**
* Simple basic auth middleware for use with Express 4.x.
*
* @example
* app.use('/api-requiring-auth', utils.basicAuth('username', 'password'));
*
* @param {string} username Expected username
* @param {string}... | next();
};
};
exports.cpuTemp = function() {
var cputemp = Math.round(((parseFloat(fs.readFileSync("/sys/class/thermal/thermal_zone0/temp"))/1000) * (9/5) + 32)*100)/100;
return cputemp;
};
exports.w1Temp = function(serial) {
var temp;
var re=/t=(\d+)/;
try {
var text=fs.readFileSync('/sys/bus/w1/... | res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.sendStatus(401);
}
| random_line_split |
setup.py | # -*- coding: utf-8 -*-
"""
pytest-pylint
=============
Plugin for py.test for doing pylint tests
"""
from setuptools import setup
setup(
name='pytest-pylint',
description='pytest plugin to check source code with pylint',
long_description=open("README.rst").read(),
license="MIT",
version='0.3.0',... | 'Programming Language :: Python :: 3.4',
],
) | 'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3', | random_line_split |
UserListModalEntry.tsx | import * as React from "react";
import FollowButton from "../FollowButton";
import SimilarityScore from "../SimilarityScore";
import { SimilarUsersModalProps } from "./SimilarUsersModal";
export type UserListModalEntryProps = {
mode: "follow-following" | "similar-users";
user: ListenBrainzUser | SimilarUser;
log... | rel="noopener noreferrer"
>
{user.name}
</a>
{loggedInUser && mode === "similar-users" && (
<SimilarityScore
similarityScore={(user as SimilarUser).similarityScore}
user={user}
type="compact"
/>
... | <div>
<a
href={`/user/${user.name}`}
target="_blank" | random_line_split |
index.js |
context of the RichTextEditor component and to have the invocation of that
method be safely handled and executed by the Ember run loop.
@method bind
@static
@for @ember/runloop
@param {Object} [target] target of method to call
@param {Function|String} method Method to invoke.
May be a function or a ... | random_line_split | ||
index.js |
export const backburner = new Backburner(queues, backburnerOptions);
/**
@module @ember/runloop
*/
// ..........................................................
// run - this is ideally the only public API the dev sees
//
/**
Runs the passed target and method inside of a RunLoop, ensuring any
deferred actions ... | {
queues.unshift('sync');
backburnerOptions.sync = {
before: beginPropertyChanges,
after: endPropertyChanges,
};
} | conditional_block | |
index.js | of that function to the Ember run loop. This ability
makes this method a great way to asynchronously integrate third-party libraries
into your Ember application.
`bind` takes two main arguments, the desired context and the function to
invoke in that context. Any additional arguments will be supplied as argume... | (/*target, method*/) {
return backburner.later(...arguments);
}
/**
Schedule a function to run one time during the current RunLoop. This is equivalent
to calling `scheduleOnce` with the "actions" queue.
@method once
@static
@for @ember/runloop
@param {Object} [target] The target of the method to invoke.
... | later | identifier_name |
index.js | of that function to the Ember run loop. This ability
makes this method a great way to asynchronously integrate third-party libraries
into your Ember application.
`bind` takes two main arguments, the desired context and the function to
invoke in that context. Any additional arguments will be supplied as argume... |
/**
Schedule a function to run one time during the current RunLoop. This is equivalent
to calling `scheduleOnce` with the "actions" queue.
@method once
@static
@for @ember/runloop
@param {Object} [target] The target of the method to invoke.
@param {Function|String} method The method to invoke.
If yo... | {
return backburner.later(...arguments);
} | identifier_body |
index.js | import React from "react"
import { graphql } from "gatsby"
import Helmet from "react-helmet"
import Layout from "../components/layout"
import presets, { colors } from "../utils/presets"
import { rhythm, options } from "../utils/typography"
import { WebpackIcon, ReactJSIcon, GraphQLIcon } from "../assets/logos"
import {... | extends React.Component {
render() {
const blogPosts = this.props.data.allMarkdownRemark
return (
<Layout location={this.props.location}>
<Helmet>
<meta
name="Description"
content="Blazing fast modern site generator for React. Go beyond static sites: build blog... | IndexRoute | identifier_name |
index.js | import React from "react"
import { graphql } from "gatsby"
import Helmet from "react-helmet"
import Layout from "../components/layout"
import presets, { colors } from "../utils/presets"
import { rhythm, options } from "../utils/typography"
import { WebpackIcon, ReactJSIcon, GraphQLIcon } from "../assets/logos"
import {... | </div>
</div>
</Layout>
)
}
}
export default IndexRoute
export const pageQuery = graphql`
query {
file(relativePath: { eq: "gatsby-explanation.png" }) {
childImageSharp {
fluid(maxWidth: 870) {
src
srcSet
sizes
}
}
}
... | </main>
</div> | random_line_split |
index.js | import React from "react"
import { graphql } from "gatsby"
import Helmet from "react-helmet"
import Layout from "../components/layout"
import presets, { colors } from "../utils/presets"
import { rhythm, options } from "../utils/typography"
import { WebpackIcon, ReactJSIcon, GraphQLIcon } from "../assets/logos"
import {... | <MastheadContent />
<UsedBy />
<div
css={{
padding: rhythm(presets.gutters.default / 2),
flex: `0 0 100%`,
maxWidth: `100%`,
[presets.Hd]: {
padding: vP,
paddingTop: 0,
... | {
const blogPosts = this.props.data.allMarkdownRemark
return (
<Layout location={this.props.location}>
<Helmet>
<meta
name="Description"
content="Blazing fast modern site generator for React. Go beyond static sites: build blogs, ecommerce sites, full-blown apps, a... | identifier_body |
Safe.pipe.ts | import {Pipe} from '@angular/core';
import {DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl} from '@angular/platform-browser';
@Pipe({
name: 'safe'
})
export class SafePipe {
| (protected _sanitizer: DomSanitizer) {
}
public transform(value: string, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
switch (type) {
case 'html':
return this._sanitizer.bypassSecurityTrustHtml(value);
case 'style':
return this._sanitizer.bypassSecurityTrustStyl... | constructor | identifier_name |
Safe.pipe.ts | import {Pipe} from '@angular/core';
import {DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl} from '@angular/platform-browser';
@Pipe({
name: 'safe'
})
export class SafePipe {
constructor(protected _sanitizer: DomSanitizer) {
}
public transform(value: string, type: string): SafeHtml | Saf... | case 'script':
return this._sanitizer.bypassSecurityTrustScript(value);
case 'url':
return this._sanitizer.bypassSecurityTrustUrl(value);
case 'resourceUrl':
return this._sanitizer.bypassSecurityTrustResourceUrl(value);
default:
throw new Error(`Unable to bypass security for inva... | random_line_split | |
index.d.ts | // Type definitions for cors 2.8
// Project: https://github.com/troygoode/node-cors/
// Definitions by: Alan Plum <https://github.com/pluma>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2 |
import express = require('express');
type CustomOrigin = (
requestOrigin: string,
callback: (err: Error | null, allow?: boolean) => void
) => void;
declare namespace e {
interface CorsOptions {
origin?: boolean | string | RegExp | (string | RegExp)[] | CustomOrigin;
methods?: string | str... | random_line_split | |
firebase_update.js | module.exports = function (RED) {
var firebase = require('firebase');
var Utils = require('./utils/utils');
var _ = require('lodash-node');
function FirebaseUpdate(n) {
RED.nodes.createNode(this, n);
this.firebaseConfig = RED.nodes.getNode(n.firebaseConfig);
this.childpath = n.childpath;
this.a... |
this.status({ fill: "green", shape: "ring", text: "Connected" });
this.on('input', function (msg) {
if (this.firebaseConfig.fbConfig.fbApp) {
firebase.database().ref(this.childpath).update(msg.payload);
node.status({ fill: "green", shape: "ring", text: "Updated Data at " + Utils.getTime(... | {
this.status({ fill: "red", shape: "ring", text: "invalid credentials" })
this.error('You need to setup Firebase credentials!');
return;
} | conditional_block |
firebase_update.js | module.exports = function (RED) {
var firebase = require('firebase');
var Utils = require('./utils/utils');
var _ = require('lodash-node');
function | (n) {
RED.nodes.createNode(this, n);
this.firebaseConfig = RED.nodes.getNode(n.firebaseConfig);
this.childpath = n.childpath;
this.activeRequests = [];
this.ready = false;
var node = this;
if (!this.firebaseConfig) {
this.status({ fill: "red", shape: "ring", text: "invalid credentials... | FirebaseUpdate | identifier_name |
firebase_update.js | module.exports = function (RED) {
var firebase = require('firebase');
var Utils = require('./utils/utils');
var _ = require('lodash-node');
function FirebaseUpdate(n) | }
});
}
RED.nodes.registerType('shri.firebase.update', FirebaseUpdate);
};
| {
RED.nodes.createNode(this, n);
this.firebaseConfig = RED.nodes.getNode(n.firebaseConfig);
this.childpath = n.childpath;
this.activeRequests = [];
this.ready = false;
var node = this;
if (!this.firebaseConfig) {
this.status({ fill: "red", shape: "ring", text: "invalid credentials" })... | identifier_body |
firebase_update.js | module.exports = function (RED) {
var firebase = require('firebase');
var Utils = require('./utils/utils');
var _ = require('lodash-node');
function FirebaseUpdate(n) {
RED.nodes.createNode(this, n);
this.firebaseConfig = RED.nodes.getNode(n.firebaseConfig);
this.childpath = n.childpath;
this.a... | }
RED.nodes.registerType('shri.firebase.update', FirebaseUpdate);
}; | node.send(msg);
}
}); | random_line_split |
epub.py | item', '',
[
('href', self.name),
('id', self.ident),
('media-type', self.media_type)
])
def spine_entry(self):
'''Write the XML element for the spine.
(Empty string if in_spine is False.)'''
if self.in_spine:
return _make_x... |
except IndexError:
pass
try:
day = int(m.group(3)[1:])
datetime.date(year, mon, day) # raises ValueError if invalid
except IndexError:
pass
self.tag = 'dc:date'
self.text = date
self.attr = ()
class _EpubLang(_EpubMeta):
... | raise ValueError('month must be in 1..12') | conditional_block |
epub.py | n'
'<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">\n'
' <rootfiles>\n'
' <rootfile full-path="package.opf" media-type="application/oebps-package+xml"/>\n'
' </rootfiles>\n'
'</container>\n'
)
_html = (
'<?xml version="1.0" encoding="ut... | guide_type = None, arcname = None):
'''Include an external file into the ebook. By default, it will
be added to the archive under its basename; the argument
"arcname" can be used to specify a different name.''' | random_line_split | |
epub.py | item', '',
[
('href', self.name),
('id', self.ident),
('media-type', self.media_type)
])
def spine_entry(self):
'''Write the XML element for the spine.
(Empty string if in_spine is False.)'''
if self.in_spine:
return _make_x... | (self):
'''Write the XML element for the guide.
(Empty string if no guide title and type are given.)'''
if self.guide_title and self.guide_type:
return _make_xml_elem('reference', '',
[
('title', self.guide_title),
('type', self.guide_typ... | guide_entry | identifier_name |
epub.py | '{0}<navPoint id="nav{1}">\n'
'{0} <navLabel>\n'
'{0} <text>{2}</text>\n'
'{0} </navLabel>\n'
'{0} <content src="{3}" />\n'
))
def _navp_xml(self, entry, indent_lvl):
'Write xml for an entry and all its subentries.'
xml = self._navp.format(' '*indent_lvl, st... | 'Table of contents.'
_head = ((
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1" xml:lang="en-US">\n'
' <head>\n'
' <meta name="dtb:uid" content="{}" />\n'
' <meta name="dtb:depth" content="{}" />\n'
' <meta ... | identifier_body | |
os_str.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn push_slice(&mut self, s: &Slice) {
self.inner.push_wtf8(&s.inner)
}
}
impl Slice {
pub fn from_str(s: &str) -> &Slice {
unsafe { mem::transmute(Wtf8::from_str(s)) }
}
pub fn to_str(&self) -> Option<&str> {
self.inner.as_str()
}
pub fn to_string_lossy(&self... | {
self.inner.into_string().map_err(|buf| Buf { inner: buf })
} | identifier_body |
os_str.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | pub fn as_slice(&self) -> &Slice {
unsafe { mem::transmute(self.inner.as_slice()) }
}
pub fn into_string(self) -> Result<String, Buf> {
self.inner.into_string().map_err(|buf| Buf { inner: buf })
}
pub fn push_slice(&mut self, s: &Slice) {
self.inner.push_wtf8(&s.inner)
... | Buf { inner: Wtf8Buf::from_string(s) }
}
| random_line_split |
os_str.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
self.inner.fmt(formatter)
}
}
impl Buf {
pub fn from_string(s: String) -> Buf {
Buf { inner: Wtf8Buf::from_string(s) }
}
pub fn as_slice(&self) -> &Slice {
unsafe { mem::transmute(self.inner.as_slice()) }
}... | fmt | identifier_name |
transport.rs | use std::convert::From;
use std::io;
use std::io::prelude::*;
#[derive(Debug)]
pub enum Error {
Io(io::Error),
BadInput(&'static str),
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Error::Io(err)
}
}
const LENGTH_HEADER: &'static str = "Content-Length:";
#[derive(Debug... |
}
let content_length = content_length.ok_or(Error::BadInput("no content length"))?;
self.read_buffer.clear();
(&mut self.reader)
.take(content_length)
.read_line(&mut self.read_buffer)?;
Ok(self.read_buffer.clone())
}
pub fn send_message(&mut sel... | {
return Err(Error::BadInput("unexpected eof"));
} | conditional_block |
transport.rs | use std::convert::From;
use std::io;
use std::io::prelude::*;
#[derive(Debug)]
pub enum Error {
Io(io::Error),
BadInput(&'static str),
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Error::Io(err)
}
}
const LENGTH_HEADER: &'static str = "Content-Length:";
#[derive(Debug... | } else if self.read_buffer == "\r\n" {
break;
} else if self.read_buffer.is_empty() {
return Err(Error::BadInput("unexpected eof"));
}
}
let content_length = content_length.ok_or(Error::BadInput("no content length"))?;
self.read... | random_line_split | |
transport.rs | use std::convert::From;
use std::io;
use std::io::prelude::*;
#[derive(Debug)]
pub enum Error {
Io(io::Error),
BadInput(&'static str),
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Error::Io(err)
}
}
const LENGTH_HEADER: &'static str = "Content-Length:";
#[derive(Debug... | (reader: R, writer: W) -> Self {
Transport {
read_buffer: String::new(),
reader,
writer,
}
}
pub fn read_message(&mut self) -> Result<String, Error> {
let mut content_length = None;
loop {
self.read_buffer.clear();
self... | new | identifier_name |
moving_avg_net.js | 0.3285535310819797,
65: -0.09546114827149688,
66: -0.7147345133646377,
67: 10.189854736303543,
74: 0.2206061082955423,
83: 0.057572114707332415,
75: -2.4998375726165474,
76: -2.7954210713027443,
77: 3.3710663208638567,
84: 0.054257566315458174
};
F[0] = input[0];
F[1] = input[1];
F[2] = input[2];
F[3] = input[3];
F[4]... | {
// set up USB serial port
USB.setup(115200,{
bytesize:8, // How many data bits
stopbits:1, // Number of stop bits to use
});
sensor_data = []; // initialise sensor array that will hold objects
// list of sensor names
sensor_names = ["front_left","front_right","left","right","back"];
// lis... | identifier_body | |
moving_avg_net.js | 8457515236,
54: 0.24982956020584846,
62: -3.234370678324734,
72: -2.8435237716709016,
82: 0.42830345699084077,
63: 0.5035156049687228,
55: -0.32130179138580495,
56: 0.014062651620663225,
57: 14.605665153004754,
64: 0.24998764052170389,
73: 0.3285535310819797,
65: -0.09546114827149688,
66: -0.7147345133646377,
67: 10.18... | onInit | identifier_name | |
moving_avg_net.js | 84,
28: -149.75223065722227,
29: -78.93971528453746,
30: -4.325653240247082,
31: 0.391635118645311,
32: 43.63778415344155,
34: 0.19404594592684338,
60: -4.214589549036702,
70: -6.75989422197201,
80: 0.353125540117511,
43: 0.9138069113725101,
35: 2.2606694512316934,
36: 2.3610292963124633,
37: -4.6254624603393895,
38: 0... | F[15] = F[16];F[16] = F[17];F[16] += F[0] * F[18];F[16] += F[1] * F[19];F[16] += F[2] * F[20];F[16] += F[3] * F[21];F[16] += F[4] * F[22];F[23] = (1 / (1 + Math.exp(-F[16])));F[24] = F[23] * (1 - F[23]);
F[25] = F[26];F[26] = F[27];F[26] += F[0] * F[28];F[26] += F[1] * F[29];F[26] += F[2] * F[30];F[26] += F[3] * F[31];... | random_line_split | |
moving_avg_net.js | ] = F[6];F[6] = F[7];F[6] += F[0] * F[8];F[6] += F[1] * F[9];F[6] += F[2] * F[10];F[6] += F[3] * F[11];F[6] += F[4] * F[12];F[13] = (1 / (1 + Math.exp(-F[6])));F[14] = F[13] * (1 - F[13]);
F[15] = F[16];F[16] = F[17];F[16] += F[0] * F[18];F[16] += F[1] * F[19];F[16] += F[2] * F[20];F[16] += F[3] * F[21];F[16] += F[4] *... | {
sensor_data[i] = {
name: sensor_names[i], // sensor name
pin: pins[i], // sensor pin
reading: [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], // initialise readings array
mov_avg: function() {
var sum = 0;
for (var j in this.reading) {sum += this.reading[j];} // calculate array total
... | conditional_block | |
index.js | 'exciting!', _doc: { title: 'great!' }}
* , { title: 'number dos' }
* ]
* }
*
* mpath.get('comments.0.title', o) // 'exciting!'
* mpath.get('comments.0.title', o, '_doc') // 'great!'
* mpath.get('comments.title', o) // ['exciting!', 'number dos']
*
* // ... | {
return v;
} | identifier_body | |
index.js | ['__proto__', 'constructor', 'prototype'];
/**
* Returns the value of object `o` at the given `path`.
*
* ####Example:
*
* var obj = {
* comments: [
* { title: 'exciting!', _doc: { title: 'great!' }}
* , { title: 'number dos' }
* ]
* }
*
* mpath.get('comme... |
exports.unset = function (path, o) {
var parts = typeof path === 'string' ?
path.split('.') :
path;
if (!Array.isArray(parts)) {
throw new TypeError('Invalid `path`. Must be either string or array');
}
var len = parts.length;
var cur = o;
for (var i = 0; i < len; ++i) {
if (cur == null ||... | * @param {Object} o
*/ | random_line_split |
index.js | comments: [
* { title: 'exciting!', _doc: { title: 'great!' }}
* , { title: 'number dos' }
* ]
* }
*
* mpath.get('comments.0.title', o) // 'exciting!'
* mpath.get('comments.0.title', o, '_doc') // 'great!'
* mpath.get('comments.title', o) ... | K | identifier_name | |
socket.io-client.d.ts | declare var io: SocketIOClientStatic;
declare module 'socket.io-client' {
export = io;
}
| (details?: any): SocketIOClient.Socket;
connect(host: string, details?: any): SocketIOClient.Socket;
connect(details?: any): SocketIOClient.Socket;
protocol: number;
Socket: { new (...args: any[]): SocketIOClient.Socket };
Manager: SocketIOClient.ManagerStatic;
}
declare module SocketIOClient {... | interface SocketIOClientStatic {
(host: string, details?: any): SocketIOClient.Socket; | random_line_split |
redis_view.py | #
# Hubblemon - Yet another general purpose system monitor
#
# Copyright 2015 NAVER Corp.
#
# 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
#
# Un... | global redis_cloud_map
global last_ts
ts = time.time()
if ts - last_ts >= 300:
redis_cloud_map_tmp = {}
entity_list = common.core.get_entity_list()
for entity in entity_list:
instance_list = common.core.get_table_list_of_entity(entity, 'redis_')
if len(instance_list) > 0:
redis_cloud_map_tmp[entity... | def get_chart_list(param):
#print(param) | random_line_split |
redis_view.py |
#
# Hubblemon - Yet another general purpose system monitor
#
# Copyright 2015 NAVER Corp.
#
# 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
#
# U... | (path, title = ''):
return common.core.loader(path, redis_preset, title)
#
# chart list
#
redis_cloud_map = {}
last_ts = 0
def init_plugin():
print('#### redis init ########')
ret = get_chart_list({})
print(ret)
def get_chart_data(param):
#print(param)
global redis_cloud_map
type = 'redis_stat'
if 'typ... | redis_view | identifier_name |
redis_view.py |
#
# Hubblemon - Yet another general purpose system monitor
#
# Copyright 2015 NAVER Corp.
#
# 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
#
# U... |
#
# chart list
#
redis_cloud_map = {}
last_ts = 0
def init_plugin():
print('#### redis init ########')
ret = get_chart_list({})
print(ret)
def get_chart_data(param):
#print(param)
global redis_cloud_map
type = 'redis_stat'
if 'type' in param:
type = param['type']
if 'instance' not in param or 'serv... | return common.core.loader(path, redis_preset, title) | identifier_body |
redis_view.py |
#
# Hubblemon - Yet another general purpose system monitor
#
# Copyright 2015 NAVER Corp.
#
# 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
#
# U... |
return results
def get_chart_list(param):
#print(param)
global redis_cloud_map
global last_ts
ts = time.time()
if ts - last_ts >= 300:
redis_cloud_map_tmp = {}
entity_list = common.core.get_entity_list()
for entity in entity_list:
instance_list = common.core.get_table_list_of_entity(entity, 'redis_... | if node.startswith(instance_name):
results = common.core.loader(server_name + '/' + node, redis_preset, title=node)
break | conditional_block |
getMessageCount.ts | // WebChatty
// Copyright (C) 2015 Andy Christianson, Brian Luft, Willie Zutz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// right... | module.exports = (server: api.Server) => {
server.addRoute(api.RequestMethod.Post, "/v2/getMessageCount", async (req) => {
const query = new api.QueryParser(req);
const username = query.getString("username");
const password = query.getString("password");
const credentials = await ser... | import * as api from "../../index";
import * as spec from "../../../spec/index";
| random_line_split |
home.client.controller.js | angular.module('core').controller('HomeController', ['$scope', 'Authentication',
function($scope, Authentication) {
// This provides Authentication context.
$scope.authentication = Authentication;
$scope.alerts = [
{
icon: 'glyphicon-user',
colour: 'btn-success',
total: '20,408',
description: 'TOT... | 'use strict';
| random_line_split | |
index.spec.ts | import {
Client,
Server,
IGBClientMessage,
IGBServerMessage,
IServiceHandle,
IGRPCTree,
} from './index';
import { buildTree, MockServer } from './mock';
let grpc = require('grpc');
let mockProtoDefs = buildTree();
let mockProto = grpc.loadObject(mockProtoDefs.lookup(''));
describe('e2e', () => {
let gr... | }, 5000);
}); | random_line_split | |
index.spec.ts | import {
Client,
Server,
IGBClientMessage,
IGBServerMessage,
IServiceHandle,
IGRPCTree,
} from './index';
import { buildTree, MockServer } from './mock';
let grpc = require('grpc');
let mockProtoDefs = buildTree();
let mockProto = grpc.loadObject(mockProtoDefs.lookup(''));
describe('e2e', () => {
let gr... |
done();
});
call.write({name: 'FailFish'});
call.end();
}, 5000);
it('should make a bidirectional streaming call properly', (done) => {
mockServer.callReceived.subscribe((call: string) => {
expect(call).toBe('sayHelloBidiStream');
});
let call = gbClientService['sayHelloBidiStr... | {
throw err;
} | conditional_block |
assistant.js | 'use strict';
var React = require('react');
var SvgIcon = require('../../svg-icon');
var ImageAssistant = React.createClass({
displayName: 'ImageAssistant',
render: function render() {
return React.createElement( | }
});
module.exports = ImageAssistant; | SvgIcon,
this.props,
React.createElement('path', { d: "M19 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h4l3 3 3-3h4c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-5.12 10.88L12 17l-1.88-4.12L6 11l4.12-1.88L12 5l1.88 4.12L18 11l-4.12 1.88z" })
); | random_line_split |
test_clean_prime_step.py | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016-2018 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in ... |
def test_clean_prime_step(self):
bindir = os.path.join(self.prime_dir, 'bin')
self.assertThat(os.path.join(bindir, 'file1'), FileExists())
self.assertThat(os.path.join(bindir, 'file2'), FileExists())
output = self.run_snapcraft(
['clean', '--step=prime'], debug=False)
... | super().setUp()
self.copy_project_to_cwd('independent-parts')
self.run_snapcraft('prime') | identifier_body |
test_clean_prime_step.py | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016-2018 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in ... | # Now try to prime again
self.run_snapcraft('prime')
self.assertThat(os.path.join(bindir, 'file1'), FileExists())
self.assertThat(os.path.join(bindir, 'file2'), FileExists()) | random_line_split | |
test_clean_prime_step.py | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016-2018 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in ... | (self):
super().setUp()
self.copy_project_to_cwd('independent-parts')
self.run_snapcraft('prime')
def test_clean_prime_step(self):
bindir = os.path.join(self.prime_dir, 'bin')
self.assertThat(os.path.join(bindir, 'file1'), FileExists())
self.assertThat(os.path.join(... | setUp | identifier_name |
frame.js | var debug = require('debug')('openframe:model:Frame');
module.exports = function(Frame) {
Frame.disableRemoteMethodByName('createChangeStream');
// Remove sensitive data from Artworks being returned
// in public frames
// Frame.afterRemote('**', function(ctx, resultInstance, next) {
// debug('... | (frame, managers) {
var OpenframeUser = Frame.app.models.OpenframeUser;
return new Promise((resolve, reject) => {
OpenframeUser.find({ where: { username: { inq: managers }}}, function(err, users) {
if (err) {
debug(err);
}
... | addManagers | identifier_name |
frame.js | var debug = require('debug')('openframe:model:Frame');
module.exports = function(Frame) {
Frame.disableRemoteMethodByName('createChangeStream');
// Remove sensitive data from Artworks being returned
// in public frames
// Frame.afterRemote('**', function(ctx, resultInstance, next) {
// debug('... | count++;
if (count === total) {
// all who are no longer present in the new list have been removed
resolve();
}
}
});
... | {
return new Promise((resolve, reject) => {
frame.managers(function(err, current_managers) {
debug(current_managers);
if (current_managers.length) {
var count = 0,
total = current_managers.length;
current... | identifier_body |
frame.js | var debug = require('debug')('openframe:model:Frame');
module.exports = function(Frame) {
Frame.disableRemoteMethodByName('createChangeStream');
// Remove sensitive data from Artworks being returned
// in public frames
// Frame.afterRemote('**', function(ctx, resultInstance, next) {
// debug('... | }
}
});
}
else {
// there are no current managers
resolve();
}
});
});
}
// Painful painful painful -- so gross. Why loopback, why!?
function ... | {
var count = 0,
total = current_managers.length;
current_managers.forEach(function(cur_man) {
debug(cur_man);
if (managers.indexOf(cur_man.username) === -1) {
debug('removing %s',... | conditional_block |
frame.js | var debug = require('debug')('openframe:model:Frame');
module.exports = function(Frame) {
Frame.disableRemoteMethodByName('createChangeStream');
// Remove sensitive data from Artworks being returned
// in public frames
// Frame.afterRemote('**', function(ctx, resultInstance, next) {
// debug('... | count++;
if (count === total) {
Frame.findById(frame.id, {include: 'managers'}, function(err, frame) {
debug(err, frame);
resolve(frame);
... | // update hasAndBelongsToMany relationships :/
users.forEach(function(user) {
frame.managers.add(user, function(err) { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.