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 |
|---|---|---|---|---|
setup_py2exe.py | of the DiRefl application. For testing
purposes, direfl.exe can be run from the dist directory.
"""
import os
import sys
'''
print "*** Python path is:"
for i, p in enumerate(sys.path):
print "%5d %s" %(i, p)
'''
from distutils.core import setup
# Augment the setup interface with the py2exe command and make ... |
elif sys.version_info >= (2, 6):
manifest = manifest_for_python26
elif sys.version_info >= (2, 5):
manifest = manifest_for_python25
# Create a list of all files to include along side the executable being built
# in the dist directory tree. Each element of the data_files list is a tuple
# consisting of a path... | print "*** This script only works with Python 2.5, 2.6, or 2.7."
sys.exit() | conditional_block |
setup_py2exe.py | of the DiRefl application. For testing
purposes, direfl.exe can be run from the dist directory.
"""
import os
import sys
'''
print "*** Python path is:"
for i, p in enumerate(sys.path):
print "%5d %s" %(i, p)
'''
from distutils.core import setup
# Augment the setup interface with the py2exe command and make ... |
client = Target(
name = 'DiRefl',
description = 'Direct Inversion Reflectometry (DiRefl) application',
script = 'bin/direfl.py', # module to run on application start
dest_base = 'direfl', # file name part of the exe file to create
icon_resources = [(1, 'direfl.ico')], # also need to specify in ... | self.__dict__.update(kw)
self.version = version | identifier_body |
histogram.ts | import {JobState} from "../api/prow";
export class JobHistogram {
public start: number;
public end: number;
private data: JobSample[];
constructor() {
this.data = [];
this.start = Number.MAX_SAFE_INTEGER;
this.end = 0;
}
// add adds a sample to the histogram, filtering states that didn't... |
if (sample.start > this.end) {
this.end = sample.start;
}
this.data.push(sample);
}
// buckets assigns all samples between start and end into cols buckets, sorted by
// start timestamp, while the buckets themselves are sorted by duration.
public buckets(start: number, end: number, c... | {
this.start = sample.start;
} | conditional_block |
histogram.ts | import {JobState} from "../api/prow";
export class JobHistogram {
public start: number;
public end: number;
private data: JobSample[];
constructor() {
this.data = [];
this.start = Number.MAX_SAFE_INTEGER;
this.end = 0;
}
// add adds a sample to the histogram, filtering states that didn't... | bucket.sort((s1, s2) => s1.duration - s2.duration);
next = next + stride;
while (next < sample.start) {
buckets.push([]);
next = next + stride;
}
buckets.push([sample]);
});
if (buckets.length > 0) {
const lastBucket = ... | {
this.data.sort((s1, s2) => s1.start - s2.start);
const buckets: JobSample[][] = [[]];
const stride = (end - start) / cols;
let next = start + stride;
let max = 0;
this.data.forEach((sample) => {
if (sample.start < start || sample.start > end) {
return;
... | identifier_body |
histogram.ts | import {JobState} from "../api/prow";
export class JobHistogram {
public start: number;
public end: number;
private data: JobSample[];
constructor() {
this.data = [];
this.start = Number.MAX_SAFE_INTEGER;
this.end = 0;
}
// add adds a sample to the histogram, filtering states that didn't... | (bucket: JobSample[], rows: number): JobSample[][] {
const stride = Math.ceil((this.max) / rows);
const chunks: JobSample[][] = [];
chunks[0] = [];
let next = stride;
for (const sample of bucket) {
if (sample.duration <= next) {
chunks[chunks.length - 1].push(sample... | linearChunks | identifier_name |
histogram.ts | import {JobState} from "../api/prow";
export class JobHistogram {
public start: number;
public end: number;
private data: JobSample[];
constructor() {
this.data = [];
this.start = Number.MAX_SAFE_INTEGER;
this.end = 0;
}
// add adds a sample to the histogram, filtering states that didn't... | chunks.push([]);
next = next + stride;
}
if (chunks.length > (rows - 1)) {
chunks[chunks.length - 1].push(sample);
} else {
chunks.push([sample]);
}
}
if (chunks.length > rows) {
throw new Error("invalid rows");
... | break;
} | random_line_split |
wechat_pay.js | import slayer from "./s_layer";
let params;
export function jsApiCall(callback) {
WeixinJSBridge.invoke(
'getBrandWCPayRequest',
params,
function (res) {
if (res.err_msg == "get_brand_wcpay_request:ok") {
slayer.alert('支付成功');
if (callback) {
callback();
}
}... | pay(jsApiParams, callback) {
params = jsApiParams;
callpay(callback);
}
} | }
export default { | random_line_split |
wechat_pay.js | import slayer from "./s_layer";
let params;
export function jsApiCall(callback) {
WeixinJSBridge.invoke(
'getBrandWCPayRequest',
params,
function (res) {
if (res.err_msg == "get_brand_wcpay_request:ok") {
slayer.alert('支付成功');
if (callback) {
callback();
}
}... | ck) {
params = jsApiParams;
callpay(callback);
}
}
| lba | identifier_name |
wechat_pay.js | import slayer from "./s_layer";
let params;
export function jsApiCall(callback) {
WeixinJSBridge.invoke(
'getBrandWCPayRequest',
params,
function (res) {
if (res.err_msg == "get_brand_wcpay_request:ok") {
slayer.alert('支付成功');
if (callback) {
callback();
}
}... | t function callpay(callback) {
if (typeof('WeixinJSBridge') == "undefined") {
if (document.addEventListener) {
document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
} else if (document.attachEvent) {
document.attachEvent('WeixinJSBridgeReady', jsApiCall);
document.attachEvent('... | slayer.alert('用户取消支付');
}
}
);
}
expor | conditional_block |
wechat_pay.js | import slayer from "./s_layer";
let params;
export function jsApiCall(callback) {
WeixinJSBridge.invoke(
'getBrandWCPayRequest',
params,
function (res) {
if (res.err_msg == "get_brand_wcpay_request:ok") {
slayer.alert('支付成功');
if (callback) {
callback();
}
}... | Params;
callpay(callback);
}
}
| identifier_body | |
Table.controller.js | './Formatter',
'sap/ui/core/mvc/Controller',
'sap/ui/model/json/JSONModel',
'sap/m/ColumnListItem',
'sap/m/Input',
'sap/m/MessageToast'
], function(deepExtend, Formatter, Controller, JSONModel, ColumnListItem, Input, MessageToast) {
"use strict";
var TableController = Controller.extend("sap.m.sample.TableEdita... | sap.ui.define([
'sap/base/util/deepExtend', | random_line_split | |
db.py | import logging
from datetime import datetime
from core import app
from sqlalchemy import inspect
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
class Show(db.Model):
show_id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
link = db.Column(db.String(255))
c... | self.air_date = air_date
self.title = title
self.link = link
self.watched = watched
def is_older(self, dt=datetime.now().date()):
return self.air_date < dt
def insert_show(show):
db.session.add(show)
db.session.commit()
def insert_entity(entity):
db.session.... | episode_id = db.Column(db.Integer, primary_key=True)
show_id = db.Column(db.Integer, db.ForeignKey('show.show_id'))
episode_number = db.Column(db.Integer)
season_number = db.Column(db.Integer)
season_episode_number = db.Column(db.Integer)
air_date = db.Column(db.Date)
title = db.Column(db.String... | identifier_body |
db.py | import logging
from datetime import datetime
from core import app
from sqlalchemy import inspect
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
class Show(db.Model):
show_id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
link = db.Column(db.String(255))
c... |
def drop_tables():
logging.info('Deleting tables')
db.drop_all()
def check_table_exists():
table_names = inspect(db.engine).get_table_names()
return 'episode' in table_names and 'show' in table_names
if __name__ == '__main__':
import sys
app.config['SQLALCHEMY_ECHO'] = True
if sys.arg... | random_line_split | |
db.py | import logging
from datetime import datetime
from core import app
from sqlalchemy import inspect
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
class Show(db.Model):
show_id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
link = db.Column(db.String(255))
c... | (entity):
db.session.add(entity)
db.session.commit()
def show_exists(show_id):
show = Show.query.filter_by(show_id=show_id).first()
return show is not None
def delete_show(show_id):
show = Show.query.filter_by(show_id=show_id).first()
db.session.delete(show)
for e in Episode.query.filter... | insert_entity | identifier_name |
db.py | import logging
from datetime import datetime
from core import app
from sqlalchemy import inspect
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
class Show(db.Model):
show_id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
link = db.Column(db.String(255))
c... | create_tables() | conditional_block | |
rest.py | from datetime import datetime
from flask import Blueprint, jsonify, request
from app.dao.fact_notification_status_dao import (
get_total_notifications_for_date_range,
)
from app.dao.fact_processing_time_dao import (
get_processing_time_percentage_for_date_range,
)
from app.dao.services_dao import get_live_ser... |
return j
def transform_processing_time_results_to_json(processing_time_results):
j = []
for x in processing_time_results:
j.append({"date": x.date, "percentage_under_10_seconds": x.percentage})
return j
def transform_services_to_json(services_results):
j = []
for x in services_resu... | j.append({"date": x.bst_date, "emails": x.emails, "sms": x.sms, "letters": x.letters}) | conditional_block |
rest.py | from datetime import datetime
from flask import Blueprint, jsonify, request
from app.dao.fact_notification_status_dao import (
get_total_notifications_for_date_range,
)
from app.dao.fact_processing_time_dao import (
get_processing_time_percentage_for_date_range,
)
from app.dao.services_dao import get_live_ser... | j = []
for x in services_results:
j.append({"service_id": x.service_id, "service_name": x.service_name,
"organisation_id": x.organisation_id, "organisation_name": x.organisation_name}
)
return j | identifier_body | |
rest.py | from datetime import datetime
from flask import Blueprint, jsonify, request
from app.dao.fact_notification_status_dao import (
get_total_notifications_for_date_range,
)
from app.dao.fact_processing_time_dao import (
get_processing_time_percentage_for_date_range,
)
from app.dao.services_dao import get_live_ser... | "processing_time": transform_processing_time_results_to_json(processing_time_results),
"live_service_count": len(services),
"services_using_notify": transform_services_to_json(services)
}
return jsonify(stats)
def transform_results_into_totals(total_notifications_results):
total_... | "total_notifications": total_notifications,
"email_notifications": emails,
"sms_notifications": sms,
"letter_notifications": letters,
"notifications_by_type": transform_into_notification_by_type_json(totals_for_date_range), | random_line_split |
rest.py | from datetime import datetime
from flask import Blueprint, jsonify, request
from app.dao.fact_notification_status_dao import (
get_total_notifications_for_date_range,
)
from app.dao.fact_processing_time_dao import (
get_processing_time_percentage_for_date_range,
)
from app.dao.services_dao import get_live_ser... | (total_notifications):
j = []
for x in total_notifications:
j.append({"date": x.bst_date, "emails": x.emails, "sms": x.sms, "letters": x.letters})
return j
def transform_processing_time_results_to_json(processing_time_results):
j = []
for x in processing_time_results:
j.append({"da... | transform_into_notification_by_type_json | identifier_name |
build-declarations.test.js | import assert from 'assert'
import {
default as buildDeclarations,
buildSingleDeclaration,
isArray
} from '../../lib/utils/build-declarations'
describe('buildDeclarations function', () => {
it('should return a string with the css declarations', () => {
const actual = buildDeclarations({
borderRadius:... |
it('should handle vendor prefixes generated by css-prefix', () => {
const actual = buildDeclarations({
display: ['-webkit-flex', 'flex']
})
const expected = 'display:-webkit-flex;display:flex;'
assert.strictEqual(actual, expected)
})
it('should ignore declarations that include pseudo selec... | assert.strictEqual(actual, expected)
}) | random_line_split |
msgfmt.py | #! /usr/bin/env python3
# Written by Martin v. Löwis <loewis@informatik.hu-berlin.de>
"""Generate binary message catalog from textual translation description.
This program converts a textual Uniforum-style message catalog (.po file) into
a binary GNU catalog (.mo file). This is essentially the same function as the
G... |
def generate():
"Return the generated output."
global MESSAGES
# the keys are sorted in the .mo file
keys = sorted(MESSAGES.keys())
offsets = []
ids = strs = b''
for id in keys:
# For each string, we need size and file offset. Each string is NUL
# terminated; the NUL doe... | ESSAGES[id] = str
| conditional_block |
msgfmt.py | #! /usr/bin/env python3
# Written by Martin v. Löwis <loewis@informatik.hu-berlin.de>
"""Generate binary message catalog from textual translation description.
This program converts a textual Uniforum-style message catalog (.po file) into
a binary GNU catalog (.mo file). This is essentially the same function as the
G... | return
for filename in args:
make(filename, outfile)
if __name__ == '__main__':
main()
| ry:
opts, args = getopt.getopt(sys.argv[1:], 'hVo:',
['help', 'version', 'output-file='])
except getopt.error as msg:
usage(1, msg)
outfile = None
# parse options
for opt, arg in opts:
if opt in ('-h', '--help'):
usage(0)
el... | identifier_body |
msgfmt.py | #! /usr/bin/env python3
# Written by Martin v. Löwis <loewis@informatik.hu-berlin.de>
"""Generate binary message catalog from textual translation description.
This program converts a textual Uniforum-style message catalog (.po file) into
a binary GNU catalog (.mo file). This is essentially the same function as the
G... | id, str, fuzzy):
"Add a non-fuzzy translation to the dictionary."
global MESSAGES
if not fuzzy and str:
MESSAGES[id] = str
def generate():
"Return the generated output."
global MESSAGES
# the keys are sorted in the .mo file
keys = sorted(MESSAGES.keys())
offsets = []
ids ... | dd( | identifier_name |
msgfmt.py | #! /usr/bin/env python3
# Written by Martin v. Löwis <loewis@informatik.hu-berlin.de>
"""Generate binary message catalog from textual translation description.
This program converts a textual Uniforum-style message catalog (.po file) into
a binary GNU catalog (.mo file). This is essentially the same function as the
G... |
def generate():
"Return the generated output."
global MESSAGES
# the keys are sorted in the .mo file
keys = sorted(MESSAGES.keys())
offsets = []
ids = strs = b''
for id in keys:
# For each string, we need size and file offset. Each string is NUL
# terminated; the NUL does ... | random_line_split | |
local_ptr.rs | is optimized:
//
// mov %fs:0x0, %r14
// mov -0x8(%r14), %rbx
// // do something with %rbx, the rust Task pointer
//
// ... // <- do more things
//
// mov -0x8(%r14), %rbx
// // do something else with %rbx
//
// Note that the optimization done h... | mem::transmute(realrustrt::shouldnt_be_public::maybe_tls_key())
}
} | random_line_split | |
local_ptr.rs | 8;
pub fn init() {}
pub unsafe fn cleanup() {}
// Rationale for all of these functions being inline(never)
//
// The #[thread_local] annotation gets propagated all the way through to
// LLVM, meaning the global is specially treated by LLVM to lower it to an
// efficient sequence of instru... | {
None
} | conditional_block | |
local_ptr.rs | , the
/// pointer is returned.
pub struct Borrowed<T> {
val: *const (),
}
#[unsafe_destructor]
impl<T> Drop for Borrowed<T> {
fn drop(&mut self) {
unsafe {
if self.val.is_null() {
rtabort!("Aiee, returning null borrowed object!");
}
let val: Box<T> = ... | <T>() -> Borrowed<T> {
let val: *const () = mem::transmute(take::<T>());
Borrowed {
val: val,
}
}
/// Compiled implementation of accessing the runtime local pointer. This is
/// implemented using LLVM's thread_local attribute which isn't necessarily
/// working on all platforms. This implementation... | borrow | identifier_name |
gather_moves.rs | // Copyright 2012-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-MI... | (bccx: &BorrowckCtxt,
move_data: &mut MoveData,
assignment_id: ast::NodeId,
assignment_span: Span,
assignee_loan_path: @LoanPath,
assignee_id: ast::NodeId) {
move_data.add_assignment(bccx.tcx... | gather_assignment | identifier_name |
gather_moves.rs | // Copyright 2012-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-MI... |
match opt_loan_path(cmt) {
Some(loan_path) => {
move_data.add_move(bccx.tcx, loan_path, move_id, move_kind);
}
None => {
// move from rvalue or unsafe pointer, hence ok
}
}
}
pub fn gather_captures(bccx: &BorrowckCtxt,
move_data: &... | if !check_is_legal_to_move_from(bccx, cmt, cmt) {
return;
} | random_line_split |
gather_moves.rs | // Copyright 2012-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-MI... |
pub fn gather_move_from_pat(bccx: &BorrowckCtxt,
move_data: &mut MoveData,
move_pat: @ast::Pat,
cmt: mc::cmt) {
gather_move_from_expr_or_pat(bccx, move_data, move_pat.id,
MovePat(move_pat), cmt);
}... | {
gather_move_from_expr_or_pat(bccx, move_data, move_expr.id,
MoveExpr(move_expr), cmt);
} | identifier_body |
08b6358a04bf_txnreconcile_allow_txn_id_to_be_null.py | """TxnReconcile allow txn_id to be null
Revision ID: 08b6358a04bf
Revises: 04e61490804b
Create Date: 2018-03-07 19:48:06.050926
"""
from alembic import op
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '08b6358a04bf'
down_revision = '04e61490804b'
branch_labels = None
depen... | )
conn.execute("SET FOREIGN_KEY_CHECKS=1") | random_line_split | |
08b6358a04bf_txnreconcile_allow_txn_id_to_be_null.py | """TxnReconcile allow txn_id to be null
Revision ID: 08b6358a04bf
Revises: 04e61490804b
Create Date: 2018-03-07 19:48:06.050926
"""
from alembic import op
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '08b6358a04bf'
down_revision = '04e61490804b'
branch_labels = None
depen... |
def downgrade():
conn = op.get_bind()
conn.execute("SET FOREIGN_KEY_CHECKS=0")
op.alter_column(
'txn_reconciles', 'txn_id',
existing_type=mysql.INTEGER(display_width=11),
nullable=False
)
conn.execute("SET FOREIGN_KEY_CHECKS=1")
| op.alter_column(
'txn_reconciles', 'txn_id',
existing_type=mysql.INTEGER(display_width=11),
nullable=True
) | identifier_body |
08b6358a04bf_txnreconcile_allow_txn_id_to_be_null.py | """TxnReconcile allow txn_id to be null
Revision ID: 08b6358a04bf
Revises: 04e61490804b
Create Date: 2018-03-07 19:48:06.050926
"""
from alembic import op
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '08b6358a04bf'
down_revision = '04e61490804b'
branch_labels = None
depen... | ():
op.alter_column(
'txn_reconciles', 'txn_id',
existing_type=mysql.INTEGER(display_width=11),
nullable=True
)
def downgrade():
conn = op.get_bind()
conn.execute("SET FOREIGN_KEY_CHECKS=0")
op.alter_column(
'txn_reconciles', 'txn_id',
existing_type=mysql.IN... | upgrade | identifier_name |
InsertStream_test.js | import assert from 'assert';
import sinon from 'sinon';
import fs from 'fs';
import stream from 'stream';
import { InsertStream } from '../';
/**
* Transform class to turn our string JSON data into objects.
*/
class TransformToObject extends stream.Transform {
| () {
super({objectMode:true});
}
_transform(data, encoding, cb) {
data.split('\n')
.filter(line => line.length)
.forEach(line => this.push(JSON.parse(line)));
cb();
}
}
function getSpies() {
const insertSpy = sinon.spy();
const insertManySpy = sinon.spy();
const collection = {
... | constructor | identifier_name |
InsertStream_test.js | import assert from 'assert';
import sinon from 'sinon';
import fs from 'fs';
import stream from 'stream';
import { InsertStream } from '../';
/**
* Transform class to turn our string JSON data into objects.
*/
class TransformToObject extends stream.Transform {
constructor() {
super({objectMode:true});
}
... |
};
return [insertSpy, insertManySpy, collection];
}
function getOption(opts) {
return {
highWaterMark: opts.highWaterMark,
collectionName: 'test-collection',
db: {
collection: function(name, cb) {
cb(opts.err, opts.collection);
}
}
};
}
function createTestStream(highWater... | {
insertManySpy(data);
cb();
} | identifier_body |
InsertStream_test.js | import assert from 'assert';
import sinon from 'sinon';
import fs from 'fs';
import stream from 'stream';
import { InsertStream } from '../';
/**
* Transform class to turn our string JSON data into objects.
*/
class TransformToObject extends stream.Transform {
constructor() {
super({objectMode:true});
}
... | createTestStream(1, {}, stream => {
stream.on('error', () => {
assert.ok(true);
done();
});
});
} | export function testError(done) { | random_line_split |
main.rs | ();
let usage = caps.supported_usage_flags;
let format = caps.supported_formats[0].0;
vulkano::swapchain::Swapchain::new(&device, &window.surface(), caps.min_image_count, format, dimensions, 1,
&usage, &queue, vulkano::swapchain::SurfaceTransform::Iden... |
(cgmath::Point3::new(4.0, 0.6, 0.0), cgmath::Vector3::new(0.0, -1.0, 0.0))
} | conditional_block | |
main.rs | // furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WA... | // copies of the Software, and to permit persons to whom the Software is | random_line_split | |
main.rs | concat!(env!("OUT_DIR"), "/shaders/src/bin/chess_vs.glsl")} }
mod fs { include!{concat!(env!("OUT_DIR"), "/shaders/src/bin/chess_fs.glsl")} }
mod data;
mod model;
mod chess;
mod system;
mod graphics;
use model::Model;
use system::System;
use graphics::{GraphicsEngine, Matrices};
mod renderpass {
single_pass_rende... | let (device, mut queues) = vulkano::device::Device::new(&physical, physical.supported_features(),
&device_ext, [(queue, 0.5)].iter().cloned())
.expect("failed to create device");
let queue = queues.next().unwrap();
l... |
// Set up lots of stuff ... see vulkano examples
let extensions = vulkano_win::required_extensions();
let instance = vulkano::instance::Instance::new(None, &extensions, None).expect("failed to create instance");
let physical = vulkano::instance::PhysicalDevice::enumerate(&instance)
... | identifier_body |
main.rs | concat!(env!("OUT_DIR"), "/shaders/src/bin/chess_vs.glsl")} }
mod fs { include!{concat!(env!("OUT_DIR"), "/shaders/src/bin/chess_fs.glsl")} }
mod data;
mod model;
mod chess;
mod system;
mod graphics;
use model::Model;
use system::System;
use graphics::{GraphicsEngine, Matrices};
mod renderpass {
single_pass_rende... | ) {
// Set up lots of stuff ... see vulkano examples
let extensions = vulkano_win::required_extensions();
let instance = vulkano::instance::Instance::new(None, &extensions, None).expect("failed to create instance");
let physical = vulkano::instance::PhysicalDevice::enumerate(&instance)
... | ain( | identifier_name |
App.tests.tsx | import * as React from 'react';
import * as TestUtils from 'react-addons-test-utils';
import App from '../../src/components/App';
import WhoToGreet from '../../src/components/WhoToGreet';
import Greeting from '../../src/components/Greeting';
import GreetingStore from '../../src/stores/GreetingStore';
describe('App', (... | ] }
</div>
);
});
function render(state: any) {
const shallowRenderer = TestUtils.createRenderer();
spyOn(GreetingStore, 'getState').and.returnValue(state);
shallowRenderer.render(<App />);
return shallowRenderer.getRenderOutput();
}
}); | random_line_split | |
App.tests.tsx | import * as React from 'react';
import * as TestUtils from 'react-addons-test-utils';
import App from '../../src/components/App';
import WhoToGreet from '../../src/components/WhoToGreet';
import Greeting from '../../src/components/Greeting';
import GreetingStore from '../../src/stores/GreetingStore';
describe('App', (... | (state: any) {
const shallowRenderer = TestUtils.createRenderer();
spyOn(GreetingStore, 'getState').and.returnValue(state);
shallowRenderer.render(<App />);
return shallowRenderer.getRenderOutput();
}
});
| render | identifier_name |
App.tests.tsx | import * as React from 'react';
import * as TestUtils from 'react-addons-test-utils';
import App from '../../src/components/App';
import WhoToGreet from '../../src/components/WhoToGreet';
import Greeting from '../../src/components/Greeting';
import GreetingStore from '../../src/stores/GreetingStore';
describe('App', (... |
});
| {
const shallowRenderer = TestUtils.createRenderer();
spyOn(GreetingStore, 'getState').and.returnValue(state);
shallowRenderer.render(<App />);
return shallowRenderer.getRenderOutput();
} | identifier_body |
diy_hints.rs | use std::collections::HashSet;
use rustyline::hint::{Hint, Hinter};
use rustyline::Context;
use rustyline::{Editor, Result};
use rustyline_derive::{Completer, Helper, Highlighter, Validator};
#[derive(Completer, Helper, Validator, Highlighter)]
struct DIYHinter {
// It's simple example of rustyline, for more effi... | }
impl Hinter for DIYHinter {
type Hint = CommandHint;
fn hint(&self, line: &str, pos: usize, _ctx: &Context<'_>) -> Option<CommandHint> {
if line.is_empty() || pos < line.len() {
return None;
}
self.hints
.iter()
.filter_map(|hint| {
... | display: self.display[strip_chars..].to_owned(),
complete_up_to: self.complete_up_to.saturating_sub(strip_chars),
}
} | random_line_split |
diy_hints.rs | use std::collections::HashSet;
use rustyline::hint::{Hint, Hinter};
use rustyline::Context;
use rustyline::{Editor, Result};
use rustyline_derive::{Completer, Helper, Highlighter, Validator};
#[derive(Completer, Helper, Validator, Highlighter)]
struct DIYHinter {
// It's simple example of rustyline, for more effi... | (&self, line: &str, pos: usize, _ctx: &Context<'_>) -> Option<CommandHint> {
if line.is_empty() || pos < line.len() {
return None;
}
self.hints
.iter()
.filter_map(|hint| {
// expect hint after word complete, like redis cli, add condition:
... | hint | identifier_name |
diy_hints.rs | use std::collections::HashSet;
use rustyline::hint::{Hint, Hinter};
use rustyline::Context;
use rustyline::{Editor, Result};
use rustyline_derive::{Completer, Helper, Highlighter, Validator};
#[derive(Completer, Helper, Validator, Highlighter)]
struct DIYHinter {
// It's simple example of rustyline, for more effi... |
fn main() -> Result<()> {
println!("This is a DIY hint hack of rustyline");
let h = DIYHinter { hints: diy_hints() };
let mut rl: Editor<DIYHinter> = Editor::new();
rl.set_helper(Some(h));
loop {
let input = rl.readline("> ")?;
println!("input: {}", input);
}
}
| {
let mut set = HashSet::new();
set.insert(CommandHint::new("help", "help"));
set.insert(CommandHint::new("get key", "get "));
set.insert(CommandHint::new("set key value", "set "));
set.insert(CommandHint::new("hget key field", "hget "));
set.insert(CommandHint::new("hset key field value", "hset... | identifier_body |
diy_hints.rs | use std::collections::HashSet;
use rustyline::hint::{Hint, Hinter};
use rustyline::Context;
use rustyline::{Editor, Result};
use rustyline_derive::{Completer, Helper, Highlighter, Validator};
#[derive(Completer, Helper, Validator, Highlighter)]
struct DIYHinter {
// It's simple example of rustyline, for more effi... |
})
.next()
}
}
fn diy_hints() -> HashSet<CommandHint> {
let mut set = HashSet::new();
set.insert(CommandHint::new("help", "help"));
set.insert(CommandHint::new("get key", "get "));
set.insert(CommandHint::new("set key value", "set "));
set.insert(CommandHint::new("hget ... | {
None
} | conditional_block |
gulpfile.js | const
gulp = require('gulp'),
rename = require('gulp-rename'),
sketch = require('gulp-sketch'),
iconfont = require('gulp-iconfont'),
imagemin = require('gulp-imagemin'),
consolidate = require('gulp-consolidate')
/**
* Font settings
*/
const
// set name of your symbol font
fontName = 'floating-top-lin... | * This is needed for mapping glyphs and codepoints.
*/
function mapGlyphs(glyph) {
return { name: glyph.name, codepoint: glyph.unicode[0].charCodeAt(0) }
} | )
gulp.task('watch', () => gulp.watch('*.sketch', ['symbols']))
/** | random_line_split |
gulpfile.js | const
gulp = require('gulp'),
rename = require('gulp-rename'),
sketch = require('gulp-sketch'),
iconfont = require('gulp-iconfont'),
imagemin = require('gulp-imagemin'),
consolidate = require('gulp-consolidate')
/**
* Font settings
*/
const
// set name of your symbol font
fontName = 'floating-top-lin... | (glyph) {
return { name: glyph.name, codepoint: glyph.unicode[0].charCodeAt(0) }
}
| mapGlyphs | identifier_name |
gulpfile.js | const
gulp = require('gulp'),
rename = require('gulp-rename'),
sketch = require('gulp-sketch'),
iconfont = require('gulp-iconfont'),
imagemin = require('gulp-imagemin'),
consolidate = require('gulp-consolidate')
/**
* Font settings
*/
const
// set name of your symbol font
fontName = 'floating-top-lin... | {
return { name: glyph.name, codepoint: glyph.unicode[0].charCodeAt(0) }
} | identifier_body | |
browser.py | firefox_profile_')
log.debug("created firefox profile")
# Clean up tempdir at exit
atexit.register(rmtree, firefox_profile_tmpdir, ignore_errors=True)
template = data_path.join('firefox_profile.js.template').read()
profile_json = Template(template).substitute(profile_dir=firefox_profile_tmpdir)
... |
else:
return cls(BrowserFactory(webdriver_class, browser_kwargs))
def _is_alive(self):
log.debug("alive check")
try:
self.browser.current_url
except UnexpectedAlertPresentException:
# We shouldn't think that an Unexpected alert means the browser ... | wharf = Wharf(browser_conf['webdriver_wharf'])
atexit.register(wharf.checkin)
return cls(WharfFactory(webdriver_class, browser_kwargs, wharf)) | conditional_block |
browser.py | my_id:
self._get('checkin', my_id)
log.info('Checked in webdriver container %s', my_id)
self._renew_thread = None
def _start_renew_thread(self):
assert self._renew_thread is None
self._renew_thread = threading.Thread(target=self._renew_function)
self._re... |
"""
if not url_key: | random_line_split | |
browser.py | firefox_profile_')
log.debug("created firefox profile")
# Clean up tempdir at exit
atexit.register(rmtree, firefox_profile_tmpdir, ignore_errors=True)
template = data_path.join('firefox_profile.js.template').read()
profile_json = Template(template).substitute(profile_dir=firefox_profile_tmpdir)
... | (object):
def __init__(self, webdriver_class, browser_kwargs):
self.webdriver_class = webdriver_class
self.browser_kwargs = browser_kwargs
self._add_missing_options()
def _add_missing_options(self):
if self.webdriver_class is not webdriver.Remote:
# desired_capabili... | BrowserFactory | identifier_name |
browser.py | _missing_options()
def _add_missing_options(self):
if self.webdriver_class is not webdriver.Remote:
# desired_capabilities is only for Remote driver, but can sneak in
self.browser_kwargs.pop('desired_capabilities', None)
elif self.browser_kwargs['desired_capabilities']['brow... | screenshot = None
screenshot_error = None
try:
screenshot = browser().get_screenshot_as_base64()
except (AttributeError, WebDriverException):
# See comments utils.browser.ensure_browser_open for why these two exceptions
screenshot_error = 'browser error'
except Exception as ex:
... | identifier_body | |
forecast.py | # coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
__metaclass__ = type
import pandas as pd
from pyoptflow import utils
from pyoptflow.core import extract_motion_proesmans
from pyoptflow.extrapolation import semilagrangian
def read_rainrate(filename):
return
def ... |
return pd.Series(index=index, data=fcast_list, name='forecast')
| fcast_list.append(extrapolate(cropped_rainrates.loc[tmax], v, t+1)) | conditional_block |
forecast.py | # coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
__metaclass__ = type
import pandas as pd
from pyoptflow import utils
from pyoptflow.core import extract_motion_proesmans
from pyoptflow.extrapolation import semilagrangian
def read_rainrate(filename):
return
def ... | dt = tmax-tmin
index = pd.DatetimeIndex(freq=dt, periods=steps, start=tmax+dt)
rr_ubyte = cropped_rainrates.apply(rr2ubyte)
v = motion(rr_ubyte.iloc[0], rr_ubyte.iloc[1])
fcast_list = []
for t in range(steps):
fcast_list.append(extrapolate(cropped_rainrates.loc[tmax], v, t+1))
return... | if cropped_rainrates.size != 2:
raise ValueError('cropped_rainrates must be a two-row pandas.Series')
tmax = cropped_rainrates.index.max()
tmin = cropped_rainrates.index.min() | random_line_split |
forecast.py | # coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
__metaclass__ = type
import pandas as pd
from pyoptflow import utils
from pyoptflow.core import extract_motion_proesmans
from pyoptflow.extrapolation import semilagrangian
def read_rainrate(filename):
return
def ... | (rr0ubyte, rr1ubyte, lam=25.0, num_iter=250, num_levels=6):
return extract_motion_proesmans(rr0ubyte, rr1ubyte, lam=lam,
num_iter=num_iter,
num_levels=num_levels)[0]
def extrapolate(rr, v, t, n_steps=15, n_iter=3, inverse=True):
return se... | motion | identifier_name |
forecast.py | # coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
__metaclass__ = type
import pandas as pd
from pyoptflow import utils
from pyoptflow.core import extract_motion_proesmans
from pyoptflow.extrapolation import semilagrangian
def read_rainrate(filename):
return
def ... |
def extrapolate(rr, v, t, n_steps=15, n_iter=3, inverse=True):
return semilagrangian(rr, v, t, n_steps=n_steps, n_iter=n_iter,
inverse=inverse)
def forecast(cropped_rainrates, steps=13):
"""
cropped_rainrates: two-row Series of input rainrate fields
steps: number of time s... | return extract_motion_proesmans(rr0ubyte, rr1ubyte, lam=lam,
num_iter=num_iter,
num_levels=num_levels)[0] | identifier_body |
test_api_audit.py | import json
from .base import MyTestCase
from privacyidea.lib.error import (ParameterError, ConfigAdminError)
from urllib import urlencode
PWFILE = "tests/testdata/passwords"
POLICYFILE = "tests/testdata/policy.cfg"
POLICYEMPTY = "tests/testdata/policy_empty_file.cfg"
class APIAuditTestCase(MyTestCase):
def test... | (self):
with self.app.test_request_context('/audit/statistics',
method='GET',
headers={'Authorization': self.at}):
res = self.app.full_dispatch_request()
self.assertTrue(res.status_code == 200, res)
... | test_01_get_statistics | identifier_name |
test_api_audit.py | import json
from .base import MyTestCase
from privacyidea.lib.error import (ParameterError, ConfigAdminError) |
PWFILE = "tests/testdata/passwords"
POLICYFILE = "tests/testdata/policy.cfg"
POLICYEMPTY = "tests/testdata/policy_empty_file.cfg"
class APIAuditTestCase(MyTestCase):
def test_00_get_audit(self):
with self.app.test_request_context('/audit/',
method='GET',
... | from urllib import urlencode | random_line_split |
test_api_audit.py | import json
from .base import MyTestCase
from privacyidea.lib.error import (ParameterError, ConfigAdminError)
from urllib import urlencode
PWFILE = "tests/testdata/passwords"
POLICYFILE = "tests/testdata/policy.cfg"
POLICYEMPTY = "tests/testdata/policy_empty_file.cfg"
class APIAuditTestCase(MyTestCase):
| "result").get("value"), json_response.get("result"))
#def test_01_download_audit(self):
# with self.app.test_request_context('/audit/auditfile.csv',
# method='GET',
# headers={'Authorization': self.at}):
... | def test_00_get_audit(self):
with self.app.test_request_context('/audit/',
method='GET',
headers={'Authorization': self.at}):
res = self.app.full_dispatch_request()
self.assertTrue(res.status_code == 20... | identifier_body |
schemeContainer.js | describe("Render scheme", function () {
let mainPage
let schemeContainer
beforeEach(function (client, done) {
mainPage = client
.url("localhost:3200")
.page.main()
schemeContainer = mainPage.section.schemeContainer
client.waitForElementVisible(".download-url-input"... |
it("render section", function (client) {
mainPage.expect.section("@schemeContainer").to.be.visible.before(5000)
client.end()
})
it("render scheme option", function (client) {
schemeContainer.waitForElementVisible("@httpOption", 5000)
.expect.element("@httpOption").to.be.sel... | done()
}) | random_line_split |
mqtt-stack.js | var mqttLayer = require('./mqtt-layer');
class MqttStack {
constructor() {
this.request = {};
// inherited from the router
this.options = {};
// all layers EXCEPT DEFAULT HANDLER
this.stack = [];
// handle all remaining errors at the end of stack
// default... |
addDefaultHandler(handle) {
if (handle.length < 2) {
throw new TypeError('A default handler must have an error argument!')
}
this.defaultHandler = handle;
}
/**
* Uses the stack for the given request
* Builds a custom MQTTRequest request object, containing topic... | */ | random_line_split |
mqtt-stack.js | var mqttLayer = require('./mqtt-layer');
class MqttStack {
constructor() {
this.request = {};
// inherited from the router
this.options = {};
// all layers EXCEPT DEFAULT HANDLER
this.stack = [];
// handle all remaining errors at the end of stack
// default... |
};
}
/**
* Goes through stack then calls handle on matching route, if any
* @private
*/
execute() {
var index = 0;
var next = (err) => {
var layerError = err;
// find the next route
var match, layer;
while ( index < t... | {
console.log('Error in ', request.path, ': ', error.stack);
} | conditional_block |
mqtt-stack.js | var mqttLayer = require('./mqtt-layer');
class MqttStack {
constructor() {
this.request = {};
// inherited from the router
this.options = {};
// all layers EXCEPT DEFAULT HANDLER
this.stack = [];
// handle all remaining errors at the end of stack
// default... |
/**
* Adds the specified function to the mqtt router, at a given path (path '#' matches to all)
* @param {Path} path
* @param {function} fn
* @public
*/
add(path, handle) {
var layer = new mqttLayer(path, handle, this.options);
this.stack.push(layer);
}
/**
* ... | {
try {
return layer.match(request.topic);
} catch (err) {
return err;
}
} | identifier_body |
mqtt-stack.js | var mqttLayer = require('./mqtt-layer');
class MqttStack {
constructor() {
this.request = {};
// inherited from the router
this.options = {};
// all layers EXCEPT DEFAULT HANDLER
this.stack = [];
// handle all remaining errors at the end of stack
// default... | (path, handle) {
var layer = new mqttLayer(path, handle, this.options);
this.stack.push(layer);
}
/**
* Adds default path to stack (will be performed if a channel is subscribed outside the router)
* @param {function} fn
* @public
*/
addDefaultHandler(handle) {
if (h... | add | identifier_name |
problem.py | from math import sqrt
from collections import defaultdict, Counter
from fractions import Fraction
def reverse_erathos(n):
d = defaultdict(set)
for i in range(2, n + 1):
if i not in d:
j = 2 * i
while j <= n:
d[j].add(i)
j += i
return d
def to... |
def compute_solution(n):
c = 1
prime_decs = reverse_erathos(n)
res = []
for i in range(2, n + 1):
if c % 50000 == 0:
print(c)
tot = totient(i, prime_decs)
if Counter(str(i)) == Counter(str(tot)):
res.append((i, tot, Fraction(i, tot)))
c += 1
... | if n not in prime_decs:
return n - 1
res = n
for prime in prime_decs[n]:
res *= 1 - Fraction(1, prime)
return int(res) | identifier_body |
problem.py | from math import sqrt
from collections import defaultdict, Counter
from fractions import Fraction
def reverse_erathos(n):
d = defaultdict(set)
for i in range(2, n + 1):
if i not in d:
j = 2 * i
while j <= n:
d[j].add(i)
j += i
return d |
def totient(n, prime_decs):
if n not in prime_decs:
return n - 1
res = n
for prime in prime_decs[n]:
res *= 1 - Fraction(1, prime)
return int(res)
def compute_solution(n):
c = 1
prime_decs = reverse_erathos(n)
res = []
for i in range(2, n + 1):
if c % 50000 == 0... | random_line_split | |
problem.py | from math import sqrt
from collections import defaultdict, Counter
from fractions import Fraction
def reverse_erathos(n):
d = defaultdict(set)
for i in range(2, n + 1):
|
return d
def totient(n, prime_decs):
if n not in prime_decs:
return n - 1
res = n
for prime in prime_decs[n]:
res *= 1 - Fraction(1, prime)
return int(res)
def compute_solution(n):
c = 1
prime_decs = reverse_erathos(n)
res = []
for i in range(2, n + 1):
if ... | if i not in d:
j = 2 * i
while j <= n:
d[j].add(i)
j += i | conditional_block |
problem.py | from math import sqrt
from collections import defaultdict, Counter
from fractions import Fraction
def | (n):
d = defaultdict(set)
for i in range(2, n + 1):
if i not in d:
j = 2 * i
while j <= n:
d[j].add(i)
j += i
return d
def totient(n, prime_decs):
if n not in prime_decs:
return n - 1
res = n
for prime in prime_decs[n]:
... | reverse_erathos | identifier_name |
StringMsg.ts | // Copyright (c) ComUnity 2013
// hansm@comunity.co.za (Hans Malherbe)
///<reference path="../typed/node/node.d.ts" />
///<reference path="../typed/q/Q.d.ts" />
import BaseMsg = require('./BaseMsg')
import Msg = require('./Msg')
import Q = require('q')
import Response = require('./Response')
class StringMsg extends ... | }
}
export = StringMsg | }
getObject(): Q.Promise<any> {
return Q.fcall(() => JSON.parse(this._content)) | random_line_split |
StringMsg.ts | // Copyright (c) ComUnity 2013
// hansm@comunity.co.za (Hans Malherbe)
///<reference path="../typed/node/node.d.ts" />
///<reference path="../typed/q/Q.d.ts" />
import BaseMsg = require('./BaseMsg')
import Msg = require('./Msg')
import Q = require('q')
import Response = require('./Response')
class StringMsg extends ... | (): Q.Promise<NodeBuffer> {
return Q.fcall(() => new Buffer(this._content))
}
getString(): Q.Promise<string> {
return Q.fcall(() => this._content)
}
getObject(): Q.Promise<any> {
return Q.fcall(() => JSON.parse(this._content))
}
}
export = StringMsg | getBuffer | identifier_name |
pubsub.d.ts | import { CloudFunction, EventContext } from '../cloud-functions';
/** Select Cloud Pub/Sub topic to listen to.
* @param topic Name of Pub/Sub topic, must belong to the same project as the function. | /** Builder used to create Cloud Functions for Google Pub/Sub topics. */
export declare class TopicBuilder {
private triggerResource;
private opts;
/** Handle a Pub/Sub message that was published to a Cloud Pub/Sub topic */
onPublish(handler: (message: Message, context: EventContext) => PromiseLike<any>... | */
export declare function topic(topic: string): TopicBuilder; | random_line_split |
pubsub.d.ts | import { CloudFunction, EventContext } from '../cloud-functions';
/** Select Cloud Pub/Sub topic to listen to.
* @param topic Name of Pub/Sub topic, must belong to the same project as the function.
*/
export declare function topic(topic: string): TopicBuilder;
/** Builder used to create Cloud Functions for Google Pub... | {
private triggerResource;
private opts;
/** Handle a Pub/Sub message that was published to a Cloud Pub/Sub topic */
onPublish(handler: (message: Message, context: EventContext) => PromiseLike<any> | any): CloudFunction<Message>;
}
/**
* A Pub/Sub message.
*
* This class has an additional .json help... | TopicBuilder | identifier_name |
complex_query.rs | extern crate rustorm;
extern crate uuid;
extern crate chrono;
extern crate rustc_serialize;
use uuid::Uuid;
use rustorm::query::Query;
use rustorm::query::Equality;
use rustorm::dao::{Dao, IsDao};
use rustorm::pool::ManagedPool;
#[derive(Debug, Clone)]
pub struct | {
pub photo_id: Uuid,
pub url: Option<String>,
}
impl IsDao for Photo{
fn from_dao(dao: &Dao) -> Self {
Photo {
photo_id: dao.get("photo_id"),
url: dao.get_opt("url"),
}
}
fn to_dao(&self) -> Dao {
let mut dao = Dao::new();
dao.set("photo_id... | Photo | identifier_name |
complex_query.rs | extern crate rustorm;
extern crate uuid;
extern crate chrono;
extern crate rustc_serialize;
use uuid::Uuid;
use rustorm::query::Query;
use rustorm::query::Equality;
use rustorm::dao::{Dao, IsDao};
use rustorm::pool::ManagedPool;
#[derive(Debug, Clone)]
pub struct Photo {
pub photo_id: Uuid,
pub url: Option<S... |
fn to_dao(&self) -> Dao {
let mut dao = Dao::new();
dao.set("photo_id", &self.photo_id);
match self.url {
Some(ref _value) => dao.set("url", _value),
None => dao.set_null("url"),
}
dao
}
}
fn main() {
let url = "postgres://postgres:p0stgr3s@... | {
Photo {
photo_id: dao.get("photo_id"),
url: dao.get_opt("url"),
}
} | identifier_body |
complex_query.rs | extern crate rustorm;
extern crate uuid;
extern crate chrono; |
use uuid::Uuid;
use rustorm::query::Query;
use rustorm::query::Equality;
use rustorm::dao::{Dao, IsDao};
use rustorm::pool::ManagedPool;
#[derive(Debug, Clone)]
pub struct Photo {
pub photo_id: Uuid,
pub url: Option<String>,
}
impl IsDao for Photo{
fn from_dao(dao: &Dao) -> Self {
Photo {
... | extern crate rustc_serialize; | random_line_split |
trans_real.py | It will construct a object for the
requested language and add a fallback to the default language, if it's
different from the requested language.
"""
global _translations
t = _translations.get(language, None)
if t is not None:
return t
from django.conf import settings
... | random_line_split | ||
trans_real.py | , language):
self.__language = language
def language(self):
return self.__language
def __repr__(self):
return "<DjangoTranslation lang:%s>" % self.__language
class DjangoTranslation23(DjangoTranslation):
"""
Compatibility class that is only used with Python 2.3.
... |
_translations[lang] = res
return res
default_translation = _fetch(settings.LANGUAGE_CODE)
current_translation = _fetch(language, fallback=default_translation)
return current_translation
def activate(language):
"""
Fetches the translation object for a given tuple of app... | return gettext_module.NullTranslations() | conditional_block |
trans_real.py | , language):
self.__language = language
def language(self):
return self.__language
def __repr__(self):
return "<DjangoTranslation lang:%s>" % self.__language
class DjangoTranslation23(DjangoTranslation):
"""
Compatibility class that is only used with Python 2.3.
... | ():
"""
Returns the current active catalog for further processing.
This can be used if you need to modify the catalog or want to access the
whole message catalog instead of just translating one string.
"""
global _default, _active
t = _active.get(currentThread(), None)
if t is no... | catalog | identifier_name |
trans_real.py | , language):
self.__language = language
def language(self):
return self.__language
def __repr__(self):
return "<DjangoTranslation lang:%s>" % self.__language
class DjangoTranslation23(DjangoTranslation):
"""
Compatibility class that is only used with Python 2.3.
... |
def ungettext(singular, plural, number):
"""
Returns a unicode strings of the translation of either the singular or
plural, based on the number.
"""
return do_ntranslate(singular, plural, number, 'ungettext')
def check_for_language(lang_code):
"""
Checks whether there is a glob... | """
Returns a UTF-8 bytestring of the translation of either the singular or
plural, based on the number.
"""
return do_ntranslate(singular, plural, number, 'ngettext') | identifier_body |
home-tips.ts | import { Component, OnInit, Input } from '@angular/core';
import { Events } from 'ionic-angular';
import { Guimo } from './../../providers/guimo';
/*
Generated class for the HomeTips component.
See https://angular.io/docs/ts/latest/api/core/index/ComponentMetadata-class.html
for more info on Angular 2 Componen... |
}
| {
} | identifier_body |
home-tips.ts | import { Component, OnInit, Input } from '@angular/core';
import { Events } from 'ionic-angular';
import { Guimo } from './../../providers/guimo';
/*
Generated class for the HomeTips component.
See https://angular.io/docs/ts/latest/api/core/index/ComponentMetadata-class.html
for more info on Angular 2 Componen... | implements OnInit{
@Input() attempts:number;
btStatus: boolean = this.guimo.btStatus;
btConnected: boolean;
constructor(private guimo:Guimo, private events:Events) {
this.events.subscribe('bt:Connected',(res)=>{
this.btConnected = res;
console.log('home-tips btcon',this.btConnected);
... | HomeTipsComponent | identifier_name |
home-tips.ts | import { Component, OnInit, Input } from '@angular/core';
import { Events } from 'ionic-angular';
import { Guimo } from './../../providers/guimo';
/* | Generated class for the HomeTips component.
See https://angular.io/docs/ts/latest/api/core/index/ComponentMetadata-class.html
for more info on Angular 2 Components.
*/
@Component({
selector: 'home-tips',
templateUrl: 'home-tips.html'
})
export class HomeTipsComponent implements OnInit{
@Input() attempts:... | random_line_split | |
keyring.py | #!/usr/bin/env python
'''
Handles access to the WebDAV's server creditentials.
'''
from collections import namedtuple
import secretstorage
APPLICATION_NAME = "davify"
FileStorage = namedtuple('FileStorage',
'username password protocol server port path')
def get_secret_storage():
bus =... | return items
def _parse_item(item):
item_attr = item.get_attributes()
return FileStorage(username=item_attr['username'],
password=item.get_secret().decode('utf-8'),
protocol=item_attr['protocol'],
server=item_attr['server'],
... | random_line_split | |
keyring.py | #!/usr/bin/env python
'''
Handles access to the WebDAV's server creditentials.
'''
from collections import namedtuple
import secretstorage
APPLICATION_NAME = "davify"
FileStorage = namedtuple('FileStorage',
'username password protocol server port path')
def get_secret_storage():
bus =... | (username, pwd, protocol, server, port, path):
'''
stores the given password in the gnome keyring
'''
secret_storage = get_secret_storage()
attrs = {'application': APPLICATION_NAME,
'username': username,
'server': server,
'protocol': protocol,
'por... | store_password | identifier_name |
keyring.py | #!/usr/bin/env python
'''
Handles access to the WebDAV's server creditentials.
'''
from collections import namedtuple
import secretstorage
APPLICATION_NAME = "davify"
FileStorage = namedtuple('FileStorage',
'username password protocol server port path')
def get_secret_storage():
bus =... |
if __name__ == '__main__':
print(get_passwords())
| item_attr = item.get_attributes()
return FileStorage(username=item_attr['username'],
password=item.get_secret().decode('utf-8'),
protocol=item_attr['protocol'],
server=item_attr['server'],
port=item_attr['port'],
... | identifier_body |
keyring.py | #!/usr/bin/env python
'''
Handles access to the WebDAV's server creditentials.
'''
from collections import namedtuple
import secretstorage
APPLICATION_NAME = "davify"
FileStorage = namedtuple('FileStorage',
'username password protocol server port path')
def get_secret_storage():
bus =... | print(get_passwords()) | conditional_block | |
extern-pass-TwoU32s.rs | // Copyright 2012 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 ... | () {
unsafe {
let x = TwoU32s {one: 22, two: 23};
let y = rust_dbg_extern_identity_TwoU32s(x);
assert_eq!(x, y);
}
}
| main | identifier_name |
extern-pass-TwoU32s.rs | // Copyright 2012 The Rust Project Developers. See the 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test a foreign f... | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | random_line_split |
extern-pass-TwoU32s.rs | // Copyright 2012 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 ... | {
unsafe {
let x = TwoU32s {one: 22, two: 23};
let y = rust_dbg_extern_identity_TwoU32s(x);
assert_eq!(x, y);
}
} | identifier_body | |
Benchmark.test.js | // @flow
import * as React from 'react';
import Benchmark, { type BenchmarkRef } from '../Benchmark';
import BenchmarkType from '../BenchmarkType';
import { act, render, waitFor } from '@testing-library/react';
import type { Sample } from '../types';
type Props = {| testID: number |};
function Test({ testID }: Props)... |
describe('new', () => {
beforeEach(() => {
jest.useRealTimers();
});
test('renders nothing if not running', () => {
const { getByTestId } = render(<Benchmark component={Test} onComplete={jest.fn()} samples={2} />);
expect(() => getByTestId('test')).toThrow('Unable to find an element');
});
tes... | {
return <div id={testID}>hello</div>;
} | identifier_body |
Benchmark.test.js | // @flow
import * as React from 'react';
import Benchmark, { type BenchmarkRef } from '../Benchmark';
import BenchmarkType from '../BenchmarkType';
import { act, render, waitFor } from '@testing-library/react';
import type { Sample } from '../types';
type Props = {| testID: number |};
function | ({ testID }: Props) {
return <div id={testID}>hello</div>;
}
describe('new', () => {
beforeEach(() => {
jest.useRealTimers();
});
test('renders nothing if not running', () => {
const { getByTestId } = render(<Benchmark component={Test} onComplete={jest.fn()} samples={2} />);
expect(() => getByTest... | Test | identifier_name |
Benchmark.test.js | // @flow
import * as React from 'react';
import Benchmark, { type BenchmarkRef } from '../Benchmark';
import BenchmarkType from '../BenchmarkType';
import { act, render, waitFor } from '@testing-library/react';
import type { Sample } from '../types';
type Props = {| testID: number |};
function Test({ testID }: Props)... | })
)
);
}
);
describe('results', () => {
let results;
beforeAll(async () => {
const ref = React.createRef<BenchmarkRef | void>();
const handleComplete = jest.fn();
render(<Benchmark ref={ref} component={Test} onComplete={handleComplete} samples={2} />);
... | random_line_split | |
lex_rule_loader.rs | use common::lexer::{Ruleset, LexRule};
use walkdir::{WalkDir, DirEntry};
use std::io::prelude::*;
use std::io;
use std::fs;
pub fn ruleset_from_dir (dir_path: String) -> io::Result<Ruleset> {
ruleset_from_dir_v(dir_path, false)
}
pub fn | (dir_path: String, verbose: bool) -> io::Result<Ruleset> {
let mut lex_list:Vec<DirEntry> = Vec::new();
for entry in WalkDir::new(dir_path) {
let entry = entry.unwrap();
let ent_path = &entry.path();
match ent_path.extension() {
Some(ext) => {
if ext == "lex"... | ruleset_from_dir_v | identifier_name |
lex_rule_loader.rs | use common::lexer::{Ruleset, LexRule};
use walkdir::{WalkDir, DirEntry};
use std::io::prelude::*;
use std::io;
use std::fs;
pub fn ruleset_from_dir (dir_path: String) -> io::Result<Ruleset> {
ruleset_from_dir_v(dir_path, false)
}
pub fn ruleset_from_dir_v (dir_path: String, verbose: bool) -> io::Result<Ruleset> | }
let mut file = fs::File::open(entry.path())?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
for line in contents.lines() {
if ! ((line.trim() == "") || (line.starts_with("#"))) {
rules.add(LexRule::from_string(String::from(l... | {
let mut lex_list:Vec<DirEntry> = Vec::new();
for entry in WalkDir::new(dir_path) {
let entry = entry.unwrap();
let ent_path = &entry.path();
match ent_path.extension() {
Some(ext) => {
if ext == "lex" {
lex_list.push(entry.clone());
... | identifier_body |
lex_rule_loader.rs | use common::lexer::{Ruleset, LexRule};
use walkdir::{WalkDir, DirEntry};
use std::io::prelude::*;
use std::io;
use std::fs;
pub fn ruleset_from_dir (dir_path: String) -> io::Result<Ruleset> {
ruleset_from_dir_v(dir_path, false)
}
pub fn ruleset_from_dir_v (dir_path: String, verbose: bool) -> io::Result<Ruleset> {... | lex_list.push(entry.clone());
}
},
None => ()
}
}
let mut rules = Ruleset::new();
for entry in lex_list {
if verbose {
println!("Loading rules from file [{}]", &entry.path().display());
}
let mut file =... | Some(ext) => {
if ext == "lex" { | random_line_split |
lib.rs | //! (Hopefully) Safe fork-join parallelism abstractions
//!
//! Implements the [`divide`](fn.divide.html) and
//! [`execute!`](../parallel_macros/macro.execute!.html) functions proposed in Niko's
//! [blog](http://smallcultfollowing.com/babysteps/blog/2013/06/11/data-parallelism-in-rust/).
//!
//! # Cargo
//!
//! ``` t... |
#![allow(unused_features)]
#![cfg_attr(test, plugin(quickcheck_macros))]
#![deny(warnings)]
#![feature(core)]
#![feature(os)]
#![feature(plugin)]
#![feature(std_misc)]
#[cfg(test)]
extern crate quickcheck;
#[cfg(test)]
extern crate rand;
pub use divide::divide;
pub use apply::apply;
mod divide;
mod apply; | //! [dependencies.parallel_macros]
//! git = "https://github.com/japaric/parallel.rs"
//! ``` | random_line_split |
data.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>,... | fn contains_pfx(haystack: &[&str], needle: &str) -> bool {
haystack.iter().any(|&x| needle.starts_with(x))
}
// Quirks-mode matches are case-insensitive.
let public = opt_to_ascii_lower(public);
let system = opt_to_ascii_lower(system);
let quirk = match (opt_as_slice(&public), opt_as_s... | // FIXME: We could do something asymptotically faster here.
// But there aren't many strings, and this happens at most once per parse. | random_line_split |
data.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>,... | (x: Option<&str>) -> Option<String> {
x.map(|y| y.to_ascii_lower())
}
let name = opt_as_slice(&doctype.name);
let public = opt_as_slice(&doctype.public_id);
let system = opt_as_slice(&doctype.system_id);
let err = match (name, public, system) {
(Some("html"), None, None)
... | opt_to_ascii_lower | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.