file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
changevalidator_test.py | import unittest
from biicode.common.edition.hive import Hive
from biicode.common.model.blob import Blob
from biicode.common.exception import BiiException
from biicode.common.edition import changevalidator
from biicode.common.edition.processors.processor_changes import ProcessorChanges
from biicode.common.conf import BI... | (self):
self.load = Blob()
def test_large_cell_reject(self):
self.load.binary = bytearray(BII_FILE_SIZE_LIMIT)
files = {"user/block/file": (None, self.load)}
biiout = OutputStream()
changevalidator.remove_large_cells(files, biiout)
self.assertEquals(0, len(files))
... | setUp | identifier_name |
changevalidator_test.py | import unittest
from biicode.common.edition.hive import Hive
from biicode.common.model.blob import Blob
from biicode.common.exception import BiiException
from biicode.common.edition import changevalidator
from biicode.common.edition.processors.processor_changes import ProcessorChanges
from biicode.common.conf import BI... | str(biiout))
def test_size_reject_accept(self):
self.load.binary = bytearray(BII_FILE_SIZE_LIMIT)
load2 = Blob()
load2.binary = bytearray(BII_FILE_SIZE_LIMIT - 1)
files = {"user/block/filelarge": (None, self.load),
"user/block/filesmall": ... | changevalidator.remove_large_cells(files, biiout)
self.assertEquals(0, len(files))
self.assertEquals("WARN: File user/block/file is bigger "
"than %s: discarded\n" % BII_FILE_SIZE_LIMIT_STR, | random_line_split |
changevalidator_test.py | import unittest
from biicode.common.edition.hive import Hive
from biicode.common.model.blob import Blob
from biicode.common.exception import BiiException
from biicode.common.edition import changevalidator
from biicode.common.edition.processors.processor_changes import ProcessorChanges
from biicode.common.conf import BI... |
def test_size_reject_accept(self):
self.load.binary = bytearray(BII_FILE_SIZE_LIMIT)
load2 = Blob()
load2.binary = bytearray(BII_FILE_SIZE_LIMIT - 1)
files = {"user/block/filelarge": (None, self.load),
"user/block/filesmall": (None, load2)}
biiout = Outpu... | self.load.binary = bytearray(BII_FILE_SIZE_LIMIT)
files = {"user/block/file": (None, self.load)}
biiout = OutputStream()
changevalidator.remove_large_cells(files, biiout)
self.assertEquals(0, len(files))
self.assertEquals("WARN: File user/block/file is bigger "
... | identifier_body |
changevalidator_test.py | import unittest
from biicode.common.edition.hive import Hive
from biicode.common.model.blob import Blob
from biicode.common.exception import BiiException
from biicode.common.edition import changevalidator
from biicode.common.edition.processors.processor_changes import ProcessorChanges
from biicode.common.conf import BI... |
hive.update(changes)
changevalidator.check_hive_num_cells(hive)
| name = "user/block/file%d" % i
changes.upsert(name, Content(id_=name, load=Blob())) | conditional_block |
tokenizer.rs | use std::collections::HashSet;
#[derive(PartialEq)]
enum CharTypes {
IsNumeric,
IsAlphabetic,
IsSpace,
IsOther,
}
#[derive(Debug, PartialEq, Clone)]
pub enum TokenType {
IsVariable,
IsNumeric,
IsFunction,
IsOperation,
}
#[derive(Debug, Clone)]
pub struct Token {
pub param: String,... | }
// add last token to stack
if last_type != CharTypes::IsSpace {
let tmp = strcpy(buffer, last_pos, curr_pos);
let token_type = identify(tmp);
stack.push(Token::new(tmp, token_type));
}
stack
} | last_pos = curr_pos;
last_type = curr_type;
}
curr_pos += 1; | random_line_split |
tokenizer.rs | use std::collections::HashSet;
#[derive(PartialEq)]
enum CharTypes {
IsNumeric,
IsAlphabetic,
IsSpace,
IsOther,
}
#[derive(Debug, PartialEq, Clone)]
pub enum TokenType {
IsVariable,
IsNumeric,
IsFunction,
IsOperation,
}
#[derive(Debug, Clone)]
pub struct Token {
pub param: String,... | <'a>(buffer: &'a str) -> Vec<Token> {
// unsafe copy function
fn strcpy<'a>(buffer: &'a str, start: usize, stop: usize) -> &'a str {
unsafe { buffer.slice_unchecked(start, stop) }
}
let mut stack: Vec<Token> = Vec::new();
let mut last_pos: usize = 0;
let mut curr_pos: usize = 0;
let ... | tokenize | identifier_name |
tokenizer.rs | use std::collections::HashSet;
#[derive(PartialEq)]
enum CharTypes {
IsNumeric,
IsAlphabetic,
IsSpace,
IsOther,
}
#[derive(Debug, PartialEq, Clone)]
pub enum TokenType {
IsVariable,
IsNumeric,
IsFunction,
IsOperation,
}
#[derive(Debug, Clone)]
pub struct Token {
pub param: String,... |
}
trait SpecTypes {
fn get_type(&self) -> CharTypes;
}
impl SpecTypes for char {
// get character type
fn get_type(&self) -> CharTypes {
if self.is_numeric() || *self == '.' {
CharTypes::IsNumeric
} else if self.is_alphabetic() {
CharTypes::IsAlphabetic
} e... | {
Token {
param: buffer.into(),
id: id,
}
} | identifier_body |
tokenizer.rs | use std::collections::HashSet;
#[derive(PartialEq)]
enum CharTypes {
IsNumeric,
IsAlphabetic,
IsSpace,
IsOther,
}
#[derive(Debug, PartialEq, Clone)]
pub enum TokenType {
IsVariable,
IsNumeric,
IsFunction,
IsOperation,
}
#[derive(Debug, Clone)]
pub struct Token {
pub param: String,... |
}
}
fn identify(item: &str) -> TokenType {
// available functions
let funcs: HashSet<&'static str> = seq!["exit", "print", "read", "stack"];
// get first character from string
let chr = item.chars().nth(0).unwrap();
// check character type
if chr.is_numeric() {
TokenType::IsNumeric... | {
CharTypes::IsOther
} | conditional_block |
user.js | import { put, takeLatest, call, select } from 'redux-saga/effects';
import { push } from 'react-router-redux';
import { LOGIN, RESOLVE_APP_STAGE, GET_PROFILE, SIGN_OUT } from '../../constants/user';
import { ROUTES } from '../../constants/routes';
import { setUser, destroyUser, setProfile } from '../../actions/user';
i... |
}
export function* getUser() {
let user = yield select((state) => state.get('user'));
if (!user.toJS().profile) {
const profile = yield getUserProfile();
if (profile) {
yield put(setProfile(convertProfileResponse(profile)));
const stateUser = yield select((state) => state.get('user'));
... | {
yield put(setProfile(convertProfileResponse(profile)));
} | conditional_block |
user.js | import { put, takeLatest, call, select } from 'redux-saga/effects';
import { push } from 'react-router-redux';
import { LOGIN, RESOLVE_APP_STAGE, GET_PROFILE, SIGN_OUT } from '../../constants/user';
import { ROUTES } from '../../constants/routes';
import { setUser, destroyUser, setProfile } from '../../actions/user';
i... | }
}
export function* loginUserSaga({ payload: { user } }) {
const { token } = user;
setAuthToken(token);
yield put(setUser(user));
}
export function* signOutSaga() {
removeAuthToken();
yield put(destroyUser());
yield put(push(ROUTES.USER.LOGIN));
}
export function* getUserProfile() {
const response =... | } else {
yield put(push(ROUTES.APP.HOME));
} | random_line_split |
MockObjects.js | /* 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/. */
/**
* Allows registering a mock XPCOM component, that temporarily replaces the
* original one when an object im... | createInstance: function MF_createInstance(aOuter, aIid) {
if (aOuter != null)
throw SpecialPowers.Cr.NS_ERROR_NO_AGGREGATION;
return new providedConstructor().QueryInterface(aIid);
}
};
var retVal = SpecialPowers.swapFactoryRegistration(this._cid, this._contractID, this._... | throw new Exception("Invalid object state when calling register()");
// Define a factory that creates a new object using the given constructor.
var providedConstructor = this._replacementCtor;
this._mockFactory = { | random_line_split |
MockObjects.js | /* 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/. */
/**
* Allows registering a mock XPCOM component, that temporarily replaces the
* original one when an object im... |
MockObjectRegisterer.prototype = {
/**
* Replaces the current factory with one that returns a new mock object.
*
* After register() has been called, it is mandatory to call unregister() to
* restore the original component. Usually, you should use a try-catch block
* to ensure that unregister() is cal... | {
this._contractID = aContractID;
this._replacementCtor = aReplacementCtor;
} | identifier_body |
MockObjects.js | /* 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/. */
/**
* Allows registering a mock XPCOM component, that temporarily replaces the
* original one when an object im... |
},
/**
* Restores the original factory.
*/
unregister: function MOR_unregister() {
if (!this._originalFactory)
throw new Exception("Invalid object state when calling unregister()");
// Free references to the mock factory.
SpecialPowers.swapFactoryRegistration(this._cid, this._contractID... | {
this._cid = retVal.cid;
this._originalFactory = retVal.originalFactory;
} | conditional_block |
MockObjects.js | /* 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/. */
/**
* Allows registering a mock XPCOM component, that temporarily replaces the
* original one when an object im... | (aContractID, aReplacementCtor) {
this._contractID = aContractID;
this._replacementCtor = aReplacementCtor;
}
MockObjectRegisterer.prototype = {
/**
* Replaces the current factory with one that returns a new mock object.
*
* After register() has been called, it is mandatory to call unregister() to
* ... | MockObjectRegisterer | identifier_name |
TemplateAssetsDialog.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... |
def onDelete(self,evt):
try:
self.deleteObject('No template asset','Delete template asset',self.dbProxy.deleteTemplateAsset)
except ARMException,errorText:
dlg = wx.MessageDialog(self,str(errorText),'Delete template asset',wx.OK | wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy
| selectedObjt = self.objts[self.selectedLabel]
assetId = selectedObjt.id()
try:
updateParameters = DialogClassParameters(TEMPLATEASSET_ID,'Edit template asset',TemplateAssetDialog,TEMPLATEASSET_BUTTONCOMMIT_ID,self.dbProxy.updateTemplateAsset,False)
self.updateObject(selectedObjt,updateParameters)
... | identifier_body |
TemplateAssetsDialog.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... | listCtrl = self.FindWindowById(TEMPLATEASSETS_ASSETLIST_ID)
listCtrl.SetColumnWidth(0,150)
listCtrl.SetColumnWidth(1,150)
def addObjectRow(self,assetListCtrl,listRow,asset):
assetListCtrl.InsertStringItem(listRow,asset.name())
assetListCtrl.SetStringItem(listRow,1,asset.type())
def onAdd(self... | DimensionBaseDialog.__init__(self,parent,TEMPLATEASSETS_ID,'Template Assets',(930,300),'asset.png')
self.rmFrame = parent
idList = [TEMPLATEASSETS_ASSETLIST_ID,TEMPLATEASSETS_BUTTONADD_ID,TEMPLATEASSETS_BUTTONDELETE_ID]
columnList = ['Name','Type']
self.buildControls(idList,columnList,self.dbProxy.g... | random_line_split |
TemplateAssetsDialog.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... | (self,evt):
try:
self.deleteObject('No template asset','Delete template asset',self.dbProxy.deleteTemplateAsset)
except ARMException,errorText:
dlg = wx.MessageDialog(self,str(errorText),'Delete template asset',wx.OK | wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy
| onDelete | identifier_name |
DeleteModal.tsx | import * as React from 'react';
import { RouteComponentProps } from 'react-router-dom';
import { Dialog, DialogType, DialogFooter } from 'office-ui-fabric-react/lib/Dialog';
import { PrimaryButton, DefaultButton } from 'office-ui-fabric-react/lib/Button';
interface DeleteModalProps {
open: boolean;
onHide: () ... |
public render() {
return (
<Dialog
hidden={!this.props.open}
onDismiss={() => this.props.onHide()}
dialogContentProps={{
type: DialogType.normal,
title: 'Delete',
subText: 'Are you sure ... | {
this.props.onHide();
this.props.onConfirm();
} | identifier_body |
DeleteModal.tsx | import * as React from 'react';
import { RouteComponentProps } from 'react-router-dom';
import { Dialog, DialogType, DialogFooter } from 'office-ui-fabric-react/lib/Dialog';
import { PrimaryButton, DefaultButton } from 'office-ui-fabric-react/lib/Button';
interface DeleteModalProps {
open: boolean;
onHide: () ... | }
public render() {
return (
<Dialog
hidden={!this.props.open}
onDismiss={() => this.props.onHide()}
dialogContentProps={{
type: DialogType.normal,
title: 'Delete',
subText: 'Are you ... | random_line_split | |
DeleteModal.tsx | import * as React from 'react';
import { RouteComponentProps } from 'react-router-dom';
import { Dialog, DialogType, DialogFooter } from 'office-ui-fabric-react/lib/Dialog';
import { PrimaryButton, DefaultButton } from 'office-ui-fabric-react/lib/Button';
interface DeleteModalProps {
open: boolean;
onHide: () ... | () {
this.props.onHide();
this.props.onConfirm();
}
public render() {
return (
<Dialog
hidden={!this.props.open}
onDismiss={() => this.props.onHide()}
dialogContentProps={{
type: DialogType.normal,
... | handleConfirmClick | identifier_name |
app.js |
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, '... |
app.get('/', routes.index);
app.get('/users', user.list);
var server = http.createServer(app);
var chatServer = require('./chat_server');
chatServer(server);
server.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
| {
app.use(express.errorHandler());
} | conditional_block |
app.js | /**
* Module dependencies.
*/
var express = require('express'); | var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
... | var routes = require('./routes'); | random_line_split |
dsf_with_sic.py | class | (object):
"""docstring for SIC_Map"""
def __init__(self, dsffile = 'crsp/dsf.csv', sicfile = 'sic_codes.txt'):
self.dsf = pd.read_csv("dsf.csv", dtype = {'CUSIP': np.str, 'PRC': np.float}, na_values = {'PRC': '-'})
self.sic = pd.read_table(sicfile, header = 1)
self.sic.columns = ['HSICCD... | DSF_SIC_Map | identifier_name |
dsf_with_sic.py | class DSF_SIC_Map(object):
"""docstring for SIC_Map"""
def __init__(self, dsffile = 'crsp/dsf.csv', sicfile = 'sic_codes.txt'):
|
def process(self, day = 20100101, columns = ['PERMNO', 'DATE', 'PRC', 'VOL', 'SHROUT', 'RET', 'HSICCD']):
self.dsf_startdate(date = day)
self.dsf_subset(to_keep = columns)
self.sic_merge()
def dsf_startdate(self, date = 20100101):
self.dsf = self.dsf[self.dsf.DATE >= date]
d... | self.dsf = pd.read_csv("dsf.csv", dtype = {'CUSIP': np.str, 'PRC': np.float}, na_values = {'PRC': '-'})
self.sic = pd.read_table(sicfile, header = 1)
self.sic.columns = ['HSICCD', 'SICNAME'] | identifier_body |
dsf_with_sic.py | class DSF_SIC_Map(object):
"""docstring for SIC_Map""" | self.dsf = pd.read_csv("dsf.csv", dtype = {'CUSIP': np.str, 'PRC': np.float}, na_values = {'PRC': '-'})
self.sic = pd.read_table(sicfile, header = 1)
self.sic.columns = ['HSICCD', 'SICNAME']
def process(self, day = 20100101, columns = ['PERMNO', 'DATE', 'PRC', 'VOL', 'SHROUT', 'RET', 'HSICCD... | def __init__(self, dsffile = 'crsp/dsf.csv', sicfile = 'sic_codes.txt'): | random_line_split |
index.js | /**
* Reparse the Grunt command line options flags.
*
* Using the arguments parsing logic from Grunt:
* https://github.com/gruntjs/grunt/blob/master/lib/grunt/cli.js
*/
module.exports = function(grunt){
// Get the current Grunt CLI instance.
var nopt = require('nopt'),
parsedOptions = parseOptions(nopt, gru... |
// Parse `optlist` into a form that nopt can handle.
function getParams(optlist){
var aliases = {};
var known = {};
Object.keys(optlist).forEach(function(key) {
var short = optlist[key].short;
if (short) {
aliases[short] = '--' + key;
}
known[key] = optlist[key].type;
});
return {
known: known,... | {
for (var i in parsedOptions){
if (parsedOptions.hasOwnProperty(i) && i != 'argv'){
grunt.option(i, parsedOptions[i]);
}
}
} | identifier_body |
index.js | /**
* Reparse the Grunt command line options flags.
*
* Using the arguments parsing logic from Grunt:
* https://github.com/gruntjs/grunt/blob/master/lib/grunt/cli.js
*/
module.exports = function(grunt){
// Get the current Grunt CLI instance.
var nopt = require('nopt'),
parsedOptions = parseOptions(nopt, gru... | (optlist){
var aliases = {};
var known = {};
Object.keys(optlist).forEach(function(key) {
var short = optlist[key].short;
if (short) {
aliases[short] = '--' + key;
}
known[key] = optlist[key].type;
});
return {
known: known,
aliases: aliases
}
}
// Initialize any Array options that weren't in... | getParams | identifier_name |
index.js | /**
* Reparse the Grunt command line options flags.
*
* Using the arguments parsing logic from Grunt:
* https://github.com/gruntjs/grunt/blob/master/lib/grunt/cli.js
*/
module.exports = function(grunt){
// Get the current Grunt CLI instance.
var nopt = require('nopt'),
parsedOptions = parseOptions(nopt, gru... | return {
known: known,
aliases: aliases
}
}
// Initialize any Array options that weren't initialized.
function initArrays(optlist, parsedOptions){
Object.keys(optlist).forEach(function(key) {
if (optlist[key].type === Array && !(key in parsedOptions)) {
parsedOptions[key] = [];
}
});
} | known[key] = optlist[key].type;
});
| random_line_split |
index.js | /**
* Reparse the Grunt command line options flags.
*
* Using the arguments parsing logic from Grunt:
* https://github.com/gruntjs/grunt/blob/master/lib/grunt/cli.js
*/
module.exports = function(grunt){
// Get the current Grunt CLI instance.
var nopt = require('nopt'),
parsedOptions = parseOptions(nopt, gru... |
known[key] = optlist[key].type;
});
return {
known: known,
aliases: aliases
}
}
// Initialize any Array options that weren't initialized.
function initArrays(optlist, parsedOptions){
Object.keys(optlist).forEach(function(key) {
if (optlist[key].type === Array && !(key in parsedOptions)) {
parsedOpti... | {
aliases[short] = '--' + key;
} | conditional_block |
modifiers.rs | /// Modifiers which can be injected by the application logic to change the state
use ::api;
use ::api::optional::Optional;
/// `StatusModifier`s are used to modify the status
pub trait StatusModifier: Send + Sync {
/// Called after all registered sensors are read
fn modify(&self, status: &mut api::Status);
}
... | status.state.message = Optional::Value(format!("{} person here right now", count));
} else if count > 1 {
status.state.message = Optional::Value(format!("{} people here right now", count));
}
}
}
} | .into();
if let Some(count) = people_now_present {
status.state.open = Some(count > 0);
if count == 1 { | random_line_split |
modifiers.rs | /// Modifiers which can be injected by the application logic to change the state
use ::api;
use ::api::optional::Optional;
/// `StatusModifier`s are used to modify the status
pub trait StatusModifier: Send + Sync {
/// Called after all registered sensors are read
fn modify(&self, status: &mut api::Status);
}
... |
}
}
| {
status.state.open = Some(count > 0);
if count == 1 {
status.state.message = Optional::Value(format!("{} person here right now", count));
} else if count > 1 {
status.state.message = Optional::Value(format!("{} people here right now", count));
... | conditional_block |
modifiers.rs | /// Modifiers which can be injected by the application logic to change the state
use ::api;
use ::api::optional::Optional;
/// `StatusModifier`s are used to modify the status
pub trait StatusModifier: Send + Sync {
/// Called after all registered sensors are read
fn modify(&self, status: &mut api::Status);
}
... | ;
impl StatusModifier for StateFromPeopleNowPresent {
fn modify(&self, status: &mut api::Status) {
// Update state depending on number of people present
let people_now_present: Option<u64> = status.sensors.as_ref()
.and_then(|sensors| sensors.people_now_present.as_ref())
.ma... | StateFromPeopleNowPresent | identifier_name |
schedule_controller.ts | import { GET, POST, PUT, DELETE, QueryParam, BodyParam, PathParam, BaseController } from 'webapi-router';
import { ResObject } from '../interfaces/res_object';
import * as Koa from 'koa';
import { DtoSchedule } from '../common/interfaces/dto_schedule';
import { ScheduleService } from '../services/schedule_service';
imp... | extends BaseController {
@POST('/schedule')
async createNew(ctx: Koa.Context, @BodyParam schedule: DtoSchedule): Promise<ResObject> {
return ScheduleService.createNew(schedule, (<any>ctx).session.user);
}
@PUT('/schedule')
async update(@BodyParam schedule: DtoSchedule): Promise<ResObject>... | ScheduleController | identifier_name |
schedule_controller.ts | import { GET, POST, PUT, DELETE, QueryParam, BodyParam, PathParam, BaseController } from 'webapi-router';
import { ResObject } from '../interfaces/res_object';
import * as Koa from 'koa'; | import { ScheduleService } from '../services/schedule_service';
import { ScheduleRecordService } from '../services/schedule_record_service';
import { Message } from '../utils/message';
import { ScheduleRunner } from '../run_engine/schedule_runner';
export default class ScheduleController extends BaseController {
... | import { DtoSchedule } from '../common/interfaces/dto_schedule'; | random_line_split |
schedule_controller.ts | import { GET, POST, PUT, DELETE, QueryParam, BodyParam, PathParam, BaseController } from 'webapi-router';
import { ResObject } from '../interfaces/res_object';
import * as Koa from 'koa';
import { DtoSchedule } from '../common/interfaces/dto_schedule';
import { ScheduleService } from '../services/schedule_service';
imp... |
@GET('/schedules')
async getSchedules(ctx: Koa.Context): Promise<ResObject> {
const schedules = await ScheduleService.getByUserId((<any>ctx).session.userId);
return { success: true, message: '', result: schedules };
}
@GET('/schedule/:id/records')
async getSchedulesInPage(@PathPar... | {
return ScheduleService.delete(id);
} | identifier_body |
schedule_controller.ts | import { GET, POST, PUT, DELETE, QueryParam, BodyParam, PathParam, BaseController } from 'webapi-router';
import { ResObject } from '../interfaces/res_object';
import * as Koa from 'koa';
import { DtoSchedule } from '../common/interfaces/dto_schedule';
import { ScheduleService } from '../services/schedule_service';
imp... |
new ScheduleRunner().runSchedule(schedule, null, false);
return { success: true, message: '' };
}
} | {
return { success: false, message: Message.get('scheduleNotExist') };
} | conditional_block |
WorkerTest.js | var WorkerInstance = require("../lib/workers/WorkerInstance.js").WorkerInstance,
EventEmitter = require("events").EventEmitter;
exports.WorkerPrototypeTests = {
setUp: function(done) {
done();
},
"Worker has a EventEmitter in prototype chain": function(test) {
test.expect(1);
var worker = new W... | worker.once("die", function(err) {
die = true;
error = err;
});
worker.spawn();
test.equal(die, true, "die event should occure after invalid execution");
test.equal(error, "Error", "die event should return exception object");
test.done();
}
}; | var error = null,
die = false,
worker = new WorkerInstance(function() { throw "Error"; });
| random_line_split |
transforms.py | , -0.8122141),
(-0.560893, 0.7183267, 0.41158938))
def bgr_to_rgb(image):
return image[..., ::-1]
def rgb_to_bgr(image):
return image[..., ::-1]
def brightness(image, variance):
alpha = 1 + tf.random.uniform(
[1], dtype=tf.float32, minval=-variance, maxval=variance)[0]
return imag... | (original_image_size,
input_image_size,
padding_keep_size=127,
random=False,
random_side_scale_range=None):
"""Computer affine transform."""
if input_image_... | compute_image_size_affine_transform | identifier_name |
transforms.py | = lambda i: tf.math.less_equal(size - border // i, border // i)
body = lambda i: tf.multiply(i, 2)
r = tf.while_loop(cond, body, [i])
return border // r[0]
def compute_image_size_affine_transform(original_image_size,
input_image_size,
... | new_points = image_utils.transform_points(points.numpy(), center.numpy(),
scale.numpy(), output_size.numpy(),
inverse)
return new_points | identifier_body | |
transforms.py | , -0.8122141),
(-0.560893, 0.7183267, 0.41158938))
def bgr_to_rgb(image):
return image[..., ::-1]
def rgb_to_bgr(image):
return image[..., ::-1]
def brightness(image, variance):
alpha = 1 + tf.random.uniform(
[1], dtype=tf.float32, minval=-variance, maxval=variance)[0]
return imag... |
else:
image.set_shape([None, None, image.shape[-1]])
if transform_gt_annotations:
bounding_boxes_shape = bounding_boxes.shape
[
bounding_boxes,
] = tf.py_function(_affine_transform_points_np, [
bounding_boxes, original_image_size, center, side_size, input_size,
flipped
... | image.set_shape([image.shape[0], None, None, image.shape[-1]]) | conditional_block |
transforms.py | 8))
def bgr_to_rgb(image):
return image[..., ::-1]
def rgb_to_bgr(image):
return image[..., ::-1]
def brightness(image, variance):
alpha = 1 + tf.random.uniform(
[1], dtype=tf.float32, minval=-variance, maxval=variance)[0]
return image * alpha
def contrast(image, image_grayscale_mean, variance):
... | random_line_split | ||
structvlog__rate__limit.js | var structvlog__rate__limit =
[
[ "first_dropped", "structvlog__rate__limit.html#a5e5e3573e3896856f662f69dd6c61db6", null ],
[ "last_dropped", "structvlog__rate__limit.html#abf689bdafddbdd448f7fdca18545f105", null ], | [ "n_dropped", "structvlog__rate__limit.html#a94de7b5b4aa72bfa63517ca8b532aa6d", null ],
[ "token_bucket", "structvlog__rate__limit.html#af4838e83b258f9aa26779d9d6cfd2dc9", null ]
]; | [ "mutex", "structvlog__rate__limit.html#a537fdf5130c0f6394445a5e421409c04", null ], | random_line_split |
SelectEnumerationDialog.ts | import { SelectionModel } from '@angular/cdk/collections';
import { AfterViewInit, ChangeDetectionStrategy, Component, Inject, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatPaginator } from '@angular/... | implements AfterViewInit {
filterControl = new FormControl();
@ViewChild(MatPaginator, { static: true })
paginator: MatPaginator;
dataSource = new MatTableDataSource<EnumValue>([]);
selection = new SelectionModel<EnumValue>();
displayedColumns = [
'name',
'value',
];
constructor(
priva... | SelectEnumerationDialog | identifier_name |
SelectEnumerationDialog.ts | import { SelectionModel } from '@angular/cdk/collections';
import { AfterViewInit, ChangeDetectionStrategy, Component, Inject, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatPaginator } from '@angular/... |
}
}
| {
this.dialogRef.close(selected[0]);
} | conditional_block |
SelectEnumerationDialog.ts | import { SelectionModel } from '@angular/cdk/collections';
import { AfterViewInit, ChangeDetectionStrategy, Component, Inject, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatPaginator } from '@angular/... |
}
| {
const selected = this.selection.selected;
if (selected.length) {
this.dialogRef.close(selected[0]);
}
} | identifier_body |
SelectEnumerationDialog.ts | import { SelectionModel } from '@angular/cdk/collections';
import { AfterViewInit, ChangeDetectionStrategy, Component, Inject, ViewChild } from '@angular/core'; | import { Argument, EnumValue } from '../../client';
@Component({
selector: 'app-select-enumeration-dialog',
templateUrl: './SelectEnumerationDialog.html',
styleUrls: ['./SelectEnumerationDialog.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SelectEnumerationDialog implements AfterViewI... | import { FormControl } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table'; | random_line_split |
middleware.ts | // tslint:disable:no-expression-statement
import { Dispatch, MiddlewareAPI } from 'redux';
import { Store } from '../../stores';
import * as R from 'ramda';
import { sendServicesCountEvent } from './events';
import { SAVE_SERVICE_TO_MAP, LOAD_SERVICES_SUCCESS, MEMORY_REPORT_SEND_EVERY_SERVICES_COUNT } from '../../appli... |
return next(action);
});
type UpdateServicesActions = SaveServiceToMapAction | BuildServicesSuccessAction;
const sendServicesCountReport = (store: Store, action: UpdateServicesActions): void => {
const oldStore = store.services;
const newStore = servicesReducer(store.services, action);
const oldServ... | {
sendServicesCountReport(state, action);
} | conditional_block |
middleware.ts | // tslint:disable:no-expression-statement
import { Dispatch, MiddlewareAPI } from 'redux';
import { Store } from '../../stores';
import * as R from 'ramda'; | import { SAVE_SERVICE_TO_MAP, LOAD_SERVICES_SUCCESS, MEMORY_REPORT_SEND_EVERY_SERVICES_COUNT } from '../../application/constants';
import { reducer as servicesReducer } from '../../stores/services';
import { SaveServiceToMapAction, BuildServicesSuccessAction } from '../../stores/services/actions';
// tslint:disable-ne... | import { sendServicesCountEvent } from './events'; | random_line_split |
product-list.component.ts | import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { IProduct } from './product';
import { ProductService } from './product.service';
@Component({
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class Product... | (private productService: ProductService) {}
performFilter(filterBy: string): IProduct[] {
filterBy = filterBy.toLocaleLowerCase();
return this.products.filter((product: IProduct) =>
product.productName.toLocaleLowerCase().includes(filterBy));
}
toggleImage(): void {
this.showImage = !this.show... | constructor | identifier_name |
product-list.component.ts | import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { IProduct } from './product';
import { ProductService } from './product.service';
@Component({
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class Product... | constructor(private productService: ProductService) {}
performFilter(filterBy: string): IProduct[] {
filterBy = filterBy.toLocaleLowerCase();
return this.products.filter((product: IProduct) =>
product.productName.toLocaleLowerCase().includes(filterBy));
}
toggleImage(): void {
this.showImage... | random_line_split | |
product-list.component.ts | import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { IProduct } from './product';
import { ProductService } from './product.service';
@Component({
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class Product... |
ngOnDestroy(): void {
this.sub.unsubscribe();
}
onRatingClicked(message: string): void {
this.pageTitle = 'Product List: ' + message;
}
}
| {
this.sub = this.productService.getProducts().subscribe({
next: products => {
this.products = products;
this.filteredProducts = this.products;
},
error: err => this.errorMessage = err
});
} | identifier_body |
index.d.ts | // Type definitions for pi-camera 1.5
// Project: https://github.com/stetsmando/pi-camera
// Definitions by: Ata Berk YILMAZ <https://github.com/ataberkylmz>
// Piotr Błażejewicz <https://github.com/peterblazejewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped | constructor(config?: PiCamera.CameraConfig);
snap(): Promise<string>;
/** @async */
snapDataUrl(maxBuffer?: number): Promise<string>;
record(): Promise<string>;
get(prop: PiCamera.ConfigKey): PiCamera.ConfigValue;
set(prop: PiCamera.ConfigKey, value: PiCamera.ConfigValue): PiCamera.ConfigVal... |
declare class PiCamera { | random_line_split |
index.d.ts | // Type definitions for pi-camera 1.5
// Project: https://github.com/stetsmando/pi-camera
// Definitions by: Ata Berk YILMAZ <https://github.com/ataberkylmz>
// Piotr Błażejewicz <https://github.com/peterblazejewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare class Pi |
constructor(config?: PiCamera.CameraConfig);
snap(): Promise<string>;
/** @async */
snapDataUrl(maxBuffer?: number): Promise<string>;
record(): Promise<string>;
get(prop: PiCamera.ConfigKey): PiCamera.ConfigValue;
set(prop: PiCamera.ConfigKey, value: PiCamera.ConfigValue): PiCamera.ConfigVa... | Camera { | identifier_name |
openstackutils.py | #!/usr/bin/env python
#-*- coding: utf-8 -
import keystoneclient.v2_0.client as keystone
from keystoneauth1.identity import v2
from keystoneauth1 import session
import novaclient.client as nova
import cinderclient.client as cinder
from glanceclient.v1 import client as glance
import neutronclient.v2_0.client as neutron
... | self.cinder_client.volumes.delete(volume.id) | identifier_body | |
openstackutils.py | #!/usr/bin/env python
#-*- coding: utf-8 -
import keystoneclient.v2_0.client as keystone
from keystoneauth1.identity import v2
from keystoneauth1 import session
import novaclient.client as nova
import cinderclient.client as cinder
from glanceclient.v1 import client as glance
import neutronclient.v2_0.client as neutron
... | (self,server):
self.wait_server_available(server)
return self.nova_client.servers.get(server.id).unrescue()
def attach_volume_to_server(self,server,volume):
#self.nova_client.volumes.create_server_volume(server_id=server.id,volume_id=env['NOSE_VOLUME_ID'])
self.nova_client.volumes.... | unrescue | identifier_name |
openstackutils.py | #!/usr/bin/env python
#-*- coding: utf-8 -
import keystoneclient.v2_0.client as keystone
from keystoneauth1.identity import v2
from keystoneauth1 import session
import novaclient.client as nova
import cinderclient.client as cinder
from glanceclient.v1 import client as glance
import neutronclient.v2_0.client as neutron
... | return ssh_connection
def create_floating_ip(self):
return self.nova_client.floating_ips.create('public')
#def associate_floating_ip_to_port(self,floating_ip):
# self.neutron_client.update_floatingip(floating_ip.id,{'floatingip': {'port_id': env['NOSE_PORT_ID'] }})
def associate... | retries_left -= 1 | random_line_split |
openstackutils.py | #!/usr/bin/env python
#-*- coding: utf-8 -
import keystoneclient.v2_0.client as keystone
from keystoneauth1.identity import v2
from keystoneauth1 import session
import novaclient.client as nova
import cinderclient.client as cinder
from glanceclient.v1 import client as glance
import neutronclient.v2_0.client as neutron
... |
print "server is up"
def wait_for_cloud_init(self,server):
while True:
console_log = self.get_console_log(server)
if re.search('^.*Cloud-init .* finished.*$', console_log, flags=re.MULTILINE):
print("Cloudinit finished")
break
else:
... | status = self.get_server(server.id).status | conditional_block |
train.py | # Example implementing 5 layer encoder
# Original code taken from
# https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/autoencoder.py
# The model trained here is restored in load.py
from __future__ import division, print_function, absolute_import
# Import MNIST data
# from tens... |
print("===final===")
print(sess.run(accuracy, feed_dict={x: batch_x_test0, y: batch_y_test0}))
print(sess.run(accuracy, feed_dict={x: batch_x_test1, y: batch_y_test1}))
# Save
model.save(sess, 'example_3')
| _, c = sess.run([optimizer, cost], feed_dict={x: batch_x_t0, y: batch_y_t0})
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x_t1, y: batch_y_t1})
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x_p0, y: batch_y_p0})
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x_p1, y: batch_y_p1})
... | conditional_block |
train.py | # Example implementing 5 layer encoder
# Original code taken from
# https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/autoencoder.py
# The model trained here is restored in load.py
from __future__ import division, print_function, absolute_import
# Import MNIST data
# from tens... | _, c = sess.run([optimizer, cost], feed_dict={x: batch_x_t1, y: batch_y_t1})
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x_p0, y: batch_y_p0})
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x_p1, y: batch_y_p1})
# Display logs per epoch step
print("Epoch:", '%04d' % (epoch+1), "c... | # Train
for epoch in range(training_epochs):
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x_t0, y: batch_y_t0}) | random_line_split |
projections.py | #!/usr/bin/env python
from math import pi, sin, log, exp, atan
DEG_TO_RAD = pi / 180
RAD_TO_DEG = 180 / pi
def minmax (a,b,c):
a = max(a,b)
a = min(a,c)
return a
class GoogleProjection:
"""
Google projection transformations. Sourced from the OSM.
Have not taken the time to figure out how thi... |
def fromLLtoPixel(self, ll, zoom):
d = self.zc[zoom]
e = round(d[0] + ll[0] * self.Bc[zoom])
f = minmax(sin(DEG_TO_RAD * ll[1]),-0.9999,0.9999)
g = round(d[1] + 0.5*log((1+f)/(1-f))*-self.Cc[zoom])
return (e,g)
def fromPixelToLL(self, px, zoom... | e = c/2;
self.Bc.append(c/360.0)
self.Cc.append(c/(2 * pi))
self.zc.append((e,e))
self.Ac.append(c)
c *= 2 | conditional_block |
projections.py | #!/usr/bin/env python
from math import pi, sin, log, exp, atan
DEG_TO_RAD = pi / 180
RAD_TO_DEG = 180 / pi
def minmax (a,b,c):
a = max(a,b)
a = min(a,c)
return a
class GoogleProjection:
"""
Google projection transformations. Sourced from the OSM.
Have not taken the time to figure out how thi... | e = self.zc[zoom]
f = (px[0] - e[0])/self.Bc[zoom]
g = (px[1] - e[1])/-self.Cc[zoom]
h = RAD_TO_DEG * ( 2 * atan(exp(g)) - 0.5 * pi)
return (f,h) | identifier_body | |
projections.py | #!/usr/bin/env python
from math import pi, sin, log, exp, atan
DEG_TO_RAD = pi / 180
RAD_TO_DEG = 180 / pi
def minmax (a,b,c):
a = max(a,b)
a = min(a,c)
return a
class GoogleProjection:
"""
Google projection transformations. Sourced from the OSM.
Have not taken the time to figure out how thi... | d = self.zc[zoom]
e = round(d[0] + ll[0] * self.Bc[zoom])
f = minmax(sin(DEG_TO_RAD * ll[1]),-0.9999,0.9999)
g = round(d[1] + 0.5*log((1+f)/(1-f))*-self.Cc[zoom])
return (e,g)
def fromPixelToLL(self, px, zoom):
e = self.zc[zoom]
f = (px[0] - e[0])... | c *= 2
def fromLLtoPixel(self, ll, zoom): | random_line_split |
projections.py | #!/usr/bin/env python
from math import pi, sin, log, exp, atan
DEG_TO_RAD = pi / 180
RAD_TO_DEG = 180 / pi
def minmax (a,b,c):
a = max(a,b)
a = min(a,c)
return a
class | :
"""
Google projection transformations. Sourced from the OSM.
Have not taken the time to figure out how this works.
"""
def __init__(self, levels=18):
self.Bc = []
self.Cc = []
self.zc = []
self.Ac = []
c = 256
for d in range(levels + 1):
... | GoogleProjection | identifier_name |
hybrid_key_templates.ts | /**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {AeadKeyTemplates} from '../aead/aead_key_templates';
import {PbEciesAeadDemParams, PbEciesAeadHkdfKeyFormat, PbEciesAeadHkdfParams, PbEciesHkdfKemParams, PbEllipticCurveType, PbHashType, PbKeyTemplate, PbOutputPrefixType, P... | (): PbKeyTemplate {
return createEciesAeadHkdfKeyTemplate_(
/* curveType = */
PbEllipticCurveType.NIST_P256,
/* hkdfHash = */
PbHashType.SHA256,
/* pointFormat = */
PbPointFormat.UNCOMPRESSED,
/* demKeyTemplate = */
AeadKeyTemplates.aes128Gcm(),
... | eciesP256HkdfHmacSha256Aes128Gcm | identifier_name |
hybrid_key_templates.ts | /**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {AeadKeyTemplates} from '../aead/aead_key_templates';
import {PbEciesAeadDemParams, PbEciesAeadHkdfKeyFormat, PbEciesAeadHkdfParams, PbEciesHkdfKemParams, PbEllipticCurveType, PbHashType, PbKeyTemplate, PbOutputPrefixType, P... | .setEcPointFormat(pointFormat);
return params;
} | random_line_split | |
hybrid_key_templates.ts | /**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {AeadKeyTemplates} from '../aead/aead_key_templates';
import {PbEciesAeadDemParams, PbEciesAeadHkdfKeyFormat, PbEciesAeadHkdfParams, PbEciesHkdfKemParams, PbEllipticCurveType, PbHashType, PbKeyTemplate, PbOutputPrefixType, P... |
function createEciesAeadHkdfParams_(
curveType: PbEllipticCurveType, hkdfHash: PbHashType,
pointFormat: PbPointFormat, demKeyTemplate: PbKeyTemplate,
hkdfSalt: Uint8Array): PbEciesAeadHkdfParams {
// KEM params
const kemParams = (new PbEciesHkdfKemParams())
.setCurveType(curveT... | {
// key format
const keyFormat =
(new PbEciesAeadHkdfKeyFormat())
.setParams(createEciesAeadHkdfParams_(
curveType, hkdfHash, pointFormat, demKeyTemplate, hkdfSalt));
// key template
const keyTemplate =
(new PbKeyTemplate())
.setTypeUrl(HybridConfig.ECIES_AEAD_HKD... | identifier_body |
modal-visual.component.ts | import { Component } from '@angular/core';
import { SkyModalService } from '@blackbaud/skyux/dist/core';
import { ModalDemoComponent } from './modal-demo.component';
import { ModalLargeDemoComponent } from './modal-large-demo.component';
import { ModalFullPageDemoComponent } from './modal-fullpage-demo.component';
imp... |
public openFullScreenModal() {
this.modal.open(ModalFullPageDemoComponent, { 'providers': [], 'fullPage': true });
}
public openContentModal() {
this.modal.open(ModalContentDemoComponent);
}
public openSmallSizeModal() {
this.modal.open(
ModalDemoComponent, { 'providers': [], 'fullPage':... | {
this.modal.open(ModalLargeDemoComponent, { 'providers': [] });
} | identifier_body |
modal-visual.component.ts | import { Component } from '@angular/core';
import { SkyModalService } from '@blackbaud/skyux/dist/core';
import { ModalDemoComponent } from './modal-demo.component';
import { ModalLargeDemoComponent } from './modal-large-demo.component';
import { ModalFullPageDemoComponent } from './modal-fullpage-demo.component';
imp... | public openContentModal() {
this.modal.open(ModalContentDemoComponent);
}
public openSmallSizeModal() {
this.modal.open(
ModalDemoComponent, { 'providers': [], 'fullPage': false , 'size': 'small'});
}
public openMediumSizeModal() {
this.modal.open(
ModalDemoComponent, { 'providers': ... | }
| random_line_split |
modal-visual.component.ts | import { Component } from '@angular/core';
import { SkyModalService } from '@blackbaud/skyux/dist/core';
import { ModalDemoComponent } from './modal-demo.component';
import { ModalLargeDemoComponent } from './modal-large-demo.component';
import { ModalFullPageDemoComponent } from './modal-fullpage-demo.component';
imp... | () {
this.modal.open(ModalContentDemoComponent);
}
public openSmallSizeModal() {
this.modal.open(
ModalDemoComponent, { 'providers': [], 'fullPage': false , 'size': 'small'});
}
public openMediumSizeModal() {
this.modal.open(
ModalDemoComponent, { 'providers': [], 'fullPage': false , '... | openContentModal | identifier_name |
compat.py | :
return string
res = [bits[0]]
append = res.append
for item in bits[1:]:
try:
append(compat_urllib_parse._hextochr[item[:2]])
append(item[2:])
except KeyError:
append(b'%')
append(item)
r... |
def encode_list(l):
return [encode_elem(e) for e in l]
return compat_urllib_parse.urlencode(encode_elem(query), doseq=doseq)
try:
from urllib.request import DataHandler as compat_urllib_request_DataHandler
except ImportError: # Python < 3.4
# Ported from CPython 98774:1733b3bd46... | return dict((encode_elem(k), encode_elem(v)) for k, v in d.items()) | identifier_body |
compat.py | :
return string
res = [bits[0]]
append = res.append
for item in bits[1:]:
try:
append(compat_urllib_parse._hextochr[item[:2]])
append(item[2:])
except KeyError:
append(b'%')
append(item)
r... | (string, encoding='utf-8', errors='replace'):
"""Replace %xx escapes by their single-character equivalent. The optional
encoding and errors parameters specify how to decode percent-encoded
sequences into Unicode characters, as accepted by the bytes.decode()
method.
By default, pe... | compat_urllib_parse_unquote | identifier_name |
compat.py | compat_str):
e = e.encode(encoding)
return e
def encode_dict(d):
return dict((encode_elem(k), encode_elem(v)) for k, v in d.items())
def encode_list(l):
return [encode_elem(e) for e in l]
return compat_urllib_parse.urlencode(encode_elem(que... | userhome = compat_getenv('HOME') | conditional_block | |
compat.py | isinstance(e, dict):
e = encode_dict(e)
elif isinstance(e, (list, tuple,)):
list_e = encode_list(e)
e = tuple(list_e) if isinstance(e, tuple) else list_e
elif isinstance(e, compat_str):
e = e.encode(encoding)
return e
... | return path | random_line_split | |
jquery.scrollto.js | /*!
* jquery.scrollto.js 0.0.1 - https://github.com/yckart/jquery.scrollto.js
* Scroll smooth to any element in your DOM.
*
* Copyright (c) 2012 Yannick Albert (http://yckart.com)
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php).
* 2013/02/17
**/
(function($) { | $.scrollTo = $.fn.scrollTo = function(x, y, options){
if (!(this instanceof $)) return $.fn.scrollTo.apply($('html, body'), arguments);
options = $.extend({}, {
gap: {
x: 0,
y: 0
},
animation: {
easing: 'swing',
duration: 600,
... | random_line_split | |
simd.rs | // Copyright 2015 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 ... | (i32, i32, i32, i32);
extern {
// _mm_sll_epi32
#[cfg(any(target_arch = "x86",
target_arch = "x86-64"))]
#[link_name = "llvm.x86.sse2.psll.d"]
fn integer(a: i32x4, b: i32x4) -> i32x4;
// vmaxq_s32
#[cfg(any(target_arch = "arm"))]
#[link_name = "llvm.arm.neon.vmaxs.v4i32"]
... | i32x4 | identifier_name |
simd.rs | // Copyright 2015 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 ... | }
#[repr(C)]
#[derive(Copy)]
#[simd]
pub struct i32x4(i32, i32, i32, i32);
extern {
// _mm_sll_epi32
#[cfg(any(target_arch = "x86",
target_arch = "x86-64"))]
#[link_name = "llvm.x86.sse2.psll.d"]
fn integer(a: i32x4, b: i32x4) -> i32x4;
// vmaxq_s32
#[cfg(any(target_arch = "arm... | random_line_split | |
pack.rs | use std::path::Path;
use unshare::{Command, Stdio};
use container::uidmap::{map_users};
use options::pack::Options;
use wrapper::Wrapper;
use process_util::{convert_status, set_uidmap};
use super::setup;
pub fn | (wrapper: &Wrapper, cmdline: Vec<String>)
-> Result<i32, String>
{
let options = match Options::parse(&cmdline) {
Ok(x) => x,
Err(code) => return Ok(code),
};
try!(setup::setup_base_filesystem(
wrapper.project_root, wrapper.ext_settings));
let cconfig = try!(wrapper.config.c... | pack_image_cmd | identifier_name |
pack.rs | use std::path::Path;
use unshare::{Command, Stdio};
use container::uidmap::{map_users};
use options::pack::Options;
use wrapper::Wrapper;
use process_util::{convert_status, set_uidmap};
use super::setup;
pub fn pack_image_cmd(wrapper: &Wrapper, cmdline: Vec<String>)
-> Result<i32, String>
| false);
if let Some(ref f) = options.file {
cmd.arg("-f").arg(Path::new("/work").join(f));
}
cmd.arg("-C").arg(&root);
cmd.arg(".");
info!("Running {:?}", cmd);
cmd.status()
.map(convert_status)
.map_err(|e| format!("Command {:?} {}", cmd, e))
}
| {
let options = match Options::parse(&cmdline) {
Ok(x) => x,
Err(code) => return Ok(code),
};
try!(setup::setup_base_filesystem(
wrapper.project_root, wrapper.ext_settings));
let cconfig = try!(wrapper.config.containers.get(&options.name)
.ok_or(format!("Container {} not... | identifier_body |
pack.rs | use std::path::Path;
use unshare::{Command, Stdio};
use container::uidmap::{map_users};
use options::pack::Options;
use wrapper::Wrapper;
use process_util::{convert_status, set_uidmap};
use super::setup;
pub fn pack_image_cmd(wrapper: &Wrapper, cmdline: Vec<String>)
-> Result<i32, String>
{
let options = ma... | .join(container_ver).join("root");
let mut cmd = Command::new("/vagga/bin/busybox");
cmd.stdin(Stdio::null())
.arg("tar")
.arg("-c");
set_uidmap(&mut cmd,
&try!(map_users(wrapper.settings, &cconfig.uids, &cconfig.gids)),
false);
if let Some(ref f) = options.file ... | let cconfig = try!(wrapper.config.containers.get(&options.name)
.ok_or(format!("Container {} not found", options.name)));
let container_ver = wrapper.root.as_ref().unwrap();
let root = Path::new("/vagga/base/.roots") | random_line_split |
DatasetCreation.tsx | import { bind } from 'decko';
import * as R from 'ramda';
import * as React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators, Dispatch } from 'redux';
import { validateDescription } from 'shared/models/Description';
import { handleCustomErrorWithFallback } from 'shared/models/Error';
im... |
public render() {
const { creatingDataset } = this.props;
return (
<PageCard>
<PageHeader title="Create a new dataset" />
<PresetFormik<Dataset.IDatasetCreationSettings>
initialValues={this.initialSettings}
onSubmit={this.createDataset}
>
{({ valu... | {
this.props.resetCreatingDataset(undefined);
} | identifier_body |
DatasetCreation.tsx | import { bind } from 'decko';
import * as R from 'ramda';
import * as React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators, Dispatch } from 'redux';
import { validateDescription } from 'shared/models/Description';
import { handleCustomErrorWithFallback } from 'shared/models/Error';
im... | () {
this.props.resetCreatingDataset(undefined);
}
public render() {
const { creatingDataset } = this.props;
return (
<PageCard>
<PageHeader title="Create a new dataset" />
<PresetFormik<Dataset.IDatasetCreationSettings>
initialValues={this.initialSettings}
on... | UNSAFE_componentWillMount | identifier_name |
DatasetCreation.tsx | import { bind } from 'decko';
import * as R from 'ramda';
import * as React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators, Dispatch } from 'redux';
import { validateDescription } from 'shared/models/Description';
import { handleCustomErrorWithFallback } from 'shared/models/Error';
im... | } from 'features/workspaces/store';
import styles from './DatasetCreation.module.css';
const mapStateToProps = (state: IApplicationState) => {
return {
creatingDataset: DatasetsStore.selectCommunications(state).creatingDataset,
workspaces: selectWorkspaces(state),
currentWorkspace: selectCurrentWorkspac... | selectWorkspaces,
selectCurrentWorkspaceName, | random_line_split |
LiquidMagmaTotem.tsx | import SPELLS from 'common/SPELLS';
import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events, { DamageEvent } from 'parser/core/Events';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import ItemDamageDone from 'parser/ui/ItemDamageDone';
import Statistic from 'parser... | onLMTDamage(event: DamageEvent) {
this.damageGained += event.amount + (event.absorbed || 0);
}
statistic() {
return (
<Statistic position={STATISTIC_ORDER.OPTIONAL()} size="flexible">
<BoringSpellValueText spellId={SPELLS.LIQUID_MAGMA_TOTEM_TALENT.id}>
<>
<ItemDamageDo... | );
}
| random_line_split |
LiquidMagmaTotem.tsx | import SPELLS from 'common/SPELLS';
import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events, { DamageEvent } from 'parser/core/Events';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import ItemDamageDone from 'parser/ui/ItemDamageDone';
import Statistic from 'parser... | (options: Options) {
super(options);
this.active = this.selectedCombatant.hasTalent(SPELLS.LIQUID_MAGMA_TOTEM_TALENT.id);
this.addEventListener(
Events.damage.by(SELECTED_PLAYER).spell(SPELLS.LIQUID_MAGMA_TOTEM_DAMAGE),
this.onLMTDamage,
);
}
onLMTDamage(event: DamageEvent) {
this.d... | constructor | identifier_name |
LiquidMagmaTotem.tsx | import SPELLS from 'common/SPELLS';
import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events, { DamageEvent } from 'parser/core/Events';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import ItemDamageDone from 'parser/ui/ItemDamageDone';
import Statistic from 'parser... |
}
export default LiquidMagmaTotem;
| {
return (
<Statistic position={STATISTIC_ORDER.OPTIONAL()} size="flexible">
<BoringSpellValueText spellId={SPELLS.LIQUID_MAGMA_TOTEM_TALENT.id}>
<>
<ItemDamageDone amount={this.damageGained} />
</>
</BoringSpellValueText>
</Statistic>
);
} | identifier_body |
google-apps-script-events.d.ts | // Type definitions for Google Apps Script 2019-04-02
// Project: https://developers.google.com/apps-script/
// Definitions by: PopGoesTheWza <https://github.com/PopGoesTheWza>
// oshliaer <https://github.com/oshliaer>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
| /// <reference path="google-apps-script.slides.d.ts" />
declare namespace GoogleAppsScript {
/**
* Google Apps Script Events
* @see https://developers.google.com/apps-script/guides/triggers/events
*/
namespace Events {
// Internal interfaces
interface AppsScriptEvent {
authMode: Script.AuthM... | /// <reference path="google-apps-script.script.d.ts" />
/// <reference path="google-apps-script.spreadsheet.d.ts" /> | random_line_split |
index.js | var flatten = require('arr-flatten'),
ensureMap = require('ensure-map'),
onFinished = require('on-finished');
module.exports = function(logger) {
return function *(next) {
var ctx = this;
ctx.log = logger;
onFinished(ctx.res, function() {
ctx.log.debug({ res: ctx.res, req: ctx.req }, 'Respons... |
if (included.length) {
var values = {};
included.forEach(function(key) {
var alias = map[key];
values[alias] = ctx[key];
});
ctx.log = ctx.log.child(values, true);
}
yield* next;
};
};
| {
throw new Error('.use(logging(logger)) first');
} | conditional_block |
index.js | var flatten = require('arr-flatten'),
ensureMap = require('ensure-map'),
onFinished = require('on-finished');
module.exports = function(logger) {
return function *(next) {
var ctx = this;
ctx.log = logger;
onFinished(ctx.res, function() {
ctx.log.debug({ res: ctx.res, req: ctx.req }, 'Respons... | };
}; | }
yield* next; | random_line_split |
use.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | (parser, args):
print_module_placeholder_help()
| use | identifier_name |
use.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
import argparse
from spack.cmd.common import print_module_placeholder_help
description = "add package to environment using dotkit"
section = "environment"
level = "lo... | random_line_split | |
use.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... |
def use(parser, args):
print_module_placeholder_help()
| """Parser is only constructed so that this prints a nice help
message with -h. """
subparser.add_argument(
'spec', nargs=argparse.REMAINDER,
help='spec of package to use with dotkit') | identifier_body |
mspsb-spouse-info.e2e-spec.ts | import { browser, element, by } from 'protractor';
import { SpouseInfoPage } from './mspsb-supp-benefits.po';
import { FakeDataSupplementaryBenefits } from './mspsb-supp-benefits.data';
import { testGenericAllPages, testGenericSubsequentPage } from '../../msp-generic-tests';
describe('MSP Supplementary Benefits - Spou... | afterEach(() => {
browser.executeScript('window.sessionStorage.clear();');
browser.executeScript('window.localStorage.clear();');
});
testGenericAllPages(SpouseInfoPage, SPOUSE_PAGE_URL);
testGenericSubsequentPage(SpouseInfoPage, {prevLink: 'Personal Info', nextLink: 'Contact Info'}, {P... | data.setSeed();
});
| random_line_split |
plugin.js | var extend = require( 'extend' );
var findParent = require( './find-parent' );
var falafel = require( './falafel-helper' );
var ignore = require( 'esformatter-ignore' );
module.exports = {
setOptions: function ( opts ) {
var me = this;
opts = opts || { };
me.opts = opts;
var jsxOptions = opts.jsx |... |
if ( node.type === 'ExportNamedDeclaration' && node.source().indexOf( 'from' ) > -1 ) {
node.update( node.source().replace( /^export/, 'import/*___fake_import_token__*/' ) );
}
if ( node.type === 'Decorator' ) {
node.update( node.source().replace( /^\s*@/, '____decorator__at_sign___'... | {
node.update( node.source().replace( /^async/, '/*__async_token__*/' ) );
} | conditional_block |
plugin.js | var extend = require( 'extend' );
var findParent = require( './find-parent' );
var falafel = require( './falafel-helper' );
var ignore = require( 'esformatter-ignore' );
module.exports = {
setOptions: function ( opts ) {
var me = this;
opts = opts || { };
me.opts = opts;
var jsxOptions = opts.jsx |... | if ( !me.jsxOptions.formatJSX ) {
return code;
}
me._ignore = me._ignore || [ ];
var _ignore = Object.create( ignore );
me._ignore.push( _ignore );
code = _ignore.stringBefore( code );
me._staticProps = me._staticProps || [ ];
var staticProps = [ ];
var ast = falafel( code... | var jsxElements = [ ];
| random_line_split |
regress-441477-01.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */
var gTestfile = 'regress-441477-01... | ()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
try
{
for (i = 0; i < 5;)
{
if (i > 5)
throw "bad";
i++;
continue;
}
}
catch(ex)
{
actual = ex + '';
}
reportCompare(expect, actual, summary);
exitFunc ('test');
}
| test | identifier_name |
regress-441477-01.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */
var gTestfile = 'regress-441477-01... |
exitFunc ('test');
}
| {
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
try
{
for (i = 0; i < 5;)
{
if (i > 5)
throw "bad";
i++;
continue;
}
}
catch(ex)
{
actual = ex + '';
}
reportCompare(expect, actual, summary); | identifier_body |
regress-441477-01.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */
var gTestfile = 'regress-441477-01... | function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
try
{
for (i = 0; i < 5;)
{
if (i > 5)
throw "bad";
i++;
continue;
}
}
catch(ex)
{
actual = ex + '';
}
reportCompare(expect, actual, summary);
exitFunc ('test'... | random_line_split | |
model.tsx | import { safeDump } from 'js-yaml';
import { find, omit } from 'lodash';
import { app } from 'mobx-app';
import { inject, observer } from 'mobx-react';
import React from 'react';
import Button from '../../../components/Button';
import Container from '../../../components/Container';
import Header from '../../../componen... | headTitle="dashboard / models"
/>
<Container>
<Section>
<Button appearance="default" onClick={exportModel(model)}>Get YAML file</Button>
<pre>{JSON.stringify(model, null, 2)}</pre>
</Section>
</Container>
</React.Fragment>
);
}));
const exportModel = (json) => () => {
const yaml = sa... | random_line_split | |
fablib.py | ? (or hit Ctrl-C to exit)',
default=default_branch, validate=validate_branch)
def check_for_local_changes():
""" check if there are local changes on the remote server """
require('repo_type', 'vcs_root_dir', provided_by=env.valid_envs)
status_cmd = {
'svn': 'svn status --quiet'... | if not files.exists(target_path):
sudo_or_run('ln -s %s %s' % (source_file, target_path)) | identifier_body | |
fablib.py | host)
downtime_start = datetime.now()
link_webserver_conf(maintenance=True)
with settings(warn_only=True):
webserver_cmd('reload')
next_to_current_to_rollback()
# Use tasks.py deploy:env to actually do the deployment, including
# creating the virtualenv if it thinks it necessary, ignori... | (keep=None):
"""Delete old rollback directories, keeping the last "keep" (default 5)"."""
require('prev_root', provided_by=env.valid_envs)
# the -1 argument ensures one directory per line
prev_versions = run('ls -1 ' + env.prev_root).split('\n')
if keep is None:
if 'versions_to_keep' in env:... | delete_old_rollback_versions | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.