file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
test_guest_vlan_range.py | """ P1 tests for Dedicating Guest Vlan Ranges
"""
# Import Local Modules
from marvin.cloudstackAPI import *
from marvin.cloudstackTestCase import *
from marvin.lib.base import *
from marvin.lib.common import *
from marvin.lib.utils import *
from nose.plugins.attrib import attr
class TestDedicateGuestVlanRange(cloudst... | (self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
return
def tearDown(self):
try:
# Clean up
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
... | setUp | identifier_name |
test_guest_vlan_range.py | """ P1 tests for Dedicating Guest Vlan Ranges
"""
# Import Local Modules
from marvin.cloudstackAPI import *
from marvin.cloudstackTestCase import *
from marvin.lib.base import *
from marvin.lib.common import *
from marvin.lib.utils import *
from nose.plugins.attrib import attr
class TestDedicateGuestVlanRange(cloudst... | list_dedicated_guest_vlan_range_response = PhysicalNetwork.listDedicated(self.apiclient)
self.assertEqual(
list_dedicated_guest_vlan_range_response,
None,
"Check vlan range is not available in listDedicatedGuestVlanRanges"
) | self.debug("Releasing guest vlan range");
dedicate_guest_vlan_range_response.release(self.apiclient) | random_line_split |
ParameterType.py | """
Created on Feb 15, 2014
@author: alex
"""
from sqlalchemy import Column
from sqlalchemy.types import SmallInteger
from sqlalchemy.types import Unicode
from .meta import Base
class | (Base):
"""
classdocs
"""
__tablename__ = 'ParameterTypes'
_id = Column(SmallInteger, primary_key=True, autoincrement=True, nullable=False, unique=True)
name = Column(Unicode(250), nullable=False, unique=True)
unit = Column(Unicode(250), nullable=False)
def __init__(self, name, unit):
... | ParameterType | identifier_name |
ParameterType.py | """
Created on Feb 15, 2014
@author: alex
"""
from sqlalchemy import Column
from sqlalchemy.types import SmallInteger
from sqlalchemy.types import Unicode
from .meta import Base
class ParameterType(Base):
"""
classdocs
"""
__tablename__ = 'ParameterTypes'
_id = Column(SmallInteger, primary_key... | def serialize(self):
"""Return data in serializeable (dictionary) format"""
ret_dict = {
'id': self.id,
'name': self.name,
'unit': self.unit
}
return ret_dict
def __repr__(self):
return str(self.serialize)
def init_parameter_types(db... | @property | random_line_split |
ParameterType.py | """
Created on Feb 15, 2014
@author: alex
"""
from sqlalchemy import Column
from sqlalchemy.types import SmallInteger
from sqlalchemy.types import Unicode
from .meta import Base
class ParameterType(Base):
|
def init_parameter_types(db_session):
db_session.add(ParameterType('Temperature', '°C'))
db_session.add(ParameterType('Humidity', '%'))
db_session.add(ParameterType('Volume', 'Liter'))
db_session.add(ParameterType('pH', 'pH'))
db_session.add(ParameterType('Conductivity', 'mS'))
| """
classdocs
"""
__tablename__ = 'ParameterTypes'
_id = Column(SmallInteger, primary_key=True, autoincrement=True, nullable=False, unique=True)
name = Column(Unicode(250), nullable=False, unique=True)
unit = Column(Unicode(250), nullable=False)
def __init__(self, name, unit):
self... | identifier_body |
kendo.culture.kk-KZ.js | /*
* Kendo UI v2014.2.716 (http://www.telerik.com/kendo-ui)
* Copyright 2014 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial licen... | decimals: 2,
",": " ",
".": "-",
groupSize: [3],
symbol: "Т"
}
},
calendars: {
standard: {
days: {
names: ["Жексенбі","Дүйсенбі","Сейсенбі","Сәрсенбі","Бейсенбі","Ж... | symbol: "%"
},
currency: {
pattern: ["-$n","$n"], | random_line_split |
common.ts | /** | * @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export {Injector, OpaqueToken, ReflectiveInjector, bind, provide} from '@angular/core/src/di';
export {Options} from './... | random_line_split | |
Pagination.tsx | import Link from "next/link";
import { FunctionComponent } from "react";
import { PagedCollection } from "types/Collection";
interface Props {
collection: PagedCollection<any>;
}
const Pagination: FunctionComponent<Props> = ({ collection }) => {
const view = collection && collection['hydra:view'];
if (!view) re... | <Link href={next ? next : '#'}>
<a className={`btn btn-primary${next ? '' : ' disabled'}`}>
Next <span aria-hidden="true">→</span>
</a>
</Link>
<Link href={last ? last : '#'}>
<a className={`btn btn-primary${next ? '' : ' disabled'}`}>
Last <span aria-h... | <span aria-hidden="true">←</span> Previous
</a>
</Link> | random_line_split |
home.component.ts | import { TextSplitPipe } from '../shared/pipes/text-split.pipe';
import { Greeting } from './home.model';
import { Response } from '@angular/http';
import {
Component,
OnInit
} from '@angular/core';
import { HomeService } from './home.Service';
@Component({
selector: 'home',
styleUrls: ['./home.component.css'... | console.log(item);
}
deleteItem(item){
let index = this.values.indexOf(item);
this.values.splice(index,1);
}
} | return true;
}
printItem(item){ | random_line_split |
home.component.ts | import { TextSplitPipe } from '../shared/pipes/text-split.pipe';
import { Greeting } from './home.model';
import { Response } from '@angular/http';
import {
Component,
OnInit
} from '@angular/core';
import { HomeService } from './home.Service';
@Component({
selector: 'home',
styleUrls: ['./home.component.css'... | implements OnInit {
aboutName: string = "home";
testName: string = "";
greeting: Greeting = <Greeting>{};
values: [{ name: string; age: number; }];
valueString: string = "Hello Georgia";
valueDate: Date = new Date();
valueLongText: string = "Hello Bank of Georgia";
value3: string = new TextSplitPi... | HomeComponent | identifier_name |
home.component.ts | import { TextSplitPipe } from '../shared/pipes/text-split.pipe';
import { Greeting } from './home.model';
import { Response } from '@angular/http';
import {
Component,
OnInit
} from '@angular/core';
import { HomeService } from './home.Service';
@Component({
selector: 'home',
styleUrls: ['./home.component.css'... |
deleteItem(item){
let index = this.values.indexOf(item);
this.values.splice(index,1);
}
}
| {
console.log(item);
} | identifier_body |
app.js | var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
var dbConfig = require('./db.js');
v... | });
module.exports = app; | random_line_split | |
app.js | var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
var dbConfig = require('./db.js');
v... |
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
| {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
} | conditional_block |
CircularAudioBuffer.d.ts | /**
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
| *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the... | * You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
| random_line_split |
CircularAudioBuffer.d.ts | /**
* Copyright 2017 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or ag... | {
buffer: Float32Array;
currentIndex: number;
constructor(maxLength: number);
/**
* Add a new buffer of data. Called when we get new audio input samples.
*/
addBuffer(newBuffer: Float32Array): void;
/**
* How many samples are stored currently?
*/
getLength(): ... | CircularAudioBuffer | identifier_name |
xyz-source.js | import { createTileUrlFunctionFromTemplates } from 'ol-tilecache'
import { XYZ as XYZSource } from 'ol/source'
import { createXYZ } from 'ol/tilegrid'
import { EPSG_3857, extentFromProjection } from '../ol-ext'
import { and, coalesce, isArray, isFunction, isNumber, noop, or } from '../utils'
import source from './sourc... | mixins: [
tileImageSource,
],
props: {
/* eslint-disable vue/require-prop-types */
// ol/source/Source
projection: {
...source.props.projection,
default: EPSG_3857,
},
/* eslint-enable vue/require-prop-types */
// ol/source/XYZ
maxZoom: {
type: Number,
defau... | const validateTileSize = /*#__PURE__*/or(isNumber, and(isArray, value => value.length === 2 && value.every(isNumber)))
/**
* Base XYZ source mixin.
*/
export default { | random_line_split |
xyz-source.js | import { createTileUrlFunctionFromTemplates } from 'ol-tilecache'
import { XYZ as XYZSource } from 'ol/source'
import { createXYZ } from 'ol/tilegrid'
import { EPSG_3857, extentFromProjection } from '../ol-ext'
import { and, coalesce, isArray, isFunction, isNumber, noop, or } from '../utils'
import source from './sourc... | () {
const urlFunc = coalesce(this.tileUrlFunction, this.tileUrlFunc)
if (isFunction(urlFunc)) return urlFunc
if (this.currentUrls.length === 0) return
return createTileUrlFunctionFromTemplates(this.currentUrls, this.tileGrid)
},
},
methods: {
/**
* @return {module:ol/source/X... | inputTileUrlFunction | identifier_name |
xyz-source.js | import { createTileUrlFunctionFromTemplates } from 'ol-tilecache'
import { XYZ as XYZSource } from 'ol/source'
import { createXYZ } from 'ol/tilegrid'
import { EPSG_3857, extentFromProjection } from '../ol-ext'
import { and, coalesce, isArray, isFunction, isNumber, noop, or } from '../utils'
import source from './sourc... | ,
},
methods: {
/**
* @return {module:ol/source/XYZ~XYZSource}
* @protected
*/
createSource () {
return new XYZSource({
// ol/source/Source
attributions: this.currentAttributions,
attributionsCollapsible: this.attributionsCollapsible,
projection: this.res... | {
const urlFunc = coalesce(this.tileUrlFunction, this.tileUrlFunc)
if (isFunction(urlFunc)) return urlFunc
if (this.currentUrls.length === 0) return
return createTileUrlFunctionFromTemplates(this.currentUrls, this.tileGrid)
} | identifier_body |
authentication.js | // @flow
import {
AUTH_ASAP,
AUTH_BASIC,
AUTH_BEARER,
AUTH_HAWK,
AUTH_OAUTH_1,
AUTH_OAUTH_2
} from '../common/constants';
import getOAuth2Token from './o-auth-2/get-token';
import getOAuth1Token from './o-auth-1/get-token';
import * as Hawk from 'hawk';
import jwtAuthentication from 'jwt-authentication';
im... |
if (authentication.type === AUTH_BASIC) {
const { username, password } = authentication;
return getBasicAuthHeader(username, password);
}
if (authentication.type === AUTH_BEARER) {
const { token, prefix } = authentication;
return getBearerAuthHeader(token, prefix);
}
if (authentication.typ... | {
return null;
} | identifier_body |
authentication.js | // @flow
import {
AUTH_ASAP,
AUTH_BASIC,
AUTH_BEARER,
AUTH_HAWK,
AUTH_OAUTH_1,
AUTH_OAUTH_2
} from '../common/constants';
import getOAuth2Token from './o-auth-2/get-token';
import getOAuth1Token from './o-auth-1/get-token';
import * as Hawk from 'hawk';
import jwtAuthentication from 'jwt-authentication';
im... | (authentication.type === AUTH_BEARER) {
const { token, prefix } = authentication;
return getBearerAuthHeader(token, prefix);
}
if (authentication.type === AUTH_OAUTH_2) {
// HACK: GraphQL requests use a child request to fetch the schema with an
// ID of "{{request_id}}.graphql". Here we are removi... | if | identifier_name |
authentication.js | // @flow
import {
AUTH_ASAP,
AUTH_BASIC,
AUTH_BEARER,
AUTH_HAWK,
AUTH_OAUTH_1,
AUTH_OAUTH_2
} from '../common/constants';
import getOAuth2Token from './o-auth-2/get-token';
import getOAuth1Token from './o-auth-1/get-token';
import * as Hawk from 'hawk';
import jwtAuthentication from 'jwt-authentication';
im... | if (typeof parsedAdditionalClaims !== 'object') {
throw new Error(
`additional-claims must be an object received: '${typeof parsedAdditionalClaims}' instead`
);
}
claims = Object.assign(parsedAdditionalClaims, claims);
}
const options = {
privateKey,
kid... |
if (parsedAdditionalClaims) { | random_line_split |
authentication.js | // @flow
import {
AUTH_ASAP,
AUTH_BASIC,
AUTH_BEARER,
AUTH_HAWK,
AUTH_OAUTH_1,
AUTH_OAUTH_2
} from '../common/constants';
import getOAuth2Token from './o-auth-2/get-token';
import getOAuth1Token from './o-auth-1/get-token';
import * as Hawk from 'hawk';
import jwtAuthentication from 'jwt-authentication';
im... |
});
});
}
return null;
}
function _buildBearerHeader(accessToken, prefix) {
if (!accessToken) {
return null;
}
const name = 'Authorization';
const value = `${prefix || 'Bearer'} ${accessToken}`;
return { name, value };
}
| {
resolve({
name: 'Authorization',
value: headerValue
});
} | conditional_block |
main.js | // For an introduction to the Page Control template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232511
(function () {
"use strict";
var app = WinJS.Application;
var nav = WinJS.Navigation;
var sched = WinJS.Utilities.Scheduler;
var ui = WinJS.UI;
WinJS.UI.Pages... | },
toggleNavBarVisibility: function (ev) {
document.getElementById('createNavBar').winControl.show();
},
launchtileInvoked: function (ev) {
var tile = ev.currentTarget;
var location = "pages/" + tile.dataset.page + "/" + tile.dataset.page + ".html";
... | var launchtile = launchtiles[n];
launchtile.addEventListener('click', this.launchtileInvoked.bind(this));
}
| conditional_block |
main.js | // For an introduction to the Page Control template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232511
(function () {
"use strict";
var app = WinJS.Application;
var nav = WinJS.Navigation;
var sched = WinJS.Utilities.Scheduler;
var ui = WinJS.UI;
WinJS.UI.Pages... | },
updateLayout: function (element) {
/// <param name="element" domElement="true" />
// TODO: Respond to changes in layout.
}
});
})(); | // TODO: Respond to navigations away from this page. | random_line_split |
index.js | 'use strict';
var Grid = require('nd-grid');
var datetime = require('nd-datetime');
var RbacRoleModel = require('../../../mod/model/rbac/role');
module.exports = function(util) {
if (!util.auth.hasAuth('=8')) {
return util.redirect('error/403');
}
var instance = new Grid({
parentNode: '#main',
pro... | start: require('./add/start')
}
},
editItem: {
disabled: false,
listeners: {
start: require('./edit/start')
}
},
delItem: {
disabled: false
},
search: {
disabled: util.RBAC_ENABLED,
listeners: {
sta... | listeners: { | random_line_split |
shared.ts | import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
import {isBlank, isPresent, looseIdentical, hasConstructor} from 'angular2/src/facade/lang';
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
import {ControlContainer} from './control_container';
import {NgCont... | (control: ControlGroup, dir: NgControlGroup) {
if (isBlank(control)) _throwError(dir, "Cannot find control");
control.validator = Validators.compose([control.validator, dir.validator]);
control.asyncValidator = Validators.composeAsync([control.asyncValidator, dir.asyncValidator]);
}
function _throwError(dir: Abs... | setUpControlGroup | identifier_name |
shared.ts | import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
import {isBlank, isPresent, looseIdentical, hasConstructor} from 'angular2/src/facade/lang';
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
import {ControlContainer} from './control_container';
import {NgCont... |
export function composeAsyncValidators(
validators: /* Array<Validator|Function> */ any[]): AsyncValidatorFn {
return isPresent(validators) ? Validators.composeAsync(validators.map(normalizeAsyncValidator)) :
null;
}
export function isPropertyUpdated(changes: {[key: string]: an... | {
return isPresent(validators) ? Validators.compose(validators.map(normalizeValidator)) : null;
} | identifier_body |
shared.ts | import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
import {isBlank, isPresent, looseIdentical, hasConstructor} from 'angular2/src/facade/lang';
import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';
import {ControlContainer} from './control_container';
import {NgCont... | }
// TODO: vsavkin remove it once https://github.com/angular/angular/issues/3011 is implemented
export function selectValueAccessor(dir: NgControl,
valueAccessors: ControlValueAccessor[]): ControlValueAccessor {
if (isBlank(valueAccessors)) return null;
var defaultAccessor: Con... | var change = changes["model"];
if (change.isFirstChange()) return true;
return !looseIdentical(viewModel, change.currentValue); | random_line_split |
preparse_postformat.js | var moment = require('../../moment'),
symbolMap = { | '3': '#',
'4': '$',
'5': '%',
'6': '^',
'7': '&',
'8': '*',
'9': '(',
'0': ')'
},
numberMap = {
'!': '1',
'@': '2',
'#': '3',
'$': '4',
'%': '5',
'^': '6',
'&': '7',
'*': '8',
... | '1': '!',
'2': '@', | random_line_split |
locale_nl.js | if (window.midgardCreate === undefined) {
window.midgardCreate = {};
}
if (window.midgardCreate.locale === undefined) |
window.midgardCreate.locale.nl = {
// Session-state buttons for the main toolbar
'Save': 'Opslaan',
'Saving': 'Bezig met opslaan',
'Cancel': 'Annuleren',
'Edit': 'Bewerken',
// Storage status messages
'localModification': 'Items "<%= label %>" op de pagina heeft lokale wijzigingen',
'localModification... | {
window.midgardCreate.locale = {};
} | conditional_block |
locale_nl.js | if (window.midgardCreate === undefined) {
window.midgardCreate = {};
}
if (window.midgardCreate.locale === undefined) {
window.midgardCreate.locale = {};
}
window.midgardCreate.locale.nl = {
// Session-state buttons for the main toolbar
'Save': 'Opslaan',
'Saving': 'Bezig met opslaan',
'Cancel': 'Annuleren... | // Collection widgets
'Add': 'Toevoegen',
'Choose type to add': 'Kies type om toe te voegen'
}; | random_line_split | |
basemodule.js | // Copyright 2008 The Closure Library 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
//
// Unl... | * A basic module object that represents a module of Javascript code that can
* be dynamically loaded.
*
* @constructor
* @extends {goog.Disposable}
*/
goog.module.BaseModule = function() {
goog.Disposable.call(this);
};
goog.inherits(goog.module.BaseModule, goog.Disposable);
/**
* Performs any l... |
/**
| random_line_split |
el.js | /*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute ... | 201 : 'Ένα αρχείο με την ίδια ονομασία υπάρχει ήδη. Το μεταφορτωμένο αρχείο μετονομάστηκε σε "%1"',
202 : 'Λανθασμένο Αρχείο',
203 : 'Λανθασμένο Αρχείο. Το μέγεθος του αρχείου είναι πολύ μεγάλο.',
204 : 'Το μεταφορτωμένο αρχείο είναι χαλασμένο.',
205 : 'Δεν υπάρχει προσωρινός φάκελος για να χρησιμοποιηθεί για ... | 110 : 'Άγνωστο Λάθος.',
115 : 'Το αρχείο ή φάκελος υπάρχει ήδη.',
116 : 'Ο φάκελος δεν βρέθηκε. Παρακαλούμε ανανεώστε τη σελίδα και προσπαθήστε ξανά.',
117 : 'Το αρχείο δεν βρέθηκε. Παρακαλούμε ανανεώστε τη σελίδα και προσπαθήστε ξανά.',
118 : 'Source and target paths are equal.', // MISSING
| random_line_split |
error.rs | use std::io;
use std::fmt;
use std::error::Error;
/// Result type for using with [`EmuleadError`].
pub type EmuleadResult<T> = Result<T, EmuleadError>;
/// Error type using for the project errors.
#[derive(Debug)]
pub enum EmuleadError {
/// IO Error
Io(io::Error),
/// Rotate bytes error used in [`network... | }
} |
fn from(err: io::Error) -> EmuleadError {
EmuleadError::Io(err) | random_line_split |
error.rs | use std::io;
use std::fmt;
use std::error::Error;
/// Result type for using with [`EmuleadError`].
pub type EmuleadResult<T> = Result<T, EmuleadError>;
/// Error type using for the project errors.
#[derive(Debug)]
pub enum EmuleadError {
/// IO Error
Io(io::Error),
/// Rotate bytes error used in [`network... | (&self) -> Option<&Error> {
match *self {
EmuleadError::Io(ref err) => Some(err),
_ => None
}
}
}
impl From<io::Error> for EmuleadError {
fn from(err: io::Error) -> EmuleadError {
EmuleadError::Io(err)
}
}
| cause | identifier_name |
error.rs | use std::io;
use std::fmt;
use std::error::Error;
/// Result type for using with [`EmuleadError`].
pub type EmuleadResult<T> = Result<T, EmuleadError>;
/// Error type using for the project errors.
#[derive(Debug)]
pub enum EmuleadError {
/// IO Error
Io(io::Error),
/// Rotate bytes error used in [`network... |
}
impl From<io::Error> for EmuleadError {
fn from(err: io::Error) -> EmuleadError {
EmuleadError::Io(err)
}
}
| {
match *self {
EmuleadError::Io(ref err) => Some(err),
_ => None
}
} | identifier_body |
crawler_wikipedia.py | #encoding=utf-8
#------------------------------------------------------------------
# File Name: crawler_wikipedia_v0.py
# Author: yy
# Mail: RNHisnothuman@gmail.com
# Date: 2014年02月12日 星期三 15时15分24秒
#-------------------------------------------------------------------
import time
import sys
import string
import ur... | print """
-----------------------------------------------------------------
a crawler on wikipedia
-----------------------------------------------------------------
content is in file:
wiki.txt
the program is working......
"""
mycrawler = crawler_wikipedia()
mycrawler.main() | # program entrance
#
#----------------------------------------------------------------
| random_line_split |
crawler_wikipedia.py | #encoding=utf-8
#------------------------------------------------------------------
# File Name: crawler_wikipedia_v0.py
# Author: yy
# Mail: RNHisnothuman@gmail.com
# Date: 2014年02月12日 星期三 15时15分24秒
#-------------------------------------------------------------------
import time
import sys
import string
import ur... | pagecontent = urllib2.urlopen(apistr).read()
bs = BeautifulSoup(str(pagecontent))
content = bs.find('page')
if None == content:
print apistr + u' is empty!!'
return None
else:
flag_title = False
for attribute in content.attrs:
if attribute =... | (self,apistr):
| identifier_name |
crawler_wikipedia.py | #encoding=utf-8
#------------------------------------------------------------------
# File Name: crawler_wikipedia_v0.py
# Author: yy
# Mail: RNHisnothuman@gmail.com
# Date: 2014年02月12日 星期三 15时15分24秒
#-------------------------------------------------------------------
import time
import sys
import string
import ur... | flag_title = False
for attribute in content.attrs:
if attribute == u'title':
flag_title = True
if flag_title:
print apistr + u' has content!!'
contentStr = self.get_content_helper(apistr)
return contentStr
else:
return None
#--------------------------------------------... | is empty!!'
return None
else:
| conditional_block |
crawler_wikipedia.py | #encoding=utf-8
#------------------------------------------------------------------
# File Name: crawler_wikipedia_v0.py
# Author: yy
# Mail: RNHisnothuman@gmail.com
# Date: 2014年02月12日 星期三 15时15分24秒
#-------------------------------------------------------------------
import time
import sys
import string
import ur... | --------------------------------------------------
#
# program entrance
#
#----------------------------------------------------------------
print """
-----------------------------------------------------------------
a crawler on wikipedia
------------------------------------... | setdefaultencoding('utf-8')
#init the pageid
count = 121213#a exsit word
#get the handle of output file
outputfile = open(self.__class__.MeanFileName,'a+')
#write the working time into file
beginStr = 'begin time:\n' + time.asctime() + u'\n'
outputfile.write(beginStr)
#while(count < 2):
# #generat... | identifier_body |
connect.test.js | //@ sourceMappingURL=connect.test.map
// Generated by CoffeeScript 1.6.1
(function() {
var assert, async, wongo,
__hasProp = {}.hasOwnProperty;
assert = require('assert'); | async = require('async');
wongo = require('../lib/wongo');
describe('Wongo.connect()', function() {
it('should connect to the database', function(done) {
wongo.connect(process.env.DB_URL);
return done();
});
return it('should clear every registered schema', function(done) {
var _ty... | random_line_split | |
account_report_account_balance.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | (osv.osv_memory):
_inherit = "account.common.account.report"
_name = 'account.balance.report'
_description = 'Trial Balance Report'
_columns = {
'journal_ids': fields.many2many('account.journal', 'account_balance_report_journal_rel', 'account_id', 'journal_id', 'Journals', required=True),
}... | account_balance_report | identifier_name |
account_report_account_balance.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| data = self.pre_print_report(cr, uid, ids, data, context=context)
return {'type': 'ir.actions.report.xml', 'report_name': 'account.account.balance', 'datas': data} | identifier_body |
account_report_account_balance.py | # -*- coding: utf-8 -*-
##############################################################################
# | #
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that... | # OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). | random_line_split |
base-platform.ts | import { ExecuteInCurrentWindow, Inject, mutation, StatefulService } from 'services/core';
import {
EPlatformCallResult,
IPlatformState,
TPlatform,
TPlatformCapability,
TStartStreamOptions,
TPlatformCapabilityMap,
} from './index';
import { StreamingService } from 'services/streaming';
import { UserService ... | if (this.hasCapability('viewerCount')) {
const count = await this.fetchViewerCount();
this.nViewerSamples += 1;
this.averageViewers =
(this.averageViewers * (this.nViewerSamples - 1) + count) / this.nViewerSamples;
this.peakViewers = Math.max(this.peakViewers, count);
... | const runInterval = async () => { | random_line_split |
base-platform.ts | import { ExecuteInCurrentWindow, Inject, mutation, StatefulService } from 'services/core';
import {
EPlatformCallResult,
IPlatformState,
TPlatform,
TPlatformCapability,
TStartStreamOptions,
TPlatformCapabilityMap,
} from './index';
import { StreamingService } from 'services/streaming';
import { UserService ... | () {
return Promise.resolve({});
}
@mutation()
protected SET_VIEWERS_COUNT(viewers: number) {
this.state.viewersCount = viewers;
}
@mutation()
protected SET_STREAM_KEY(key: string) {
this.state.streamKey = key;
}
@mutation()
protected SET_PREPOPULATED(isPrepopulated: boolean) {
this... | fetchUserInfo | identifier_name |
base-platform.ts | import { ExecuteInCurrentWindow, Inject, mutation, StatefulService } from 'services/core';
import {
EPlatformCallResult,
IPlatformState,
TPlatform,
TPlatformCapability,
TStartStreamOptions,
TPlatformCapabilityMap,
} from './index';
import { StreamingService } from 'services/streaming';
import { UserService ... |
}
| {
this.state.settings = { ...this.state.settings, ...settingsPatch };
} | identifier_body |
middlewares.rs | use config::Config;
use db;
use hyper::header::UserAgent;
use hyper::method::Method;
use nickel::{Continue, Halt, MediaType, Middleware, MiddlewareResult, Request, Response};
use nickel::status::StatusCode;
use plugin::Extensible;
use r2d2::{Config as PoolConfig, Pool};
use r2d2_postgres::{PostgresConnectionManager as ... | <'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, rep: Response<'mw, D>) -> MiddlewareResult<'mw, D> {
req.extensions_mut().insert::<ConfigMiddleware>(self.config.clone());
Ok(Continue(rep))
}
}
pub struct PostgresMiddleware {
pub pool: Pool<Manager>,
}
impl PostgresMiddleware {
pub fn... | invoke | identifier_name |
middlewares.rs | use config::Config;
use db;
use hyper::header::UserAgent;
use hyper::method::Method;
use nickel::{Continue, Halt, MediaType, Middleware, MiddlewareResult, Request, Response};
use nickel::status::StatusCode;
use plugin::Extensible;
use r2d2::{Config as PoolConfig, Pool};
use r2d2_postgres::{PostgresConnectionManager as ... |
}
}
| {
res.set(StatusCode::Forbidden);
res.set(MediaType::Json);
let mut stream = res.start()?;
if let Err(err) = stream.write_all(r#"{"data": "Access denied", "success": false}"#.as_bytes()) {
stream.bail(format!("[AuthMiddleware] Unable to halt request: {}", ... | conditional_block |
middlewares.rs | use config::Config;
use db;
use hyper::header::UserAgent;
use hyper::method::Method;
use nickel::{Continue, Halt, MediaType, Middleware, MiddlewareResult, Request, Response};
use nickel::status::StatusCode;
use plugin::Extensible;
use r2d2::{Config as PoolConfig, Pool};
use r2d2_postgres::{PostgresConnectionManager as ... |
}
impl Key for ConfigMiddleware {
type Value = Arc<Config>;
}
impl<D> Middleware<D> for ConfigMiddleware {
fn invoke<'mw, 'conn>(&self, req: &mut Request<'mw, 'conn, D>, rep: Response<'mw, D>) -> MiddlewareResult<'mw, D> {
req.extensions_mut().insert::<ConfigMiddleware>(self.config.clone());
... | {
ConfigMiddleware { config: config }
} | identifier_body |
middlewares.rs | use config::Config;
use db;
use hyper::header::UserAgent;
use hyper::method::Method;
use nickel::{Continue, Halt, MediaType, Middleware, MiddlewareResult, Request, Response};
use nickel::status::StatusCode;
use plugin::Extensible;
use r2d2::{Config as PoolConfig, Pool};
use r2d2_postgres::{PostgresConnectionManager as ... | } {
Ok(Continue(res))
} else {
res.set(StatusCode::Forbidden);
res.set(MediaType::Json);
let mut stream = res.start()?;
if let Err(err) = stream.write_all(r#"{"data": "Access denied", "success": false}"#.as_bytes()) {
stream.bai... | }
_ => false, | random_line_split |
replace_pipe.ts | import {
isBlank,
isString,
isNumber,
isFunction,
RegExpWrapper,
StringWrapper
} from 'angular2/src/facade/lang';
import {Injectable, PipeTransform, Pipe} from 'angular2/core';
import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception';
/**
* Creates a new String with some or all of th... |
private _supportedReplacement(replacement: any): boolean {
return isString(replacement) || isFunction(replacement);
}
}
| {
return isString(pattern) || pattern instanceof RegExp;
} | identifier_body |
replace_pipe.ts | import {
isBlank,
isString,
isNumber,
isFunction,
RegExpWrapper,
StringWrapper
} from 'angular2/src/facade/lang';
import {Injectable, PipeTransform, Pipe} from 'angular2/core';
import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception';
/**
* Creates a new String with some or all of th... |
return StringWrapper.replace(input, <string>pattern, <string>replacement);
}
private _supportedInput(input: any): boolean { return isString(input) || isNumber(input); }
private _supportedPattern(pattern: any): boolean {
return isString(pattern) || pattern instanceof RegExp;
}
private _supportedRe... | {
// use the replaceAll variant
return StringWrapper.replaceAll(input, pattern, <string>replacement);
} | conditional_block |
replace_pipe.ts | import {
isBlank,
isString,
isNumber,
isFunction,
RegExpWrapper,
StringWrapper
} from 'angular2/src/facade/lang';
import {Injectable, PipeTransform, Pipe} from 'angular2/core';
import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception';
/**
* Creates a new String with some or all of th... | (input: any): boolean { return isString(input) || isNumber(input); }
private _supportedPattern(pattern: any): boolean {
return isString(pattern) || pattern instanceof RegExp;
}
private _supportedReplacement(replacement: any): boolean {
return isString(replacement) || isFunction(replacement);
}
}
| _supportedInput | identifier_name |
replace_pipe.ts | import {
isBlank,
isString,
isNumber,
isFunction,
RegExpWrapper,
StringWrapper
} from 'angular2/src/facade/lang';
import {Injectable, PipeTransform, Pipe} from 'angular2/core';
import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception';
/**
* Creates a new String with some or all of th... | }
if (!this._supportedInput(value)) {
throw new InvalidPipeArgumentException(ReplacePipe, value);
}
var input = value.toString();
if (!this._supportedPattern(pattern)) {
throw new InvalidPipeArgumentException(ReplacePipe, pattern);
}
if (!this._supportedReplacement(replacement... | export class ReplacePipe implements PipeTransform {
transform(value: any, pattern: string | RegExp, replacement: Function | string): any {
if (isBlank(value)) {
return value; | random_line_split |
trace_pid.py | # Copyright (c) 2015, Simone Margaritelli <evilsocket at gmail dot com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notic... |
pid = int(sys.argv[1])
try:
adb = ADB()
print "@ Pushing files to /data/local/tmp ..."
adb.sh( "rm -rf /data/local/tmp/injector /data/local/tmp/libhook.so" )
adb.push( "libs/armeabi-v7a/injector", "/data/local/tmp/injector" )
adb.push( "libs/armeabi-v7a/libhook.so", "/data/local/tmp/libhook.so... | print "Usage: python %s <pid>" % sys.argv[0]
quit() | conditional_block |
trace_pid.py | # Copyright (c) 2015, Simone Margaritelli <evilsocket at gmail dot com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notic... | adb.set_selinux_level( 0 )
adb.clear_log()
print "@ Injection into PID %d starting ..." % pid
adb.sudo( "/data/local/tmp/injector %d /data/local/tmp/libhook.so" % pid )
adb.logcat("LIBHOOK")
except KeyboardInterrupt:
pass |
# we need to set selinux to permissive in order to make ptrace work | random_line_split |
location_mock.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Location, LocationStrategy} from '@angular/common';
import {EventEmitter, Injectable} from '@angular/core';
... | isCurrentPathEqualTo(path: string, query: string = ''): boolean {
const givenPath = path.endsWith('/') ? path.substring(0, path.length - 1) : path;
const currPath =
this.path().endsWith('/') ? this.path().substring(0, this.path().length - 1) : this.path();
return currPath == givenPath + (query.le... | path(): string { return this._history[this._historyIndex].path; }
private state(): string { return this._history[this._historyIndex].state; }
| random_line_split |
location_mock.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Location, LocationStrategy} from '@angular/common';
import {EventEmitter, Injectable} from '@angular/core';
... |
replaceState(path: string, query: string = '', state: any = null) {
path = this.prepareExternalUrl(path);
const history = this._history[this._historyIndex];
if (history.path == path && history.query == query) {
return;
}
history.path = path;
history.query = query;
history.state =... | {
path = this.prepareExternalUrl(path);
if (this._historyIndex > 0) {
this._history.splice(this._historyIndex + 1);
}
this._history.push(new LocationState(path, query, state));
this._historyIndex = this._history.length - 1;
const locationState = this._history[this._historyIndex - 1];
... | identifier_body |
location_mock.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Location, LocationStrategy} from '@angular/common';
import {EventEmitter, Injectable} from '@angular/core';
... | (url: string) { this._baseHref = url; }
path(): string { return this._history[this._historyIndex].path; }
private state(): string { return this._history[this._historyIndex].state; }
isCurrentPathEqualTo(path: string, query: string = ''): boolean {
const givenPath = path.endsWith('/') ? path.substring(0, pa... | setBaseHref | identifier_name |
location_mock.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Location, LocationStrategy} from '@angular/common';
import {EventEmitter, Injectable} from '@angular/core';
... |
const url = path + (query.length > 0 ? ('?' + query) : '');
this.urlChanges.push(url);
this._subject.emit({'url': url, 'pop': false});
}
replaceState(path: string, query: string = '', state: any = null) {
path = this.prepareExternalUrl(path);
const history = this._history[this._historyIndex]... | {
return;
} | conditional_block |
app.js | import * as THREE from '../../libs/three/three.module.js';
import { Stats } from '../../libs/stats.module.js';
import { OrbitControls } from '../../libs/three/jsm/OrbitControls.js';
import { ARButton } from '../../libs/ARButton.js';
class App{
| (){
// Creates a <div> element and adds it to the HTML page.
const container = document.createElement( 'div' );
document.body.appendChild( container );
/*
* SCENE
*/
// INITIALIZATION
this.scene = new THREE.Scene();
// LIGHTING
// Create an a... | constructor | identifier_name |
app.js | import * as THREE from '../../libs/three/three.module.js';
import { Stats } from '../../libs/stats.module.js';
import { OrbitControls } from '../../libs/three/jsm/OrbitControls.js';
import { ARButton } from '../../libs/ARButton.js';
class App{
constructor(){
// Creates a <div> element and adds it to the HTM... | // ORBIT CONTROLS for non-XR view
this.controls = new OrbitControls( this.camera, this.renderer.domElement );
this.controls.target.set(0, 1.6, 0);
this.controls.update();
// STATS for XR
this.stats = new Stats();
document.body.appendChild( this.stats.dom );
... | random_line_split | |
app.js | import * as THREE from '../../libs/three/three.module.js';
import { Stats } from '../../libs/stats.module.js';
import { OrbitControls } from '../../libs/three/jsm/OrbitControls.js';
import { ARButton } from '../../libs/ARButton.js';
class App{
constructor(){
// Creates a <div> element and adds it to the HTM... |
}
export { App }; | {
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize( window.innerWidth, window.innerHeight );
} | identifier_body |
spawn.js | 'use strict'
const { spawn } = require('@malept/cross-spawn-promise')
const which = require('which')
function updateExecutableMissingException (err, hasLogger) |
module.exports = async function (cmd, args, logger) {
if (process.platform !== 'win32') {
args.unshift(cmd)
cmd = 'mono'
}
return spawn(cmd, args, {
logger,
updateErrorCallback: updateExecutableMissingException
})
}
| {
if (hasLogger && err.code === 'ENOENT' && err.syscall === 'spawn mono') {
let installer
let pkg
if (process.platform === 'darwin') {
installer = 'brew'
pkg = 'mono'
} else if (which.sync('dnf', { nothrow: true })) {
installer = 'dnf'
pkg = 'mono-core'
} else { // assume ... | identifier_body |
spawn.js | 'use strict'
const { spawn } = require('@malept/cross-spawn-promise')
const which = require('which')
function | (err, hasLogger) {
if (hasLogger && err.code === 'ENOENT' && err.syscall === 'spawn mono') {
let installer
let pkg
if (process.platform === 'darwin') {
installer = 'brew'
pkg = 'mono'
} else if (which.sync('dnf', { nothrow: true })) {
installer = 'dnf'
pkg = 'mono-core'
}... | updateExecutableMissingException | identifier_name |
spawn.js | 'use strict'
const { spawn } = require('@malept/cross-spawn-promise')
const which = require('which')
function updateExecutableMissingException (err, hasLogger) {
if (hasLogger && err.code === 'ENOENT' && err.syscall === 'spawn mono') {
let installer
let pkg
if (process.platform === 'darwin') {
in... | else { // assume apt-based Linux distro
installer = 'apt'
pkg = 'mono-runtime'
}
err.message = `Your system is missing the ${pkg} package. Try, e.g. '${installer} install ${pkg}'`
}
}
module.exports = async function (cmd, args, logger) {
if (process.platform !== 'win32') {
args.unshift(cm... | {
installer = 'dnf'
pkg = 'mono-core'
} | conditional_block |
spawn.js | 'use strict'
const { spawn } = require('@malept/cross-spawn-promise')
const which = require('which')
function updateExecutableMissingException (err, hasLogger) {
if (hasLogger && err.code === 'ENOENT' && err.syscall === 'spawn mono') {
let installer
let pkg
if (process.platform === 'darwin') {
in... | pkg = 'mono-runtime'
}
err.message = `Your system is missing the ${pkg} package. Try, e.g. '${installer} install ${pkg}'`
}
}
module.exports = async function (cmd, args, logger) {
if (process.platform !== 'win32') {
args.unshift(cmd)
cmd = 'mono'
}
return spawn(cmd, args, {
logger,
... | pkg = 'mono-core'
} else { // assume apt-based Linux distro
installer = 'apt' | random_line_split |
version.rs | use std::str::FromStr;
use cargo_edit::VersionExt;
use crate::errors::*;
#[derive(Clone, Debug)]
pub enum TargetVersion {
Relative(BumpLevel),
Absolute(semver::Version),
}
impl TargetVersion {
pub fn bump(
&self,
current: &semver::Version,
metadata: Option<&str>,
) -> CargoRe... |
}
#[derive(Debug, Clone, Copy)]
pub enum BumpLevel {
Major,
Minor,
Patch,
/// Strip all pre-release flags
Release,
Rc,
Beta,
Alpha,
}
impl BumpLevel {
pub fn variants() -> &'static [&'static str] {
&["major", "minor", "patch", "release", "rc", "beta", "alpha"]
}
}
imp... | {
TargetVersion::Relative(BumpLevel::Release)
} | identifier_body |
version.rs | use std::str::FromStr;
use cargo_edit::VersionExt;
use crate::errors::*;
#[derive(Clone, Debug)]
pub enum TargetVersion {
Relative(BumpLevel),
Absolute(semver::Version),
}
impl TargetVersion {
pub fn bump(
&self,
current: &semver::Version,
metadata: Option<&str>,
) -> CargoRe... | version.increment_alpha()?;
}
};
if let Some(metadata) = metadata {
version.metadata(metadata)?;
}
Ok(())
}
} | }
BumpLevel::Beta => {
version.increment_beta()?;
}
BumpLevel::Alpha => { | random_line_split |
version.rs | use std::str::FromStr;
use cargo_edit::VersionExt;
use crate::errors::*;
#[derive(Clone, Debug)]
pub enum TargetVersion {
Relative(BumpLevel),
Absolute(semver::Version),
}
impl TargetVersion {
pub fn bump(
&self,
current: &semver::Version,
metadata: Option<&str>,
) -> CargoRe... | (
self,
version: &mut semver::Version,
metadata: Option<&str>,
) -> CargoResult<()> {
match self {
BumpLevel::Major => {
version.increment_major();
}
BumpLevel::Minor => {
version.increment_minor();
}
... | bump_version | identifier_name |
pa-Guru.js | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
glo... |
global.ng.common.locales['pa-guru'] = [
'pa-Guru',
[['ਸ.', 'ਸ਼.'], ['ਪੂ.ਦੁ.', 'ਬਾ.ਦੁ.'], u],
[['ਪੂ.ਦੁ.', 'ਬਾ.ਦੁ.'], u, u],
[
['ਐ', 'ਸੋ', 'ਮੰ', 'ਬੁੱ', 'ਵੀ', 'ਸ਼ੁੱ', 'ਸ਼'],
[
'ਐਤ', 'ਸੋਮ', 'ਮੰਗਲ', 'ਬੁੱਧ', 'ਵੀਰ', 'ਸ਼ੁੱਕਰ',
'ਸ਼ਨਿੱਚਰ'
],
[
'ਐਤਵਾਰ', 'ਸੋਮਵਾਰ', ... | {
if (n === Math.floor(n) && n >= 0 && n <= 1) return 1;
return 5;
} | identifier_body |
pa-Guru.js | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
glo... | ]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window); | 'ਅੱਧੀ ਰਾਤ', 'ਸਵੇਰੇ', 'ਦੁਪਹਿਰੇ', 'ਸ਼ਾਮ',
'ਰਾਤ'
]
],
['00:00', ['04:00', '12:00'], ['12:00', '16:00'], ['16:00', '21:00'], ['21:00', '04:00']] | random_line_split |
pa-Guru.js | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
glo... | (n) {
if (n === Math.floor(n) && n >= 0 && n <= 1) return 1;
return 5;
}
global.ng.common.locales['pa-guru'] = [
'pa-Guru',
[['ਸ.', 'ਸ਼.'], ['ਪੂ.ਦੁ.', 'ਬਾ.ਦੁ.'], u],
[['ਪੂ.ਦੁ.', 'ਬਾ.ਦੁ.'], u, u],
[
['ਐ', 'ਸੋ', 'ਮੰ', 'ਬੁੱ', 'ਵੀ', 'ਸ਼ੁੱ', 'ਸ਼'],
[
'ਐਤ', 'ਸੋਮ', 'ਮੰਗਲ', 'ਬੁੱਧ... | plural | identifier_name |
filetable.rs | /*
* Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Genera... | log!(
FILES,
"FileEPs[{}] = EP:{},FD:{}", i, ep, fd
);
self.file_eps[i] = Some(FileEP {
fd: fd,
ep: ep,
});
... | for i in 0..MAX_EPS {
if self.file_eps[i].is_none() { | random_line_split |
filetable.rs | /*
* Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Genera... | (&self, s: &mut VecSink) {
let count = self.files.iter().filter(|&f| f.is_some()).count();
s.push(&count);
for fd in 0..MAX_FILES {
if let Some(ref f) = self.files[fd] {
let file = f.borrow();
s.push(&fd);
s.push(&file.file_type());
... | serialize | identifier_name |
filetable.rs | /*
* Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Genera... |
pub fn alloc(&mut self, file: FileHandle) -> Result<Fd, Error> {
for fd in 0..MAX_FILES {
if self.files[fd].is_none() {
self.set(fd, file);
return Ok(fd);
}
}
Err(Error::new(Code::NoSpace))
}
pub fn get(&self, fd: Fd) -> Opti... | {
self.alloc(file.clone()).map(|fd| FileRef::new(file, fd))
} | identifier_body |
filetable.rs | /*
* Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Genera... |
}
// TODO be smarter here
let mut i = self.file_ep_victim;
for _ in 0..MAX_EPS {
if let Some(ref mut fep) = self.file_eps[i] {
log!(
FILES,
"FileEPs[{}] = EP:{},FD: switching from {} to {}",
i, fep.... | {
for i in 0..MAX_EPS {
if self.file_eps[i].is_none() {
log!(
FILES,
"FileEPs[{}] = EP:{},FD:{}", i, ep, fd
);
self.file_eps[i] = Some(FileEP {
... | conditional_block |
system_settings.py | from django.core.management.base import BaseCommand
from dojo.models import System_Settings
class Command(BaseCommand):
| help = 'Updates product grade calculation'
def handle(self, *args, **options):
code = """def grade_product(crit, high, med, low):
health=100
if crit > 0:
health = 40
health = health - ((crit - 1) * 5)
if high > 0:
if health... | identifier_body | |
system_settings.py | from django.core.management.base import BaseCommand
from dojo.models import System_Settings
class Command(BaseCommand):
help = 'Updates product grade calculation'
def | (self, *args, **options):
code = """def grade_product(crit, high, med, low):
health=100
if crit > 0:
health = 40
health = health - ((crit - 1) * 5)
if high > 0:
if health == 100:
health = 60
h... | handle | identifier_name |
system_settings.py | from django.core.management.base import BaseCommand
from dojo.models import System_Settings
class Command(BaseCommand):
help = 'Updates product grade calculation'
def handle(self, *args, **options):
code = """def grade_product(crit, high, med, low):
health=100
if crit > 0:
... | health = health - low
if health < 5:
health = 5
return health
"""
system_settings = System_Settings.objects.get(id=1)
system_settings.product_grade = code
system_settings.save() | health = 80
health = health - ((med - 1) * 2)
if low > 0:
if health == 100:
health = 95 | random_line_split |
mysql-tests.ts | import fs = require('fs');
import mysql = require('mysql');
import stream = require('stream');
/// Connections
let connection = mysql.createConnection({
host: 'localhost',
user: 'me',
password: 'test'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
if (... | connection.pause();
const processRow = (row: any, cb: () => void) => {
cb();
};
processRow(row, () => {
connection.resume();
});
})
.on('end', () => {
// all rows have been received
});
const writable = fs.createWriteStream('file.txt... | .on('result', row => {
// Pausing the connnection is useful if your processing involves I/O | random_line_split |
mysql-tests.ts | import fs = require('fs');
import mysql = require('mysql');
import stream = require('stream');
/// Connections
let connection = mysql.createConnection({
host: 'localhost',
user: 'me',
password: 'test'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => {
if (... |
return txt;
});
};
connection.query("UPDATE posts SET title = :title", {title: "Hello MySQL"});
const s: stream.Readable = connection.query("UPDATE posts SET title = :title", {title: "Hello MySQL"}).stream({highWaterMark: 5});
connection.query('INSERT INTO posts SET ?', {title: 'test'}, (err, result) =>... | {
return this.escape(values[key]);
} | conditional_block |
test_dauth.py |
from nintendo import dauth, switch
from anynet import http
import pytest
CHALLENGE_REQUEST = \
"POST /v6/challenge HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n... |
async with http.serve(handler, "127.0.0.1", 12345):
keys = switch.KeySet()
keys["aes_kek_generation_source"] = bytes.fromhex("485d45ad27c07c7e538c0183f90ee845")
keys["master_key_0a"] = bytes.fromhex("37eed242e0f2ce6f8371e783c1a6a0ae")
client = dauth.DAuthClient(keys)
client.set_url("127.0.0.1:12345... | assert request.encode().decode() == TOKEN_REQUEST
response = http.HTTPResponse(200)
response.json = {
"device_auth_token": "device token"
}
return response | conditional_block |
test_dauth.py | from nintendo import dauth, switch
from anynet import http
import pytest
CHALLENGE_REQUEST = \
"POST /v6/challenge HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n" ... | async def test_dauth():
async def handler(client, request):
if request.path == "/v6/challenge":
assert request.encode().decode() == CHALLENGE_REQUEST
response = http.HTTPResponse(200)
response.json = {
"challenge": "vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=",
"data": "dlL7ZBNSLmYo1hUlKYZiU... | random_line_split | |
test_dauth.py |
from nintendo import dauth, switch
from anynet import http
import pytest
CHALLENGE_REQUEST = \
"POST /v6/challenge HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n... | ():
async def handler(client, request):
if request.path == "/v6/challenge":
assert request.encode().decode() == CHALLENGE_REQUEST
response = http.HTTPResponse(200)
response.json = {
"challenge": "vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=",
"data": "dlL7ZBNSLmYo1hUlKYZiUA=="
}
retur... | test_dauth | identifier_name |
test_dauth.py |
from nintendo import dauth, switch
from anynet import http
import pytest
CHALLENGE_REQUEST = \
"POST /v6/challenge HTTP/1.1\r\n" \
"Host: 127.0.0.1:12345\r\n" \
"User-Agent: libcurl (nnDauth; 16f4553f-9eee-4e39-9b61-59bc7c99b7c8; SDK 12.3.0.0)\r\n" \
"Accept: */*\r\n" \
"X-Nintendo-PowerState: FA\r\n... |
async with http.serve(handler, "127.0.0.1", 12345):
keys = switch.KeySet()
keys["aes_kek_generation_source"] = bytes.fromhex("485d45ad27c07c7e538c0183f90ee845")
keys["master_key_0a"] = bytes.fromhex("37eed242e0f2ce6f8371e783c1a6a0ae")
client = dauth.DAuthClient(keys)
client.set_url("127.0.0.1:12345... | if request.path == "/v6/challenge":
assert request.encode().decode() == CHALLENGE_REQUEST
response = http.HTTPResponse(200)
response.json = {
"challenge": "vaNgVZZH7gUse0y3t8Cksuln-TAVtvBmcD-ow59qp0E=",
"data": "dlL7ZBNSLmYo1hUlKYZiUA=="
}
return response
else:
assert request.encode... | identifier_body |
util.py | #!/usr/bin/env python
# encoding: utf-8
import random
def | (brightness_offset=1):
hex_color = "#%06x" % random.randint(0,0xFFFFFF)
""" takes a color like #87c95f and produces a lighter or darker variant """
if len(hex_color) != 7:
raise Exception("Passed %s into color_variant(), needs to be in #87c95f format." % hex_color)
rgb_hex = [hex_color[x:x+2... | color_variant | identifier_name |
util.py | #!/usr/bin/env python
# encoding: utf-8
import random
def color_variant(brightness_offset=1):
| hex_color = "#%06x" % random.randint(0,0xFFFFFF)
""" takes a color like #87c95f and produces a lighter or darker variant """
if len(hex_color) != 7:
raise Exception("Passed %s into color_variant(), needs to be in #87c95f format." % hex_color)
rgb_hex = [hex_color[x:x+2] for x in [1, 3, 5]]
n... | identifier_body | |
util.py | #!/usr/bin/env python
# encoding: utf-8
import random
def color_variant(brightness_offset=1):
hex_color = "#%06x" % random.randint(0,0xFFFFFF)
""" takes a color like #87c95f and produces a lighter or darker variant """
if len(hex_color) != 7:
|
rgb_hex = [hex_color[x:x+2] for x in [1, 3, 5]]
new_rgb_int = [int(hex_value, 16) + brightness_offset for hex_value in rgb_hex]
new_rgb_int = [min([255, max([0, i])]) for i in new_rgb_int] # make sure new values are between 0 and 255
# hex() produces "0x88", we want just "88"
return [hex_color, "#"... | raise Exception("Passed %s into color_variant(), needs to be in #87c95f format." % hex_color) | conditional_block |
util.py | #!/usr/bin/env python
# encoding: utf-8
import random
def color_variant(brightness_offset=1):
hex_color = "#%06x" % random.randint(0,0xFFFFFF) | new_rgb_int = [int(hex_value, 16) + brightness_offset for hex_value in rgb_hex]
new_rgb_int = [min([255, max([0, i])]) for i in new_rgb_int] # make sure new values are between 0 and 255
# hex() produces "0x88", we want just "88"
return [hex_color, "#" + "".join([hex(i)[2:] for i in new_rgb_int])] | """ takes a color like #87c95f and produces a lighter or darker variant """
if len(hex_color) != 7:
raise Exception("Passed %s into color_variant(), needs to be in #87c95f format." % hex_color)
rgb_hex = [hex_color[x:x+2] for x in [1, 3, 5]] | random_line_split |
format-violation-test.ts | import { Result } from 'axe-core';
import { module, test } from 'qunit';
import formatViolation from 'ember-a11y-testing/test-support/format-violation';
module('Unit | Utils | formatViolation', function () {
test('formats a well-formed violation and relevant html', function (assert) {
let violation: Result = {
... | ],
};
let message = formatViolation(violation, [violation.nodes[0].html]);
let expected = `[critical]: it should be better \nViolated 1 time. Offending nodes are: \n<input type="text">\nhttp://example.com`;
assert.strictEqual(message, expected);
});
test('formats a well-formed violation', fu... | random_line_split | |
go90.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
determine_ext,
ExtractorError,
int_or_none,
parse_age_limit,
parse_iso8601,
)
class Go90IE(InfoExtractor):
| _VALID_URL = r'https?://(?:www\.)?go90\.com/videos/(?P<id>[0-9a-zA-Z]+)'
_TEST = {
'url': 'https://www.go90.com/videos/84BUqjLpf9D',
'md5': 'efa7670dbbbf21a7b07b360652b24a32',
'info_dict': {
'id': '84BUqjLpf9D',
'ext': 'mp4',
'title': 'Daily VICE - Inside ... | identifier_body | |
go90.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
determine_ext,
ExtractorError,
int_or_none,
parse_age_limit,
parse_iso8601,
)
class | (InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?go90\.com/videos/(?P<id>[0-9a-zA-Z]+)'
_TEST = {
'url': 'https://www.go90.com/videos/84BUqjLpf9D',
'md5': 'efa7670dbbbf21a7b07b360652b24a32',
'info_dict': {
'id': '84BUqjLpf9D',
'ext': 'mp4',
'title': ... | Go90IE | identifier_name |
go90.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
determine_ext,
ExtractorError,
int_or_none,
parse_age_limit,
parse_iso8601,
)
class Go90IE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?go90\.com/videos/(?P<id>[0-9a... |
elif source_type == 'dash':
formats.extend(self._extract_mpd_formats(
source_location, video_id, mpd_id='dash', fatal=False))
else:
formats.append({
'format_id': source.get('n... | m3u8_formats = self._extract_m3u8_formats(
source_location, video_id, 'mp4',
'm3u8_native', m3u8_id='hls', fatal=False)
for f in m3u8_formats:
mobj = re.search(r'/hls-(\d+)-(\d+)K', f['url'])
... | conditional_block |
go90.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
determine_ext,
ExtractorError,
int_or_none,
parse_age_limit,
parse_iso8601,
)
class Go90IE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?go90\.com/videos/(?P<id>[0-9a... | 'description': video_data.get('short_description'),
'like_count': int_or_none(video_data.get('like_count')),
'timestamp': parse_iso8601(video_data.get('released_at')),
'series': series,
'episode': episode,
'season': season,
'season_id':... | random_line_split | |
volume_axes.py | from traits.api import Bool, Float, Tuple
from tvtk.api import tvtk
from .volume_scene_member import ABCVolumeSceneMember
# Convenience for the trait definitions below
FloatPair = Tuple(Float, Float)
class VolumeAxes(ABCVolumeSceneMember):
""" An object which builds a CubeAxesActor for a scene containing a Volu... |
#--------------------------------------------------------------------------
# Default values
#--------------------------------------------------------------------------
def _visible_axis_ranges_default(self):
return ((0.0, 1.0), (0.0, 1.0), (0.0, 1.0))
def _visible_axis_scales_default(se... | if any(self.visible_axis_scales):
bounds = volume_actor.bounds
x_vis, y_vis, z_vis = self.visible_axis_scales
x_range, y_range, z_range = self.visible_axis_ranges
cube_axes = tvtk.CubeAxesActor(
bounds=bounds,
camera=scene_model.camera,
... | identifier_body |
volume_axes.py | from traits.api import Bool, Float, Tuple
from tvtk.api import tvtk
from .volume_scene_member import ABCVolumeSceneMember
# Convenience for the trait definitions below
FloatPair = Tuple(Float, Float)
class VolumeAxes(ABCVolumeSceneMember):
""" An object which builds a CubeAxesActor for a scene containing a Volu... | (self):
return (False, False, False)
| _visible_axis_scales_default | identifier_name |
volume_axes.py | from traits.api import Bool, Float, Tuple
from tvtk.api import tvtk
from .volume_scene_member import ABCVolumeSceneMember
# Convenience for the trait definitions below
FloatPair = Tuple(Float, Float)
class VolumeAxes(ABCVolumeSceneMember):
""" An object which builds a CubeAxesActor for a scene containing a Volu... |
#--------------------------------------------------------------------------
# Default values
#--------------------------------------------------------------------------
def _visible_axis_ranges_default(self):
return ((0.0, 1.0), (0.0, 1.0), (0.0, 1.0))
def _visible_axis_scales_default(se... | bounds = volume_actor.bounds
x_vis, y_vis, z_vis = self.visible_axis_scales
x_range, y_range, z_range = self.visible_axis_ranges
cube_axes = tvtk.CubeAxesActor(
bounds=bounds,
camera=scene_model.camera,
tick_location='outside',
... | conditional_block |
volume_axes.py | from traits.api import Bool, Float, Tuple
from tvtk.api import tvtk
from .volume_scene_member import ABCVolumeSceneMember
# Convenience for the trait definitions below
FloatPair = Tuple(Float, Float)
class VolumeAxes(ABCVolumeSceneMember):
""" An object which builds a CubeAxesActor for a scene containing a Volu... |
#--------------------------------------------------------------------------
# Default values
#--------------------------------------------------------------------------
def _visible_axis_ranges_default(self):
return ((0.0, 1.0), (0.0, 1.0), (0.0, 1.0))
def _visible_axis_scales_default(sel... | scene_model.renderer.add_actor(cube_axes) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.