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 |
|---|---|---|---|---|
base64.rs | #![feature(test)]
extern crate test;
extern crate rustc_serialize;
use rustc_serialize::base64::{FromBase64, ToBase64, STANDARD};
use test::Bencher;
#[bench]
fn bench_to_base64(b: &mut Bencher) {
let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
b.iter(|| {
s.as_bytes(... | ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
let sb = s.as_bytes().to_base64(STANDARD);
b.iter(|| {
sb.from_base64().unwrap();
});
b.bytes = sb.len() as u64;
}
#[bench]
fn bench_to_base64_large(b: &mut Bencher) {
let s: Vec<_> = (0..10000).map(|i| ((i as u32 * 12345) % 256) as u8).collect()... | #[bench]
fn bench_from_base64(b: &mut Bencher) {
let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \ | random_line_split |
base64.rs | #![feature(test)]
extern crate test;
extern crate rustc_serialize;
use rustc_serialize::base64::{FromBase64, ToBase64, STANDARD};
use test::Bencher;
#[bench]
fn | (b: &mut Bencher) {
let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
b.iter(|| {
s.as_bytes().to_base64(STANDARD);
});
b.bytes = s.len() as u64;
}
#[bench]
fn bench_from_base64(b: &mut Bencher) {
let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
ウヰノオクヤマ ケフコ... | bench_to_base64 | identifier_name |
base64.rs | #![feature(test)]
extern crate test;
extern crate rustc_serialize;
use rustc_serialize::base64::{FromBase64, ToBase64, STANDARD};
use test::Bencher;
#[bench]
fn bench_to_base64(b: &mut Bencher) {
let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
b.iter(|| {
s.as_bytes(... | );
b.bytes = s.len() as u64;
}
#[bench]
fn bench_from_base64_large(b: &mut Bencher) {
let s: Vec<_> = (0..10000).map(|i| ((i as u32 * 12345) % 256) as u8).collect();
let sb = s.to_base64(STANDARD);
b.iter(|| {
sb.from_base64().unwrap();
});
b.bytes = sb.len() as u64;
}
| sb = s.as_bytes().to_base64(STANDARD);
b.iter(|| {
sb.from_base64().unwrap();
});
b.bytes = sb.len() as u64;
}
#[bench]
fn bench_to_base64_large(b: &mut Bencher) {
let s: Vec<_> = (0..10000).map(|i| ((i as u32 * 12345) % 256) as u8).collect();
b.iter(|| {
s.to_base64(STANDARD);
... | identifier_body |
suppliers.py | from flask.ext.wtf import Form
from wtforms import IntegerField, StringField, FieldList
from wtforms.validators import DataRequired, Email, ValidationError
def word_length(limit=None, message=None):
message = message or 'Must not be more than %d words'
message = message % limit
def _length(form, field):
... |
class EditContactInformationForm(Form):
id = IntegerField()
address1 = StringField('Business address')
address2 = StringField('Business address')
city = StringField('Town or city')
country = StringField()
postcode = StringField(validators=[
DataRequired(message="Postcode can not be em... | raise ValidationError('You must have 10 or fewer clients') | conditional_block |
suppliers.py | from flask.ext.wtf import Form
from wtforms import IntegerField, StringField, FieldList
from wtforms.validators import DataRequired, Email, ValidationError
def word_length(limit=None, message=None):
|
class EditSupplierForm(Form):
description = StringField('Supplier summary', validators=[
word_length(50, 'Your summary must not be more than %d words')
])
clients = FieldList(StringField())
def validate_clients(form, field):
if len(field.data) > 10:
raise ValidationError(... | message = message or 'Must not be more than %d words'
message = message % limit
def _length(form, field):
if not field.data or not limit:
return field
if len(field.data.split()) > limit:
raise ValidationError(message)
return _length | identifier_body |
suppliers.py | from flask.ext.wtf import Form
from wtforms import IntegerField, StringField, FieldList
from wtforms.validators import DataRequired, Email, ValidationError
def | (limit=None, message=None):
message = message or 'Must not be more than %d words'
message = message % limit
def _length(form, field):
if not field.data or not limit:
return field
if len(field.data.split()) > limit:
raise ValidationError(message)
return _length
... | word_length | identifier_name |
suppliers.py | from flask.ext.wtf import Form
from wtforms import IntegerField, StringField, FieldList
from wtforms.validators import DataRequired, Email, ValidationError
def word_length(limit=None, message=None):
message = message or 'Must not be more than %d words'
message = message % limit
def _length(form, field):
... | ])
website = StringField()
phoneNumber = StringField('Phone number')
email = StringField('Email address', validators=[
DataRequired(message="Email can not be empty"),
Email(message="Please enter a valid email address")
])
contactName = StringField('Contact name', validators=[
... | city = StringField('Town or city')
country = StringField()
postcode = StringField(validators=[
DataRequired(message="Postcode can not be empty"), | random_line_split |
army-state.ts | import {List, Record, OrderedMap} from 'immutable';
const MapPositionRecord = Record({
x: 0,
y: 0
});
export class MapPosition extends MapPositionRecord {
x: number;
y: number;
constructor(props:any) {
super(props);
}
}
const ArmyRecord = Record({
id: 0,
pos: undefined,
data: {}
});
export class... |
}
const ArmyStateRecord = Record({
armies: {},
movements: {}
})
export class ArmyState extends ArmyStateRecord {
armies: OrderedMap<number,Army>;
movements: OrderedMap<number,List<Movement>>;
constructor(props:any) {
super(props);
}
}
export const initialArmyState = new ArmyState({});
| {
super(props);
} | identifier_body |
army-state.ts | import {List, Record, OrderedMap} from 'immutable';
const MapPositionRecord = Record({
x: 0,
y: 0
});
export class MapPosition extends MapPositionRecord {
x: number;
y: number;
constructor(props:any) {
super(props);
}
}
const ArmyRecord = Record({
id: 0,
pos: undefined,
data: {}
}); | constructor(props:any) {
super(props);
}
}
const MovementRecord = Record({
id: 0,
armyId: 0,
from: undefined,
to: undefined,
data: {}
})
export class Movement extends MovementRecord {
id: number;
armyId: number;
from: MapPosition;
to: MapPosition;
data: JSON;
constructor(props:any) {
... | export class Army extends ArmyRecord {
id: number;
pos: MapPosition;
data: JSON; | random_line_split |
army-state.ts | import {List, Record, OrderedMap} from 'immutable';
const MapPositionRecord = Record({
x: 0,
y: 0
});
export class MapPosition extends MapPositionRecord {
x: number;
y: number;
constructor(props:any) {
super(props);
}
}
const ArmyRecord = Record({
id: 0,
pos: undefined,
data: {}
});
export class... | (props:any) {
super(props);
}
}
const MovementRecord = Record({
id: 0,
armyId: 0,
from: undefined,
to: undefined,
data: {}
})
export class Movement extends MovementRecord {
id: number;
armyId: number;
from: MapPosition;
to: MapPosition;
data: JSON;
constructor(props:any) {
super(props);... | constructor | identifier_name |
windz.js | $(function () {
var root = this,
viewers = root.viewers || {},
WDZV = (viewers.WDZV = {});
root.viewers = viewers;
var canvas = document.getElementById("map-wdz"),
context = canvas.getContext("2d");
canvas.width = 640;
canvas.height = 512;
var N = Scl.N, M = Scl.M;
| context.clearRect(0, 0, 640, 512);
for (var i = 0; i < N; i++) {
for (var j = 0; j <= M; j++) {
var measure = data.map[i][j],
wdz = measure[8],
fill = "#000000";
if (wdz > 100 || wdz < -100) {
fill =... | WDZV.paint = function (data) { | random_line_split |
windz.js | $(function () {
var root = this,
viewers = root.viewers || {},
WDZV = (viewers.WDZV = {});
root.viewers = viewers;
var canvas = document.getElementById("map-wdz"),
context = canvas.getContext("2d");
canvas.width = 640;
canvas.height = 512;
var N = Scl.N, M = Scl.M;
... |
if (i === 150 && j === 50) {
$("#wdz2").html(wdz);
}
}
}
};
});
| {
$("#wdz1").html(wdz);
} | conditional_block |
dms.js | W). A variety of separators are accepted (eg 3° 37′ 09″W).
* Seconds and minutes may be omitted.
*
* @param {string|number} dmsStr - Degrees or deg/min/sec in variety of formats.
* @returns {number} Degrees as decimal number. | */
Dms.parseDMS = function(dmsStr) {
// check for signed decimal degrees without NSEW, if so return it directly
if (typeof dmsStr == 'number' && isFinite(dmsStr)) return Number(dmsStr);
// strip off any sign or compass dir'n & split out separate d/m/s
var dms = String(dmsStr).trim().replace(/^-/,'').r... | random_line_split | |
styles.js | import { StyleSheet } from "react-native";
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "flex-start",
alignItems: "center",
backgroundColor: "#669999"
},
buttons: {
// flex: 0.15,
flexDirection: "row",
alignItems: "center",... |
export default styles; | random_line_split | |
Input.tsx | import React, { PureComponent, ChangeEvent } from 'react';
import classNames from 'classnames';
import { validate, EventsWithValidation, hasValidationEvent } from '../../../../utils';
import { ValidationEvents, ValidationRule } from '../../../../types';
export enum LegacyInputStatus {
Invalid = 'invalid',
Valid = ... | };
state: State = {
error: null,
};
get status() {
return this.state.error ? LegacyInputStatus.Invalid : LegacyInputStatus.Valid;
}
get isInvalid() {
return this.status === LegacyInputStatus.Invalid;
}
validatorAsync = (validationRules: ValidationRule[]) => {
return (evt: ChangeEvent... |
export class Input extends PureComponent<Props, State> {
static defaultProps = {
className: '', | random_line_split |
Input.tsx | import React, { PureComponent, ChangeEvent } from 'react';
import classNames from 'classnames';
import { validate, EventsWithValidation, hasValidationEvent } from '../../../../utils';
import { ValidationEvents, ValidationRule } from '../../../../types';
export enum LegacyInputStatus {
Invalid = 'invalid',
Valid = ... |
};
}
});
return inputElementProps;
};
render() {
const { validationEvents, className, hideErrorMessage, inputRef, ...restProps } = this.props;
const { error } = this.state;
const inputClassName = classNames('gf-form-input', { invalid: this.isInvalid }, className);
const input... | {
restProps[eventName].apply(null, [evt, this.status]);
} | conditional_block |
Input.tsx | import React, { PureComponent, ChangeEvent } from 'react';
import classNames from 'classnames';
import { validate, EventsWithValidation, hasValidationEvent } from '../../../../utils';
import { ValidationEvents, ValidationRule } from '../../../../types';
export enum LegacyInputStatus {
Invalid = 'invalid',
Valid = ... | () {
return this.state.error ? LegacyInputStatus.Invalid : LegacyInputStatus.Valid;
}
get isInvalid() {
return this.status === LegacyInputStatus.Invalid;
}
validatorAsync = (validationRules: ValidationRule[]) => {
return (evt: ChangeEvent<HTMLInputElement>) => {
const errors = validate(evt.t... | status | identifier_name |
Input.tsx | import React, { PureComponent, ChangeEvent } from 'react';
import classNames from 'classnames';
import { validate, EventsWithValidation, hasValidationEvent } from '../../../../utils';
import { ValidationEvents, ValidationRule } from '../../../../types';
export enum LegacyInputStatus {
Invalid = 'invalid',
Valid = ... |
get isInvalid() {
return this.status === LegacyInputStatus.Invalid;
}
validatorAsync = (validationRules: ValidationRule[]) => {
return (evt: ChangeEvent<HTMLInputElement>) => {
const errors = validate(evt.target.value, validationRules);
this.setState((prevState) => {
return { ...pre... | {
return this.state.error ? LegacyInputStatus.Invalid : LegacyInputStatus.Valid;
} | identifier_body |
jmethodid.rs | use std::marker::PhantomData;
use sys::jmethodID;
/// Wrapper around `sys::jmethodid` that adds a lifetime. This prevents it from
/// outliving the context in which it was acquired and getting GC'd out from
/// under us. It matches C's representation of the raw pointer, so it can be
/// used in any of the extern func... |
impl<'a> JMethodID<'a> {
/// Unwrap to the internal jni type.
pub fn into_inner(self) -> jmethodID {
self.internal
}
} | }
}
} | random_line_split |
jmethodid.rs | use std::marker::PhantomData;
use sys::jmethodID;
/// Wrapper around `sys::jmethodid` that adds a lifetime. This prevents it from
/// outliving the context in which it was acquired and getting GC'd out from
/// under us. It matches C's representation of the raw pointer, so it can be
/// used in any of the extern func... | (self) -> jmethodID {
self.internal
}
}
| into_inner | identifier_name |
jmethodid.rs | use std::marker::PhantomData;
use sys::jmethodID;
/// Wrapper around `sys::jmethodid` that adds a lifetime. This prevents it from
/// outliving the context in which it was acquired and getting GC'd out from
/// under us. It matches C's representation of the raw pointer, so it can be
/// used in any of the extern func... |
}
| {
self.internal
} | identifier_body |
plot_stats_cluster_spatio_temporal_repeated_measures_anova.py | numpy.random import randn
import matplotlib.pyplot as plt
import mne
from mne import (io, spatial_tris_connectivity, compute_morph_matrix,
grade_to_tris)
from mne.stats import (spatio_temporal_cluster_test, f_threshold_mway_rm,
f_mway_rm, summarize_clusters_stc)
from mne.minim... |
tmin = conditions[0].tmin
tstep = conditions[0].tstep
###############################################################################
# Transform to common cortical space
# ----------------------------------
#
# Normally you would read in estimates across several subjects and morph them
# to the same cortical space ... | evoked = epochs[cond].average()
evoked.resample(50, npad='auto')
condition = apply_inverse(evoked, inverse_operator, lambda2, method)
# Let's only deal with t > 0, cropping to reduce multiple comparisons
condition.crop(0, None)
conditions.append(condition) | conditional_block |
plot_stats_cluster_spatio_temporal_repeated_measures_anova.py | numpy.random import randn
import matplotlib.pyplot as plt
import mne
from mne import (io, spatial_tris_connectivity, compute_morph_matrix,
grade_to_tris)
from mne.stats import (spatio_temporal_cluster_test, f_threshold_mway_rm,
f_mway_rm, summarize_clusters_stc)
from mne.minim... | (*args):
return f_mway_rm(np.swapaxes(args, 1, 0), factor_levels=factor_levels,
effects=effects, return_pvals=return_pvals)[0]
# get f-values only.
###############################################################################
# Compute clustering statistic
# ----------------------------
... | stat_fun | identifier_name |
plot_stats_cluster_spatio_temporal_repeated_measures_anova.py | numpy.random import randn
import matplotlib.pyplot as plt
import mne
from mne import (io, spatial_tris_connectivity, compute_morph_matrix,
grade_to_tris)
from mne.stats import (spatio_temporal_cluster_test, f_threshold_mway_rm,
f_mway_rm, summarize_clusters_stc)
from mne.minim... |
###############################################################################
# Compute clustering statistic
# ----------------------------
#
# To use an algorithm optimized for spatio-temporal clustering, we
# just pass the spatial connectivity matrix (instead of spatio-temporal).
source_space = grade_to_tris(5)
... | return f_mway_rm(np.swapaxes(args, 1, 0), factor_levels=factor_levels,
effects=effects, return_pvals=return_pvals)[0]
# get f-values only. | identifier_body |
plot_stats_cluster_spatio_temporal_repeated_measures_anova.py | import os.path as op
import numpy as np
from numpy.random import randn
import matplotlib.pyplot as plt
import mne
from mne import (io, spatial_tris_connectivity, compute_morph_matrix,
grade_to_tris)
from mne.stats import (spatio_temporal_cluster_test, f_threshold_mway_rm,
f_mway... | #
# License: BSD (3-clause)
| random_line_split | |
error.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 std::error;
use std::fmt;
use svgdom;
/// List of all errors.
#[derive(Debug)]
pub enum | {
/// Only `svg` and `svgz` suffixes are supported.
InvalidFileSuffix,
/// Failed to open the provided file.
FileOpenFailed,
/// Only UTF-8 content are supported.
NotAnUtf8Str,
/// Compressed SVG must use the GZip algorithm.
MalformedGZip,
/// SVG doesn't have a valid size.
... | Error | identifier_name |
error.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 std::error;
use std::fmt;
use svgdom;
/// List of all errors.
#[derive(Debug)]
pub enum Error {
/// Only `s... |
Error::FileOpenFailed => {
write!(f, "failed to open the provided file")
}
Error::NotAnUtf8Str => {
write!(f, "provided data has not an UTF-8 encoding")
}
Error::MalformedGZip => {
write!(f, "provided data has a... | {
write!(f, "invalid file suffix")
} | conditional_block |
error.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 std::error;
use std::fmt;
use svgdom;
/// List of all errors.
#[derive(Debug)]
pub enum Error {
/// Only `s... | /// Failed to open the provided file.
FileOpenFailed,
/// Only UTF-8 content are supported.
NotAnUtf8Str,
/// Compressed SVG must use the GZip algorithm.
MalformedGZip,
/// SVG doesn't have a valid size.
///
/// Occurs when width and/or height are <= 0.
///
/// Also occurs... | random_line_split | |
mod.rs | use serde::{Deserialize, Serialize};
use std::error::Error;
use std::fs::File;
use std::path::Path;
#[derive(Serialize, Deserialize)]
pub struct Database {
pub repository: String,
}
#[derive(Serialize, Deserialize)]
pub struct | {
pub port: u16,
pub address: String,
pub hostname: String,
}
#[derive(Serialize, Deserialize)]
pub struct Display {
pub width: u32,
pub height: u32,
}
#[derive(Serialize, Deserialize)]
pub struct Poetry {
pub font: String,
pub speed: f32,
}
#[derive(Serialize, Deserialize)]
pub struct E... | Server | identifier_name |
mod.rs | use serde::{Deserialize, Serialize};
use std::error::Error;
use std::fs::File;
use std::path::Path;
#[derive(Serialize, Deserialize)]
pub struct Database {
pub repository: String,
}
#[derive(Serialize, Deserialize)]
pub struct Server {
pub port: u16,
pub address: String,
pub hostname: String,
}
#[der... | #[derive(Serialize, Deserialize, Clone)]
pub struct Mqtt {
pub server: String,
pub port: Option<u16>,
pub username: Option<String>,
pub password: Option<String>,
pub topic: String,
}
fn default_fps() -> u32 {
60
}
#[derive(Serialize, Deserialize)]
pub struct Config {
pub logconfig: String,... | #[serde(default = "default_fps")]
pub fps: u32,
}
| random_line_split |
test_randomcolor_visual.py | import randomcolor
import random
def main():
hues = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink',
'monochrome', 'random']
luminosities = ['bright', 'light', 'dark', 'random']
formats = ['rgb', 'hex']
colors = []
rand_color = randomcolor.RandomColor(42)
rand = ra... | <style>
.color {
height: 30px;
width: 30px;
border-radius: 30px;
display: inline-block;
}
</style>
</head>
<body>
<div class="container">
<div class="row col-md-10 col-md-offset-1">
<h1>Random Color Test</h1>
<table class="table">
%s
</tab... | <title>randomcolor test</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"> | random_line_split |
test_randomcolor_visual.py | import randomcolor
import random
def | ():
hues = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink',
'monochrome', 'random']
luminosities = ['bright', 'light', 'dark', 'random']
formats = ['rgb', 'hex']
colors = []
rand_color = randomcolor.RandomColor(42)
rand = random.Random(42)
rand_int = lambda: rand... | main | identifier_name |
test_randomcolor_visual.py | import randomcolor
import random
def main():
hues = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink',
'monochrome', 'random']
luminosities = ['bright', 'light', 'dark', 'random']
formats = ['rgb', 'hex']
colors = []
rand_color = randomcolor.RandomColor(42)
rand = ra... | <table class="table">
%s
</table>
</div>
</body>
</html>
""" % table_rows
if __name__ == "__main__":
main()
| return """
<!DOCTYPE html>
<html lang="en">
<head>
<title>randomcolor test</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<style>
.color {
height: 30px;
width: 30px;
border-radius: 30px;
display: inline-blo... | identifier_body |
test_randomcolor_visual.py | import randomcolor
import random
def main():
hues = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink',
'monochrome', 'random']
luminosities = ['bright', 'light', 'dark', 'random']
formats = ['rgb', 'hex']
colors = []
rand_color = randomcolor.RandomColor(42)
rand = ra... |
return s
def generate_html(table_rows):
return """
<!DOCTYPE html>
<html lang="en">
<head>
<title>randomcolor test</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<style>
.color {
height: 30px;
width: 30px;
... | s += "<tr>"
s += "<td>%s</td>" % (color_name)
s += "<td>"
for color in colors:
s += "<div class='color' style='background-color:%s'></div>" % color
s += "</td>"
s += "</tr>" | conditional_block |
constants.rs | /// π <https://oeis.org/A000796>
pub const PI: f64 =
3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214;
/// sqrt(2) <https://oeis.org/A002193>
pub const SQRT_2: f64 =
1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503... | pub const SQRT_2_BY_3: f64 =
0.816496580927726032732428024901963797321982493552223376144230855750320125819105008846619811034880078272864f64;
/// sqt(3/2) <https://oeis.org/A115754>
pub const SQRT_3_BY_2: f64 =
1.22474487139158904909864203735294569598297374032833506421634628362548018872865751326992971655232011f... | pub const SQRT_6: f64 =
2.44948974278317809819728407470589139196594748065667012843269256725096037745731502653985943310464023f64;
/// sqrt(2/3) <https://oeis.org/A157697> | random_line_split |
index.ts | import type { Quarter } from '../../../../types'
import type { Match } from '../../../types'
import buildMatchFn from '../../../_lib/buildMatchFn/index'
import buildMatchPatternFn from '../../../_lib/buildMatchPatternFn/index'
const matchOrdinalNumberPattern = /^(\d+)\.?/i
const parseOrdinalNumberPattern = /\d+/i
con... | defaultParseWidth: 'any',
}),
quarter: buildMatchFn({
matchPatterns: matchQuarterPatterns,
defaultMatchWidth: 'wide',
parsePatterns: parseQuarterPatterns,
defaultParseWidth: 'any',
valueCallback: (index) => (index + 1) as Quarter,
}),
month: buildMatchFn({
matchPatterns: matchMonth... | parsePatterns: parseEraPatterns, | random_line_split |
melfilterbank.py | import os, sys
dirname = os.path.dirname(__file__)
lib_path = os.path.join(dirname, "python_speech_features")
sys.path.append(lib_path)
import features as speechfeatures
import numpy as np
def filter(samplerate, signal, winlen=0.02, winstep=0.01,
nfilt=40, nfft=512, lowfreq=100, highfreq=5000, preemph=0.9... | (samplerate, signal, *args, **kwargs):
"""extracts log mel filterbank energies from a given signal
Args:
samplerate (int): samples taken per second
signal(1d numpy array): sample values
*args: piped through to filter
**kwargs: piped thought to filter
Returns:
feat(2d numpy array): logarithm ... | logfilter | identifier_name |
melfilterbank.py | import os, sys
dirname = os.path.dirname(__file__)
lib_path = os.path.join(dirname, "python_speech_features")
sys.path.append(lib_path)
import features as speechfeatures
import numpy as np
def filter(samplerate, signal, winlen=0.02, winstep=0.01,
nfilt=40, nfft=512, lowfreq=100, highfreq=5000, preemph=0.9... | """extracts log mel filterbank energies from a given signal
Args:
samplerate (int): samples taken per second
signal(1d numpy array): sample values
*args: piped through to filter
**kwargs: piped thought to filter
Returns:
feat(2d numpy array): logarithm of filterbank energies
"""
feat = fi... | identifier_body | |
melfilterbank.py | import os, sys
dirname = os.path.dirname(__file__)
lib_path = os.path.join(dirname, "python_speech_features")
sys.path.append(lib_path)
import features as speechfeatures
import numpy as np
def filter(samplerate, signal, winlen=0.02, winstep=0.01,
nfilt=40, nfft=512, lowfreq=100, highfreq=5000, preemph=0.9... | Args:
samplerate (int): samples taken per second
signal(1d numpy array): sample values
*args: piped through to filter
**kwargs: piped thought to filter
Returns:
feat(2d numpy array): logarithm of filterbank energies
"""
feat = filter(samplerate, signal, *args, **kwargs)
return np.log(fea... | def logfilter(samplerate, signal, *args, **kwargs):
"""extracts log mel filterbank energies from a given signal
| random_line_split |
app.ts | () {
return 'tab-search-app';
}
static get properties() {
return {
searchText_: {
type: String,
value: '',
},
availableHeight_: Number,
filteredItems_: {
type: Array,
value: [],
},
/**
* Options for fuzzy search. Controls how hea... | is | identifier_name | |
app.ts | State === 'visible') {
this.windowShownTimestamp_ = Date.now();
this.updateTabs_();
} else {
this.onDocumentHidden_();
}
};
this.mediaTabsTitleItem_ =
new TitleItem(loadTimeData.getString('mediaTabs'));
this.openTabsTitleItem_ = new TitleItem(loadTimeData.getStr... |
private recordMetricsForAction(
action: string, isMediaTab: boolean, tabIndex: number,
indexRelativeToSection: number,
distanceFromInitiallySelectedIndex: number) {
const withSearch = !!this.searchText_;
if (action === 'SwitchTab') {
chrome.metricsPrivate.recordEnumerationValue(
... | {
const tabItem = e.model.item;
this.tabItemAction_(tabItem, e.model.index);
} | identifier_body |
app.ts | State === 'visible') {
this.windowShownTimestamp_ = Date.now();
this.updateTabs_();
} else {
this.onDocumentHidden_();
}
};
this.mediaTabsTitleItem_ =
new TitleItem(loadTimeData.getString('mediaTabs'));
this.openTabsTitleItem_ = new TitleItem(loadTimeData.getStr... |
}
// If the updated tab's id is not found in the existing open tabs, add it
// to the list.
this.openTabs_.push(tabData);
this.updateFilteredTabs_();
}
private onTabsRemoved_(tabsRemovedInfo: TabsRemovedInfo) {
if (this.openTabs_.length === 0) {
return;
}
const ids = new Se... | {
this.openTabs_[i] = tabData;
this.updateFilteredTabs_();
return;
} | conditional_block |
app.ts | ));
// The infinite-list produces viewport-filled events whenever a data or
// scroll position change triggers the the viewport fill logic.
listenOnce(this.$.tabsList, 'viewport-filled', () => {
// Push showUI() to the event loop to allow reflow to occur following
// the DOM update.
... | });
this.recentlyClosedTitleItem_.expanded = | random_line_split | |
switch.py | """Allows to configure a switch using RPi GPIO."""
import logging
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA
from homeassistant.components import rpi_gpio
from homeassistant.const import DEVICE_DEFAULT_NAME
from homeassistant.helpers.entity import ToggleEntity
import homeassi... |
add_entities(switches)
class RPiGPIOSwitch(ToggleEntity):
"""Representation of a Raspberry Pi GPIO."""
def __init__(self, name, port, invert_logic):
"""Initialize the pin."""
self._name = name or DEVICE_DEFAULT_NAME
self._port = port
self._invert_logic = invert_logic
... | switches.append(RPiGPIOSwitch(name, port, invert_logic)) | conditional_block |
switch.py | """Allows to configure a switch using RPi GPIO."""
import logging
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA
from homeassistant.components import rpi_gpio
from homeassistant.const import DEVICE_DEFAULT_NAME
from homeassistant.helpers.entity import ToggleEntity
import homeassi... | (hass, config, add_entities, discovery_info=None):
"""Set up the Raspberry PI GPIO devices."""
invert_logic = config.get(CONF_INVERT_LOGIC)
switches = []
ports = config.get(CONF_PORTS)
for port, name in ports.items():
switches.append(RPiGPIOSwitch(name, port, invert_logic))
add_entities... | setup_platform | identifier_name |
switch.py | """Allows to configure a switch using RPi GPIO."""
import logging
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA
from homeassistant.components import rpi_gpio
from homeassistant.const import DEVICE_DEFAULT_NAME
from homeassistant.helpers.entity import ToggleEntity
import homeassi... |
@property
def should_poll(self):
"""No polling needed."""
return False
@property
def is_on(self):
"""Return true if device is on."""
return self._state
def turn_on(self, **kwargs):
"""Turn the device on."""
rpi_gpio.write_output(self._port, 0 if se... | """Return the name of the switch."""
return self._name | identifier_body |
switch.py | """Allows to configure a switch using RPi GPIO."""
import logging
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA
from homeassistant.components import rpi_gpio
from homeassistant.const import DEVICE_DEFAULT_NAME
from homeassistant.helpers.entity import ToggleEntity
import homeassi... |
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def should_poll(self):
"""No polling needed."""
return False
@property
def is_on(self):
"""Return true if device is on."""
return self._state
def tur... | self._state = False
rpi_gpio.setup_output(self._port)
rpi_gpio.write_output(self._port, 1 if self._invert_logic else 0) | random_line_split |
app.module.ts | import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { BlockUIModule } from 'ng-block-ui';
import { BsDropdownModule } ... | }),
BlockUIModule,
BsDropdownModule.forRoot(),
ToolsModule
],
providers: [
MainConfigService
],
bootstrap: [
AppComponent
]
})
export class AppModule { } | enableTracing: false | random_line_split |
app.module.ts | import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { BlockUIModule } from 'ng-block-ui';
import { BsDropdownModule } ... | { }
| AppModule | identifier_name |
App.js | import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import config from '../../config';
import { connect } from 'react-redux';
import { logout, loadAuthCookie, loadPersonalInfo } from 'redux/modules/auth';
import { load as loadGenre } from 'redux/modules/genre';
import { loadCartInf... | };
componentWillMount() {
// Load overall informations.
this.props.loadGenre();
// Authentication
this.props.loadAuthCookie();
if (this.props.logged) {
this.props.loadPersonalInfo();
this.props.loadCartInformations();
this.props.loadCartEntries();
}
}
componentDidMoun... | store: PropTypes.object.isRequired | random_line_split |
App.js | import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import config from '../../config';
import { connect } from 'react-redux';
import { logout, loadAuthCookie, loadPersonalInfo } from 'redux/modules/auth';
import { load as loadGenre } from 'redux/modules/genre';
import { loadCartInf... | () {
ga.initialize('UA-41334661-1', { debug: true });
ga.pageview(this.props.location.pathname);
}
componentWillReceiveProps(nextProps) {
const isLogged = this.props.logged;
const nextStateIsLogged = nextProps.logged;
if (isLogged === false && nextStateIsLogged === true) {
// I just got l... | componentDidMount | identifier_name |
App.js | import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import config from '../../config';
import { connect } from 'react-redux';
import { logout, loadAuthCookie, loadPersonalInfo } from 'redux/modules/auth';
import { load as loadGenre } from 'redux/modules/genre';
import { loadCartInf... |
}
handleLogout = (event) => {
event.preventDefault();
this.props.logout();
};
render() {
const {user, logged, genres, totalBasketItems} = this.props;
const styles = require('./less/aphextwin.less');
return (
<div className={styles}>
<Helmet {...config.app.head}/>
<nav cl... | {
ga.pageview(nextProps.location.pathname);
} | conditional_block |
contourAnimation.py | import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
# from sympy import *
from src import jeffery_model as jm
DoubleletStrength = np.array((1, 0, 0))
alpha = 1
B = np.array((0, 1, 0))
lbd = (alpha ** 2 - 1) / (alpha ** 2 + 1)
x, y = np.meshgrid(np.linspace(-1, 1, 100), np.linspa... | (i):
zi = (1 + i) / length * 2
for tp in p[0].collections:
tp.remove()
p[0] = ax.contourf(x, y, np.log10(fun(zi)))
return p[0].collections
ani = animation.FuncAnimation(fig, update, frames=length,
interval=5, blit=True, repeat=True)
# plt.show()
Writer = animatio... | update | identifier_name |
contourAnimation.py | import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
# from sympy import *
from src import jeffery_model as jm
DoubleletStrength = np.array((1, 0, 0))
alpha = 1
B = np.array((0, 1, 0))
lbd = (alpha ** 2 - 1) / (alpha ** 2 + 1)
x, y = np.meshgrid(np.linspace(-1, 1, 100), np.linspa... |
ani = animation.FuncAnimation(fig, update, frames=length,
interval=5, blit=True, repeat=True)
# plt.show()
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=600)
ani.save('t2.mp4', writer=writer)
print('111')
| zi = (1 + i) / length * 2
for tp in p[0].collections:
tp.remove()
p[0] = ax.contourf(x, y, np.log10(fun(zi)))
return p[0].collections | identifier_body |
contourAnimation.py | import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
# from sympy import *
from src import jeffery_model as jm
DoubleletStrength = np.array((1, 0, 0))
alpha = 1
B = np.array((0, 1, 0)) | x, y = np.meshgrid(np.linspace(-1, 1, 100), np.linspace(-1, 1, 100))
problem = jm.SingleDoubleletJefferyProblem(B=B, DoubleletStrength=DoubleletStrength)
length = 200
def fun(zi):
location = np.vstack((x.flatten(), y.flatten(), np.ones_like(y.flatten()) * zi))
Jij = problem.J_matrix(location)
JijT = Jij.t... | lbd = (alpha ** 2 - 1) / (alpha ** 2 + 1) | random_line_split |
contourAnimation.py | import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
# from sympy import *
from src import jeffery_model as jm
DoubleletStrength = np.array((1, 0, 0))
alpha = 1
B = np.array((0, 1, 0))
lbd = (alpha ** 2 - 1) / (alpha ** 2 + 1)
x, y = np.meshgrid(np.linspace(-1, 1, 100), np.linspa... |
p[0] = ax.contourf(x, y, np.log10(fun(zi)))
return p[0].collections
ani = animation.FuncAnimation(fig, update, frames=length,
interval=5, blit=True, repeat=True)
# plt.show()
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=600)
a... | tp.remove() | conditional_block |
passport-facebook-token-tests.ts | import * as express from 'express';
import * as passport from 'passport';
import PassportFacebookToken = require('passport-facebook-token');
const User = {
findOrCreate(id: string, provider: string, callback: (err: any, user: any) => void): void |
};
const options: PassportFacebookToken.StrategyOptions = {
clientID: 'TEST_CLIENT_ID',
clientSecret: 'TEST_CLIENT_SECRET'
};
const optionsWithFbGraphVersion: PassportFacebookToken.StrategyOptions = {
clientID: 'TEST_CLIENT_ID',
clientSecret: 'TEST_CLIENT_SECRET',
fbGraphVersion: 'v3'
};
const o... | {
callback(null, { username: 'ray' });
} | identifier_body |
passport-facebook-token-tests.ts | import * as express from 'express';
import * as passport from 'passport';
import PassportFacebookToken = require('passport-facebook-token');
const User = {
findOrCreate(id: string, provider: string, callback: (err: any, user: any) => void): void {
callback(null, { username: 'ray' });
}
};
const option... | const optionsWithFbGraphVersion: PassportFacebookToken.StrategyOptions = {
clientID: 'TEST_CLIENT_ID',
clientSecret: 'TEST_CLIENT_SECRET',
fbGraphVersion: 'v3'
};
const optionsWithRequest: PassportFacebookToken.StrategyOptionsWithRequest = {
clientID: 'TEST_CLIENT_ID',
clientSecret: 'TEST_CLIENT_SE... | clientID: 'TEST_CLIENT_ID',
clientSecret: 'TEST_CLIENT_SECRET'
};
| random_line_split |
passport-facebook-token-tests.ts | import * as express from 'express';
import * as passport from 'passport';
import PassportFacebookToken = require('passport-facebook-token');
const User = {
findOrCreate(id: string, provider: string, callback: (err: any, user: any) => void): void {
callback(null, { username: 'ray' });
}
};
const option... |
done(null, user);
});
};
passport.use(new PassportFacebookToken(options, verify));
passport.use(new PassportFacebookToken(optionsWithFbGraphVersion, verify));
passport.use(new PassportFacebookToken(optionsWithRequest, verifyWithRequest));
| {
done(err);
} | conditional_block |
passport-facebook-token-tests.ts | import * as express from 'express';
import * as passport from 'passport';
import PassportFacebookToken = require('passport-facebook-token');
const User = {
| (id: string, provider: string, callback: (err: any, user: any) => void): void {
callback(null, { username: 'ray' });
}
};
const options: PassportFacebookToken.StrategyOptions = {
clientID: 'TEST_CLIENT_ID',
clientSecret: 'TEST_CLIENT_SECRET'
};
const optionsWithFbGraphVersion: PassportFacebookToke... | findOrCreate | identifier_name |
test.py | from cStringIO import StringIO
from datetime import datetime
from unidecode import unidecode
from handler import Patobj, PatentHandler
import re
import uuid
import xml.sax
import xml_util
import xml_driver
xml_string = 'ipg050104.xml'
| l = xml.sax.xmlreader.Locator()
xh.setDocumentLocator(l)
#parser.parse(StringIO(xml_string))
parser.parse(xml_string)
print "parsing done"
#print type(xh.root.us_bibliographic_data_grant.publication_reference.contents_of('document_id', '', as_string=False))
print xh.root.claims.contents_of('claim', '', as_string=True... | xh = xml_driver.XMLHandler()
parser = xml_driver.make_parser()
parser.setContentHandler(xh)
parser.setFeature(xml_driver.handler.feature_external_ges, False)
| random_line_split |
bulk_test.py | # -*- coding: utf-8; -*-
#
# Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. Crate licenses
# this file to you under the Apache License, Version 2.0 (the "License"... |
fake_cursor.description = ()
fake_cursor.rowcount = len(chars)
fake_cursor.executemany.return_value = [
{'rowcount': 1},
{'rowcount': 1},
{'rowcount': 1},
]
self.session.bulk_save_objects(chars)
(stmt, bulk_args), _kwargs = fake_cursor... | def setUp(self):
self.engine = sa.create_engine('crate://')
Base = declarative_base(bind=self.engine)
class Character(Base):
__tablename__ = 'characters'
name = sa.Column(sa.String, primary_key=True)
age = sa.Column(sa.Integer)
self.character = Char... | identifier_body |
bulk_test.py | # -*- coding: utf-8; -*-
#
# Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. Crate licenses
# this file to you under the Apache License, Version 2.0 (the "License"... | # However, if you have executed another commercial license agreement
# with Crate these terms will supersede the license and you may use the
# software solely pursuant to the terms of the relevant commercial agreement.
from unittest import TestCase
from unittest.mock import patch, MagicMock
import sqlalchemy as sa
fr... | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
# | random_line_split |
bulk_test.py | # -*- coding: utf-8; -*-
#
# Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. Crate licenses
# this file to you under the Apache License, Version 2.0 (the "License"... | (TestCase):
def setUp(self):
self.engine = sa.create_engine('crate://')
Base = declarative_base(bind=self.engine)
class Character(Base):
__tablename__ = 'characters'
name = sa.Column(sa.String, primary_key=True)
age = sa.Column(sa.Integer)
self... | SqlAlchemyBulkTest | identifier_name |
shuffle_split.rs | //! Validation via repeated random shuffling
//! of the data and splitting into a training and test set.
//!
//! # Examples
//!
//! ```
//! use rustlearn::prelude::*;
//! use rustlearn::datasets::iris;
//! use rustlearn::cross_validation::ShuffleSplit;
//!
//!
//! let (X, y) = iris::load_data();
//!
//! let num_splits ... | else {
None
};
self.iter += 1;
ret
}
}
#[cfg(test)]
mod tests {
use super::*;
extern crate rand;
use rand::{SeedableRng, StdRng};
#[test]
fn iteration() {
let split = ShuffleSplit::new(100, 4, 0.2);
let mut count = 0;
for _ in s... | {
let split_idx: usize = (self.n as f32 * (1.0 - self.test_size)).floor() as usize;
let shuffled_indices = self.get_shuffled_indices();
let (train, test) = shuffled_indices.split_at(split_idx);
Some((train.to_owned(), test.to_owned()))
} | conditional_block |
shuffle_split.rs | //! Validation via repeated random shuffling
//! of the data and splitting into a training and test set.
//!
//! # Examples
//!
//! ```
//! use rustlearn::prelude::*;
//! use rustlearn::datasets::iris;
//! use rustlearn::cross_validation::ShuffleSplit;
//!
//!
//! let (X, y) = iris::load_data();
//!
//! let num_splits ... | let set2 = split2.collect::<Vec<_>>();
assert!(set1[0].0 == set2[0].0);
}
} | let set1 = split1.collect::<Vec<_>>(); | random_line_split |
shuffle_split.rs | //! Validation via repeated random shuffling
//! of the data and splitting into a training and test set.
//!
//! # Examples
//!
//! ```
//! use rustlearn::prelude::*;
//! use rustlearn::datasets::iris;
//! use rustlearn::cross_validation::ShuffleSplit;
//!
//!
//! let (X, y) = iris::load_data();
//!
//! let num_splits ... | (&mut self) -> Option<(Vec<usize>, Vec<usize>)> {
let ret = if self.iter < self.n_iter {
let split_idx: usize = (self.n as f32 * (1.0 - self.test_size)).floor() as usize;
let shuffled_indices = self.get_shuffled_indices();
let (train, test) = shuffled_indices.split_at(split_... | next | identifier_name |
shuffle_split.rs | //! Validation via repeated random shuffling
//! of the data and splitting into a training and test set.
//!
//! # Examples
//!
//! ```
//! use rustlearn::prelude::*;
//! use rustlearn::datasets::iris;
//! use rustlearn::cross_validation::ShuffleSplit;
//!
//!
//! let (X, y) = iris::load_data();
//!
//! let num_splits ... |
fn get_shuffled_indices(&mut self) -> Vec<usize> {
let mut indices = (0..self.n).collect::<Vec<usize>>();
self.rng.shuffle(&mut indices);
indices
}
}
impl Iterator for ShuffleSplit {
type Item = (Vec<usize>, Vec<usize>);
fn next(&mut self) -> Option<(Vec<usize>, Vec<usize>)>... | {
self.rng = rng;
} | identifier_body |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | (self, spec, prefix):
configure('--prefix={0}'.format(prefix))
make()
make('install')
# `make install` copies the files to the font-util installation.
# Create a fake directory to convince Spack that we actually
# installed something.
mkdir(prefix.lib)
| install | identifier_name |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class FontIsasMisc(Package):
"""X.org isas-misc font."""
homepage = "http://cgit.freedesktop.org/xorg/font/isas-misc"
url = "ht... | # You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software | random_line_split |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... |
# `make install` copies the files to the font-util installation.
# Create a fake directory to convince Spack that we actually
# installed something.
mkdir(prefix.lib)
| """X.org isas-misc font."""
homepage = "http://cgit.freedesktop.org/xorg/font/isas-misc"
url = "https://www.x.org/archive/individual/font/font-isas-misc-1.0.3.tar.gz"
version('1.0.3', 'ecc3b6fbe8f5721ddf5c7fc66f73e76f')
depends_on('font-util')
depends_on('fontconfig', type='build')
depe... | identifier_body |
disk.py | import os
from pi3bar.plugins.base import Plugin
from pi3bar.utils import humanize_size_bytes
class Disk(Plugin):
"""
:class:`pi3bar.app.Pi3Bar` plugin to disk usage.
Available format replacements (``*_p`` = percentage):
* ``%(size)s`` E.g. '100GB'
* ``%(free)s`` E.g. '70GB'
* ``%(free_p)f``... |
size_bytes = statvfs.f_frsize * statvfs.f_blocks
free_bytes = statvfs.f_frsize * statvfs.f_bfree # with reserved space
free_percent = 100.0 / size_bytes * free_bytes
available_bytes = statvfs.f_frsize * statvfs.f_bavail # without reserved space
available_percent = 100.0 / si... |
def get_stats(self):
statvfs = os.statvfs(self.mount_path) | random_line_split |
disk.py | import os
from pi3bar.plugins.base import Plugin
from pi3bar.utils import humanize_size_bytes
class Disk(Plugin):
"""
:class:`pi3bar.app.Pi3Bar` plugin to disk usage.
Available format replacements (``*_p`` = percentage):
* ``%(size)s`` E.g. '100GB'
* ``%(free)s`` E.g. '70GB'
* ``%(free_p)f``... |
elif float(stats['usage_p']) > self.warning_usage:
self.color = self.warning_color
self.background = self.warning_background
else:
self.color = None
self.background = None
| self.color = self.critical_color
self.background = self.critical_background | conditional_block |
disk.py | import os
from pi3bar.plugins.base import Plugin
from pi3bar.utils import humanize_size_bytes
class Disk(Plugin):
"""
:class:`pi3bar.app.Pi3Bar` plugin to disk usage.
Available format replacements (``*_p`` = percentage):
* ``%(size)s`` E.g. '100GB'
* ``%(free)s`` E.g. '70GB'
* ``%(free_p)f``... |
def get_stats(self):
statvfs = os.statvfs(self.mount_path)
size_bytes = statvfs.f_frsize * statvfs.f_blocks
free_bytes = statvfs.f_frsize * statvfs.f_bfree # with reserved space
free_percent = 100.0 / size_bytes * free_bytes
available_bytes = statvfs.f_frsize * statvfs.... | self.instance = mount_path
self.mount_path = mount_path
self.full_format = kwargs.pop('full_format', '%(usage_p).2f%% (%(size)s)')
self.short_format = kwargs.pop('short_format', '%(usage_p).2f%%')
self.warning_usage = kwargs.pop('warning_usage', 90)
self.warning_color = kwargs.... | identifier_body |
disk.py | import os
from pi3bar.plugins.base import Plugin
from pi3bar.utils import humanize_size_bytes
class Disk(Plugin):
"""
:class:`pi3bar.app.Pi3Bar` plugin to disk usage.
Available format replacements (``*_p`` = percentage):
* ``%(size)s`` E.g. '100GB'
* ``%(free)s`` E.g. '70GB'
* ``%(free_p)f``... | (self):
stats = self.get_stats()
prefix = '%s ' % self.mount_path
self.full_text = prefix + self.full_format % stats
self.short_text = prefix + self.short_format % stats
if float(stats['usage_p']) > self.critical_usage:
self.color = self.critical_color
se... | cycle | identifier_name |
ESipHeaderIgnore.py | # Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved.
# Copyright (c) 2006-2007 Sippy Software, Inc. All rights reserved.
#
# This file is part of SIPPY, a free RFC3261 SIP stack and B2BUA.
#
# SIPPY is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License a... | (self):
Exception.__init__(self)
| __init__ | identifier_name |
ESipHeaderIgnore.py | # Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved.
# Copyright (c) 2006-2007 Sippy Software, Inc. All rights reserved.
#
# This file is part of SIPPY, a free RFC3261 SIP stack and B2BUA.
#
# SIPPY is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License a... | #
# SIPPY 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.
#
# You should have received a copy of the GNU General Public License
# along with ... | random_line_split | |
ESipHeaderIgnore.py | # Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved.
# Copyright (c) 2006-2007 Sippy Software, Inc. All rights reserved.
#
# This file is part of SIPPY, a free RFC3261 SIP stack and B2BUA.
#
# SIPPY is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License a... | def __init__(self):
Exception.__init__(self) | identifier_body | |
sieve.rs | extern crate sieve;
use sieve::*;
#[test]
fn limit_lower_than_the_first_prime() {
assert_eq!(sieve::primes_up_to(1), []);
}
#[test]
fn limit_is_the_first_prime() {
assert_eq!(sieve::primes_up_to(2), [2]);
}
#[test]
fn primes_up_to_10() {
assert_eq!(sieve::primes_up_to(10), [2, 3, 5, 7]);
}
#[test]
fn ... | () {
let expected = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,
71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149,
151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
... | limit_of_1000 | identifier_name |
sieve.rs | extern crate sieve;
use sieve::*;
#[test]
fn limit_lower_than_the_first_prime() {
assert_eq!(sieve::primes_up_to(1), []);
}
#[test]
fn limit_is_the_first_prime() {
assert_eq!(sieve::primes_up_to(2), [2]);
}
| fn primes_up_to_10() {
assert_eq!(sieve::primes_up_to(10), [2, 3, 5, 7]);
}
#[test]
fn limit_is_prime() {
assert_eq!(sieve::primes_up_to(13), [2, 3, 5, 7, 11, 13]);
}
#[test]
fn limit_of_1000() {
let expected = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,
... | #[test] | random_line_split |
sieve.rs | extern crate sieve;
use sieve::*;
#[test]
fn limit_lower_than_the_first_prime() {
assert_eq!(sieve::primes_up_to(1), []);
}
#[test]
fn limit_is_the_first_prime() {
assert_eq!(sieve::primes_up_to(2), [2]);
}
#[test]
fn primes_up_to_10() {
assert_eq!(sieve::primes_up_to(10), [2, 3, 5, 7]);
}
#[test]
fn ... |
#[test]
fn limit_of_1000() {
let expected = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,
71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149,
151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 2... | {
assert_eq!(sieve::primes_up_to(13), [2, 3, 5, 7, 11, 13]);
} | identifier_body |
AccessibilityTreeNode.ts | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as i18n from '../../../core/i18n/i18n.js';
import * as Platform from '../../../core/platform/platform.js';
import * as Protocol from '../../../ge... | });
}
}
ComponentHelpers.CustomElements.defineComponent('devtools-accessibility-tree-node', AccessibilityTreeNode);
declare global {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface HTMLElementTagNameMap {
'devtools-accessibility-tree-node': AccessibilityTreeNode;
}
} | random_line_split | |
AccessibilityTreeNode.ts | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as i18n from '../../../core/i18n/i18n.js';
import * as Platform from '../../../core/platform/platform.js';
import * as Protocol from '../../../ge... | (valueType: Protocol.Accessibility.AXValueType): boolean {
switch (valueType) {
case Protocol.Accessibility.AXValueType.Boolean:
case Protocol.Accessibility.AXValueType.BooleanOrUndefined:
case Protocol.Accessibility.AXValueType.String:
case Protocol.Accessibility.AXValueType.Number:
return true... | isPrintable | identifier_name |
AccessibilityTreeNode.ts | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as i18n from '../../../core/i18n/i18n.js';
import * as Platform from '../../../core/platform/platform.js';
import * as Protocol from '../../../ge... |
return text;
}
function isPrintable(valueType: Protocol.Accessibility.AXValueType): boolean {
switch (valueType) {
case Protocol.Accessibility.AXValueType.Boolean:
case Protocol.Accessibility.AXValueType.BooleanOrUndefined:
case Protocol.Accessibility.AXValueType.String:
case Protocol.Accessibilit... | {
return Platform.StringUtilities.trimMiddle(text, maxTextContentLength);
} | conditional_block |
AccessibilityTreeNode.ts | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as i18n from '../../../core/i18n/i18n.js';
import * as Platform from '../../../core/platform/platform.js';
import * as Protocol from '../../../ge... |
connectedCallback(): void {
this.#shadow.adoptedStyleSheets = [accessibilityTreeNodeStyles];
}
async #render(): Promise<void> {
const role = LitHtml.html`<span class='role-value'>${truncateTextIfNeeded(this.#role)}</span>`;
const name = LitHtml.html`"<span class='attribute-value'>${this.#name}</spa... | {
this.#ignored = data.ignored;
this.#name = data.name;
this.#role = data.role;
this.#properties = data.properties;
void this.#render();
} | identifier_body |
test_no_emulator.py | def test_dummy_request():
from rasa.nlu.emulators.no_emulator import NoEmulator
em = NoEmulator()
norm = em.normalise_request_json({"text": ["arb text"]})
assert norm == {"text": "arb text", "time": None}
norm = em.normalise_request_json({"text": ["arb text"], "time": "1499279161658"})
assert ... |
def test_emulators_can_handle_missing_data():
from rasa.nlu.emulators.luis import LUISEmulator
em = LUISEmulator()
norm = em.normalise_response_json(
{"text": "this data doesn't contain an intent result"}
)
assert norm["prediction"]["topIntent"] is None
assert norm["prediction"]["int... | from rasa.nlu.emulators.no_emulator import NoEmulator
em = NoEmulator()
data = {"intent": "greet", "text": "hi", "entities": {}, "confidence": 1.0}
assert em.normalise_response_json(data) == data | identifier_body |
test_no_emulator.py | def | ():
from rasa.nlu.emulators.no_emulator import NoEmulator
em = NoEmulator()
norm = em.normalise_request_json({"text": ["arb text"]})
assert norm == {"text": "arb text", "time": None}
norm = em.normalise_request_json({"text": ["arb text"], "time": "1499279161658"})
assert norm == {"text": "arb ... | test_dummy_request | identifier_name |
test_no_emulator.py | def test_dummy_request():
from rasa.nlu.emulators.no_emulator import NoEmulator
em = NoEmulator()
norm = em.normalise_request_json({"text": ["arb text"]})
assert norm == {"text": "arb text", "time": None}
norm = em.normalise_request_json({"text": ["arb text"], "time": "1499279161658"})
assert ... | em = LUISEmulator()
norm = em.normalise_response_json(
{"text": "this data doesn't contain an intent result"}
)
assert norm["prediction"]["topIntent"] is None
assert norm["prediction"]["intents"] == {} |
def test_emulators_can_handle_missing_data():
from rasa.nlu.emulators.luis import LUISEmulator
| random_line_split |
migrations.js | // Anytime you change the schema of one of the collection in a non-backward
// compatible way you have to write a migration in this file using the following
// API:
//
// Migrations.add(name, migrationCallback, optionalOrder);
// Note that we have extra migrations defined in `sandstorm.js` that are
// exclusive to S... | });
Attachments.update({}, {$unset: {cover: ''}}, noValidateMulti);
});
Migrations.add('use-css-class-for-boards-colors', () => {
const associationTable = {
'#27AE60': 'nephritis',
'#C0392B': 'pomegranate',
'#2980B9': 'belize',
'#8E44AD': 'wisteria',
'#2C3E50': 'midnight',
'#E67E22': 'pump... | Cards.update(card._id, {$set: {coverId: cover._id}}, noValidate);
}
| conditional_block |
migrations.js | // Anytime you change the schema of one of the collection in a non-backward
// compatible way you have to write a migration in this file using the following
// API:
//
// Migrations.add(name, migrationCallback, optionalOrder);
// Note that we have extra migrations defined in `sandstorm.js` that are
// exclusive to S... | }, noValidateMulti);
});
Migrations.add('lowercase-board-permission', () => {
['Public', 'Private'].forEach((permission) => {
Boards.update(
{ permission },
{ $set: { permission: permission.toLowerCase() } },
noValidateMulti
);
});
});
// Security migration: see https://github.com/weka... | background: {
type: 'color',
color: defaultColor,
},
}, | random_line_split |
variables.py | # #
# Copyright 2012-2015 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (ht... | v.nappend_el('BAR', 30, idx= -2)
self.assertEqual(str(v), "{'BAR': [[0, 1, 2], [10, 11, 30], [20]]}")
self.assertEqual(str(v['BAR']), '0 1 2 10 11 30 20')
v['FOO'] = range(3)
self.assertEqual(str(v['FOO']), "0,1,2")
v['BARSTR'] = 'XYZ'
self.assertEqual(v['BARSTR... | """ Baseclass for easyblock testcases """
def test_variables(self):
class TestVariables(Variables):
MAP_CLASS = {'FOO':CommaList}
v = TestVariables()
self.assertEqual(str(v), "{}")
# DEFAULTCLASS is StrList
v['BAR'] = range(3)
self.assertEqual(str(v), "... | identifier_body |
variables.py | # #
# Copyright 2012-2015 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (ht... | main() | conditional_block | |
variables.py | # #
# Copyright 2012-2015 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (ht... | MAP_CLASS = {'FOO':CommaList}
v = TestVariables()
self.assertEqual(str(v), "{}")
# DEFAULTCLASS is StrList
v['BAR'] = range(3)
self.assertEqual(str(v), "{'BAR': [[0, 1, 2]]}")
self.assertEqual(str(v['BAR']), "0 1 2")
v['BAR'].append(StrList(range(10... | """ Baseclass for easyblock testcases """
def test_variables(self):
class TestVariables(Variables): | random_line_split |
variables.py | # #
# Copyright 2012-2015 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (ht... | (self):
"""Test playing around with empty variables."""
v = Variables()
v.nappend('FOO', [])
self.assertEqual(v['FOO'], [])
v.join('BAR', 'FOO')
self.assertEqual(v['BAR'], [])
v.join('FOOBAR', 'BAR')
self.assertEqual(v['FOOBAR'], [])
def suite():
""" ... | test_empty_variables | identifier_name |
Channeling.ts | import SPELLS from 'common/SPELLS';
import { AbilityEvent, Ability, CastEvent, EndChannelEvent } from 'parser/core/Events';
import { Options } from 'parser/core/Module';
import CoreChanneling from 'parser/shared/modules/Channeling';
import Penance from '../spells/Penance';
const PENANCE_MINIMUM_RECAST_TIME = 3500; //... |
// Handle the first bolt of each cast
if (this.isNewPenanceCast(event.timestamp)) {
this._bolt = 0;
this._previousPenanceTimestamp = event.timestamp;
this.beginChannel(event, {
guid: SPELLS.PENANCE.id,
name: SPELLS.PENANCE.name,
type: 2,
abilityIcon: SPELLS.PE... | {
super.onCast(event);
return;
} | conditional_block |
Channeling.ts | import SPELLS from 'common/SPELLS';
import { AbilityEvent, Ability, CastEvent, EndChannelEvent } from 'parser/core/Events';
import { Options } from 'parser/core/Module';
import CoreChanneling from 'parser/shared/modules/Channeling';
import Penance from '../spells/Penance';
const PENANCE_MINIMUM_RECAST_TIME = 3500; //... | (event: EndChannelEvent, ability: Ability) {
if (this.isChannelingSpell(SPELLS.PENANCE.id)) {
// If a channeling spell is "canceled" it was actually just ended, so if it looks canceled then instead just mark it as ended
debug &&
this.debug(
'Marking',
((this._currentChannel a... | cancelChannel | identifier_name |
Channeling.ts | import SPELLS from 'common/SPELLS';
import { AbilityEvent, Ability, CastEvent, EndChannelEvent } from 'parser/core/Events';
import { Options } from 'parser/core/Module';
import CoreChanneling from 'parser/shared/modules/Channeling';
import Penance from '../spells/Penance';
const PENANCE_MINIMUM_RECAST_TIME = 3500; //... | }
// Handle the first bolt of each cast
if (this.isNewPenanceCast(event.timestamp)) {
this._bolt = 0;
this._previousPenanceTimestamp = event.timestamp;
this.beginChannel(event, {
guid: SPELLS.PENANCE.id,
name: SPELLS.PENANCE.name,
type: 2,
abilityIcon: SPEL... |
onCast(event: CastEvent) {
if (!Penance.isPenance(event.ability.guid)) {
super.onCast(event);
return; | random_line_split |
app.editadmin.ts | import {Component, NgModule, ViewChild, ViewContainerRef, ViewEncapsulation, OnDestroy, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms';
import {FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES} from "@angular/forms/src/directives";
//import {FORM_DIRECTIVES, REACTI... | () {
this.sub = this.route.params.subscribe(params => {
this.id = params['id']; // (+) converts string 'id' to a number
console.log((this.id));
// In a real app: dispatch action to load the details here.
});
}
ngOnDestroy() {
this.sub.unsubscribe();
... | ngOnInit | identifier_name |
app.editadmin.ts | import {Component, NgModule, ViewChild, ViewContainerRef, ViewEncapsulation, OnDestroy, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms';
import {FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES} from "@angular/forms/src/directives";
//import {FORM_DIRECTIVES, REACTI... |
}
static validateEmail(control: FormControl){
console.log('34324324');
console.log(control.value);
if (control.value=='' || !control.value.match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/)) {... | {
return { 'isTermsChecked': true };
} | conditional_block |
app.editadmin.ts | import {Component, NgModule, ViewChild, ViewContainerRef, ViewEncapsulation, OnDestroy, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms';
import {FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES} from "@angular/forms/src/directives";
//import {FORM_DIRECTIVES, REACTI... | phone: "",
zip: "",
is_active: ""
}
this.sub = this.route.params.subscribe(params => {
this.id = params['id']; // (+) converts string 'id' to a number
let ids={id:this.id};
this.http.post(this.serverUrl+'editadmin',ids)
... | {
this.items = commonservices.getItems();
this.http=http;
this.router=router;
this.cookeiservice=cookeiservice;
this.appcomponent=appcomponent;
console.log(this.items);
console.log(this.items[0].serverUrl);
this.serverUrl = this.items[0].serverUrl;
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.