file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
packed-struct-vec.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | use std::sys;
#[packed]
#[deriving(Eq)]
struct Foo {
bar: u8,
baz: u64
}
fn main() {
let foos = [Foo { bar: 1, baz: 2 }, .. 10];
assert_eq!(sys::size_of::<[Foo, .. 10]>(), 90);
for i in range(0u, 10) {
assert_eq!(foos[i], Foo { bar: 1, baz: 2});
}
for &foo in foos.iter() {
... | random_line_split | |
packed-struct-vec.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let foos = [Foo { bar: 1, baz: 2 }, .. 10];
assert_eq!(sys::size_of::<[Foo, .. 10]>(), 90);
for i in range(0u, 10) {
assert_eq!(foos[i], Foo { bar: 1, baz: 2});
}
for &foo in foos.iter() {
assert_eq!(foo, Foo { bar: 1, baz: 2 });
}
} | identifier_body | |
GroupStore.js | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
import { EventEmitter } from 'events';
import ActorClient from 'utils/ActorClient';
import DialogStore from 'stores/DialogStore'
import { register, waitFor } from 'dispatcher/ActorAppDispatcher';
import { ActionTypes, AsyncActionStates } from 'constants/Acto... | (callback) {
this.removeListener(CHANGE_EVENT, callback);
}
}
let GroupStoreInstance = new GroupStore();
GroupStoreInstance.dispatchToken = register(action => {
switch (action.type) {
case ActionTypes.LEFT_GROUP:
GroupStoreInstance.emitChange();
break;
case ActionTypes.GET_INTEGRATION_TOK... | removeChangeListener | identifier_name |
GroupStore.js | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
import { EventEmitter } from 'events';
import ActorClient from 'utils/ActorClient';
import DialogStore from 'stores/DialogStore'
import { register, waitFor } from 'dispatcher/ActorAppDispatcher';
import { ActionTypes, AsyncActionStates } from 'constants/Acto... | return ActorClient.getGroup(gid);
}
getIntegrationToken() {
return _integrationToken;
}
emitChange() {
this.emit(CHANGE_EVENT);
}
addChangeListener(callback) {
this.on(CHANGE_EVENT, callback);
}
removeChangeListener(callback) {
this.removeListener(CHANGE_EVENT, callback);
}
}
... | getGroup(gid) { | random_line_split |
GroupStore.js | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
import { EventEmitter } from 'events';
import ActorClient from 'utils/ActorClient';
import DialogStore from 'stores/DialogStore'
import { register, waitFor } from 'dispatcher/ActorAppDispatcher';
import { ActionTypes, AsyncActionStates } from 'constants/Acto... |
removeChangeListener(callback) {
this.removeListener(CHANGE_EVENT, callback);
}
}
let GroupStoreInstance = new GroupStore();
GroupStoreInstance.dispatchToken = register(action => {
switch (action.type) {
case ActionTypes.LEFT_GROUP:
GroupStoreInstance.emitChange();
break;
case ActionT... | {
this.on(CHANGE_EVENT, callback);
} | identifier_body |
localeTool.js | var path = require('path');
var fs = require('fs');
var localeDir = path.resolve(__dirname, '../../src/config/i18n');
var distFile = path.resolve(__dirname, '../tmp/i18n.json');
/**
* 查找所有的多语言文件
*/
var findLangs = function(dir) {
if (!fs.existsSync(dir)) {
return null;
}
var dirs = fs.readdirSy... | */
var mergeLangs = function(files) {
if (!files || files.length === 0) {
return {cn: {}};
}
return files.reduce(function(ret, item) {
var reg = /(\w+)\.json$/;
var m = item.match(reg);
if (m && m.length === 2) {
var langName = m[1];
var content = fs... | });
};
/**
* 合并多语言文件到 locales.json | random_line_split |
localeTool.js | var path = require('path');
var fs = require('fs');
var localeDir = path.resolve(__dirname, '../../src/config/i18n');
var distFile = path.resolve(__dirname, '../tmp/i18n.json');
/**
* 查找所有的多语言文件
*/
var findLangs = function(dir) {
if (!fs.existsSync(dir)) {
return nul | readdirSync(dir);
if (!dirs || dirs.length === 0) {
return null;
}
return dirs.filter(function(fileName) {
return /\.json/.test(fileName);
}).map(function(fileName) {
return path.resolve(localeDir, fileName);
});
};
/**
* 合并多语言文件到 locales.json
*/
var mergeLangs = function... | l;
}
var dirs = fs. | conditional_block |
index.d.ts | // Type definitions for jsUri 1.3
// Project: https://github.com/derek-watson/jsUri
// Definitions by: Chris Charabaruk <https://github.com/coldacid>, Florian Wagner <https://github.com/flqw>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace jsuri {
type Primitive = string | number... | * @param {string} [oldVal] replace only one specific value (otherwise replaces all)
* @return {Uri} returns self for fluent chaining
*/
replaceQueryParam(key: string, newVal: Primitive, oldVal?: Primitive): Uri;
/**
* Define fluent setter methods (setProtocol, setHasAutho... | * replaces query param values
* @param {string} key key to replace value for
* @param {string} newVal new value | random_line_split |
index.d.ts | // Type definitions for jsUri 1.3
// Project: https://github.com/derek-watson/jsUri
// Definitions by: Chris Charabaruk <https://github.com/coldacid>, Florian Wagner <https://github.com/flqw>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace jsuri {
type Primitive = string | number... | {
/**
* Creates a new Uri object
* @constructor
* @param {string} str
*/
constructor(str?: string);
/**
* Define getter/setter methods
*/
protocol(val?: string): string;
userInfo(val?: string): string;
host(val?: string): string;
port(val?: number): number;
... | Uri | identifier_name |
references.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
paths::{self, Path},
shared::*,
};
use std::{
cmp::Ordering,
collections::{BTreeMap, BTreeSet},
fmt,
fmt::Debug,
};
//********************************************************************************... |
}
}
}
impl<Loc: Copy, Lbl: Clone + Ord> Ref<Loc, Lbl> {
/// Utility for remapping the reference ids according the `id_map` provided
/// If it is not in the map, the id remains the same
pub(crate) fn remap_refs(&mut self, id_map: &BTreeMap<RefID, RefID>) {
self.borrowed_by.remap_refs(id... | {
self.0.insert(*new, edges);
} | conditional_block |
references.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
paths::{self, Path},
shared::*,
};
use std::{
cmp::Ordering,
collections::{BTreeMap, BTreeSet},
fmt,
fmt::Debug,
};
//********************************************************************************... | for (old, new) in id_map {
if let Some(edges) = self.0.remove(old) {
self.0.insert(*new, edges);
}
}
}
}
impl<Loc: Copy, Lbl: Clone + Ord> Ref<Loc, Lbl> {
/// Utility for remapping the reference ids according the `id_map` provided
/// If it is not in ... | /// Utility for remapping the reference ids according the `id_map` provided
/// If it is not in the map, the id remains the same
pub(crate) fn remap_refs(&mut self, id_map: &BTreeMap<RefID, RefID>) { | random_line_split |
references.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
paths::{self, Path},
shared::*,
};
use std::{
cmp::Ordering,
collections::{BTreeMap, BTreeSet},
fmt,
fmt::Debug,
};
//********************************************************************************... |
}
impl<Loc: Copy, Lbl: Clone + Ord> PartialEq for BorrowEdge<Loc, Lbl> {
fn eq(&self, other: &BorrowEdge<Loc, Lbl>) -> bool {
BorrowEdgeNoLoc::new(self) == BorrowEdgeNoLoc::new(other)
}
}
impl<Loc: Copy, Lbl: Clone + Ord> Eq for BorrowEdge<Loc, Lbl> {}
impl<Loc: Copy, Lbl: Clone + Ord> PartialOrd fo... | {
BorrowEdgeNoLoc {
strong: e.strong,
path: &e.path,
}
} | identifier_body |
references.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
paths::{self, Path},
shared::*,
};
use std::{
cmp::Ordering,
collections::{BTreeMap, BTreeSet},
fmt,
fmt::Debug,
};
//********************************************************************************... | <Loc: Copy, Lbl: Clone + Ord> {
/// Parent to child
/// 'self' is borrowed by _
pub(crate) borrowed_by: BorrowEdges<Loc, Lbl>,
/// Child to parent
/// 'self' borrows from _
/// Needed for efficient querying, but should be in one-to-one corespondence with borrowed by
/// i.e. x is borrowed by... | Ref | identifier_name |
artifact.rs | use byteorder::*;
use core::io::{BinaryComponent, DecodeError, WrResult};
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct ArtifactData {
spec: u16, // Artifact code. Big-endian 0xXXXY, where X is the namespace and Y is the subtype.
body: Vec<u8> // Actual artifact format is specified in a higher layer.
}
... | Ok(ArtifactData {
spec: sp,
body: b
})
}
fn to_writer<W: WriteBytesExt>(&self, write: &mut W) -> WrResult {
write.write_u16::<BigEndian>(self.spec)?;
write.write_u64::<BigEndian>(self.body.len() as u64)?;
write.write_all(self.body.as_slice())?;
... | random_line_split | |
artifact.rs | use byteorder::*;
use core::io::{BinaryComponent, DecodeError, WrResult};
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct ArtifactData {
spec: u16, // Artifact code. Big-endian 0xXXXY, where X is the namespace and Y is the subtype.
body: Vec<u8> // Actual artifact format is specified in a higher layer.
}
... | <R: ReadBytesExt>(read: &mut R) -> Result<Self, DecodeError> {
let sp = read.read_u16::<BigEndian>()?;
let mut b = vec![0; read.read_u64::<BigEndian>()? as usize];
read.read(b.as_mut_slice())?;
Ok(ArtifactData {
spec: sp,
body: b
})
}
fn to_wri... | from_reader | identifier_name |
global-data.js | * Created by Rodrigo on 25/01/2017.
*/
const data = {};
const subscribers = {};
const EVENTS = {
SET: 'set',
SUBSCRIBE : 'subscribe',
UNSUBSCRIBE: 'unsubscribe'
};
/**
* Notify to all the subscriber the new value.
* A subscriber must implement a _onEvent method.
* @param event
* @param detail
* @par... | /** | random_line_split | |
linear_gradient.rs | // svgcleaner could help you to clean up your SVG files
// from unnecessary data.
// Copyright (C) 2012-2018 Evgeniy Reizner
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version ... |
#[cfg(test)]
mod tests {
use super::*;
use svgdom::{Document, ToStringWithOptions};
use task;
macro_rules! test {
($name:ident, $in_text:expr, $out_text:expr) => (
#[test]
fn $name() {
let doc = Document::from_str($in_text).unwrap();
tas... | {
let attrs = [
AId::X1,
AId::Y1,
AId::X2,
AId::Y2,
AId::GradientUnits,
AId::SpreadMethod,
];
let mut nodes = doc.descendants()
.filter(|n| n.is_tag_name(EId::LinearGradient))
.collect::<Vec<Node>>();
super::... | identifier_body |
linear_gradient.rs | // svgcleaner could help you to clean up your SVG files
// from unnecessary data.
// Copyright (C) 2012-2018 Evgeniy Reizner
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version ... | //
// 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.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
use svgdom::{
Document,
Node,
};
use task::short::{EId, AId};
pub fn remove_dupl_linear_gradi... | //
// 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 |
linear_gradient.rs | // svgcleaner could help you to clean up your SVG files
// from unnecessary data.
// Copyright (C) 2012-2018 Evgeniy Reizner
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version ... | (doc: &Document) {
let attrs = [
AId::X1,
AId::Y1,
AId::X2,
AId::Y2,
AId::GradientUnits,
AId::SpreadMethod,
];
let mut nodes = doc.descendants()
.filter(|n| n.is_tag_name(EId::LinearGradient))
.collect::<Vec<Node>... | remove_dupl_linear_gradients | identifier_name |
linear_gradient.rs | // svgcleaner could help you to clean up your SVG files
// from unnecessary data.
// Copyright (C) 2012-2018 Evgeniy Reizner
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version ... |
true
});
}
#[cfg(test)]
mod tests {
use super::*;
use svgdom::{Document, ToStringWithOptions};
use task;
macro_rules! test {
($name:ident, $in_text:expr, $out_text:expr) => (
#[test]
fn $name() {
let doc = Document::from_str($in_text).unwra... | {
return false;
} | conditional_block |
index.js | /**
* webdriverio
* https://github.com/Camme/webdriverio
*
* A WebDriver module for nodejs. Either use the super easy help commands or use the base
* Webdriver wire protocol commands. Its totally inspired by jellyfishs webdriver, but the
* goal is to make all the webdriver protocol items available, as near the or... | * Vincent Voyer <vincent@zeroload.net>
*/
import WebdriverIO from './lib/webdriverio'
import Multibrowser from './lib/multibrowser'
import ErrorHandler from './lib/utils/ErrorHandler'
import getImplementedCommands from './lib/helpers/getImplementedCommands'
import pkg from './package.json'
const IMPLEMENTED_COM... | * Dan Jenkins <dan.jenkins@holidayextras.com>
* Christian Bromann <mail@christian-bromann.com> | random_line_split |
update.rs | use std::collections::HashMap;
use util::H256;
use header::BlockNumber;
use blockchain::block_info::BlockInfo;
use blooms::BloomGroup;
use super::extras::{BlockDetails, BlockReceipts, TransactionAddress, LogGroupPosition};
/// Block extras update info.
pub struct | <'a> {
/// Block info.
pub info: BlockInfo,
/// Current block uncompressed rlp bytes
pub block: &'a [u8],
/// Modified block hashes.
pub block_hashes: HashMap<BlockNumber, H256>,
/// Modified block details.
pub block_details: HashMap<H256, BlockDetails>,
/// Modified block receipts.
pub block_receipts: HashMa... | ExtrasUpdate | identifier_name |
update.rs | use std::collections::HashMap;
use util::H256;
use header::BlockNumber;
use blockchain::block_info::BlockInfo;
use blooms::BloomGroup;
use super::extras::{BlockDetails, BlockReceipts, TransactionAddress, LogGroupPosition};
/// Block extras update info.
pub struct ExtrasUpdate<'a> {
/// Block info.
pub info: BlockInf... | } | pub transactions_addresses: HashMap<H256, Option<TransactionAddress>>, | random_line_split |
meshopt-compression.ts | import { Accessor, Buffer, BufferUtils, Extension, GLB_BUFFER, GLTF, PropertyType, ReaderContext, WriterContext } from '@gltf-transform/core';
import { EncoderMethod, MeshoptBufferViewExtension, MeshoptFilter } from './constants';
import { EXT_MESHOPT_COMPRESSION } from '../constants';
import { getMeshoptFilter, getMes... | * Meshopt compression (based on the [meshoptimizer](https://github.com/zeux/meshoptimizer)
* library) offers a lightweight decoder with very fast runtime decompression, and is
* appropriate for models of any size. Meshopt can reduce the transmission sizes of geometry,
* morph targets, animation, and other numeric d... | *
* [[include:VENDOR_EXTENSIONS_NOTE.md]]
* | random_line_split |
meshopt-compression.ts | import { Accessor, Buffer, BufferUtils, Extension, GLB_BUFFER, GLTF, PropertyType, ReaderContext, WriterContext } from '@gltf-transform/core';
import { EncoderMethod, MeshoptBufferViewExtension, MeshoptFilter } from './constants';
import { EXT_MESHOPT_COMPRESSION } from '../constants';
import { getMeshoptFilter, getMes... | ends Extension {
public readonly extensionName = NAME;
public readonly prereadTypes = [PropertyType.BUFFER, PropertyType.PRIMITIVE];
public readonly prewriteTypes = [PropertyType.BUFFER, PropertyType.ACCESSOR];
public readonly readDependencies = ['meshopt.decoder'];
public readonly writeDependencies = ['meshopt.en... | optCompression ext | identifier_name |
meshopt-compression.ts | import { Accessor, Buffer, BufferUtils, Extension, GLB_BUFFER, GLTF, PropertyType, ReaderContext, WriterContext } from '@gltf-transform/core';
import { EncoderMethod, MeshoptBufferViewExtension, MeshoptFilter } from './constants';
import { EXT_MESHOPT_COMPRESSION } from '../constants';
import { getMeshoptFilter, getMes... | ** @internal Decode buffer views. */
private _prereadBuffers(context: ReaderContext): void {
const jsonDoc = context.jsonDoc;
const viewDefs = jsonDoc.json.bufferViews || [];
viewDefs.forEach((viewDef, index) => {
if (!viewDef.extensions || !viewDef.extensions[NAME]) return;
const meshoptDef = viewDef.ex... | if (!this._decoder) {
if (!this.isRequired()) return this;
throw new Error(`[${NAME}] Please install extension dependency, "meshopt.decoder".`);
}
if (!this._decoder.supported) {
if (!this.isRequired()) return this;
throw new Error(`[${NAME}]: Missing WASM support.`);
}
if (propertyType === Propert... | identifier_body |
meshopt-compression.ts | import { Accessor, Buffer, BufferUtils, Extension, GLB_BUFFER, GLTF, PropertyType, ReaderContext, WriterContext } from '@gltf-transform/core';
import { EncoderMethod, MeshoptBufferViewExtension, MeshoptFilter } from './constants';
import { EXT_MESHOPT_COMPRESSION } from '../constants';
import { getMeshoptFilter, getMes... | f (key === 'meshopt.encoder') {
this._encoder = dependency as typeof MeshoptEncoder;
}
return this;
}
/**
* Configures Meshopt options for quality/compression tuning. The two methods rely on different
* pre-processing before compression, and should be compared on the basis of (a) quality/loss
* and (b) ... | this._decoder = dependency as typeof MeshoptDecoder;
}
i | conditional_block |
platform_directives_and_pipes.ts | * available in every component of the application.
*
* ### Example
*
* ```typescript
* import {PLATFORM_DIRECTIVES} from '@angular/core';
* import {OtherDirective} from './myDirectives';
*
* @Component({
* selector: 'my-component',
* template: `
* <!-- can use other directive even though the compone... | import {OpaqueToken} from './di';
/**
* A token that can be provided when bootstraping an application to make an array of directives | random_line_split | |
extract_and_upload_iris_classifier.py | #!/usr/bin/env python
# Load common imports and system envs to build the core object |
# Load the Environment:
os.environ["ENV_DEPLOYMENT_TYPE"] = "JustRedis"
from src.common.inits_for_python import *
#####################################################################
#
# Start Arg Processing:
#
action = "Extract and Upload IRIS Models to S3"
parser = argparse.ArgumentPars... | import sys, os | random_line_split |
extract_and_upload_iris_classifier.py | #!/usr/bin/env python
# Load common imports and system envs to build the core object
import sys, os
# Load the Environment:
os.environ["ENV_DEPLOYMENT_TYPE"] = "JustRedis"
from src.common.inits_for_python import *
#####################################################################
#
# Start Arg Processing:
#
act... |
else:
lg("", 6)
lg("ERROR: Failed Upload Model and Analysis Caches as file for DSName(" + str(ds_name) + ")", 6)
lg(upload_results["Error"], 6)
lg("", 6)
sys.exit(1)
# end of if extract + upload worked
lg("", 6)
lg("Extract and Upload Completed", 5)
lg("", 6)
sys.exit(0)
| lg("Done Uploading Model and Analysis DSName(" + str(ds_name) + ") S3Loc(" + str(cache_req["S3Loc"]) + ")", 6) | conditional_block |
styles.js | 'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
var $ = require('gulp-load-plugins')();
var wiredep = require('wiredep').stream;
var _ = require('lodash');
gulp.task('styles', function () {
var sassOptions = {
styl... | },
starttag: '// injector',
endtag: '// endinjector',
addRootSlash: false
};
return gulp.src([
path.join(conf.paths.src, '/app/index.scss')
])
.pipe($.inject(injectFiles, injectOptions))
.pipe(wiredep(_.extend({}, conf.wiredep)))
.pipe($.sourcemaps.init())
.pipe($.sass(sassOp... |
var injectOptions = {
transform: function(filePath) {
filePath = filePath.replace(conf.paths.src + '/app/', '');
return '@import "' + filePath + '";'; | random_line_split |
queries.ts | import Api = require('../api')
import Filters = require('./filters');
import Selects = require('./selects');
import QueryBuilder = require('./query-builder');
import Q = require('q');
import request = require('superagent');
import _ = require('underscore');
module Queries {
export class ConnectQuery {
_client: Api.... |
return new ConnectQuery(this._client, this._collection, this._selects, this._filters, groups, this._timeframe, this._interval, this._timezone, this._customQueryOptions);
}
public timeframe(timeframe: Api.Timeframe): ConnectQuery {
return new ConnectQuery(this._client, this._collection, this._selects, this... | {
groups = this._groups.concat(field);
} | conditional_block |
queries.ts | import Api = require('../api')
import Filters = require('./filters');
import Selects = require('./selects');
import QueryBuilder = require('./query-builder');
import Q = require('q');
import request = require('superagent');
import _ = require('underscore');
module Queries {
export class ConnectQuery {
_client: Api.... |
private _addToRunningQueries(executeQuery:Api.ClientDeferredQuery) {
this._runningRequests.push(executeQuery);
var removeFromRunningQueries = () => {
var finishedQueryIndex = this._runningRequests.indexOf(executeQuery);
if(finishedQueryIndex < 0) return;
this._runningRequests.splice(finishedQueryIn... | } | random_line_split |
queries.ts | import Api = require('../api')
import Filters = require('./filters');
import Selects = require('./selects');
import QueryBuilder = require('./query-builder');
import Q = require('q');
import request = require('superagent');
import _ = require('underscore');
module Queries {
export class ConnectQuery {
_client: Api.... |
public isExecuting() {
return this._runningRequests.length > 0;
}
private _addToRunningQueries(executeQuery:Api.ClientDeferredQuery) {
this._runningRequests.push(executeQuery);
var removeFromRunningQueries = () => {
var finishedQueryIndex = this._runningRequests.indexOf(executeQuery);
if(finis... | {
var length = this._runningRequests.length;
_.each(this._runningRequests, request => {
request.request.abort();
request.deferred.reject('request aborted');
});
this._runningRequests.splice(0, length);
} | identifier_body |
queries.ts | import Api = require('../api')
import Filters = require('./filters');
import Selects = require('./selects');
import QueryBuilder = require('./query-builder');
import Q = require('q');
import request = require('superagent');
import _ = require('underscore');
module Queries {
export class ConnectQuery {
_client: Api.... | (filterSpecification: any): ConnectQuery {
var filters = _.chain(filterSpecification)
.map(Filters.queryFilterBuilder)
.flatten()
.value()
.concat(this._filters);
filters = _.uniq(filters, filter => filter.field + '|' + filter.operator);
return new ConnectQuery(this._client, this._collection,... | filter | identifier_name |
main.js | ;(function() {
"use strict";
var app = angular.module("AddressApp",[]);
app.controller("AddressBookController", function() {
var vm = this;
vm.contacts = [
{
name: "Hank",
email: "blahblah@ymail.com",
phone: 9876543210,
addr... | email: "lovecookies@gmail.com",
phone: 1234567890,
address: "Sesame Street"
},
{
name: "Clifford",
email: "bigreddog@aol.com",
phone: 127361239,
address: "Too big for an address"
}
];... | name: "Cookie Monster", | random_line_split |
invalidation.py | import collections
import functools
import hashlib
import logging
import socket
from django.conf import settings
from django.core.cache import cache as default_cache, get_cache, parse_backend_uri
from django.core.cache.backends.base import InvalidCacheBackendError
from django.utils import encoding, translation
try:
... | (self, keys):
"""
Recursively search for flush lists and objects to invalidate.
The search starts with the lists in `keys` and expands to any flush
lists found therein. Returns ({objects to flush}, {flush keys found}).
"""
new_keys = keys = set(map(flush_key, keys))
... | find_flush_lists | identifier_name |
invalidation.py | import collections
import functools
import hashlib
import logging
import socket
from django.conf import settings
from django.core.cache import cache as default_cache, get_cache, parse_backend_uri
from django.core.cache.backends.base import InvalidCacheBackendError
from django.utils import encoding, translation
try:
... |
class NullInvalidator(Invalidator):
def add_to_flush_list(self, mapping):
return
def get_redis_backend():
"""Connect to redis from a string like CACHE_BACKEND."""
# From django-redis-cache.
_, server, params = parse_backend_uri(settings.REDIS_BACKEND)
db = params.pop('db', 1)
try:
... | redis.delete(*map(self.safe_key, keys)) | identifier_body |
invalidation.py | import collections
import functools
import hashlib
import logging
import socket
from django.conf import settings
from django.core.cache import cache as default_cache, get_cache, parse_backend_uri
from django.core.cache.backends.base import InvalidCacheBackendError
from django.utils import encoding, translation
try:
... |
# memcached keys must be < 250 bytes and w/o whitespace, but it's nice
# to see the keys when using locmem.
return hashlib.md5(key).hexdigest()
def flush_key(obj):
"""We put flush lists in the flush: namespace."""
key = obj if isinstance(obj, basestring) else obj.cache_key
return FLUSH + make... | key += encoding.smart_str(translation.get_language()) | conditional_block |
invalidation.py | import collections
import functools
import hashlib
import logging
import socket
from django.conf import settings
from django.core.cache import cache as default_cache, get_cache, parse_backend_uri
from django.core.cache.backends.base import InvalidCacheBackendError
from django.utils import encoding, translation
try:
... | redislib = None
# Look for an own cache first before falling back to the default cache
try:
cache = get_cache('cache_machine')
except (InvalidCacheBackendError, ValueError):
cache = default_cache
CACHE_PREFIX = getattr(settings, 'CACHE_PREFIX', '')
FETCH_BY_ID = getattr(settings, 'FETCH_BY_ID', False)
FL... | random_line_split | |
textutil.py | #!/usr/bin/env python
# http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string
import re
import unicodedata
def strip_accents(text):
"""
Strip accents from input String.
:param text: The input string.
:type text: String.
:returns: The proces... | :param text: The input string.
:type text: String.
:returns: The processed String.
:rtype: String.
"""
text = strip_accents(text.lower())
text = re.sub('[ ]+', '_', text)
text = re.sub('[^0-9a-zA-Z_-]', '', text)
return text | def text_to_id(text):
"""
Convert input text to id.
| random_line_split |
textutil.py | #!/usr/bin/env python
# http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string
import re
import unicodedata
def strip_accents(text):
|
def text_to_id(text):
"""
Convert input text to id.
:param text: The input string.
:type text: String.
:returns: The processed String.
:rtype: String.
"""
text = strip_accents(text.lower())
text = re.sub('[ ]+', '_', text)
text = re.sub('[^0-9a-zA-Z_-]', '', text)
return ... | """
Strip accents from input String.
:param text: The input string.
:type text: String.
:returns: The processed String.
:rtype: String.
"""
try:
text = unicode(text, 'utf-8')
except NameError: # unicode is a default on python 3
pass
text = unicodedata.normalize('NF... | identifier_body |
textutil.py | #!/usr/bin/env python
# http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string
import re
import unicodedata
def | (text):
"""
Strip accents from input String.
:param text: The input string.
:type text: String.
:returns: The processed String.
:rtype: String.
"""
try:
text = unicode(text, 'utf-8')
except NameError: # unicode is a default on python 3
pass
text = unicodedata.n... | strip_accents | identifier_name |
test_data_source.py | #
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
def test_show_attribute(self):
ds = self._create_resource('data-source', self.rsrc_defn, self.stack)
value = mock.MagicMock()
value.to_dict.return_value = {'ds': 'info'}
self.client.data_sources.get.return_value = value
self.assertEqual({'ds': 'info'}, ds.FnGetAtt('show'))
... | ds = self._create_resource('data-source', self.rsrc_defn,
self.stack)
props = self.stack.t.t['resources']['data-source']['properties'].copy()
props['type'] = 'hdfs'
props['url'] = 'my/path'
self.rsrc_defn = self.rsrc_defn.freeze(properties=props)
... | identifier_body |
test_data_source.py | #
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | (common.HeatTestCase):
def setUp(self):
super(SaharaDataSourceTest, self).setUp()
t = template_format.parse(data_source_template)
self.stack = utils.parse_stack(t)
resource_defns = self.stack.t.resource_definitions(self.stack)
self.rsrc_defn = resource_defns['data-source']
... | SaharaDataSourceTest | identifier_name |
test_data_source.py | #
# 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
# | #
# Unless required by applicable law or agreed to in writing, software
# 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.
... | # http://www.apache.org/licenses/LICENSE-2.0 | random_line_split |
server.js | const fs = require('fs')
const path = require('path')
const LRU = require('lru-cache')
const express = require('express')
const favicon = require('serve-favicon')
const compression = require('compression')
const resolve = file => path.resolve(__dirname, file)
const { createBundleRenderer } = require('vue-server-rendere... | // 1-second microcache.
// https://www.nginx.com/blog/benefits-of-microcaching-nginx/
const microCache = LRU({
max: 100,
maxAge: 1000
})
// since this app has no user-specific content, every page is micro-cacheable.
// if your app involves user-specific content, you need to implement custom
// logic to determine w... | app.use('/manifest.json', serve('./manifest.json', true))
app.use('/service-worker.js', serve('./dist/service-worker.js'))
| random_line_split |
server.js | const fs = require('fs')
const path = require('path')
const LRU = require('lru-cache')
const express = require('express')
const favicon = require('serve-favicon')
const compression = require('compression')
const resolve = file => path.resolve(__dirname, file)
const { createBundleRenderer } = require('vue-server-rendere... |
let renderer
let readyPromise
if (isProd) {
// In production: create server renderer using built server bundle.
// The server bundle is generated by vue-ssr-webpack-plugin.
const bundle = require('./dist/vue-ssr-server-bundle.json')
// The client manifests are optional, but it allows the renderer
// to auto... | {
// https://github.com/vuejs/vue/blob/dev/packages/vue-server-renderer/README.md#why-use-bundlerenderer
return createBundleRenderer(bundle, Object.assign(options, {
template,
// for component caching
cache: LRU({
max: 1000,
maxAge: 1000 * 60 * 15
}),
// this is only needed when vue-... | identifier_body |
server.js | const fs = require('fs')
const path = require('path')
const LRU = require('lru-cache')
const express = require('express')
const favicon = require('serve-favicon')
const compression = require('compression')
const resolve = file => path.resolve(__dirname, file)
const { createBundleRenderer } = require('vue-server-rendere... | (req, res) {
const s = Date.now()
res.setHeader("Content-Type", "text/html")
res.setHeader("Server", serverInfo)
const handleError = err => {
if (err.url) {
res.redirect(err.url)
} else if(err.code === 404) {
res.status(404).end('404 | Page Not Found')
} else {
// Render Error P... | render | identifier_name |
setext_header.rs | use parser::span::parse_spans;
use parser::Block;
use parser::Block::Header;
use regex::Regex;
pub fn parse_setext_header(lines: &[&str]) -> Option<(Block, usize)> {
lazy_static! {
static ref HORIZONTAL_RULE_1: Regex = Regex::new(r"^===+$").unwrap();
static ref HORIZONTAL_RULE_2: Regex = Regex::new... | () {
assert_eq!(
parse_setext_header(&vec!["Test", "=========="]).unwrap(),
(Header(vec![Text("Test".to_owned())], 1), 2)
);
assert_eq!(
parse_setext_header(&vec!["Test", "----------"]).unwrap(),
(Header(vec![Text("Test".to_owned())], 2), 2)
... | finds_atx_header | identifier_name |
setext_header.rs | use parser::span::parse_spans;
use parser::Block;
use parser::Block::Header;
use regex::Regex;
pub fn parse_setext_header(lines: &[&str]) -> Option<(Block, usize)> |
#[cfg(test)]
mod test {
use super::parse_setext_header;
use parser::Block::Header;
use parser::Span::Text;
#[test]
fn finds_atx_header() {
assert_eq!(
parse_setext_header(&vec!["Test", "=========="]).unwrap(),
(Header(vec![Text("Test".to_owned())], 1), 2)
)... | {
lazy_static! {
static ref HORIZONTAL_RULE_1: Regex = Regex::new(r"^===+$").unwrap();
static ref HORIZONTAL_RULE_2: Regex = Regex::new(r"^---+$").unwrap();
}
if lines.len() > 1 && !lines[0].is_empty() {
if HORIZONTAL_RULE_1.is_match(lines[1]) {
return Some((Header(parse... | identifier_body |
setext_header.rs | use parser::span::parse_spans;
use parser::Block;
use parser::Block::Header;
use regex::Regex;
pub fn parse_setext_header(lines: &[&str]) -> Option<(Block, usize)> {
lazy_static! {
static ref HORIZONTAL_RULE_1: Regex = Regex::new(r"^===+$").unwrap();
static ref HORIZONTAL_RULE_2: Regex = Regex::new... |
assert_eq!(
parse_setext_header(&vec!["This is a test", "==="]).unwrap(),
(Header(vec![Text("This is a test".to_owned())], 1), 2)
);
assert_eq!(
parse_setext_header(&vec!["This is a test", "---"]).unwrap(),
(Header(vec![Text("This is a test".to_o... | ); | random_line_split |
setext_header.rs | use parser::span::parse_spans;
use parser::Block;
use parser::Block::Header;
use regex::Regex;
pub fn parse_setext_header(lines: &[&str]) -> Option<(Block, usize)> {
lazy_static! {
static ref HORIZONTAL_RULE_1: Regex = Regex::new(r"^===+$").unwrap();
static ref HORIZONTAL_RULE_2: Regex = Regex::new... | else if HORIZONTAL_RULE_2.is_match(lines[1]) {
return Some((Header(parse_spans(lines[0]), 2), 2));
}
}
None
}
#[cfg(test)]
mod test {
use super::parse_setext_header;
use parser::Block::Header;
use parser::Span::Text;
#[test]
fn finds_atx_header() {
assert_eq!(
... | {
return Some((Header(parse_spans(lines[0]), 1), 2));
} | conditional_block |
vec-matching-legal-tail-element-borrow.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x = &[1i, 2, 3, 4, 5];
let x: &[int] = &[1, 2, 3, 4, 5];
if !x.is_empty() {
let el = match x {
[1, ..ref tail] => &tail[0],
_ => unreachable!()
};
println!("{}", *el);
}
} | identifier_body | |
vec-matching-legal-tail-element-borrow.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let x = &[1i, 2, 3, 4, 5];
let x: &[int] = &[1, 2, 3, 4, 5];
if !x.is_empty() {
let el = match x {
[1, ..ref tail] => &tail[0],
_ => unreachable!()
};
println!("{}", *el);
}
}
| main | identifier_name |
vec-matching-legal-tail-element-borrow.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
} | random_line_split | |
app.js | const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const index = require('./routes/index')
const users = require('./routes/users') | // api代理
const proxy = require('koa-proxies')
const httpsProxyAgent = require('https-proxy-agent')
app.use(proxy('/api', {
target: 'http://172.16.8.197:8081',
changeOrigin: true,
logs: true,
rewrite: path => path.replace(/^\/api/g, '')
// agent: new httpsProxyAgent('http://172.16.8.197:8081'),
// rewrite: p... |
const config = require('./config.js')
| random_line_split |
app.js | const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const index = require('./routes/index')
const users = require('./routes/users')
... | ('connected as id ' + connection.threadId);
});
global.connection = connection;
global.sf = require('./boot.js');
// error handler
onerror(app)
// middlewares
app.use(bodyparser({
enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
// 使用端路由渲染页面
// app.use(require('koa-static')(__dirname + '/... | error('error connecting: ' + err.stack);
return;
}
console.log | conditional_block |
test_lib_trees.py |
from synapse.tests.common import *
import synapse.lib.trees as s_trees
class TreeTest(SynTest):
def test_lib_tree_interval(self):
| ivals = (
((-30, 50), {'name': 'foo'}),
((30, 100), {'name': 'bar'}),
((80, 100), {'name': 'baz'}),
)
itree = s_trees.IntervalTree(ivals)
#import pprint
#pprint.pprint(itree.root)
# test a multi-level overlap
names = [ival[1].get('na... | identifier_body | |
test_lib_trees.py |
from synapse.tests.common import *
import synapse.lib.trees as s_trees
class TreeTest(SynTest):
def | (self):
ivals = (
((-30, 50), {'name': 'foo'}),
((30, 100), {'name': 'bar'}),
((80, 100), {'name': 'baz'}),
)
itree = s_trees.IntervalTree(ivals)
#import pprint
#pprint.pprint(itree.root)
# test a multi-level overlap
names = ... | test_lib_tree_interval | identifier_name |
test_lib_trees.py | from synapse.tests.common import *
import synapse.lib.trees as s_trees
class TreeTest(SynTest):
def test_lib_tree_interval(self):
ivals = (
((-30, 50), {'name': 'foo'}),
((30, 100), {'name': 'bar'}),
((80, 100), {'name': 'baz'}),
)
itree = s_trees.Inte... | self.eq(itree.get(101), [])
self.eq(itree.get(0xffffffff), []) | random_line_split | |
hangouts.py | """
Hangouts notification service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.hangouts/
"""
import logging
import voluptuous as vol
from homeassistant.components.notify import (ATTR_TARGET, PLATFORM_SCHEMA,
... |
messages = []
if 'title' in kwargs:
messages.append({'text': kwargs['title'], 'is_bold': True})
messages.append({'text': message, 'parse_str': True})
service_data = {
ATTR_TARGET: target_conversations,
ATTR_MESSAGE: messages,
}
if kwa... | for target in kwargs.get(ATTR_TARGET):
target_conversations.append({'id': target})
else:
target_conversations = self._default_conversations | random_line_split |
hangouts.py | """
Hangouts notification service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.hangouts/
"""
import logging
import voluptuous as vol
from homeassistant.components.notify import (ATTR_TARGET, PLATFORM_SCHEMA,
... | (hass, config, discovery_info=None):
"""Get the Hangouts notification service."""
return HangoutsNotificationService(config.get(CONF_DEFAULT_CONVERSATIONS))
class HangoutsNotificationService(BaseNotificationService):
"""Send Notifications to Hangouts conversations."""
def __init__(self, default_conve... | get_service | identifier_name |
hangouts.py | """
Hangouts notification service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.hangouts/
"""
import logging
import voluptuous as vol
from homeassistant.components.notify import (ATTR_TARGET, PLATFORM_SCHEMA,
... | """Send the message to the Google Hangouts server."""
target_conversations = None
if ATTR_TARGET in kwargs:
target_conversations = []
for target in kwargs.get(ATTR_TARGET):
target_conversations.append({'id': target})
else:
target_conversations ... | identifier_body | |
hangouts.py | """
Hangouts notification service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.hangouts/
"""
import logging
import voluptuous as vol
from homeassistant.components.notify import (ATTR_TARGET, PLATFORM_SCHEMA,
... |
else:
target_conversations = self._default_conversations
messages = []
if 'title' in kwargs:
messages.append({'text': kwargs['title'], 'is_bold': True})
messages.append({'text': message, 'parse_str': True})
service_data = {
ATTR_TARGET: targ... | target_conversations.append({'id': target}) | conditional_block |
list_companies.py | #!/usr/bin/env python
# Copyright 2019 Google, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
except Error as e:
print('Got exception while listing companies')
raise e
| print('No companies') | conditional_block |
list_companies.py | #!/usr/bin/env python
# Copyright 2019 Google, LLC.
#
# 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 | # 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.
import os
from googleapiclient.discovery import build
from googleapiclient.errors import Error
client_service = build('jobs', 'v3')
project... | #
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, | random_line_split |
health-check.ts | /*
* This file is part of ndb-core.
*
* ndb-core is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* nd... | } else if (this.bmi >= 18 && this.bmi <= 25) {
return WarningLevel.OK;
} else {
return WarningLevel.WARNING;
}
}
} | }
getWarningLevel(): WarningLevel {
if (this.bmi <= 16 || this.bmi >= 30) {
return WarningLevel.URGENT; | random_line_split |
health-check.ts | /*
* This file is part of ndb-core.
*
* ndb-core is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* nd... | (): WarningLevel {
if (this.bmi <= 16 || this.bmi >= 30) {
return WarningLevel.URGENT;
} else if (this.bmi >= 18 && this.bmi <= 25) {
return WarningLevel.OK;
} else {
return WarningLevel.WARNING;
}
}
}
| getWarningLevel | identifier_name |
health-check.ts | /*
* This file is part of ndb-core.
*
* ndb-core is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* nd... | else {
return WarningLevel.WARNING;
}
}
}
| {
return WarningLevel.OK;
} | conditional_block |
health-check.ts | /*
* This file is part of ndb-core.
*
* ndb-core is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* nd... |
getWarningLevel(): WarningLevel {
if (this.bmi <= 16 || this.bmi >= 30) {
return WarningLevel.URGENT;
} else if (this.bmi >= 18 && this.bmi <= 25) {
return WarningLevel.OK;
} else {
return WarningLevel.WARNING;
}
}
}
| {
return this.weight / ((this.height / 100) * (this.height / 100));
} | identifier_body |
graph.py | """
Unit tests for nyx.panel.graph.
"""
import datetime
import unittest
import stem.control
import nyx.curses
import nyx.panel.graph
import test
from test import require_curses
from mock import patch
EXPECTED_BLANK_GRAPH = """
Download:
0 b
0 b
5s 10 15
""".rstrip()
EXPECTED_ACCOUNTING = """
Accoun... | tor_controller_mock().is_alive.return_value = False
rendered = test.render(nyx.panel.graph._draw_accounting_stats, 0, None)
self.assertEqual('Accounting: Connection Closed...', rendered.content) | @require_curses
@patch('nyx.panel.graph.tor_controller')
def test_draw_accounting_stats_disconnected(self, tor_controller_mock): | random_line_split |
graph.py | """
Unit tests for nyx.panel.graph.
"""
import datetime
import unittest
import stem.control
import nyx.curses
import nyx.panel.graph
import test
from test import require_curses
from mock import patch
EXPECTED_BLANK_GRAPH = """
Download:
0 b
0 b
5s 10 15
""".rstrip()
EXPECTED_ACCOUNTING = """
Accoun... |
@require_curses
@patch('nyx.panel.graph.tor_controller')
def test_draw_accounting_stats(self, tor_controller_mock):
tor_controller_mock().is_alive.return_value = True
accounting_stat = stem.control.AccountingStats(
1410723598.276578,
'awake',
datetime.datetime(2014, 9, 14, 19, 41),
... | tor_controller_mock().get_info.return_value = '543,543 421,421 551,551 710,710 200,200 175,175 188,188 250,250 377,377'
data = nyx.panel.graph.BandwidthStats()
rendered = test.render(nyx.panel.graph._draw_subgraph, data.primary, 0, 30, 7, nyx.panel.graph.Bounds.LOCAL_MAX, nyx.panel.graph.Interval.EACH_SECOND, ... | identifier_body |
graph.py | """
Unit tests for nyx.panel.graph.
"""
import datetime
import unittest
import stem.control
import nyx.curses
import nyx.panel.graph
import test
from test import require_curses
from mock import patch
EXPECTED_BLANK_GRAPH = """
Download:
0 b
0 b
5s 10 15
""".rstrip()
EXPECTED_ACCOUNTING = """
Accoun... |
def test_y_axis_labels(self):
data = nyx.panel.graph.ConnectionStats()
# check with both even and odd height since that determines an offset in the middle
self.assertEqual({2: '10', 4: '7', 6: '5', 9: '2', 11: '0'}, nyx.panel.graph._y_axis_labels(12, data.primary, 0, 10))
self.assertEqual({2: '10'... | self.assertEqual(expected, nyx.panel.graph._x_axis_labels(interval, 80)) | conditional_block |
graph.py | """
Unit tests for nyx.panel.graph.
"""
import datetime
import unittest
import stem.control
import nyx.curses
import nyx.panel.graph
import test
from test import require_curses
from mock import patch
EXPECTED_BLANK_GRAPH = """
Download:
0 b
0 b
5s 10 15
""".rstrip()
EXPECTED_ACCOUNTING = """
Accoun... | (unittest.TestCase):
def test_x_axis_labels(self):
test_inputs = {
0: {},
7: {},
10: {5: '25s'},
15: {5: '25s', 10: '50'},
20: {5: '25s', 10: '50', 15: '1m'},
25: {5: '25s', 10: '50', 15: '1m', 20: '1.6'},
45: {5: '25s', 10: '50', 15: '1m', 20: '1.6', 25: '2.0', 30: '2.5'... | TestGraphPanel | identifier_name |
pageContainer.tsx | import * as React from 'react';
import * as toastr from 'toastr';
import {hashHistory} from 'react-router';
import {routeConstants} from '../../common/constants/routeConstants';
import {loginAPI} from '../../rest-api/login/loginAPI';
import {LoginCredentials} from '../../models/loginCredentials';
import {UserProfile} f... | // Other way to assign new object to loginCredentials to avoid mutation is:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
/*
var newLoginCredentiasl = Object.assign({}, this.state.loginCredentials, {
[fieldName]: value,
});
*/
// We are use a J... | loginCredentials: new LoginCredentials(),
};
}
| random_line_split |
pageContainer.tsx | import * as React from 'react';
import * as toastr from 'toastr';
import {hashHistory} from 'react-router';
import {routeConstants} from '../../common/constants/routeConstants';
import {loginAPI} from '../../rest-api/login/loginAPI';
import {LoginCredentials} from '../../models/loginCredentials';
import {UserProfile} f... | () {
return (
<LoginPage
loginCredentials={this.state.loginCredentials}
updateLoginInfo={this.updateLoginInfo.bind(this)}
loginRequest={this.loginRequest.bind(this)}
/>
);
}
}
| render | identifier_name |
pageContainer.tsx | import * as React from 'react';
import * as toastr from 'toastr';
import {hashHistory} from 'react-router';
import {routeConstants} from '../../common/constants/routeConstants';
import {loginAPI} from '../../rest-api/login/loginAPI';
import {LoginCredentials} from '../../models/loginCredentials';
import {UserProfile} f... |
// Other way to assign new object to loginCredentials to avoid mutation is:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
/*
var newLoginCredentiasl = Object.assign({}, this.state.loginCredentials, {
[fieldName]: value,
});
*/
// We are use a... | {
super();
this.state = {
loginCredentials: new LoginCredentials(),
};
} | identifier_body |
config.py | #! /usr/bin/env python
# coding:utf-8
# レコードファイルがあるディレクトリ
# デフォルトではこのスクリプトファイルが存在する
# ディレクトリにある zones/ 以下に配置する
zone_dir = "testzones"
# 生成した HTML をおくディレクトリ
html_dir = "build"
# レコードに関する情報をおいているディレクトリ
record_info_dir = "testzones" | a_record_filenames = [
"example.jp.zone",
]
# PTR レコードのゾーンファイル名そのネットワーク
ptr_record_filename_networks = [
('192.168.0.rev', '192.168.0.0/24'),
]
# レコード情報を納めたファイル
record_info_filenames = [
'192.168.0.info',
] |
# A レコードのゾーンファイル名 | random_line_split |
config-test.ts | /* tslint:disable:no-sync-functions */
import { expect } from 'chai'
import { Repository } from '../../../src/models/repository'
import {
getConfigValue,
getGlobalConfigPath,
getGlobalConfigValue,
setGlobalConfigValue,
} from '../../../src/lib/git'
import { GitProcess } from 'dugite'
import { setupFixtureRepo... | })
}) | )
}) | random_line_split |
metrix++.py | #
# Metrix++, Copyright 2009-2013, Metrix++ Project
# Link: http://metrixplusplus.sourceforge.net
#
# This file is a part of Metrix++ Tool.
#
# Metrix++ is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the ... | metrixpp.start() | import metrixpp
| random_line_split |
metrix++.py | #
# Metrix++, Copyright 2009-2013, Metrix++ Project
# Link: http://metrixplusplus.sourceforge.net
#
# This file is a part of Metrix++ Tool.
#
# Metrix++ is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the ... | import metrixpp
metrixpp.start() | conditional_block | |
test_geocoding.py | # -*- coding: utf-8 -*-
import pytest
from gmaps import errors
from gmaps import Geocoding
from .testutils import retry
geocoding = Geocoding(sensor=False)
@retry
def test_geocode():
results = geocoding.geocode(u"Wrocław, Hubska")
assert results
assert len(results) > 0
@retry
def test_geocode_override... |
@retry
def test_geocode_no_results_exception():
components = {"administrative_area": "TZ", "country": "FR"}
with pytest.raises(errors.NoResults):
geocoding.geocode(components)
@retry
def test_geocode_language():
results = geocoding.geocode(u"Wrocław, Hubska", language='pl')
assert 'Polska' in... | results_with_address = geocoding.geocode(components=components)
results_without_address = geocoding.geocode(address)
assert results_with_address[0]['geometry']['location'] == \
results_without_address[0]['geometry']['location']
| random_line_split |
test_geocoding.py | # -*- coding: utf-8 -*-
import pytest
from gmaps import errors
from gmaps import Geocoding
from .testutils import retry
geocoding = Geocoding(sensor=False)
@retry
def test_geocode():
results = geocoding.geocode(u"Wrocław, Hubska")
assert results
assert len(results) > 0
@retry
def test_geocode_override... | results = geocoding.reverse(lat=51.213, lon=21.213, sensor=True)
assert results
assert len(results) > 0
@retry
def test_reverse_language():
results = geocoding.reverse(lat=51.213, lon=21.213, language='pl')
assert results
# given lat lon are position somwhere in poland so test if there is
# 'P... | erse_override_sensor():
| identifier_name |
test_geocoding.py | # -*- coding: utf-8 -*-
import pytest
from gmaps import errors
from gmaps import Geocoding
from .testutils import retry
geocoding = Geocoding(sensor=False)
@retry
def test_geocode():
results = geocoding.geocode(u"Wrocław, Hubska")
assert results
assert len(results) > 0
@retry
def test_geocode_override... | y
def test_geocode_bounds():
results1 = geocoding.geocode("Winnetka", bounds=(
(42.1282269, -87.71095989999999), (42.0886089, -87.7708363)))
results2 = geocoding.geocode("Winnetka", bounds=(
(34.172684, -118.604794), (34.236144, -118.500938)))
assert results1[0]['formatted_address'] != resul... | = geocoding.geocode("Toledo", region="us")
assert 'USA' in results[0]['formatted_address']
results = geocoding.geocode("Toledo", region="es")
assert 'Spain' in results[0]['formatted_address']
@retr | identifier_body |
bigquerydatatransfer_v1_generated_data_transfer_service_get_data_source_sync.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
# [END bigquerydatatransfer_v1_generated_DataTransferService_GetDataSource_sync]
| client = bigquery_datatransfer_v1.DataTransferServiceClient()
# Initialize request argument(s)
request = bigquery_datatransfer_v1.GetDataSourceRequest(
name="name_value",
)
# Make the request
response = client.get_data_source(request=request)
# Handle the response
print(response) | identifier_body |
bigquerydatatransfer_v1_generated_data_transfer_service_get_data_source_sync.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | ():
# Create a client
client = bigquery_datatransfer_v1.DataTransferServiceClient()
# Initialize request argument(s)
request = bigquery_datatransfer_v1.GetDataSourceRequest(
name="name_value",
)
# Make the request
response = client.get_data_source(request=request)
# Handle the... | sample_get_data_source | identifier_name |
bigquerydatatransfer_v1_generated_data_transfer_service_get_data_source_sync.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Handle the response
print(response)
# [END bigquerydatatransfer_v1_generated_DataTransferService_GetDataSource_sync] | )
# Make the request
response = client.get_data_source(request=request)
| random_line_split |
common.py | from datetime import date
class YearInfo(object):
def __init__(self, year, months_ok, months_na):
self.year = year
self.months = set(range(1, 13))
self.months_ok = set(months_ok)
self.months_na = set(months_na)
self.months_er = self.months - (self.months_ok | self.months_na)... |
return True
def missing_months(payments_list):
plist = payments_by_month(payments_list)
missing = []
for yi in plist:
if yi.missing():
for month in yi.months_er:
missing.append((yi.year, month))
return missing
| if year.missing():
return False | conditional_block |
common.py | from datetime import date
class | (object):
def __init__(self, year, months_ok, months_na):
self.year = year
self.months = set(range(1, 13))
self.months_ok = set(months_ok)
self.months_na = set(months_na)
self.months_er = self.months - (self.months_ok | self.months_na)
today = date.today()
if... | YearInfo | identifier_name |
common.py | from datetime import date | self.months = set(range(1, 13))
self.months_ok = set(months_ok)
self.months_na = set(months_na)
self.months_er = self.months - (self.months_ok | self.months_na)
today = date.today()
if self.year == today.year:
self.months_er -= set(range(today.month, 13))
... |
class YearInfo(object):
def __init__(self, year, months_ok, months_na):
self.year = year | random_line_split |
common.py | from datetime import date
class YearInfo(object):
def __init__(self, year, months_ok, months_na):
self.year = year
self.months = set(range(1, 13))
self.months_ok = set(months_ok)
self.months_na = set(months_na)
self.months_er = self.months - (self.months_ok | self.months_na)... |
def payments_by_month(payments_list):
monthly_data = set()
if not payments_list:
return []
for payment in payments_list:
for m in payment.formonths():
monthly_data.add(m)
since_year = payment.user.date_joined.year
since_month = payment.user.date_joined.month
years... | return len(self.months_er) != 0 | identifier_body |
exercise.py | #!/usr/bin/python
from __future__ import unicode_literals
import os
def wait():
raw_input('\nPress Enter to continue...\n\n')
os.system(['clear', 'cls'][os.name == 'nt'])
# Create a class to handle items in a wallet
class BaseWalletHandler(object):
def __init__(self):
self.items = {
... |
def exercise():
wallet_handler = BaseWalletHandler()
wallet_handler.add_item('Driver\'s License')
wallet_handler.add_item('ICE Info')
wallet_handler.add_item('Credit Card')
wallet_handler.add_item('Business Card')
wallet_handler.show_items()
wait()
wallet_handler = WalletHandler()
... | def add_item(self, item):
super(WalletHandler, self).add_item(item)
if item not in self.items.keys():
self.items[item] = True | random_line_split |
exercise.py | #!/usr/bin/python
from __future__ import unicode_literals
import os
def wait():
raw_input('\nPress Enter to continue...\n\n')
os.system(['clear', 'cls'][os.name == 'nt'])
# Create a class to handle items in a wallet
class BaseWalletHandler(object):
def __init__(self):
self.items = {
... |
# Can more refactoring happen to clean this up more?
class WalletHandler(BaseWalletHandler):
def __init__(self):
super(WalletHandler, self).__init__()
def add_item(self, item):
super(WalletHandler, self).add_item(item)
if item not in self.items.keys():
self.items[item] = ... | print key | conditional_block |
exercise.py | #!/usr/bin/python
from __future__ import unicode_literals
import os
def wait():
raw_input('\nPress Enter to continue...\n\n')
os.system(['clear', 'cls'][os.name == 'nt'])
# Create a class to handle items in a wallet
class BaseWalletHandler(object):
def __init__(self):
self.items = {
... |
# Can more refactoring happen to clean this up more?
class WalletHandler(BaseWalletHandler):
def __init__(self):
super(WalletHandler, self).__init__()
def add_item(self, item):
super(WalletHandler, self).add_item(item)
if item not in self.items.keys():
self.items[item] = ... | for key, value in self.items.items():
if value is True:
print key | identifier_body |
exercise.py | #!/usr/bin/python
from __future__ import unicode_literals
import os
def wait():
raw_input('\nPress Enter to continue...\n\n')
os.system(['clear', 'cls'][os.name == 'nt'])
# Create a class to handle items in a wallet
class BaseWalletHandler(object):
def __init__(self):
self.items = {
... | (self, item):
if item in self.items.keys():
self.items[item] = True
def remove_item(self, item):
if item in self.items.keys():
self.items[item] = False
def show_items(self):
for key, value in self.items.items():
if value is True:
prin... | add_item | identifier_name |
hellojs.d.ts | // Type definitions for hello.js 0.2.3
// Project: http://adodson.com/hello.js/
// Definitions by: Pavel Zika <https://github.com/PavelPZ>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface HelloJSLoginOptions {
redirect_uri?: string;
display?: string;
scope?: string;
respons... | xhr?: (par: any) => void;
jsonp?: (par: any) => void;
form?: (par: any) => void;
api?: (...par: any[]) => void;
}
declare var hello: HelloJSStatic; | get?: { [id: string]: any; };
post?: { [id: string]: any; };
del?: { [id: string]: string; };
put?: { [id: string]: any; };
wrap?: { [id: string]: (par: any) => void; }; | random_line_split |
unittest_cst.py | """
@file
@brief Helpers to compress constant used in unit tests.
"""
import base64
import json
import lzma
import pprint
def compress_cst(data, length=70, as_text=False):
"""
Transforms a huge constant into a sequence of compressed binary strings.
:param data: data
:param length: line length
:pa... |
if as_text:
return pprint.pformat(bufs) # pragma: no cover
return bufs
def decompress_cst(data):
"""
Transforms a huge constant produced by function @see fn compress_cst
into the original value.
:param data: data
:param length: line length
:param as_text: returns the results... | bufs.append(data64[pos:])
pos = len(data64) | conditional_block |
unittest_cst.py | """
@file
@brief Helpers to compress constant used in unit tests.
"""
import base64
import json
import lzma
import pprint
def compress_cst(data, length=70, as_text=False):
"""
Transforms a huge constant into a sequence of compressed binary strings.
:param data: data
:param length: line length
:pa... | pos += length
else:
bufs.append(data64[pos:])
pos = len(data64)
if as_text:
return pprint.pformat(bufs) # pragma: no cover
return bufs
def decompress_cst(data):
"""
Transforms a huge constant produced by function @see fn compress_cst
into the or... | bufs.append(data64[pos:pos + length]) | random_line_split |
unittest_cst.py | """
@file
@brief Helpers to compress constant used in unit tests.
"""
import base64
import json
import lzma
import pprint
def compress_cst(data, length=70, as_text=False):
"""
Transforms a huge constant into a sequence of compressed binary strings.
:param data: data
:param length: line length
:pa... | (data):
"""
Transforms a huge constant produced by function @see fn compress_cst
into the original value.
:param data: data
:param length: line length
:param as_text: returns the results as text
:return: results
.. runpython::
:showcode:
from pyquickhelper.pycode.unitt... | decompress_cst | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.