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 |
|---|---|---|---|---|
tilemap.rs |
extern crate gl;
extern crate nalgebra;
use gl::types::*;
use nalgebra::na::{Mat4};
use nalgebra::na;
use std::mem;
use std::ptr;
use super::engine;
use super::shader;
use super::math;
//static CHUNK_SIZE : u8 = 10;
pub struct |
{
shader :shader::ShaderProgram,
vao : u32,
vbo_vertices : u32,
vbo_indices: u32,
vbo_tileid : u32,
indices_count : u32
//save model matrix
//hold ref/owned to TilemapChunkData logical part?
// tile_texture_atlas
// tile_texture_atlas_normal? <- normal map for tiles?
}
impl TilemapChunk
{
pub fn new(... | TilemapChunk | identifier_name |
key-is-lower-than-zero.js | // Copyright (C) 2016 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-integer-indexed-exotic-objects-hasproperty-p
description: Return false if P's value is < 0
info: |
9.4.5.2 [[HasProperty]](P)
...
3. If Type(P) is String, then... | // Prevents false positives using OrdinaryHasProperty
TypedArray.prototype[-1] = "test262";
testWithBigIntTypedArrayConstructors(function(TA) {
var sample = new TA(1);
assert.sameValue(Reflect.has(sample, "-1"), false, 'Reflect.has(sample, "-1") must return false');
}); | random_line_split | |
actions.js | /**
* This file specifies any system Action permission keys that are used by the
* apps in this Module.
* | * Action Keys are assigned to a user in the system by the Roles & Permission
* system. An Action Key is a unique string usually specified in the following
* format: "[application].[subapp].[verb]" which represents permission to
* perform [verb] for the [subapp] portion of the [application].
*
* [verbs] can ... | random_line_split | |
param_tcp_rxbufsize_8k.py | from trex_astf_lib.api import *
# IPV6 tunable example
#
# ipv6.src_msb
# ipv6.dst_msb
# ipv6.enable
#
class Prof1():
|
return ASTFProfile(default_ip_gen=ip_gen,
# Defaults affects all files
default_c_glob_info=c_glob_info,
default_s_glob_info=s_glob_info,
cap_list=[
ASTFCapInfo(file... | def __init__(self):
pass
def get_profile(self, **kwargs):
# ip generator
ip_gen_c = ASTFIPGenDist(ip_range=["16.0.0.0", "16.0.0.255"], distribution="seq")
ip_gen_s = ASTFIPGenDist(ip_range=["48.0.0.0", "48.0.255.255"], distribution="seq")
ip_gen = ASTFIPGen(glob=ASTFIPGenGl... | identifier_body |
param_tcp_rxbufsize_8k.py | from trex_astf_lib.api import *
# IPV6 tunable example
#
# ipv6.src_msb
# ipv6.dst_msb
# ipv6.enable
#
class Prof1():
def __init__(self):
pass
def get_profile(self, **kwargs):
# ip generator
ip_gen_c = ASTFIPGenDist(ip_range=["16.0.0.0", "16.0.0.255"], distribution="seq")
... | ():
return Prof1()
| register | identifier_name |
param_tcp_rxbufsize_8k.py | from trex_astf_lib.api import *
# IPV6 tunable example
#
# ipv6.src_msb
# ipv6.dst_msb
# ipv6.enable
#
class Prof1():
def __init__(self):
pass
def get_profile(self, **kwargs):
# ip generator
ip_gen_c = ASTFIPGenDist(ip_range=["16.0.0.0", "16.0.0.255"], distribution="seq")
... | def register():
return Prof1() | random_line_split | |
projects.py | # -*- coding: utf-8 -*-
# Copyright (C) 2010-2014 GRNET S.A.
#
# 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, or
# (at your option) any later version.
#
# This ... | """Test if project quota are measured properly."""
# Get the reported description of the resource.
resource = Resource.objects.get(name=u"σέρβις1.ρίσορς11")
desc = resource.report_desc
# Get the member and project quota.
member_quota = get_project_quota_category(self.project, "m... | identifier_body | |
projects.py | # -*- coding: utf-8 -*-
# Copyright (C) 2010-2014 GRNET S.A.
#
# 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, or
# (at your option) any later version.
#
# This ... | (self):
"""Test if project quota are measured properly."""
# Get the reported description of the resource.
resource = Resource.objects.get(name=u"σέρβις1.ρίσορς11")
desc = resource.report_desc
# Get the member and project quota.
member_quota = get_project_quota_category(... | test_quota | identifier_name |
projects.py | # -*- coding: utf-8 -*-
# Copyright (C) 2010-2014 GRNET S.A.
#
# 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, or | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#import logging
from astakos.im.models import Resource
from synne... | # (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of | random_line_split |
test_cc2_tensor.py | #!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright 2014 Nervana Systems Inc.
# 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
#
# ... |
@nottest # TODO: add scalar assignment to self.gpt class
def test_scalar_slice_assignment(self):
tns = self.gpt([[1, 2], [3, 4]])
tns[1, 0] = 9
assert_tensor_equal(tns, self.gpt([[1, 2], [9, 4]]))
def test_asnumpyarray(self):
tns = self.gpt([[1, 2], [3, 4]])
res =... | tns = self.gpt([[1, 2], [3, 4]])
res = tns[0:2, 0]
assert res.shape == (2, 1)
assert_tensor_equal(res, self.gpt([1, 3])) | identifier_body |
test_cc2_tensor.py | #!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright 2014 Nervana Systems Inc.
# 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
#
# ... | (self):
shapes = ((1, 1, 1), (1, 2, 3, 4), (1, 2, 3, 4, 5, 6, 7))
for shape in shapes:
tns = self.gpt(np.empty(shape))
assert tns.shape == shape
def test_str(self):
tns = self.gpt([[1, 2], [3, 4]])
assert str(tns) == "[[ 1. 2.]\n [ 3. 4.]]"
def test_sc... | test_higher_dim_creation | identifier_name |
test_cc2_tensor.py | #!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright 2014 Nervana Systems Inc.
# 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
#
# ... |
assert tns.shape == expected_shape
def test_2d_creation(self):
tns = self.gpt([[1, 2], [3, 4]])
expected_shape = (2, 2)
while len(expected_shape) < tns._min_dims:
expected_shape += (1, )
assert tns.shape == expected_shape
def test_2d_ndarray_creation(self):... | expected_shape += (1, ) | conditional_block |
test_cc2_tensor.py | #!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright 2014 Nervana Systems Inc.
# 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
#
# ... | def test_asnumpyarray(self):
tns = self.gpt([[1, 2], [3, 4]])
res = tns.asnumpyarray()
assert isinstance(res, np.ndarray)
assert_tensor_equal(res, np.array([[1, 2], [3, 4]]))
@nottest # TODO: fix this for self.gpt
def test_transpose(self):
tns = self.gpt([[1, 2], [3... | tns[1, 0] = 9
assert_tensor_equal(tns, self.gpt([[1, 2], [9, 4]]))
| random_line_split |
index.js | import React from 'react';
import { render } from 'react-dom';
import App from './components/app.js';
import Login from './components/Login.js';
import About from './components/About.js';
import MyApp from './components/MyApp.js';
import MyServer from './components/MyServer.js';
import AllApps from './components/AllApp... |
});
});
};
store.subscribe(() => {
const state = store.getState();
localStorage.setItem('state', JSON.stringify(state));
});
restoreSession()
.then(() => {
render(
<Provider store={store}>
<Router history={history}>
<Route path="/login" component={Login} />
<Route p... | {
resolve(res.text);
} | conditional_block |
index.js | import React from 'react';
import { render } from 'react-dom';
import App from './components/app.js';
import Login from './components/Login.js';
import About from './components/About.js';
import MyApp from './components/MyApp.js';
import MyServer from './components/MyServer.js';
import AllApps from './components/AllApp... | console.log('LO hit');
auth.logout();
store.dispatch(actions.USER_RESET());
window.location.href = '/login';
};
const restoreSession = () => {
return new Promise((resolve, reject) => {
resthandler.get('/user/sessionreload', (err, res) => {
if (err) {
console.log(err);
} else {
... |
const logout = () => { | random_line_split |
front.py | ##########
import web
import hmac
from time import strftime
from datetime import datetime
from hashlib import sha256
from lib.utils import db
from lib.utils import render
from lib.utils import etherpad
from lib.validate import valid_user, valid_pw, make_salt
##########
class FrontPage:
def GET(self):
r... | raise web.seeother('/') | conditional_block | |
front.py | ##########
import web
import hmac
from time import strftime
from datetime import datetime
from hashlib import sha256
from lib.utils import db
from lib.utils import render
from lib.utils import etherpad
from lib.validate import valid_user, valid_pw, make_salt
##########
class FrontPage:
def GET(self):
|
def POST(self):
uid = web.input().signup_uid
pw = web.input().signup_pw
if valid_user(uid) and valid_pw(pw):
# Makes random 16-character alphabet
# Stored in the db
salt = make_salt()
# Specifies that hmac uses sha256 instead of md... | return render('front.html') | identifier_body |
front.py | ##########
import web
import hmac
from time import strftime
from datetime import datetime
from hashlib import sha256
from lib.utils import db
from lib.utils import render
from lib.utils import etherpad
from lib.validate import valid_user, valid_pw, make_salt
##########
class FrontPage:
def | (self):
return render('front.html')
def POST(self):
uid = web.input().signup_uid
pw = web.input().signup_pw
if valid_user(uid) and valid_pw(pw):
# Makes random 16-character alphabet
# Stored in the db
salt = make_salt()
# Sp... | GET | identifier_name |
front.py | ##########
import web
import hmac
from time import strftime
from datetime import datetime
from hashlib import sha256
from lib.utils import db
from lib.utils import render
from lib.utils import etherpad
from lib.validate import valid_user, valid_pw, make_salt
##########
class FrontPage:
def GET(self):
r... | # Specifies that hmac uses sha256 instead of md5
# hmac complicates the hash
hashed_pw = hmac.new(salt, pw, sha256).hexdigest()
db.insert('users', username = uid,
pw = hashed_pw, salt = salt,
joined = datetime.now())
... | random_line_split | |
user-security-question.component.ts | import Swal from 'sweetalert2';
import {Component} from '@angular/core';
import {UserService} from "./user.service";
import {UserSecurityModel, UserModel} from "./user.model";
import {Validators, FormBuilder, FormGroup} from "@angular/forms";
import {QUESTION_LIST} from '../../../shared/configs/security-question.config... |
}
successStatusMessage(res:any) {
Swal("Success !", res.message, "success");
this.triggerCancelForm();
}
errorMessage(objResponse:any) {
Swal("Alert !", objResponse, "info");
}
triggerCancelForm() {
if(this.showCancel)
this.router.navigate(['/user-... | {
this._objUserService.updateSecurityQuestion(this.objUserSecurity)
.subscribe(res => this.successStatusMessage(res),
error => this.errorMessage);
} | conditional_block |
user-security-question.component.ts | import Swal from 'sweetalert2'; | import {Validators, FormBuilder, FormGroup} from "@angular/forms";
import {QUESTION_LIST} from '../../../shared/configs/security-question.config';
import { Router } from '@angular/router';
import { Config } from '../../../shared/configs/general.config';
@Component({
selector: 'user-security',
templateUrl: './u... | import {Component} from '@angular/core';
import {UserService} from "./user.service";
import {UserSecurityModel, UserModel} from "./user.model"; | random_line_split |
user-security-question.component.ts | import Swal from 'sweetalert2';
import {Component} from '@angular/core';
import {UserService} from "./user.service";
import {UserSecurityModel, UserModel} from "./user.model";
import {Validators, FormBuilder, FormGroup} from "@angular/forms";
import {QUESTION_LIST} from '../../../shared/configs/security-question.config... |
}
| {
if(this.showCancel)
this.router.navigate(['/user-management']);
else
this.router.navigate(['/profile/security']);
} | identifier_body |
user-security-question.component.ts | import Swal from 'sweetalert2';
import {Component} from '@angular/core';
import {UserService} from "./user.service";
import {UserSecurityModel, UserModel} from "./user.model";
import {Validators, FormBuilder, FormGroup} from "@angular/forms";
import {QUESTION_LIST} from '../../../shared/configs/security-question.config... | () {
if(this.showCancel)
this.router.navigate(['/user-management']);
else
this.router.navigate(['/profile/security']);
}
}
| triggerCancelForm | identifier_name |
stage.ts | 'use strict';
import { Class, Instance, isInstanceOf } from 'immutable-class';
export interface MarinParameters {
left?: number;
right?: number;
top?: number;
bottom?: number;
}
export interface StageValue {
x: number;
y: number;
width: number;
height: number;
}
// ToDo: make this a higher object
ex... | x: rect.left,
y: rect.top,
width: rect.width,
height: rect.height
});
}
static fromSize(width: number, height: number): Stage {
return new Stage({
x: 0,
y: 0,
width,
height
});
}
public x: number;
public y: number;
public width: number;
public... | static fromClientRect(rect: ClientRect): Stage {
return new Stage({ | random_line_split |
stage.ts | 'use strict';
import { Class, Instance, isInstanceOf } from 'immutable-class';
export interface MarinParameters {
left?: number;
right?: number;
top?: number;
bottom?: number;
}
export interface StageValue {
x: number;
y: number;
width: number;
height: number;
}
// ToDo: make this a higher object
ex... |
if (bottom) {
value.height -= bottom;
}
return new Stage(value);
}
}
| {
value.y = top;
value.height -= top;
} | conditional_block |
stage.ts | 'use strict';
import { Class, Instance, isInstanceOf } from 'immutable-class';
export interface MarinParameters {
left?: number;
right?: number;
top?: number;
bottom?: number;
}
export interface StageValue {
x: number;
y: number;
width: number;
height: number;
}
// ToDo: make this a higher object
ex... |
public getTransform(): string {
return `translate(${this.x},${this.y})`;
}
public within(param: MarinParameters): Stage {
var value = this.sizeOnlyValue();
var { left, right, top, bottom } = param;
if (left) {
value.x = left;
value.width -= left;
}
if (right) {
value... | {
return `[stage: ${this.width}x${this.height}}]`;
} | identifier_body |
stage.ts | 'use strict';
import { Class, Instance, isInstanceOf } from 'immutable-class';
export interface MarinParameters {
left?: number;
right?: number;
top?: number;
bottom?: number;
}
export interface StageValue {
x: number;
y: number;
width: number;
height: number;
}
// ToDo: make this a higher object
ex... | (): string {
return `translate(${this.x},${this.y})`;
}
public within(param: MarinParameters): Stage {
var value = this.sizeOnlyValue();
var { left, right, top, bottom } = param;
if (left) {
value.x = left;
value.width -= left;
}
if (right) {
value.width -= right;
}
... | getTransform | identifier_name |
ViewGenerator.ts | /*
* Copyright (C) 2020 Graylog, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; withou... | * <http://www.mongodb.com/licensing/server-side-public-license>.
*/
import View from './View';
import ViewStateGenerator from './ViewStateGenerator';
import type { ViewType } from './View';
import Search from '../search/Search';
import QueryGenerator from '../queries/QueryGenerator';
export default async (type: Vie... | * You should have received a copy of the Server Side Public License
* along with this program. If not, see | random_line_split |
rightLogShift.js | 'use strict';
module.exports = function (math, config) {
var util = require('../../util/index'),
Matrix = math.type.Matrix,
Unit = require('../../type/Unit'),
collection = math.collection,
isBoolean = util['boolean'].isBoolean,
isInteger = util.number.isInteger,
isNumber = util.... |
if (isCollection(x) && isNumber(y)) {
return collection.deepMap2(x, y, rightLogShift);
}
if (isBoolean(x) || x === null) {
return rightLogShift(+x, y);
}
if (isBoolean(y) || y === null) {
return rightLogShift(x, +y);
}
throw new math.error.UnsupportedTypeError('rightLog... | {
if (!isInteger(x) || !isInteger(y)) {
throw new Error('Parameters in function rightLogShift must be integer numbers');
}
return x >>> y;
} | conditional_block |
rightLogShift.js | 'use strict';
module.exports = function (math, config) {
var util = require('../../util/index'),
Matrix = math.type.Matrix,
Unit = require('../../type/Unit'),
collection = math.collection,
isBoolean = util['boolean'].isBoolean,
isInteger = util.number.isInteger, | isCollection = collection.isCollection;
/**
* Bitwise right logical shift of value x by y number of bits, `x >>> y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.rightLogShift(x, y)
*
*... | isNumber = util.number.isNumber, | random_line_split |
public_map.js | /**
* Necessary tasks for public map(vis) view
*
*/
$(function() {
$.extend( $.easing, {
easeInQuad: function (x, t, b, c, d) { | }
});
cdb.init(function() {
cdb.config.set(config);
if (cdb.config.isOrganizationUrl()) cdb.config.set('url_prefix', cdb.config.organizationUrl());
cdb.templates.namespace = 'cartodb/';
// No attributions and no links in this map (at least from cartodb)
cartodb.config.set({... | return c*(t/=d)*t + b; | random_line_split |
Gruntfile.js | /*
* grunt-assetic-dump
* https://github.com/adam187/grunt-assetic-dump
*
* Copyright (c) 2013 Adam Misiorny |
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>',
],
options: {
jshintrc: '.jshintrc',
},
},
// Before generating any new files,... | * Licensed under the MIT license.
*/ | random_line_split |
background.js | function contextMenusOnClick(info,tab,opt) {
var balloon;
chrome.tabs.getSelected(null, function(tab) { // get selected string in current tab
chrome.tabs.executeScript(tab.id,{file:'js/content.js',allFrames:true},function() {
chrome.tabs.getSelected(null, function(tab) { // get selected string in current tab
... | (opt){
var optString = '';
var L = JSONSwitch(LANGUAGES);
optString += opt.split('|')[0] ? L[opt.split('|')[0]] : t('detectLanguage');
optString += ' » ';
optString += opt.split('|')[1] ? L[opt.split('|')[1]] : t('detectLanguage');
chrome.contextMenus.create({
"title": optString,
"contexts":['selection'],
"... | createcontextMenusOption | identifier_name |
background.js | function contextMenusOnClick(info,tab,opt) {
var balloon;
chrome.tabs.getSelected(null, function(tab) { // get selected string in current tab
chrome.tabs.executeScript(tab.id,{file:'js/content.js',allFrames:true},function() {
chrome.tabs.getSelected(null, function(tab) { // get selected string in current tab
... | var preferred = JSON.parse(localStorage.getItem('preferred'));
chrome.contextMenus.removeAll();
for (var i = 0, max = preferred.length; i < max; i++) {
createcontextMenusOption(preferred[i]);
}
}
$(document).ready(function(){
LANGUAGES = {};
LOCALE = "";
chrome.i18n.getAcceptLanguages( function(L) {
LOCALE... |
localStorage.setItem('preferred', JSON.stringify(["|"+window.navigator.language]));
window.open('options.html');
}
| conditional_block |
background.js | function contextMenusOnClick(info,tab,opt) | });
},
'error' : function(jqXHR, textStatus, errorThrown) {
var T = 'ERROR! ' + textStatus;
chrome.tabs.getSelected(null, function(tab) { // get selected string in current tab
chrome.tabs.executeScript(tab.id,{file:'js/content.js',allFrames:true},function() {injCallBack(T)});
... | {
var balloon;
chrome.tabs.getSelected(null, function(tab) { // get selected string in current tab
chrome.tabs.executeScript(tab.id,{file:'js/content.js',allFrames:true},function() {
chrome.tabs.getSelected(null, function(tab) { // get selected string in current tab
chrome.tabs.sendRequest(tab.id,{'method':'... | identifier_body |
background.js | function contextMenusOnClick(info,tab,opt) {
var balloon;
chrome.tabs.getSelected(null, function(tab) { // get selected string in current tab
chrome.tabs.executeScript(tab.id,{file:'js/content.js',allFrames:true},function() { | var F = info.selectionText;
$.ajax({
url : 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate',
data : {
'appId' : '76518BFCEBBF18E107C7073FBD4A735001B56BB1',
'text' : F,
'from' : opt.split("|")[0],
'to' : opt.split("|")[1],
'c... | chrome.tabs.getSelected(null, function(tab) { // get selected string in current tab
chrome.tabs.sendRequest(tab.id,{'method':'prepareBalloon'},function(){ | random_line_split |
editor.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
/**
* The right hand side URI to open inside a diff editor.
*/
rightResource: URI;
}
export interface IResourceSideBySideInput extends IBaseResourceInput {
/**
* The right hand side URI to open inside a side by side editor.
*/
masterResource: URI;
/**
* The left hand side URI to open inside a side by... | */
leftResource: URI; | random_line_split |
ScrollBar.py | #
# This file is part of GNU Enterprise.
#
# GNU Enterprise 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, or (at your option) any later version.
#
# GNU Enterprise is distributed ... |
return
elif ch == Container.TokLeftArrow:
self._Dec(None,None,None)
elif ch == Container.TokRightArrow:
self._Inc(None, None, None)
def _ChangePos(self,arg1,arg2,newX):
X = newX - self.start
if X >= (self.WorkingArea-1):
val = self._max
else:
v... | BACKWARDS = 1 | conditional_block |
ScrollBar.py | #
# This file is part of GNU Enterprise.
#
# GNU Enterprise 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, or (at your option) any later version.
#
# GNU Enterprise is distributed ... |
def _Inc(self, arg1,arg2,arg3):
self.Inc(None,None,None)
self._Action()
def Set(self,newVal):
if newVal < 0:
newVal = 0
elif newVal > self._max:
newVal =self._max
self._val = newVal
self.Paint(None,None,None)
def __del__(self):
Parent = self.PARENT
... | if self._val < self._max:
self._val += 1
self.Paint(None,None,None) | identifier_body |
ScrollBar.py | #
# This file is part of GNU Enterprise.
#
# GNU Enterprise 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, or (at your option) any later version.
#
# GNU Enterprise is distributed ... | (self,arg1,arg2,arg3):
if self._val < self._max:
self._val += 1
self.Paint(None,None,None)
def _Inc(self, arg1,arg2,arg3):
self.Inc(None,None,None)
self._Action()
def Set(self,newVal):
if newVal < 0:
newVal = 0
elif newVal > self._max:
newVal =self._max
... | Inc | identifier_name |
ScrollBar.py | #
# This file is part of GNU Enterprise.
#
# GNU Enterprise 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, or (at your option) any later version.
#
# GNU Enterprise is distributed ... | BACKWARDS = 1
return
elif ch == Container.TokLeftArrow:
self._Dec(None,None,None)
elif ch == Container.TokRightArrow:
self._Inc(None, None, None)
def _ChangePos(self,arg1,arg2,newX):
X = newX - self.start
if X >= (self.WorkingArea-1):
val = self._... | if ch == Container.TokUpArrow:
| random_line_split |
main.rs | use std::collections::HashSet;
fn main() {
struct PentNums {
n: usize,
curr: usize
}
impl PentNums {
fn new(index: usize) -> PentNums {
if index == 0 |
PentNums{n: index, curr: PentNums::get(index)}
}
fn get(index: usize) -> usize {
(index * ((index * 3) - 1)) / 2
}
}
impl Iterator for PentNums {
type Item = usize;
fn next(&mut self) -> Option<usize> {
self.n += 1;
sel... | {
return PentNums{n: index, curr: 0};
} | conditional_block |
main.rs | use std::collections::HashSet;
fn main() {
struct PentNums {
n: usize,
curr: usize
}
impl PentNums {
fn new(index: usize) -> PentNums {
if index == 0 {
return PentNums{n: index, curr: 0};
}
PentNums{n: index, curr: PentNums::get... | (a: usize, b: usize, mut h: &mut HashSet<usize>) -> bool {
if a >= b {
return false;
}
let e = a + b;
// println!("{:?}", e);
if !is_pent(e, &mut h) {
return false;
}
let d = b - a;
// println!("{:?}", d);
if !is_pent(... | sum_diff_pent | identifier_name |
main.rs | use std::collections::HashSet;
fn main() {
struct PentNums {
n: usize,
curr: usize
}
impl PentNums {
fn new(index: usize) -> PentNums {
if index == 0 {
return PentNums{n: index, curr: 0};
}
PentNums{n: index, curr: PentNums::get... |
// assumes a and b are pentagonal
fn sum_diff_pent(a: usize, b: usize, mut h: &mut HashSet<usize>) -> bool {
if a >= b {
return false;
}
let e = a + b;
// println!("{:?}", e);
if !is_pent(e, &mut h) {
return false;
}
let d = ... | {
if h.contains(&num) {
return true
}
let mut p = PentNums::new(h.len());
for elem in p {
if num == elem {
h.insert(num);
return true;
} else if elem > num {
return false;
}
}
... | identifier_body |
main.rs | use std::collections::HashSet;
fn main() {
struct PentNums {
n: usize,
curr: usize
}
impl PentNums {
fn new(index: usize) -> PentNums {
if index == 0 {
return PentNums{n: index, curr: 0};
}
PentNums{n: index, curr: PentNums::get... | }
'outer: for curr in pA {
// println!("{:?}", curr);
let mut pB = PentNums::new(4)
.take(2500)
.collect::<Vec<_>>();
for elem in pB {
// println!("{:?}", elem);
if elem >= curr {
continue 'outer;
}
... | h.insert(num); | random_line_split |
makemessages.py | else:
old = '#: ' + work_file[2:]
new = '#: ' + orig_file[2:]
msgs = msgs.replace(old, new)
write_pot_file(potfile, msgs)
if is_templatized:
os.unlink(work_file)
def write_pot_file(potfile, msgs):
"""
Write t... | continue | conditional_block | |
makemessages.py | -wrap', action='store_true', dest='no_wrap',
default=False, help="Don't break long message lines into several lines.")
parser.add_argument('--no-location', action='store_true', dest='no_location',
default=False, help="Don't write '#: filename:line' lines.")
parser.add_argumen... | write_po_file | identifier_name | |
makemessages.py |
@property
def path(self):
return os.path.join(self.dirpath, self.file)
def process(self, command, domain):
"""
Extract translatable literals from self.file for :param domain:,
creating or updating the POT file.
Uses the xgettext GNU gettext utility.
... | return self.path < other.path | identifier_body | |
makemessages.py | text_noop',
'--keyword=gettext_lazy',
'--keyword=ngettext_lazy:1,2',
'--keyword=pgettext:1c,2',
'--keyword=npgettext:1c,2,3',
'--output=-'
] + command.xgettext_options
args.append(work_file)
elif doma... | action='append')
parser.add_argument('--symlinks', '-s', action='store_true', dest='symlinks',
default=False, help='Follows symlinks to directories when examining '
'source code and templates for translation strings.')
parser.add_argument('--ig... | help='The file extension(s) to examine (default: "html,txt", or "js" '
'if the domain is "djangojs"). Separate multiple extensions with '
'commas, or use -e multiple times.',
| random_line_split |
urls.py | from django.conf.urls import url
from . import views
urlpatterns = [ # pylint:disable=invalid-name
url(r'^status$', views.Control.as_view()),
url(r'^status/(?P<group>([0-9]))$', views.Control.as_view()),
url(r'^control/(?P<command>([a-z_-]+))/(?P<group>([0-9]))$',
views.Control.as_view()),
url... | views.ControlPerSource.as_view()),
url(r'^timed/(?P<command>([a-z-_]+))/(?P<action>([a-z-_]+))$',
views.TimedProgram.as_view()),
] | url(r'^control/source/(?P<source>([a-z_-]+))/(?P<command>([a-z_-]+))$', | random_line_split |
paragraph.ts | import { OpenXmlElement } from "./dom";
import { CommonProperties, Length, ns, parseCommonProperty } from "./common";
import { Borders } from "./border";
import { parseSectionProperties, SectionProperties } from "./section";
import { LineSpacing, parseLineSpacing } from "./line-spacing";
import { XmlParser } from "../p... |
export function parseParagraphProperty(elem: Element, props: ParagraphProperties, xml: XmlParser) {
if (elem.namespaceURI != ns.wordml)
return false;
if(parseCommonProperty(elem, props, xml))
return true;
switch (elem.localName) {
case "tabs":
props.tabs = parseTabs(e... | {
let result = <ParagraphProperties>{};
for(let el of xml.elements(elem)) {
parseParagraphProperty(el, result, xml);
}
return result;
} | identifier_body |
paragraph.ts | import { OpenXmlElement } from "./dom";
import { CommonProperties, Length, ns, parseCommonProperty } from "./common";
import { Borders } from "./border";
import { parseSectionProperties, SectionProperties } from "./section";
import { LineSpacing, parseLineSpacing } from "./line-spacing";
import { XmlParser } from "../p... | (elem: Element, xml: XmlParser): ParagraphNumbering {
var result = <ParagraphNumbering>{};
for (let e of xml.elements(elem)) {
switch (e.localName) {
case "numId":
result.id = xml.attr(e, "val");
break;
case "ilvl":
result.level =... | parseNumbering | identifier_name |
paragraph.ts | import { OpenXmlElement } from "./dom";
import { CommonProperties, Length, ns, parseCommonProperty } from "./common";
import { Borders } from "./border";
import { parseSectionProperties, SectionProperties } from "./section";
import { LineSpacing, parseLineSpacing } from "./line-spacing";
import { XmlParser } from "../p... |
case "keepNext":
props.keepLines = xml.boolAttr(elem, "val", true);
break;
case "keepNext":
props.keepNext = xml.boolAttr(elem, "val", true);
break;
case "pageBreakBefore":
props.pageBreakBefore = xml.boolAttr(elem, "val"... |
case "textAlignment":
props.textAlignment = xml.attr(elem, "val");
return false; //TODO
break; | random_line_split |
globalize.culture.en-ZA.js | /*
* Globalize Culture en-ZA
*
* http://github.com/jquery/globalize
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* This file was generated by the Globalize Culture Generator
* Translation: bugs found in this file need t... |
Globalize.addCultureInfo( "en-ZA", "default", {
name: "en-ZA",
englishName: "English (South Africa)",
nativeName: "English (South Africa)",
numberFormat: {
",": " ",
percent: {
pattern: ["-n%","n%"],
",": " "
},
currency: {
pattern: ["$-n","$ n"],
",": " ",
".": ",",
symbol: "R"
}
},
... | {
// Global variable
Globalize = window.Globalize;
} | conditional_block |
globalize.culture.en-ZA.js | /*
* Globalize Culture en-ZA
*
* http://github.com/jquery/globalize
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* This file was generated by the Globalize Culture Generator
* Translation: bugs found in this file need t... | ",": " "
},
currency: {
pattern: ["$-n","$ n"],
",": " ",
".": ",",
symbol: "R"
}
},
calendars: {
standard: {
patterns: {
d: "yyyy/MM/dd",
D: "dd MMMM yyyy",
t: "hh:mm tt",
T: "hh:mm:ss tt",
f: "dd MMMM yyyy hh:mm tt",
F: "dd MMMM yyyy hh:mm:ss tt",
M: "dd MMMM",
... | percent: {
pattern: ["-n%","n%"], | random_line_split |
test_score.py | """
test pretrained models
"""
from __future__ import print_function
import mxnet as mx
from common import find_mxnet, modelzoo
from score import score
VAL_DATA='data/val-5k-256.rec'
def download_data():
return mx.test_utils.download(
'http://data.mxnet.io/data/val-5k-256.rec', VAL_DATA)
def test_imagenet... | def test_imagenet1k_inception_bn(**kwargs):
acc = mx.metric.create('acc')
m = 'imagenet1k-inception-bn'
g = 0.75
(speed,) = score(model=m,
data_val=VAL_DATA,
rgb_mean='123.68,116.779,103.939', metrics=acc, **kwargs)
r = acc.get()[1]
print('Tested %s acc ... | print('Tested %s, acc = %f, speed = %f img/sec' % (m, r, speed))
assert r > g and r < g + .1
| random_line_split |
test_score.py | """
test pretrained models
"""
from __future__ import print_function
import mxnet as mx
from common import find_mxnet, modelzoo
from score import score
VAL_DATA='data/val-5k-256.rec'
def download_data():
|
def test_imagenet1k_resnet(**kwargs):
models = ['imagenet1k-resnet-50', 'imagenet1k-resnet-152']
accs = [.77, .78]
for (m, g) in zip(models, accs):
acc = mx.metric.create('acc')
(speed,) = score(model=m, data_val=VAL_DATA,
rgb_mean='0,0,0', metrics=acc, **kwargs)
... | return mx.test_utils.download(
'http://data.mxnet.io/data/val-5k-256.rec', VAL_DATA) | identifier_body |
test_score.py | """
test pretrained models
"""
from __future__ import print_function
import mxnet as mx
from common import find_mxnet, modelzoo
from score import score
VAL_DATA='data/val-5k-256.rec'
def download_data():
return mx.test_utils.download(
'http://data.mxnet.io/data/val-5k-256.rec', VAL_DATA)
def test_imagenet... | gpus = mx.test_utils.list_gpus()
assert len(gpus) > 0
batch_size = 16 * len(gpus)
gpus = ','.join([str(i) for i in gpus])
kwargs = {'gpus':gpus, 'batch_size':batch_size, 'max_num_examples':500}
download_data()
test_imagenet1k_resnet(**kwargs)
test_imagenet1k_inception_bn(**kwargs) | conditional_block | |
test_score.py | """
test pretrained models
"""
from __future__ import print_function
import mxnet as mx
from common import find_mxnet, modelzoo
from score import score
VAL_DATA='data/val-5k-256.rec'
def download_data():
return mx.test_utils.download(
'http://data.mxnet.io/data/val-5k-256.rec', VAL_DATA)
def test_imagenet... | (**kwargs):
acc = mx.metric.create('acc')
m = 'imagenet1k-inception-bn'
g = 0.75
(speed,) = score(model=m,
data_val=VAL_DATA,
rgb_mean='123.68,116.779,103.939', metrics=acc, **kwargs)
r = acc.get()[1]
print('Tested %s acc = %f, speed = %f img/sec' % (m, ... | test_imagenet1k_inception_bn | identifier_name |
detector.py | from __future__ import print_function
import mxnet as mx
import numpy as np
from timeit import default_timer as timer
from dataset.testdb import TestDB
from dataset.iterator import DetIter
class Detector(object):
"""
SSD detector which hold a detection network and wraps detection API
Parameters:
-----... | is_train=False)
return self.detect(test_iter, show_timer)
def visualize_detection(self, img, dets, classes=[], thresh=0.6):
"""
visualize detections in one image
Parameters:
----------
img : numpy.array
image, in bgr format
... | """
wrapper for detecting multiple images
Parameters:
----------
im_list : list of str
image path or list of image paths
root_dir : str
directory of input images, optional if image path already
has full directory information
extension ... | identifier_body |
detector.py | from __future__ import print_function
import mxnet as mx
import numpy as np
from timeit import default_timer as timer
from dataset.testdb import TestDB
from dataset.iterator import DetIter
class Detector(object):
"""
SSD detector which hold a detection network and wraps detection API
Parameters:
-----... | (self, im_list, root_dir=None, extension=None,
classes=[], thresh=0.6, show_timer=False):
"""
wrapper for im_detect and visualize_detection
Parameters:
----------
im_list : list of str or str
image path or list of image paths
root... | detect_and_visualize | identifier_name |
detector.py | from __future__ import print_function
import mxnet as mx
import numpy as np
from timeit import default_timer as timer
from dataset.testdb import TestDB
from dataset.iterator import DetIter
class Detector(object):
"""
SSD detector which hold a detection network and wraps detection API
Parameters:
-----... | score threshold
"""
import matplotlib.pyplot as plt
import random
plt.imshow(img)
height = img.shape[0]
width = img.shape[1]
colors = dict()
for i in range(dets.shape[0]):
cls_id = int(dets[i, 0])
if cls_id >= 0:
... | thresh : float | random_line_split |
detector.py | from __future__ import print_function
import mxnet as mx
import numpy as np
from timeit import default_timer as timer
from dataset.testdb import TestDB
from dataset.iterator import DetIter
class Detector(object):
"""
SSD detector which hold a detection network and wraps detection API
Parameters:
-----... |
start = timer()
detections = self.mod.predict(det_iter).asnumpy()
time_elapsed = timer() - start
if show_timer:
print("Detection time for {} images: {:.4f} sec".format(
num_images, time_elapsed))
result = []
for i in range(detections.shape[0])... | det_iter = mx.io.PrefetchingIter(det_iter) | conditional_block |
ISearchTvResult.ts | import { BaseRequestOptions, INewSeasonRequests } from "./IRequestModel";
export interface ISearchTvResult {
id: number;
title: string; // used in the request
aliases: string[];
banner: string;
seriesId: number;
status: string;
firstAired: string;
network: string;
networkId: string... | firstSeason: boolean;
latestSeason: boolean;
languageProfile: number | undefined;
seasons: ISeasonsViewModel[];
}
export interface ISeasonsViewModel {
seasonNumber: number;
episodes: IEpisodesViewModel[];
}
export interface IEpisodesViewModel {
episodeNumber: number;
} |
export interface ITvRequestViewModelBase extends BaseRequestOptions {
requestAll: boolean; | random_line_split |
Iterable.js | i)) return this.items[i];
}
return undefined;
};
/*
* Finds the first item of this collection of objects that owns a property set to a given value.
* This is a special case of find(). The property can be arbitrarily nested.
*/
Iterable.prototype.findBy = function(property, value) {
var doPluck = getPluckFunc... | {
if (currentContext == null && i != length) return undefined;
currentContext = currentContext[propertyChain[i]];
i++;
} | conditional_block | |
Iterable.js | * The current Array representation of the collection.
* It should be considered read-only and never modified directly.
*/
Iterable.prototype.items = null;
/*
* Returns the number of items in this collection.
*/
Iterable.prototype.size = function() {
return this.items.length;
};
/*
* Indicates whether this collect... | random_line_split | ||
calibrator.py | import todsynth
import os
import numpy
import json
import pandas
class | ( object ):
'''
A todsynth.calibrator object is a container that stores coefficients
that transform RAW dac units to physical units for a given TOD.
'''
# Calibrator description.
#000000000000000000000000000000000000000000000000000000000000000000000000
name = ""
description ... | Calibrator | identifier_name |
calibrator.py | import todsynth
import os
import numpy
import json
import pandas
class Calibrator( object ):
|
def __init__( self ):
'''
self.name = name
self.description = descrp
self.calType = calType
'''
def setCoeffs( self, c , uid=None ):
'''
Set calibrator coefficients to c.
'''
# Perform numpy.copy() to avoid cross referencing stuff
... | '''
A todsynth.calibrator object is a container that stores coefficients
that transform RAW dac units to physical units for a given TOD.
'''
# Calibrator description.
#000000000000000000000000000000000000000000000000000000000000000000000000
name = ""
description = ""
calType... | identifier_body |
calibrator.py | import todsynth
import os
import numpy
import json
import pandas
class Calibrator( object ):
'''
A todsynth.calibrator object is a container that stores coefficients
that transform RAW dac units to physical units for a given TOD.
'''
# Calibrator description.
#00000000000000000000000000... |
def getCoeffs( self ):
'''
Get a *copy* of the coefficients array.
'''
return numpy.copy( self.coeffs )
def updateInfo( self, prop, value ):
'''
Update calibrator info with a pair of prop : value
'''
self.info.update( { 'prop' : value } )
... | self.__uid = numpy.arange( len( self.coeffs ) ) | conditional_block |
calibrator.py | import todsynth
import os
import numpy
import json
import pandas
class Calibrator( object ):
'''
A todsynth.calibrator object is a container that stores coefficients
that transform RAW dac units to physical units for a given TOD.
'''
# Calibrator description.
#00000000000000000000000000... | @classmethod
def readFromPath( cls, systemPath ):
'''
'''
self = cls()
name,caltype,_ = os.path.basename( systemPath ).split('.')
self.name = name
self.calType = caltype
self.description = ''
# Load file
calDF = pandas.read_csv(... | sep=' ',
header=True )
| random_line_split |
issue_tracker_service.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provides a layer of abstraction for the issue tracker API."""
import logging
from apiclient import discovery
from apiclient import errors
import httplib... |
response = self._MakeGetCommentsRequest(bug_id)
if response and all(v in response.keys()
for v in ['totalResults', 'items']):
bug_comments = response.get('items')[response.get('totalResults') - 1]
if bug_comments.get('content') and bug_comments.get('published'):
retu... | return None | conditional_block |
issue_tracker_service.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provides a layer of abstraction for the issue tracker API."""
import logging
from apiclient import discovery
from apiclient import errors
import httplib... | (self, request):
"""Make a request to the issue tracker.
Args:
request: The request object, which has a execute method.
Returns:
The response if there was one, or else None.
"""
try:
response = request.execute(http=self._http)
return response
except errors.HttpError as ... | _ExecuteRequest | identifier_name |
issue_tracker_service.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provides a layer of abstraction for the issue tracker API."""
import logging
from apiclient import discovery
from apiclient import errors
import httplib... | return {
'comment': bug_comments.get('content'),
'timestamp': bug_comments.get('published')
}
return None
def _MakeGetCommentsRequest(self, bug_id):
"""Make a request to the issue tracker to get comments in the bug."""
# TODO (prasadv): By default the max number of... | if bug_comments.get('content') and bug_comments.get('published'): | random_line_split |
issue_tracker_service.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provides a layer of abstraction for the issue tracker API."""
import logging
from apiclient import discovery
from apiclient import errors
import httplib... | """Make a request to the issue tracker.
Args:
request: The request object, which has a execute method.
Returns:
The response if there was one, or else None.
"""
try:
response = request.execute(http=self._http)
return response
except errors.HttpError as e:
logging.erro... | identifier_body | |
views.py | from __future__ import unicode_literals
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from blog.forms import Post... | # -*- coding: utf-8 -*- | random_line_split | |
views.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
fro... |
@login_required
def comment_remove(request,pk):
comment = get_object_or_404(Comment,pk=pk)
post_pk = comment.post.pk
comment.delete()
return redirect('post_detail',pk=post_pk) | comment = get_object_or_404(Comment,pk=pk)
comment.approve()
return redirect('post_detail',pk=comment.post.pk) | identifier_body |
views.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
fro... | (self, form):
form.instance.author = self.request.user
form.instance.title = form.instance.title.title()
form.save()
return super(CreatePostView, self).form_valid(form)
class PostUpdateView(LoginRequiredMixin,UpdateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostF... | form_valid | identifier_name |
views.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
fro... |
else:
form = CommentForm()
return render(request,'blog/comment_form.html',{'form':form})
@login_required
def comment_approve(request,pk):
comment = get_object_or_404(Comment,pk=pk)
comment.approve()
return redirect('post_detail',pk=comment.post.pk)
@login_required
def comment_remove(request,pk):
comment = ge... | comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('post_detail',pk=post.pk) | conditional_block |
builder.rs | {
#[inline(always)]
fn default() -> Self {
SelectorBuilder {
simple_selectors: SmallVec::new(),
combinators: SmallVec::new(),
current_len: 0,
}
}
}
impl<Impl: SelectorImpl> Push<Component<Impl>> for SelectorBuilder<Impl> {
fn push(&mut self, value: C... | unreachable!(
"Found combinator {:?} in simple selectors vector? {:?}", | random_line_split | |
builder.rs | push_combinator() methods to append selector data as it is encountered
/// (from left to right). Once the process is complete, callers should invoke
/// build(), which transforms the contents of the SelectorBuilder into a heap-
/// allocated Selector and leaves the builder in a drained state.
#[derive(Debug)]
pub stru... | self) -> usize {
self.current_simple_selectors.len() + self.rest_of_simple_selectors.len() +
self.combinators.len()
}
}
impl<'a, Impl: SelectorImpl> Iterator for SelectorBuilderIter<'a, Impl> {
type Item = Component<Impl>;
#[inline(always)]
fn next(&mut self) -> Option<Self::Item> {... | n(& | identifier_name |
builder.rs | push_combinator() methods to append selector data as it is encountered
/// (from left to right). Once the process is complete, callers should invoke
/// build(), which transforms the contents of the SelectorBuilder into a heap-
/// allocated Selector and leaves the builder in a drained state.
#[derive(Debug)]
pub stru... |
self.build_with_specificity_and_flags(spec)
}
/// Builds with an explicit SpecificityAndFlags. This is separated from build() so
/// that unit tests can pass an explicit specificity.
#[inline(always)]
pub fn build_with_specificity_and_flags(
&mut self,
spec: SpecificityAnd... | {
spec.0 |= HAS_SLOTTED_BIT;
} | conditional_block |
builder.rs | push_combinator() methods to append selector data as it is encountered
/// (from left to right). Once the process is complete, callers should invoke
/// build(), which transforms the contents of the SelectorBuilder into a heap-
/// allocated Selector and leaves the builder in a drained state.
#[derive(Debug)]
pub stru... | #[inline]
pub fn is_slotted(&self) -> bool {
(self.0 & HAS_SLOTTED_BIT) != 0
}
}
const MAX_10BIT: u32 = (1u32 << 10) - 1;
#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
struct Specificity {
id_selectors: u32,
class_like_selectors: u32,
element_selectors: u32,
}
impl AddAssign for... | (self.0 & HAS_PSEUDO_BIT) != 0
}
| identifier_body |
test-pcopy.py | #!/usr/bin/python
import libploop
import shutil
import io
import os
import socket
import time
import subprocess as sp
import unittest
import hashlib
sleep_sec = 3
def hashfile(afile, hasher, blocksize=65536):
buf = afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
print (... | (unittest.TestCase):
def setUp(self):
if not os.path.exists('/dev/ploop0'):
sp.call(['mknod', '/dev/ploop0', 'b', '182', '0'])
if os.path.exists(get_ddxml()):
ploop_umount(get_ddxml())
shutil.rmtree(get_storage())
if not os.path.exists(get_storage()):
os.mkdir(get_storage())
if not os.path.exist... | testPcopy | identifier_name |
test-pcopy.py | #!/usr/bin/python
import libploop
import shutil
import io
import os
import socket
import time
import subprocess as sp
import unittest
import hashlib
sleep_sec = 3
def hashfile(afile, hasher, blocksize=65536):
buf = afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
print (... |
def tearDown(self):
print "tearDown"
if os.path.exists(get_ddxml()):
ploop_umount(get_ddxml())
shutil.rmtree(get_storage())
def test_aremote(self):
print "Start remote"
parent, child = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
self.rcv_thr = start_pcopy_receiver(self.out, child.fileno... | if not os.path.exists('/dev/ploop0'):
sp.call(['mknod', '/dev/ploop0', 'b', '182', '0'])
if os.path.exists(get_ddxml()):
ploop_umount(get_ddxml())
shutil.rmtree(get_storage())
if not os.path.exists(get_storage()):
os.mkdir(get_storage())
if not os.path.exists(get_mnt_dir()):
os.mkdir(get_mnt_dir... | identifier_body |
test-pcopy.py | #!/usr/bin/python
import libploop
import shutil
import io
import os
import socket
import time
import subprocess as sp
import unittest
import hashlib
sleep_sec = 3
def hashfile(afile, hasher, blocksize=65536):
buf = afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
print (... |
print "Wait filler %d" % pid
os.kill(pid, 15)
os.waitpid(pid, 0)
print "Stop sopy"
pc.copy_stop()
ploop_umount(ddxml)
class testPcopy(unittest.TestCase):
def setUp(self):
if not os.path.exists('/dev/ploop0'):
sp.call(['mknod', '/dev/ploop0', 'b', '182', '0'])
if os.path.exists(get_ddxml()):
ploop_... | print "transferred:", transferred
time.sleep(sleep_sec) | random_line_split |
test-pcopy.py | #!/usr/bin/python
import libploop
import shutil
import io
import os
import socket
import time
import subprocess as sp
import unittest
import hashlib
sleep_sec = 3
def hashfile(afile, hasher, blocksize=65536):
buf = afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
print (... |
if not os.path.exists(get_storage()):
os.mkdir(get_storage())
if not os.path.exists(get_mnt_dir()):
os.mkdir(get_mnt_dir())
ploop_create(get_image())
self.out = os.path.join(get_storage(), "out.hds")
self.ddxml = get_ddxml()
def tearDown(self):
print "tearDown"
if os.path.exists(get_ddxml()):
... | ploop_umount(get_ddxml())
shutil.rmtree(get_storage()) | conditional_block |
nytimes-scrape.py | model_search = "http://api.nytimes.com/svc/search/v2/" + \
"articlesearch.response-format?" + \
"[q=search term&" + \
"fq=filter-field:(filter-term)&additional-params=values]" + \
"&api-key=9key"
"""http://api.nytimes.com/svc/search/v2/articlesearch.json?q=terrorism+OR+t... |
#print(frames)
result = pd.concat(frames)
result
| df = pd.DataFrame.from_dict(x)
frames.append(df) | conditional_block |
nytimes-scrape.py | model_search = "http://api.nytimes.com/svc/search/v2/" + \
"articlesearch.response-format?" + \
"[q=search term&" + \
"fq=filter-field:(filter-term)&additional-params=values]" + \
"&api-key=9key"
"""http://api.nytimes.com/svc/search/v2/articlesearch.json?q=terrorism+OR+t... | json_files = []
print(months_list)
for x in months_list:
month_s = x
month_e = x
for y in days_list:
day_s = y
day_e = str(int(y)+1).zfill(2)
year_s = "1990"
year_e = "1990"
start = year_s + month_s + day_s
end = year_e + month_e + day_e
dates = "&begi... | aggressive for looping in order to overcome the ten article limit. instead search each key word PER JOUR, and then concat the jsons into a nice pandas dataframe, and then eventually a csv.
"""
months_list = ["%.2d" % i for i in range(1,2)]
days_list = ["%.2d" % i for i in range(1,32)] | random_line_split |
run-sequence.d.ts | // Compiled using typings@0.6.8
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/40c60850ad6c8175a62d5ab48c4e016ea5b3dffe/run-sequence/run-sequence.d.ts
// Type definitions for run-sequence
// Project: https://github.com/OverZealous/run-sequence
// Definitions by: Keita Kagurazaka <https://g... | (...streams: (string | string[] | gulp.TaskCallback)[]): NodeJS.ReadWriteStream;
use(gulp: gulp.Gulp): IRunSequence;
}
var _tmp: IRunSequence;
export = _tmp;
} | import gulp = require('gulp');
interface IRunSequence { | random_line_split |
zones.py | #!/usr/bin/env python
import sys, os, re, tarfile, json
FILES = {
'africa', 'antarctica', 'asia', 'australasia',
'europe', 'northamerica', 'southamerica',
}
WS_SPLIT = re.compile("[ \t]+")
def lines(fn):
with tarfile.open(fn, 'r:*') as tar:
for info in tar:
if not info.isfile() or info.name not in FILE... |
path = sys.argv[1]
version = re.match('tzdata(.*)\.tar\.gz$', os.path.basename(path))
if version is None:
raise StandardError('argument must be tzdata archive')
print(json.dumps(parse(path))) | random_line_split | |
zones.py | #!/usr/bin/env python
import sys, os, re, tarfile, json
FILES = {
'africa', 'antarctica', 'asia', 'australasia',
'europe', 'northamerica', 'southamerica',
}
WS_SPLIT = re.compile("[ \t]+")
def lines(fn):
with tarfile.open(fn, 'r:*') as tar:
for info in tar:
if not info.isfile() or info.name not in FILE... | else:
assert False, ln
return {'zones': zones, 'rules': rules}
if __name__ == '__main__':
path = sys.argv[1]
version = re.match('tzdata(.*)\.tar\.gz$', os.path.basename(path))
if version is None:
raise StandardError('argument must be tzdata archive')
print(json.dumps(parse(path)))
| words = WS_SPLIT.split(ln)
if words[0] == 'Zone':
assert words[1] not in zones, words[1]
zone = []
zone.append(zoneline(words[2:]))
if '/' in words[1]:
zones[words[1]] = zone
elif words[0] == '':
assert zone is not None
zone.append(zoneline(words[1:]))
elif words[0] == 'Rule':
zone... | conditional_block |
zones.py | #!/usr/bin/env python
import sys, os, re, tarfile, json
FILES = {
'africa', 'antarctica', 'asia', 'australasia',
'europe', 'northamerica', 'southamerica',
}
WS_SPLIT = re.compile("[ \t]+")
def lines(fn):
with tarfile.open(fn, 'r:*') as tar:
for info in tar:
if not info.isfile() or info.name not in FILE... |
def parse(fn):
zones, rules, zone = {}, {}, None
for ln in lines(fn):
# see zic(8) for documentation
words = WS_SPLIT.split(ln)
if words[0] == 'Zone':
assert words[1] not in zones, words[1]
zone = []
zone.append(zoneline(words[2:]))
if '/' in words[1]:
zones[words[1]] = zone
elif wor... | ls[1] = None if ls[1] == '-' else ls[1]
tmp = offset(ls[0]), ls[1], ls[2], ls[3:]
return {k: v for (k, v) in zip('orfu', tmp)} | identifier_body |
zones.py | #!/usr/bin/env python
import sys, os, re, tarfile, json
FILES = {
'africa', 'antarctica', 'asia', 'australasia',
'europe', 'northamerica', 'southamerica',
}
WS_SPLIT = re.compile("[ \t]+")
def lines(fn):
with tarfile.open(fn, 'r:*') as tar:
for info in tar:
if not info.isfile() or info.name not in FILE... | (s):
if s in {'-', '0'}:
return 0
dir, s = (-1, s[1:]) if s[0] == '-' else (1, s)
words = [int(n) for n in s.split(':')]
assert 1 <= len(words) < 4, words
words = words + [0] * (3 - len(words))
assert 0 <= words[0] < 24, words
assert 0 <= words[1] < 60, words
assert 0 <= words[2] < 60, words
return ... | offset | identifier_name |
S15.3.5.3_A2_T2.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.3.5.3_A2_T2;
* @section: 15.3.5.3, 11.8.6; | * ii) Let O be Result(i).
* iii) O is not an object, throw a TypeError exception;
* @description: F.prototype is undefined, and V is empty object;
*/
FACTORY = new Function;
FACTORY.prototype = undefined;
obj={};
//CHECK#1
try {
obj instanceof FACTORY;
$FAIL('#1: O is not an object, throw a TypeError exception... | * @assertion: Assume F is a Function object. When the [[HasInstance]] method of F is called with value V and V is an object, the following steps are taken:
* i) Call the [[Get]] method of F with property name "prototype". | random_line_split |
S15.3.5.3_A2_T2.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.3.5.3_A2_T2;
* @section: 15.3.5.3, 11.8.6;
* @assertion: Assume F is a Function object. When the [[HasInstance]] method of F is called with value V and V is an object, th... |
}
| {
$ERROR('#1.1: O is not an object, throw a TypeError exception');
} | conditional_block |
vec-dst.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
sub_expr();
index();
}
| main | identifier_name |
vec-dst.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | assert!(x[2] == 3);
}
pub fn main() {
sub_expr();
index();
}
| {
// Tests for indexing into box/& [T, ..n]
let x: [int, ..3] = [1, 2, 3];
let mut x: Box<[int, ..3]> = box x;
assert!(x[0] == 1);
assert!(x[1] == 2);
assert!(x[2] == 3);
x[1] = 45;
assert!(x[0] == 1);
assert!(x[1] == 45);
assert!(x[2] == 3);
let mut x: [int, ..3] = [1, 2, 3... | identifier_body |
vec-dst.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | fn sub_expr() {
// Test for a &[T] => &&[T] coercion in sub-expression position
// (surpisingly, this can cause errors which are not caused by either of:
// `let x = vec.slice_mut(0, 2);`
// `foo(vec.slice_mut(0, 2));` ).
let mut vec: Vec<int> = vec!(1, 2, 3, 4);
let b: &mut [int] = [1, 2]... | // <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.
| random_line_split |
job.py | RCODE_FAIL.format(e, self.retry_time)).flush()
self.retry_count = self.retry_count + 1
if self.retry_count == 20:
self.retry_count = 0
try:
os.remove(self.get_cookie_path())
except:
pass
time.slee... | e:
passenger = array_dict_find_by_key_value(self.passengers, 'passenger_name', member)
if audlt:
passenger['passenger_type'] = UserType.ADULT
if n | conditional_block | |
job.py | (self.get_name(), Config().USER_HEARTBEAT_INTERVAL) | return int(self.cluster.session.get(Cluster.KEY_USER_LAST_HEARTBEAT, 0))
return self.last_heartbeat
def set_last_heartbeat(self, time=None):
time = time if time != None else time_int()
if Config().is_cluster_enabled():
self.cluster.session.set(Cluster.KEY_USER_LAST_... | UserLog.add_quick_log(message).flush()
def get_last_heartbeat(self):
if Config().is_cluster_enabled(): | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.