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 |
|---|---|---|---|---|
test_concurrency.py | from __future__ import absolute_import
import os
from itertools import count
from mock import Mock
from celery.concurrency.base import apply_target, BasePool
from celery.tests.case import AppCase
class test_BasePool(AppCase):
def test_apply_target(self):
scratch = {}
counter = count(0)
... | (self):
self.assertIsNone(BasePool(10).on_hard_timeout(Mock()))
def test_interface_close(self):
p = BasePool(10)
p.on_close = Mock()
p.close()
self.assertEqual(p._state, p.CLOSE)
p.on_close.assert_called_with()
def test_interface_no_close(self):
self.ass... | test_interface_on_hard_timeout | identifier_name |
test_concurrency.py | from __future__ import absolute_import
import os
from itertools import count
from mock import Mock
from celery.concurrency.base import apply_target, BasePool
from celery.tests.case import AppCase
class test_BasePool(AppCase):
def test_apply_target(self):
scratch = {}
counter = count(0)
... |
apply_target(gen_callback('target', 42),
args=(8, 16),
callback=gen_callback('callback'),
accept_callback=gen_callback('accept_callback'))
self.assertDictContainsSubset(
{'target': (1, (8, 16)), 'callback': (2, (42, ))},
... | def callback(*args):
scratch[name] = (next(counter), args)
return retval
return callback | identifier_body |
user.ts | import {Injectable} from '@angular/core';
import {Config} from '../config';
import {Submission} from '../models/submission';
import {User} from '../models/user';
import {HttpService} from './http';
import {PollingService} from './polling';
import {ProblemService} from './problem';
@Inje... |
}
});
resolve(user);
});
}
}
| {
user.insertOrUpdate(s);
} | conditional_block |
user.ts | import {Injectable} from '@angular/core';
import {Config} from '../config';
import {Submission} from '../models/submission';
import {User} from '../models/user';
import {HttpService} from './http';
import {PollingService} from './polling';
import {ProblemService} from './problem';
@Inje... |
getUser(id: number): Promise<User> {
return new Promise<User>((resolve) => {
this.loadUser(id, resolve);
});
}
private loadUser(id: number, resolve) {
this._httpService.get(Config.API_PATH + '/subs-user/' + id)
.then(res => {
this.subscribeUser(new User({
userid: id,
... | {
} | identifier_body |
user.ts | import {Injectable} from '@angular/core';
import {Config} from '../config';
import {Submission} from '../models/submission';
import {User} from '../models/user';
import {HttpService} from './http';
import {PollingService} from './polling';
import {ProblemService} from './problem';
@Inje... | (
private _httpService: HttpService,
private _problemService: ProblemService,
private _pollingService: PollingService) {
}
getUser(id: number): Promise<User> {
return new Promise<User>((resolve) => {
this.loadUser(id, resolve);
});
}
private loadUser(id: number, resolve) {
this._... | constructor | identifier_name |
user.ts | import {Injectable} from '@angular/core';
import {Config} from '../config';
import {Submission} from '../models/submission';
import {User} from '../models/user';
import {HttpService} from './http';
import {PollingService} from './polling';
import {ProblemService} from './problem';
@Inje... | return new Promise<User>((resolve) => {
this.loadUser(id, resolve);
});
}
private loadUser(id: number, resolve) {
this._httpService.get(Config.API_PATH + '/subs-user/' + id)
.then(res => {
this.subscribeUser(new User({
userid: id,
name: res.name,
userna... | random_line_split | |
intersection.rs | // Copyright 2018 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 agreed to in ... | {
pub id: IntersectionID,
pub point: Vec2d,
polygon: Vec<Vec2d>,
}
impl DrawIntersection {
pub fn new(
inter: &map_model::Intersection,
map: &Map,
roads: &Vec<DrawRoad>,
bounds: &Bounds,
) -> DrawIntersection {
let mut pts: Vec<Vec2d> = Vec::new();
... | DrawIntersection | identifier_name |
intersection.rs | // Copyright 2018 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 agreed to in ... |
polygon: Vec<Vec2d>,
}
impl DrawIntersection {
pub fn new(
inter: &map_model::Intersection,
map: &Map,
roads: &Vec<DrawRoad>,
bounds: &Bounds,
) -> DrawIntersection {
let mut pts: Vec<Vec2d> = Vec::new();
// TODO this smashes encapsulation to bits :D
... | pub point: Vec2d, | random_line_split |
intersection.rs | // Copyright 2018 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 agreed to in ... |
angle as i64
});
let first_pt = pts[0].clone();
pts.push(first_pt);
DrawIntersection {
id: inter.id,
point: [center.x(), center.y()],
polygon: pts,
}
}
pub fn draw(&self, g: &mut GfxCtx, color: Color) {
let poly =... | {
angle += 360.0;
} | conditional_block |
partial_file.rs | // Copyright (c) 2017 Simon Dickson
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::cmp;
use std::fs::File;
use std::io::{self, BufReader, SeekFrom, See... | let mut partial_content = BufReader::new(self.file);
let _ = partial_content.seek(SeekFrom::Start(range.0));
let result = partial_content.take(content_len);
response.set_status(Status::PartialContent);
response.set_streamed_body(result);
} else {
... | response.set_header(ContentLength(content_len));
response.set_header(content_range); | random_line_split |
partial_file.rs | // Copyright (c) 2017 Simon Dickson
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::cmp;
use std::fs::File;
use std::io::{self, BufReader, SeekFrom, See... | else {
if let Some(file_length) = file_length {
response.set_header(ContentRange(ContentRangeSpec::Bytes {
range: None,
instance_length: Some(file_length),
}));
};
response.set_status(Status::RangeNotSatisfiable... | {
let content_range = ContentRange(ContentRangeSpec::Bytes {
range: Some(range),
instance_length: file_length,
});
let content_len = range.1 - range.0 + 1;
response.set_header(ContentLength(content_len));
response.set_header(con... | conditional_block |
partial_file.rs | // Copyright (c) 2017 Simon Dickson
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::cmp;
use std::fs::File;
use std::io::{self, BufReader, SeekFrom, See... | if last < file_length {
Some((file_length - last, file_length - 1))
} else {
Some((0, file_length - 1))
}
},
(_, None) => None,
};
if let Some(range) = range {
let con... | {
use self::PartialFileRange::*;
let metadata : Option<_> = self.file.metadata().ok();
let file_length : Option<u64> = metadata.map(|m| m.len());
let range : Option<(u64, u64)> = match (range.into(), file_length) {
(FromTo(from, to), Some(file_length)) => {
if... | identifier_body |
partial_file.rs | // Copyright (c) 2017 Simon Dickson
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::cmp;
use std::fs::File;
use std::io::{self, BufReader, SeekFrom, See... | (video_path: &Path) -> io::Result<PartialFile> {
PartialFile::open(video_path)
}
| serve_partial | identifier_name |
randsone_ldif.py | # -*- coding: utf-8 -*-
#
# Copyright 2017-2020 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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 2 of the License, or
# ... |
self.ou_tree = dict((ou, tree[ou]) for ou in ous if ou in tree)
def init_attr2id2contacts(self):
self.attr2id2contacts = {}
self.id2labeledURI = {}
def init_person_titles(self):
self.person_titles = {}
def init_person_addresses(self):
self.addr_info = {}
| ous.extend(tree.get(ou, ())) | conditional_block |
randsone_ldif.py | # -*- coding: utf-8 -*-
#
# Copyright 2017-2020 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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 2 of the License, or
# ... | def init_ou_structure(self):
# Change from original: Drop OUs outside self.root_ou_id subtree.
super(RandsoneOrgLdif, self).init_ou_structure()
ous, tree = [self.root_ou_id], self.ou_tree
for ou in ous:
ous.extend(tree.get(ou, ()))
self.ou_tree = dict((ou, tree[ou]) f... | identifier_body | |
randsone_ldif.py | # -*- coding: utf-8 -*-
#
# Copyright 2017-2020 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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 2 of the License, or
# ... |
def init_person_addresses(self):
self.addr_info = {} | self.id2labeledURI = {}
def init_person_titles(self):
self.person_titles = {} | random_line_split |
randsone_ldif.py | # -*- coding: utf-8 -*-
#
# Copyright 2017-2020 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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 2 of the License, or
# ... | (self):
# Change from original: Drop OUs outside self.root_ou_id subtree.
super(RandsoneOrgLdif, self).init_ou_structure()
ous, tree = [self.root_ou_id], self.ou_tree
for ou in ous:
ous.extend(tree.get(ou, ()))
self.ou_tree = dict((ou, tree[ou]) for ou in ous if ou in... | init_ou_structure | identifier_name |
drawback.component.ts | import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router";
import { LiveService } from "../../live/service/live.service";
import { OrderService } from "../../order/service/order.service";
declare var $: any;
declare var layer: any;
@Component({
selector: 'app-drawba... | this.select = true;
this.type = 1;
} else {
this.select = false;
this.type = 2;
}
}
next() {
this.step_small = 2;
if (this.type == 1) {
this.returnDesc = '僅退款';
} else {
this.returnDesc = '退貨退款';
}
}
getRefundDetail(order_id, goods_id) {
this.ord... | }
selectReturn(types) {
if (types == 1) { | random_line_split |
drawback.component.ts | import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router";
import { LiveService } from "../../live/service/live.service";
import { OrderService } from "../../order/service/order.service";
declare var $: any;
declare var layer: any;
@Component({
selector: 'app-drawba... | this.returnDesc = '僅退款';
} else {
this.returnDesc = '退貨退款';
}
}
getRefundDetail(order_id, goods_id) {
this.orderService.getRefundDetail(this.routerParams.order_id, this.good.goods_id)
.subscribe(
data => {
// console.log(data);
this.returnDetail = data.d;
}, er... | 1;
} else {
this.select = false;
this.type = 2;
}
}
next() {
this.step_small = 2;
if (this.type == 1) {
| identifier_body |
drawback.component.ts | import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router";
import { LiveService } from "../../live/service/live.service";
import { OrderService } from "../../order/service/order.service";
declare var $: any;
declare var layer: any;
@Component({
selector: 'app-drawba... | next() {
this.step_small = 2;
if (this.type == 1) {
this.returnDesc = '僅退款';
} else {
this.returnDesc = '退貨退款';
}
}
getRefundDetail(order_id, goods_id) {
this.orderService.getRefundDetail(this.routerParams.order_id, this.good.goods_id)
.subscribe(
data => {
// c... | this.select = false;
this.type = 2;
}
}
| conditional_block |
drawback.component.ts | import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router";
import { LiveService } from "../../live/service/live.service";
import { OrderService } from "../../order/service/order.service";
declare var $: any;
declare var layer: any;
@Component({
selector: 'app-drawba... | rService.delRefund(order_id, goods_id)
.subscribe(
data => {
if (data.c == 1) {
layer.msg("撤銷申請成功");
setTimeout(function () {
that.router.navigate(["/order/orders/all"]);
}, 2000);
} else {
layer.msg(data.m);
}
... | at.orde | identifier_name |
test_fftlog.py | .3150140927838524E-03, +0.9149121960963704E-03,
+0.5808089753959363E-02, +0.2548065256377240E-01,
+0.1339477692089897E+00, +0.4821530509479356E+00,
+0.2659899781579785E+00, -0.1116475278448113E-01,
+0.1791441617592385E-02, -0.4181810476548056E-03,
+0... | k = np.exp(offset)/r[::-1] | random_line_split | |
test_fftlog.py | offset, bias=bias)
theirs = [-0.1159922613593045E-02, +0.1625822618458832E-02,
-0.1949518286432330E-02, +0.3789220182554077E-02,
+0.5093959119952945E-03, +0.2785387803618774E-01,
+0.9944952700848897E-01, +0.4599202164586588E+00,
+0.3157462160881342E+00, -0.820... |
A = fht(a, dln, mu, offset=offset, bias=bias)
a_ = ifht(A, dln, mu, offset=offset, bias=bias)
assert_allclose(a, a_)
def test_fht_special_cases():
rng = np.random.RandomState(3491349965)
a = rng.standard_normal(64)
dln = rng.uniform(-1, 1)
# let xp = (mu+1+q)/2, xm = (mu+1-q)/2, M = {... | offset = fhtoffset(dln, mu, initial=offset, bias=bias) | conditional_block |
test_fftlog.py | E-03, +0.3568398050238820E-03,
-0.5554454827797206E-03, +0.8286331026468585E-03]
assert_allclose(ours, theirs)
# test 2: change to optimal offset
offset = fhtoffset(dln, mu, bias=bias)
ours = fht(a, dln, mu, offset=offset, bias=bias)
theirs = [+0.4353768523152057E-04, -0.9197045663594... | test_fht_exact | identifier_name | |
test_fftlog.py | 897E-01, +0.4599202164586588E+00,
+0.3157462160881342E+00, -0.8201236844404755E-03,
-0.7834031308271878E-03, +0.3931444945110708E-03,
-0.2697710625194777E-03, +0.3568398050238820E-03,
-0.5554454827797206E-03, +0.8286331026468585E-03]
assert_allclose(ours, thei... | rng = np.random.RandomState(3491349965)
a = rng.standard_normal(64)
dln = rng.uniform(-1, 1)
# let xp = (mu+1+q)/2, xm = (mu+1-q)/2, M = {0, -1, -2, ...}
# case 1: xp in M, xm in M => well-defined transform
mu, bias = -4.0, 1.0
with warnings.catch_warnings(record=True) as record:
fht(... | identifier_body | |
bower.js | var gulp = require('gulp'),
config = require('../config'),
mergeStream = require('merge-stream'),
mainBowerFiles = require('main-bower-files'),
flatten = require('gulp-flatten'),
rename = require("gulp-rename"),
bowerRequireJS = require('bower-requirejs'),
wiredep = require('wiredep').stream;
gulp.task('... | cb();
})
}); | console.info('------> Updated paths config in '+options.config); | random_line_split |
preview-thumbnail.component.spec.ts | // Copyright 2020 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ap... | }));
beforeEach(() => {
fixture = TestBed.createComponent(PreviewThumbnailComponent);
componentInstance = fixture.componentInstance;
imageUploadHelperService = (
TestBed.inject(ImageUploadHelperService) as unknown) as
jasmine.SpyObj<ImageUploadHelperService>;
contextService = TestBe... | ]
}).compileComponents(); | random_line_split |
modistile.js | define([
'aeris/util',
'aeris/errors/invalidargumenterror',
'aeris/maps/layers/aeristile'
], function(_, InvalidArgumentError, AerisTile) {
/**
* Representation of an Aeris Modis layer.
*
* @constructor
* @class aeris.maps.layers.ModisTile
* @extends aeris.maps.layers.AerisTile
*/
var ModisT... | /* eg
1: "modis_tileType_1day",
3: "modis_tileType_3day"
*/
}
}, opt_attrs);
// Set initial tileType
_.extend(attrs, {
tileType: attrs.modisPeriodTileTypes[options.period]
});
AerisTile.call(this, attrs, opt_options);
this.setModisPeriod(options.... | *
* @attribute modisPeriodTileTypes
* @type {Object.<number, string>}
*/
modisPeriodTileTypes: { | random_line_split |
modistile.js | define([
'aeris/util',
'aeris/errors/invalidargumenterror',
'aeris/maps/layers/aeristile'
], function(_, InvalidArgumentError, AerisTile) {
/**
* Representation of an Aeris Modis layer.
*
* @constructor
* @class aeris.maps.layers.ModisTile
* @extends aeris.maps.layers.AerisTile
*/
var ModisT... |
if (!(period in this.get('modisPeriodTileTypes'))) {
throw new InvalidArgumentError('Invalid MODIS periods: available periods are: ' + validPeriods.join(','));
}
// Set new tile type
this.set('tileType', this.get('modisPeriodTileTypes')[period], { validate: true });
};
return ModisTile;
})... | {
throw new InvalidArgumentError('Invalid MODIS period: period must be a positive integer');
} | conditional_block |
s3.rs | storage_class: Option<String>,
upload_id: String,
parts: Vec<CompletedPart>,
}
/// Specifies the minimum size to use multi-part upload.
/// AWS S3 requires each part to be at least 5 MiB.
const MINIMUM_PART_SIZE: usize = 5 * 1024 * 1024;
impl<'client> S3Uploader<'client> {
/// Creates a new uploader wit... | {
let magic_contents = "5678";
let config = Config {
region: "ap-southeast-2".to_string(),
bucket: "mybucket".to_string(),
prefix: "myprefix".to_string(),
access_key: "abc".to_string(),
secret_access_key: "xyz".to_string(),
..Defaul... | identifier_body | |
s3.rs | Send + Sync + 'static,
{
Self::check_config(config)?;
let client = new_client!(S3Client, config, dispatcher);
Ok(S3Storage {
config: config.clone(),
client,
_not_send: PhantomData::default(),
})
}
fn check_config(config: &Config) -> io::R... | }
/// Starts a multipart upload process.
async fn begin(&self) -> Result<String, RusotoError<CreateMultipartUploadError>> {
let output = self
.client
.create_multipart_upload(CreateMultipartUploadRequest {
bucket: self.bucket.clone(),
key: sel... | let _ = retry(|| self.abort()).await;
}
upload_res
} | random_line_split |
s3.rs | Send + Sync + 'static,
{
Self::check_config(config)?;
let client = new_client!(S3Client, config, dispatcher);
Ok(S3Storage {
config: config.clone(),
client,
_not_send: PhantomData::default(),
})
}
fn check_config(config: &Config) -> io::R... | (&self) -> Result<(), RusotoError<AbortMultipartUploadError>> {
self.client
.abort_multipart_upload(AbortMultipartUploadRequest {
bucket: self.bucket.clone(),
key: self.key.clone(),
upload_id: self.upload_id.clone(),
..Default::default(... | abort | identifier_name |
member_constraints.rs | use rustc_data_structures::fx::FxHashMap;
use rustc_index::vec::IndexVec;
use rustc_middle::infer::MemberConstraint;
use rustc_middle::ty::{self, Ty};
use rustc_span::Span;
use std::hash::Hash;
use std::ops::Index;
/// Compactly stores a set of `R0 member of [R1...Rn]` constraints,
/// indexed by the region `R0`.
crat... |
}
/// Given a linked list starting at `source_list` and another linked
/// list starting at `target_list`, modify `target_list` so that it is
/// followed by `source_list`.
///
/// Before:
///
/// ```
/// target_list: A -> B -> C -> (None)
/// source_list: D -> E -> F -> (None)
/// ```
///
/// After:
///
/// ```
/// ... | {
&self.constraints[i]
} | identifier_body |
member_constraints.rs | use rustc_data_structures::fx::FxHashMap;
use rustc_index::vec::IndexVec;
use rustc_middle::infer::MemberConstraint;
use rustc_middle::ty::{self, Ty};
use rustc_span::Span;
use std::hash::Hash;
use std::ops::Index;
/// Compactly stores a set of `R0 member of [R1...Rn]` constraints,
/// indexed by the region `R0`.
crat... | crate struct NllMemberConstraint<'tcx> {
next_constraint: Option<NllMemberConstraintIndex>,
/// The span where the hidden type was instantiated.
crate definition_span: Span,
/// The hidden type in which `R0` appears. (Used in error reporting.)
crate hidden_ty: Ty<'tcx>,
/// The region `R0`.
... | random_line_split | |
member_constraints.rs | use rustc_data_structures::fx::FxHashMap;
use rustc_index::vec::IndexVec;
use rustc_middle::infer::MemberConstraint;
use rustc_middle::ty::{self, Ty};
use rustc_span::Span;
use std::hash::Hash;
use std::ops::Index;
/// Compactly stores a set of `R0 member of [R1...Rn]` constraints,
/// indexed by the region `R0`.
crat... | (&self, pci: NllMemberConstraintIndex) -> &[ty::RegionVid] {
let NllMemberConstraint { start_index, end_index, .. } = &self.constraints[pci];
&self.choice_regions[*start_index..*end_index]
}
}
impl<'tcx, R> Index<NllMemberConstraintIndex> for MemberConstraintSet<'tcx, R>
where
R: Copy + Eq,
{
... | choice_regions | identifier_name |
keybindingParser.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | matchedModifier = true;
}
if (/^win(\+|\-)/.test(input)) {
meta = true;
input = input.substr('win-'.length);
matchedModifier = true;
}
if (/^cmd(\+|\-)/.test(input)) {
meta = true;
input = input.substr('cmd-'.length);
matchedModifier = true;
}
}
while (matchedModifier);
... | {
matchedModifier = false;
if (/^ctrl(\+|\-)/.test(input)) {
ctrl = true;
input = input.substr('ctrl-'.length);
matchedModifier = true;
}
if (/^shift(\+|\-)/.test(input)) {
shift = true;
input = input.substr('shift-'.length);
matchedModifier = true;
}
if (/^alt(\+|\-)/.test(inp... | conditional_block |
keybindingParser.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
static parseUserBinding(input: string): (SimpleKeybinding | ScanCodeBinding)[] {
if (!input) {
return [];
}
const parts: (SimpleKeybinding | ScanCodeBinding)[] = [];
let part: SimpleKeybinding | ScanCodeBinding;
while (input.length > 0) {
[part, input] = this.parseSimpleUserBinding(input);
parts... | {
const mods = this._readModifiers(input);
const scanCodeMatch = mods.key.match(/^\[([^\]]+)\]$/);
if (scanCodeMatch) {
const strScanCode = scanCodeMatch[1];
const scanCode = ScanCodeUtils.lowerCaseToEnum(strScanCode);
return [new ScanCodeBinding(mods.ctrl, mods.shift, mods.alt, mods.meta, scanCode), mod... | identifier_body |
keybindingParser.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | const scanCodeMatch = mods.key.match(/^\[([^\]]+)\]$/);
if (scanCodeMatch) {
const strScanCode = scanCodeMatch[1];
const scanCode = ScanCodeUtils.lowerCaseToEnum(strScanCode);
return [new ScanCodeBinding(mods.ctrl, mods.shift, mods.alt, mods.meta, scanCode), mods.remains];
}
const keyCode = KeyCodeUtil... | const mods = this._readModifiers(input); | random_line_split |
keybindingParser.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (input: string): (SimpleKeybinding | ScanCodeBinding)[] {
if (!input) {
return [];
}
const parts: (SimpleKeybinding | ScanCodeBinding)[] = [];
let part: SimpleKeybinding | ScanCodeBinding;
while (input.length > 0) {
[part, input] = this.parseSimpleUserBinding(input);
parts.push(part);
}
return ... | parseUserBinding | identifier_name |
mount.rs | use libc::{c_ulong, c_int};
use libc;
use {Errno, Result, NixPath};
bitflags!( | const MS_NOSUID = libc::MS_NOSUID; // Ignore suid and sgid bits
const MS_NODEV = libc::MS_NODEV; // Disallow access to device special files
const MS_NOEXEC = libc::MS_NOEXEC; // Disallow program execution
const MS_SYNCHRONOUS = libc::MS_SYNCHRONOUS; // Wri... | pub struct MsFlags: c_ulong {
const MS_RDONLY = libc::MS_RDONLY; // Mount read-only | random_line_split |
mount.rs | use libc::{c_ulong, c_int};
use libc;
use {Errno, Result, NixPath};
bitflags!(
pub struct MsFlags: c_ulong {
const MS_RDONLY = libc::MS_RDONLY; // Mount read-only
const MS_NOSUID = libc::MS_NOSUID; // Ignore suid and sgid bits
const MS_NODEV = libc::MS_NODEV; ... |
pub fn umount2<P: ?Sized + NixPath>(target: &P, flags: MntFlags) -> Result<()> {
let res = try!(target.with_nix_path(|cstr| {
unsafe { libc::umount2(cstr.as_ptr(), flags.bits) }
}));
Errno::result(res).map(drop)
}
| {
let res = try!(target.with_nix_path(|cstr| {
unsafe { libc::umount(cstr.as_ptr()) }
}));
Errno::result(res).map(drop)
} | identifier_body |
mount.rs | use libc::{c_ulong, c_int};
use libc;
use {Errno, Result, NixPath};
bitflags!(
pub struct MsFlags: c_ulong {
const MS_RDONLY = libc::MS_RDONLY; // Mount read-only
const MS_NOSUID = libc::MS_NOSUID; // Ignore suid and sgid bits
const MS_NODEV = libc::MS_NODEV; ... | <P: ?Sized + NixPath>(target: &P) -> Result<()> {
let res = try!(target.with_nix_path(|cstr| {
unsafe { libc::umount(cstr.as_ptr()) }
}));
Errno::result(res).map(drop)
}
pub fn umount2<P: ?Sized + NixPath>(target: &P, flags: MntFlags) -> Result<()> {
let res = try!(target.with_nix_path(|cstr| ... | umount | identifier_name |
types.js | 'use strict'; | * Visible page viewport
*
* @param {number} scrollX X scroll offset in CSS pixels.
* @param {number} scrollY Y scroll offset in CSS pixels.
* @param {number} contentsWidth Contents width in CSS pixels.
* @param {number} contentsHeight Contents height in CSS pixels.
* @param {number} pageScaleFactor... | // This file is auto-generated using scripts/doc-sync.js
/** | random_line_split |
do_release.py | # GitHub release artifact just before the release is actually cut.
CANDIDATE_VERSION_REPLACE = [
(re.compile(r'__version__\s*=\s*".*"'),
'__version__ = "{version-no-v}"'),
(re.compile(r'\*\*release\*\*'),
'{version}'),
(re.compile('http://www\.projectcalico\.org/latest/calicoctl'),
'http://... | random_line_split | ||
do_release.py | /calico.git@{calico-version}'),
(re.compile(r'git\+https://github\.com/projectcalico/libcalico\.git'),
'git+https://github.com/projectcalico/libcalico.git@{libcalico-version}'),
(re.compile(r'calico_docker_ver\s*=\s*"latest"'),
'calico_docker_ver = "{version}"'),
(re.compile('calico_node_ver... | complete | identifier_name | |
do_release.py | /projectcalico/calico.git@{calico-version}'),
(re.compile(r'git\+https://github\.com/projectcalico/libcalico\.git'),
'git+https://github.com/projectcalico/libcalico.git@{libcalico-version}'),
(re.compile(r'calico_docker_ver\s*=\s*"latest"'),
'calico_docker_ver = "{version}"'),
(re.compile('c... | """
Master branch is now checked out and needs updating.
"""
utils.check_or_exit("Is your git repository now on master")
# Update the master files.
utils.update_files(MASTER_VERSION_REPLACE, release_data["versions"],
is_release=False)
new_version = release_data["versions... | identifier_body | |
do_release.py | artifact for an arbitrary branch. This is replaced with the
# GitHub release artifact just before the release is actually cut.
CANDIDATE_VERSION_REPLACE = [
(re.compile(r'__version__\s*=\s*".*"'),
'__version__ = "{version-no-v}"'),
(re.compile(r'\*\*release\*\*'),
'{version}'),
(re.compile('ht... |
else:
subprocess.call("git push origin %s-candidate" % new_version, shell=True)
actions()
bullet("Create a DockerHub release called '%s'" % new_version)
bullet("Monitor the semaphore, CircleCI and Docker builds for this branch "
"until all have successfully completed. Fix any issues... | subprocess.call("git push -f origin %s-candidate" % new_version, shell=True) | conditional_block |
mod.rs | as `LintPass` instances. These run just before
//! translation to LLVM bytecode. The `LintPass`es built into rustc are defined
//! within `builtin.rs`, which has further comments on how to add such a lint.
//! rustc can also load user-defined lint plugins via the plugin mechanism.
//!
//! Some of rustc's lints are def... | Level | identifier_name | |
mod.rs | _might_
//! want to enforce, but might reasonably want to permit as well, on a
//! module-by-module basis. They contrast with static constraints enforced by
//! other phases of the compiler, which are generally required to hold in order
//! to compile the program at all.
//!
//! Most lints can be written as `LintPass`... |
fn check_struct_field(&mut self, _: &Context, _: &ast::StructField) { }
fn check_variant(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) { }
fn check_variant_post(&mut self, _: &Context, _: &ast::Variant, _: &ast::Generics) { }
fn check_opt_lifetime_ref(&mut self, _: &Context, _: Span, _: ... | { } | identifier_body |
mod.rs | user _might_
//! want to enforce, but might reasonably want to permit as well, on a
//! module-by-module basis. They contrast with static constraints enforced by
//! other phases of the compiler, which are generally required to hold in order
//! to compile the program at all.
//!
//! Most lints can be written as `Lint... | );
}
/// Declare a static `LintArray` and return it as an expression.
#[macro_export]
macro_rules! lint_array { ($( $lint:expr ),*) => (
{
#[allow(non_upper_case_globals)]
static array: LintArray = &[ $( &$lint ),* ];
array
}
) }
pub type LintArray = &'static [&'static &'static Lin... | = &lint_initializer!($name, $level, $desc); | random_line_split |
views.py | import logging
from requests_oauthlib import OAuth1Session
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from .models import QuickbooksToken, get_quickbooks_token
from... | access_token=response['oauth_token'],
access_token_secret=response['oauth_token_secret'],
realm_id=realm_id,
data_source=data_source)
# Cache blue dot menu
try:
request.session[BLUE_DOT_CACHE_KEY] = None
blue_dot_menu(request)
except AttributeError:
r... | session = OAuth1Session(client_key=settings.QUICKBOOKS['CONSUMER_KEY'],
client_secret=settings.QUICKBOOKS['CONSUMER_SECRET'],
resource_owner_key=request.session['qb_oauth_token'],
resource_owner_secret=request.session['qb_oauth_token_se... | identifier_body |
views.py | import logging
from requests_oauthlib import OAuth1Session
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from .models import QuickbooksToken, get_quickbooks_token
from... | try:
QuickbooksApi(token).disconnect()
except AuthenticationFailure:
# If there is an authentication error, then these tokens are bad
# We need to destroy them in any case.
pass
request.user.quickbookstoken_set.all().delete()
return HttpResponseRedirect(settings.QUICKBOO... |
token = get_quickbooks_token(request) | random_line_split |
views.py | import logging
from requests_oauthlib import OAuth1Session
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from .models import QuickbooksToken, get_quickbooks_token
from... |
access_token_callback = settings.QUICKBOOKS['OAUTH_CALLBACK_URL']
if callable(access_token_callback):
access_token_callback = access_token_callback(request)
session = OAuth1Session(client_key=settings.QUICKBOOKS['CONSUMER_KEY'],
client_secret=settings.QUICKBOOKS['CONSU... | del request.session[BLUE_DOT_CACHE_KEY] | conditional_block |
views.py | import logging
from requests_oauthlib import OAuth1Session
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from .models import QuickbooksToken, get_quickbooks_token
from... | (request):
""" Returns the blue dot menu. If possible a cached copy is returned.
"""
html = request.session.get(BLUE_DOT_CACHE_KEY)
if not html:
html = request.session[BLUE_DOT_CACHE_KEY] = \
HttpResponse(QuickbooksApi(request.user).app_menu())
return html
@login_required
def ... | blue_dot_menu | identifier_name |
AddCommand.py | # Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <bram@topydo.org>
#
# 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 3 of the License,... | (self, p_todo_text):
def _preprocess_input_todo(p_todo_text):
"""
Pre-processes user input when adding a task.
It detects a priority mid-sentence and puts it at the start.
"""
todo_text = re.sub(r'^(.+) (\([A-Z]\))(.*)$', r'\2 \1\3',
... | _add_todo | identifier_name |
AddCommand.py | # Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <bram@topydo.org>
#
# 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 3 of the License,... | f = stdin
else:
f = codecs.open(self.from_file, 'r', encoding='utf-8')
todos = f.read().splitlines()
return todos
def _add_todo(self, p_todo_text):
def _preprocess_input_todo(p_todo_text):
"""
Pre-processes user input when adding a t... | def __init__(self, p_args, p_todolist, # pragma: no branch
p_out=lambda a: None,
p_err=lambda a: None,
p_prompt=lambda a: None):
super().__init__(
p_args, p_todolist, p_out, p_err, p_prompt)
self.text = ' '.join(p_args)
self.from_fil... | identifier_body |
AddCommand.py | # Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <bram@topydo.org>
#
# 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 3 of the License,... | from sys import stdin
from topydo.lib.Config import config
from topydo.lib.prettyprinters.Numbers import PrettyPrinterNumbers
from topydo.lib.WriteCommand import WriteCommand
class AddCommand(WriteCommand):
def __init__(self, p_args, p_todolist, # pragma: no branch
p_out=lambda a: None,
... | from os.path import expanduser | random_line_split |
AddCommand.py | # Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <bram@topydo.org>
#
# 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 3 of the License,... |
else:
self.error(self.usage())
def usage(self):
return """Synopsis:
add <TEXT>
add -f <FILE> | -"""
def help(self):
return """\
This subcommand automatically adds the creation date to the added item.
TEXT may contain:
* Priorities mid-sentence. Example: add "... | self._add_todo(self.text) | conditional_block |
check_no_handler_pragma.ts | import {Issue} from "../issue";
import * as Statements from "../abap/2_statements/statements";
import {ABAPRule} from "./_abap_rule";
import {BasicRuleConfig} from "./_basic_rule_config";
import {StatementNode} from "../abap/nodes";
import {Comment} from "../abap/2_statements/statements/_statement";
import {IRuleMetada... |
public getConfig() {
return this.conf;
}
public setConfig(conf: CheckNoHandlerPragmaConf) {
this.conf = conf;
}
public runParsed(file: ABAPFile) {
const issues: Issue[] = [];
let noHandler: boolean = false;
const statements = file.getStatements();
for (let i = 0; i < statements.le... | {
return {
key: "check_no_handler_pragma",
title: "Check if NO_HANDLER can be removed",
shortDescription: `Checks NO_HANDLER pragmas that can be removed`,
tags: [RuleTag.SingleFile],
badExample: `TRY.
...
CATCH zcx_abapgit_exception ##NO_HANDLER.
RETURN. " it has a handler
EN... | identifier_body |
check_no_handler_pragma.ts | import {Issue} from "../issue";
import * as Statements from "../abap/2_statements/statements";
import {ABAPRule} from "./_abap_rule";
import {BasicRuleConfig} from "./_basic_rule_config";
import {StatementNode} from "../abap/nodes";
import {Comment} from "../abap/2_statements/statements/_statement";
import {IRuleMetada... | noHandler = false;
} else if (statement.get() instanceof Comment) {
continue;
} else if (noHandler === true && !(statement.get() instanceof Statements.Catch)) {
const message = "NO_HANDLER pragma or pseudo comment can be removed";
const issue = Issue.atStatement(file, stateme... | random_line_split | |
check_no_handler_pragma.ts | import {Issue} from "../issue";
import * as Statements from "../abap/2_statements/statements";
import {ABAPRule} from "./_abap_rule";
import {BasicRuleConfig} from "./_basic_rule_config";
import {StatementNode} from "../abap/nodes";
import {Comment} from "../abap/2_statements/statements/_statement";
import {IRuleMetada... | (): IRuleMetadata {
return {
key: "check_no_handler_pragma",
title: "Check if NO_HANDLER can be removed",
shortDescription: `Checks NO_HANDLER pragmas that can be removed`,
tags: [RuleTag.SingleFile],
badExample: `TRY.
...
CATCH zcx_abapgit_exception ##NO_HANDLER.
RETURN. " i... | getMetadata | identifier_name |
check_no_handler_pragma.ts | import {Issue} from "../issue";
import * as Statements from "../abap/2_statements/statements";
import {ABAPRule} from "./_abap_rule";
import {BasicRuleConfig} from "./_basic_rule_config";
import {StatementNode} from "../abap/nodes";
import {Comment} from "../abap/2_statements/statements/_statement";
import {IRuleMetada... |
}
return issues;
}
private containsNoHandler(statement: StatementNode, next: StatementNode | undefined): boolean {
for (const t of statement.getPragmas()) {
if (t.getStr().toUpperCase() === "##NO_HANDLER") {
return true;
}
}
if (next
&& next.get() instanceof Commen... | {
noHandler = this.containsNoHandler(statement, statements[i + 1]);
} | conditional_block |
browser-clean.js | /**
* @author ddchen
*/
var objectRinser = require("./objectRinser.js");
var originalEventRinser = require("./originalEventRinser.js");
var cleanRules = [];
var confs = null;
var addCleanRule = function(rule) {
cleanRules.push(rule);
}
var isFunction = function(fn) {
return !!fn && !fn.nodeName && fn.constructo... |
});
module.exports = {
addCleanRule: addCleanRule,
addEventIgnore: originalEventRinser.addEventIgnore,
record: function(opts) {
confs = opts || {};
objectRinser.record(confs.objects);
if (confs.events && confs.events.on === true) {
originalEventRinser.record(confs.events);
}
},
clean: function() {
f... | {
originalEventRinser.clean();
} | conditional_block |
browser-clean.js | /**
* @author ddchen
*/
var objectRinser = require("./objectRinser.js");
var originalEventRinser = require("./originalEventRinser.js");
var cleanRules = [];
var confs = null;
var addCleanRule = function(rule) {
cleanRules.push(rule);
}
| }
addCleanRule(function() {
objectRinser.clean();
if (confs.events && confs.events.on === true) {
originalEventRinser.clean();
}
});
module.exports = {
addCleanRule: addCleanRule,
addEventIgnore: originalEventRinser.addEventIgnore,
record: function(opts) {
confs = opts || {};
objectRinser.record(confs.obj... | var isFunction = function(fn) {
return !!fn && !fn.nodeName && fn.constructor != String &&
fn.constructor != RegExp && fn.constructor != Array &&
/function/i.test(fn + ""); | random_line_split |
custom_sharding.py | #!/usr/bin/env python
#
# Copyright 2015, Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
import unittest
import environment
import utils
import tablet
# shards
shard_0_master = tablet.Tablet()
shard_0_rdonly = tablet.Tablet()
sh... |
class TestCustomSharding(unittest.TestCase):
def _insert_data(self, shard, start, count, table='data'):
sql = 'insert into %s(id, name) values (:id, :name)' % table
for x in xrange(count):
bindvars = {
'id': start+x,
'name': 'row %d' % (start+x),
}
utils.vtgate.execut... | if utils.options.skip_teardown:
return
teardown_procs = [
shard_0_master.teardown_mysql(),
shard_0_rdonly.teardown_mysql(),
shard_1_master.teardown_mysql(),
shard_1_rdonly.teardown_mysql(),
]
utils.wait_procs(teardown_procs, raise_on_error=False)
environment.topo_server().teard... | identifier_body |
custom_sharding.py | #!/usr/bin/env python
#
# Copyright 2015, Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
import unittest
import environment
import utils
import tablet
# shards
shard_0_master = tablet.Tablet()
shard_0_rdonly = tablet.Tablet()
sh... | (self):
"""Runs through the common operations of a custom sharded keyspace.
Tests creation with one shard, schema change, reading / writing
data, adding one more shard, reading / writing data from both
shards, applying schema changes again, and reading / writing data
from both shards again.
"""... | test_custom_end_to_end | identifier_name |
custom_sharding.py | #!/usr/bin/env python
#
# Copyright 2015, Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
import unittest
import environment
import utils
import tablet
# shards
shard_0_master = tablet.Tablet()
shard_0_rdonly = tablet.Tablet()
sh... |
for t in [shard_0_master, shard_0_rdonly]:
t.wait_for_vttablet_state('SERVING')
utils.run_vtctl(['InitShardMaster', 'test_keyspace/0',
shard_0_master.tablet_alias], auto_log=True)
utils.run_vtctl(['RebuildKeyspaceGraph', 'test_keyspace'], auto_log=True)
ks = utils.run_vtctl... | t.create_db('vt_test_keyspace')
t.start_vttablet(wait_for_state=None) | conditional_block |
custom_sharding.py | #!/usr/bin/env python
#
# Copyright 2015, Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
import unittest
import environment
import utils
import tablet
# shards
shard_0_master = tablet.Tablet()
shard_0_rdonly = tablet.Tablet()
sh... | raise
def tearDownModule():
if utils.options.skip_teardown:
return
teardown_procs = [
shard_0_master.teardown_mysql(),
shard_0_rdonly.teardown_mysql(),
shard_1_master.teardown_mysql(),
shard_1_rdonly.teardown_mysql(),
]
utils.wait_procs(teardown_procs, raise_on_error=False... | tearDownModule() | random_line_split |
window.rs | WindowBuilder<'a> {
self.attribs.gl_robustness = robustness;
self
}
/// Requests that the window has vsync enabled.
pub fn with_vsync(mut self) -> WindowBuilder<'a> {
self.attribs.vsync = true;
self
}
/// Sets whether the window will be initially hidden or visible.... | self.window.make_current()
}
/// Returns true if this context is the current one in this thread.
#[inline]
pub fn is_current(&self) -> bool {
self.window.is_current()
}
/// Returns the address of an OpenGL function.
///
/// Contrary to `wglGetProcAddress`, all available... | pub unsafe fn make_current(&self) -> Result<(), ContextError> { | random_line_split |
window.rs | Builder<'a> {
self.attribs.gl_robustness = robustness;
self
}
/// Requests that the window has vsync enabled.
pub fn with_vsync(mut self) -> WindowBuilder<'a> {
self.attribs.vsync = true;
self
}
/// Sets whether the window will be initially hidden or visible.
pu... |
// default dimensions
if self.attribs.dimensions.is_none() {
self.attribs.dimensions = Some((1024, 768));
}
// building
platform::Window::new(self.attribs).map(|w| Window { window: w })
}
/// Builds the window.
///
/// The context is build in a *st... | {
self.attribs.dimensions = Some(self.attribs.monitor.as_ref().unwrap().get_dimensions())
} | conditional_block |
window.rs | should be very rare and only occur in case of permission denied, incompatible system,
/// out of memory, etc.
#[inline]
pub fn new() -> Result<Window, CreationError> {
let builder = WindowBuilder::new();
builder.build()
}
/// Modifies the title of the window.
///
/// This ... | {
self.proxy.wakeup_event_loop();
} | identifier_body | |
window.rs | (mut self, title: String) -> WindowBuilder<'a> {
self.attribs.title = title;
self
}
/// Requests fullscreen mode.
///
/// If you don't specify dimensions for the window, it will match the monitor's.
pub fn with_fullscreen(mut self, monitor: MonitorID) -> WindowBuilder<'a> {
... | with_title | identifier_name | |
urls.py | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
# not sure about line 7
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^dropzone-drag-drop/$', inc... |
if settings.DEBUG:
# urlpatterns add STATIC_URL and serves the STATIC_ROOT file
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT) | # not sure if I need an actual url wrapper in this code.
# url(r'^admin/varnish/', include('varnishapp.urls')),
)
| random_line_split |
urls.py | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
# not sure about line 7
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^dropzone-drag-drop/$', inc... | urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT) | conditional_block | |
client.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 OpenStack LLC.
# All Rights Reserved.
#
# 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/... | resp, body = httpclient.request("%sextensions" % url, "GET",
headers={'Accept': 'application/json'})
if resp.status in (200, 204): # in some cases we get No Content
try:
results = {}
if 'extensions' in... | url += '/' | random_line_split |
client.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 OpenStack LLC.
# All Rights Reserved.
#
# 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/... |
else:
# Support incorrect, but prevalent format
for extension in body['extensions']:
alias, name = self._get_extension_info(
extension)
... | for extension in body['extensions']['values']:
alias, name = self._get_extension_info(
extension['extension'])
results[alias] = name
return results | conditional_block |
client.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 OpenStack LLC.
# All Rights Reserved.
#
# 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/... | (self, url=None):
""" Discover Keystone servers and return API versions supported.
:param url: optional url to test (without version)
Returns::
{
'message': 'Keystone found at http://127.0.0.1:5000/',
'v2.0': {
'status': 'beta',
... | discover | identifier_name |
client.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 OpenStack LLC.
# All Rights Reserved.
#
# 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/... |
def discover(self, url=None):
""" Discover Keystone servers and return API versions supported.
:param url: optional url to test (without version)
Returns::
{
'message': 'Keystone found at http://127.0.0.1:5000/',
'v2.0': {
... | """ Initialize a new client for the Keystone v2.0 API. """
super(Client, self).__init__(endpoint=endpoint, **kwargs)
self.endpoint = endpoint | identifier_body |
index.d.ts | import * as React from "react";
import ReactToolbox from "../index";
export interface DropdownTheme {
/**
* Added to the root element when the dropdown is active.
*/
active?: string;
/**
* Added to the root element when it's disabled.
*/
disabled?: string;
/**
* Root element class.
*/
dro... | value?: string;
/**
* Used for the list of values.
*/
values?: string;
}
interface DropdownProps extends ReactToolbox.Props {
/**
* If true the dropdown will preselect the first item if the supplied value matches none of the options' values.
* @default true
*/
allowBlank?: boolean;
/**
* ... | random_line_split | |
index.d.ts | import * as React from "react";
import ReactToolbox from "../index";
export interface DropdownTheme {
/**
* Added to the root element when the dropdown is active.
*/
active?: string;
/**
* Added to the root element when it's disabled.
*/
disabled?: string;
/**
* Root element class.
*/
dro... | extends React.Component<DropdownProps, {}> { }
export default Dropdown;
| Dropdown | identifier_name |
build.server.prod.ts | import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import * as merge from 'merge-stream';
import { join/*, sep, relative*/ } from 'path';
import Config from '../../config';
import { makeTsProject, TemplateLocalsBuilder } from '../../utils';
import { TypeScriptTask } from '../typescript... | () {
const tsProject: any;
const typings = gulp.src([
Config.TOOLS_DIR + '/manual_typings/**/*.d.ts'
]);
const src = [
join(Config.APP_SERVER_SRC, '**/*.ts')
];
let projectFiles = gulp.src(src);
let result: any;
let isFullCompile = true;
// Only do... | run | identifier_name |
build.server.prod.ts | import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import * as merge from 'merge-stream';
import { join/*, sep, relative*/ } from 'path';
import Config from '../../config';
import { makeTsProject, TemplateLocalsBuilder } from '../../utils';
import { TypeScriptTask } from '../typescript... |
result = projectFiles
.pipe(plugins.plumber())
.pipe(plugins.sourcemaps.init())
.pipe(tsProject())
.on('error', () => {
typedBuildCounter = Config.TYPED_COMPILE_INTERVAL;
});
if (isFullCompile) {
typedBuildCounter = 0;
} else {
typed... | {
tsProject = makeTsProject();
projectFiles = merge(typings, projectFiles);
} | conditional_block |
build.server.prod.ts | import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import * as merge from 'merge-stream';
import { join/*, sep, relative*/ } from 'path';
import Config from '../../config';
import { makeTsProject, TemplateLocalsBuilder } from '../../utils';
import { TypeScriptTask } from '../typescript... | projectFiles = merge(typings, projectFiles);
}
result = projectFiles
.pipe(plugins.plumber())
.pipe(plugins.sourcemaps.init())
.pipe(tsProject())
.on('error', () => {
typedBuildCounter = Config.TYPED_COMPILE_INTERVAL;
});
if (isFullCompile) {... | {
const tsProject: any;
const typings = gulp.src([
Config.TOOLS_DIR + '/manual_typings/**/*.d.ts'
]);
const src = [
join(Config.APP_SERVER_SRC, '**/*.ts')
];
let projectFiles = gulp.src(src);
let result: any;
let isFullCompile = true;
// Only do a ... | identifier_body |
build.server.prod.ts | import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import * as merge from 'merge-stream';
import { join/*, sep, relative*/ } from 'path';
import Config from '../../config';
import { makeTsProject, TemplateLocalsBuilder } from '../../utils';
import { TypeScriptTask } from '../typescript... | /**
* Executes the build process, transpiling the TypeScript files (except the spec and e2e-spec files) for the development
* environment.
*/
export =
class BuildServerDev extends TypeScriptTask {
run() {
const tsProject: any;
const typings = gulp.src([
Config.TOOLS_DIR + '/manual_typings/*... | random_line_split | |
NumberUtil.ts | /**
* Provides helper functions for Number handling.
*
* @author Tim Duesterhus
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @module WoltLabSuite/Core/NumberUtil
*/
/**
* Decimal adjustment of a number.
*
* @see http... |
value = +value;
exp = +exp;
// If the value is not a number or the exp is not an integer...
if (isNaN(value) || !(typeof (exp as any) === "number" && exp % 1 === 0)) {
return NaN;
}
// Shift
let tmp = value.toString().split("e");
let exponent = tmp[1] ? +tmp[1] - exp : -exp;
value = Math.round(... | {
return Math.round(value);
} | conditional_block |
NumberUtil.ts | /**
* Provides helper functions for Number handling.
*
* @author Tim Duesterhus
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @module WoltLabSuite/Core/NumberUtil
*/
/**
* Decimal adjustment of a number.
*
* @see http... | (value: number, exp: number): number {
// If the exp is undefined or zero...
if (typeof exp === "undefined" || +exp === 0) {
return Math.round(value);
}
value = +value;
exp = +exp;
// If the value is not a number or the exp is not an integer...
if (isNaN(value) || !(typeof (exp as any) === "number" &... | round | identifier_name |
NumberUtil.ts | /**
* Provides helper functions for Number handling.
*
* @author Tim Duesterhus
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @module WoltLabSuite/Core/NumberUtil
*/
/**
* Decimal adjustment of a number.
*
* @see http... | }
// Shift
let tmp = value.toString().split("e");
let exponent = tmp[1] ? +tmp[1] - exp : -exp;
value = Math.round(+`${tmp[0]}e${exponent}`);
// Shift back
tmp = value.toString().split("e");
exponent = tmp[1] ? +tmp[1] + exp : exp;
return +`${tmp[0]}e${exponent}`;
} | random_line_split | |
NumberUtil.ts | /**
* Provides helper functions for Number handling.
*
* @author Tim Duesterhus
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @module WoltLabSuite/Core/NumberUtil
*/
/**
* Decimal adjustment of a number.
*
* @see http... | exponent = tmp[1] ? +tmp[1] + exp : exp;
return +`${tmp[0]}e${exponent}`;
}
| {
// If the exp is undefined or zero...
if (typeof exp === "undefined" || +exp === 0) {
return Math.round(value);
}
value = +value;
exp = +exp;
// If the value is not a number or the exp is not an integer...
if (isNaN(value) || !(typeof (exp as any) === "number" && exp % 1 === 0)) {
return NaN;
... | identifier_body |
libs.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
import datetime
import logging
import csv
import six
from datetime import date
from django.apps import apps
from django.utils import timezone
logger = logging.getLogger(__name__)
ats_settings = apps.get_app_config('ats')
def get_user_rea... |
def export_csv_task(datalist, add_header, new_line):
_s = ''
if six.PY2:
bufffer = six.BytesIO()
else:
bufffer = six.StringIO()
try:
if True:
_writer = csv.writer(
bufffer, lineterminator=new_line,
quotechar='"', quoting=csv.QUOTE_A... | _now = timezone.localtime()
_ret = _now.replace(day=1)
# logger.debug("get_thismonth_1st(): %s" % (_ret))
return _ret | identifier_body |
libs.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
import datetime
import logging
import csv
import six
from datetime import date
from django.apps import apps
from django.utils import timezone
logger = logging.getLogger(__name__)
ats_settings = apps.get_app_config('ats')
def get_user_rea... |
try:
if True:
_writer = csv.writer(
bufffer, lineterminator=new_line,
quotechar='"', quoting=csv.QUOTE_ALL)
if add_header:
_header = [
'date',
'project',
'code',
... | bufffer = six.StringIO() | conditional_block |
libs.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
import datetime
import logging
import csv
import six
from datetime import date
from django.apps import apps
from django.utils import timezone
logger = logging.getLogger(__name__)
ats_settings = apps.get_app_config('ats')
def get_user_rea... | ():
_now = timezone.localtime()
# logger.debug("get_localtime() : %s" % (_now))
return _now
def get_thismonth_1st():
_now = timezone.localtime()
_ret = _now.replace(day=1)
# logger.debug("get_thismonth_1st(): %s" % (_ret))
return _ret
def export_csv_task(datalist, add_header, new_li... | get_localtime | identifier_name |
libs.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
import datetime
import logging
import csv
import six
from datetime import date
from django.apps import apps
from django.utils import timezone
logger = logging.getLogger(__name__)
ats_settings = apps.get_app_config('ats')
def get_user_rea... | _now = timezone.localtime()
_ret = _now.replace(day=1)
# logger.debug("get_thismonth_1st(): %s" % (_ret))
return _ret
def export_csv_task(datalist, add_header, new_line):
_s = ''
if six.PY2:
bufffer = six.BytesIO()
else:
bufffer = six.StringIO()
try:
if True:
... | def get_thismonth_1st(): | random_line_split |
gulpfile.js | var gulp = require('gulp');
var exec = require('child_process').exec;
var mkdirs = require('mkdirs');
var browserify = require('gulp-browserify');
var rename = require('gulp-rename');
var autoprefixer = require('gulp-autoprefixer');
var sass = require('gulp-sass');
var nodemon = require('gulp-nodemon')
function | (command) {
return function (cb) {
exec(command, function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
cb(err);
});
}
}
gulp.task('create-data-folder', function() {
mkdirs('./mongodb/data');
});
//https://stackoverflow.com/questions/28665395/using-gulp-to-manage-op... | runCommand | identifier_name |
gulpfile.js | var gulp = require('gulp');
var exec = require('child_process').exec;
var mkdirs = require('mkdirs');
var browserify = require('gulp-browserify');
var rename = require('gulp-rename');
var autoprefixer = require('gulp-autoprefixer');
var sass = require('gulp-sass');
var nodemon = require('gulp-nodemon')
function runCo... | , env: { 'NODE_ENV': 'development' }
})
})
gulp.task('start-live', function () {
nodemon({
script: 'bin/www'
, ext: 'js html ejs'
, env: { 'NODE_ENV': 'development' }
})
})
gulp.task('live',['start-live']);
gulp.task('default', ['sass','scripts','start-mongo', 'watch','start']); | gulp.task('start', function () {
nodemon({
script: 'bin/www'
, ext: 'js html ejs' | random_line_split |
gulpfile.js | var gulp = require('gulp');
var exec = require('child_process').exec;
var mkdirs = require('mkdirs');
var browserify = require('gulp-browserify');
var rename = require('gulp-rename');
var autoprefixer = require('gulp-autoprefixer');
var sass = require('gulp-sass');
var nodemon = require('gulp-nodemon')
function runCo... |
gulp.task('create-data-folder', function() {
mkdirs('./mongodb/data');
});
//https://stackoverflow.com/questions/28665395/using-gulp-to-manage-opening-and-closing-mongodb
gulp.task('start-mongo', runCommand('mongod --dbpath ./mongodb/data/'));
gulp.task('stop-mongo', runCommand('mongo --eval "use admin; db.shutdo... | {
return function (cb) {
exec(command, function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
cb(err);
});
}
} | identifier_body |
as_bytes.rs | // Copyright 2016 blake2-rfc Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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... |
unsafe impl Safe for u8 {}
unsafe impl Safe for u16 {}
unsafe impl Safe for u32 {}
unsafe impl Safe for u64 {}
unsafe impl Safe for i8 {}
unsafe impl Safe for i16 {}
unsafe impl Safe for i32 {}
unsafe impl Safe for i64 {} | } | random_line_split |
as_bytes.rs | // Copyright 2016 blake2-rfc Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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... |
#[inline]
fn as_mut_bytes(&mut self) -> &mut [u8] {
unsafe {
slice::from_raw_parts_mut(self.as_mut_ptr() as *mut u8,
self.len() * mem::size_of::<T>())
}
}
}
unsafe impl Safe for u8 {}
unsafe impl Safe for u16 {}
unsafe impl Safe for u32 {}... | {
unsafe {
slice::from_raw_parts(self.as_ptr() as *const u8,
self.len() * mem::size_of::<T>())
}
} | identifier_body |
as_bytes.rs | // Copyright 2016 blake2-rfc Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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... | (&mut self) -> &mut [u8] {
unsafe {
slice::from_raw_parts_mut(self.as_mut_ptr() as *mut u8,
self.len() * mem::size_of::<T>())
}
}
}
unsafe impl Safe for u8 {}
unsafe impl Safe for u16 {}
unsafe impl Safe for u32 {}
unsafe impl Safe for u64 {}
unsafe... | as_mut_bytes | identifier_name |
test_hoursbalance_model.py | import datetime
import pytz
from django.utils import timezone
from django.contrib.auth.models import User
from django.test import TestCase
from gerencex.core.models import HoursBalance, Timing, Office
from gerencex.core.time_calculations import DateData
class HoursBalanceModelTest(TestCase):
@classmethod
de... | (cls):
cls.user = User.objects.create_user('testuser', 'test@user.com', 'senha123')
def test_balances(self):
r1 = HoursBalance.objects.create(
date=datetime.date(2016, 8, 18),
user=self.user,
credit=datetime.timedelta(hours=6).seconds,
debit=datetime.... | setUpTestData | identifier_name |
test_hoursbalance_model.py | import datetime
import pytz
from django.utils import timezone
from django.contrib.auth.models import User
from django.test import TestCase
from gerencex.core.models import HoursBalance, Timing, Office
from gerencex.core.time_calculations import DateData
class HoursBalanceModelTest(TestCase):
@classmethod
de... | def test_credit_triggers(self):
# Let's record a check in...
t1 = Timing.objects.create(
user=self.user,
date_time=timezone.make_aware(datetime.datetime(2016, 10, 3, 12, 0, 0, 0)),
checkin=True
)
# ...and a checkout
t2 = Timing.objects... | Office.objects.create(name='Nenhuma lotação',
initials='NL',
regular_work_hours=datetime.timedelta(hours=6))
User.objects.create_user('testuser', 'test@user.com', 'senha123')
cls.user = User.objects.get(username='testuser')
| identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.