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 |
|---|---|---|---|---|
product.service.ts | import {Injectable} from '@angular/core';
import {Headers, Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
export interface Product {
// Uni... | else if (search) {
url += `/?title=${search}`;
}
return this.http
.get(url)
.map((response: Response) => response.json().data as Product[])
.catch(this.handleError);
}
getProduct(id: string): Observable<Product> {
return this.http
... | {
url += `/?categoryId=${category}`;
} | conditional_block |
product.service.ts | import {Injectable} from '@angular/core';
import {Headers, Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
export interface Product {
// Uni... | imageS: string;
// Path to large image
imageL: string;
}
@Injectable()
export class ProductService {
// URL to Products web api
private productsUrl = 'app/products';
constructor(private http: Http) {}
getProducts(category?: string, search?: string): Observable<Product[]> {
let u... | // Mark product with specialproce
isSpecial: boolean;
// Description
desc: string;
// Path to small image | random_line_split |
product.service.ts | import {Injectable} from '@angular/core';
import {Headers, Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
export interface Product {
// Uni... |
}
| {
let errMsg = (error.message) ? error.message : error.status ?
`${error.status} - ${error.statusText}` : 'Server error';
window.alert(`An error occurred: ${errMsg}`);
return Observable.throw(errMsg);
} | identifier_body |
product.service.ts | import {Injectable} from '@angular/core';
import {Headers, Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
export interface Product {
// Uni... | (error: any): Observable<any> {
let errMsg = (error.message) ? error.message : error.status ?
`${error.status} - ${error.statusText}` : 'Server error';
window.alert(`An error occurred: ${errMsg}`);
return Observable.throw(errMsg);
}
}
| handleError | identifier_name |
aux_plugin_settings.js | /*
* Participants Database Aux Plugin settings page support
*
* sets up the tab functionality on the plugin settings page
* | * @version 1.1
*
*/
PDbAuxSettings = (function ($) {
var tabsetup;
var wrapped;
var wrapclass;
var effect = {
effect : 'fadeToggle',
duration : 200
};
const lastTab = 'pdb-settings-page-tab';
const tabvar = 'settingstab';
var getCurrentTab = function () {
var currentTab = isNaN(Cookies.g... | random_line_split | |
aux_plugin_settings.js | /*
* Participants Database Aux Plugin settings page support
*
* sets up the tab functionality on the plugin settings page
*
* @version 1.1
*
*/
PDbAuxSettings = (function ($) {
var tabsetup;
var wrapped;
var wrapclass;
var effect = {
effect : 'fadeToggle',
duration : 200
};
const lastTab =... |
return parseInt(currentTab);
}
var setupTabConfig = function () {
if ($.versioncompare("1.9", $.ui.version) == 1) {
tabsetup = {
fx : {
opacity : "show",
duration : "fast"
},
cookie : {
expires : 1
}
}
} else {
tabsetup = {... | {
currentTab = urlTab;
} | conditional_block |
__init__.py | # -*- coding: utf-8 -*-
# Copyright 2013 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | publish()
| logger.debug(
"RPC cast to orchestrator:\n{0}".format(
jsonutils.dumps(message, indent=4)
)
)
use_queue = naily_queue if not service else naily_service_queue
use_exchange = naily_exchange if not service else naily_service_exchange
with Connection(conn_str) as conn:
wi... | identifier_body |
__init__.py | # -*- coding: utf-8 -*-
# Copyright 2013 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | publish = functools.partial(producer.publish, message,
exchange=use_exchange, routing_key=name, declare=[use_queue])
try:
publish()
except amqp_exceptions.PreconditionFailed as e:
logger.warning(six.text_type(e))
# (dshu... | with conn.Producer(serializer='json') as producer: | random_line_split |
__init__.py | # -*- coding: utf-8 -*-
# Copyright 2013 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | (name, message, service=False):
logger.debug(
"RPC cast to orchestrator:\n{0}".format(
jsonutils.dumps(message, indent=4)
)
)
use_queue = naily_queue if not service else naily_service_queue
use_exchange = naily_exchange if not service else naily_service_exchange
with Conn... | cast | identifier_name |
functions.js | // @flow
/**
* Selector to return lobby enable state.
*
* @param {any} state - State object.
* @returns {boolean}
*/
export function getLobbyEnabled(state: any) {
return state['features/lobby'].lobbyEnabled;
}
/**
* Selector to return a list of knocking participants.
*
* @param {any} state - State object.
* @retu... | (state: any) {
return getKnockingParticipants(state).map(participant => participant.id);
}
| getKnockingParticipantsById | identifier_name |
functions.js | // @flow
/**
* Selector to return lobby enable state.
*
* @param {any} state - State object.
* @returns {boolean}
*/ | /**
* Selector to return a list of knocking participants.
*
* @param {any} state - State object.
* @returns {Array<Object>}
*/
export function getKnockingParticipants(state: any) {
return state['features/lobby'].knockingParticipants;
}
/**
* Selector to return lobby visibility.
*
* @param {any} state - State ob... | export function getLobbyEnabled(state: any) {
return state['features/lobby'].lobbyEnabled;
}
| random_line_split |
functions.js | // @flow
/**
* Selector to return lobby enable state.
*
* @param {any} state - State object.
* @returns {boolean}
*/
export function getLobbyEnabled(state: any) {
return state['features/lobby'].lobbyEnabled;
}
/**
* Selector to return a list of knocking participants.
*
* @param {any} state - State object.
* @retu... |
/**
* Selector to return array with knocking participant ids.
*
* @param {any} state - State object.
* @returns {Array}
*/
export function getKnockingParticipantsById(state: any) {
return getKnockingParticipants(state).map(participant => participant.id);
}
| {
return state['features/lobby'].lobbyVisible;
} | identifier_body |
jsdocTypedefTag.ts | /// <reference path="../fourslash.ts"/>
// @allowNonTsExtensions: true
// @Filename: jsdocCompletion_typedef.js
//// /** @typedef {(string | number)} NumberLike */
////
//// /**
//// * @typedef Animal - think Giraffes
//// * @type {Object}
//// * @property {string} animalName
//// * @property {number} ... | { marker: "person", includes: ["personName", "personAge"] },
{ marker: "personName", includes: "charAt" },
{ marker: "personAge", includes: "toExponential" },
{ marker: "animal", includes: ["animalName", "animalAge"] },
{ marker: "animalName", includes: "charAt" },
{ marker: "animalAge", ... | random_line_split | |
ckform.js | var __check_form_last_error_info = [];
var check_form = function (formname, opt) {
var formobj; //Ö¸¶¨µ±Ç°±íµ¥
var e_error = "";
var focus_obj = ""; //µÚÒ»¸ö³öÏÖ´íÎó¶ÔÏñ
var error = [];
var _temp_ajax = new Array; //ajaxУÑéÇëÇóµÄ»º´æ
var opt = opt || {}; //Ñ¡Ïî
opt = $.extend({
... | random_line_split | ||
ckform.js | 1, i)
str3 = escape(str2);
if (str3.length > 3) {
nLen = nLen + 2;
}
else {
nLen = nLen + 1;
}
}
return nLen;
}
//////////////////////////////////////////**** ¼ì²â¹¦Äܺ¯Êý×é****//////////////////////////... | urn true;
if (str.indexOf('<') == -1 && str.indexOf('>') == -1) return true;
obj.data('jscheckerror', 'º¬ÓÐhtml×Ö·û');
return false;
}
//ajaxУÑé
function cf_ajax(obj, str) {
| conditional_block | |
ckform.js | УÑéHTML
if (jscheckrule.indexOf('html=') == -1) {
jscheckrule += ';html=0';
}
var jsvalue = formobj_i.val();
var errflag = 0;//´íÎó±ê¼Ç
if (obj_tag == 'TEXTAREA' && (jsmaxlen > 0 ? (jsvalue.length > jsmaxlen ? 1 : 0) : 0)) {
jscheckerror = (jschecktitle ... | type = obj.attr('type'), str;
if (obj_type == 'checkbox' || obj_type == 'radio') {
var objname = obj.attr('name');
str = formobj.filter(':' + obj_type + '[name=' + objname + '][checked]').map(function () {
return this.value;
}).get().join(',');
}
... | ar obj_ | identifier_name |
ckform.js | name = obj.attr('name');
str = formobj.filter(':' + obj_type + '[name=' + objname + '][checked]').map(function () {
return this.value;
}).get().join(',');
}
else {
str = obj.val();
}
str = str && typeof(str) == 'object' ? str.join(',') ... | identifier_body | ||
fixer_util.py | an import statement in the form:
from package import name_leafs"""
# XXX: May not handle dotted imports properly (eg, package_name='foo.bar')
#assert package_name == '.' or '.' not in package_name, "FromImport has "\
# "not been tested with dotted package names -- use at your own "\
# ... | if not package:
return ret
if is_import(ret):
return ret | conditional_block | |
fixer_util.py | , prefix=None):
"""A function call"""
node = Node(syms.power, [func_name, ArgList(args)])
if prefix is not None:
node.prefix = prefix
return node
def Newline():
"""A newline literal"""
return Leaf(token.NEWLINE, u"\n")
def BlankLine():
"""A blank line"""
return Leaf(token.NEWLI... | (node):
"""Returns true if the node is an import statement."""
return node.type in (syms.import_name, syms.import_from)
def touch_import(package, name, node):
""" Works like `does_tree_import` but adds an import statement
if it was not imported. """
def is_import_stmt(node):
return node... | is_import | identifier_name |
fixer_util.py | , prefix=None):
"""A function call"""
node = Node(syms.power, [func_name, ArgList(args)]) | if prefix is not None:
node.prefix = prefix
return node
def Newline():
"""A newline literal"""
return Leaf(token.NEWLINE, u"\n")
def BlankLine():
"""A blank line"""
return Leaf(token.NEWLINE, u"")
def Number(n, prefix=None):
return Leaf(token.NUMBER, n, prefix=prefix)
def Subscri... | random_line_split | |
fixer_util.py |
def ArgList(args, lparen=LParen(), rparen=RParen()):
"""A parenthesised argument list, used by Call()"""
node = Node(syms.trailer, [lparen.clone(), rparen.clone()])
if args:
node.insert_child(1, Node(syms.arglist, args))
return node
def Call(func_name, args=None, prefix=None):
"""A functi... | """A period (.) leaf"""
return Leaf(token.DOT, u".") | identifier_body | |
fontface.js | /*
* grunt-fontface
* https://github.com/nsmith7989/grunt-fontface
*
* Copyright (c) 2014 Nathanael Smith
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-t... |
});
//build contents
uniqFontFiles.forEach(function(elem) {
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g
};
var template = _.template(options.template);
contents += template({font: elem}) + grunt.util.linefeed;
});
grunt.file.write(options.outputFile, contents);
});
};
| {
return elem;
} | conditional_block |
fontface.js | /*
* grunt-fontface
* https://github.com/nsmith7989/grunt-fontface
*
* Copyright (c) 2014 Nathanael Smith
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-t... | fontDir: 'fonts',
outputFile: 'sass/_fonts.scss',
removeFromFile: '-webfont'
}),
fontFiles = [];
var _ = require('underscore'),
path = require('path'),
fs = require('fs'),
fontFiles = [],
uniqFontFiles = [],
contents = '';
//rewrite file names
fs.readdirSync(process.cwd() + ... |
var options = this.options({ | random_line_split |
connect.py | (msg, color='red'):
"""Print colorful string and exit."""
color_print(msg, color=color)
time.sleep(2)
sys.exit()
def get_win_size():
"""This function use to get the size of the windows!"""
if 'TIOCGWINSZ' in dir(termios):
TIOCGWINSZ = termios.TIOCGWINSZ
else:
TIOCGWINSZ = 1... | color_print_exit | identifier_name | |
connect.py | )
time.sleep(2)
sys.exit()
def get_win_size():
"""This function use to get the size of the windows!"""
if 'TIOCGWINSZ' in dir(termios):
TIOCGWINSZ = termios.TIOCGWINSZ
else:
TIOCGWINSZ = 1074295912L # Assume
s = struct.pack('HHHH', 0, 0, 0, 0)
x = fcntl.ioctl(sys.stdout.fi... |
def print_user_host(username):
try:
hosts_attr = get_user_host(username)
except ServerError, e:
color_print(e, 'red')
return
hosts = hosts_attr.keys()
hosts.sort()
for ip in hosts:
print '%-15s -- %s' % (ip, hosts_attr[ip][2])
print ''
def print_user_hostgroup(... | print textwrap.dedent(msg)
| random_line_split |
connect.py | .get(username=username).dept.name
pid = os.getpid()
pts = os.popen("ps axu | awk '$2==%s{ print $7 }'" % pid).read().strip()
ip_list = os.popen("who | awk '$2==\"%s\"{ print $5 }'" % pts).read().strip('()\n')
if not os.path.isdir(today_connect_log_dir):
try:
os.makedirs(today_connec... | break | conditional_block | |
connect.py | )
time.sleep(2)
sys.exit()
def get_win_size():
"""This function use to get the size of the windows!"""
if 'TIOCGWINSZ' in dir(termios):
TIOCGWINSZ = termios.TIOCGWINSZ
else:
TIOCGWINSZ = 1074295912L # Assume
s = struct.pack('HHHH', 0, 0, 0, 0)
x = fcntl.ioctl(sys.stdout.fi... |
def verify_connect(username, part_ip):
ip_matched = []
try:
hosts_attr = get_user_host(username)
hosts = hosts_attr.values()
except ServerError, e:
color_print(e, 'red')
return False
for ip_info in hosts:
if part_ip in ip_info[1:] and part_ip:
ip_m... | """Get the hostgroup hosts of under the user control."""
hosts_attr = {}
user = User.objects.get(username=username)
hosts = user_perm_group_hosts_api(gid)
for host in hosts:
alias = AssetAlias.objects.filter(user=user, host=host)
if alias and alias[0].alias != '':
hosts_attr[... | identifier_body |
BarSeries.js | /**
* The BarSeries class renders bars positioned vertically along a category or time axis. The bars'
* lengths are proportional to the values they represent along a horizontal axis.
* and the relevant data points.
*
* @module charts
* @class BarSeries
* @extends MarkerSeries
* @uses Histogram
* @constructor
... |
}
}
}
}
}, {
ATTRS: {
/**
* Read-only attribute indicating the type of series.
*
* @attribute type
* @type String
* @default bar
*/
type: {
value: "bar"
},
/**
* Indic... | {
renderer.set("y", (ys[n] - seriesSize/2));
} | conditional_block |
BarSeries.js | /**
* The BarSeries class renders bars positioned vertically along a category or time axis. The bars'
* lengths are proportional to the values they represent along a horizontal axis.
* and the relevant data points.
*
* @module charts
* @class BarSeries
* @extends MarkerSeries
* @uses Histogram
* @constructor
... | * Resizes and positions markers based on a mouse interaction.
*
* @method updateMarkerState
* @param {String} type state of the marker
* @param {Number} i index of the marker
* @protected
*/
updateMarkerState: function(type, i)
{
if(this._markers && this._markers[i])
... | }
return config;
},
/** | random_line_split |
table.rs | extern crate serde_json;
extern crate term;
use self::term::{Attr, color};
use prettytable::Table;
use prettytable::row::Row;
use prettytable::cell::Cell;
pub fn print_list_table(rows: &Vec<serde_json::Value>, headers: &[(&str, &str)], empty_msg: &str) {
if rows.is_empty() {
return println_succ!("{}", emp... |
Cell::new(&value)
})
.collect::<Vec<Cell>>();
table.add_row(Row::new(columns));
} | {
value = row[key].as_object().unwrap()
.iter()
.map(|(key, value)| format!("{}:{}", key, value))
.collect::<Vec<String>>()
.join(",");
value = format!("{{{}}}", value)
} | conditional_block |
table.rs | extern crate serde_json;
extern crate term;
use self::term::{Attr, color};
use prettytable::Table;
use prettytable::row::Row;
use prettytable::cell::Cell;
pub fn print_list_table(rows: &Vec<serde_json::Value>, headers: &[(&str, &str)], empty_msg: &str) {
if rows.is_empty() {
return println_succ!("{}", emp... | (table: &mut Table, headers: &[(&str, &str)]) {
let tittles = headers.iter().clone()
.map(|&(_, ref header)| Cell::new(header)
.with_style(Attr::Bold)
.with_style(Attr::ForegroundColor(color::GREEN))
).collect::<Vec<Cell>>();
table.add_row(Row::new(tittles));
}
pub fn p... | print_header | identifier_name |
table.rs | use prettytable::row::Row;
use prettytable::cell::Cell;
pub fn print_list_table(rows: &Vec<serde_json::Value>, headers: &[(&str, &str)], empty_msg: &str) {
if rows.is_empty() {
return println_succ!("{}", empty_msg);
}
let mut table = Table::new();
print_header(&mut table, headers);
for r... | extern crate serde_json;
extern crate term;
use self::term::{Attr, color};
use prettytable::Table; | random_line_split | |
table.rs | extern crate serde_json;
extern crate term;
use self::term::{Attr, color};
use prettytable::Table;
use prettytable::row::Row;
use prettytable::cell::Cell;
pub fn print_list_table(rows: &Vec<serde_json::Value>, headers: &[(&str, &str)], empty_msg: &str) {
if rows.is_empty() {
return println_succ!("{}", emp... |
pub fn print_header(table: &mut Table, headers: &[(&str, &str)]) {
let tittles = headers.iter().clone()
.map(|&(_, ref header)| Cell::new(header)
.with_style(Attr::Bold)
.with_style(Attr::ForegroundColor(color::GREEN))
).collect::<Vec<Cell>>();
table.add_row(Row::new(t... | {
let mut table = Table::new();
print_header(&mut table, headers);
print_row(&mut table, row, headers);
table.printstd();
} | identifier_body |
matchMakingThread.py | #This will be the thread responsible for the matchmaking which operates as follows:
#There are four lists where the players are divided into based on their rank.
#List 1 is for ranks 0,1,2.
#List 2 is for ranks 3,4,5.
#List 3 is for ranks 6,7,8.
#List 4 is for ranks 9,10.
#When a player waits for a match too long, this... | #Add player tokens to Queue for game play thread
if foundMatch:
bothPlayers = [firstPlayer,secondPlayer]
data = {'turn':0,'players':bothPlayers}
print'Add new Player token'
outputQueue.put(data)
#Match players in same list... | position = player.get('rank') // 3
foundMatch = False
#Check for empty list
if len(playerList[position]) == 0 or playerList[position][0] != player:
continue
#Check for enemy player one list above this player
if position + 1 < len(playerList) ... | conditional_block |
matchMakingThread.py | #This will be the thread responsible for the matchmaking which operates as follows:
#There are four lists where the players are divided into based on their rank.
#List 1 is for ranks 0,1,2.
#List 2 is for ranks 3,4,5.
#List 3 is for ranks 6,7,8.
#List 4 is for ranks 9,10.
#When a player waits for a match too long, this... | for category in playerList:
while True:
try:
#Try to pop two players from the list
#If successfull, put their token into game play thread Queue
firstPlayer = None
secondPlayer = None
f... | #Match players in same list | random_line_split |
matchMakingThread.py | #This will be the thread responsible for the matchmaking which operates as follows:
#There are four lists where the players are divided into based on their rank.
#List 1 is for ranks 0,1,2.
#List 2 is for ranks 3,4,5.
#List 3 is for ranks 6,7,8.
#List 4 is for ranks 9,10.
#When a player waits for a match too long, this... | (inputQueue,exitQueue,outputQueue):
#Lists for all difficulties
noviceList = []
apprenticeList = []
adeptList = []
expertList = []
#put them in one list
playerList = [noviceList,apprenticeList,adeptList,expertList]
#This list contains the players that have waited for too long in their... | mmThread | identifier_name |
matchMakingThread.py | #This will be the thread responsible for the matchmaking which operates as follows:
#There are four lists where the players are divided into based on their rank.
#List 1 is for ranks 0,1,2.
#List 2 is for ranks 3,4,5.
#List 3 is for ranks 6,7,8.
#List 4 is for ranks 9,10.
#When a player waits for a match too long, this... | pass
#loop over new entries at most MAX_LOOPS times then do it again
while loopCounter < MAX_LOOPS:
try:
#Get new player and add him to a list according to his rank
newPlayer = inputQueue.get(False)
playerRank = newPlayer.get('rank... | noviceList = []
apprenticeList = []
adeptList = []
expertList = []
#put them in one list
playerList = [noviceList,apprenticeList,adeptList,expertList]
#This list contains the players that have waited for too long in their Queue
needRematch = []
while True:
loopCounter = 0
... | identifier_body |
ris.js | modified;
},
getActionHtml: function(labelSearch, actionLabel)
{
return window.external.GetActionHtml(labelSearch, actionLabel);
},
// attempts to resolve the specified query string to a staff person,
// returning a Staff object if successful, otherwise null.
// note: this method may i... | __asyncInvocationCompleted | identifier_name | |
ris.js | this._asyncCount++;
},
_unregisterAsyncCall: function()
{
if(this._asyncStarted)
{
this._asyncCount--;
if(this._asyncCount === 0 && document.getElementById("loadingAnimation"))
{
document.getElementById("loadingAnimation").style.display = 'none';
}
}
},
//... | {
// re-direct script errors through the host app
window.onerror = function(message, url, lineNumber) {
window.external.OnScriptError(message, url, lineNumber);
};
var Ris = {
_asyncStarted: false,
_asyncCount: 0,
_registerAsyncCall: function()
{
if(this._asyncStarted == false)
{
... | conditional_block | |
ris.js | Staff(value.staffId, value.staffName, value.staffType);
return value;
},
// map used to store async callback functions
_asyncCallbackMap: {},
// callback from an async service operation (see GetServiceProxy)
_asyncInvocationCompleted: function(invocationId, responseJsml)
{
// look up ... | getHealthcareContext: function()
{
| random_line_split | |
ris.js | function(query)
{
var staffSummary = JSML.parse(window.external.ResolveStaffName(query || ""));
if(staffSummary == null)
return null;
return new Staff(
staffSummary.StaffId,
staffSummary.Name.FamilyName + ", " + staffSummary.Name.GivenName,
staffSummary.StaffType.Value);
},
... | {
// forward to the Ris object
Ris._asyncInvocationError(invocationId, errorMessage);
} | identifier_body | |
forms.py | # -*- coding: utf-8 -*-
# @Date : 2016-01-21 13:15
# @Author : leiyue (mr.leiyue@gmail.com)
# @Link : https://leiyue.wordpress.com/
from flask_wtf import Form
from wtforms import StringField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, length
from .models import User
class LoginFo... |
if self.nickname.data == self.original_nickname:
return True
user = User.query.filter_by(nickname=self.nickname.data).first()
if user is not None:
self.nickname.errors.append('This nickname is already in use, Please choose another one.')
return False
... | return False | conditional_block |
forms.py | # -*- coding: utf-8 -*-
# @Date : 2016-01-21 13:15
# @Author : leiyue (mr.leiyue@gmail.com)
# @Link : https://leiyue.wordpress.com/
from flask_wtf import Form
from wtforms import StringField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, length
from .models import User
class | (Form):
openid = StringField('openid', validators=[DataRequired()])
remember_me = BooleanField('remember_me', default=False)
class EditForm(Form):
nickname = StringField('nickname', validators=[DataRequired()])
about_me = TextAreaField('about_me', validators=[length(min=0, max=140)])
def __init__... | LoginForm | identifier_name |
forms.py | # -*- coding: utf-8 -*-
# @Date : 2016-01-21 13:15
# @Author : leiyue (mr.leiyue@gmail.com)
# @Link : https://leiyue.wordpress.com/
from flask_wtf import Form
from wtforms import StringField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, length
from .models import User
class LoginFo... |
class SearchForm(Form):
search = StringField('search', validators=[DataRequired()])
| post = TextAreaField('post', validators=[DataRequired(), length(min=0, max=140)]) | identifier_body |
forms.py | # -*- coding: utf-8 -*-
# @Date : 2016-01-21 13:15
# @Author : leiyue (mr.leiyue@gmail.com)
# @Link : https://leiyue.wordpress.com/
from flask_wtf import Form
from wtforms import StringField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, length
from .models import User
class LoginFo... | post = TextAreaField('post', validators=[DataRequired(), length(min=0, max=140)])
class SearchForm(Form):
search = StringField('search', validators=[DataRequired()]) | return False
return True
class PostForm(Form): | random_line_split |
__openerp__.py | # -*- coding: utf-8 -*-
############################################################################## | # Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar)
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or ... | # | random_line_split |
aunt_annes.py | "San Sai", "Kamphaeng Phet", "Pak Kret", "Hat Yai", "Ban Nam Hak", "Khlung", "Makkasan",
"Bang Sao Thong", "Ban Hua Thale", "Klaeng", "Chulabhorn", "Ban Don Sak", "Phanna Nikhom",
"Ban Na", "Ban Ko Pao","Mae Sot"
)
Korea_Cities = (
"Seoul", "Incheon", "Paju", "Cheonan", "Yongin", "Kwanghui-dong... | if child.tag in ('latitude', 'longitude'):
props[MAPPING[child.tag]] = float(child.text)
else:
props[MAPPING[child.tag]] = child.text | conditional_block | |
aunt_annes.py | ", "Khan Na Yao", "Bang Sue", "Sam Khok", "Don Mueang",
"Ban Pratunam Tha Khai","Sena", "Prakanong", "Ban Tha Pai", "Bang Lamung", "Nakhon Sawan",
"San Sai", "Kamphaeng Phet", "Pak Kret", "Hat Yai", "Ban Nam Hak", "Khlung", "Makkasan",
"Bang Sao Thong", "Ban Hua Thale", "Klaeng", "Chulabhorn", "... | allowed_domains = ["hosted.where2getit.com/auntieannes"]
download_delay = 0.2
def process_poi(self, poi):
props = {} | random_line_split | |
aunt_annes.py | laeng", "Chulabhorn", "Ban Don Sak", "Phanna Nikhom",
"Ban Na", "Ban Ko Pao","Mae Sot"
)
Korea_Cities = (
"Seoul", "Incheon", "Paju", "Cheonan", "Yongin", "Kwanghui-dong", "Pon-dong",
"Gwangju", "Gwangmyeong", "Tang-ni", "Busan", "Seongnam-si", "Suwon-si", "Namyang",
"Namyangju", "Jeju-s... | name = "auntie_annes"
allowed_domains = ["hosted.where2getit.com/auntieannes"]
download_delay = 0.2
def process_poi(self, poi):
props = {}
add_parts = []
for child in poi:
if child.tag in TAGS and child.tag in MAPPING:
if child.tag in ('latitude', 'longi... | identifier_body | |
aunt_annes.py | Gwangju", "Gwangmyeong", "Tang-ni", "Busan", "Seongnam-si", "Suwon-si", "Namyang",
"Namyangju", "Jeju-si", "Ulsan", "Osan", "Hanam", "Pyong-gol", "Anyang-si",
"Yangsan", "Daejeon", "Nonsan", "Seocho", "Wonju", "Kisa", "Daegu", "Ansan-si", "Gongju",
"Haeundae", "Sasang", "Bucheon-si", "Chuncheon"... | parse | identifier_name | |
cmdshell.py | # Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# 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 restriction, including
# without limitation the rights to use, copy, modi... |
except paramiko.BadHostKeyException:
print "%s has an entry in ~/.ssh/known_hosts and it doesn't match" % self.server.hostname
print 'Edit that file to remove the entry and then hit return to try again'
raw_input('Hit Enter when ready')
retry ... | raise | conditional_block |
cmdshell.py | # Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# 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 restriction, including
# without limitation the rights to use, copy, modi... |
def run(self, command):
"""
Execute a command on the remote host. Return a tuple containing
an integer status and two strings, the first containing stdout
and the second containing stderr from the command.
"""
boto.log.debug('running:%s on %s' % (command, self.serv... | """
Start an interactive shell session on the remote host.
"""
channel = self._ssh_client.invoke_shell()
interactive_shell(channel) | identifier_body |
cmdshell.py | # Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# 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 restriction, including
# without limitation the rights to use, copy, modi... | """
Create and return an SSHClient object given an
instance object.
:type instance: :class`boto.ec2.instance.Instance` object
:param instance: The instance object.
:type ssh_key_file: str
:param ssh_key_file: A path to the private key file used
to log into instance... | random_line_split | |
cmdshell.py | # Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# 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 restriction, including
# without limitation the rights to use, copy, modi... | (self):
return self._ssh_client.open_sftp()
def get_file(self, src, dst):
sftp_client = self.open_sftp()
sftp_client.get(src, dst)
def put_file(self, src, dst):
sftp_client = self.open_sftp()
sftp_client.put(src, dst)
def open(self, filename, mode='r', bufsize=-1):... | open_sftp | identifier_name |
expr-match-generic-unique2.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
fn test_vec() {
fn compare_box(v1: Box<isize>, v2: Box<isize>) -> bool { return v1 == v2; }
test_generic::<Box<isize>, _>(box 1, compare_box);
}
pub fn main() { test_vec(); } | true => expected.clone(),
_ => panic!("wat")
};
assert!(eq(expected, actual));
} | random_line_split |
expr-match-generic-unique2.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | { test_vec(); } | identifier_body | |
expr-match-generic-unique2.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | <T: Clone, F>(expected: T, eq: F) where F: FnOnce(T, T) -> bool {
let actual: T = match true {
true => expected.clone(),
_ => panic!("wat")
};
assert!(eq(expected, actual));
}
fn test_vec() {
fn compare_box(v1: Box<isize>, v2: Box<isize>) -> bool { return v1 == v2; }
test_generic::<... | test_generic | identifier_name |
shape.js | // Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unl... |
/**
* The original path, specified by the caller.
* @type {goog.graphics.Path}
* @private
*/
goog.graphics.ext.Shape.prototype.path_;
/**
* The bounding box of the original path.
* @type {goog.math.Rect?}
* @private
*/
goog.graphics.ext.Shape.prototype.boundingBox_ = null;
/**
* The scal... | */
goog.graphics.ext.Shape.prototype.autoSize_ = false;
| random_line_split |
shape.js | // Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unl... |
this.scaleAndSetPath_();
};
/**
* Scale the internal path to fit.
* @private
*/
goog.graphics.ext.Shape.prototype.scaleAndSetPath_ = function() {
this.scaledPath_ = this.boundingBox_ ? this.path_.clone().modifyBounds(
-this.boundingBox_.left, -this.boundingBox_.top,
this.getWidth() /... | {
this.boundingBox_ = path.getBoundingBox();
} | conditional_block |
tuple.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 ... | //! assert!(b == c);
//!
//! let d : (u32, f32) = Default::default();
//! assert_eq!(d, (0, 0.0f32));
//! ```
#![doc(primitive = "tuple")]
#![stable(feature = "rust1", since = "1.0.0")] | //! let c = b.clone(); | random_line_split |
binduser.py | #! /usr/bin/env python
#
# Copyright (c) 2008-2009 University of Utah and the Flux Group.
#
# {{{GENIPUBLIC-LICENSE
#
# GENI Public License
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without rest... | import sys
import pwd
import getopt
import os
import time
import re
import xmlrpclib
from M2Crypto import X509
ACCEPTSLICENAME=1
execfile( "test-common.py" )
#
# Get a credential for myself, that allows me to do things at the SA.
#
mycredential = get_self_credential()
print "Got self credential"
#
# Lookup slice.
#... | # | random_line_split |
binduser.py | #! /usr/bin/env python
#
# Copyright (c) 2008-2009 University of Utah and the Flux Group.
#
# {{{GENIPUBLIC-LICENSE
#
# GENI Public License
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without rest... |
print "Bound myself to slice"
| Fatal("Could not bind myself to slice")
pass | conditional_block |
query.js | var dns = require('native-dns'),
util = require('util');
var question = dns.Question({
name: 'www.google.com',
type: 'A', // could also be the numerical representation
});
var start = new Date().getTime();
var req = dns.Request({
question: question,
server: '8.8.8.8',
/*
// Optionally you can define an... | });
req.on('end', function () {
/* Always fired at the end */
var delta = (new Date().getTime()) - start;
console.log('Finished processing request: ' + delta.toString() + 'ms');
});
req.send(); | console.log(a.address);
}); | random_line_split |
filer.py | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import
import hashlib
import six
from djan... | upload = model.objects.filter(sha1=sha1).first()
if upload:
return upload
file_form_cls = modelform_factory(
model=model, fields=('original_filename', 'owner', 'file'))
upload_form = file_form_cls(
data={
'original_filename': upload_data.name,
... | :type sha1: basestring
:return: Filer file
"""
if sha1: | random_line_split |
filer.py | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import
import hashlib
import six
from djan... | (model, request, path, upload_data, sha1=None):
"""
Create some sort of Filer file (either File or Image, really) from the given upload data (ContentFile or UploadFile)
:param model: Model class
:param request: Request, to figure out the owner for this file
:type request: django.http.request.HttpRe... | _filer_file_from_upload | identifier_name |
filer.py | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import
import hashlib
import six
from djan... |
upload.save()
return upload
def filer_file_from_upload(request, path, upload_data, sha1=None):
"""
Create a filer.models.filemodels.File from an upload (UploadedFile or such).
If the `sha1` parameter is passed and a file with said SHA1 is found, it will be returned instead.
:param request: R... | upload.folder = filer_folder_from_path(path) | conditional_block |
filer.py | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import
import hashlib
import six
from djan... |
def filer_image_from_data(request, path, file_name, file_data, sha1=None):
"""
Create a Filer Image from the given data string.
If the `sha1` parameter is passed and True (the value True, not a truey value), the SHA-1 of the data string
is calculated and passed to the underlying creation function.
... | """
Create a Filer Image from an upload (UploadedFile or such).
If the `sha1` parameter is passed and an Image with said SHA1 is found, it will be returned instead.
:param request: Request, to figure out the owner for this file
:type request: django.http.request.HttpRequest|None
:param path: Pathna... | identifier_body |
main.rs | extern crate kiss3d;
extern crate nalgebra as na;
extern crate time;
extern crate rustc_serialize;
use kiss3d::window::Window;
use kiss3d::light::Light;
mod leg;
mod constants;
use leg::Leg;
use std::fs::{File};
use std::io::prelude::{Read};
use std::io::Write;
use std::vec::Vec;
use std::f32::consts::PI;
use rus... | };
//Reading the file into a string
let mut s = String::new();
file.read_to_string(&mut s).unwrap();
//let json_data = json::Json::from_str(&s).unwrap();
result = match json::decode(&s)
{
Ok(val) => {
is_done = true;
... | {
let file_dir = String::from("/tmp/hexsim");
let filepath = file_dir.clone() + "/leg_input";
try_with_yolo!(std::fs::create_dir(&file_dir));
//Opening the file
//let mut file = None;
let mut is_done = false;
let mut result: Vec<LegTarget> = vec!();
while !is_done
{
le... | identifier_body |
main.rs | extern crate kiss3d;
extern crate nalgebra as na;
extern crate time;
extern crate rustc_serialize;
use kiss3d::window::Window;
use kiss3d::light::Light;
mod leg;
mod constants;
use leg::Leg;
use std::fs::{File};
use std::io::prelude::{Read};
use std::io::Write;
use std::vec::Vec;
use std::f32::consts::PI;
use rus... |
window.set_light(Light::StickToCamera);
let mut robot = Robot::new(&mut window);
let mut old_time = time::precise_time_s() as f32;
while window.render()
{
let new_time = time::precise_time_s() as f32;
let delta_time = (new_time - old_time) * constants::TIME_MODIFIER;
old_... | }
fn main() {
let mut window = Window::new("Kiss3d: cube"); | random_line_split |
main.rs | extern crate kiss3d;
extern crate nalgebra as na;
extern crate time;
extern crate rustc_serialize;
use kiss3d::window::Window;
use kiss3d::light::Light;
mod leg;
mod constants;
use leg::Leg;
use std::fs::{File};
use std::io::prelude::{Read};
use std::io::Write;
use std::vec::Vec;
use std::f32::consts::PI;
use rus... | (&self)
{
{
let mut file = File::create("/tmp/hexsim/servo_states").unwrap();
let mut result = String::from("");
for leg in &self.legs
{
for status in leg.is_still_moving()
{
result += match status
... | write_angles_done | identifier_name |
rtctrackevent.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/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods;
use crate::dom::bindings::... |
}
impl RTCTrackEventMethods for RTCTrackEvent {
// https://w3c.github.io/webrtc-pc/#dom-rtctrackevent-track
fn Track(&self) -> DomRoot<MediaStreamTrack> {
DomRoot::from_ref(&*self.track)
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event... | {
Ok(RTCTrackEvent::new(
&window.global(),
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
&init.track,
))
} | identifier_body |
rtctrackevent.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/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods;
use crate::dom::bindings::... | pub fn new(
global: &GlobalScope,
type_: Atom,
bubbles: bool,
cancelable: bool,
track: &MediaStreamTrack,
) -> DomRoot<RTCTrackEvent> {
let trackevent = reflect_dom_object(
Box::new(RTCTrackEvent::new_inherited(&track)),
global,
... | event: Event::new_inherited(),
track: Dom::from_ref(track),
}
}
| random_line_split |
rtctrackevent.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/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods;
use crate::dom::bindings::... | (&self) -> bool {
self.event.IsTrusted()
}
}
| IsTrusted | identifier_name |
entity.model.ts | import { InfoType } from './info.model';
import { DefinitionType } from './definition.model';
import { DefinitionsType } from './definitions.model';
import { HubUIData } from './hubuidata.model';
import { Point } from '../components/entity-modeler/math-helper';
import { Flow } from './flow.model';
import * as _ from 'l... |
constructor() {}
fromJSON(json) {
this.filename = json.filename;
if (json && json.hubUi) {
this.hubUi = new HubUIData().fromJSON(json.hubUi);
this.updateTransform();
}
if (json.info) {
this.info = new InfoType().fromJSON(json.info);
}
if (json.definition) {
this.... | {
this.definitions = _definitions;
} | identifier_body |
entity.model.ts | import { InfoType } from './info.model';
import { DefinitionType } from './definition.model';
import { DefinitionsType } from './definitions.model';
import { HubUIData } from './hubuidata.model';
import { Point } from '../components/entity-modeler/math-helper';
import { Flow } from './flow.model';
import * as _ from 'l... | {
filename: string;
hubUi: HubUIData;
info: InfoType;
definition: DefinitionType;
definitions: DefinitionsType;
inputFlows: Array<Flow>;
harmonizeFlows: Array<Flow>;
///////////////////////////////////
// ephemeral data
// holds a copy of the original, untouched values
// used for editing ent... | Entity | identifier_name |
entity.model.ts | import { InfoType } from './info.model';
import { DefinitionType } from './definition.model';
import { DefinitionsType } from './definitions.model';
import { HubUIData } from './hubuidata.model';
import { Point } from '../components/entity-modeler/math-helper';
import { Flow } from './flow.model';
import * as _ from 'l... |
if (json.definitions) {
this.definitions = new DefinitionsType().fromJSON(json.definitions);
if (!json.definition) {
this.definition = this.definitions.get(this.name);
}
}
this.inputFlows = [];
if (json.inputFlows && _.isArray(json.inputFlows)) {
for (let flow of json.... | {
this.definition = new DefinitionType().fromJSON(json.definition);
} | conditional_block |
entity.model.ts | import { InfoType } from './info.model';
import { DefinitionType } from './definition.model';
import { DefinitionsType } from './definitions.model';
import { HubUIData } from './hubuidata.model';
import { Point } from '../components/entity-modeler/math-helper';
import { Flow } from './flow.model';
import * as _ from 'l... | this.definitions = new DefinitionsType().fromJSON(json.definitions);
if (!json.definition) {
this.definition = this.definitions.get(this.name);
}
}
this.inputFlows = [];
if (json.inputFlows && _.isArray(json.inputFlows)) {
for (let flow of json.inputFlows) {
this.inp... | if (json.definition) {
this.definition = new DefinitionType().fromJSON(json.definition);
}
if (json.definitions) { | random_line_split |
constellation_msg.rs | , Serialize, HeapSizeOf)]
pub struct WindowSizeData {
/// The size of the initial layout viewport, before parsing an
/// http://www.w3.org/TR/css-device-adapt/#initial-viewport
pub initial_viewport: TypedSize2D<ViewportPx, f32>,
/// The "viewing area" in page px. See `PagePx` documentation for details.... | }
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct SubpageId(pub u32); | random_line_split | |
constellation_msg.rs | Url;
use util::geometry::{PagePx, ViewportPx};
use webdriver_msg::{LoadStatus, WebDriverScriptCommand};
use webrender_traits;
#[derive(Deserialize, Serialize)]
pub struct ConstellationChan<T: Deserialize + Serialize>(pub IpcSender<T>);
impl<T: Deserialize + Serialize> ConstellationChan<T> {
pub fn | () -> (IpcReceiver<T>, ConstellationChan<T>) {
let (chan, port) = ipc::channel().unwrap();
(port, ConstellationChan(chan))
}
}
impl<T: Serialize + Deserialize> Clone for ConstellationChan<T> {
fn clone(&self) -> ConstellationChan<T> {
ConstellationChan(self.0.clone())
}
}
// We pas... | new | identifier_name |
joiner.rs | use std::os;
use std::io::File;
//use std::ops::BitXor;
fn main()
{
let args: ~[~str] = os::args();
if args.len() != 3
{
println!("Usage: {:s} <intputfile>", args[0]);
}
else | let fname_a = args[1].clone();
let path_a = Path::new(fname_a.clone());
let msg_file_a = File::open(&path_a);
let fname_b = args[2];
let path_b = Path::new(fname_b.clone());
let msg_file_b = File::open(&path_b);
match(msg_file_a, msg_file_b)
{
(Some(mut msg_a), Some(mut msg_b)) =>
{
let msg_... | { | random_line_split |
joiner.rs | use std::os;
use std::io::File;
//use std::ops::BitXor;
fn main()
{
let args: ~[~str] = os::args();
if args.len() != 3
{
println!("Usage: {:s} <intputfile>", args[0]);
}
else
{
let fname_a = args[1].clone();
let path_a = Path::new(fname_a.clone());
let msg_file_a = File::open(&path_a);
let fname_b =... | (a: &[u8], b: &[u8])-> ~[u8]
{
let mut ret = ~[];
for i in range(0, a.len())
{
ret.push(a[i] ^ b[i]);
}
ret
}
fn joiner(mut join: File, msg_bytes_a: &[u8], msg_bytes_b: &[u8])
{
let unencrypted_bytes = xor(msg_bytes_a, msg_bytes_b);
join.write((unencrypted_bytes));
} | xor | identifier_name |
joiner.rs | use std::os;
use std::io::File;
//use std::ops::BitXor;
fn main()
{
let args: ~[~str] = os::args();
if args.len() != 3
{
println!("Usage: {:s} <intputfile>", args[0]);
}
else
{
let fname_a = args[1].clone();
let path_a = Path::new(fname_a.clone());
let msg_file_a = File::open(&path_a);
let fname_b =... | ,
None => fail!("Error opening output files!"),
}
},
(_, _) => fail!("Error opening message file: {:s}", fname_a)
}
}
}
fn xor(a: &[u8], b: &[u8])-> ~[u8]
{
let mut ret = ~[];
for i in range(0, a.len())
{
ret.push(a[i] ^ b[i]);
}
ret
}
fn joiner(mut join: File, msg_bytes_a: &[u8], msg_byt... | {
joiner(join, msg_bytes_a, msg_bytes_b);
} | conditional_block |
joiner.rs | use std::os;
use std::io::File;
//use std::ops::BitXor;
fn main()
{
let args: ~[~str] = os::args();
if args.len() != 3
{
println!("Usage: {:s} <intputfile>", args[0]);
}
else
{
let fname_a = args[1].clone();
let path_a = Path::new(fname_a.clone());
let msg_file_a = File::open(&path_a);
let fname_b =... | {
let unencrypted_bytes = xor(msg_bytes_a, msg_bytes_b);
join.write((unencrypted_bytes));
} | identifier_body | |
demoSensorController.js | 'use strict';
// Load the application's configuration
const config = require('../server/config');
const url = config.express_host + '/api';
// Required modules
const async = require('async');
const colors = require('colors');
const request = require('request');
// Counter for the Measurements
let counter = 1;
/... | url: url + '/measurements',
json: measurementJson
}, function(error, response, body) {
if (!error) {
console.log(' New Measurement', ('#' + counter).cyan, 'created.'.green, '\nValue:', body.value.cyan);
counter++;
} else {
console.log(' New Measurement creation', 'failed'.red);
... | headers: {'content-type': 'application/json'}, | random_line_split |
demoSensorController.js | 'use strict';
// Load the application's configuration
const config = require('../server/config');
const url = config.express_host + '/api';
// Required modules
const async = require('async');
const colors = require('colors');
const request = require('request');
// Counter for the Measurements
let counter = 1;
/... |
console.log('\n------------------------------------------------------------\n');
callback(error, body._id);
});
},
// Create a new Feature
function(thingId, callback) {
console.log(' Creating a new', 'Feature...\n'.cyan);
const featureJson = {
name: 'demoFeature',
unit: 'foo',
token: ... | {
console.log(' New Thing creation', 'failed'.red);
} | conditional_block |
earthpos.js | /*
** Copyright 2013 Google Inc.
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to i... | MAX_SEARCH_RADIUS
);
},
error: function(jqXHR, textStatus, errorThrown) {
console.warn('Error fetching Earth posiition:', errorThrown);
}
};
$.ajax(
config.earth_pos_url,
ajax_opts
);
... | ll,
MIN_SEARCH_RADIUS,
self.searchCB.bind(self), | random_line_split |
infiniteBlock.ts | import {
_,
Autowired,
IGetRowsParams,
NumberSequence,
PostConstruct,
PreDestroy,
RowNode,
Autowired,
PostConstruct,
IGetRowsParams,
IEventEmitter,
RowNodeBlock,
RowRenderer,
_
} from "@ag-grid-community/core";
import { InfiniteCacheParams } from "./infiniteCache"... | (): void {
super.init();
}
public getNodeIdPrefix(): string {
return null;
}
public getRow(displayIndex: number): RowNode {
return this.getRowUsingLocalIndex(displayIndex);
}
protected processServerFail(): void {
// todo - this method has better handling in SSR... | init | identifier_name |
infiniteBlock.ts | import {
_,
Autowired,
IGetRowsParams,
NumberSequence,
PostConstruct,
PreDestroy,
RowNode,
Autowired,
PostConstruct,
IGetRowsParams,
IEventEmitter,
RowNodeBlock,
RowRenderer,
_
} from "@ag-grid-community/core";
import { InfiniteCacheParams } from "./infiniteCache"... |
public getDisplayIndexStart(): number {
return this.getBlockNumber() * this.cacheParams.blockSize;
}
// this is an estimate, as the last block will probably only be partially full. however
// this method is used to know if this block is been rendered, before destroying, so
// and this est... | {
super(pageNumber, params);
this.cacheParams = params;
} | identifier_body |
infiniteBlock.ts | import {
_,
Autowired,
IGetRowsParams,
NumberSequence,
PostConstruct,
PreDestroy,
RowNode,
Autowired,
PostConstruct,
IGetRowsParams,
IEventEmitter,
RowNodeBlock,
RowRenderer,
_
} from "@ag-grid-community/core";
import { InfiniteCacheParams } from "./infiniteCache"... |
}
protected processServerResult(params: LoadSuccessParams): void {
const rowNodesToRefresh: RowNode[] = [];
this.rowNodes.forEach((rowNode: RowNode, index: number) => {
const data = params.rowData ? params.rowData[index] : undefined;
if (rowNode.stub) {
... | {
const rowIndex = this.startRow + i;
const rowNode = this.getContext().createBean(new RowNode());
rowNode.setRowHeight(this.params.rowHeight);
rowNode.uiLevel = 0;
rowNode.setRowIndex(rowIndex);
rowNode.rowTop = this.params.rowHeight * rowIndex;... | conditional_block |
infiniteBlock.ts | import {
_,
Autowired,
IGetRowsParams,
NumberSequence,
PostConstruct,
PreDestroy,
RowNode,
Autowired,
PostConstruct,
IGetRowsParams,
IEventEmitter,
RowNodeBlock,
RowRenderer,
_
} from "@ag-grid-community/core";
import { InfiniteCacheParams } from "./infiniteCache"... | rowNode.uiLevel = 0;
this.setIndexAndTopOnRowNode(rowNode, rowIndex);
return rowNode;
}
protected setDataAndId(rowNode: RowNode, data: any, index: number): void {
if (_.exists(data)) {
// this means if the user is not providing id's we just use the
// i... | }
protected createBlankRowNode(rowIndex: number): RowNode {
const rowNode = super.createBlankRowNode();
| random_line_split |
dismantling.module.ts | import { NgModule } from '@angular/core';
import { SharedModule } from '../../shared/shared.module';
import { DismantlingRoutingModule } from './dismantling-routing.module';
import { DismantlingHomeComponent } from './dismantling-home/dismantling-home.component';
// import { DismantlingIdleComponent } from './dismantl... | { }
| DismantlingModule | identifier_name |
dismantling.module.ts | import { NgModule } from '@angular/core';
import { SharedModule } from '../../shared/shared.module';
import { DismantlingRoutingModule } from './dismantling-routing.module';
import { DismantlingHomeComponent } from './dismantling-home/dismantling-home.component';
// import { DismantlingIdleComponent } from './dismantl... | DismantlingRoutingModule
],
declarations: [DismantlingHomeComponent, /* DismantlingIdleComponent, */ DismantlingProgressingComponent, DismantlingCompletedComponent, DismantlingIdle2Component, DismantlingPreDismantlingComponent]
})
export class DismantlingModule { } | import { DismantlingPreDismantlingComponent } from './dismantling-pre-dismantling/dismantling-pre-dismantling.component';
@NgModule({
imports: [
SharedModule, | random_line_split |
formatUtils.ts | export const formatByteAmount = (
amount: number,
unit: "mebibyte" | "gibibyte"
) =>
`${(
amount / (unit === "mebibyte" ? Math.pow(1024, 2) : Math.pow(1024, 3))
).toFixed(1)} ${unit === "mebibyte" ? "MiB" : "GiB"}`;
export const formatUsage = (
used: number,
total: number,
unit: "mebibyte" | "gibibyt... | const durationHours = Math.floor(durationInSeconds / 60 / 60) % 24;
const durationDays = Math.floor(durationInSeconds / 60 / 60 / 24);
const pad = (value: number) => value.toString().padStart(2, "0");
return [
durationDays ? `${durationDays}d` : "",
`${pad(durationHours)}h`,
`${pad(durationMinutes)}... |
export const formatDuration = (durationInSeconds: number) => {
const durationSeconds = Math.floor(durationInSeconds) % 60;
const durationMinutes = Math.floor(durationInSeconds / 60) % 60; | random_line_split |
scope.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {ClassDeclaration} from '../../reflection';
import {SymbolWithValueDeclarati... | name: string;
} | * Name of the pipe.
*/ | random_line_split |
conversation-header.component.js | "use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Refl... | () {
}
ConversationHeaderComponent.prototype.ngOnInit = function () {
};
__decorate([
core_1.Input(),
__metadata('design:type', Object)
], ConversationHeaderComponent.prototype, "conversationDetailItem", void 0);
ConversationHeaderComponent = __decorate([
core_1.Componen... | ConversationHeaderComponent | identifier_name |
conversation-header.component.js | "use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Refl... |
ConversationHeaderComponent.prototype.ngOnInit = function () {
};
__decorate([
core_1.Input(),
__metadata('design:type', Object)
], ConversationHeaderComponent.prototype, "conversationDetailItem", void 0);
ConversationHeaderComponent = __decorate([
core_1.Component({
... | {
} | identifier_body |
conversation-header.component.js | "use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Refl... | ConversationHeaderComponent = __decorate([
core_1.Component({
selector: 'ngm-conversation-header',
styleUrls: ['./conversation-header.component.scss'],
templateUrl: './conversation-header.component.html'
}),
__metadata('design:paramtypes', [])
], Conv... | random_line_split | |
npEvents.js | 'use strict';
let db = require('server-lib').neo4j;
let parser = requireLib('iCalEventParser');
let eventExport = require('server-lib').eventExport;
let logger = require('server-lib').logging.getLogger(__filename);
let saveEventToDb = async function (event, idOrg, timestamp) {
return await db.cypher().match(`(org... |
} else {
logger.error(`Failed to parse iCal from project ${idOrg} / platform ${platformId}`);
}
};
module.exports = {
importEvent
};
| {
logger.error(`Failed to import event ${uid}. Parsed uid ${events[0].uid} of event is not the same`);
} | conditional_block |
npEvents.js | 'use strict';
let db = require('server-lib').neo4j;
let parser = requireLib('iCalEventParser');
let eventExport = require('server-lib').eventExport;
let logger = require('server-lib').logging.getLogger(__filename);
let saveEventToDb = async function (event, idOrg, timestamp) {
return await db.cypher().match(`(org... | };
let importEvent = async function (uid, timestamp, iCal, idOrg, platformId) {
let events = parser.parseEvents(iCal);
if (events.length === 1) {
if (events[0].uid === uid) {
let resp = await saveEventToDb(events[0], idOrg, timestamp);
if(resp.length === 1) {
awa... | .return(`org.organizationId AS organizationId`)
.end({uid: event.uid, idOrg: idOrg}).send(); | random_line_split |
DotScreenRGBShader.js | /**
* @author alteredq / http://alteredqualia.com/
*
* Dot screen shader
* based on glfx.js sepia shader
* https://github.com/evanw/glfx.js
*/
THREE.DotScreenRGBShader = {
uniforms: {
"tDiffuse": { type: "t", value: null },
"tSize": { type: "v2", value: new THREE.Vector2( 256, 256 ) },
"center": { ... | "float b = color.b * 10.0 - 5.0 + pattern();",
"gl_FragColor = vec4( r, g, b, color.a );",
"}"
].join("\n")
}; |
"float r = color.r * 10.0 - 5.0 + pattern();",
"float g = color.g * 10.0 - 5.0 + pattern();", | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.