file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
table.js | // GFM table, non-standard
'use strict';
function getLine(state, line) {
var pos = state.bMarks[line] + state.blkIndent,
max = state.eMarks[line];
return state.src.substr(pos, max - pos);
}
function escapedSplit(str) {
var result = [],
pos = 0,
max = str.length,
ch,
escapes = 0,... |
lineText = getLine(state, startLine + 1);
if (!/^[-:| ]+$/.test(lineText)) { return false; }
rows = lineText.split('|');
if (rows.length < 2) { return false; }
aligns = [];
for (i = 0; i < rows.length; i++) {
t = rows[i].trim();
if (!t) {
// allow empty columns before and after table, but n... | { return false; } | conditional_block |
table.js | // GFM table, non-standard
'use strict';
function getLine(state, line) {
var pos = state.bMarks[line] + state.blkIndent,
max = state.eMarks[line];
return state.src.substr(pos, max - pos);
}
function | (str) {
var result = [],
pos = 0,
max = str.length,
ch,
escapes = 0,
lastPos = 0,
backTicked = false,
lastBackTick = 0;
ch = str.charCodeAt(pos);
while (pos < max) {
if (ch === 0x60/* ` */ && (escapes % 2 === 0)) {
backTicked = !backTicked;
lastBackTick... | escapedSplit | identifier_name |
leave_message.py | #!/usr/bin/python
import cgi
from redis import Connection
from socket import gethostname
from navi import *
fields = cgi.FieldStorage()
title = "Message Box"
msg_prefix = 'custom.message.'
def | (cust, tm, msg):
conn = Connection(host=gethostname(),port=6379)
conn.send_command('set', msg_prefix+cust+'--'+tm, msg)
conn.disconnect()
def read_msg():
ret = ''
conn = Connection(host=gethostname(),port=6379)
conn.send_command('keys', msg_prefix+'*')
keys = conn.read_response()
va... | insert_msg | identifier_name |
leave_message.py | #!/usr/bin/python
import cgi
from redis import Connection
from socket import gethostname
from navi import *
fields = cgi.FieldStorage()
title = "Message Box"
msg_prefix = 'custom.message.'
def insert_msg(cust, tm, msg):
conn = Connection(host=gethostname(),port=6379)
conn.send_command('set', msg_prefix+cust... |
def reply():
import time, os
ret = ""
ret += "Content-Type: text/html\n\n"
ret += "<!DOCTYPE html>"
ret += "<html>"
ret += default_head(title)
ret += default_navigator()
ret += "<body>"
ret += "<div class=\"content\">"
ret += "<h2>Welcome, " + os.environ["REMOTE_ADDR"] + ... | ret = ''
conn = Connection(host=gethostname(),port=6379)
conn.send_command('keys', msg_prefix+'*')
keys = conn.read_response()
vals = []
if len(keys) != 0:
conn.send_command('mget', *keys)
vals = conn.read_response()
ret += "<h2>" + "Message log" + "</h2>"
for k, ... | identifier_body |
leave_message.py | #!/usr/bin/python
import cgi
from redis import Connection
from socket import gethostname
from navi import *
fields = cgi.FieldStorage()
title = "Message Box"
msg_prefix = 'custom.message.'
def insert_msg(cust, tm, msg):
conn = Connection(host=gethostname(),port=6379)
conn.send_command('set', msg_prefix+cust... |
ret += default_head(title)
ret += default_navigator()
ret += "<body>"
ret += "<div class=\"content\">"
ret += "<h2>Welcome, " + os.environ["REMOTE_ADDR"] + "!</h2>"
ret += "<span>" + os.environ["HTTP_USER_AGENT"] + "</span><br><br>"
if fields.has_key('msgbox'):
insert_msg(os.en... | ret += "<html>" | random_line_split |
leave_message.py | #!/usr/bin/python
import cgi
from redis import Connection
from socket import gethostname
from navi import *
fields = cgi.FieldStorage()
title = "Message Box"
msg_prefix = 'custom.message.'
def insert_msg(cust, tm, msg):
conn = Connection(host=gethostname(),port=6379)
conn.send_command('set', msg_prefix+cust... |
conn.disconnect()
ret += "<br>"
return ret
def reply():
import time, os
ret = ""
ret += "Content-Type: text/html\n\n"
ret += "<!DOCTYPE html>"
ret += "<html>"
ret += default_head(title)
ret += default_navigator()
ret += "<body>"
ret += "<div class=\"content\">"
... | conn.send_command('mget', *keys)
vals = conn.read_response()
ret += "<h2>" + "Message log" + "</h2>"
for k, v in zip(keys, vals):
ret += "<span>" + k.replace(msg_prefix, '').replace('--', ' ') + "</span>"
ret += "<pre readonly=\"true\">" + v + "</pre>" | conditional_block |
FieldPresence.ts | import { Adt, Fun } from '@ephox/katamari';
export type StrictField<T> = () => T;
export type DefaultedThunkField<T> = (fallbackThunk: (...rest: any[]) => any) => T;
export type AsOptionField<T> = () => T;
export type AsDefaultedOptionThunkField<T> = (fallbackThunk: (...rest: any[]) => any) => T;
export type MergeWith... | mergeWithThunk: MergeWithThunkField<FieldPresenceAdt>;
} = Adt.generate([
{ strict: [ ] },
{ defaultedThunk: [ 'fallbackThunk' ] },
{ asOption: [ ] },
{ asDefaultedOptionThunk: [ 'fallbackThunk' ] },
{ mergeWithThunk: [ 'baseThunk' ] }
]);
const defaulted = <T>(fallback: T): FieldPresenceAdt => {
return ... | defaultedThunk: DefaultedThunkField<FieldPresenceAdt>;
asOption: AsOptionField<FieldPresenceAdt>;
asDefaultedOptionThunk: MergeWithThunkField<FieldPresenceAdt>; | random_line_split |
no_0215_kth_largest_element_in_an_array.rs | struct Solution;
use std::cmp::Ordering;
impl Solution {
// by zhangyuchen.
pub fn find_kth_largest(mut nums: Vec<i32>, k: i32) -> i32 {
Self::find(&mut nums, k as usize)
}
fn find(nums: &mut [i32], k: usize) -> i32 {
let mut pos = 1; // 第一个大于等于哨兵的位置
let sentinel = nums[0]; //... | identifier_name | ||
no_0215_kth_largest_element_in_an_array.rs | struct Solution;
use std::cmp::Ordering;
impl Solution {
// by zhangyuchen.
pub fn find_kth_largest(mut nums: Vec<i32>, k: i32) -> i32 {
Self::find(&mut nums, k as usize)
}
fn find(nums: &mut [i32], k: usize) -> i32 { | // 小于哨兵的放到哨兵左侧
let temp = nums[pos];
nums[pos] = nums[i];
nums[i] = temp;
pos += 1;
}
}
// 把哨兵放到它应该在的位置, pos-1 是最靠右的小于哨兵的位置
let temp = nums[pos - 1];
nums[pos - 1] = sentinel;
nums[0] = te... | let mut pos = 1; // 第一个大于等于哨兵的位置
let sentinel = nums[0]; // 哨兵
for i in 1..nums.len() {
if nums[i] < sentinel { | random_line_split |
all_8.js | var searchData=
[
['haier_443',['haier',['../classIRac.html#ae0a29a4cb8c7a4707a7725c576822a58',1,'IRac']]],
['haier_5fac_444',['HAIER_AC',['../IRremoteESP8266_8h.html#ad5b287a488a8c1b7b8661f029ab56fada1f232bcdf330ec2e353196941b9f1628',1,'IRremoteESP8266.h']]],
['haier_5fac_5fyrw02_445',['HAIER_AC_YRW02',['../IRre... | ['header1_455',['Header1',['../structCoronaSection.html#a3d6d6c1e31f82a76cd88f81bcdb83a3a',1,'CoronaSection']]],
['health_456',['Health',['../unionHaierProtocol.html#a4cf70c633e33066e3fc0f98bb2ad3820',1,'HaierProtocol::Health()'],['../unionHaierYRW02Protocol.html#a7fa39803fd72a788736bb8f00acfa76f',1,'HaierYRW02Prot... | ['hasacstate_451',['hasACState',['../IRutils_8cpp.html#a6efd4986db60709d3501606ec7ab5382',1,'hasACState(const decode_type_t protocol): IRutils.cpp'],['../IRutils_8h.html#a6efd4986db60709d3501606ec7ab5382',1,'hasACState(const decode_type_t protocol): IRutils.cpp']]],
['hasinvertedstates_452',['hasInvertedS... | random_line_split |
build_cosine_tables.py | import os
import string
import codecs
import ast
import math
from vector3 import Vector3
filename_out = "../../Assets/cosine_table"
table_size = 512
fixed_point_precision = 512
def dumpCosine(_cosine_func, display_name, f):
f.write('const int ' + display_name + '[] =' + '\n')
f.write('{' + '\n')
... |
main() | f = codecs.open(filename_out + '.h', 'w')
f.write('#define COSINE_TABLE_LEN ' + str(table_size) + '\n')
f.write('\n')
f.write('extern const int tcos[COSINE_TABLE_LEN];' + '\n')
f.write('extern const int tsin[COSINE_TABLE_LEN];' + '\n')
f.close()
## Creates the C file
f = codecs.open(filename_out +... | identifier_body |
build_cosine_tables.py | import os
import string
import codecs
import ast
import math
from vector3 import Vector3
filename_out = "../../Assets/cosine_table"
table_size = 512
fixed_point_precision = 512
def | (_cosine_func, display_name, f):
f.write('const int ' + display_name + '[] =' + '\n')
f.write('{' + '\n')
# _str_out = '\t'
for angle in range(0,table_size):
_cos = int(_cosine_func(angle * math.pi / (table_size / 2.0)) * fixed_point_precision)
_str_out = str(_cos) + ','
f.write(_str_out + '\n')
#... | dumpCosine | identifier_name |
build_cosine_tables.py | import os
import string
import codecs
import ast
import math
from vector3 import Vector3
filename_out = "../../Assets/cosine_table"
table_size = 512
fixed_point_precision = 512
def dumpCosine(_cosine_func, display_name, f):
f.write('const int ' + display_name + '[] =' + '\n')
f.write('{' + '\n')
... |
f.write('};' + '\n')
def main():
## Creates the header
f = codecs.open(filename_out + '.h', 'w')
f.write('#define COSINE_TABLE_LEN ' + str(table_size) + '\n')
f.write('\n')
f.write('extern const int tcos[COSINE_TABLE_LEN];' + '\n')
f.write('extern const int tsin[COSINE_TABLE_LEN];' + '\n')
f... | _cos = int(_cosine_func(angle * math.pi / (table_size / 2.0)) * fixed_point_precision)
_str_out = str(_cos) + ','
f.write(_str_out + '\n')
# if angle%10 == 9:
# f.write(_str_out + '\n')
# _str_out = '\t'
| conditional_block |
build_cosine_tables.py | import os
import string
import codecs
import ast
import math
| from vector3 import Vector3
filename_out = "../../Assets/cosine_table"
table_size = 512
fixed_point_precision = 512
def dumpCosine(_cosine_func, display_name, f):
f.write('const int ' + display_name + '[] =' + '\n')
f.write('{' + '\n')
# _str_out = '\t'
for angle in range(0,table_size):
_cos ... | random_line_split | |
cellEditorOptions.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | else {
cell.lineNumbers = 'on';
}
}
});
| {
cell.lineNumbers = 'off';
} | conditional_block |
cellEditorOptions.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | () {
super({
id: 'notebook.toggleLineNumbers',
title: { value: localize('notebook.toggleLineNumbers', "Toggle Notebook Line Numbers"), original: 'Toggle Notebook Line Numbers' },
precondition: NOTEBOOK_EDITOR_FOCUSED,
menu: [
{
id: MenuId.NotebookToolbar,
group: 'notebookLayout',
order:... | constructor | identifier_name |
cellEditorOptions.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | configurationService.updateValue('notebook.lineNumbers', 'off');
} else {
configurationService.updateValue('notebook.lineNumbers', 'on');
}
}
});
registerAction2(class ToggleActiveLineNumberAction extends NotebookMultiCellAction {
constructor() {
super({
id: 'notebook.cell.toggleLineNumbers',
title... | const renderLiNumbers = configurationService.getValue<'on' | 'off'>('notebook.lineNumbers') === 'on';
if (renderLiNumbers) { | random_line_split |
cellEditorOptions.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
setLineNumbers(lineNumbers: 'on' | 'off' | 'inherit'): void {
this._lineNumbers = lineNumbers;
if (this._lineNumbers === 'inherit') {
const renderLiNumbers = this.configurationService.getValue<'on' | 'off'>('notebook.lineNumbers') === 'on';
const lineNumbers: LineNumbersType = renderLiNumbers ? 'on' : 'off... | {
return {
...this._value,
...{
padding: { top: 12, bottom: 12 }
}
};
} | identifier_body |
readerrdy.js | // Generated by CoffeeScript 1.6.3
var BackoffTimer, ConnectionRdy, ConnectionRdyState, EventEmitter, NSQDConnection, NodeState, READER_COUNT, ReaderRdy, RoundRobinList, StateChangeLogger, _,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, ke... |
};
ReaderRdy.prototype.bump = function() {
var conn, _i, _len, _ref, _results;
_ref = this.connections;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
conn = _ref[_i];
_results.push(conn.bump());
}
return _results;
};
ReaderRdy.prototype["try"] = functi... | {
return this.goto('ZERO');
} | conditional_block |
readerrdy.js | // Generated by CoffeeScript 1.6.3
var BackoffTimer, ConnectionRdy, ConnectionRdyState, EventEmitter, NSQDConnection, NodeState, READER_COUNT, ReaderRdy, RoundRobinList, StateChangeLogger, _,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, ke... |
ConnectionRdyState.prototype.log = function(message) {
return this.connRdy.log(message);
};
ConnectionRdyState.prototype.states = {
INIT: {
bump: function() {
if (this.connRdy.maxConnRdy > 0) {
return this.goto('MAX');
}
},
backoff: function() {},
adjus... | {
this.connRdy = connRdy;
ConnectionRdyState.__super__.constructor.call(this, {
autostart: false,
initial_state: 'INIT',
sync_goto: true
});
} | identifier_body |
readerrdy.js | // Generated by CoffeeScript 1.6.3
var BackoffTimer, ConnectionRdy, ConnectionRdyState, EventEmitter, NSQDConnection, NodeState, READER_COUNT, ReaderRdy, RoundRobinList, StateChangeLogger, _,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, ke... | (connRdy) {
this.connRdy = connRdy;
ConnectionRdyState.__super__.constructor.call(this, {
autostart: false,
initial_state: 'INIT',
sync_goto: true
});
}
ConnectionRdyState.prototype.log = function(message) {
return this.connRdy.log(message);
};
ConnectionRdyState.prototype.st... | ConnectionRdyState | identifier_name |
readerrdy.js | // Generated by CoffeeScript 1.6.3
var BackoffTimer, ConnectionRdy, ConnectionRdyState, EventEmitter, NSQDConnection, NodeState, READER_COUNT, ReaderRdy, RoundRobinList, StateChangeLogger, _,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, ke... | ConnectionRdyState.prototype.log = function(message) {
return this.connRdy.log(message);
};
ConnectionRdyState.prototype.states = {
INIT: {
bump: function() {
if (this.connRdy.maxConnRdy > 0) {
return this.goto('MAX');
}
},
backoff: function() {},
adjustM... | random_line_split | |
connect-four.js | /**
* Minimax Implementation
* @jQuery version
*/
function Game() {
this.rows = 6; // Height
this.columns = 7; // Width
this.status = 0; // 0: running, 1: won, 2: lost, 3: tie
this.depth = 4; // Search depth
this.score = 100000, // Win/loss score
this.round = 0; // 0: Human, 1: Computer
... |
}
/**
* On-click event
*/
Game.prototype.act = function(e) {
var element = e.target || window.event.srcElement;
// Check if not in animation and start with human
if (!($('#coin').is(":animated"))) {
if (that.round == 0) {
that.place(element.cellIndex);
}
}
}
/**
* Plac... | {
if (td[i].addEventListener) {
td[i].addEventListener('click', that.act, false);
} else if (td[i].attachEvent) {
td[i].attachEvent('click', that.act)
}
} | conditional_block |
connect-four.js | /**
* Minimax Implementation
* @jQuery version
*/
function Game() |
Game.prototype.init = function() {
// Generate 'real' board
// Create 2-dimensional array
var game_board = new Array(that.rows);
for (var i = 0; i < game_board.length; i++) {
game_board[i] = new Array(that.columns);
for (var j = 0; j < game_board[i].length; j++) {
game_boa... | {
this.rows = 6; // Height
this.columns = 7; // Width
this.status = 0; // 0: running, 1: won, 2: lost, 3: tie
this.depth = 4; // Search depth
this.score = 100000, // Win/loss score
this.round = 0; // 0: Human, 1: Computer
this.winning_array = []; // Winning (chips) array
this.iterations ... | identifier_body |
connect-four.js | /**
* Minimax Implementation
* @jQuery version
*/
function Game() {
this.rows = 6; // Height
this.columns = 7; // Width
this.status = 0; // 0: running, 1: won, 2: lost, 3: tie
this.depth = 4; // Search depth
this.score = 100000, // Win/loss score
this.round = 0; // 0: Human, 1: Computer
... | for (var i = 0; i < that.rows; i++) {
game_board += "<tr>";
for (var j = 0; j < that.columns; j++) {
game_board += "<td class='empty'></td>";
}
game_board += "</tr>";
}
document.getElementById('game_board').innerHTML = game_board;
// Action listeners
var... | this.board = new Board(this, game_board, 0);
// Generate visual board
var game_board = "<col/><col/><col/><col/><col/><col/><col/>"; | random_line_split |
connect-four.js | /**
* Minimax Implementation
* @jQuery version
*/
function | () {
this.rows = 6; // Height
this.columns = 7; // Width
this.status = 0; // 0: running, 1: won, 2: lost, 3: tie
this.depth = 4; // Search depth
this.score = 100000, // Win/loss score
this.round = 0; // 0: Human, 1: Computer
this.winning_array = []; // Winning (chips) array
this.iteratio... | Game | identifier_name |
index.js | var utils = require('./utils')
, implode = require('implode')
exports.State = require('./state')
exports.initialize = exports.State.init
exports.Template = require('./template')
exports.Fragment = require('./fragment')
exports.Routes = {}
var isServer = exports.isServer = utils.isServer
, isClient = exports.i... | (href) {
var origin = location.protocol + "//" + location.hostname + ":" + location.port
return href.indexOf('http') == -1 || href.indexOf(origin) === 0
}
document.body.addEventListener('click', function(e) {
if (e.ctrlKey || e.metaKey) return
if (e.defaultPrevented) return
// ensure link
... | sameOrigin | identifier_name |
index.js | var utils = require('./utils')
, implode = require('implode')
exports.State = require('./state')
exports.initialize = exports.State.init
exports.Template = require('./template')
exports.Fragment = require('./fragment')
exports.Routes = {}
var isServer = exports.isServer = utils.isServer
, isClient = exports.i... |
document.body.addEventListener('click', function(e) {
if (e.ctrlKey || e.metaKey) return
if (e.defaultPrevented) return
// ensure link
var el = e.target
while (el && 'A' != el.nodeName) el = el.parentNode
if (!el || 'A' != el.nodeName) return
// if the `data-external` attribute is set ... | {
var origin = location.protocol + "//" + location.hostname + ":" + location.port
return href.indexOf('http') == -1 || href.indexOf(origin) === 0
} | identifier_body |
index.js | var utils = require('./utils')
, implode = require('implode')
exports.State = require('./state')
exports.initialize = exports.State.init
exports.Template = require('./template')
exports.Fragment = require('./fragment')
exports.Routes = {}
var isServer = exports.isServer = utils.isServer
, isClient = exports.i... | })
document.body.addEventListener('submit', function(e) {
var el = e.target
// if the `data-side` attribute is set to `server`, do not
// intercept this link
if (el.dataset.side === 'server') return
var origin = window.location.protocol + "//" + window.location.host
, method = el.meth... | })
page.dispatch(ctx)
if (!ctx.unhandled && !Boolean(el.dataset.silent)) {
ctx.pushState()
} | random_line_split |
config.js | const _ = require('lodash');
let defaults = {
PORT: 3000,
METADATA_CRON_SCHEDULE: '0 0 * * Monday', // update file from gprofiler etc. (Monday at midnight)
PC_URL: 'https://www.pathwaycommons.org/',
XREF_SERVICE_URL: 'https://biopax.baderlab.org/',
DOWNLOADS_FOLDER_NAME: 'downloads',
GPROFILER_URL: "https:... |
}
let conf = Object.assign( {}, defaults, envVars );
Object.freeze( conf );
module.exports = conf;
| {
delete envVars[key];
} | conditional_block |
config.js | const _ = require('lodash');
let defaults = { | METADATA_CRON_SCHEDULE: '0 0 * * Monday', // update file from gprofiler etc. (Monday at midnight)
PC_URL: 'https://www.pathwaycommons.org/',
XREF_SERVICE_URL: 'https://biopax.baderlab.org/',
DOWNLOADS_FOLDER_NAME: 'downloads',
GPROFILER_URL: "https://biit.cs.ut.ee/gprofiler/",
GMT_ARCHIVE_URL: 'https://biit... | PORT: 3000, | random_line_split |
enigma-gui-resizable-window.py | #!/usr/bin/python3
from tkinter import *
from tkinter.messagebox import *
fenetre = Tk()
fenetre.title("The Enigma Machine")
fenetre.configure(background='white')
fenetre.geometry("550x800")
class AutoScrollbar(Scrollbar):
#create a 'responsive' scrollbar
def set(self, lo, hi):
if float(lo) <= 0.0 and ... |
vscrollbar = AutoScrollbar(fenetre)
vscrollbar.grid(row=0, column=1, sticky=N+S)
hscrollbar = AutoScrollbar(fenetre, orient=HORIZONTAL)
hscrollbar.grid(row=1, column=0, sticky=E+W)
canvas = Canvas(fenetre,
yscrollcommand=vscrollbar.set,
xscrollcommand=hscrollbar.set)
canvas.grid(row=0... | raise(TclError, "can't grid this widget") | identifier_body |
enigma-gui-resizable-window.py | #!/usr/bin/python3
from tkinter import *
from tkinter.messagebox import *
fenetre = Tk()
fenetre.title("The Enigma Machine")
fenetre.configure(background='white')
fenetre.geometry("550x800")
class AutoScrollbar(Scrollbar):
#create a 'responsive' scrollbar
def set(self, lo, hi):
if float(lo) <= 0.0 and ... |
liste.delete(0, END)
#button_to_(de)code
b1 = Button(frame, text="(de)code", width=10, command=code, background="white")
b1.pack()
#store_results
f1 = Frame(frame)
s1 = Scrollbar(f1)
liste = Listbox(f1, height=5, width=50, borderwidth=0, background='white')
s1.config(command = liste.yview)
liste.config(yscrollco... | ar(): | identifier_name |
enigma-gui-resizable-window.py | #!/usr/bin/python3
from tkinter import *
from tkinter.messagebox import *
fenetre = Tk()
fenetre.title("The Enigma Machine")
fenetre.configure(background='white')
fenetre.geometry("550x800")
class AutoScrollbar(Scrollbar):
#create a 'responsive' scrollbar
def set(self, lo, hi):
if float(lo) <= 0.0 and ... | #rotor2 = ['N','T','Z','P','S','F','B','O','K','M','W','R','C','J','D','I','V','L','A','E','Y','U','X','H','G','Q']
#rotor3 = ['J','V','I','U','B','H','T','C','D','Y','A','K','E','Q','Z','P','O','S','G','X','N','R','M','W','F','L']
reflector = ['Y', 'R', 'U', 'H', 'Q', 'S', 'L', 'D', 'P', 'X', 'N', 'G', 'O'... | random_line_split | |
enigma-gui-resizable-window.py | #!/usr/bin/python3
from tkinter import *
from tkinter.messagebox import *
fenetre = Tk()
fenetre.title("The Enigma Machine")
fenetre.configure(background='white')
fenetre.geometry("550x800")
class AutoScrollbar(Scrollbar):
#create a 'responsive' scrollbar
def set(self, lo, hi):
if float(lo) <= 0.0 and ... | value = StringVar()
value.set(''.join(s))
liste.insert(END, value.get())
liste.see("end")
#text_entry
entryvar = StringVar()
entry = Entry(frame, textvariable = entryvar, width=50, background="white")
entry.focus_set()
entry.bind("<Return>", code)
entry.pack(padx=10, pady=10)
#clear_list... | alphabetDict[sortieListe[i].upper()]
b = rotor1[a-1]
c = alphabetDict[b]
d = rotor2[c-1]
e = alphabetDict[d]
f = rotor3[e-1]
g = alphabetDict[f]
h = reflector[g-1]
j = rotor3.index(h)
k = alphabetList[j]
... | conditional_block |
koa.ts | // Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | ip: '0.0.0.0',
};
const FULL_RES_DERIVATION_VALUE = {
status: 200,
};
const FULL_REQ_EXPECTED_VALUE = {
method: 'STUB_METHOD',
url: 'www.TEST-URL.com',
userAgent: 'Something like Mozilla',
referrer: 'www.ANOTHER-TEST.com',
remoteAddress: '0... | random_line_split | |
localshell.ts | ///<reference path='refs.ts'/>
module TDev {
export var baseUrl: string = "./";
export module LocalShell {
export function localProxyHandler() {
return function (cmd, data) {
if (cmd == "shell") return LocalShell.runShellAsync(data)
else return LocalShell.mg... |
export function mgmtRequestAsync(path: string, data?: any): Promise {
Util.log("shell mgmtRequest " + path)
if (!data) return Util.httpGetJsonAsync(mgmtUrl(path))
else return Util.httpPostRealJsonAsync(mgmtUrl(path), data)
}
var lastShell: WebSocket = undef... | {
if (path && !/^\//.test(path)) path = "/" + path
var localProxy = window.localStorage.getItem("local_proxy")
if (localProxy) {
var r = localProxy + path
Util.log('shell: local proxy {0}', r);
return r
}
var t... | identifier_body |
localshell.ts | ///<reference path='refs.ts'/>
module TDev {
export var baseUrl: string = "./";
export module LocalShell {
export function localProxyHandler() {
return function (cmd, data) {
if (cmd == "shell") return LocalShell.runShellAsync(data)
else return LocalShell.mg... |
var tok = window.localStorage.getItem("td_deployment_key")
if (!tok) {
Util.log('shell: missing deployment key');
return null
}
var m = /(.*:\/\/[^\/]+\/)/.exec(baseUrl)
if (!m) {
Util.log('shell: invalid base... | {
var r = localProxy + path
Util.log('shell: local proxy {0}', r);
return r
} | conditional_block |
localshell.ts | ///<reference path='refs.ts'/>
module TDev {
export var baseUrl: string = "./";
export module LocalShell {
export function localProxyHandler() {
return function (cmd, data) {
if (cmd == "shell") return LocalShell.runShellAsync(data)
else return LocalShell.mg... | } | random_line_split | |
localshell.ts | ///<reference path='refs.ts'/>
module TDev {
export var baseUrl: string = "./";
export module LocalShell {
export function localProxyHandler() {
return function (cmd, data) {
if (cmd == "shell") return LocalShell.runShellAsync(data)
else return LocalShell.mg... | (path: string): string {
if (path && !/^\//.test(path)) path = "/" + path
var localProxy = window.localStorage.getItem("local_proxy")
if (localProxy) {
var r = localProxy + path
Util.log('shell: local proxy {0}', r);
return r
... | mgmtUrl | identifier_name |
text_view.rs | use std::ops::Deref;
use std::sync::Arc;
use std::sync::{Mutex, MutexGuard};
use owning_ref::{ArcRef, OwningHandle};
use unicode_width::UnicodeWidthStr;
use crate::align::*;
use crate::theme::Effect;
use crate::utils::lines::spans::{LinesIterator, Row};
use crate::utils::markup::StyledString;
use crate::view::{SizeCa... |
/// Sets the alignment for this view.
pub fn align(mut self, a: Align) -> Self {
self.align = a;
self
}
/// Center the text horizontally and vertically inside the view.
pub fn center(mut self) -> Self {
self.align = Align::center();
self
}
/// Replace the... | {
self.align.v = v;
self
} | identifier_body |
text_view.rs | use std::ops::Deref;
use std::sync::Arc;
use std::sync::{Mutex, MutexGuard};
use owning_ref::{ArcRef, OwningHandle};
use unicode_width::UnicodeWidthStr;
use crate::align::*;
use crate::theme::Effect;
use crate::utils::lines::spans::{LinesIterator, Row};
use crate::utils::markup::StyledString;
use crate::view::{SizeCa... | (self) -> Self {
self.with(|s| s.set_content_wrap(false))
}
/// Controls content wrap for this view.
///
/// If `true` (the default), text will wrap long lines when needed.
pub fn set_content_wrap(&mut self, wrap: bool) {
self.wrap = wrap;
}
/// Sets the horizontal alignmen... | no_wrap | identifier_name |
text_view.rs | use std::ops::Deref;
use std::sync::Arc;
use std::sync::{Mutex, MutexGuard};
use owning_ref::{ArcRef, OwningHandle};
use unicode_width::UnicodeWidthStr;
use crate::align::*;
use crate::theme::Effect;
use crate::utils::lines::spans::{LinesIterator, Row};
use crate::utils::markup::StyledString;
use crate::view::{SizeCa... | >,
// We also need to keep a copy of Arc so `deref` can return
// a reference to the `StyledString`
data: Arc<StyledString>,
}
impl Deref for TextContentRef {
type Target = StyledString;
fn deref(&self) -> &StyledString {
self.data.as_ref()
}
}
impl TextContent {
/// Replaces ... | ArcRef<Mutex<TextContentInner>>,
MutexGuard<'static, TextContentInner>, | random_line_split |
zk_test_mkdirp.js | var ZK = require ('../lib/zookeeper');
var assert = require('assert');
var log4js = require('log4js');
var async = require('async');
//
// based on node-leader
// https://github.com/mcavage/node-leader
// callback(error, zookeeperConnection)
//
function startZK(options, callback) |
if (require.main === module) {
var options = {
zookeeper: 'localhost:2181',
log4js: log4js
};
var PATH = '/mkdirp/test/path/of/death/n/destruction';
var con = null;
startZK(options, function(err, connection) {
if(err) return console.log(err);
con = connection;
return con.mkdirp(PATH, on... | {
if(typeof(options) !== 'object')
throw new TypeError('options (Object) required');
if(typeof(options.zookeeper) !== 'string')
throw new TypeError('options.zookeeper (String) required');
if(typeof(options.log4js) !== 'object')
throw new TypeError('options.log4js (Object) required');
if(options.time... | identifier_body |
zk_test_mkdirp.js | var ZK = require ('../lib/zookeeper');
var assert = require('assert');
var log4js = require('log4js');
var async = require('async');
//
// based on node-leader
// https://github.com/mcavage/node-leader
// callback(error, zookeeperConnection)
//
function startZK(options, callback) {
if(typeof(options) !== 'object')
... | , function (cb) { con.a_delete_(dirs[5], 0, normalizeCb(cb)); }
, function (cb) { con.a_delete_(dirs[6], 0, normalizeCb(cb)); }
], function(err, results) {
console.log('Deleted mkdirp`ed dirs: '+results.length+' of '+dirs.length);
process.exit(0);
});
}
// allows a callback that exp... | , function (cb) { con.a_delete_(dirs[3], 0, normalizeCb(cb)); }
, function (cb) { con.a_delete_(dirs[4], 0, normalizeCb(cb)); } | random_line_split |
zk_test_mkdirp.js | var ZK = require ('../lib/zookeeper');
var assert = require('assert');
var log4js = require('log4js');
var async = require('async');
//
// based on node-leader
// https://github.com/mcavage/node-leader
// callback(error, zookeeperConnection)
//
function startZK(options, callback) {
if(typeof(options) !== 'object')
... | (err, win) {
assert.ifError(err);
// make sure the path now exists :)
con.a_exists(PATH, null, function(rc, error, stat) {
if(rc != 0) {
throw new Error('Zookeeper Error: code='+rc+' '+error);
}
// path already exists, do nothing :)
assert.ok(stat);
return mkDirpAgai... | onMkdir | identifier_name |
angular-gantt-resizeSensor-plugin.js | /*
Project: angular-gantt v1.2.8 - Gantt chart component for AngularJS
Authors: Marco Schweighauser, Rémi Alvergnat
License: MIT
Homepage: https://www.angular-gantt.com
Github: https://github.com/angular-gantt/angular-gantt.git
*/
(function(){
/* global ResizeSensor: false */
/* global ElementQueries: false */
... |
var rendered = false;
api.core.on.rendered(scope, function() {
rendered = true;
if (sensor !== undefined) {
sensor.detach();
}
if (scope.enabled) {
ElementQuer... |
var ganttElement = element.parent().parent().parent()[0].querySelectorAll('div.gantt')[0];
return new ResizeSensor(ganttElement, function() {
ganttCtrl.gantt.$scope.ganttElementWidth = ganttElement.clientWidth;
ganttCtrl.gantt.$sco... | identifier_body |
angular-gantt-resizeSensor-plugin.js | /*
Project: angular-gantt v1.2.8 - Gantt chart component for AngularJS
Authors: Marco Schweighauser, Rémi Alvergnat
License: MIT
Homepage: https://www.angular-gantt.com
Github: https://github.com/angular-gantt/angular-gantt.git
*/
(function(){
/* global ResizeSensor: false */
/* global ElementQueries: false */
... | ) {
var ganttElement = element.parent().parent().parent()[0].querySelectorAll('div.gantt')[0];
return new ResizeSensor(ganttElement, function() {
ganttCtrl.gantt.$scope.ganttElementWidth = ganttElement.clientWidth;
ganttCtrl.gantt.$... | uildSensor( | identifier_name |
angular-gantt-resizeSensor-plugin.js | /*
Project: angular-gantt v1.2.8 - Gantt chart component for AngularJS
Authors: Marco Schweighauser, Rémi Alvergnat
License: MIT
Homepage: https://www.angular-gantt.com
Github: https://github.com/angular-gantt/angular-gantt.git
*/
(function(){
/* global ResizeSensor: false */
/* global ElementQueries: false */
... | if (scope.enabled) {
ElementQueries.update();
sensor = buildSensor();
}
});
var sensor;
scope.$watch('enabled', function(newValue) {
if (rendered) {
... |
sensor.detach();
}
| conditional_block |
angular-gantt-resizeSensor-plugin.js | /*
Project: angular-gantt v1.2.8 - Gantt chart component for AngularJS
Authors: Marco Schweighauser, Rémi Alvergnat
License: MIT
Homepage: https://www.angular-gantt.com
Github: https://github.com/angular-gantt/angular-gantt.git
*/
(function(){
/* global ResizeSensor: false */
/* global ElementQueries: false */
... | restrict: 'E',
require: '^gantt',
scope: {
enabled: '=?'
},
link: function(scope, element, attrs, ganttCtrl) {
var api = ganttCtrl.gantt.api;
// Load options from global options attribute.
if (sc... | angular.module('gantt.resizeSensor', ['gantt']).directive('ganttResizeSensor', [function() {
return { | random_line_split |
regions-fn-subtyping-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 has_same_region(f: &fn<'a>(x: &'a int, g: &fn(y: &'a int))) {
// `f` should be the type that `wants_same_region` wants, but
// right now the compiler complains that it isn't.
wants_same_region(f);
}
fn wants_same_region(_f: &fn<'b>(x: &'b int, g: &fn(y: &'b int))) {
}
pub fn main() {
} | random_line_split | |
regions-fn-subtyping-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-fn-subtyping-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 ... |
pub fn main() {
}
| {
} | identifier_body |
tabs.py | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
# Copyright 2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use t... |
def allowed(self, request):
return network.floating_ip_supported(request)
class APIAccessTab(tabs.TableTab):
table_classes = (EndpointsTable,)
name = _("API Access")
slug = "api_access_tab"
template_name = "horizon/common/_detail_table.html"
def get_endpoints_data(self):
ser... | try:
floating_ips = network.tenant_floating_ip_list(self.request)
except neutron_exc.ConnectionFailed:
floating_ips = []
exceptions.handle(self.request)
except Exception:
floating_ips = []
exceptions.handle(self.request,
... | identifier_body |
tabs.py | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
# Copyright 2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use t... | from openstack_dashboard.api import nova
from openstack_dashboard.dashboards.project.access_and_security.\
api_access.tables import EndpointsTable
from openstack_dashboard.dashboards.project.access_and_security.\
floating_ips.tables import FloatingIPsTable
from openstack_dashboard.dashboards.project.access_and... |
from neutronclient.common import exceptions as neutron_exc
from openstack_dashboard.api import keystone
from openstack_dashboard.api import network | random_line_split |
tabs.py | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
# Copyright 2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use t... |
return floating_ips
def allowed(self, request):
return network.floating_ip_supported(request)
class APIAccessTab(tabs.TableTab):
table_classes = (EndpointsTable,)
name = _("API Access")
slug = "api_access_tab"
template_name = "horizon/common/_detail_table.html"
def get_endp... | ip.instance_name = instances_dict.get(ip.instance_id)
ip.pool_name = pool_dict.get(ip.pool, ip.pool) | conditional_block |
tabs.py | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
# Copyright 2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use t... | (self):
try:
floating_ips = network.tenant_floating_ip_list(self.request)
except neutron_exc.ConnectionFailed:
floating_ips = []
exceptions.handle(self.request)
except Exception:
floating_ips = []
exceptions.handle(self.request,
... | get_floating_ips_data | identifier_name |
unitConvertUtils.spec.ts | import { unitConvertUtils } from './unitConvertUtils'
import { PLNumber, plNumber, plString } from 'pocket-lisp-stdlib'
import { floatEq } from '../../utils/math'
export function | (a: PLNumber, b: PLNumber): boolean {
return floatEq(a.value, b.value)
}
const pln = plNumber
const pls = plString
describe('convert utils', () => {
test('convert-unit', () => {
const fn = unitConvertUtils['convert-unit']
expect(() => {
fn(pln(1), pls('from'), pls('to'))
}).toThrow('Invalid unit... | floatEqPL | identifier_name |
unitConvertUtils.spec.ts | import { unitConvertUtils } from './unitConvertUtils'
import { PLNumber, plNumber, plString } from 'pocket-lisp-stdlib'
import { floatEq } from '../../utils/math'
export function floatEqPL(a: PLNumber, b: PLNumber): boolean |
const pln = plNumber
const pls = plString
describe('convert utils', () => {
test('convert-unit', () => {
const fn = unitConvertUtils['convert-unit']
expect(() => {
fn(pln(1), pls('from'), pls('to'))
}).toThrow('Invalid unit: "from"')
expect(() => {
fn(pln(1), pls('kg'), pls('s'))
})... | {
return floatEq(a.value, b.value)
} | identifier_body |
unitConvertUtils.spec.ts | import { unitConvertUtils } from './unitConvertUtils'
import { PLNumber, plNumber, plString } from 'pocket-lisp-stdlib'
import { floatEq } from '../../utils/math'
export function floatEqPL(a: PLNumber, b: PLNumber): boolean {
return floatEq(a.value, b.value)
}
const pln = plNumber
const pls = plString
describe('co... | }).toThrow('Invalid unit: "from"')
expect(() => {
fn(pln(1), pls('kg'), pls('s'))
}).toThrow('Units "kg" and "s" don\\\'t match')
expect(floatEqPL(fn(pln(10), pls('kg'), pls('g')), pln(10000))).toBe(true)
expect(floatEqPL(fn(pln(2), pls('h'), pls('s')), pln(7200))).toBe(true)
expect(floatE... | test('convert-unit', () => {
const fn = unitConvertUtils['convert-unit']
expect(() => {
fn(pln(1), pls('from'), pls('to')) | random_line_split |
types.rs | use game::{Position, Move, Score, NumPlies, NumMoves};
#[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Debug)]
pub struct NumNodes(pub u64);
#[derive(Clone, Debug)]
pub struct State {
pub pos: Position,
pub prev_pos: Option<Position>,
pub prev_move: Option<Move>,
pub param: Param,
}
#[derive(C... |
}
| {
InnerData { nodes: NumNodes(self.nodes.0 + 1) }
} | identifier_body |
types.rs | use game::{Position, Move, Score, NumPlies, NumMoves};
#[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Debug)]
pub struct NumNodes(pub u64);
#[derive(Clone, Debug)]
pub struct State {
pub pos: Position,
pub prev_pos: Option<Position>,
pub prev_move: Option<Move>,
pub param: Param,
}
#[derive(C... | (pub Move, pub Option<Move>);
#[derive(Clone, Debug)]
pub struct Report {
pub data: Data,
pub score: Score,
pub pv: Vec<Move>,
}
#[derive(Clone, Debug)]
pub struct Data {
pub nodes: NumNodes,
pub depth: NumPlies,
}
// TODO put actual data here
#[derive(Clone, Debug)]
pub struct InnerData {
pu... | BestMove | identifier_name |
types.rs | use game::{Position, Move, Score, NumPlies, NumMoves};
#[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Debug)]
pub struct NumNodes(pub u64);
#[derive(Clone, Debug)]
pub struct State {
pub pos: Position,
pub prev_pos: Option<Position>,
pub prev_move: Option<Move>,
pub param: Param,
}
#[derive(C... | pub hash_size: usize,
}
impl Param {
pub fn new(hash_size: usize) -> Self {
Param {
ponder: false,
search_moves: None,
depth: None,
nodes: None,
mate: None,
hash_size: hash_size,
}
}
}
#[derive(PartialEq, Eq, Copy, Clon... | pub mate: Option<NumMoves>, | random_line_split |
fields.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import six
from django.core.exceptions import ValidationError
from django.db import models
from django.forms import CheckboxSelectMultiple
from django.utils.text import capfirst
from dynamic_forms.forms import MultiSelectFormField
class TextMultiSelect... |
return
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_db_prep_value(value)
def get_internal_type(self):
return "TextField"
| if opt_select not in arr_choices:
raise ValidationError(
self.error_messages['invalid_choice'] % value) | conditional_block |
fields.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import six
from django.core.exceptions import ValidationError
from django.db import models
from django.forms import CheckboxSelectMultiple
from django.utils.text import capfirst
from dynamic_forms.forms import MultiSelectFormField
class TextMultiSelect... |
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_db_prep_value(value)
def get_internal_type(self):
return "TextField"
| """
:param callable convert: A callable to be applied for each choice
"""
arr_choices = self.get_choices_selected(self.get_choices_default())
for opt_select in value:
if opt_select not in arr_choices:
raise ValidationError(
self.error_messa... | identifier_body |
fields.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import six
from django.core.exceptions import ValidationError
from django.db import models
from django.forms import CheckboxSelectMultiple
from django.utils.text import capfirst
from dynamic_forms.forms import MultiSelectFormField
class | (six.with_metaclass(models.SubfieldBase,
models.TextField)):
# http://djangosnippets.org/snippets/2753/
widget = CheckboxSelectMultiple
def __init__(self, *args, **kwargs):
self.separate_values_by = kwargs.pop('separate_values_by', '\n')
super(... | TextMultiSelectField | identifier_name |
fields.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import six
from django.core.exceptions import ValidationError
from django.db import models
from django.forms import CheckboxSelectMultiple
from django.utils.text import capfirst
from dynamic_forms.forms import MultiSelectFormField
class TextMultiSelect... |
def to_python(self, value):
if value is not None:
return (value if isinstance(value, list) else
value.split(self.separate_values_by))
return []
def validate(self, value, model_instance):
"""
:param callable convert: A callable to be applied for each ... | return chces
def get_prep_value(self, value):
return value | random_line_split |
inferno-router.js | /*!
* inferno-router v0.7.14
* (c) 2016 Dominic Gannaway
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.InfernoRouter = f... | (string, object, value) {
/* eslint no-return-assign: 0 */
string.split(',').forEach(function (i) { return object[i] = value; });
}
var xlinkNS = 'http://www.w3.org/1999/xlink';
var xmlNS = 'http://www.w3.org/XML/1998/namespace';
var strictProps = {};
var booleanProps = {};
v... | constructDefaults | identifier_name |
inferno-router.js | /*!
* inferno-router v0.7.14
* (c) 2016 Dominic Gannaway
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.InfernoRouter = f... |
function pathRankSort(a, b) {
var aAttr = a.attrs || EMPTY$1,
bAttr = b.attrs || EMPTY$1;
var diff = rank(bAttr.path) - rank(aAttr.path);
return diff || (bAttr.path.length - aAttr.path.length);
}
function rank(url) {
return (strip(url).match(/\/+/g) || '').length;
}
var... | {
if ( opts === void 0 ) opts = EMPTY$1;
var reg = /(?:\?([^#]*))?(#.*)?$/,
c = url.match(reg),
matches = {},
ret;
if (c && c[1]) {
var p = c[1].split('&');
for (var i = 0; i < p.length; i++) {
var r = p[i].split('=');
matches[decodeURIComponent(r[0])] = decod... | identifier_body |
inferno-router.js | /*!
* inferno-router v0.7.14
* (c) 2016 Dominic Gannaway
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.InfernoRouter = f... |
if (this._blockSetState === false) {
queueStateChanges(this, newState, callback);
} else {
throw Error('Inferno Warning: Cannot update state via setState() in componentWillUpdate()');
}
};
Component.prototype.componentDidMount = function componentDidMount () {
};
Component.... | {
throw Error(noOp);
} | conditional_block |
inferno-router.js | /*!
* inferno-router v0.7.14
* (c) 2016 Dominic Gannaway
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.InfernoRouter = f... | scrollX = window.scrollX;
scrollY = window.scrollY;
screenWidth = window.screen.width;
screenHeight = window.screen.height;
lastScrollTime = performance.now();
};
}
function Lifecycle() {
this._listeners = [];
this.scrollX = null;
this.scrollY = null;
this... | random_line_split | |
progressevent.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::EventMethods;
use crate::dom::bindings::codegen::Bindi... | (&self) -> u64 {
self.loaded
}
// https://xhr.spec.whatwg.org/#dom-progressevent-total
fn Total(&self) -> u64 {
self.total
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| Loaded | identifier_name |
progressevent.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::EventMethods;
use crate::dom::bindings::codegen::Bindi... | type_: Atom,
can_bubble: EventBubbles,
cancelable: EventCancelable,
length_computable: bool,
loaded: u64,
total: u64,
) -> DomRoot<ProgressEvent> {
let ev = reflect_dom_object(
Box::new(ProgressEvent::new_inherited(
length_computabl... | }
}
pub fn new(
global: &GlobalScope, | random_line_split |
assembunny.rs | use std::io::prelude::*;
use std::fs::File;
struct Registers {
a: i32,
b: i32,
c: i32,
d: i32
}
impl Registers {
fn new() -> Registers {
Registers{a: 0, b: 0, c: 0, d: 0}
}
fn get(&self, name: &str) -> i32 |
fn inc(&mut self, name: &str) {
let curr_val = self.get(name);
self.set(name, curr_val + 1);
}
fn dec(&mut self, name: &str) {
let curr_val = self.get(name);
self.set(name, curr_val - 1);
}
fn set(&mut self, name: &str, val: i32) {
match name {
... | {
match name {
"a" => self.a,
"b" => self.b,
"c" => self.c,
"d" => self.d,
_ => panic!("invalid register {}!", name),
}
} | identifier_body |
assembunny.rs | use std::io::prelude::*;
use std::fs::File;
struct Registers {
a: i32,
b: i32,
c: i32,
d: i32
}
impl Registers {
fn new() -> Registers {
Registers{a: 0, b: 0, c: 0, d: 0}
}
fn get(&self, name: &str) -> i32 {
match name {
"a" => self.a,
"b" => self.b... | (&mut self, name: &str) {
let curr_val = self.get(name);
self.set(name, curr_val + 1);
}
fn dec(&mut self, name: &str) {
let curr_val = self.get(name);
self.set(name, curr_val - 1);
}
fn set(&mut self, name: &str, val: i32) {
match name {
"a" => self... | inc | identifier_name |
assembunny.rs | use std::io::prelude::*;
use std::fs::File;
struct Registers {
a: i32,
b: i32,
c: i32,
d: i32
}
impl Registers {
fn new() -> Registers {
Registers{a: 0, b: 0, c: 0, d: 0}
}
fn get(&self, name: &str) -> i32 {
match name {
"a" => self.a,
"b" => self.b... | let mut data = String::new();
f.read_to_string(&mut data).expect("unable to read file");
let mut instructions: Vec<&str> = data.split("\n").collect();
instructions.pop();
let mut regs = Registers::new();
let mut current_ins: i32 = 0;
loop {
if current_ins < 0 || current_ins as usiz... | }
}
fn main() {
let mut f = File::open("data.txt").expect("unable to open file"); | random_line_split |
parse.js | const initStart = process.hrtime();
const DeviceDetector = require('device-detector-js');
const detector = new DeviceDetector({ skipBotDetection: true, cache: false });
// Trigger a parse to force cache loading
detector.parse('Test String');
const initTime = process.hrtime(initStart)[1] / 1000000000;
const package = r... |
const output = {
results: [],
parse_time: 0,
init_time: initTime,
memory_used: 0,
version: version
};
lineReader.on('line', function(line) {
if (line === '') {
return;
}
const start = process.hrtime();
let error = null,
result = {},
r;
try {
r =... | input: require('fs').createReadStream(process.argv[2])
}); | random_line_split |
parse.js | const initStart = process.hrtime();
const DeviceDetector = require('device-detector-js');
const detector = new DeviceDetector({ skipBotDetection: true, cache: false });
// Trigger a parse to force cache loading
detector.parse('Test String');
const initTime = process.hrtime(initStart)[1] / 1000000000;
const package = r... | else {
result.error = error;
result.time = end;
}
output.results.push(result);
});
lineReader.on('close', function() {
output.memory_used = process.memoryUsage().heapUsed;
console.log(JSON.stringify(output));
});
| {
result = {
useragent: line,
parsed: {
browser: {
name: r.client && r.client.name ? r.client.name : null,
version:
r.client && r.client.version ? r.client.version : null
},
pl... | conditional_block |
urls.py | #
# File that determines what each URL points to. This uses _Python_ regular
# expressions, not Perl's.
#
# See:
# http://diveintopython.org/regular_expressions/street_addresses.html#re.matching.2.3
#
from django.conf import settings
from django.conf.urls.defaults import *
from django.contrib import admin
from django.... |
# PM Extension
if (forum_settings.PM_SUPPORT):
urlpatterns += patterns('',
(r'^mail/', include('mail_urls')),
)
if (settings.DEBUG):
urlpatterns += patterns('',
(r'^%s(?P<path>.*)$' % settings.MEDIA_URL.lstrip('/'),
'django.views.static.serve', {'document_root': settings.MEDIA_... | urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
(r'^wiki/([^/]+/)*wiki/(?P<path>.*)$', 'django.views.static.serve', {'docu... | conditional_block |
urls.py | #
# File that determines what each URL points to. This uses _Python_ regular
# expressions, not Perl's.
#
# See:
# http://diveintopython.org/regular_expressions/street_addresses.html#re.matching.2.3
#
from django.conf import settings
from django.conf.urls.defaults import *
from django.contrib import admin
from django.... |
# Registration stuff
url(r'^roster/', include('roster.urls', namespace='roster')),
# Character related stuff.
url(r'^character/', include('character.urls', namespace='character')),
# Mail stuff
url(r'^mail/', include('mail.urls', namespace='mail')),
# Search utilities
url(r'^search/'... | (r'^favicon\.ico$', RedirectView.as_view(url='/media/images/favicon.ico')), | random_line_split |
imutils_test.py | import unittest
import numpy as np
from ..imutils import nan_to_zero, quantile_threshold, interpolate
class ImutilsTest(unittest.TestCase):
def test_nan_to_zero_with_ge_zero(self):
|
def test_nan_to_zero_with_negatives(self):
negs = (
np.array([-1]),
np.array([np.nan]),
- np.arange(1, 1024 * 1024 + 1).reshape((1024, 1024)),
np.linspace(0, -20, 201)
)
for neg in negs:
sh = neg.shape
expected_notnull... | ids = (
np.zeros(1),
np.ones(range(1, 10)),
np.arange(1024 * 1024)
)
for id_ in ids:
before = id_.copy()
notnull = nan_to_zero(id_)
np.testing.assert_array_equal(before, id_)
np.testing.assert_array_equal(notnull, before... | identifier_body |
imutils_test.py | import unittest
import numpy as np
from ..imutils import nan_to_zero, quantile_threshold, interpolate
class ImutilsTest(unittest.TestCase):
def test_nan_to_zero_with_ge_zero(self):
ids = (
np.zeros(1),
np.ones(range(1, 10)),
np.arange(1024 * 1024)
)
fo... | (self):
negs = (
np.array([-1]),
np.array([np.nan]),
- np.arange(1, 1024 * 1024 + 1).reshape((1024, 1024)),
np.linspace(0, -20, 201)
)
for neg in negs:
sh = neg.shape
expected_notnull = np.zeros(sh).astype(np.bool_)
... | test_nan_to_zero_with_negatives | identifier_name |
imutils_test.py | import unittest
import numpy as np
from ..imutils import nan_to_zero, quantile_threshold, interpolate
class ImutilsTest(unittest.TestCase):
def test_nan_to_zero_with_ge_zero(self):
ids = (
np.zeros(1),
np.ones(range(1, 10)),
np.arange(1024 * 1024)
)
fo... |
def test_interpolate(self):
im_in = np.arange(900, dtype=np.float32).reshape((30, 30))
im_in[2, 3] = np.nan
notnull = im_in > 0
im_out = interpolate(im_in, notnull)
np.testing.assert_array_almost_equal(im_in[notnull], im_out[notnull])
self.assertAlmostEqual(im_out... | kwargs = {kw: val for kw, val in zip(kws, args)}
im_in = args[0]
im_expected, q_expected = expected
q_actual = quantile_threshold(**kwargs)
self.assertAlmostEqual(q_expected, q_actual, delta=1e-7)
np.testing.assert_array_almost_equal(im_in, im_expected, decima... | conditional_block |
imutils_test.py | import unittest
import numpy as np
from ..imutils import nan_to_zero, quantile_threshold, interpolate
class ImutilsTest(unittest.TestCase):
def test_nan_to_zero_with_ge_zero(self):
ids = (
np.zeros(1),
np.ones(range(1, 10)),
np.arange(1024 * 1024)
)
fo... | np.testing.assert_array_equal(input_, expected)
def test_nan_to_zero_with_empty(self):
in_ = None
self.assertRaises(AttributeError, nan_to_zero, in_)
self.assertIs(in_, None)
in_ = []
self.assertRaises(TypeError, nan_to_zero, in_)
self.assertEqual(in_, [... | )
for input_, expected in test_cases:
nan_to_zero(input_) | random_line_split |
serde.rs | // Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0.
use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};
use serde::ser::{Error as SerError, Serialize, SerializeMap, SerializeTuple, Serializer};
use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;
use std::str... |
}
struct JsonVisitor;
impl<'de> Visitor<'de> for JsonVisitor {
type Value = Json;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "a json value")
}
fn visit_unit<E>(self) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Json... | {
match serde_json::from_str(s) {
Ok(value) => Ok(value),
Err(e) => Err(invalid_type!("Illegal Json text: {:?}", e)),
}
} | identifier_body |
serde.rs | // Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0.
use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};
use serde::ser::{Error as SerError, Serialize, SerializeMap, SerializeTuple, Serializer};
use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;
use std::str... | }
}
}
impl ToString for Json {
fn to_string(&self) -> String {
serde_json::to_string(&self.as_ref()).unwrap()
}
}
impl FromStr for Json {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match serde_json::from_str(s) {
Ok(value) => Ok(value),
... | }
tup.end()
} | random_line_split |
serde.rs | // Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0.
use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};
use serde::ser::{Error as SerError, Serialize, SerializeMap, SerializeTuple, Serializer};
use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;
use std::str... | <E>(self, v: u64) -> Result<Self::Value, E>
where
E: de::Error,
{
if v > (std::i64::MAX as u64) {
Ok(Json::from_f64(v as f64).map_err(de::Error::custom)?)
} else {
Ok(Json::from_i64(v as i64).map_err(de::Error::custom)?)
}
}
fn visit_f64<E>(self, ... | visit_u64 | identifier_name |
AtbashSpec.ts | import { Atbash } from "../../../main/decryptor/converters/Atbash";
import { Converter } from "../../../main/decryptor/converters/Converter";
describe("Atbash", () => {
describe("convert", () => {
it("converts empty string to empty string", () => {
expect(new Atbash().convert("")).toBe("");
... | });
describe("toJSON", () => {
it("serializes the converter", () => {
expect(new Atbash().toJSON()).toEqual({
"type": "atbash"
});
});
});
describe("fromJSON", () => {
it("deserializes a converter", () => {
const converter = C... | expect(new Atbash().convert("#12FooBar!")).toBe("#12UllYzi!");
}); | random_line_split |
course-delete.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
import { ICourse } from '../icourse';
import { CourseService } from '../course.service';
@Component({
selector: 'app-course-delete',
templateUr... | () {
this.sub = this._route.params.subscribe(
params => {
let id = +params['id'];
this.getCourse(id);
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
getCourse(id: number) {
this._courseService.getCourse(id).subscribe(
course => this.course = course,
error =... | ngOnInit | identifier_name |
course-delete.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
import { ICourse } from '../icourse';
import { CourseService } from '../course.service';
@Component({
selector: 'app-course-delete',
templateUr... | error => this.errorMessage = <any>error);
}
} | random_line_split | |
server.py | import SocketServer
class | (SocketServer.BaseRequestHandler):
def handle(self):
msg = self.request.recv(1024)
a = msg.split(" ",2)
if len(a) >1 and a[0] == "GET":
a = a[1].split("/")
a =[i for i in a if i != '']
if len(a) == 0:
self.request.sendall(self.server.... | ProtoHandler | identifier_name |
server.py | import SocketServer
class ProtoHandler(SocketServer.BaseRequestHandler):
def handle(self):
msg = self.request.recv(1024)
a = msg.split(" ",2)
if len(a) >1 and a[0] == "GET":
a = a[1].split("/")
a =[i for i in a if i != '']
if len(a) == 0:
... |
if __name__ == "__main__":
s = ProtoServer(("192.168.1.253", 6661),"index.html")
s.serve_forever()
| def __init__(self,hostport,default):
self.allow_reuse_address = True
SocketServer.TCPServer.__init__(self,hostport, ProtoHandler)
with open (default, "r") as myfile:
self.ret=myfile.read() | identifier_body |
server.py | import SocketServer
class ProtoHandler(SocketServer.BaseRequestHandler):
def handle(self):
msg = self.request.recv(1024)
a = msg.split(" ",2)
if len(a) >1 and a[0] == "GET":
a = a[1].split("/")
a =[i for i in a if i != '']
if len(a) == 0:
... |
else:
self.server.data=a
print a
class ProtoServer(SocketServer.TCPServer):
def __init__(self,hostport,default):
self.allow_reuse_address = True
SocketServer.TCPServer.__init__(self,hostport, ProtoHandler)
with open (default,... | self.request.sendall(self.server.ret) | conditional_block |
server.py | import SocketServer
class ProtoHandler(SocketServer.BaseRequestHandler):
def handle(self):
msg = self.request.recv(1024)
a = msg.split(" ",2)
if len(a) >1 and a[0] == "GET":
a = a[1].split("/")
a =[i for i in a if i != '']
if len(a) == 0:
... |
if __name__ == "__main__":
s = ProtoServer(("192.168.1.253", 6661),"index.html")
s.serve_forever() | random_line_split | |
particle_system.py | import math
import random
import struct
import GLWindow
import ModernGL
# Window & Context
wnd = GLWindow.create_window()
ctx = ModernGL.create_context()
tvert = ctx.vertex_shader('''
#version 330
uniform vec2 acc;
in vec2 in_pos;
in vec2 in_prev;
out vec2 out_pos;
out vec2 out_prev;
... |
render_vao.render(ModernGL.POINTS, 1024)
vao1.transform(vbo2, ModernGL.POINTS, 1024)
ctx.copy_buffer(vbo1, vbo2)
| vbo1.write(particle(), offset=idx * struct.calcsize('2f2f'))
idx = (idx + 1) % 1024 | conditional_block |
particle_system.py | import math
import random
import struct
import GLWindow
import ModernGL
# Window & Context
wnd = GLWindow.create_window()
ctx = ModernGL.create_context()
tvert = ctx.vertex_shader('''
#version 330
uniform vec2 acc;
in vec2 in_pos;
in vec2 in_prev;
out vec2 out_pos;
out vec2 out_prev;
... |
vbo1 = ctx.buffer(b''.join(particle() for i in range(1024)))
vbo2 = ctx.buffer(reserve=vbo1.size)
vao1 = ctx.simple_vertex_array(transform, vbo1, ['in_pos', 'in_prev'])
vao2 = ctx.simple_vertex_array(transform, vbo2, ['in_pos', 'in_prev'])
render_vao = ctx.vertex_array(prog, [
(vbo1, '2f8x', ['vert']),
])
tra... | a = random.uniform(0.0, math.pi * 2.0)
r = random.uniform(0.0, 0.001)
return struct.pack('2f2f', 0.0, 0.0, math.cos(a) * r - 0.003, math.sin(a) * r - 0.008) | identifier_body |
particle_system.py | import math
import random
import struct
import GLWindow
import ModernGL
# Window & Context
wnd = GLWindow.create_window()
ctx = ModernGL.create_context()
tvert = ctx.vertex_shader('''
#version 330
uniform vec2 acc;
in vec2 in_pos;
in vec2 in_prev;
out vec2 out_pos;
out vec2 out_prev;
... | ():
a = random.uniform(0.0, math.pi * 2.0)
r = random.uniform(0.0, 0.001)
return struct.pack('2f2f', 0.0, 0.0, math.cos(a) * r - 0.003, math.sin(a) * r - 0.008)
vbo1 = ctx.buffer(b''.join(particle() for i in range(1024)))
vbo2 = ctx.buffer(reserve=vbo1.size)
vao1 = ctx.simple_vertex_array(transform, vbo... | particle | identifier_name |
particle_system.py | import math
import random
import struct
import GLWindow
import ModernGL
# Window & Context
wnd = GLWindow.create_window()
ctx = ModernGL.create_context()
tvert = ctx.vertex_shader('''
#version 330
uniform vec2 acc;
in vec2 in_pos;
in vec2 in_prev;
out vec2 out_pos;
out vec2 out_prev;
... | vert = ctx.vertex_shader('''
#version 330
in vec2 vert;
void main() {
gl_Position = vec4(vert, 0.0, 1.0);
}
''')
frag = ctx.fragment_shader('''
#version 330
out vec4 color;
void main() {
color = vec4(0.30, 0.50, 1.00, 1.0);
}
''')
prog = ctx.program(vert, frag])
tr... | out_pos = in_pos * 2.0 - in_prev + acc;
out_prev = in_pos;
}
''')
| random_line_split |
processOps.ts |
const BASE_PATH = 'editor.composition.i'
const TOOLBOX_PATH = 'editor.$toolbox'
declare var global: any
export function processOps
( { state, props } ) | {
const { ops } = props
if ( ! ops ) {
return
}
let newselection
ops.forEach
( op => {
const path = op.path && `${BASE_PATH}.${op.path.join('.i.')}`
switch ( op.op ) {
case 'update':
state.set ( path, op.value )
break
case 'delete':
state.unset ... | identifier_body | |
processOps.ts |
const BASE_PATH = 'editor.composition.i'
const TOOLBOX_PATH = 'editor.$toolbox'
declare var global: any
export function |
( { state, props } ) {
const { ops } = props
if ( ! ops ) {
return
}
let newselection
ops.forEach
( op => {
const path = op.path && `${BASE_PATH}.${op.path.join('.i.')}`
switch ( op.op ) {
case 'update':
state.set ( path, op.value )
break
case 'delete':
... | processOps | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.