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 |
|---|---|---|---|---|
blockdev.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// Code to handle a single block device.
use std::fs::OpenOptions;
use std::path::PathBuf;
use chrono::{DateTime, T... |
}
fn set_dbus_path(&mut self, path: MaybeDbusPath) {
self.dbus_path = path
}
fn get_dbus_path(&self) -> &MaybeDbusPath {
&self.dbus_path
}
}
impl Recordable<BaseBlockDevSave> for StratBlockDev {
fn record(&self) -> BaseBlockDevSave {
BaseBlockDevSave {
uui... | {
BlockDevState::NotInUse
} | conditional_block |
document.service.ts | import { Injectable } from '@angular/core';
import { Headers, Response } from '@angular/http';
import { Router } from '@angular/router';
import { AuthHttp } from 'angular2-jwt';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/th... | (document: Document): Observable<Document> {
return this.http.put(this.api + 'documents/' + document.id, JSON.stringify(document)).map(response => response.json()).catch(error => this.handleError(error, this.router));
}
deleteDocument(documentId: number): Observable<any> {
return this.http.dele... | updateDocument | identifier_name |
document.service.ts | import { Injectable } from '@angular/core';
import { Headers, Response } from '@angular/http';
import { Router } from '@angular/router';
import { AuthHttp } from 'angular2-jwt';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/th... |
return Observable.throw(error);
}
}
| {
router.navigate(['/login']); // THIS.router = NULL? WHY???
Notify.notifyRetryLogin();
return <Observable<any>>Observable.never();
} | conditional_block |
document.service.ts | import { Injectable } from '@angular/core';
import { Headers, Response } from '@angular/http';
import { Router } from '@angular/router';
import { AuthHttp } from 'angular2-jwt';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/th... | }
listAllDocuments(): Observable<Document[]> {
return this.http.get(this.api + 'documents').map(response => response.json()).catch(error => this.handleError(error, this.router));
}
getDocument(documentId: number): Observable<Document> {
return this.http.get(this.api + 'documents/' + do... | private api: string = environment.api_url;
constructor(private router: Router, private http: AuthHttp) {
console.log(this.constructor.name, 'API URL:', this.api); | random_line_split |
document.service.ts | import { Injectable } from '@angular/core';
import { Headers, Response } from '@angular/http';
import { Router } from '@angular/router';
import { AuthHttp } from 'angular2-jwt';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/th... |
listAllDocuments(): Observable<Document[]> {
return this.http.get(this.api + 'documents').map(response => response.json()).catch(error => this.handleError(error, this.router));
}
getDocument(documentId: number): Observable<Document> {
return this.http.get(this.api + 'documents/' + documen... | {
console.log(this.constructor.name, 'API URL:', this.api);
} | identifier_body |
gcloud_iam_sa_keys.py | # pylint: skip-file
# vim: expandtab:tabstop=4:shiftwidth=4
#pylint: disable=too-many-branches
def main():
|
# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
# import module snippets. This are required
from ansible.module_utils.basic import *
main()
| ''' ansible module for gcloud iam service-account keys'''
module = AnsibleModule(
argument_spec=dict(
# credentials
state=dict(default='present', type='str', choices=['present', 'absent', 'list']),
service_account_name=dict(required=True, type='str'),
key_form... | identifier_body |
gcloud_iam_sa_keys.py | # pylint: skip-file
# vim: expandtab:tabstop=4:shiftwidth=4
#pylint: disable=too-many-branches
def | ():
''' ansible module for gcloud iam service-account keys'''
module = AnsibleModule(
argument_spec=dict(
# credentials
state=dict(default='present', type='str', choices=['present', 'absent', 'list']),
service_account_name=dict(required=True, type='str'),
... | main | identifier_name |
gcloud_iam_sa_keys.py | # pylint: skip-file
# vim: expandtab:tabstop=4:shiftwidth=4
#pylint: disable=too-many-branches
def main():
''' ansible module for gcloud iam service-account keys'''
module = AnsibleModule(
argument_spec=dict(
# credentials
state=dict(default='present', type='str', choices=['pres... | # Get
#####
if state == 'list':
api_rval = gcloud.list_service_account_keys()
if api_rval['returncode'] != 0:
module.fail_json(msg=api_rval, state="list")
module.exit_json(changed=False, results=api_rval['results'], state="list")
########
# Delete
########
... | state = module.params['state']
##### | random_line_split |
gcloud_iam_sa_keys.py | # pylint: skip-file
# vim: expandtab:tabstop=4:shiftwidth=4
#pylint: disable=too-many-branches
def main():
''' ansible module for gcloud iam service-account keys'''
module = AnsibleModule(
argument_spec=dict(
# credentials
state=dict(default='present', type='str', choices=['pres... |
api_rval = gcloud.delete_service_account_key(module.params['key_id'])
if api_rval['returncode'] != 0:
module.fail_json(msg=api_rval)
module.exit_json(changed=True, results=api_rval, state="absent")
if state == 'present':
########
# Create
########
... | module.exit_json(changed=False, msg='Would have performed a delete.') | conditional_block |
timesheet.py | import xml.etree.ElementTree as ET
import datetime
import sys
import openpyxl
import re
import dateutil
def main():
print 'Number of arguments:', len(sys.argv), 'arguments.' #DEBUG
print 'Argument List:', str(sys.argv) #DEBUG
Payrate = raw_input("Enter your pay rate: ") #DEBUG
sNumber = raw_input("Enter 900#: ... | (position, dateList):
match = next(x[0] for x in enumerate(dateList) if x[1] == sheet[position].value)
jobCode = dateList[num+4]
if jobCode == 900:
raise error("Cannot start day with 900 break")
else:
sheet[date] = roundTime(
def roundTime(time):
... | writeTimes | identifier_name |
timesheet.py | import xml.etree.ElementTree as ET
import datetime
import sys
import openpyxl
import re
import dateutil
def main():
print 'Number of arguments:', len(sys.argv), 'arguments.' #DEBUG
print 'Argument List:', str(sys.argv) #DEBUG
Payrate = raw_input("Enter your pay rate: ") #DEBUG
sNumber = raw_input("Enter 900#: ... |
for x in char_range('G','Z'):
writeTimes(x + '17' , dates)
def writeTimes (position, dateList):
match = next(x[0] for x in enumerate(dateList) if x[1] == sheet[position].value)
jobCode = dateList[num+4]
if jobCode == 900:
raise error("Cannot st... | dates.append(x.text) | conditional_block |
timesheet.py | import xml.etree.ElementTree as ET
import datetime
import sys
import openpyxl
import re
import dateutil
def main():
print 'Number of arguments:', len(sys.argv), 'arguments.' #DEBUG
print 'Argument List:', str(sys.argv) #DEBUG
Payrate = raw_input("Enter your pay rate: ") #DEBUG
sNumber = raw_input("Enter 900#: ... |
def char_range(c1, c2):
"""Generates the characters from `c1` to `c2`, inclusive."""
"""Courtesy http://stackoverflow.com/questions/7001144/range-over-character-in-python"""
for c in xrange(ord(c1), ord(c2)+1):
yield chr(c)
main()
| sheet['6k']=num | identifier_body |
timesheet.py | import xml.etree.ElementTree as ET
import datetime
import sys
import openpyxl
import re
import dateutil
def main():
print 'Number of arguments:', len(sys.argv), 'arguments.' #DEBUG
print 'Argument List:', str(sys.argv) #DEBUG
Payrate = raw_input("Enter your pay rate: ") #DEBUG
sNumber = raw_input("Enter 900#: ... | main() | random_line_split | |
storage_thread.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use ipc_channel::ipc::IpcSender;
use servo_url::ServoUrl;
#[derive(Copy, Clone, Deserialize, Serialize, HeapSizeO... | Exit(IpcSender<()>)
} | random_line_split | |
storage_thread.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use ipc_channel::ipc::IpcSender;
use servo_url::ServoUrl;
#[derive(Copy, Clone, Deserialize, Serialize, HeapSizeO... | {
/// gets the number of key/value pairs present in the associated storage data
Length(IpcSender<usize>, ServoUrl, StorageType),
/// gets the name of the key at the specified index in the associated storage data
Key(IpcSender<Option<String>>, ServoUrl, StorageType, u32),
/// Gets the available ke... | StorageThreadMsg | identifier_name |
default.ts | /**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* 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... |
/**
* @deprecated
*/
resizeVideo(): void {
console.warn("`DefaultRenderer.resizeVideo(width, height)` has been deprecated. Use `DefaultRenderer.resize()` instead.");
this.resize();
}
protected _ready(): void {
this.resize();
super._ready();
}
}
| {
// Handle letterboxing around the video. If the width or height are greater than the video can be, then consider that dead space.
const videoWidth = this._video.videoWidth;
const videoHeight = this._video.videoHeight;
const videoOffsetWidth = this._video.offsetWidth;
const videoOffsetHeight = this._video.o... | identifier_body |
default.ts | /**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* 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... | (): void {
// Handle letterboxing around the video. If the width or height are greater than the video can be, then consider that dead space.
const videoWidth = this._video.videoWidth;
const videoHeight = this._video.videoHeight;
const videoOffsetWidth = this._video.offsetWidth;
const videoOffsetHeight = this... | resize | identifier_name |
default.ts | /**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* 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... | this.resize();
}
protected _ready(): void {
this.resize();
super._ready();
}
} | /**
* @deprecated
*/
resizeVideo(): void {
console.warn("`DefaultRenderer.resizeVideo(width, height)` has been deprecated. Use `DefaultRenderer.resize()` instead."); | random_line_split |
services.js | angular.module('DataService', []).factory('DataService',
[ '$q', '$http', '$rootScope', function($q, $http, $rootScope) {
var logout = function() {
var data = $q.defer();
$http.post('logout', {}).success(function() {
data.resolve();
}, function() {
data.resolve();
});
return data.prom... | }).error(function(e) {
deferred.reject(e);
});
return deferred.promise;
},
publishApp : function() {
var deferred = $q.defer();
$http.put('console/publish', {}).success(function(data) {
deferred.resolve(data);
}).error(function(e) {
deferred.reject(e);
});
... | deferred.resolve(data); | random_line_split |
dota2.js | import chai from 'chai';
import nock from 'nock';
import path from 'path';
import dota from '../../src/commands/games/dota2';
import { loadFixtures } from '../_helpers';
chai.should();
const FIXTURES = loadFixtures(path.join(__dirname, '../fixtures/dota2/'));
describe('dota2', () => {
describe('best', () => {
... | nock('http://www.dotabuff.com')
.get('/heroes/impact')
.reply(200, FIXTURES.impact);
dota.dota2({sendMessage}, {channel: 'test'}, 'impact');
});
});
describe('items', () => {
it('it should return the most used items for anti-mage', done => {
function sendMessage(channel, ... | }
nock.cleanAll(); | random_line_split |
dota2.js | import chai from 'chai';
import nock from 'nock';
import path from 'path';
import dota from '../../src/commands/games/dota2';
import { loadFixtures } from '../_helpers';
chai.should();
const FIXTURES = loadFixtures(path.join(__dirname, '../fixtures/dota2/'));
describe('dota2', () => {
describe('best', () => {
... |
nock.cleanAll();
nock('http://www.dotabuff.com')
.get('/heroes/lanes?lane=mid')
.reply(200, FIXTURES.best);
dota.dota2({sendMessage}, {channel: 'test'}, 'best mid');
});
});
describe('build', () => {
it('it should return the most popular build for anti-mage', done => {
... | {
channel.should.equal('test');
res.should.equal(`Okay! Here's the top 10 **statistical** Heroes for **mid**:
*1st*. **Shadow Fiend**
Presence: __90.74%__ | Winrate: __51.22%__ | KDA: __2.7691__ | GPM: __546.8119__ | XPM: __571.5334__
*2nd*. **Templar Assassin**
Presence: __88.29%__ | Winrate: ... | identifier_body |
dota2.js | import chai from 'chai';
import nock from 'nock';
import path from 'path';
import dota from '../../src/commands/games/dota2';
import { loadFixtures } from '../_helpers';
chai.should();
const FIXTURES = loadFixtures(path.join(__dirname, '../fixtures/dota2/'));
describe('dota2', () => {
describe('best', () => {
... | (channel, res) {
channel.should.equal('test');
res.should.equal(`Okay! Here's the top 10 **statistical** Heroes for **mid**:
*1st*. **Shadow Fiend**
Presence: __90.74%__ | Winrate: __51.22%__ | KDA: __2.7691__ | GPM: __546.8119__ | XPM: __571.5334__
*2nd*. **Templar Assassin**
Presence: __88.29... | sendMessage | identifier_name |
test_update_loyalty_program.py | # coding: utf-8
"""
Talon.One API
The Talon.One API is used to manage applications and campaigns, as well as to integrate with your application. The operations in the _Integration API_ section are used to integrate with our platform, while the other operations are used to manage applications and campaigns. #... |
else :
return UpdateLoyaltyProgram(
)
def testUpdateLoyaltyProgram(self):
"""Test UpdateLoyaltyProgram"""
inst_req_only = self.make_instance(include_optional=False)
inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
... | return UpdateLoyaltyProgram(
title = '0',
description = '0',
subscribed_applications = [
56
],
default_validity = '0',
default_pending = '0',
allow_subledger = True
) | conditional_block |
test_update_loyalty_program.py | # coding: utf-8
"""
Talon.One API
The Talon.One API is used to manage applications and campaigns, as well as to integrate with your application. The operations in the _Integration API_ section are used to integrate with our platform, while the other operations are used to manage applications and campaigns. #... |
def make_instance(self, include_optional):
"""Test UpdateLoyaltyProgram
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included """
# model = talon_one.models.update_loyalty_program.Upda... | pass | identifier_body |
test_update_loyalty_program.py | # coding: utf-8
"""
Talon.One API
The Talon.One API is used to manage applications and campaigns, as well as to integrate with your application. The operations in the _Integration API_ section are used to integrate with our platform, while the other operations are used to manage applications and campaigns. #... | (self, include_optional):
"""Test UpdateLoyaltyProgram
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included """
# model = talon_one.models.update_loyalty_program.UpdateLoyaltyProgram() # n... | make_instance | identifier_name |
test_update_loyalty_program.py | # coding: utf-8
"""
Talon.One API
The Talon.One API is used to manage applications and campaigns, as well as to integrate with your application. The operations in the _Integration API_ section are used to integrate with our platform, while the other operations are used to manage applications and campaigns. #... | Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import datetime
import talon_one
from talon_one.models.update_loyalty_program import UpdateLoyaltyProgram # noqa: E501
from talon_one.rest import ApiException
class TestUpdateLoyaltyProgram(unittest.TestCas... |
The version of the OpenAPI document: 1.0.0 | random_line_split |
qt4.py | # Copyright 2015 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to ... | ():
mlog.warning('rcc dependencies will not work properly until this upstream issue is fixed:',
mlog.bold('https://bugreports.qt.io/browse/QTBUG-45460'))
return Qt4Module()
| initialize | identifier_name |
qt4.py | # Copyright 2015 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to ... |
return ModuleReturnValue(sources, sources)
def initialize():
mlog.warning('rcc dependencies will not work properly until this upstream issue is fixed:',
mlog.bold('https://bugreports.qt.io/browse/QTBUG-45460'))
return Qt4Module()
| moc_kwargs = {'output': '@BASENAME@.moc',
'arguments': ['@INPUT@', '-o', '@OUTPUT@']}
moc_gen = build.Generator([self.moc], moc_kwargs)
moc_output = moc_gen.process_files('Qt4 moc source', moc_sources, state)
sources.append(moc_output) | conditional_block |
qt4.py | # Copyright 2015 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to ... | mlog.log(' uic:', mlog.green('YES'), '(%s, %s)' %
(self.uic.get_path(), uic_ver.split()[-1]))
else:
mlog.log(' uic:', mlog.red('NO'))
if self.rcc.found():
stdout, stderr = Popen_safe(self.rcc.get_command() + ['-v'])[1:3]
stdout = stdou... | if 'version 4.' in stderr:
uic_ver = stderr
else:
raise MesonException('Uic compiler is not for Qt4. Output:\n%s\n%s' %
(stdout, stderr)) | random_line_split |
qt4.py | # Copyright 2015 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to ... |
def preprocess(self, state, args, kwargs):
rcc_files = kwargs.pop('qresources', [])
if not isinstance(rcc_files, list):
rcc_files = [rcc_files]
ui_files = kwargs.pop('ui_files', [])
if not isinstance(ui_files, list):
ui_files = [ui_files]
moc_headers... | abspath = os.path.join(state.environment.source_dir, state.subdir, fname)
relative_part = os.path.split(fname)[0]
try:
tree = ET.parse(abspath)
root = tree.getroot()
result = []
for child in root[0]:
if child.tag != 'file':
... | identifier_body |
express.ts | // importing modules the es6 way
import routes from './routes';
import config from '../config';
import * as mongoose from 'mongoose';
import * as path from 'path';
import * as passport from 'passport';
import * as express from 'express';
import * as fs from 'graceful-fs';
import * as chalk from 'chalk';
import * as mo... | ;
export default expressInit;
| {
//aditional app Initializations
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(cookieParser());
// Initialize passport and passport session
app.use(passport.initialize());
//initialize morgan express logger
// NOTE: all nod... | identifier_body |
express.ts | // importing modules the es6 way
import routes from './routes';
import config from '../config';
import * as mongoose from 'mongoose';
import * as path from 'path';
import * as passport from 'passport';
import * as express from 'express';
import * as fs from 'graceful-fs';
import * as chalk from 'chalk';
import * as mo... |
routes(app);
const dist = fs.existsSync('dist');
//exposes the client and node_modules folders to the client for file serving when client queries "/"
app.use('/node_modules', express.static('node_modules'));
app.use('/custom_modules', express.static('custom_modules'));
app.use(express.static(`${ dist ? '... | { %>app.use(session({
secret: config.sessionSecret,
saveUninitialized: true,
resave: false,
store: new MongoStore({
mongooseConnection: mongoose.connection
})
}));<% } %>
//sets the routes for all the API queries | conditional_block |
express.ts | // importing modules the es6 way
import routes from './routes';
import config from '../config';
import * as mongoose from 'mongoose';
import * as path from 'path';
import * as passport from 'passport';
import * as express from 'express';
import * as fs from 'graceful-fs';
import * as chalk from 'chalk';
import * as mo... | (app) {
//aditional app Initializations
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(cookieParser());
// Initialize passport and passport session
app.use(passport.initialize());
//initialize morgan express logger
// NOTE: a... | expressInit | identifier_name |
express.ts | // importing modules the es6 way
import routes from './routes';
import config from '../config';
import * as mongoose from 'mongoose';
import * as path from 'path';
import * as passport from 'passport';
import * as express from 'express';
import * as fs from 'graceful-fs';
import * as chalk from 'chalk';
import * as mo... | let MongoStore = connectMongo(session);<% } %>
// function to initialize the express app
function expressInit(app) {
//aditional app Initializations
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(cookieParser());
// Initialize pass... | random_line_split | |
Seo.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import Helmet from 'react-helmet';
import { useStaticQuery, graphql } from 'gatsby';
export const SEO = ({ description, lang, meta, title }: any) => {
const { site } = useStaticQuery(
graphql`
query {
site {
siteMetadata ... | },
{
name: `twitter:card`,
content: `summary`,
},
{
name: `twitter:creator`,
content: site.siteMetadata.author,
},
{
name: `twitter:title`,
content: title,
},
{
name: `twitter:descriptio... | random_line_split | |
adapted.py | #!/usr/bin/env python
# encoding: utf-8
from django.contrib.auth.decorators import (
permission_required as original_permission_required,
login_required as original_login_required,)
from keyauth.decorators import key_required as original_key_required
from functools import wraps
class DjangoToYardDecorator(obj... | '''
return DjangoToYardDecorator( original_key_required )(*args, **kwargs) | random_line_split | |
adapted.py | #!/usr/bin/env python
# encoding: utf-8
from django.contrib.auth.decorators import (
permission_required as original_permission_required,
login_required as original_login_required,)
from keyauth.decorators import key_required as original_key_required
from functools import wraps
class DjangoToYardDecorator(obj... |
def login_required(*args, **kwargs):
'''
Check if user is authenticated
'''
return DjangoToYardDecorator( original_login_required )(*args, **kwargs)
def permission_required(*args, **kwargs):
'''
Check if user has permissions
'''
return DjangoToYardDecorator(original_permission_r... | def decorator(func):
@wraps(func)
def wrapper(klass, request, *rargs, **rkwargs):
def func_wrapper(request, *a, **k):
return func(klass, request, *rargs, **rkwargs)
original_decorator = self.original_decorator(*args, **kwargs)
r... | identifier_body |
adapted.py | #!/usr/bin/env python
# encoding: utf-8
from django.contrib.auth.decorators import (
permission_required as original_permission_required,
login_required as original_login_required,)
from keyauth.decorators import key_required as original_key_required
from functools import wraps
class DjangoToYardDecorator(obj... | (klass, request, *rargs, **rkwargs):
def func_wrapper(request, *a, **k):
return func(klass, request, *rargs, **rkwargs)
original_decorator = self.original_decorator(*args, **kwargs)
return original_decorator(func_wrapper)(
request, ... | wrapper | identifier_name |
urls.py | # -*- coding: utf-8 -*-
# Copyright (C) 2014 Universidade de Aveiro, DETI/IEETA, Bioinformatics Group - http://bioinformatics.ua.pt/
#
# 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 vers... |
url(r'^api/store/getComments/(?P<fingerprint>[^/]+)$', getCommentsView.as_view()),
url(r'^api/store/putComment/(?P<fingerprint>[^/]+)$', putCommentView.as_view()),
# fast links to dependency latest revision
url(r'^file/(?P<plugin_hash>[^/]+)/(?P<version>[0-9]+)/(?P<filename>[^/]+)$',
Develop... |
url(r'^api/store/getDocuments/(?P<fingerprint>[^/]+)$', getDocumentsView.as_view()),
url(r'^api/store/putDocuments/(?P<fingerprint>[^/]+)$', putDocumentsView.as_view()),
url(r'^api/store/getPublications/(?P<fingerprint>[^/]+)$', getPublicationsView.as_view()), | random_line_split |
evec-internal.rs | // Copyright 2012-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-MI... | () {
let x : [int; 5] = [1,2,3,4,5];
let _y : [int; 5] = [1,2,3,4,5];
let mut z = [1,2,3,4,5];
z = x;
assert_eq!(z[0], 1);
assert_eq!(z[4], 5);
let a : [int; 5] = [1,1,1,1,1];
let b : [int; 5] = [2,2,2,2,2];
let c : [int; 5] = [2,2,2,2,3];
log(debug, a);
assert!(a < b);
... | main | identifier_name |
evec-internal.rs | // Copyright 2012-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-MI... | z = x;
assert_eq!(z[0], 1);
assert_eq!(z[4], 5);
let a : [int; 5] = [1,1,1,1,1];
let b : [int; 5] = [2,2,2,2,2];
let c : [int; 5] = [2,2,2,2,3];
log(debug, a);
assert!(a < b);
assert!(a <= b);
assert!(a != b);
assert!(b >= a);
assert!(b > a);
log(debug, b);
a... | random_line_split | |
evec-internal.rs | // Copyright 2012-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-MI... | {
let x : [int; 5] = [1,2,3,4,5];
let _y : [int; 5] = [1,2,3,4,5];
let mut z = [1,2,3,4,5];
z = x;
assert_eq!(z[0], 1);
assert_eq!(z[4], 5);
let a : [int; 5] = [1,1,1,1,1];
let b : [int; 5] = [2,2,2,2,2];
let c : [int; 5] = [2,2,2,2,3];
log(debug, a);
assert!(a < b);
a... | identifier_body | |
vendor-prefix.js | var style = document.createElement('p').style,
prefixes = 'O ms Moz webkit'.split(' '),
hasPrefix = /^(o|ms|moz|webkit)/,
upper = /([A-Z])/g,
memo = {};
function get(key) {
return (key in memo) ? memo[key] : memo[key] = prefix(key);
}
function prefix(key) {
var capitalizedKey = key.replace(/-([a-z])/g, fu... | (key) {
var prefixedKey = get(key),
upper = /([A-Z])/g;
if (upper.test(prefixedKey)) {
prefixedKey = (hasPrefix.test(prefixedKey) ? '-' : '') + prefixedKey.replace(upper, '-$1');
}
return prefixedKey.toLowerCase();
}
if (typeof module != 'undefined' && module.exports) {
module.exports = get;
modu... | dashedPrefix | identifier_name |
vendor-prefix.js | var style = document.createElement('p').style,
prefixes = 'O ms Moz webkit'.split(' '),
hasPrefix = /^(o|ms|moz|webkit)/,
upper = /([A-Z])/g,
memo = {};
function get(key) |
function prefix(key) {
var capitalizedKey = key.replace(/-([a-z])/g, function (s, match) {
return match.toUpperCase();
}),
i = prefixes.length,
name;
if (style[capitalizedKey] !== undefined) return capitalizedKey;
capitalizedKey = capitalize(key);
while (i--) {
name = prefixes[i] + ca... | {
return (key in memo) ? memo[key] : memo[key] = prefix(key);
} | identifier_body |
vendor-prefix.js | var style = document.createElement('p').style,
prefixes = 'O ms Moz webkit'.split(' '),
hasPrefix = /^(o|ms|moz|webkit)/,
upper = /([A-Z])/g,
memo = {};
function get(key) {
return (key in memo) ? memo[key] : memo[key] = prefix(key);
}
function prefix(key) {
var capitalizedKey = key.replace(/-([a-z])/g, fu... | }
throw new Error('unable to prefix ' + key);
}
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function dashedPrefix(key) {
var prefixedKey = get(key),
upper = /([A-Z])/g;
if (upper.test(prefixedKey)) {
prefixedKey = (hasPrefix.test(prefixedKey) ? '-' : '') + prefi... | name = prefixes[i] + capitalizedKey;
if (style[name] !== undefined) return name; | random_line_split |
buddhist.js | define(
//begin v1.x content
{
"dateFormatItem-yM": "MM/yyyy GGGGG",
"dateFormatItem-yQ": "Q yyyy GGGGG",
"dayPeriods-format-wide-pm": "p.m.",
"eraNames": [
"eB"
],
"dateFormatItem-MMMEd": "E d MMM",
"dateFormatItem-hms": "h:mm:ss a",
"dateFormatItem-yQQQ": "QQQ y G",
"days-standAlone-wide": [
"Diumenge",
... | "g",
"f",
"m",
"a",
"m",
"j",
"j",
"a",
"s",
"o",
"n",
"d"
],
"dayPeriods-format-wide-am": "a.m.",
"quarters-standAlone-abbr": [
"1T",
"2T",
"3T",
"4T"
],
"dateFormatItem-y": "y G",
"timeFormat-full": "H.mm.ss zzzz",
"months-standAlone-abbr": [
"gen.",
"febr.",
"març",
"ab... | "Dissabte"
],
"dateFormatItem-MMM": "LLL",
"months-standAlone-narrow": [ | random_line_split |
helper.rs | // Just functions that may be useful to many modules.
use std::fs::Metadata;
use std::fs::FileType as StdFileType;
use std::os::unix::fs::{MetadataExt, FileTypeExt, PermissionsExt};
use time::Timespec;
use fuse::{FileAttr, FileType};
pub fn | (file_type : StdFileType) -> FileType {
if file_type.is_dir() == true {
FileType::Directory
} else if file_type.is_file() == true {
FileType::RegularFile
} else if file_type.is_symlink() == true {
FileType::Symlink
} else if file_type.is_block_device() == ... | fuse_file_type | identifier_name |
helper.rs | // Just functions that may be useful to many modules.
use std::fs::Metadata;
use std::fs::FileType as StdFileType;
use std::os::unix::fs::{MetadataExt, FileTypeExt, PermissionsExt};
use time::Timespec;
use fuse::{FileAttr, FileType};
pub fn fuse_file_type(file_type : StdFileType) -> FileType {
if file_type.is_dir... |
use std::path::Path;
use fuse::Request;
use libc::EACCES;
use mirrorfs::MirrorFS;
use std::ops::Shl;
// Allows or denies access according to DAC (user/group permissions).
impl MirrorFS {
pub fn u_access(&self, _req: &Request, path: &Path, _mask: u32) -> Result<(), i32> {
let (uid, gid) = self.usermap(_req);
#... | {
FileAttr{
ino : md.ino(),
size : md.size(),
blocks : md.blocks(),
atime : Timespec{ sec : md.atime(), nsec : md.atime_nsec() as i32, },
mtime : Timespec{ sec : md.mtime(), nsec : md.mtime_nsec() as i32, },
ctime : Timespec{ sec : md.ctime(), nsec : md.ctime_nsec() a... | identifier_body |
helper.rs | // Just functions that may be useful to many modules.
use std::fs::Metadata;
use std::fs::FileType as StdFileType;
use std::os::unix::fs::{MetadataExt, FileTypeExt, PermissionsExt};
use time::Timespec;
use fuse::{FileAttr, FileType};
pub fn fuse_file_type(file_type : StdFileType) -> FileType {
if file_type.is_dir... |
},
Err(why) => {
warn!("Could not get metadata to file {} : {:?}", path.display(), why);
return Err(why.raw_os_error().unwrap());
}
}
}
}
| {
if md.permissions().mode() | _mask == md.permissions().mode() {
trace!("Access request {:b} as \"other\" on path {} is ok", _mask, path.display());
return Ok(());
} else {
trace!("Access request as \"other\" isn't ok! Request was {:b}, Permissions were {:b}", _mask, md.permissions().mode(... | conditional_block |
helper.rs | // Just functions that may be useful to many modules.
use std::fs::Metadata;
use std::fs::FileType as StdFileType;
use std::os::unix::fs::{MetadataExt, FileTypeExt, PermissionsExt};
use time::Timespec;
use fuse::{FileAttr, FileType};
pub fn fuse_file_type(file_type : StdFileType) -> FileType {
if file_type.is_dir... | }
}
}
} | },
Err(why) => {
warn!("Could not get metadata to file {} : {:?}", path.display(), why);
return Err(why.raw_os_error().unwrap()); | random_line_split |
apps-add.validator.ts | import { FormControl, FormGroup } from '@angular/forms';
/**
* Validators for Bulk Import Form
* Static methods
*
* @author Damien Vitrac
*/
export class AppsAddValidator {
/**
* Uri regex
*/
static uriRegex = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
/**
* ... |
}
| {
if (!formControl.value) {
return null;
}
let tmp;
try {
formControl.value.toString()
.split('\n')
.map((a) => a.trim())
.filter((a) => a.toString())
.map((a: String) => {
tmp = a.split('=');
if (tmp.length !== 2) {
throw new ... | identifier_body |
apps-add.validator.ts | import { FormControl, FormGroup } from '@angular/forms';
/**
* Validators for Bulk Import Form
* Static methods
*
* @author Damien Vitrac
*/
export class | {
/**
* Uri regex
*/
static uriRegex = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
/**
* Validate the uri conditions
*
* @param {FormControl} formControl
* @returns {any}
*/
static uri(formControl: FormControl): any {
if (!formControl.value) {
... | AppsAddValidator | identifier_name |
apps-add.validator.ts | import { FormControl, FormGroup } from '@angular/forms';
/**
* Validators for Bulk Import Form
* Static methods
*
* @author Damien Vitrac
*/
export class AppsAddValidator {
/**
* Uri regex
*/
static uriRegex = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
/**
* ... |
const val: string = tmp[1];
const startWidth = ['http://', 'https://', 'docker:', 'maven://'];
if (startWidth.filter((b) => val.startsWith(b)).length === 0) {
throw new Error();
}
});
} catch (e) {
return { invalid: true };
}
return null;
... | {
throw new Error();
} | conditional_block |
apps-add.validator.ts | import { FormControl, FormGroup } from '@angular/forms';
/**
* Validators for Bulk Import Form
* Static methods
*
* @author Damien Vitrac
*/
export class AppsAddValidator {
/**
* Uri regex
*/
static uriRegex = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
| /**
* Validate the uri conditions
*
* @param {FormControl} formControl
* @returns {any}
*/
static uri(formControl: FormControl): any {
if (!formControl.value) {
return null;
}
if (!AppsAddValidator.uriRegex.test(formControl.value)) {
return { invalid: true };
}
return ... | random_line_split | |
run_lstm.py | import os
import sys
import numpy as np
sys.path.insert(0, os.getcwd() + '/../../tools/')
import lstm
import wb
import wer
def rescore_all(workdir, nbestdir, config):
for tsk in ['nbestlist_{}_{}'.format(a, b) for a in ['dt05', 'et05'] for b in ['real', 'simu']]:
print('process ' + tsk)
nbest_txt... | if '-test' in sys.argv:
lstm.ppl(workdir, train, config)
lstm.ppl(workdir, valid, config)
if '-rescore' in sys.argv:
rescore_all(workdir, nbestdir, config)
if '-wer' in sys.argv:
lmpaths = {'KN5': nbestdir + '<tsk>/lmwt.lmonly',
'RNN': nbestdir + '<tsk>/lmw... | random_line_split | |
run_lstm.py | import os
import sys
import numpy as np
sys.path.insert(0, os.getcwd() + '/../../tools/')
import lstm
import wb
import wer
def rescore_all(workdir, nbestdir, config):
|
if __name__ == '__main__':
print(sys.argv)
if len(sys.argv) == 1:
print(
' \"python run.py -train\" train LSTM\n \"python run.py -rescore\" rescore nbest\n \"python run.py -wer\" compute WER')
absdir = os.getcwd() + '/'
train = absdir + 'data/train'
valid = absdir + 'data/valid'
... | for tsk in ['nbestlist_{}_{}'.format(a, b) for a in ['dt05', 'et05'] for b in ['real', 'simu']]:
print('process ' + tsk)
nbest_txt = nbestdir + tsk + '/words_text'
outdir = workdir + nbestdir.split('/')[-2] + '/' + tsk + '/'
wb.mkdir(outdir)
write_lmscore = outdir + 'lmwt.lstm'
... | identifier_body |
run_lstm.py | import os
import sys
import numpy as np
sys.path.insert(0, os.getcwd() + '/../../tools/')
import lstm
import wb
import wer
def rescore_all(workdir, nbestdir, config):
for tsk in ['nbestlist_{}_{}'.format(a, b) for a in ['dt05', 'et05'] for b in ['real', 'simu']]:
print('process ' + tsk)
nbest_txt... | lmpaths = {'KN5': nbestdir + '<tsk>/lmwt.lmonly',
'RNN': nbestdir + '<tsk>/lmwt.rnn',
'LSTM': workdir + nbestdir.split('/')[-2] + '/<tsk>/lmwt.lstm',
'TRF': '/home/ozj/NAS_workspace/wangb/Experiments/ChiME4/lmscore/' + nbestdir.split('/')[
... | conditional_block | |
run_lstm.py | import os
import sys
import numpy as np
sys.path.insert(0, os.getcwd() + '/../../tools/')
import lstm
import wb
import wer
def | (workdir, nbestdir, config):
for tsk in ['nbestlist_{}_{}'.format(a, b) for a in ['dt05', 'et05'] for b in ['real', 'simu']]:
print('process ' + tsk)
nbest_txt = nbestdir + tsk + '/words_text'
outdir = workdir + nbestdir.split('/')[-2] + '/' + tsk + '/'
wb.mkdir(outdir)
writ... | rescore_all | identifier_name |
solution.rs | use std::io;
macro_rules! read_n {
( $name : ident, $typ : ty ) => {
let mut line : String = String::new();
io::stdin().read_line(&mut line);
let $name : $typ = line.trim().parse::<$typ>().expect("invalid data type");
};
}
fn main() {
read_n!(x, u32);
read_n!(n, u32);
let... |
if powers.len() == 0 || sum > x {
return;
}
for i in start..powers.len() {
permut(x, sum + powers[i], &mut powers, i + 1, &mut no_of_ways);
}
}
| {
*no_of_ways += 1;
return;
} | conditional_block |
solution.rs | use std::io;
macro_rules! read_n {
( $name : ident, $typ : ty ) => {
let mut line : String = String::new();
io::stdin().read_line(&mut line);
let $name : $typ = line.trim().parse::<$typ>().expect("invalid data type");
};
}
fn main() {
read_n!(x, u32);
read_n!(n, u32);
let... | {
if sum == x {
*no_of_ways += 1;
return;
}
if powers.len() == 0 || sum > x {
return;
}
for i in start..powers.len() {
permut(x, sum + powers[i], &mut powers, i + 1, &mut no_of_ways);
}
} | identifier_body | |
solution.rs | use std::io;
macro_rules! read_n {
( $name : ident, $typ : ty ) => {
let mut line : String = String::new();
io::stdin().read_line(&mut line);
let $name : $typ = line.trim().parse::<$typ>().expect("invalid data type");
};
}
fn | () {
read_n!(x, u32);
read_n!(n, u32);
let mut powers : Vec<u32> = (1..32).map(|x: u32| x.pow(n)).collect();
let mut no_of_ways: u32 = 0;
permut(x, 0, &mut powers, 0, &mut no_of_ways);
println!("{}", no_of_ways);
}
fn permut(x: u32, sum: u32, mut powers: &mut Vec<u32>, start: usize, mut no_... | main | identifier_name |
solution.rs | use std::io;
macro_rules! read_n {
( $name : ident, $typ : ty ) => {
let mut line : String = String::new();
io::stdin().read_line(&mut line);
let $name : $typ = line.trim().parse::<$typ>().expect("invalid data type");
};
}
fn main() {
read_n!(x, u32);
read_n!(n, u32);
let... | fn permut(x: u32, sum: u32, mut powers: &mut Vec<u32>, start: usize, mut no_of_ways: &mut u32) {
if sum == x {
*no_of_ways += 1;
return;
}
if powers.len() == 0 || sum > x {
return;
}
for i in start..powers.len() {
permut(x, sum + powers[i], &mut powers, i + 1, &mut... | }
| random_line_split |
intersection.ts | import { cubicRoots } from "./polyRoots";
/**
* Returns the intersection point for the given pair of line segments, or null,
* if the segments are parallel or don't intersect.
* Based on http://paulbourke.net/geometry/pointlineplane/
*/
export function segmentIntersection(ax1: number, ay1: number, ax2: number, ay2... | px3: number, py3: number, px4: number, py4: number,
x1: number, y1: number, x2: number, y2: number): { x: number, y: number }[] {
const intersections: { x: number, y: number }[] = [];
// Find line equation coefficients.
const A = y1 - y2;
const B = x2 - x1;
const C = x1 * (y2 - y1) - y1 * ... | export function cubicSegmentIntersections(
px1: number, py1: number, px2: number, py2: number, | random_line_split |
intersection.ts | import { cubicRoots } from "./polyRoots";
/**
* Returns the intersection point for the given pair of line segments, or null,
* if the segments are parallel or don't intersect.
* Based on http://paulbourke.net/geometry/pointlineplane/
*/
export function segmentIntersection(ax1: number, ay1: number, ax2: number, ay2... |
/**
* Returns the given coordinates vector multiplied by the coefficient matrix
* of the parametric cubic Bézier equation.
*/
export function bezierCoefficients(P1: number, P2: number, P3: number, P4: number) {
return [ // Bézier expressed as matrix operations:
-P1 + 3 * P2 - 3 ... | {
const intersections: { x: number, y: number }[] = [];
// Find line equation coefficients.
const A = y1 - y2;
const B = x2 - x1;
const C = x1 * (y2 - y1) - y1 * (x2 - x1);
// Find cubic Bezier curve equation coefficients from control points.
const bx = bezierCoefficients(px1, px2, px3, p... | identifier_body |
intersection.ts | import { cubicRoots } from "./polyRoots";
/**
* Returns the intersection point for the given pair of line segments, or null,
* if the segments are parallel or don't intersect.
* Based on http://paulbourke.net/geometry/pointlineplane/
*/
export function segmentIntersection(ax1: number, ay1: number, ax2: number, ay2... |
if (s >= 0 && s <= 1) {
intersections.push({x, y});
}
}
return intersections;
}
/**
* Returns the given coordinates vector multiplied by the coefficient matrix
* of the parametric cubic Bézier equation.
*/
export function bezierCoefficients(P1: number, P2: number, P3: number, P4... | { // the line is vertical
s = (y - y1) / (y2 - y1);
} | conditional_block |
intersection.ts | import { cubicRoots } from "./polyRoots";
/**
* Returns the intersection point for the given pair of line segments, or null,
* if the segments are parallel or don't intersect.
* Based on http://paulbourke.net/geometry/pointlineplane/
*/
export function segmentIntersection(ax1: number, ay1: number, ax2: number, ay2... | P1: number, P2: number, P3: number, P4: number) {
return [ // Bézier expressed as matrix operations:
-P1 + 3 * P2 - 3 * P3 + P4, // |-1 3 -3 1| |P1|
3 * P1 - 6 * P2 + 3 * P3, // [t^3 t^2 t 1] | 3 -6 3 0| |P2|
-3 * P1 + 3 * P2, // ... | ezierCoefficients( | identifier_name |
SpeedyshareCom.py | # -*- coding: utf-8 -*-
#
# Test links:
# http://speedy.sh/ep2qY/Zapp-Brannigan.jpg
import re
import urlparse
from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo
class SpeedyshareCom(SimpleHoster):
__name__ = "SpeedyshareCom"
__type__ = "hoster"
__version__ = "0.06"
_... | __pattern__ = r'https?://(?:www\.)?(speedyshare\.com|speedy\.sh)/\w+'
__config__ = [("use_premium", "bool", "Use premium account if available", True)]
__description__ = """Speedyshare.com hoster plugin"""
__license__ = "GPLv3"
__authors__ = [("zapp-brannigan", "fuerst.reinje@web.de")]
... | random_line_split | |
SpeedyshareCom.py | # -*- coding: utf-8 -*-
#
# Test links:
# http://speedy.sh/ep2qY/Zapp-Brannigan.jpg
import re
import urlparse
from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo
class SpeedyshareCom(SimpleHoster):
|
getInfo = create_getInfo(SpeedyshareCom)
| __name__ = "SpeedyshareCom"
__type__ = "hoster"
__version__ = "0.06"
__status__ = "testing"
__pattern__ = r'https?://(?:www\.)?(speedyshare\.com|speedy\.sh)/\w+'
__config__ = [("use_premium", "bool", "Use premium account if available", True)]
__description__ = """Speedyshare.com hoster... | identifier_body |
SpeedyshareCom.py | # -*- coding: utf-8 -*-
#
# Test links:
# http://speedy.sh/ep2qY/Zapp-Brannigan.jpg
import re
import urlparse
from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo
class | (SimpleHoster):
__name__ = "SpeedyshareCom"
__type__ = "hoster"
__version__ = "0.06"
__status__ = "testing"
__pattern__ = r'https?://(?:www\.)?(speedyshare\.com|speedy\.sh)/\w+'
__config__ = [("use_premium", "bool", "Use premium account if available", True)]
__description__ = """Sp... | SpeedyshareCom | identifier_name |
SpeedyshareCom.py | # -*- coding: utf-8 -*-
#
# Test links:
# http://speedy.sh/ep2qY/Zapp-Brannigan.jpg
import re
import urlparse
from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo
class SpeedyshareCom(SimpleHoster):
__name__ = "SpeedyshareCom"
__type__ = "hoster"
__version__ = "0.06"
_... |
getInfo = create_getInfo(SpeedyshareCom)
| self.link = m.group(1) | conditional_block |
main.py | #!/usr/bin/env python
import os.path
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init... | (tornado.web.RequestHandler):
def get(self):
self.render(
"index.html",
page_title = "Burt's Books | Home",
header_text = "Welcome to Burt's Books!",
footer_text = "For more information, please email us at <a href=\"mailto:contact@burtsbooks.com\">contact@burtsbooks.com</a>.",
)
def main():
tornado... | MainHandler | identifier_name |
main.py | #!/usr/bin/env python
import os.path
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init... | main() | conditional_block | |
main.py | #!/usr/bin/env python
import os.path
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init... |
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
| def get(self):
self.render(
"index.html",
page_title = "Burt's Books | Home",
header_text = "Welcome to Burt's Books!",
footer_text = "For more information, please email us at <a href=\"mailto:contact@burtsbooks.com\">contact@burtsbooks.com</a>.",
) | identifier_body |
main.py | #!/usr/bin/env python
import os.path
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init... | template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
debug=True,
autoescape=None
)
tornado.web.Application.__init__(self, handlers, **settings)
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render(
... | random_line_split | |
use-from-trait-xc.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:use_fr... | // | random_line_split |
use-from-trait-xc.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 ... | () {}
| main | identifier_name |
use-from-trait-xc.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 ... | {} | identifier_body | |
helpers.py | # coding=utf-8
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: https://sickrage.github.io
#
# This file is part of SickRage.
#
# SickRage 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 L... |
# if they provided a fanart number try to use it instead
if imgNum is not None:
tempURL = url.split('-')[0] + "-" + str(imgNum) + ".jpg"
else:
tempURL = url
logger.log("Fetching image from " + tempURL, logger.DEBUG)
image_data = helpers.getURL(tempURL, session=meta_session, retur... | return None | conditional_block |
helpers.py | # coding=utf-8
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: https://sickrage.github.io
#
# This file is part of SickRage.
#
# SickRage 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 L... | if url is None:
return None
# if they provided a fanart number try to use it instead
if imgNum is not None:
tempURL = url.split('-')[0] + "-" + str(imgNum) + ".jpg"
else:
tempURL = url
logger.log("Fetching image from " + tempURL, logger.DEBUG)
image_data = helpers.getURL(t... | identifier_body | |
helpers.py | # coding=utf-8
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: https://sickrage.github.io
#
# This file is part of SickRage.
#
# SickRage 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 L... | (url, imgNum=None):
if url is None:
return None
# if they provided a fanart number try to use it instead
if imgNum is not None:
tempURL = url.split('-')[0] + "-" + str(imgNum) + ".jpg"
else:
tempURL = url
logger.log("Fetching image from " + tempURL, logger.DEBUG)
image... | getShowImage | identifier_name |
helpers.py | # coding=utf-8
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: https://sickrage.github.io
#
# This file is part of SickRage.
#
# SickRage 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 L... | tempURL = url
logger.log("Fetching image from " + tempURL, logger.DEBUG)
image_data = helpers.getURL(tempURL, session=meta_session, returns='content')
if image_data is None:
logger.log("There was an error trying to retrieve the image, aborting", logger.WARNING)
return
return i... | else: | random_line_split |
app.constants.ts | export const _appRoles: any = {
"_MEMBER": {
title: 'Members'
},
"_ADMIN": {
title: 'Admin'
},
"_SUPERADMIN": {
title: 'Super admin'
}
}
export const _appErrorCodes: any = {
"500": {
title: "Internal server error",
message: "Some internal server error... | typeId: 2,
name: "Hostel",
attributes: [{
attributeId: 9
}]
},
{
typeId: 3,
name: "Rental flat",
attributes: [{
attributeId: 9
}]
}
] | },
{ | random_line_split |
f32.rs | // Copyright 2012-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-MI... | else {
unsafe { intrinsics::copysignf32(1.0, self) }
}
}
/// Returns `true` if `self` is positive, including `+0.0` and
/// `Float::infinity()`.
#[inline]
fn is_positive(self) -> bool {
self > 0.0 || (1.0 / self) == Float::infinity()
}
/// Returns `true` if `se... | {
Float::nan()
} | conditional_block |
f32.rs | // Copyright 2012-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-MI... | pub const DIGITS: u32 = 6;
#[stable(feature = "rust1", since = "1.0.0")]
pub const EPSILON: f32 = 1.19209290e-07_f32;
/// Smallest finite f32 value
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN: f32 = -3.40282347e+38_f32;
/// Smallest positive, normalized f32 value
#[stable(feature = "rust1", since = "1... | random_line_split | |
f32.rs | // Copyright 2012-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-MI... | (self) -> f32 {
unsafe { intrinsics::ceilf32(self) }
}
/// Rounds to nearest integer. Rounds half-way cases away from zero.
#[inline]
fn round(self) -> f32 {
unsafe { intrinsics::roundf32(self) }
}
/// Returns the integer part of the number (rounds towards zero).
#[inline]
... | ceil | identifier_name |
f32.rs | // Copyright 2012-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-MI... |
/// Returns `true` if `self` is negative, including `-0.0` and
/// `Float::neg_infinity()`.
#[inline]
fn is_negative(self) -> bool {
self < 0.0 || (1.0 / self) == Float::neg_infinity()
}
/// Fused multiply-add. Computes `(self * a) + b` with only one rounding
/// error. This produ... | {
self > 0.0 || (1.0 / self) == Float::infinity()
} | identifier_body |
app.js | //Requires
var lirc = require("./modules/lirc.js");
var sonybravia = require("./modules/sonybravia.js");
var exec = require('child_process').exec;
var alarms = require("./modules/alarms.js").initialize();
var express = require('express');
var app = express();
var fs = require('fs');
var moment = require('moment');
var ... |
if (/^\/trigger\/[a-z0-9]+\/[a-z0-9]+$/.test(req.url)) {
return next();
}
if (!user || !user.name || !user.pass) {
return unauthorized(res);
};
if (user.name === 'rob' && user.pass === 'SuperGeheim123qweASD') {
return next();
} else {
return unauthorized(res);... | {
return next();
} | conditional_block |
app.js | //Requires
var lirc = require("./modules/lirc.js");
var sonybravia = require("./modules/sonybravia.js");
var exec = require('child_process').exec;
var alarms = require("./modules/alarms.js").initialize();
var express = require('express');
var app = express();
var fs = require('fs');
var moment = require('moment');
var ... |
process.on('uncaughtException', function(err) {
if(err.errno === 'EADDRINUSE') {
console.log('Listening address on port ' + WEBSERVER_PORT + ' is in use or unavailable.');
process.exit(1);
} else {
throw err;
}
});
| {
if (res.outcomes == undefined || res.outcomes.length == 0) {
//textToSpeech('Lol. Sorry. I did not understand a word of that.');
textToSpeech(responses.notUnderstood[Math.floor(Math.random() * responses.notUnderstood.length)]);
console.log('No outcomes.');
return;
}
_.each... | identifier_body |
app.js | //Requires
var lirc = require("./modules/lirc.js");
var sonybravia = require("./modules/sonybravia.js");
var exec = require('child_process').exec;
var alarms = require("./modules/alarms.js").initialize();
var express = require('express');
var app = express();
var fs = require('fs');
var moment = require('moment');
var ... | stopListening();
}, 5000);
}, 1900);
}
console.log(voicecommands.commands);
function parseSpeech(res) {
if (res.outcomes == undefined || res.outcomes.length == 0) {
//textToSpeech('Lol. Sorry. I did not understand a word of that.');
textToSpeech(responses.notUnderstood[Math.... | console.log(exception);
}
}));
setTimeout(function () { | random_line_split |
app.js | //Requires
var lirc = require("./modules/lirc.js");
var sonybravia = require("./modules/sonybravia.js");
var exec = require('child_process').exec;
var alarms = require("./modules/alarms.js").initialize();
var express = require('express');
var app = express();
var fs = require('fs');
var moment = require('moment');
var ... | () {
if (isRecording == false) {
return;
}
console.log('Stop recording');
lpcm16.stop();
isRecording = false;
sonybravia.setVolume(tv_volume);
}
function listenToSpeech(res) {
if (isRecording == true) {
return;
}
console.log('Recording...');
isRecording = true;
... | stopListening | identifier_name |
runningjobswidget.js | function fetchData{{ id }}() {
function | (series) {
data = [series];
$.plot("#{{ id }}", data, {
series: {
shadowSize: 0,
},
bars: {
show: true,
barWidth: series.barWidth,
align: "center"
},
xaxis: {
tickDecimals: 0,
mode: "time",
timezone... | onDataReceived | identifier_name |
runningjobswidget.js | function fetchData{{ id }}() {
function onDataReceived(series) | ;
$.ajax({
url: '{% url id %}',
type: "GET",
dataType: "json",
success: onDataReceived,
});
};
{% include 'pages/refreshbutton.js' %}
$('#{{ id }}remove').click(function(){
var url = "{% url 'usersprofiledash' 'off' id %}";
$.ajax({
url: url,
type: "GET",
})... | {
data = [series];
$.plot("#{{ id }}", data, {
series: {
shadowSize: 0,
},
bars: {
show: true,
barWidth: series.barWidth,
align: "center"
},
xaxis: {
tickDecimals: 0,
mode: "time",
timezone: "browse... | identifier_body |
runningjobswidget.js | function fetchData{{ id }}() {
function onDataReceived(series) {
data = [series];
$.plot("#{{ id }}", data, {
series: {
shadowSize: 0,
},
bars: {
show: true,
barWidth: series.barWidth,
align: "center"
},
xaxis: {
t... | $("#{{ id }}loading").hide();
};
$.ajax({
url: '{% url id %}',
type: "GET",
dataType: "json",
success: onDataReceived,
});
};
{% include 'pages/refreshbutton.js' %}
$('#{{ id }}remove').click(function(){
var url = "{% url 'usersprofiledash' 'off' id %}";
$.ajax({
... | random_line_split | |
extent.py | # -*- coding: utf-8 -*-
"""The Virtual File System (VFS) extent."""
class Extent(object):
"""Extent.
Attributes:
extent_type (str): type of the extent, for example EXTENT_TYPE_SPARSE.
offset (int): offset of the extent relative from the start of the file
system in bytes.
size (int): size of t... | self.size = size | """
super(Extent, self).__init__()
self.extent_type = extent_type
self.offset = offset | random_line_split |
extent.py | # -*- coding: utf-8 -*-
"""The Virtual File System (VFS) extent."""
class Extent(object):
| """Extent.
Attributes:
extent_type (str): type of the extent, for example EXTENT_TYPE_SPARSE.
offset (int): offset of the extent relative from the start of the file
system in bytes.
size (int): size of the extent in bytes.
"""
def __init__(self, extent_type=None, offset=None, size=None):
... | identifier_body | |
extent.py | # -*- coding: utf-8 -*-
"""The Virtual File System (VFS) extent."""
class Extent(object):
"""Extent.
Attributes:
extent_type (str): type of the extent, for example EXTENT_TYPE_SPARSE.
offset (int): offset of the extent relative from the start of the file
system in bytes.
size (int): size of t... | (self, extent_type=None, offset=None, size=None):
"""Initializes an extent.
Args:
extent_type (Optional[str]): type of the extent, for example
EXTENT_TYPE_SPARSE.
offset (Optional[int]): offset of the extent relative from the start of
the file system in bytes.
size (Option... | __init__ | identifier_name |
controllers-endpoint.test.ts | import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import { App } from '../../lib/app';
import { TemplateApp } from '../mock/template-app';
chai.config.truncateThreshold = 500;
chai.use(chaiAsPromised);
chai.should();
describe('[Controller Endpoints]', () => {
let app: App;
let testO... | return tpl.get('/api/tests').should.become({
count: 3,
pagination: {
limit: 30,
offset: 0,
page: 1
},
data: [
{ id_test: 1 },
{ id_test: 4 },
{ id_test: 42 }
]
});
});
it('should run endpoint for model action "testParam" that returns params', ()... | });
it('should run endpoint for default "list"', () => { | random_line_split |
format_currency.js | import {expect} from 'chai';
import formatCurrency from '../../../frontend/src/lib/format_currency';
describe('formatCurrency', () => {
it('should return $12.34', () => {
expect(formatCurrency(12.34)).to.equal('$12.34');
});
it('should return $12,345.67', () => {
expect(formatCurrency(12345.67)).to.equ... | });
it('should return -€12.34', () => {
expect(formatCurrency(-12.34,'EUR')).to.equal('-€12,34');
});
it('should return MXN$10', () => {
expect(formatCurrency(10,'MXN',{precision: 0, compact: false})).to.equal('MXN $10');
})
}); | random_line_split | |
graph-data.service.ts | // Copyright 2018 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ap... |
// Returns an object which can be treated as the input to a visualization
// for a directed graph. The returned object has the following keys:
// - nodes: an object whose keys are node ids (equal to node names) and
// whose values are node names
// - links: a list of objects. Each object ... | 'ExplorationStatesService',
function(
ComputeGraphService, ExplorationInitStateNameService,
ExplorationStatesService) {
var _graphData = null; | random_line_split |
graph-data.service.ts | // Copyright 2018 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by ap... |
var states = ExplorationStatesService.getStates();
var initStateId = ExplorationInitStateNameService.savedMemento;
_graphData = ComputeGraphService.compute(initStateId, states);
};
return {
recompute: function() {
_recomputeGraphData();
},
getGraphData: function() ... | {
return;
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.