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 |
|---|---|---|---|---|
server.js | 'use strict';
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('questions', ['questions']);
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStrategy = requi... |
//LOG IN AND SIGN UP ROUTES
app.post('/login', passport.authenticate('local'), function(req, res){
console.log(req.user);
res.json(req.user);
});
app.get('/currentuser',isAuthenticated,function(req,res){
res.json(req.user);
});
app.post('/signup',function(req,res){
var u = new User();
u.userna... | {
if(req.isAuthenticated()){
return next();
}
res.send(401);
} | identifier_body |
server.js | 'use strict';
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('questions', ['questions']);
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStrategy = requi... | (req,res,next){
if(req.isAuthenticated()){
return next();
}
res.send(401);
}
//LOG IN AND SIGN UP ROUTES
app.post('/login', passport.authenticate('local'), function(req, res){
console.log(req.user);
res.json(req.user);
});
app.get('/currentuser',isAuthenticated,function(req,res){
r... | isAuthenticated | identifier_name |
server.js | 'use strict';
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('questions', ['questions']);
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStrategy = requi... | });
});
//CHECK IF AUTHENTICATED
function isAuthenticated(req,res,next){
if(req.isAuthenticated()){
return next();
}
res.send(401);
}
//LOG IN AND SIGN UP ROUTES
app.post('/login', passport.authenticate('local'), function(req, res){
console.log(req.user);
res.json(req.user);
});
ap... | random_line_split | |
test428.js | if (typeof exports === 'object') {
var assert = require('assert');
var alasql = require('..');
}
/*
Test for issue #379
*/
var test = 428;
describe('Test ' + test + ' UUID()', function () {
before(function () {
alasql('CREATE DATABASE test' + test + ';USE test' + test);
});
| after(function () {
alasql('DROP DATABASE test' + test);
});
it('1. Simple test GUID', function (done) {
var res = alasql('=UUID()');
assert(
!!res.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)
);
done();
});
it('2. DEFAULT GUID', function (done) {
alasql('CRE... | random_line_split | |
test428.js | if (typeof exports === 'object') |
/*
Test for issue #379
*/
var test = 428;
describe('Test ' + test + ' UUID()', function () {
before(function () {
alasql('CREATE DATABASE test' + test + ';USE test' + test);
});
after(function () {
alasql('DROP DATABASE test' + test);
});
it('1. Simple test GUID', function (done) {
var res = alasql('... | {
var assert = require('assert');
var alasql = require('..');
} | conditional_block |
LabFourCoin.ts | "use strict";
import { IEventDispatcher, EventDispatcher, EventCallback, EventArgs } from '../engine/events/EventDispatcher';
import { DisplayObject } from '../engine/display/DisplayObject';
import { Sprite } from '../engine/display/Sprite';
import { ArrayList } from '../engine/util/ArrayList';
import { applyMixins } ... |
}
}
// implemented by EventDispatcher mixin
addEventListener : (type : string, callback : EventCallback) => void;
removeEventListener : (type : string, callback : EventCallback) => void;
hasEventListener : (type : string, callback : EventCallback) => boolean;
protected initDispatcher : () => void;
p... | {
this.visible = false;
this.dispatchEvent(new LabFourCoinEventArgs(true));
} | conditional_block |
LabFourCoin.ts | "use strict";
import { IEventDispatcher, EventDispatcher, EventCallback, EventArgs } from '../engine/events/EventDispatcher';
import { DisplayObject } from '../engine/display/DisplayObject';
import { Sprite } from '../engine/display/Sprite';
import { ArrayList } from '../engine/util/ArrayList';
import { applyMixins } ... | extends Sprite implements IEventDispatcher {
constructor(id : string, filename : string) {
super(id, filename);
this.initDispatcher();
}
/** Contrived method for checking collision and dispatching event */
checkIfHitAndDisappear(obj : DisplayObject) : void {
if (this.visible) {
if (obj.x + o... | LabFourCoin | identifier_name |
LabFourCoin.ts | "use strict";
import { IEventDispatcher, EventDispatcher, EventCallback, EventArgs } from '../engine/events/EventDispatcher';
import { DisplayObject } from '../engine/display/DisplayObject';
import { Sprite } from '../engine/display/Sprite';
import { ArrayList } from '../engine/util/ArrayList';
import { applyMixins } ... | this.visible = false;
this.dispatchEvent(new LabFourCoinEventArgs(true));
}
}
}
// implemented by EventDispatcher mixin
addEventListener : (type : string, callback : EventCallback) => void;
removeEventListener : (type : string, callback : EventCallback) => void;
hasEventListener : (... | if (this.visible) {
if (obj.x + obj.width * (1 - obj.pivotPoint.x) > this.x - this.width * (this.pivotPoint.x)
&& obj.x - obj.width * (obj.pivotPoint.x) < this.x + this.width * (1 - this.pivotPoint.x)
&& obj.y + obj.height * (1 - obj.pivotPoint.y) > this.y - this.height * (this.pivotPoint.y)
... | random_line_split |
LabFourCoin.ts | "use strict";
import { IEventDispatcher, EventDispatcher, EventCallback, EventArgs } from '../engine/events/EventDispatcher';
import { DisplayObject } from '../engine/display/DisplayObject';
import { Sprite } from '../engine/display/Sprite';
import { ArrayList } from '../engine/util/ArrayList';
import { applyMixins } ... |
/** Contrived method for checking collision and dispatching event */
checkIfHitAndDisappear(obj : DisplayObject) : void {
if (this.visible) {
if (obj.x + obj.width * (1 - obj.pivotPoint.x) > this.x - this.width * (this.pivotPoint.x)
&& obj.x - obj.width * (obj.pivotPoint.x) < this.x + this.width... | {
super(id, filename);
this.initDispatcher();
} | identifier_body |
__init__.py | # Copyright 2015 The TensorFlow 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 applica... |
else:
# V1 initializers.
v1_objs = {
'Constant': tf.compat.v1.constant_initializer,
'GlorotNormal': tf.compat.v1.glorot_normal_initializer,
'GlorotUniform': tf.compat.v1.glorot_uniform_initializer,
'Identity': tf.compat.v1.initializers.identity,
'Ones': tf.compat.v1.on... | v2_objs = {}
base_cls = initializers_v2.Initializer
generic_utils.populate_dict_with_module_objects(
v2_objs,
[initializers_v2],
obj_filter=lambda x: inspect.isclass(x) and issubclass(x, base_cls))
for key, value in v2_objs.items():
LOCAL.ALL_OBJECTS[key] = value
# Functi... | conditional_block |
__init__.py | # Copyright 2015 The TensorFlow 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 applica... | LOCAL.ALL_OBJECTS['HeUniformV2'] = initializers_v2.HeUniform
LOCAL.ALL_OBJECTS['IdentityV2'] = initializers_v2.Identity
LOCAL.ALL_OBJECTS['LecunNormalV2'] = initializers_v2.LecunNormal
LOCAL.ALL_OBJECTS['LecunUniformV2'] = initializers_v2.LecunUniform
LOCAL.ALL_OBJECTS['OnesV2'] = initializers_v2.Ones
LOCAL... | """Populates dict ALL_OBJECTS with every built-in initializer.
"""
global LOCAL
if not hasattr(LOCAL, 'ALL_OBJECTS'):
LOCAL.ALL_OBJECTS = {}
LOCAL.GENERATED_WITH_V2 = None
if LOCAL.ALL_OBJECTS and LOCAL.GENERATED_WITH_V2 == tf.__internal__.tf2.enabled():
# Objects dict is already generated for the ... | identifier_body |
__init__.py | # Copyright 2015 The TensorFlow 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 applica... | ():
"""Populates dict ALL_OBJECTS with every built-in initializer.
"""
global LOCAL
if not hasattr(LOCAL, 'ALL_OBJECTS'):
LOCAL.ALL_OBJECTS = {}
LOCAL.GENERATED_WITH_V2 = None
if LOCAL.ALL_OBJECTS and LOCAL.GENERATED_WITH_V2 == tf.__internal__.tf2.enabled():
# Objects dict is already generated fo... | populate_deserializable_objects | identifier_name |
__init__.py | # Copyright 2015 The TensorFlow 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 applica... |
import tensorflow.compat.v2 as tf
import threading
from tensorflow.python import tf2
from keras.initializers import initializers_v1
from keras.initializers import initializers_v2
from keras.utils import generic_utils
from keras.utils import tf_inspect as inspect
from tensorflow.python.ops import init_ops
from tensor... | # ==============================================================================
"""Keras initializer serialization / deserialization.""" | random_line_split |
Terminal.d.ts | import { SubConfig } from './SubConfig';
export interface Terminal {
/**
* Display the user an error message
*
* @param {(string | Error)} err
*
* @memberOf Terminal
*/
error(err: string | Error): void;
/**
* Display debug information to the user. Is automatically ignored if the config.debu... | render(): void;
} | *
* @memberOf Terminal
*/ | random_line_split |
main.js | container_interval_id = 0;
password_interval_id = 0;
distro_image = 'ubuntu.svg';
// Shows a message
// Leave text empty to hide message
// error is a boolean deciding whether or not to add an error class
function | (text, error) {
var message = document.getElementById('message');
message.innerHTML = text;
message.className = text ? (error ? 'error' : '') : 'hidden';
}
// Shows an error
function show_error(text) {
message(text, true);
// Stop the script on error
throw new Error();
}
// Center the main... | message | identifier_name |
main.js | container_interval_id = 0;
password_interval_id = 0;
distro_image = 'ubuntu.svg';
// Shows a message
// Leave text empty to hide message
// error is a boolean deciding whether or not to add an error class
function message(text, error) {
var message = document.getElementById('message');
message.innerHT... | };
el.appendChild(node);
}
if (lightdm.can_shutdown) {
var node = document.createElement('a');
node.className = 'iconic x';
node.onclick = function(e) {
lightdm.shutdown();
e.stopPropagation();
e.preventDefault(true);
... | lightdm.restart();
e.stopPropagation();
e.preventDefault(true);
return false;
| random_line_split |
main.js | container_interval_id = 0;
password_interval_id = 0;
distro_image = 'ubuntu.svg';
// Shows a message
// Leave text empty to hide message
// error is a boolean deciding whether or not to add an error class
function message(text, error) {
var message = document.getElementById('message');
message.innerHT... | else{
document.getElementById('password').focus();
}
}
// Initializes the script
(function initialize() {
// Center container initially
centerContainer();
// Center container again on container resize
centerContainerOnResize();
// Update elements that contain informations like time, d... | {
user.focus();
} | conditional_block |
main.js | container_interval_id = 0;
password_interval_id = 0;
distro_image = 'ubuntu.svg';
// Shows a message
// Leave text empty to hide message
// error is a boolean deciding whether or not to add an error class
function message(text, error) {
var message = document.getElementById('message');
message.innerHT... | lightdm.restart();
e.stopPropagation();
e.preventDefault(true);
return false;
};
el.appendChild(node);
}
if (lightdm.can_shutdown) {
var node = document.createElement('a');
node.className = 'iconic x';
node.oncli... | {
var el = document.getElementById('actions-inner');
el.innerHTML = '';
if (lightdm.can_suspend) {
var node = document.createElement('a');
node.className = 'iconic moon_fill';
node.onclick = function(e) {
lightdm.suspend();
e.stopPropagation();
... | identifier_body |
local-pizza.js | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalPizza = (props) => (
<SvgIcon {...props}>
<path d="M12 2C8.43 2 5.23 3.54 3.01 6L12 22l8.99-16C18.78 3.55 15.57 2 12 2zM7 7c0-1.1.9-2 2-2s2 .9 2 2-.9 2-2 2-2-.9-2-2zm5 8c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2... | export default MapsLocalPizza; | MapsLocalPizza = pure(MapsLocalPizza);
MapsLocalPizza.displayName = 'MapsLocalPizza';
MapsLocalPizza.muiName = 'SvgIcon';
| random_line_split |
train.py | import os
import json
import tensorflow as tf
import numpy as np
def | (taxonomy):
data_list= list(filter(lambda x:x[-3:]=='npy', os.listdir(taxonomy)))
result=[]
for data_file in data_list:
result.append(np.load('%s/%s' %(taxonomy, data_file)))
if len(result)%1000== 0:
print("%s: %d/%d" %(taxonomy, len(result), len(data_list)))
return np.array(result, dtype='f')
def train(st... | load_data | identifier_name |
train.py | import os
import json
import tensorflow as tf
import numpy as np
def load_data(taxonomy):
data_list= list(filter(lambda x:x[-3:]=='npy', os.listdir(taxonomy)))
result=[]
for data_file in data_list:
result.append(np.load('%s/%s' %(taxonomy, data_file)))
if len(result)%1000== 0:
print("%s: %d/%d" %(taxonomy, l... | y_train= []
x_val= np.concatenate((archaea_val, bacteria_val, protozoa_val, fungi_val), axis=0)
y_val= []
for i in range(len(archaea_train)):
y_train.append([0])
for i in range(len(bacteria_train)):
y_train.append([1])
for i in range(len(protozoa_train)):
y_train.append([2])
for i in range(len(fungi_train)... | archaea_data= load_data('archaea')
bacteria_data= load_data('bacteria')
protozoa_data= load_data('protozoa')
fungi_data= load_data('fungi')
val_len= int(min(len(archaea_data), len(bacteria_data), len(protozoa_data), len(fungi_data))/3)
print('Using %d data for validating each taxonomy' %(val_len))
archaea_trai... | identifier_body |
train.py | import os
import json
import tensorflow as tf
import numpy as np
def load_data(taxonomy):
data_list= list(filter(lambda x:x[-3:]=='npy', os.listdir(taxonomy)))
result=[]
for data_file in data_list:
result.append(np.load('%s/%s' %(taxonomy, data_file)))
if len(result)%1000== 0:
print("%s: %d/%d" %(taxonomy, l... | y_train.append([0])
for i in range(len(bacteria_train)):
y_train.append([1])
for i in range(len(protozoa_train)):
y_train.append([2])
for i in range(len(fungi_train)):
y_train.append([3])
y_train= np.array(y_train)
for i in range(len(archaea_val)):
y_val.append([0])
for i in range(len(bacteria_val)):
... | for i in range(len(archaea_train)): | random_line_split |
train.py | import os
import json
import tensorflow as tf
import numpy as np
def load_data(taxonomy):
data_list= list(filter(lambda x:x[-3:]=='npy', os.listdir(taxonomy)))
result=[]
for data_file in data_list:
|
return np.array(result, dtype='f')
def train(steps=10000):
archaea_data= load_data('archaea')
bacteria_data= load_data('bacteria')
protozoa_data= load_data('protozoa')
fungi_data= load_data('fungi')
val_len= int(min(len(archaea_data), len(bacteria_data), len(protozoa_data), len(fungi_data))/3)
print('Using ... | result.append(np.load('%s/%s' %(taxonomy, data_file)))
if len(result)%1000== 0:
print("%s: %d/%d" %(taxonomy, len(result), len(data_list))) | conditional_block |
quick-ignore.js | /* you know the drill
open up the browser console (ctrl + shift + i) and paste everything you see here, even comments if you want.
usage: click a user ID and the ignore command will show up. click the id again to hide the command. simple stuff
have fun
*/
if (location.hostname == 'www.999dice.com') {
$('head').appe... | $(document).on('click', '.ChatUserID', function () {
if ($(this).hasClass('shows-ignore')){
$('.toremove').remove(); $(this).removeClass('shows-ignore'); } else
{ $(this).addClass('shows-ignore');
moron = nameCalling[Math.floor( Math.random() * nameCalling.length )];
$(this).append('<span class="... | random_line_split | |
quick-ignore.js | /* you know the drill
open up the browser console (ctrl + shift + i) and paste everything you see here, even comments if you want.
usage: click a user ID and the ignore command will show up. click the id again to hide the command. simple stuff
have fun
*/
if (location.hostname == 'www.999dice.com') {
$('head').appe... |
}).on('click', '.ChatUserID-ignore', function () {
parent = ($(this).closest('p'));
$('#ChatTabText').val('/ignore ' + parent.attr('data-accountid'));
$('#ChatTabSendButton').click();
});
}
| { $(this).addClass('shows-ignore');
moron = nameCalling[Math.floor( Math.random() * nameCalling.length )];
$(this).append('<span class="toremove">- <span class="ChatUserID-ignore">Ignore this '+ moron +'</span> </span>'); } | conditional_block |
index.js | /**
* @file
* @copyright 2020 Aleksej Komarov
* @license MIT
*/
// Themes
import './styles/main.scss';
import './styles/themes/abductor.scss';
import './styles/themes/cardtable.scss';
import './styles/themes/hackerman.scss';
import './styles/themes/malfunction.scss';
import './styles/themes/neutral.scss';
import '... |
window.update(msg);
}
// Enable hot module reloading
if (module.hot) {
setupHotReloading();
module.hot.accept([
'./components',
'./debug',
'./layouts',
'./routes',
], () => {
renderApp();
});
}
};
setupApp();
| {
break;
} | conditional_block |
index.js | /**
* @file
* @copyright 2020 Aleksej Komarov
* @license MIT
*/
// Themes
import './styles/main.scss';
import './styles/themes/abductor.scss';
import './styles/themes/cardtable.scss';
import './styles/themes/hackerman.scss';
import './styles/themes/malfunction.scss';
import './styles/themes/neutral.scss';
import '... | const setupApp = () => {
// Delay setup
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', setupApp);
return;
}
setupGlobalEvents();
setupHotKeys();
captureExternalLinks();
// Subscribe for state updates
store.subscribe(renderApp);
// Dispatch incoming me... | </StoreProvider>
);
});
| random_line_split |
borrowck-move-out-of-tuple-struct-with-dtor.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 ... | match S("foo".to_owned()) {
S(_s) => {}
//~^ ERROR cannot move out of type `S`, which defines the `Drop` trait
}
}
fn move_in_let() {
let S(_s) = S("foo".to_owned());
//~^ ERROR cannot move out of type `S`, which defines the `Drop` trait
}
fn move_in_fn_arg(S(_s): S) {
//~^ ERROR c... | }
fn move_in_match() { | random_line_split |
borrowck-move-out-of-tuple-struct-with-dtor.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 ... | (&mut self) { }
}
fn move_in_match() {
match S("foo".to_owned()) {
S(_s) => {}
//~^ ERROR cannot move out of type `S`, which defines the `Drop` trait
}
}
fn move_in_let() {
let S(_s) = S("foo".to_owned());
//~^ ERROR cannot move out of type `S`, which defines the `Drop` trait
}
fn mov... | drop | identifier_name |
borrowck-move-out-of-tuple-struct-with-dtor.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 | |
dataViewObjectDescriptor.ts | /*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ""Software""), to deal
* in the Software without restrict... | propertyName: propertyName,
};
}
}
}
}
}
} | return {
objectName: objectName, | random_line_split |
dataViewObjectDescriptor.ts | /*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ""Software""), to deal
* in the Software without restrict... |
/** Attempts to find the self filter enabled property. */
export function findSelfFilterEnabled(descriptors: DataViewObjectDescriptors): DataViewObjectPropertyIdentifier {
return findProperty(
descriptors,
(propDesc: DataViewObjectPropertyDescriptor) => {
... | {
return findProperty(
descriptors,
(propDesc: DataViewObjectPropertyDescriptor) => {
let propType: StructuralTypeDescriptor = propDesc.type;
return propType && propType.filter && propType.filter.selfFilter;
});
... | identifier_body |
dataViewObjectDescriptor.ts | /*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ""Software""), to deal
* in the Software without restrict... | (descriptors: DataViewObjectDescriptors, propPredicate: (propDesc: DataViewObjectPropertyDescriptor) => boolean): DataViewObjectPropertyIdentifier {
debug.assertAnyValue(descriptors, 'descriptors');
debug.assertAnyValue(propPredicate, 'propPredicate');
if (!descriptors)
... | findProperty | identifier_name |
getManager.js | import getURL from '../utils/getURL.js'
import getUserInfo from './getUserInfo.js'
import people from './people.js'
/**
@name $SP().getManager
@function
@category people
@description Return the manager for the provided user, as a People string
@param {String} [username] With or without the domain, and you c... | }
}
| {
try {
if (arguments.length===1 && typeof username === "object") { setup=username; username="" }
// default values
username = (username || "");
setup = setup || {};
if (!setup.url) {
setup.url = await getURL.call(this);
}
let pres = await people.call(this, username, setup);
let... | identifier_body |
getManager.js | import getURL from '../utils/getURL.js'
import getUserInfo from './getUserInfo.js'
import people from './people.js'
/**
@name $SP().getManager
@function
@category people
@description Return the manager for the provided user, as a People string
@param {String} [username] With or without the domain, and you c... | (username, setup) {
try {
if (arguments.length===1 && typeof username === "object") { setup=username; username="" }
// default values
username = (username || "");
setup = setup || {};
if (!setup.url) {
setup.url = await getURL.call(this);
}
let pres = await people.call(this, usernam... | getManager | identifier_name |
getManager.js | import getURL from '../utils/getURL.js'
import getUserInfo from './getUserInfo.js'
import people from './people.js'
/**
@name $SP().getManager
@function
@category people
@description Return the manager for the provided user, as a People string
@param {String} [username] With or without the domain, and you c... | return Promise.resolve(res.ID+";#"+displayName+",#"+managerUserName+",#"+res.Email+",#"+res.Email+",#"+displayName);
} catch(err) {
return Promise.reject(err);
}
} | if (!managerUserName.startsWith('i:0')) managerUserName = "i:0#.w|" + managerUserName;
let res = await getUserInfo.call(this, managerUserName, setup);
// "42;#Doe,, John,#i:0#.w|domain\John_Doe,#John_Doe@Domain.com,#John_Doe@Domain.com,#Doe,, John
let displayName = res.Name.replace(/,/,",,"); | random_line_split |
getManager.js | import getURL from '../utils/getURL.js'
import getUserInfo from './getUserInfo.js'
import people from './people.js'
/**
@name $SP().getManager
@function
@category people
@description Return the manager for the provided user, as a People string
@param {String} [username] With or without the domain, and you c... |
let pres = await people.call(this, username, setup);
let managerUserName = pres.Manager;
if (!managerUserName.startsWith('i:0')) managerUserName = "i:0#.w|" + managerUserName;
let res = await getUserInfo.call(this, managerUserName, setup);
// "42;#Doe,, John,#i:0#.w|domain\John_Doe,#John_Doe@Doma... | {
setup.url = await getURL.call(this);
} | conditional_block |
mediawiki.py | """
Custom Authenticator to use MediaWiki OAuth with JupyterHub
Requires `mwoauth` package.
"""
import json
import os
from asyncio import wrap_future
from concurrent.futures import ThreadPoolExecutor
from jupyterhub.handlers import BaseHandler
from jupyterhub.utils import url_path_join
from mwoauth import ConsumerTok... | (self):
consumer_token = ConsumerToken(
self.authenticator.client_id,
self.authenticator.client_secret,
)
handshaker = Handshaker(self.authenticator.mw_index_url, consumer_token)
redirect, request_token = await wrap_future(
self.authenticator.executo... | get | identifier_name |
mediawiki.py | """
Custom Authenticator to use MediaWiki OAuth with JupyterHub
Requires `mwoauth` package.
"""
import json
import os
from asyncio import wrap_future
from concurrent.futures import ThreadPoolExecutor
from jupyterhub.handlers import BaseHandler
from jupyterhub.utils import url_path_join
from mwoauth import ConsumerTok... |
class MWLoginHandler(BaseHandler):
async def get(self):
consumer_token = ConsumerToken(
self.authenticator.client_id,
self.authenticator.client_secret,
)
handshaker = Handshaker(self.authenticator.mw_index_url, consumer_token)
redirect, request_token = aw... | key, secret = json.loads(js)
return RequestToken(key, secret) | identifier_body |
mediawiki.py | """
Custom Authenticator to use MediaWiki OAuth with JupyterHub
Requires `mwoauth` package.
"""
import json
import os
from asyncio import wrap_future
from concurrent.futures import ThreadPoolExecutor
from jupyterhub.handlers import BaseHandler
from jupyterhub.utils import url_path_join
from mwoauth import ConsumerTok... | def get_state_url(self):
return None
class MWOAuthenticator(OAuthenticator):
login_service = 'MediaWiki'
login_handler = MWLoginHandler
callback_handler = MWCallbackHandler
mw_index_url = Unicode(
os.environ.get('MW_INDEX_URL', 'https://meta.wikimedia.org/w/index.php'),
co... | pass
| random_line_split |
mediawiki.py | """
Custom Authenticator to use MediaWiki OAuth with JupyterHub
Requires `mwoauth` package.
"""
import json
import os
from asyncio import wrap_future
from concurrent.futures import ThreadPoolExecutor
from jupyterhub.handlers import BaseHandler
from jupyterhub.utils import url_path_join
from mwoauth import ConsumerTok... | self.log.error("No username found in %s", identity) | conditional_block | |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import os
os.system('cp config/.lircrc ~/.lircrc')
os.system('cp config/hardware.conf /etc/lirc/hardware.conf')
os.system('cp config/lircd.conf /etc/lirc/lircd.conf')
os.system('cp config/lircmd.conf /etc/lirc/lircmd.conf')
os.system('mkdir ... | 'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
],
scripts=['r-controller']
) | random_line_split | |
container.js | import React, { Component } from 'react'
import { connect } from 'react-redux'
import * as actions from './actions'
import Arcade from './Arcade'
class ArcadeContainer extends Component {
constructor(props) {
super(props)
this.state = {time:0, timer: null, startTime: 0}
}
componentDidM... | export default connect(
state => state.arcade,
actions
)(ArcadeContainer) | random_line_split | |
container.js | import React, { Component } from 'react'
import { connect } from 'react-redux'
import * as actions from './actions'
import Arcade from './Arcade'
class ArcadeContainer extends Component {
constructor(props) |
componentDidMount = () =>
this.createTrial()
createTrial = () => {
this.props.createTrial(this.props.level)
this.startTimer()
}
startTimer = () => {
let timer = setInterval(this.updateTimer, 50)
this.setState({timer, time:0, startTime: Date.now()})
}
... | {
super(props)
this.state = {time:0, timer: null, startTime: 0}
} | identifier_body |
container.js | import React, { Component } from 'react'
import { connect } from 'react-redux'
import * as actions from './actions'
import Arcade from './Arcade'
class ArcadeContainer extends Component {
| (props) {
super(props)
this.state = {time:0, timer: null, startTime: 0}
}
componentDidMount = () =>
this.createTrial()
createTrial = () => {
this.props.createTrial(this.props.level)
this.startTimer()
}
startTimer = () => {
let timer = setInterval... | constructor | identifier_name |
jsonSchemaService.ts | RegExpPattern(pattern) + '$');
} catch (e) {
// invalid pattern
this.patternRegExp = null;
}
this.schemas = [];
this.combinedSchema = null;
}
public addSchema(id: string) {
this.schemas.push(id);
this.combinedSchema = null;
}
public matchesPattern(fileName: string) : boolean {
return this.patt... |
this.contributionSchemas = {};
this.contributionAssociations = {};
this.schemasById = {};
this.filePatternAssociations = [];
this.filePatternAssociationById = {};
}
public dispose(): void {
while(this.callOnDispose.length > 0) {
this.callOnDispose.pop()();
}
}
private onResourceChange(e: IResou... | {
this.callOnDispose.push(resourceService.addListener_(ResourceEvents.CHANGED, (e: IResourceChangedEvent) => this.onResourceChange(e)));
} | conditional_block |
jsonSchemaService.ts | RegExpPattern(pattern) + '$');
} catch (e) {
// invalid pattern
this.patternRegExp = null;
}
this.schemas = [];
this.combinedSchema = null;
}
public addSchema(id: string) {
this.schemas.push(id);
this.combinedSchema = null;
}
public matchesPattern(fileName: string) : boolean {
return this.patt... | (uri:string, filePatterns: string[] = null, unresolvedSchemaContent?: IJSONSchema) : ISchemaHandle {
var id = this.normalizeId(uri);
if (filePatterns) {
filePatterns.forEach(pattern => {
this.getOrAddFilePatternAssociation(pattern).addSchema(uri);
});
}
return unresolvedSchemaContent ? this.addSchema... | registerExternalSchema | identifier_name |
jsonSchemaService.ts | RegExpPattern(pattern) + '$');
} catch (e) {
// invalid pattern
this.patternRegExp = null;
}
this.schemas = [];
this.combinedSchema = null;
}
public addSchema(id: string) {
this.schemas.push(id);
this.combinedSchema = null;
}
public matchesPattern(fileName: string) : boolean {
return this.patt... |
private getOrAddSchemaHandle(id:string, unresolvedSchemaContent?: IJSONSchema) : ISchemaHandle {
return this.schemasById[id] || this.addSchemaHandle(id, unresolvedSchemaContent);
}
private getOrAddFilePatternAssociation(pattern: string) {
var fpa = this.filePatternAssociationById[pattern];
if (!fpa) {
fp... | {
var schemaHandle = new SchemaHandle(this, id, unresolvedSchemaContent);
this.schemasById[id] = schemaHandle;
return schemaHandle;
} | identifier_body |
jsonSchemaService.ts | || path.length === 0) {
return schema;
}
var next = path.shift();
if (schema.properties && schema.properties[next]) {
return this.getSectionRecursive(path, schema.properties[next]);
} else if (Types.isObject(schema.patternProperties)) {
Object.keys(schema.patternProperties).forEach((pattern) => {
... | });
}; | random_line_split | |
nib.js |
/*!
* nib
* Copyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var stylus = require('stylus')
, nodes = stylus.nodes
, utils = stylus.utils
, Canvas
exports = module.exports = plugin;
// conditionally expose canvas-based APIs.
try {
Canvas = requir... |
}
}
| {
style.define('has-canvas', nodes.false);
} | conditional_block |
nib.js |
/*!
* nib
* Copyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var stylus = require('stylus')
, nodes = stylus.nodes
, utils = stylus.utils
, Canvas
exports = module.exports = plugin;
// conditionally expose canvas-based APIs.
try {
Canvas = requir... | () {
return function(style){
style.include(__dirname);
if (Canvas) {
style.define('has-canvas', nodes.true);
// gradients
style.define('create-gradient-image', gradient.create)
style.define('gradient-data-uri', gradient.dataURL)
style.define('add-color-stop', gradient.addColorS... | plugin | identifier_name |
nib.js |
/*!
* nib
* Copyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var stylus = require('stylus')
, nodes = stylus.nodes
, utils = stylus.utils
, Canvas
exports = module.exports = plugin;
// conditionally expose canvas-based APIs.
try {
Canvas = requir... | {
return function(style){
style.include(__dirname);
if (Canvas) {
style.define('has-canvas', nodes.true);
// gradients
style.define('create-gradient-image', gradient.create)
style.define('gradient-data-uri', gradient.dataURL)
style.define('add-color-stop', gradient.addColorStop... | identifier_body | |
nib.js | /*!
* nib
* Copyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var stylus = require('stylus')
, nodes = stylus.nodes
, utils = stylus.utils
, Canvas
exports = module.exports = plugin;
// conditionally expose canvas-based APIs.
try {
Canvas = require... |
/**
* Return the plugin callback for stylus.
*
* @return {Function}
* @api public
*/
function plugin() {
return function(style){
style.include(__dirname);
if (Canvas) {
style.define('has-canvas', nodes.true);
// gradients
style.define('create-gradient-image', gradient.create)
... | exports.path = __dirname; | random_line_split |
movie.test.ts | import { IMDb, Movie } from '../src'
describe('Movie', async () => {
// Account for the IMDb loading times
jest.setTimeout(10000)
let movie: Movie
beforeAll(async () => {
movie = await (new IMDb()).getMovie('tt3659388')
})
it('has a title', () => {
expect(movie.getTitle()).toBe('The Martian (201... | it('has director', () => {
expect(movie.getDirector()).toBe('Ridley Scott')
})
it('has metascore', () => {
expect(movie.getMetascore()).toBe(80)
})
it('has writer', () => {
expect(movie.getWriter()).toBe('Drew Goddard')
})
it('has cast', () => {
expect(movie.getCast()).toBeDefined()
}... | })
| random_line_split |
toolbar.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { Location } from '@angular/common';
import { Router, RouterModule, NavigationStart, ActivatedRoute, PRIMARY_OUTLET, Params } from '@angular/router';
import 'rxjs/add/operator/filter';
import { ApplicationState } from '../application-state';
interfac... |
public onNavigateBack() {
const previousCrumb = this.crumbs[this.crumbs.length - 2];
if (previousCrumb) {
this.router.navigateByUrl(previousCrumb.url);
} else {
this.router.navigateByUrl('/');
}
}
public onSearch() {
this.showSearch = !this.showSearch;
}
// private generateCrumbs(event: Naviga... | {
if (this.backUrl) {
this.router.navigateByUrl(this.backUrl);
this.backUrl = '';
} else {
this.router.navigate(['../'], { relativeTo: this.route });
}
// this.router.navigate(['./']);
// this.router.navigateByUrl('./');
// this.router.navigate([this.appState.backUrl]);
// this.location.back();
... | identifier_body |
toolbar.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { Location } from '@angular/common';
import { Router, RouterModule, NavigationStart, ActivatedRoute, PRIMARY_OUTLET, Params } from '@angular/router';
import 'rxjs/add/operator/filter';
import { ApplicationState } from '../application-state';
interfac... |
this.backUrl = config.data.back;
// const root: ActivatedRoute = this.route.root;
// console.log(root);
// this.crumbs = this.generateCrumbs(event);
// console.log(this.crumbs);
});
}
public onGoBack() {
if (this.backUrl) {
this.router.navigateByUrl(this.backUrl);
this.backUrl = '... | {
return;
} | conditional_block |
toolbar.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { Location } from '@angular/common';
import { Router, RouterModule, NavigationStart, ActivatedRoute, PRIMARY_OUTLET, Params } from '@angular/router';
import 'rxjs/add/operator/filter';
import { ApplicationState } from '../application-state';
interfac... | () {
const previousCrumb = this.crumbs[this.crumbs.length - 2];
if (previousCrumb) {
this.router.navigateByUrl(previousCrumb.url);
} else {
this.router.navigateByUrl('/');
}
}
public onSearch() {
this.showSearch = !this.showSearch;
}
// private generateCrumbs(event: NavigationStart): ICrumb[] {
... | onNavigateBack | identifier_name |
toolbar.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { Location } from '@angular/common';
import { Router, RouterModule, NavigationStart, ActivatedRoute, PRIMARY_OUTLET, Params } from '@angular/router';
import 'rxjs/add/operator/filter';
import { ApplicationState } from '../application-state';
interfac... |
@Component({
selector: '[app-toolbar]',
templateUrl: './toolbar.component.html',
styleUrls: ['./toolbar.component.scss']
})
export class ToolbarComponent implements OnInit, OnDestroy {
public version: string;
public module: string;
public moduleName; string;
public child: string;
public childName: string;
pub... | last: boolean;
} | random_line_split |
deactivate.rs | //! `POST /_matrix/client/*/account/deactivate`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3accountdeactivate
use ruma_common::api::ruma_api;
use crate::{
account::ThirdPartyIdRemovalStatus,
uiaa::{AuthData, I... |
#[derive(Default)]
request: {
/// Additional authentication information for the user-interactive authentication API.
#[serde(skip_serializing_if = "Option::is_none")]
pub auth: Option<AuthData<'a>>,
/// Identity server from which to unbind the user's thi... | rate_limited: true,
authentication: AccessToken,
added: 1.0,
} | random_line_split |
deactivate.rs | //! `POST /_matrix/client/*/account/deactivate`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3accountdeactivate
use ruma_common::api::ruma_api;
use crate::{
account::ThirdPartyIdRemovalStatus,
uiaa::{AuthData, I... |
}
}
| {
Self { id_server_unbind_result }
} | identifier_body |
deactivate.rs | //! `POST /_matrix/client/*/account/deactivate`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3accountdeactivate
use ruma_common::api::ruma_api;
use crate::{
account::ThirdPartyIdRemovalStatus,
uiaa::{AuthData, I... | (id_server_unbind_result: ThirdPartyIdRemovalStatus) -> Self {
Self { id_server_unbind_result }
}
}
}
| new | identifier_name |
ThemeSelectors.ts | import { Global } from '@ephox/katamari';
const isSilver = () => {
const tinymce = Global.tinymce;
if (!tinymce) {
throw new Error('Failed to get global tinymce');
}
return tinymce.activeEditor.hasOwnProperty('ui');
};
const isModern = () => !isSilver();
interface ThemeSelectors {
toolBarSelector: stri... | menuBarSelector: '.tox-menubar',
dialogCloseSelector: '.tox-button:contains("Cancel")',
dialogSubmitSelector: '.tox-button:contains("Save")'
};
const getThemeSelectors = (): ThemeSelectors => {
return isModern() ? ModernThemeSelectors : SilverThemeSelectors;
};
export {
getThemeSelectors,
isModern,
isSi... | };
const SilverThemeSelectors: ThemeSelectors = {
toolBarSelector: '.tox-toolbar', | random_line_split |
ThemeSelectors.ts | import { Global } from '@ephox/katamari';
const isSilver = () => {
const tinymce = Global.tinymce;
if (!tinymce) |
return tinymce.activeEditor.hasOwnProperty('ui');
};
const isModern = () => !isSilver();
interface ThemeSelectors {
toolBarSelector: string;
menuBarSelector: string;
dialogCloseSelector: string;
dialogSubmitSelector: string;
}
const ModernThemeSelectors: ThemeSelectors = {
toolBarSelector: '.mce-toolbar... | {
throw new Error('Failed to get global tinymce');
} | conditional_block |
stmt_parse.rs | use std::path::PathBuf;
use syntax_tree::*;
use parser::lexer::lexer_util::lexemes::*;
use parser::syntax_parser::expr_parse::*;
use parser::syntax_parser::synpar_util::*;
use error::{RollerErr, SynErr, ParseResult};
#[allow(unused_variables)]
pub fn parse_stmt(input: InType) -> ParseResult<Stmt> {
Err(())
.or(pars... |
fn parse_run(input: InType) -> ParseResult<Stmt, ()> {
if let Some((&Lexeme::Kw(KwToken::Run), input)) = input.split_first() {
if let Some((&Lexeme::Id(ref s), input)) = input.split_first() {
if input.get(0) == Some(&Lexeme::End) {
return Ok(Stmt::Run(PathBuf::from(s) ));
}
}
}
Err(())
}
fn parse_sa... | {
if input.len() == 2 { // clear, end
if let Lexeme::Kw(KwToken::Clear) = input[0] {
return Ok(Stmt::Clear);
}
}
Err(())
} | identifier_body |
stmt_parse.rs | use std::path::PathBuf;
use syntax_tree::*;
use parser::lexer::lexer_util::lexemes::*;
use parser::syntax_parser::expr_parse::*;
use parser::syntax_parser::synpar_util::*;
use error::{RollerErr, SynErr, ParseResult};
#[allow(unused_variables)]
pub fn parse_stmt(input: InType) -> ParseResult<Stmt> {
Err(())
.or(pars... | if let Some((&Lexeme::Kw(KwToken::Save), input)) = input.split_first() {
if let Some((&Lexeme::Id(ref s), input)) = input.split_first() {
if input.get(0) == Some(&Lexeme::End) {
return Ok(Stmt::Save(PathBuf::from(s) ));
}
}
}
Err(())
} | random_line_split | |
stmt_parse.rs | use std::path::PathBuf;
use syntax_tree::*;
use parser::lexer::lexer_util::lexemes::*;
use parser::syntax_parser::expr_parse::*;
use parser::syntax_parser::synpar_util::*;
use error::{RollerErr, SynErr, ParseResult};
#[allow(unused_variables)]
pub fn | (input: InType) -> ParseResult<Stmt> {
Err(())
.or(parse_assign(input))
.or(parse_fundef(input))
.or(parse_delete(input))
.or(parse_clear(input))
.or(parse_run(input))
.or(parse_save(input))
.or(Err(RollerErr::SyntaxError(SynErr::Unimplemented)))
}
fn parse_assign(input: InType) -> ParseResult<Stmt, ()> {
// ... | parse_stmt | identifier_name |
stmt_parse.rs | use std::path::PathBuf;
use syntax_tree::*;
use parser::lexer::lexer_util::lexemes::*;
use parser::syntax_parser::expr_parse::*;
use parser::syntax_parser::synpar_util::*;
use error::{RollerErr, SynErr, ParseResult};
#[allow(unused_variables)]
pub fn parse_stmt(input: InType) -> ParseResult<Stmt> {
Err(())
.or(pars... |
}
}
Err(())
}
fn parse_fundef(input: InType) -> ParseResult<Stmt, ()> {
if let Some((&Lexeme::Id(ref id), input)) = input.split_first() {
if let Some((&Lexeme::LeftParen, input)) = input.split_first() {
// parse parameters
let mut mut_input = input.clone();
let mut param_ids = Vec::new();
loop {
... | {
return Ok(Stmt::Assign(id.clone(), exp));
} | conditional_block |
messaging.py | import data
PRD = 'prd'
from utils import *
def test_messaging(IndivoClient):
try:
BODY = 'body'
SUBJECT = 'subject'
MSG_ID = 'message_id'
SEVERITY = 'severity'
admin_client = IndivoClient(data.machine_app_email, data.machine_app_secret)
admin_client.set_app_id(data.app_email)
ac... | ():
messages = xpath(parse_xml(chrome_client.account_inbox(account_id = data.account03['account_id'])), "/Messages/Message")
return len(messages)
num_messages_before = num_messages()
message_id = xpath(parse_xml(chrome_client.account_inbox(account_id = data.account03['account_id'])), "/Messages... | num_messages | identifier_name |
messaging.py | import data
PRD = 'prd'
from utils import *
def test_messaging(IndivoClient):
try:
BODY = 'body'
SUBJECT = 'subject'
MSG_ID = 'message_id'
SEVERITY = 'severity'
admin_client = IndivoClient(data.machine_app_email, data.machine_app_secret)
admin_client.set_app_id(data.app_email)
ac... |
#
# check that archival removes one of the messages
#
def num_messages():
messages = xpath(parse_xml(chrome_client.account_inbox(account_id = data.account03['account_id'])), "/Messages/Message")
return len(messages)
num_messages_before = num_messages()
message_id = xpath(par... | user_client.set_app_id(data.app_email)
user_client.get_messages(record_id = record_id)
chrome_client = IndivoClient(data.chrome_consumer_key, data.chrome_consumer_secret)
chrome_client.create_session(data.account03) | random_line_split |
messaging.py | import data
PRD = 'prd'
from utils import *
def test_messaging(IndivoClient):
| data= { SUBJECT : data.message02[SUBJECT],
BODY : data.message02[BODY],
MSG_ID : data.message02[MSG_ID],
SEVERITY : data.message02[SEVERITY]})
token =... | try:
BODY = 'body'
SUBJECT = 'subject'
MSG_ID = 'message_id'
SEVERITY = 'severity'
admin_client = IndivoClient(data.machine_app_email, data.machine_app_secret)
admin_client.set_app_id(data.app_email)
account_id = admin_client.create_account(data.account03)[PRD]['Account'][0]
admin_... | identifier_body |
app.component.ts | import { Component } from '@angular/core';
import { InetOrgPerson,OrgVO,ServiceEvent,Severity } from './model';
import { OrgService } from './org.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app work... |
});
}
onReadPerson( person : InetOrgPerson ):void {
console.log( person.givenName );
let vo = new OrgVO();
vo.person=person;
this.service.readPerson(vo).then( item => {
console.log(item.person.givenName);
if ( item.event == null ){
// OK ... | {
// POPUP ERROR MESSAGE DIALOG ...
} | conditional_block |
app.component.ts | import { Component } from '@angular/core';
import { InetOrgPerson,OrgVO,ServiceEvent,Severity } from './model';
import { OrgService } from './org.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app work... |
onUpdatePerson( person : InetOrgPerson ):void {
console.log( person.givenName );
let vo = new OrgVO();
vo.person=person;
this.service.updatePerson(vo).then( item => {
console.log(item.event);
if ( item.event.status != 200 ){
// OK MESSAGE
this.person = item.per... | {
console.log( person.givenName );
let vo = new OrgVO();
vo.person=person;
this.service.createPerson(vo).then( item => {
console.log(item.event);
this.person = item.person;
});
} | identifier_body |
app.component.ts | import { Component } from '@angular/core';
import { InetOrgPerson,OrgVO,ServiceEvent,Severity } from './model';
import { OrgService } from './org.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app work... |
onCreatePerson( person : InetOrgPerson ):void {
console.log( person.givenName );
let vo = new OrgVO();
vo.person=person;
this.service.createPerson(vo).then( item => {
console.log(item.event);
this.person = item.person;
});
}
onUpdatePerson( person : InetOrgP... | random_line_split | |
app.component.ts | import { Component } from '@angular/core';
import { InetOrgPerson,OrgVO,ServiceEvent,Severity } from './model';
import { OrgService } from './org.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app work... | ( person : InetOrgPerson ):void {
console.log( person.givenName );
let vo = new OrgVO();
vo.person=person;
this.service.updatePerson(vo).then( item => {
console.log(item.event);
if ( item.event.status != 200 ){
// OK MESSAGE
this.person = item.person;
}... | onUpdatePerson | identifier_name |
Modal.tsx | import * as React from "react";
import * as ReactDOM from "react-dom";
import { CloseStrokeIcon } from "brave-ui/components/icons";
import {
Background,
CloseIcon,
Container,
ExtraSmallContainer,
LargeContainer,
MediumContainer,
ModalDiv,
PaddingContainer,
Section,
SmallContainer,
} from "./ModalSt... | (props) {
super(props);
this.el = document.createElement("div");
}
public componentDidMount() {
this.modalRoot.appendChild(this.el);
}
public componentWillUnmount() {
this.modalRoot.removeChild(this.el);
}
public componentDidUpdate() {
// Allow users to press escape to close modal
... | constructor | identifier_name |
Modal.tsx | import * as React from "react";
import * as ReactDOM from "react-dom";
import { CloseStrokeIcon } from "brave-ui/components/icons";
import {
Background,
CloseIcon,
Container,
ExtraSmallContainer,
LargeContainer,
MediumContainer,
ModalDiv,
PaddingContainer,
Section,
SmallContainer,
} from "./ModalSt... |
public escFunction = event => {
if (event.keyCode === 27) {
this.props.handleClose();
}
};
public render() {
const childElements = (
<PaddingContainer padding={this.props.padding}>
<CloseIcon>
<CloseStrokeIcon onClick={this.props.handleClose} />
</CloseIcon>
... | {
// Allow users to press escape to close modal
if (this.props.show) {
document.addEventListener("keydown", this.escFunction, false);
} else {
document.removeEventListener("keydown", this.escFunction, false);
}
} | identifier_body |
Modal.tsx | import * as React from "react";
import * as ReactDOM from "react-dom";
import { CloseStrokeIcon } from "brave-ui/components/icons";
import {
Background,
CloseIcon,
Container,
ExtraSmallContainer,
LargeContainer,
MediumContainer,
ModalDiv,
PaddingContainer,
Section,
SmallContainer,
} from "./ModalSt... | public componentDidUpdate() {
// Allow users to press escape to close modal
if (this.props.show) {
document.addEventListener("keydown", this.escFunction, false);
} else {
document.removeEventListener("keydown", this.escFunction, false);
}
}
public escFunction = event => {
if (even... | }
| random_line_split |
Modal.tsx | import * as React from "react";
import * as ReactDOM from "react-dom";
import { CloseStrokeIcon } from "brave-ui/components/icons";
import {
Background,
CloseIcon,
Container,
ExtraSmallContainer,
LargeContainer,
MediumContainer,
ModalDiv,
PaddingContainer,
Section,
SmallContainer,
} from "./ModalSt... |
}
public escFunction = event => {
if (event.keyCode === 27) {
this.props.handleClose();
}
};
public render() {
const childElements = (
<PaddingContainer padding={this.props.padding}>
<CloseIcon>
<CloseStrokeIcon onClick={this.props.handleClose} />
</CloseIcon... | {
document.removeEventListener("keydown", this.escFunction, false);
} | conditional_block |
headless_window.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 https://mozilla.org/MPL/2.0/. */
//! A headless window implementation.
use crate::window_trait::WindowPortsMethods;
use glutin;
use euclid::{defa... |
}
pub struct Window {
context: HeadlessContext,
animation_state: Cell<AnimationState>,
fullscreen: Cell<bool>,
gl: Rc<dyn gl::Gl>,
}
impl Window {
pub fn new(size: Size2D<u32, DeviceIndependentPixel>) -> Rc<dyn WindowPortsMethods> {
let context = HeadlessContext::new(size.width, size.heig... | {
ptr::null() as *const _
} | identifier_body |
headless_window.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 https://mozilla.org/MPL/2.0/. */
//! A headless window implementation.
use crate::window_trait::WindowPortsMethods;
use glutin;
use euclid::{defa... | (s: &str) -> *const c_void {
let c_str = CString::new(s).expect("Unable to create CString");
unsafe { mem::transmute(osmesa_sys::OSMesaGetProcAddress(c_str.as_ptr())) }
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn get_proc_address(_: &str) -> *const c_void {
ptr::... | get_proc_address | identifier_name |
headless_window.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 https://mozilla.org/MPL/2.0/. */
//! A headless window implementation.
use crate::window_trait::WindowPortsMethods;
use glutin;
use euclid::{defa... |
fn servo_hidpi_factor(&self) -> Scale<f32, DeviceIndependentPixel, DevicePixel> {
match opts::get().device_pixels_per_px {
Some(device_pixels_per_px) => Scale::new(device_pixels_per_px),
_ => Scale::new(1.0),
}
}
}
impl WindowPortsMethods for Window {
fn get_events(... |
Rc::new(window)
} | random_line_split |
completionForStringLiteralNonrelativeImport4.ts | /// <reference path='fourslash.ts' /> | //// import * as foo1 from "f/*import_as0*/
//// import foo4 = require("f/*import_equals0*/
//// var foo7 = require("f/*require0*/
// @Filename: package.json
//// { "dependencies": { "fake-module": "latest" } }
// @Filename: node_modules/fake-module/ts.ts
////
// @Filename: dir1/package.json
//// { "dependencies": { ... |
// Should give completions for all node modules visible to the script
// @Filename: dir1/dir2/dir3/dir4/test0.ts | random_line_split |
borrowck-assign-comp-idx.rs | // Copyright 2012 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 | |
borrowck-assign-comp-idx.rs | // Copyright 2012 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 ... | fn main() {
} | }
| random_line_split |
borrowck-assign-comp-idx.rs | // Copyright 2012 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 ... | <F>(_x: &[isize], _f: F) where F: FnOnce() {}
fn b() {
// here we alias the mutable vector into an imm slice and try to
// modify the original:
let mut p = vec![1];
borrow(
&p,
|| p[0] = 5); //~ ERROR cannot borrow `p` as mutable
}
fn c() {
// Legal because the scope of the borro... | borrow | identifier_name |
navigator.webProfile.js | (function(){ | var worker = new ProtocolWorker('web+profile');
navigator.webProfile = {
registerProvider: function(name, uri){
navigator.registerProtocolHandler('web+profile', uri + '?%s', name);
},
getID: function(){
return worker.request({ action: 'get:id' }).then(function(response){
navigator.w... | random_line_split | |
objc_protocol_inheritance.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#![cfg(target_os = "macos")]
#[macro_use]
extern crate objc;
#[allow(non_camel_case_types)]
pub type id = *mut objc::runtime::Object;
pub trait PFoo: Sized + std::ops::Deref {}
#[repr(transparent)]
#[derive(Clone)]
pub... | fn deref(&self) -> &Self::Target {
unsafe { &*self.0 }
}
}
unsafe impl objc::Message for Foo {}
impl Foo {
pub fn alloc() -> Self {
Self(unsafe { msg_send!(objc::class!(Foo), alloc) })
}
}
impl PFoo for Foo {}
impl IFoo for Foo {}
pub trait IFoo: Sized + std::ops::Deref {}
#[repr(transpa... | impl std::ops::Deref for Foo {
type Target = objc::runtime::Object; | random_line_split |
objc_protocol_inheritance.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#![cfg(target_os = "macos")]
#[macro_use]
extern crate objc;
#[allow(non_camel_case_types)]
pub type id = *mut objc::runtime::Object;
pub trait PFoo: Sized + std::ops::Deref {}
#[repr(transparent)]
#[derive(Clone)]
pub... |
}
unsafe impl objc::Message for Foo {}
impl Foo {
pub fn alloc() -> Self {
Self(unsafe { msg_send!(objc::class!(Foo), alloc) })
}
}
impl PFoo for Foo {}
impl IFoo for Foo {}
pub trait IFoo: Sized + std::ops::Deref {}
#[repr(transparent)]
#[derive(Clone)]
pub struct Bar(pub id);
impl std::ops::Deref for... | {
unsafe { &*self.0 }
} | identifier_body |
objc_protocol_inheritance.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#![cfg(target_os = "macos")]
#[macro_use]
extern crate objc;
#[allow(non_camel_case_types)]
pub type id = *mut objc::runtime::Object;
pub trait PFoo: Sized + std::ops::Deref {}
#[repr(transparent)]
#[derive(Clone)]
pub... | (pub id);
impl std::ops::Deref for Bar {
type Target = objc::runtime::Object;
fn deref(&self) -> &Self::Target {
unsafe { &*self.0 }
}
}
unsafe impl objc::Message for Bar {}
impl Bar {
pub fn alloc() -> Self {
Self(unsafe { msg_send!(objc::class!(Bar), alloc) })
}
}
impl IFoo for Bar... | Bar | identifier_name |
objc_protocol_inheritance.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#![cfg(target_os = "macos")]
#[macro_use]
extern crate objc;
#[allow(non_camel_case_types)]
pub type id = *mut objc::runtime::Object;
pub trait PFoo: Sized + std::ops::Deref {}
#[repr(transparent)]
#[derive(Clone)]
pub... | else {
Err("This Foo cannot be downcasted to Bar")
}
}
}
impl IBar for Bar {}
pub trait IBar: Sized + std::ops::Deref {}
| {
Ok(Bar(parent.0))
} | conditional_block |
regions-implied-bounds-projection-gap-2.rs | // Copyright 2012 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 ... | #![allow(unused_variables)]
trait Trait1<'x> {
type Foo;
}
// calling this fn should trigger a check that the type argument
// supplied is well-formed.
fn wf<T>() { }
fn func<'x, T:Trait1<'x>>(t: &'x T)
{
wf::<&'x T::Foo>();
}
fn main() { } | // enough to conclude that `T::Foo: 'x`.
// compile-pass
#![allow(dead_code)] | random_line_split |
regions-implied-bounds-projection-gap-2.rs | // Copyright 2012 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 |
regions-implied-bounds-projection-gap-2.rs | // Copyright 2012 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 ... |
fn main() { }
| {
wf::<&'x T::Foo>();
} | identifier_body |
PhysicsComponent.js | var ServiceManager = require('../managers/ServiceManager.js');
var PhysicsManager = require('../managers/PhysicsManager.js');
// Utilities
var Rect = require('../utilities/Rect.js');
var Vector = require('../utilities/Vector.js');
// GameObject component for handling physical events
var PhysicsComponent = function(bl... |
while(blackboard.angle < -Math.PI){
blackboard.angle += Math.PI * 2;
}
blackboard.x += Math.cos(blackboard.angle) * blackboard.speed * (delta / 1000);
blackboard.y += Math.sin(blackboard.angle) * blackboard.speed * (delta / 1000);
return blackboard.getBounds();
};
... | {
blackboard.angle -= Math.PI * 2;
} | conditional_block |
PhysicsComponent.js | var ServiceManager = require('../managers/ServiceManager.js');
var PhysicsManager = require('../managers/PhysicsManager.js');
// Utilities
var Rect = require('../utilities/Rect.js');
var Vector = require('../utilities/Vector.js');
// GameObject component for handling physical events
var PhysicsComponent = function(bl... | PhysicsManager.removeComponent(self);
};
PhysicsManager.addComponent(this);
};
module.exports = PhysicsComponent; | this.unregister = function(){ | random_line_split |
__init__.py | # Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import inspect
import os
import re
import urlparse
_next_page_id = 0
class Page(object):
def __init__(self, url, page_set=None, base_dir=None, name=''):
... |
@property
def serving_dir(self):
file_path = os.path.realpath(self.file_path)
if os.path.isdir(file_path):
return file_path
else:
return os.path.dirname(file_path)
@property
def file_safe_name(self):
"""A version of display_name that's safe to use as a filename."""
# Just repl... | """Returns the file path, including the params, query, and fragment."""
assert self.is_file
file_path_url = os.path.normpath(os.path.join(self._base_dir, self.url[7:]))
# Preserve trailing slash or backslash.
# It doesn't matter in a file path, but it does matter in a URL.
if self.url.endswith('/'):... | identifier_body |
__init__.py | # Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import inspect
import os
import re
import urlparse
_next_page_id = 0
class Page(object):
def __init__(self, url, page_set=None, base_dir=None, name=''):
... |
@property
def name(self):
return self._name
@property
def url(self):
return self._url
@property
def id(self):
return self._id
def GetSyntheticDelayCategories(self):
result = []
for delay, options in self.synthetic_delays.items():
options = '%f;%s' % (options.get('target_durat... |
@property
def page_set(self):
return self._page_set | random_line_split |
__init__.py | # Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import inspect
import os
import re
import urlparse
_next_page_id = 0
class Page(object):
def __init__(self, url, page_set=None, base_dir=None, name=''):
... |
self._page_set.pages.remove(self)
self._page_set = another_page_set
self._page_set.AddPage(self)
def RunNavigateSteps(self, action_runner):
action_runner.NavigateToPage(self)
def CanRunOnBrowser(self, browser_info):
"""Override this to returns whether this page can be run on specific
brow... | return | conditional_block |
__init__.py | # Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import inspect
import os
import re
import urlparse
_next_page_id = 0
class | (object):
def __init__(self, url, page_set=None, base_dir=None, name=''):
self._url = url
self._page_set = page_set
# Default value of base_dir is the directory of the file that defines the
# class of this page instance.
if base_dir is None:
base_dir = os.path.dirname(inspect.getfile(self._... | Page | identifier_name |
enable_transparency.rs | use super::internal_prelude::*;
use imageflow_types::{PixelFormat, CompositingMode};
use crate::ffi::BitmapCompositingMode;
use crate::graphics::bitmaps::BitmapCompositing;
pub static ENABLE_TRANSPARENCY: EnableTransparencyDef = EnableTransparencyDef{};
pub static ENABLE_TRANSPARENCY_MUT: EnableTransparencyMutDef = En... | else if parent.fmt == PixelFormat::Bgr32 {
let mutate = ctx.graph
.add_node(Node::n(&ENABLE_TRANSPARENCY_MUT, NodeParams::None));
ctx.replace_node_with_existing(ix, mutate);
Ok(())
} else {
let canvas_params = imageflow_types::Node::CreateCanvas {
... | {
ctx.delete_node_and_snap_together(ix);
Ok(())
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.