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,
lastPos = 0,
backTicked = false,
lastBackTick = 0;
ch = str.charCodeAt(pos);
while (pos < max) {
if (ch === 0x60/* ` */ && (escapes % 2 === 0)) {
backTicked = !backTicked;
lastBackTick = pos;
} else if (ch === 0x7c/* | */ && (escapes % 2 === 0) && !backTicked) {
result.push(str.substring(lastPos, pos));
lastPos = pos + 1;
} else if (ch === 0x5c/* \ */) {
escapes++;
} else {
escapes = 0;
}
pos++;
// If there was an un-closed backtick, go back to just after
// the last backtick, but as if it was a normal character
if (pos === max && backTicked) {
backTicked = false;
pos = lastBackTick + 1;
}
ch = str.charCodeAt(pos);
}
result.push(str.substring(lastPos));
return result;
}
module.exports = function table(state, startLine, endLine, silent) {
var ch, lineText, pos, i, nextLine, rows, token,
aligns, t, tableLines, tbodyLines;
// should have at least three lines
if (startLine + 2 > endLine) { return false; }
nextLine = startLine + 1;
if (state.tShift[nextLine] < state.blkIndent) { return false; }
// first character of the second line should be '|' or '-'
pos = state.bMarks[nextLine] + state.tShift[nextLine];
if (pos >= state.eMarks[nextLine]) { return false; }
ch = state.src.charCodeAt(pos);
if (ch !== 0x7C/* | */ && ch !== 0x2D/* - */ && ch !== 0x3A/* : */) |
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 not in between columns;
// e.g. allow ` |---| `, disallow ` ---||--- `
if (i === 0 || i === rows.length - 1) {
continue;
} else {
return false;
}
}
if (!/^:?-+:?$/.test(t)) { return false; }
if (t.charCodeAt(t.length - 1) === 0x3A/* : */) {
aligns.push(t.charCodeAt(0) === 0x3A/* : */ ? 'center' : 'right');
} else if (t.charCodeAt(0) === 0x3A/* : */) {
aligns.push('left');
} else {
aligns.push('');
}
}
lineText = getLine(state, startLine).trim();
if (lineText.indexOf('|') === -1) { return false; }
rows = escapedSplit(lineText.replace(/^\||\|$/g, ''));
if (aligns.length !== rows.length) { return false; }
if (silent) { return true; }
token = state.push('table_open', 'table', 1);
token.map = tableLines = [ startLine, 0 ];
token = state.push('thead_open', 'thead', 1);
token.map = [ startLine, startLine + 1 ];
token = state.push('tr_open', 'tr', 1);
token.map = [ startLine, startLine + 1 ];
for (i = 0; i < rows.length; i++) {
token = state.push('th_open', 'th', 1);
token.map = [ startLine, startLine + 1 ];
if (aligns[i]) {
token.attrs = [ [ 'style', 'text-align:' + aligns[i] ] ];
}
token = state.push('inline', '', 0);
token.content = rows[i].trim();
token.map = [ startLine, startLine + 1 ];
token.children = [];
token = state.push('th_close', 'th', -1);
}
token = state.push('tr_close', 'tr', -1);
token = state.push('thead_close', 'thead', -1);
token = state.push('tbody_open', 'tbody', 1);
token.map = tbodyLines = [ startLine + 2, 0 ];
for (nextLine = startLine + 2; nextLine < endLine; nextLine++) {
if (state.tShift[nextLine] < state.blkIndent) { break; }
lineText = getLine(state, nextLine).trim();
if (lineText.indexOf('|') === -1) { break; }
rows = escapedSplit(lineText.replace(/^\||\|$/g, ''));
// set number of columns to number of columns in header row
rows.length = aligns.length;
token = state.push('tr_open', 'tr', 1);
for (i = 0; i < rows.length; i++) {
token = state.push('td_open', 'td', 1);
if (aligns[i]) {
token.attrs = [ [ 'style', 'text-align:' + aligns[i] ] ];
}
token = state.push('inline', '', 0);
token.content = rows[i] ? rows[i].trim() : '';
token.children = [];
token = state.push('td_close', 'td', -1);
}
token = state.push('tr_close', 'tr', -1);
}
token = state.push('tbody_close', 'tbody', -1);
token = state.push('table_close', 'table', -1);
tableLines[1] = tbodyLines[1] = nextLine;
state.line = nextLine;
return true;
};
| { 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 = pos;
} else if (ch === 0x7c/* | */ && (escapes % 2 === 0) && !backTicked) {
result.push(str.substring(lastPos, pos));
lastPos = pos + 1;
} else if (ch === 0x5c/* \ */) {
escapes++;
} else {
escapes = 0;
}
pos++;
// If there was an un-closed backtick, go back to just after
// the last backtick, but as if it was a normal character
if (pos === max && backTicked) {
backTicked = false;
pos = lastBackTick + 1;
}
ch = str.charCodeAt(pos);
}
result.push(str.substring(lastPos));
return result;
}
module.exports = function table(state, startLine, endLine, silent) {
var ch, lineText, pos, i, nextLine, rows, token,
aligns, t, tableLines, tbodyLines;
// should have at least three lines
if (startLine + 2 > endLine) { return false; }
nextLine = startLine + 1;
if (state.tShift[nextLine] < state.blkIndent) { return false; }
// first character of the second line should be '|' or '-'
pos = state.bMarks[nextLine] + state.tShift[nextLine];
if (pos >= state.eMarks[nextLine]) { return false; }
ch = state.src.charCodeAt(pos);
if (ch !== 0x7C/* | */ && ch !== 0x2D/* - */ && ch !== 0x3A/* : */) { return false; }
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 not in between columns;
// e.g. allow ` |---| `, disallow ` ---||--- `
if (i === 0 || i === rows.length - 1) {
continue;
} else {
return false;
}
}
if (!/^:?-+:?$/.test(t)) { return false; }
if (t.charCodeAt(t.length - 1) === 0x3A/* : */) {
aligns.push(t.charCodeAt(0) === 0x3A/* : */ ? 'center' : 'right');
} else if (t.charCodeAt(0) === 0x3A/* : */) {
aligns.push('left');
} else {
aligns.push('');
}
}
lineText = getLine(state, startLine).trim();
if (lineText.indexOf('|') === -1) { return false; }
rows = escapedSplit(lineText.replace(/^\||\|$/g, ''));
if (aligns.length !== rows.length) { return false; }
if (silent) { return true; }
token = state.push('table_open', 'table', 1);
token.map = tableLines = [ startLine, 0 ];
token = state.push('thead_open', 'thead', 1);
token.map = [ startLine, startLine + 1 ];
token = state.push('tr_open', 'tr', 1);
token.map = [ startLine, startLine + 1 ];
for (i = 0; i < rows.length; i++) {
token = state.push('th_open', 'th', 1);
token.map = [ startLine, startLine + 1 ];
if (aligns[i]) {
token.attrs = [ [ 'style', 'text-align:' + aligns[i] ] ];
}
token = state.push('inline', '', 0);
token.content = rows[i].trim();
token.map = [ startLine, startLine + 1 ];
token.children = [];
token = state.push('th_close', 'th', -1);
}
token = state.push('tr_close', 'tr', -1);
token = state.push('thead_close', 'thead', -1);
token = state.push('tbody_open', 'tbody', 1);
token.map = tbodyLines = [ startLine + 2, 0 ];
for (nextLine = startLine + 2; nextLine < endLine; nextLine++) {
if (state.tShift[nextLine] < state.blkIndent) { break; }
lineText = getLine(state, nextLine).trim();
if (lineText.indexOf('|') === -1) { break; }
rows = escapedSplit(lineText.replace(/^\||\|$/g, ''));
// set number of columns to number of columns in header row
rows.length = aligns.length;
token = state.push('tr_open', 'tr', 1);
for (i = 0; i < rows.length; i++) {
token = state.push('td_open', 'td', 1);
if (aligns[i]) {
token.attrs = [ [ 'style', 'text-align:' + aligns[i] ] ];
}
token = state.push('inline', '', 0);
token.content = rows[i] ? rows[i].trim() : '';
token.children = [];
token = state.push('td_close', 'td', -1);
}
token = state.push('tr_close', 'tr', -1);
}
token = state.push('tbody_close', 'tbody', -1);
token = state.push('table_close', 'table', -1);
tableLines[1] = tbodyLines[1] = nextLine;
state.line = nextLine;
return true;
};
| 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()
vals = []
if len(keys) != 0:
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>"
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\">"
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.environ["REMOTE_ADDR"], time.strftime(time.asctime()), fields['msgbox'].value)
ret += read_msg()
ret += "</div>"
ret += "</body>"
ret += "</html>"
print ret
reply()
| 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+'--'+tm, msg)
conn.disconnect()
def read_msg():
|
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"] + "!</h2>"
ret += "<span>" + os.environ["HTTP_USER_AGENT"] + "</span><br><br>"
if fields.has_key('msgbox'):
insert_msg(os.environ["REMOTE_ADDR"], time.strftime(time.asctime()), fields['msgbox'].value)
ret += read_msg()
ret += "</div>"
ret += "</body>"
ret += "</html>"
print ret
reply()
| 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, v in zip(keys, vals):
ret += "<span>" + k.replace(msg_prefix, '').replace('--', ' ') + "</span>"
ret += "<pre readonly=\"true\">" + v + "</pre>"
conn.disconnect()
ret += "<br>"
return ret | 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+'--'+tm, msg)
conn.disconnect()
def read_msg():
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, v in zip(keys, vals):
ret += "<span>" + k.replace(msg_prefix, '').replace('--', ' ') + "</span>"
ret += "<pre readonly=\"true\">" + v + "</pre>"
conn.disconnect()
ret += "<br>"
return ret
def reply():
import time, os
ret = ""
ret += "Content-Type: text/html\n\n"
ret += "<!DOCTYPE html>" |
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.environ["REMOTE_ADDR"], time.strftime(time.asctime()), fields['msgbox'].value)
ret += read_msg()
ret += "</div>"
ret += "</body>"
ret += "</html>"
print ret
reply() | 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+'--'+tm, msg)
conn.disconnect()
def read_msg():
ret = ''
conn = Connection(host=gethostname(),port=6379)
conn.send_command('keys', msg_prefix+'*')
keys = conn.read_response()
vals = []
if len(keys) != 0:
|
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\">"
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.environ["REMOTE_ADDR"], time.strftime(time.asctime()), fields['msgbox'].value)
ret += read_msg()
ret += "</div>"
ret += "</body>"
ret += "</html>"
print ret
reply()
| 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 MergeWithThunkField<T> = (baseThunk: (...rest: any[]) => any) => T;
export interface FieldPresenceAdt {
fold: <T>(
strict: StrictField<T>,
defaultedThunk: DefaultedThunkField<T>,
asOption: AsOptionField<T>,
asDefaultedOptionThunk: AsDefaultedOptionThunkField<T>,
mergeWithThunk: MergeWithThunkField<T>
) => T;
match: <T>(branches: {
strict: StrictField<T>;
defaultedThunk: DefaultedThunkField<T>;
asOption: AsOptionField<T>;
asDefaultedOptionThunk: AsDefaultedOptionThunkField<T>;
mergeWithThunk: MergeWithThunkField<T>;
}) => T;
log: (label: string) => void;
}
const adt: {
strict: StrictField<FieldPresenceAdt>; | mergeWithThunk: MergeWithThunkField<FieldPresenceAdt>;
} = Adt.generate([
{ strict: [ ] },
{ defaultedThunk: [ 'fallbackThunk' ] },
{ asOption: [ ] },
{ asDefaultedOptionThunk: [ 'fallbackThunk' ] },
{ mergeWithThunk: [ 'baseThunk' ] }
]);
const defaulted = <T>(fallback: T): FieldPresenceAdt => {
return adt.defaultedThunk(
Fun.constant(fallback)
);
};
const asDefaultedOption = <T>(fallback: T): FieldPresenceAdt => {
return adt.asDefaultedOptionThunk(
Fun.constant(fallback)
);
};
const mergeWith = (base: {}): FieldPresenceAdt => {
return adt.mergeWithThunk(
Fun.constant(base)
);
};
const strict = adt.strict;
const asOption = adt.asOption;
const defaultedThunk = adt.defaultedThunk;
const asDefaultedOptionThunk = adt.asDefaultedOptionThunk;
const mergeWithThunk = adt.mergeWithThunk;
export {
strict,
asOption,
defaulted,
defaultedThunk,
asDefaultedOption,
asDefaultedOptionThunk,
mergeWith,
mergeWithThunk
}; | 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]; // 哨兵
for i in 1..nums.len() {
if nums[i] < sentinel {
// 小于哨兵的放到哨兵左侧
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] = temp;
let right_len = nums.len() - pos + 1; // 右边的大小,包含哨兵(即哨兵是第几大)
println!(
"nums = {:?}, k = {}, pos = {}, right_len={}",
nums, k, pos, right_len
);
match right_len.cmp(&k) {
// 正好等于 k,说明哨兵就是第 k 大的数。
Ordering::Equal => sentinel,
// [哨兵, len()] 长度大于 k,说明第 k 大的数在右边
Ordering::Greater => {
let (_, right) = nums.split_at_mut(pos);
Self::find(right, k)
}
// 说明右边的数都是比较大的,但第 k 大的数在左边呢。
Ordering::Less => {
// left 不包含哨兵了
let (left, _) = nums.split_at_mut(pos - 1);
Self::find(left, k - right_len)
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_find_kth_largest_example1() {
assert_eq!(Solution::find_kth_largest(vec![3, 2, 1, 5, 6, 4], 2), 5);
}
#[test]
fn test_find_kth_largest_example2() {
assert_eq!(
Solution::find_kth_largest(vec![3, 2, 3, 1, 2, 4, 5, 5, 6], 4),
4
);
}
#[test]
fn test_find_kth_largest_example3() {
assert_eq!(Solution::find_kth_largest(vec![5, 2, 4, 1, 3, 6, 0], 4), 3);
}
}
| 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] = temp;
let right_len = nums.len() - pos + 1; // 右边的大小,包含哨兵(即哨兵是第几大)
println!(
"nums = {:?}, k = {}, pos = {}, right_len={}",
nums, k, pos, right_len
);
match right_len.cmp(&k) {
// 正好等于 k,说明哨兵就是第 k 大的数。
Ordering::Equal => sentinel,
// [哨兵, len()] 长度大于 k,说明第 k 大的数在右边
Ordering::Greater => {
let (_, right) = nums.split_at_mut(pos);
Self::find(right, k)
}
// 说明右边的数都是比较大的,但第 k 大的数在左边呢。
Ordering::Less => {
// left 不包含哨兵了
let (left, _) = nums.split_at_mut(pos - 1);
Self::find(left, k - right_len)
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_find_kth_largest_example1() {
assert_eq!(Solution::find_kth_largest(vec![3, 2, 1, 5, 6, 4], 2), 5);
}
#[test]
fn test_find_kth_largest_example2() {
assert_eq!(
Solution::find_kth_largest(vec![3, 2, 3, 1, 2, 4, 5, 5, 6], 4),
4
);
}
#[test]
fn test_find_kth_largest_example3() {
assert_eq!(Solution::find_kth_largest(vec![5, 2, 4, 1, 3, 6, 0], 4), 3);
}
} | 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',['../IRremoteESP8266_8h.html#ad5b287a488a8c1b7b8661f029ab56fadaacda5821835865551f6df46c76282fa4',1,'IRremoteESP8266.h']]],
['haierprotocol_446',['HaierProtocol',['../unionHaierProtocol.html',1,'']]],
['haieryrw02protocol_447',['HaierYRW02Protocol',['../unionHaierYRW02Protocol.html',1,'']]],
['haieryrwo2_448',['haierYrwo2',['../classIRac.html#a7bc779a162dd9a1b4c925febec443353',1,'IRac']]],
['handlespecialstate_449',['handleSpecialState',['../classIRCoolixAC.html#af78090c6d8b45b4202a80f1223640390',1,'IRCoolixAC::handleSpecialState()'],['../classIRTranscoldAc.html#a01a3e3f8f92b8fb3b6d023e595f3ce17',1,'IRTranscoldAc::handleSpecialState()']]],
['handletoggles_450',['handleToggles',['../classIRac.html#a36833999dce4ad608a5a0f084988cfd1',1,'IRac']]], | ['header1_455',['Header1',['../structCoronaSection.html#a3d6d6c1e31f82a76cd88f81bcdb83a3a',1,'CoronaSection']]],
['health_456',['Health',['../unionHaierProtocol.html#a4cf70c633e33066e3fc0f98bb2ad3820',1,'HaierProtocol::Health()'],['../unionHaierYRW02Protocol.html#a7fa39803fd72a788736bb8f00acfa76f',1,'HaierYRW02Protocol::Health()']]],
['heat_5fmode_457',['heat_mode',['../classIRArgoAC.html#a255762f71502b9ffeb0686759991ec53',1,'IRArgoAC']]],
['hitachi_458',['hitachi',['../classIRac.html#acd0f2fcf03aabf947a19a195000add3c',1,'IRac']]],
['hitachi1_459',['hitachi1',['../classIRac.html#ac8807d62f6ae87af72d44b50bed3f17b',1,'IRac']]],
['hitachi344_460',['hitachi344',['../classIRac.html#a0bc34635a1a349816344916a82585460',1,'IRac']]],
['hitachi424_461',['hitachi424',['../classIRac.html#aec6de0752ddd3a3e7c6824cb1b692508',1,'IRac']]],
['hitachi_5fac_462',['HITACHI_AC',['../IRremoteESP8266_8h.html#ad5b287a488a8c1b7b8661f029ab56fada9020fb54ac69d8aec0185f7e80c962ca',1,'IRremoteESP8266.h']]],
['hitachi_5fac1_463',['HITACHI_AC1',['../IRremoteESP8266_8h.html#ad5b287a488a8c1b7b8661f029ab56fada7d9a74161d95e62bece3c0e48900cb35',1,'IRremoteESP8266.h']]],
['hitachi_5fac1_5fremote_5fmodel_5ft_464',['hitachi_ac1_remote_model_t',['../IRsend_8h.html#acd0c6107b5a6cab2080b18a8de14ea49',1,'IRsend.h']]],
['hitachi_5fac2_465',['HITACHI_AC2',['../IRremoteESP8266_8h.html#ad5b287a488a8c1b7b8661f029ab56fadab5a44068d519506efa8a3113aa44c9c0',1,'IRremoteESP8266.h']]],
['hitachi_5fac3_466',['HITACHI_AC3',['../IRremoteESP8266_8h.html#ad5b287a488a8c1b7b8661f029ab56fadac3487c47b14da6af922f5b27992b30f3',1,'IRremoteESP8266.h']]],
['hitachi_5fac344_467',['HITACHI_AC344',['../IRremoteESP8266_8h.html#ad5b287a488a8c1b7b8661f029ab56fada1e147eb39adc40e4181940cc2357f070',1,'IRremoteESP8266.h']]],
['hitachi_5fac424_468',['HITACHI_AC424',['../IRremoteESP8266_8h.html#ad5b287a488a8c1b7b8661f029ab56fada85af068f8964d4359512265d8cc27a31',1,'IRremoteESP8266.h']]],
['htmlescape_469',['htmlEscape',['../namespaceirutils.html#a6e55c6fdcc82e1ef8bd5f73df83609a7',1,'irutils']]]
]; | ['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',['hasInvertedStates',['../classIRHitachiAc3.html#ac06b36245c85480d97c1a9f49cfaa005',1,'IRHitachiAc3']]],
['hasstatechanged_453',['hasStateChanged',['../classIRac.html#a35258c35a2d2b19886292b22b2aa053a',1,'IRac']]],
['header0_454',['Header0',['../structCoronaSection.html#a3b3c0a1a42da65bb4b481e59b42f26a6',1,'CoronaSection']]], | 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')
# _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')
# if angle%10 == 9:
# f.write(_str_out + '\n')
# _str_out = '\t'
f.write('};' + '\n')
def main():
## Creates the header
|
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 + '.c', 'w')
dumpCosine(_cosine_func = math.cos, display_name = 'tcos', f = f)
f.write('\n')
dumpCosine(_cosine_func = math.sin, display_name = 'tsin', f = f)
f.close() | 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')
# if angle%10 == 9:
# f.write(_str_out + '\n')
# _str_out = '\t'
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.close()
## Creates the C file
f = codecs.open(filename_out + '.c', 'w')
dumpCosine(_cosine_func = math.cos, display_name = 'tcos', f = f)
f.write('\n')
dumpCosine(_cosine_func = math.sin, display_name = 'tsin', f = f)
f.close()
main() | 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')
# _str_out = '\t'
for angle in range(0,table_size):
|
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.close()
## Creates the C file
f = codecs.open(filename_out + '.c', 'w')
dumpCosine(_cosine_func = math.cos, display_name = 'tcos', f = f)
f.write('\n')
dumpCosine(_cosine_func = math.sin, display_name = 'tsin', f = f)
f.close()
main() | _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 = 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'
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.close()
## Creates the C file
f = codecs.open(filename_out + '.c', 'w')
dumpCosine(_cosine_func = math.cos, display_name = 'tcos', f = f)
f.write('\n')
dumpCosine(_cosine_func = math.sin, display_name = 'tsin', f = f)
f.close()
main() | 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.
*--------------------------------------------------------------------------------------------*/
import { Emitter, Event } from 'vs/base/common/event';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { deepClone } from 'vs/base/common/objects';
import { URI } from 'vs/base/common/uri';
import { IEditorOptions, LineNumbersType } from 'vs/editor/common/config/editorOptions';
import { localize } from 'vs/nls';
import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { Registry } from 'vs/platform/registry/common/platform';
import { ActiveEditorContext } from 'vs/workbench/common/contextkeys';
import { INotebookCellToolbarActionContext, INotebookCommandContext, NotebookMultiCellAction, NOTEBOOK_ACTIONS_CATEGORY } from 'vs/workbench/contrib/notebook/browser/controller/coreActions';
import { ICellViewModel, INotebookEditorDelegate } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { NOTEBOOK_CELL_LINE_NUMBERS, NOTEBOOK_EDITOR_FOCUSED } from 'vs/workbench/contrib/notebook/common/notebookContextKeys';
import { CellPart } from 'vs/workbench/contrib/notebook/browser/view/cellParts/cellPart';
import { NotebookCellInternalMetadata, NOTEBOOK_EDITOR_ID } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { NotebookOptions } from 'vs/workbench/contrib/notebook/common/notebookOptions';
import { CellViewModelStateChangeEvent } from 'vs/workbench/contrib/notebook/browser/notebookViewEvents';
export class CellEditorOptions extends CellPart {
private static fixedEditorOptions: IEditorOptions = {
scrollBeyondLastLine: false,
scrollbar: {
verticalScrollbarSize: 14,
horizontal: 'auto',
useShadows: true,
verticalHasArrows: false,
horizontalHasArrows: false,
alwaysConsumeMouseWheel: false
},
renderLineHighlightOnlyWhenFocus: true,
overviewRulerLanes: 0,
selectOnLineNumbers: false,
lineNumbers: 'off',
lineDecorationsWidth: 0,
folding: true,
fixedOverflowWidgets: true,
minimap: { enabled: false },
renderValidationDecorations: 'on',
lineNumbersMinChars: 3
};
private _value: IEditorOptions;
private _lineNumbers: 'on' | 'off' | 'inherit' = 'inherit';
private readonly _onDidChange = this._register(new Emitter<void>());
readonly onDidChange: Event<void> = this._onDidChange.event;
private _localDisposableStore = this._register(new DisposableStore());
constructor(readonly notebookEditor: INotebookEditorDelegate, readonly notebookOptions: NotebookOptions, readonly configurationService: IConfigurationService, readonly language: string) {
super();
this._register(configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('editor') || e.affectsConfiguration('notebook')) {
this._recomputeOptions();
}
}));
this._register(notebookOptions.onDidChangeOptions(e => {
if (e.cellStatusBarVisibility || e.editorTopPadding || e.editorOptionsCustomizations) {
this._recomputeOptions();
}
}));
this._register(this.notebookEditor.onDidChangeModel(() => {
this._localDisposableStore.clear();
if (this.notebookEditor.hasModel()) {
this._localDisposableStore.add(this.notebookEditor.onDidChangeOptions(() => {
this._recomputeOptions();
}));
this._recomputeOptions();
}
}));
if (this.notebookEditor.hasModel()) {
this._localDisposableStore.add(this.notebookEditor.onDidChangeOptions(() => {
this._recomputeOptions();
}));
}
this._value = this._computeEditorOptions();
}
renderCell(element: ICellViewModel): void {
// no op
}
prepareLayout(): void {
// nothing to read
}
updateInternalLayoutNow(element: ICellViewModel): void {
// nothing to update
}
updateState(element: ICellViewModel, e: CellViewModelStateChangeEvent) {
if (e.cellLineNumberChanged) {
this.setLineNumbers(element.lineNumbers);
}
}
private _recomputeOptions(): void {
this._value = this._computeEditorOptions();
this._onDidChange.fire();
}
private _computeEditorOptions() {
const renderLineNumbers = this.configurationService.getValue<'on' | 'off'>('notebook.lineNumbers') === 'on';
const lineNumbers: LineNumbersType = renderLineNumbers ? 'on' : 'off';
const editorOptions = deepClone(this.configurationService.getValue<IEditorOptions>('editor', { overrideIdentifier: this.language }));
const layoutConfig = this.notebookOptions.getLayoutConfiguration();
const editorOptionsOverrideRaw = layoutConfig.editorOptionsCustomizations ?? {};
const editorOptionsOverride: { [key: string]: any } = {};
for (const key in editorOptionsOverrideRaw) {
if (key.indexOf('editor.') === 0) {
editorOptionsOverride[key.substring(7)] = editorOptionsOverrideRaw[key];
}
}
const computed = {
...editorOptions,
...CellEditorOptions.fixedEditorOptions,
... { lineNumbers },
...editorOptionsOverride,
...{ padding: { top: 12, bottom: 12 } },
readOnly: this.notebookEditor.isReadOnly
};
return computed;
}
getUpdatedValue(internalMetadata: NotebookCellInternalMetadata, cellUri: URI): IEditorOptions {
const options = this.getValue(internalMetadata, cellUri);
delete options.hover; // This is toggled by a debug editor contribution
return options;
}
getValue(internalMetadata: NotebookCellInternalMetadata, cellUri: URI): IEditorOptions {
return {
...this._value,
...{
padding: this.notebookOptions.computeEditorPadding(internalMetadata, cellUri)
}
};
}
getDefaultValue(): IEditorOptions {
return {
...this._value,
...{
padding: { top: 12, bottom: 12 }
}
};
}
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';
this._value.lineNumbers = lineNumbers;
} else {
this._value.lineNumbers = lineNumbers as LineNumbersType;
}
this._onDidChange.fire();
}
}
Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).registerConfiguration({
id: 'notebook',
order: 100,
type: 'object',
'properties': {
'notebook.lineNumbers': {
type: 'string',
enum: ['off', 'on'],
default: 'off',
markdownDescription: localize('notebook.lineNumbers', "Controls the display of line numbers in the cell editor.")
}
}
});
registerAction2(class ToggleLineNumberAction extends Action2 {
constructor() {
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: 2,
when: ContextKeyExpr.equals('config.notebook.globalToolbar', true)
}],
category: NOTEBOOK_ACTIONS_CATEGORY,
f1: true,
toggled: {
condition: ContextKeyExpr.notEquals('config.notebook.lineNumbers', 'off'),
title: { value: localize('notebook.showLineNumbers', "Show Notebook Line Numbers"), original: 'Show Notebook Line Numbers' },
}
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const configurationService = accessor.get(IConfigurationService);
const renderLiNumbers = configurationService.getValue<'on' | 'off'>('notebook.lineNumbers') === 'on';
if (renderLiNumbers) {
configurationService.updateValue('notebook.lineNumbers', 'off');
} else {
configurationService.updateValue('notebook.lineNumbers', 'on');
}
}
});
registerAction2(class ToggleActiveLineNumberAction extends NotebookMultiCellAction {
constructor() {
super({
id: 'notebook.cell.toggleLineNumbers',
title: localize('notebook.cell.toggleLineNumbers.title', "Show Cell Line Numbers"),
precondition: ActiveEditorContext.isEqualTo(NOTEBOOK_EDITOR_ID),
menu: [{
id: MenuId.NotebookCellTitle,
group: 'View',
order: 1
}],
toggled: ContextKeyExpr.or(
NOTEBOOK_CELL_LINE_NUMBERS.isEqualTo('on'),
ContextKeyExpr.and(NOTEBOOK_CELL_LINE_NUMBERS.isEqualTo('inherit'), ContextKeyExpr.equals('config.notebook.lineNumbers', 'on'))
)
});
}
async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> {
if (context.ui) {
this.updateCell(accessor.get(IConfigurationService), context.cell);
} else {
const configurationService = accessor.get(IConfigurationService);
context.selectedCells.forEach(cell => {
this.updateCell(configurationService, cell);
});
}
}
private updateCell(configurationService: IConfigurationService, cell: ICellViewModel) {
const renderLineNumbers = configurationService.getValue<'on' | 'off'>('notebook.lineNumbers') === 'on';
const cellLineNumbers = cell.lineNumbers;
// 'on', 'inherit' -> 'on'
// 'on', 'off' -> 'off'
// 'on', 'on' -> 'on'
// 'off', 'inherit' -> 'off'
// 'off', 'off' -> 'off'
// 'off', 'on' -> 'on'
const currentLineNumberIsOn = cellLineNumbers === 'on' || (cellLineNumbers === 'inherit' && renderLineNumbers);
if (currentLineNumberIsOn) | 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.
*--------------------------------------------------------------------------------------------*/
import { Emitter, Event } from 'vs/base/common/event';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { deepClone } from 'vs/base/common/objects';
import { URI } from 'vs/base/common/uri';
import { IEditorOptions, LineNumbersType } from 'vs/editor/common/config/editorOptions';
import { localize } from 'vs/nls';
import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { Registry } from 'vs/platform/registry/common/platform';
import { ActiveEditorContext } from 'vs/workbench/common/contextkeys';
import { INotebookCellToolbarActionContext, INotebookCommandContext, NotebookMultiCellAction, NOTEBOOK_ACTIONS_CATEGORY } from 'vs/workbench/contrib/notebook/browser/controller/coreActions';
import { ICellViewModel, INotebookEditorDelegate } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { NOTEBOOK_CELL_LINE_NUMBERS, NOTEBOOK_EDITOR_FOCUSED } from 'vs/workbench/contrib/notebook/common/notebookContextKeys';
import { CellPart } from 'vs/workbench/contrib/notebook/browser/view/cellParts/cellPart';
import { NotebookCellInternalMetadata, NOTEBOOK_EDITOR_ID } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { NotebookOptions } from 'vs/workbench/contrib/notebook/common/notebookOptions';
import { CellViewModelStateChangeEvent } from 'vs/workbench/contrib/notebook/browser/notebookViewEvents';
export class CellEditorOptions extends CellPart {
private static fixedEditorOptions: IEditorOptions = {
scrollBeyondLastLine: false,
scrollbar: {
verticalScrollbarSize: 14,
horizontal: 'auto',
useShadows: true,
verticalHasArrows: false,
horizontalHasArrows: false,
alwaysConsumeMouseWheel: false
},
renderLineHighlightOnlyWhenFocus: true,
overviewRulerLanes: 0,
selectOnLineNumbers: false,
lineNumbers: 'off',
lineDecorationsWidth: 0,
folding: true,
fixedOverflowWidgets: true,
minimap: { enabled: false },
renderValidationDecorations: 'on',
lineNumbersMinChars: 3
};
private _value: IEditorOptions;
private _lineNumbers: 'on' | 'off' | 'inherit' = 'inherit';
private readonly _onDidChange = this._register(new Emitter<void>());
readonly onDidChange: Event<void> = this._onDidChange.event;
private _localDisposableStore = this._register(new DisposableStore());
constructor(readonly notebookEditor: INotebookEditorDelegate, readonly notebookOptions: NotebookOptions, readonly configurationService: IConfigurationService, readonly language: string) {
super();
this._register(configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('editor') || e.affectsConfiguration('notebook')) {
this._recomputeOptions();
}
}));
this._register(notebookOptions.onDidChangeOptions(e => {
if (e.cellStatusBarVisibility || e.editorTopPadding || e.editorOptionsCustomizations) {
this._recomputeOptions();
}
}));
this._register(this.notebookEditor.onDidChangeModel(() => {
this._localDisposableStore.clear();
if (this.notebookEditor.hasModel()) {
this._localDisposableStore.add(this.notebookEditor.onDidChangeOptions(() => {
this._recomputeOptions();
}));
this._recomputeOptions();
}
}));
if (this.notebookEditor.hasModel()) {
this._localDisposableStore.add(this.notebookEditor.onDidChangeOptions(() => {
this._recomputeOptions();
}));
}
this._value = this._computeEditorOptions();
}
renderCell(element: ICellViewModel): void {
// no op
}
prepareLayout(): void {
// nothing to read
}
updateInternalLayoutNow(element: ICellViewModel): void {
// nothing to update
}
updateState(element: ICellViewModel, e: CellViewModelStateChangeEvent) {
if (e.cellLineNumberChanged) {
this.setLineNumbers(element.lineNumbers);
}
}
private _recomputeOptions(): void {
this._value = this._computeEditorOptions();
this._onDidChange.fire();
}
private _computeEditorOptions() {
const renderLineNumbers = this.configurationService.getValue<'on' | 'off'>('notebook.lineNumbers') === 'on';
const lineNumbers: LineNumbersType = renderLineNumbers ? 'on' : 'off';
const editorOptions = deepClone(this.configurationService.getValue<IEditorOptions>('editor', { overrideIdentifier: this.language }));
const layoutConfig = this.notebookOptions.getLayoutConfiguration();
const editorOptionsOverrideRaw = layoutConfig.editorOptionsCustomizations ?? {};
const editorOptionsOverride: { [key: string]: any } = {};
for (const key in editorOptionsOverrideRaw) {
if (key.indexOf('editor.') === 0) {
editorOptionsOverride[key.substring(7)] = editorOptionsOverrideRaw[key];
}
}
const computed = {
...editorOptions,
...CellEditorOptions.fixedEditorOptions,
... { lineNumbers },
...editorOptionsOverride,
...{ padding: { top: 12, bottom: 12 } },
readOnly: this.notebookEditor.isReadOnly
};
return computed;
}
getUpdatedValue(internalMetadata: NotebookCellInternalMetadata, cellUri: URI): IEditorOptions {
const options = this.getValue(internalMetadata, cellUri);
delete options.hover; // This is toggled by a debug editor contribution
return options;
}
getValue(internalMetadata: NotebookCellInternalMetadata, cellUri: URI): IEditorOptions {
return {
...this._value,
...{
padding: this.notebookOptions.computeEditorPadding(internalMetadata, cellUri)
}
};
}
getDefaultValue(): IEditorOptions {
return {
...this._value,
...{
padding: { top: 12, bottom: 12 }
}
};
}
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';
this._value.lineNumbers = lineNumbers;
} else {
this._value.lineNumbers = lineNumbers as LineNumbersType;
}
this._onDidChange.fire();
}
}
Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).registerConfiguration({
id: 'notebook',
order: 100,
type: 'object',
'properties': {
'notebook.lineNumbers': {
type: 'string',
enum: ['off', 'on'],
default: 'off',
markdownDescription: localize('notebook.lineNumbers', "Controls the display of line numbers in the cell editor.")
}
}
});
registerAction2(class ToggleLineNumberAction extends Action2 {
| () {
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: 2,
when: ContextKeyExpr.equals('config.notebook.globalToolbar', true)
}],
category: NOTEBOOK_ACTIONS_CATEGORY,
f1: true,
toggled: {
condition: ContextKeyExpr.notEquals('config.notebook.lineNumbers', 'off'),
title: { value: localize('notebook.showLineNumbers', "Show Notebook Line Numbers"), original: 'Show Notebook Line Numbers' },
}
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const configurationService = accessor.get(IConfigurationService);
const renderLiNumbers = configurationService.getValue<'on' | 'off'>('notebook.lineNumbers') === 'on';
if (renderLiNumbers) {
configurationService.updateValue('notebook.lineNumbers', 'off');
} else {
configurationService.updateValue('notebook.lineNumbers', 'on');
}
}
});
registerAction2(class ToggleActiveLineNumberAction extends NotebookMultiCellAction {
constructor() {
super({
id: 'notebook.cell.toggleLineNumbers',
title: localize('notebook.cell.toggleLineNumbers.title', "Show Cell Line Numbers"),
precondition: ActiveEditorContext.isEqualTo(NOTEBOOK_EDITOR_ID),
menu: [{
id: MenuId.NotebookCellTitle,
group: 'View',
order: 1
}],
toggled: ContextKeyExpr.or(
NOTEBOOK_CELL_LINE_NUMBERS.isEqualTo('on'),
ContextKeyExpr.and(NOTEBOOK_CELL_LINE_NUMBERS.isEqualTo('inherit'), ContextKeyExpr.equals('config.notebook.lineNumbers', 'on'))
)
});
}
async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> {
if (context.ui) {
this.updateCell(accessor.get(IConfigurationService), context.cell);
} else {
const configurationService = accessor.get(IConfigurationService);
context.selectedCells.forEach(cell => {
this.updateCell(configurationService, cell);
});
}
}
private updateCell(configurationService: IConfigurationService, cell: ICellViewModel) {
const renderLineNumbers = configurationService.getValue<'on' | 'off'>('notebook.lineNumbers') === 'on';
const cellLineNumbers = cell.lineNumbers;
// 'on', 'inherit' -> 'on'
// 'on', 'off' -> 'off'
// 'on', 'on' -> 'on'
// 'off', 'inherit' -> 'off'
// 'off', 'off' -> 'off'
// 'off', 'on' -> 'on'
const currentLineNumberIsOn = cellLineNumbers === 'on' || (cellLineNumbers === 'inherit' && renderLineNumbers);
if (currentLineNumberIsOn) {
cell.lineNumbers = 'off';
} else {
cell.lineNumbers = 'on';
}
}
});
| 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.
*--------------------------------------------------------------------------------------------*/
import { Emitter, Event } from 'vs/base/common/event';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { deepClone } from 'vs/base/common/objects';
import { URI } from 'vs/base/common/uri';
import { IEditorOptions, LineNumbersType } from 'vs/editor/common/config/editorOptions';
import { localize } from 'vs/nls';
import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { Registry } from 'vs/platform/registry/common/platform';
import { ActiveEditorContext } from 'vs/workbench/common/contextkeys';
import { INotebookCellToolbarActionContext, INotebookCommandContext, NotebookMultiCellAction, NOTEBOOK_ACTIONS_CATEGORY } from 'vs/workbench/contrib/notebook/browser/controller/coreActions';
import { ICellViewModel, INotebookEditorDelegate } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { NOTEBOOK_CELL_LINE_NUMBERS, NOTEBOOK_EDITOR_FOCUSED } from 'vs/workbench/contrib/notebook/common/notebookContextKeys';
import { CellPart } from 'vs/workbench/contrib/notebook/browser/view/cellParts/cellPart';
import { NotebookCellInternalMetadata, NOTEBOOK_EDITOR_ID } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { NotebookOptions } from 'vs/workbench/contrib/notebook/common/notebookOptions';
import { CellViewModelStateChangeEvent } from 'vs/workbench/contrib/notebook/browser/notebookViewEvents';
export class CellEditorOptions extends CellPart {
private static fixedEditorOptions: IEditorOptions = {
scrollBeyondLastLine: false,
scrollbar: {
verticalScrollbarSize: 14,
horizontal: 'auto',
useShadows: true,
verticalHasArrows: false,
horizontalHasArrows: false,
alwaysConsumeMouseWheel: false
},
renderLineHighlightOnlyWhenFocus: true,
overviewRulerLanes: 0,
selectOnLineNumbers: false,
lineNumbers: 'off',
lineDecorationsWidth: 0,
folding: true,
fixedOverflowWidgets: true,
minimap: { enabled: false },
renderValidationDecorations: 'on',
lineNumbersMinChars: 3
};
private _value: IEditorOptions;
private _lineNumbers: 'on' | 'off' | 'inherit' = 'inherit';
private readonly _onDidChange = this._register(new Emitter<void>());
readonly onDidChange: Event<void> = this._onDidChange.event;
private _localDisposableStore = this._register(new DisposableStore());
constructor(readonly notebookEditor: INotebookEditorDelegate, readonly notebookOptions: NotebookOptions, readonly configurationService: IConfigurationService, readonly language: string) {
super();
this._register(configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('editor') || e.affectsConfiguration('notebook')) {
this._recomputeOptions();
}
}));
this._register(notebookOptions.onDidChangeOptions(e => {
if (e.cellStatusBarVisibility || e.editorTopPadding || e.editorOptionsCustomizations) {
this._recomputeOptions();
}
}));
this._register(this.notebookEditor.onDidChangeModel(() => {
this._localDisposableStore.clear();
if (this.notebookEditor.hasModel()) {
this._localDisposableStore.add(this.notebookEditor.onDidChangeOptions(() => {
this._recomputeOptions();
}));
this._recomputeOptions();
}
}));
if (this.notebookEditor.hasModel()) {
this._localDisposableStore.add(this.notebookEditor.onDidChangeOptions(() => {
this._recomputeOptions();
}));
}
this._value = this._computeEditorOptions();
}
renderCell(element: ICellViewModel): void {
// no op
}
prepareLayout(): void {
// nothing to read
}
updateInternalLayoutNow(element: ICellViewModel): void {
// nothing to update
}
updateState(element: ICellViewModel, e: CellViewModelStateChangeEvent) {
if (e.cellLineNumberChanged) {
this.setLineNumbers(element.lineNumbers);
}
}
private _recomputeOptions(): void {
this._value = this._computeEditorOptions();
this._onDidChange.fire();
}
private _computeEditorOptions() {
const renderLineNumbers = this.configurationService.getValue<'on' | 'off'>('notebook.lineNumbers') === 'on';
const lineNumbers: LineNumbersType = renderLineNumbers ? 'on' : 'off';
const editorOptions = deepClone(this.configurationService.getValue<IEditorOptions>('editor', { overrideIdentifier: this.language }));
const layoutConfig = this.notebookOptions.getLayoutConfiguration();
const editorOptionsOverrideRaw = layoutConfig.editorOptionsCustomizations ?? {};
const editorOptionsOverride: { [key: string]: any } = {};
for (const key in editorOptionsOverrideRaw) {
if (key.indexOf('editor.') === 0) {
editorOptionsOverride[key.substring(7)] = editorOptionsOverrideRaw[key];
}
}
const computed = {
...editorOptions,
...CellEditorOptions.fixedEditorOptions,
... { lineNumbers },
...editorOptionsOverride,
...{ padding: { top: 12, bottom: 12 } },
readOnly: this.notebookEditor.isReadOnly
};
return computed;
}
getUpdatedValue(internalMetadata: NotebookCellInternalMetadata, cellUri: URI): IEditorOptions {
const options = this.getValue(internalMetadata, cellUri);
delete options.hover; // This is toggled by a debug editor contribution
return options;
}
getValue(internalMetadata: NotebookCellInternalMetadata, cellUri: URI): IEditorOptions {
return {
...this._value,
...{
padding: this.notebookOptions.computeEditorPadding(internalMetadata, cellUri)
}
};
}
getDefaultValue(): IEditorOptions {
return {
...this._value,
...{
padding: { top: 12, bottom: 12 }
}
};
}
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';
this._value.lineNumbers = lineNumbers;
} else {
this._value.lineNumbers = lineNumbers as LineNumbersType;
}
this._onDidChange.fire();
}
}
Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).registerConfiguration({
id: 'notebook',
order: 100,
type: 'object',
'properties': {
'notebook.lineNumbers': {
type: 'string',
enum: ['off', 'on'],
default: 'off',
markdownDescription: localize('notebook.lineNumbers', "Controls the display of line numbers in the cell editor.")
}
}
});
registerAction2(class ToggleLineNumberAction extends Action2 {
constructor() {
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: 2,
when: ContextKeyExpr.equals('config.notebook.globalToolbar', true)
}],
category: NOTEBOOK_ACTIONS_CATEGORY,
f1: true,
toggled: {
condition: ContextKeyExpr.notEquals('config.notebook.lineNumbers', 'off'),
title: { value: localize('notebook.showLineNumbers', "Show Notebook Line Numbers"), original: 'Show Notebook Line Numbers' },
}
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const configurationService = accessor.get(IConfigurationService); | configurationService.updateValue('notebook.lineNumbers', 'off');
} else {
configurationService.updateValue('notebook.lineNumbers', 'on');
}
}
});
registerAction2(class ToggleActiveLineNumberAction extends NotebookMultiCellAction {
constructor() {
super({
id: 'notebook.cell.toggleLineNumbers',
title: localize('notebook.cell.toggleLineNumbers.title', "Show Cell Line Numbers"),
precondition: ActiveEditorContext.isEqualTo(NOTEBOOK_EDITOR_ID),
menu: [{
id: MenuId.NotebookCellTitle,
group: 'View',
order: 1
}],
toggled: ContextKeyExpr.or(
NOTEBOOK_CELL_LINE_NUMBERS.isEqualTo('on'),
ContextKeyExpr.and(NOTEBOOK_CELL_LINE_NUMBERS.isEqualTo('inherit'), ContextKeyExpr.equals('config.notebook.lineNumbers', 'on'))
)
});
}
async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> {
if (context.ui) {
this.updateCell(accessor.get(IConfigurationService), context.cell);
} else {
const configurationService = accessor.get(IConfigurationService);
context.selectedCells.forEach(cell => {
this.updateCell(configurationService, cell);
});
}
}
private updateCell(configurationService: IConfigurationService, cell: ICellViewModel) {
const renderLineNumbers = configurationService.getValue<'on' | 'off'>('notebook.lineNumbers') === 'on';
const cellLineNumbers = cell.lineNumbers;
// 'on', 'inherit' -> 'on'
// 'on', 'off' -> 'off'
// 'on', 'on' -> 'on'
// 'off', 'inherit' -> 'off'
// 'off', 'off' -> 'off'
// 'off', 'on' -> 'on'
const currentLineNumberIsOn = cellLineNumbers === 'on' || (cellLineNumbers === 'inherit' && renderLineNumbers);
if (currentLineNumberIsOn) {
cell.lineNumbers = 'off';
} else {
cell.lineNumbers = 'on';
}
}
}); | 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.
*--------------------------------------------------------------------------------------------*/
import { Emitter, Event } from 'vs/base/common/event';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { deepClone } from 'vs/base/common/objects';
import { URI } from 'vs/base/common/uri';
import { IEditorOptions, LineNumbersType } from 'vs/editor/common/config/editorOptions';
import { localize } from 'vs/nls';
import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { Registry } from 'vs/platform/registry/common/platform';
import { ActiveEditorContext } from 'vs/workbench/common/contextkeys';
import { INotebookCellToolbarActionContext, INotebookCommandContext, NotebookMultiCellAction, NOTEBOOK_ACTIONS_CATEGORY } from 'vs/workbench/contrib/notebook/browser/controller/coreActions';
import { ICellViewModel, INotebookEditorDelegate } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { NOTEBOOK_CELL_LINE_NUMBERS, NOTEBOOK_EDITOR_FOCUSED } from 'vs/workbench/contrib/notebook/common/notebookContextKeys';
import { CellPart } from 'vs/workbench/contrib/notebook/browser/view/cellParts/cellPart';
import { NotebookCellInternalMetadata, NOTEBOOK_EDITOR_ID } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { NotebookOptions } from 'vs/workbench/contrib/notebook/common/notebookOptions';
import { CellViewModelStateChangeEvent } from 'vs/workbench/contrib/notebook/browser/notebookViewEvents';
export class CellEditorOptions extends CellPart {
private static fixedEditorOptions: IEditorOptions = {
scrollBeyondLastLine: false,
scrollbar: {
verticalScrollbarSize: 14,
horizontal: 'auto',
useShadows: true,
verticalHasArrows: false,
horizontalHasArrows: false,
alwaysConsumeMouseWheel: false
},
renderLineHighlightOnlyWhenFocus: true,
overviewRulerLanes: 0,
selectOnLineNumbers: false,
lineNumbers: 'off',
lineDecorationsWidth: 0,
folding: true,
fixedOverflowWidgets: true,
minimap: { enabled: false },
renderValidationDecorations: 'on',
lineNumbersMinChars: 3
};
private _value: IEditorOptions;
private _lineNumbers: 'on' | 'off' | 'inherit' = 'inherit';
private readonly _onDidChange = this._register(new Emitter<void>());
readonly onDidChange: Event<void> = this._onDidChange.event;
private _localDisposableStore = this._register(new DisposableStore());
constructor(readonly notebookEditor: INotebookEditorDelegate, readonly notebookOptions: NotebookOptions, readonly configurationService: IConfigurationService, readonly language: string) {
super();
this._register(configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('editor') || e.affectsConfiguration('notebook')) {
this._recomputeOptions();
}
}));
this._register(notebookOptions.onDidChangeOptions(e => {
if (e.cellStatusBarVisibility || e.editorTopPadding || e.editorOptionsCustomizations) {
this._recomputeOptions();
}
}));
this._register(this.notebookEditor.onDidChangeModel(() => {
this._localDisposableStore.clear();
if (this.notebookEditor.hasModel()) {
this._localDisposableStore.add(this.notebookEditor.onDidChangeOptions(() => {
this._recomputeOptions();
}));
this._recomputeOptions();
}
}));
if (this.notebookEditor.hasModel()) {
this._localDisposableStore.add(this.notebookEditor.onDidChangeOptions(() => {
this._recomputeOptions();
}));
}
this._value = this._computeEditorOptions();
}
renderCell(element: ICellViewModel): void {
// no op
}
prepareLayout(): void {
// nothing to read
}
updateInternalLayoutNow(element: ICellViewModel): void {
// nothing to update
}
updateState(element: ICellViewModel, e: CellViewModelStateChangeEvent) {
if (e.cellLineNumberChanged) {
this.setLineNumbers(element.lineNumbers);
}
}
private _recomputeOptions(): void {
this._value = this._computeEditorOptions();
this._onDidChange.fire();
}
private _computeEditorOptions() {
const renderLineNumbers = this.configurationService.getValue<'on' | 'off'>('notebook.lineNumbers') === 'on';
const lineNumbers: LineNumbersType = renderLineNumbers ? 'on' : 'off';
const editorOptions = deepClone(this.configurationService.getValue<IEditorOptions>('editor', { overrideIdentifier: this.language }));
const layoutConfig = this.notebookOptions.getLayoutConfiguration();
const editorOptionsOverrideRaw = layoutConfig.editorOptionsCustomizations ?? {};
const editorOptionsOverride: { [key: string]: any } = {};
for (const key in editorOptionsOverrideRaw) {
if (key.indexOf('editor.') === 0) {
editorOptionsOverride[key.substring(7)] = editorOptionsOverrideRaw[key];
}
}
const computed = {
...editorOptions,
...CellEditorOptions.fixedEditorOptions,
... { lineNumbers },
...editorOptionsOverride,
...{ padding: { top: 12, bottom: 12 } },
readOnly: this.notebookEditor.isReadOnly
};
return computed;
}
getUpdatedValue(internalMetadata: NotebookCellInternalMetadata, cellUri: URI): IEditorOptions {
const options = this.getValue(internalMetadata, cellUri);
delete options.hover; // This is toggled by a debug editor contribution
return options;
}
getValue(internalMetadata: NotebookCellInternalMetadata, cellUri: URI): IEditorOptions {
return {
...this._value,
...{
padding: this.notebookOptions.computeEditorPadding(internalMetadata, cellUri)
}
};
}
getDefaultValue(): IEditorOptions |
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';
this._value.lineNumbers = lineNumbers;
} else {
this._value.lineNumbers = lineNumbers as LineNumbersType;
}
this._onDidChange.fire();
}
}
Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).registerConfiguration({
id: 'notebook',
order: 100,
type: 'object',
'properties': {
'notebook.lineNumbers': {
type: 'string',
enum: ['off', 'on'],
default: 'off',
markdownDescription: localize('notebook.lineNumbers', "Controls the display of line numbers in the cell editor.")
}
}
});
registerAction2(class ToggleLineNumberAction extends Action2 {
constructor() {
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: 2,
when: ContextKeyExpr.equals('config.notebook.globalToolbar', true)
}],
category: NOTEBOOK_ACTIONS_CATEGORY,
f1: true,
toggled: {
condition: ContextKeyExpr.notEquals('config.notebook.lineNumbers', 'off'),
title: { value: localize('notebook.showLineNumbers', "Show Notebook Line Numbers"), original: 'Show Notebook Line Numbers' },
}
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const configurationService = accessor.get(IConfigurationService);
const renderLiNumbers = configurationService.getValue<'on' | 'off'>('notebook.lineNumbers') === 'on';
if (renderLiNumbers) {
configurationService.updateValue('notebook.lineNumbers', 'off');
} else {
configurationService.updateValue('notebook.lineNumbers', 'on');
}
}
});
registerAction2(class ToggleActiveLineNumberAction extends NotebookMultiCellAction {
constructor() {
super({
id: 'notebook.cell.toggleLineNumbers',
title: localize('notebook.cell.toggleLineNumbers.title', "Show Cell Line Numbers"),
precondition: ActiveEditorContext.isEqualTo(NOTEBOOK_EDITOR_ID),
menu: [{
id: MenuId.NotebookCellTitle,
group: 'View',
order: 1
}],
toggled: ContextKeyExpr.or(
NOTEBOOK_CELL_LINE_NUMBERS.isEqualTo('on'),
ContextKeyExpr.and(NOTEBOOK_CELL_LINE_NUMBERS.isEqualTo('inherit'), ContextKeyExpr.equals('config.notebook.lineNumbers', 'on'))
)
});
}
async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> {
if (context.ui) {
this.updateCell(accessor.get(IConfigurationService), context.cell);
} else {
const configurationService = accessor.get(IConfigurationService);
context.selectedCells.forEach(cell => {
this.updateCell(configurationService, cell);
});
}
}
private updateCell(configurationService: IConfigurationService, cell: ICellViewModel) {
const renderLineNumbers = configurationService.getValue<'on' | 'off'>('notebook.lineNumbers') === 'on';
const cellLineNumbers = cell.lineNumbers;
// 'on', 'inherit' -> 'on'
// 'on', 'off' -> 'off'
// 'on', 'on' -> 'on'
// 'off', 'inherit' -> 'off'
// 'off', 'off' -> 'off'
// 'off', 'on' -> 'on'
const currentLineNumberIsOn = cellLineNumbers === 'on' || (cellLineNumbers === 'inherit' && renderLineNumbers);
if (currentLineNumberIsOn) {
cell.lineNumbers = 'off';
} else {
cell.lineNumbers = 'on';
}
}
});
| {
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, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
_ = require('underscore');
EventEmitter = require('events').EventEmitter;
BackoffTimer = require('./backofftimer');
NodeState = require('node-state');
NSQDConnection = require('./nsqdconnection').NSQDConnection;
RoundRobinList = require('./roundrobinlist');
StateChangeLogger = require('./logging');
/*
Maintains the RDY and in-flight counts for a nsqd connection. ConnectionRdy
ensures that the RDY count will not exceed the max set for this connection.
The max for the connection can be adjusted at any time.
Usage:
connRdy = ConnectionRdy conn
connRdy.setConnectionRdyMax 10
conn.on 'message', ->
# On a successful message, bump up the RDY count for this connection.
connRdy.raise 'bump'
conn.on 'requeue', ->
# We're backing off when we encounter a requeue. Wait 5 seconds to try
# again.
connRdy.raise 'backoff'
setTimeout (-> connRdy.raise 'bump'), 5000
*/
ConnectionRdy = (function(_super) {
__extends(ConnectionRdy, _super);
ConnectionRdy.READY = 'ready';
ConnectionRdy.STATE_CHANGE = 'statechange';
function ConnectionRdy(conn) {
var _this = this;
this.conn = conn;
this.maxConnRdy = 0;
this.inFlight = 0;
this.lastRdySent = 0;
this.availableRdy = 0;
this.statemachine = new ConnectionRdyState(this);
this.conn.on(NSQDConnection.ERROR, function(err) {
return _this.log(err);
});
this.conn.on(NSQDConnection.MESSAGE, function() {
if (_this.idleId != null) {
clearTimeout(_this.idleId);
}
_this.idleId = null;
_this.inFlight += 1;
return _this.availableRdy -= 1;
});
this.conn.on(NSQDConnection.FINISHED, function() {
return _this.inFlight -= 1;
});
this.conn.on(NSQDConnection.REQUEUED, function() {
return _this.inFlight -= 1;
});
this.conn.on(NSQDConnection.READY, function() {
return _this.start();
});
}
ConnectionRdy.prototype.name = function() {
return String(this.conn.conn.localPort);
};
ConnectionRdy.prototype.start = function() {
this.statemachine.start();
return this.emit(ConnectionRdy.READY);
};
ConnectionRdy.prototype.setConnectionRdyMax = function(maxConnRdy) {
this.log("setConnectionRdyMax " + maxConnRdy);
this.maxConnRdy = Math.min(maxConnRdy, this.conn.maxRdyCount);
return this.statemachine.raise('adjustMax');
};
ConnectionRdy.prototype.bump = function() {
return this.statemachine.raise('bump');
};
ConnectionRdy.prototype.backoff = function() {
return this.statemachine.raise('backoff');
};
ConnectionRdy.prototype.isStarved = function() {
if (!(this.inFlight <= this.maxConnRdy)) {
throw new Error('isStarved check is failing');
}
return this.inFlight === this.lastRdySent;
};
ConnectionRdy.prototype.setRdy = function(rdyCount) {
this.log("RDY " + rdyCount);
if (rdyCount < 0 || rdyCount > this.maxConnRdy) {
return;
}
this.conn.setRdy(rdyCount);
return this.availableRdy = this.lastRdySent = rdyCount;
};
ConnectionRdy.prototype.log = function(message) {
return StateChangeLogger.log('ConnectionRdy', this.statemachine.current_state_name, this.name(), message);
};
return ConnectionRdy;
})(EventEmitter);
ConnectionRdyState = (function(_super) {
__extends(ConnectionRdyState, _super);
function ConnectionRdyState(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.states = {
INIT: {
bump: function() {
if (this.connRdy.maxConnRdy > 0) {
return this.goto('MAX');
}
},
backoff: function() {},
adjustMax: function() {}
},
BACKOFF: {
Enter: function() {
return this.connRdy.setRdy(0);
},
bump: function() {
if (this.connRdy.maxConnRdy > 0) {
return this.goto('ONE');
}
},
backoff: function() {},
adjustMax: function() {}
},
ONE: {
Enter: function() {
return this.connRdy.setRdy(1);
},
bump: function() {
return this.goto('MAX');
},
backoff: function() {
return this.goto('BACKOFF');
},
adjustMax: function() {}
},
MAX: {
Enter: function() {
return this.raise('bump');
},
bump: function() {
if (this.connRdy.availableRdy <= this.connRdy.lastRdySent * 0.25) {
return this.connRdy.setRdy(this.connRdy.maxConnRdy);
}
},
backoff: function() {
return this.goto('BACKOFF');
},
adjustMax: function() {
this.log("adjustMax RDY " + this.connRdy.maxConnRdy);
return this.connRdy.setRdy(this.connRdy.maxConnRdy);
}
}
};
ConnectionRdyState.prototype.transitions = {
'*': {
'*': function(data, callback) {
this.log('');
callback(data);
return this.connRdy.emit(ConnectionRdy.STATE_CHANGE);
}
}
};
return ConnectionRdyState;
})(NodeState);
/*
Usage:
backoffTime = 90
heartbeat = 30
[topic, channel] = ['sample', 'default']
[host1, port1] = ['127.0.0.1', '4150']
c1 = new NSQDConnection host1, port1, topic, channel, backoffTime, heartbeat
readerRdy = new ReaderRdy 1, 128
readerRdy.addConnection c1
message = (msg) ->
console.log "Callback [message]: #{msg.attempts}, #{msg.body.toString()}"
if msg.attempts >= 5
msg.finish()
return
if msg.body.toString() is 'requeue'
msg.requeue()
else
msg.finish()
discard = (msg) ->
console.log "Giving up on this message: #{msg.id}"
msg.finish()
c1.on NSQDConnection.MESSAGE, message
c1.connect()
*/
READER_COUNT = 0;
ReaderRdy = (function(_super) {
__extends(ReaderRdy, _super);
ReaderRdy.getId = function() {
READER_COUNT += 1;
return READER_COUNT - 1;
};
/*
Parameters:
- maxInFlight : Maximum number of messages in-flight across all
connections.
- maxBackoffDuration : The longest amount of time (secs) for a backoff event.
- lowRdyTimeout : Time (secs) to rebalance RDY count among connections
during low RDY conditions.
*/
function ReaderRdy(maxInFlight, maxBackoffDuration, lowRdyTimeout) {
this.maxInFlight = maxInFlight;
this.maxBackoffDuration = maxBackoffDuration;
this.lowRdyTimeout = lowRdyTimeout != null ? lowRdyTimeout : 1.5;
ReaderRdy.__super__.constructor.call(this, {
autostart: true,
initial_state: 'ZERO',
sync_goto: true
});
this.id = ReaderRdy.getId();
this.backoffTimer = new BackoffTimer(0, this.maxBackoffDuration);
this.backoffId = null;
this.balanceId = null;
this.connections = [];
this.roundRobinConnections = new RoundRobinList([]);
}
ReaderRdy.prototype.close = function() {
clearTimeout(this.backoffId);
return clearTimeout(this.balanceId);
};
ReaderRdy.prototype.log = function(message) {
return StateChangeLogger.log('ReaderRdy', this.current_state_name, this.id, message);
};
ReaderRdy.prototype.isStarved = function() {
var c;
if (_.isEmpty(this.connections)) {
return false;
}
return !_.isEmpty(((function() {
var _i, _len, _ref, _results;
if (c.isStarved()) {
_ref = this.connections;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
c = _ref[_i];
_results.push(c);
}
return _results;
}
}).call(this)));
};
ReaderRdy.prototype.createConnectionRdy = function(conn) {
return new ConnectionRdy(conn);
};
ReaderRdy.prototype.isLowRdy = function() {
return this.maxInFlight < this.connections.length;
};
ReaderRdy.prototype.addConnection = function(conn) {
var connectionRdy,
_this = this;
connectionRdy = this.createConnectionRdy(conn);
conn.on(NSQDConnection.CLOSED, function() {
_this.removeConnection(connectionRdy);
return _this.balance();
});
conn.on(NSQDConnection.FINISHED, function() {
_this.backoffTimer.success();
if (_this.isLowRdy()) {
_this.balance();
} else {
connectionRdy.bump();
}
return _this.raise('success');
});
conn.on(NSQDConnection.REQUEUED, function() {
if (_this.current_state_name !== 'BACKOFF') {
return connectionRdy.bump();
}
});
conn.on(NSQDConnection.BACKOFF, function() {
return _this.raise('backoff');
});
return connectionRdy.on(ConnectionRdy.READY, function() {
var _ref;
_this.connections.push(connectionRdy);
_this.roundRobinConnections.add(connectionRdy);
_this.balance();
if (_this.current_state_name === 'ZERO') {
return _this.goto('MAX');
} else if ((_ref = _this.current_state_name) === 'TRY_ONE' || _ref === 'MAX') {
return connectionRdy.bump();
}
});
};
ReaderRdy.prototype.removeConnection = function(conn) {
this.connections.splice(this.connections.indexOf(conn), 1);
this.roundRobinConnections.remove(conn);
if (this.connections.length === 0) |
};
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"] = function() {
return this.balance();
};
ReaderRdy.prototype.backoff = function() {
var conn, delay, onTimeout, _i, _len, _ref,
_this = this;
this.backoffTimer.failure();
_ref = this.connections;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
conn = _ref[_i];
conn.backoff();
}
if (this.backoffId) {
clearTimeout(this.backoffId);
}
onTimeout = function() {
return _this.raise('try');
};
delay = new Number(this.backoffTimer.getInterval().valueOf()) * 1000;
return this.backoffId = setTimeout(onTimeout, delay);
};
ReaderRdy.prototype.inFlight = function() {
var add;
add = function(previous, conn) {
return previous + conn.inFlight;
};
return this.connections.reduce(add, 0);
};
/*
Evenly or fairly distributes RDY count based on the maxInFlight across
all nsqd connections.
*/
ReaderRdy.prototype.balance = function() {
/*
In the perverse situation where there are more connections than max in
flight, we do the following:
There is a sliding window where each of the connections gets a RDY count
of 1. When the connection has processed it's single message, then the RDY
count is distributed to the next waiting connection. If the connection
does nothing with it's RDY count, then it should timeout and give it's
RDY count to another connection.
*/
var c, connMax, i, max, perConnectionMax, rdyRemainder, _i, _j, _k, _len, _len1, _ref, _ref1, _ref2, _results;
StateChangeLogger.log('ReaderRdy', this.current_state_name, this.id, 'balance');
if (this.balanceId != null) {
clearTimeout(this.balanceId);
this.balanceId = null;
}
max = this.current_state_name === 'TRY_ONE' ? 1 : this.maxInFlight;
perConnectionMax = Math.floor(max / this.connections.length);
if (perConnectionMax === 0) {
_ref = this.connections;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
c = _ref[_i];
c.backoff();
}
_ref1 = this.roundRobinConnections.next(max - this.inFlight());
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
c = _ref1[_j];
c.setConnectionRdyMax(1);
c.bump();
}
return this.balanceId = setTimeout(this.balance.bind(this), this.lowRdyTimeout * 1000);
} else {
rdyRemainder = this.maxInFlight % this.connectionsLength;
_results = [];
for (i = _k = 0, _ref2 = this.connections.length; 0 <= _ref2 ? _k < _ref2 : _k > _ref2; i = 0 <= _ref2 ? ++_k : --_k) {
connMax = perConnectionMax;
if (rdyRemainder > 0) {
connMax += 1;
rdyRemainder -= 1;
}
this.connections[i].setConnectionRdyMax(connMax);
_results.push(this.connections[i].bump());
}
return _results;
}
};
/*
The following events results in transitions in the ReaderRdy state machine:
1. Adding the first connection
2. Remove the last connections
3. Finish event from message handling
4. Backoff event from message handling
5. Backoff timeout
*/
ReaderRdy.prototype.states = {
ZERO: {
Enter: function() {
if (this.backoffId) {
return clearTimeout(this.backoffId);
}
},
backoff: function() {},
success: function() {},
"try": function() {}
},
TRY_ONE: {
Enter: function() {
return this["try"]();
},
backoff: function() {
return this.goto('BACKOFF');
},
success: function() {
return this.goto('MAX');
},
"try": function() {}
},
MAX: {
Enter: function() {
return this.bump();
},
backoff: function() {
return this.goto('BACKOFF');
},
success: function() {},
"try": function() {}
},
BACKOFF: {
Enter: function() {
return this.backoff();
},
backoff: function() {
return this.backoff();
},
success: function() {},
"try": function() {
return this.goto('TRY_ONE');
}
}
};
ReaderRdy.prototype.transitions = {
'*': {
'*': function(data, callback) {
this.log('');
return callback(data);
}
}
};
return ReaderRdy;
})(NodeState);
module.exports = {
ReaderRdy: ReaderRdy,
ConnectionRdy: ConnectionRdy
};
| {
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, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
_ = require('underscore');
EventEmitter = require('events').EventEmitter;
BackoffTimer = require('./backofftimer');
NodeState = require('node-state');
NSQDConnection = require('./nsqdconnection').NSQDConnection;
RoundRobinList = require('./roundrobinlist');
StateChangeLogger = require('./logging');
/*
Maintains the RDY and in-flight counts for a nsqd connection. ConnectionRdy
ensures that the RDY count will not exceed the max set for this connection.
The max for the connection can be adjusted at any time.
Usage:
connRdy = ConnectionRdy conn
connRdy.setConnectionRdyMax 10
conn.on 'message', ->
# On a successful message, bump up the RDY count for this connection.
connRdy.raise 'bump'
conn.on 'requeue', ->
# We're backing off when we encounter a requeue. Wait 5 seconds to try
# again.
connRdy.raise 'backoff'
setTimeout (-> connRdy.raise 'bump'), 5000
*/
ConnectionRdy = (function(_super) {
__extends(ConnectionRdy, _super);
ConnectionRdy.READY = 'ready';
ConnectionRdy.STATE_CHANGE = 'statechange';
function ConnectionRdy(conn) {
var _this = this;
this.conn = conn;
this.maxConnRdy = 0;
this.inFlight = 0;
this.lastRdySent = 0;
this.availableRdy = 0;
this.statemachine = new ConnectionRdyState(this);
this.conn.on(NSQDConnection.ERROR, function(err) {
return _this.log(err);
});
this.conn.on(NSQDConnection.MESSAGE, function() {
if (_this.idleId != null) {
clearTimeout(_this.idleId);
}
_this.idleId = null;
_this.inFlight += 1;
return _this.availableRdy -= 1;
});
this.conn.on(NSQDConnection.FINISHED, function() {
return _this.inFlight -= 1;
});
this.conn.on(NSQDConnection.REQUEUED, function() {
return _this.inFlight -= 1;
});
this.conn.on(NSQDConnection.READY, function() {
return _this.start();
});
}
ConnectionRdy.prototype.name = function() {
return String(this.conn.conn.localPort);
};
ConnectionRdy.prototype.start = function() {
this.statemachine.start();
return this.emit(ConnectionRdy.READY);
};
ConnectionRdy.prototype.setConnectionRdyMax = function(maxConnRdy) {
this.log("setConnectionRdyMax " + maxConnRdy);
this.maxConnRdy = Math.min(maxConnRdy, this.conn.maxRdyCount);
return this.statemachine.raise('adjustMax');
};
ConnectionRdy.prototype.bump = function() {
return this.statemachine.raise('bump');
};
ConnectionRdy.prototype.backoff = function() {
return this.statemachine.raise('backoff');
};
ConnectionRdy.prototype.isStarved = function() {
if (!(this.inFlight <= this.maxConnRdy)) {
throw new Error('isStarved check is failing');
}
return this.inFlight === this.lastRdySent;
};
ConnectionRdy.prototype.setRdy = function(rdyCount) {
this.log("RDY " + rdyCount);
if (rdyCount < 0 || rdyCount > this.maxConnRdy) {
return;
}
this.conn.setRdy(rdyCount);
return this.availableRdy = this.lastRdySent = rdyCount;
};
ConnectionRdy.prototype.log = function(message) {
return StateChangeLogger.log('ConnectionRdy', this.statemachine.current_state_name, this.name(), message);
};
return ConnectionRdy;
})(EventEmitter);
ConnectionRdyState = (function(_super) {
__extends(ConnectionRdyState, _super);
function ConnectionRdyState(connRdy) |
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() {},
adjustMax: function() {}
},
BACKOFF: {
Enter: function() {
return this.connRdy.setRdy(0);
},
bump: function() {
if (this.connRdy.maxConnRdy > 0) {
return this.goto('ONE');
}
},
backoff: function() {},
adjustMax: function() {}
},
ONE: {
Enter: function() {
return this.connRdy.setRdy(1);
},
bump: function() {
return this.goto('MAX');
},
backoff: function() {
return this.goto('BACKOFF');
},
adjustMax: function() {}
},
MAX: {
Enter: function() {
return this.raise('bump');
},
bump: function() {
if (this.connRdy.availableRdy <= this.connRdy.lastRdySent * 0.25) {
return this.connRdy.setRdy(this.connRdy.maxConnRdy);
}
},
backoff: function() {
return this.goto('BACKOFF');
},
adjustMax: function() {
this.log("adjustMax RDY " + this.connRdy.maxConnRdy);
return this.connRdy.setRdy(this.connRdy.maxConnRdy);
}
}
};
ConnectionRdyState.prototype.transitions = {
'*': {
'*': function(data, callback) {
this.log('');
callback(data);
return this.connRdy.emit(ConnectionRdy.STATE_CHANGE);
}
}
};
return ConnectionRdyState;
})(NodeState);
/*
Usage:
backoffTime = 90
heartbeat = 30
[topic, channel] = ['sample', 'default']
[host1, port1] = ['127.0.0.1', '4150']
c1 = new NSQDConnection host1, port1, topic, channel, backoffTime, heartbeat
readerRdy = new ReaderRdy 1, 128
readerRdy.addConnection c1
message = (msg) ->
console.log "Callback [message]: #{msg.attempts}, #{msg.body.toString()}"
if msg.attempts >= 5
msg.finish()
return
if msg.body.toString() is 'requeue'
msg.requeue()
else
msg.finish()
discard = (msg) ->
console.log "Giving up on this message: #{msg.id}"
msg.finish()
c1.on NSQDConnection.MESSAGE, message
c1.connect()
*/
READER_COUNT = 0;
ReaderRdy = (function(_super) {
__extends(ReaderRdy, _super);
ReaderRdy.getId = function() {
READER_COUNT += 1;
return READER_COUNT - 1;
};
/*
Parameters:
- maxInFlight : Maximum number of messages in-flight across all
connections.
- maxBackoffDuration : The longest amount of time (secs) for a backoff event.
- lowRdyTimeout : Time (secs) to rebalance RDY count among connections
during low RDY conditions.
*/
function ReaderRdy(maxInFlight, maxBackoffDuration, lowRdyTimeout) {
this.maxInFlight = maxInFlight;
this.maxBackoffDuration = maxBackoffDuration;
this.lowRdyTimeout = lowRdyTimeout != null ? lowRdyTimeout : 1.5;
ReaderRdy.__super__.constructor.call(this, {
autostart: true,
initial_state: 'ZERO',
sync_goto: true
});
this.id = ReaderRdy.getId();
this.backoffTimer = new BackoffTimer(0, this.maxBackoffDuration);
this.backoffId = null;
this.balanceId = null;
this.connections = [];
this.roundRobinConnections = new RoundRobinList([]);
}
ReaderRdy.prototype.close = function() {
clearTimeout(this.backoffId);
return clearTimeout(this.balanceId);
};
ReaderRdy.prototype.log = function(message) {
return StateChangeLogger.log('ReaderRdy', this.current_state_name, this.id, message);
};
ReaderRdy.prototype.isStarved = function() {
var c;
if (_.isEmpty(this.connections)) {
return false;
}
return !_.isEmpty(((function() {
var _i, _len, _ref, _results;
if (c.isStarved()) {
_ref = this.connections;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
c = _ref[_i];
_results.push(c);
}
return _results;
}
}).call(this)));
};
ReaderRdy.prototype.createConnectionRdy = function(conn) {
return new ConnectionRdy(conn);
};
ReaderRdy.prototype.isLowRdy = function() {
return this.maxInFlight < this.connections.length;
};
ReaderRdy.prototype.addConnection = function(conn) {
var connectionRdy,
_this = this;
connectionRdy = this.createConnectionRdy(conn);
conn.on(NSQDConnection.CLOSED, function() {
_this.removeConnection(connectionRdy);
return _this.balance();
});
conn.on(NSQDConnection.FINISHED, function() {
_this.backoffTimer.success();
if (_this.isLowRdy()) {
_this.balance();
} else {
connectionRdy.bump();
}
return _this.raise('success');
});
conn.on(NSQDConnection.REQUEUED, function() {
if (_this.current_state_name !== 'BACKOFF') {
return connectionRdy.bump();
}
});
conn.on(NSQDConnection.BACKOFF, function() {
return _this.raise('backoff');
});
return connectionRdy.on(ConnectionRdy.READY, function() {
var _ref;
_this.connections.push(connectionRdy);
_this.roundRobinConnections.add(connectionRdy);
_this.balance();
if (_this.current_state_name === 'ZERO') {
return _this.goto('MAX');
} else if ((_ref = _this.current_state_name) === 'TRY_ONE' || _ref === 'MAX') {
return connectionRdy.bump();
}
});
};
ReaderRdy.prototype.removeConnection = function(conn) {
this.connections.splice(this.connections.indexOf(conn), 1);
this.roundRobinConnections.remove(conn);
if (this.connections.length === 0) {
return this.goto('ZERO');
}
};
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"] = function() {
return this.balance();
};
ReaderRdy.prototype.backoff = function() {
var conn, delay, onTimeout, _i, _len, _ref,
_this = this;
this.backoffTimer.failure();
_ref = this.connections;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
conn = _ref[_i];
conn.backoff();
}
if (this.backoffId) {
clearTimeout(this.backoffId);
}
onTimeout = function() {
return _this.raise('try');
};
delay = new Number(this.backoffTimer.getInterval().valueOf()) * 1000;
return this.backoffId = setTimeout(onTimeout, delay);
};
ReaderRdy.prototype.inFlight = function() {
var add;
add = function(previous, conn) {
return previous + conn.inFlight;
};
return this.connections.reduce(add, 0);
};
/*
Evenly or fairly distributes RDY count based on the maxInFlight across
all nsqd connections.
*/
ReaderRdy.prototype.balance = function() {
/*
In the perverse situation where there are more connections than max in
flight, we do the following:
There is a sliding window where each of the connections gets a RDY count
of 1. When the connection has processed it's single message, then the RDY
count is distributed to the next waiting connection. If the connection
does nothing with it's RDY count, then it should timeout and give it's
RDY count to another connection.
*/
var c, connMax, i, max, perConnectionMax, rdyRemainder, _i, _j, _k, _len, _len1, _ref, _ref1, _ref2, _results;
StateChangeLogger.log('ReaderRdy', this.current_state_name, this.id, 'balance');
if (this.balanceId != null) {
clearTimeout(this.balanceId);
this.balanceId = null;
}
max = this.current_state_name === 'TRY_ONE' ? 1 : this.maxInFlight;
perConnectionMax = Math.floor(max / this.connections.length);
if (perConnectionMax === 0) {
_ref = this.connections;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
c = _ref[_i];
c.backoff();
}
_ref1 = this.roundRobinConnections.next(max - this.inFlight());
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
c = _ref1[_j];
c.setConnectionRdyMax(1);
c.bump();
}
return this.balanceId = setTimeout(this.balance.bind(this), this.lowRdyTimeout * 1000);
} else {
rdyRemainder = this.maxInFlight % this.connectionsLength;
_results = [];
for (i = _k = 0, _ref2 = this.connections.length; 0 <= _ref2 ? _k < _ref2 : _k > _ref2; i = 0 <= _ref2 ? ++_k : --_k) {
connMax = perConnectionMax;
if (rdyRemainder > 0) {
connMax += 1;
rdyRemainder -= 1;
}
this.connections[i].setConnectionRdyMax(connMax);
_results.push(this.connections[i].bump());
}
return _results;
}
};
/*
The following events results in transitions in the ReaderRdy state machine:
1. Adding the first connection
2. Remove the last connections
3. Finish event from message handling
4. Backoff event from message handling
5. Backoff timeout
*/
ReaderRdy.prototype.states = {
ZERO: {
Enter: function() {
if (this.backoffId) {
return clearTimeout(this.backoffId);
}
},
backoff: function() {},
success: function() {},
"try": function() {}
},
TRY_ONE: {
Enter: function() {
return this["try"]();
},
backoff: function() {
return this.goto('BACKOFF');
},
success: function() {
return this.goto('MAX');
},
"try": function() {}
},
MAX: {
Enter: function() {
return this.bump();
},
backoff: function() {
return this.goto('BACKOFF');
},
success: function() {},
"try": function() {}
},
BACKOFF: {
Enter: function() {
return this.backoff();
},
backoff: function() {
return this.backoff();
},
success: function() {},
"try": function() {
return this.goto('TRY_ONE');
}
}
};
ReaderRdy.prototype.transitions = {
'*': {
'*': function(data, callback) {
this.log('');
return callback(data);
}
}
};
return ReaderRdy;
})(NodeState);
module.exports = {
ReaderRdy: ReaderRdy,
ConnectionRdy: ConnectionRdy
};
| {
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, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
_ = require('underscore');
EventEmitter = require('events').EventEmitter;
BackoffTimer = require('./backofftimer');
NodeState = require('node-state');
NSQDConnection = require('./nsqdconnection').NSQDConnection;
RoundRobinList = require('./roundrobinlist');
StateChangeLogger = require('./logging');
/*
Maintains the RDY and in-flight counts for a nsqd connection. ConnectionRdy
ensures that the RDY count will not exceed the max set for this connection.
The max for the connection can be adjusted at any time.
Usage:
connRdy = ConnectionRdy conn
connRdy.setConnectionRdyMax 10
conn.on 'message', ->
# On a successful message, bump up the RDY count for this connection.
connRdy.raise 'bump'
conn.on 'requeue', ->
# We're backing off when we encounter a requeue. Wait 5 seconds to try
# again.
connRdy.raise 'backoff'
setTimeout (-> connRdy.raise 'bump'), 5000
*/
ConnectionRdy = (function(_super) {
__extends(ConnectionRdy, _super);
ConnectionRdy.READY = 'ready';
ConnectionRdy.STATE_CHANGE = 'statechange';
function ConnectionRdy(conn) {
var _this = this;
this.conn = conn;
this.maxConnRdy = 0;
this.inFlight = 0;
this.lastRdySent = 0;
this.availableRdy = 0;
this.statemachine = new ConnectionRdyState(this);
this.conn.on(NSQDConnection.ERROR, function(err) {
return _this.log(err);
});
this.conn.on(NSQDConnection.MESSAGE, function() {
if (_this.idleId != null) {
clearTimeout(_this.idleId);
}
_this.idleId = null;
_this.inFlight += 1;
return _this.availableRdy -= 1;
});
this.conn.on(NSQDConnection.FINISHED, function() {
return _this.inFlight -= 1;
});
this.conn.on(NSQDConnection.REQUEUED, function() {
return _this.inFlight -= 1;
});
this.conn.on(NSQDConnection.READY, function() {
return _this.start();
});
}
ConnectionRdy.prototype.name = function() {
return String(this.conn.conn.localPort);
};
ConnectionRdy.prototype.start = function() {
this.statemachine.start();
return this.emit(ConnectionRdy.READY);
};
ConnectionRdy.prototype.setConnectionRdyMax = function(maxConnRdy) {
this.log("setConnectionRdyMax " + maxConnRdy);
this.maxConnRdy = Math.min(maxConnRdy, this.conn.maxRdyCount);
return this.statemachine.raise('adjustMax');
};
ConnectionRdy.prototype.bump = function() {
return this.statemachine.raise('bump');
};
ConnectionRdy.prototype.backoff = function() {
return this.statemachine.raise('backoff');
};
ConnectionRdy.prototype.isStarved = function() {
if (!(this.inFlight <= this.maxConnRdy)) {
throw new Error('isStarved check is failing');
}
return this.inFlight === this.lastRdySent;
};
ConnectionRdy.prototype.setRdy = function(rdyCount) {
this.log("RDY " + rdyCount);
if (rdyCount < 0 || rdyCount > this.maxConnRdy) {
return;
}
this.conn.setRdy(rdyCount);
return this.availableRdy = this.lastRdySent = rdyCount;
};
ConnectionRdy.prototype.log = function(message) {
return StateChangeLogger.log('ConnectionRdy', this.statemachine.current_state_name, this.name(), message);
};
return ConnectionRdy;
})(EventEmitter);
ConnectionRdyState = (function(_super) {
__extends(ConnectionRdyState, _super);
function | (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.states = {
INIT: {
bump: function() {
if (this.connRdy.maxConnRdy > 0) {
return this.goto('MAX');
}
},
backoff: function() {},
adjustMax: function() {}
},
BACKOFF: {
Enter: function() {
return this.connRdy.setRdy(0);
},
bump: function() {
if (this.connRdy.maxConnRdy > 0) {
return this.goto('ONE');
}
},
backoff: function() {},
adjustMax: function() {}
},
ONE: {
Enter: function() {
return this.connRdy.setRdy(1);
},
bump: function() {
return this.goto('MAX');
},
backoff: function() {
return this.goto('BACKOFF');
},
adjustMax: function() {}
},
MAX: {
Enter: function() {
return this.raise('bump');
},
bump: function() {
if (this.connRdy.availableRdy <= this.connRdy.lastRdySent * 0.25) {
return this.connRdy.setRdy(this.connRdy.maxConnRdy);
}
},
backoff: function() {
return this.goto('BACKOFF');
},
adjustMax: function() {
this.log("adjustMax RDY " + this.connRdy.maxConnRdy);
return this.connRdy.setRdy(this.connRdy.maxConnRdy);
}
}
};
ConnectionRdyState.prototype.transitions = {
'*': {
'*': function(data, callback) {
this.log('');
callback(data);
return this.connRdy.emit(ConnectionRdy.STATE_CHANGE);
}
}
};
return ConnectionRdyState;
})(NodeState);
/*
Usage:
backoffTime = 90
heartbeat = 30
[topic, channel] = ['sample', 'default']
[host1, port1] = ['127.0.0.1', '4150']
c1 = new NSQDConnection host1, port1, topic, channel, backoffTime, heartbeat
readerRdy = new ReaderRdy 1, 128
readerRdy.addConnection c1
message = (msg) ->
console.log "Callback [message]: #{msg.attempts}, #{msg.body.toString()}"
if msg.attempts >= 5
msg.finish()
return
if msg.body.toString() is 'requeue'
msg.requeue()
else
msg.finish()
discard = (msg) ->
console.log "Giving up on this message: #{msg.id}"
msg.finish()
c1.on NSQDConnection.MESSAGE, message
c1.connect()
*/
READER_COUNT = 0;
ReaderRdy = (function(_super) {
__extends(ReaderRdy, _super);
ReaderRdy.getId = function() {
READER_COUNT += 1;
return READER_COUNT - 1;
};
/*
Parameters:
- maxInFlight : Maximum number of messages in-flight across all
connections.
- maxBackoffDuration : The longest amount of time (secs) for a backoff event.
- lowRdyTimeout : Time (secs) to rebalance RDY count among connections
during low RDY conditions.
*/
function ReaderRdy(maxInFlight, maxBackoffDuration, lowRdyTimeout) {
this.maxInFlight = maxInFlight;
this.maxBackoffDuration = maxBackoffDuration;
this.lowRdyTimeout = lowRdyTimeout != null ? lowRdyTimeout : 1.5;
ReaderRdy.__super__.constructor.call(this, {
autostart: true,
initial_state: 'ZERO',
sync_goto: true
});
this.id = ReaderRdy.getId();
this.backoffTimer = new BackoffTimer(0, this.maxBackoffDuration);
this.backoffId = null;
this.balanceId = null;
this.connections = [];
this.roundRobinConnections = new RoundRobinList([]);
}
ReaderRdy.prototype.close = function() {
clearTimeout(this.backoffId);
return clearTimeout(this.balanceId);
};
ReaderRdy.prototype.log = function(message) {
return StateChangeLogger.log('ReaderRdy', this.current_state_name, this.id, message);
};
ReaderRdy.prototype.isStarved = function() {
var c;
if (_.isEmpty(this.connections)) {
return false;
}
return !_.isEmpty(((function() {
var _i, _len, _ref, _results;
if (c.isStarved()) {
_ref = this.connections;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
c = _ref[_i];
_results.push(c);
}
return _results;
}
}).call(this)));
};
ReaderRdy.prototype.createConnectionRdy = function(conn) {
return new ConnectionRdy(conn);
};
ReaderRdy.prototype.isLowRdy = function() {
return this.maxInFlight < this.connections.length;
};
ReaderRdy.prototype.addConnection = function(conn) {
var connectionRdy,
_this = this;
connectionRdy = this.createConnectionRdy(conn);
conn.on(NSQDConnection.CLOSED, function() {
_this.removeConnection(connectionRdy);
return _this.balance();
});
conn.on(NSQDConnection.FINISHED, function() {
_this.backoffTimer.success();
if (_this.isLowRdy()) {
_this.balance();
} else {
connectionRdy.bump();
}
return _this.raise('success');
});
conn.on(NSQDConnection.REQUEUED, function() {
if (_this.current_state_name !== 'BACKOFF') {
return connectionRdy.bump();
}
});
conn.on(NSQDConnection.BACKOFF, function() {
return _this.raise('backoff');
});
return connectionRdy.on(ConnectionRdy.READY, function() {
var _ref;
_this.connections.push(connectionRdy);
_this.roundRobinConnections.add(connectionRdy);
_this.balance();
if (_this.current_state_name === 'ZERO') {
return _this.goto('MAX');
} else if ((_ref = _this.current_state_name) === 'TRY_ONE' || _ref === 'MAX') {
return connectionRdy.bump();
}
});
};
ReaderRdy.prototype.removeConnection = function(conn) {
this.connections.splice(this.connections.indexOf(conn), 1);
this.roundRobinConnections.remove(conn);
if (this.connections.length === 0) {
return this.goto('ZERO');
}
};
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"] = function() {
return this.balance();
};
ReaderRdy.prototype.backoff = function() {
var conn, delay, onTimeout, _i, _len, _ref,
_this = this;
this.backoffTimer.failure();
_ref = this.connections;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
conn = _ref[_i];
conn.backoff();
}
if (this.backoffId) {
clearTimeout(this.backoffId);
}
onTimeout = function() {
return _this.raise('try');
};
delay = new Number(this.backoffTimer.getInterval().valueOf()) * 1000;
return this.backoffId = setTimeout(onTimeout, delay);
};
ReaderRdy.prototype.inFlight = function() {
var add;
add = function(previous, conn) {
return previous + conn.inFlight;
};
return this.connections.reduce(add, 0);
};
/*
Evenly or fairly distributes RDY count based on the maxInFlight across
all nsqd connections.
*/
ReaderRdy.prototype.balance = function() {
/*
In the perverse situation where there are more connections than max in
flight, we do the following:
There is a sliding window where each of the connections gets a RDY count
of 1. When the connection has processed it's single message, then the RDY
count is distributed to the next waiting connection. If the connection
does nothing with it's RDY count, then it should timeout and give it's
RDY count to another connection.
*/
var c, connMax, i, max, perConnectionMax, rdyRemainder, _i, _j, _k, _len, _len1, _ref, _ref1, _ref2, _results;
StateChangeLogger.log('ReaderRdy', this.current_state_name, this.id, 'balance');
if (this.balanceId != null) {
clearTimeout(this.balanceId);
this.balanceId = null;
}
max = this.current_state_name === 'TRY_ONE' ? 1 : this.maxInFlight;
perConnectionMax = Math.floor(max / this.connections.length);
if (perConnectionMax === 0) {
_ref = this.connections;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
c = _ref[_i];
c.backoff();
}
_ref1 = this.roundRobinConnections.next(max - this.inFlight());
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
c = _ref1[_j];
c.setConnectionRdyMax(1);
c.bump();
}
return this.balanceId = setTimeout(this.balance.bind(this), this.lowRdyTimeout * 1000);
} else {
rdyRemainder = this.maxInFlight % this.connectionsLength;
_results = [];
for (i = _k = 0, _ref2 = this.connections.length; 0 <= _ref2 ? _k < _ref2 : _k > _ref2; i = 0 <= _ref2 ? ++_k : --_k) {
connMax = perConnectionMax;
if (rdyRemainder > 0) {
connMax += 1;
rdyRemainder -= 1;
}
this.connections[i].setConnectionRdyMax(connMax);
_results.push(this.connections[i].bump());
}
return _results;
}
};
/*
The following events results in transitions in the ReaderRdy state machine:
1. Adding the first connection
2. Remove the last connections
3. Finish event from message handling
4. Backoff event from message handling
5. Backoff timeout
*/
ReaderRdy.prototype.states = {
ZERO: {
Enter: function() {
if (this.backoffId) {
return clearTimeout(this.backoffId);
}
},
backoff: function() {},
success: function() {},
"try": function() {}
},
TRY_ONE: {
Enter: function() {
return this["try"]();
},
backoff: function() {
return this.goto('BACKOFF');
},
success: function() {
return this.goto('MAX');
},
"try": function() {}
},
MAX: {
Enter: function() {
return this.bump();
},
backoff: function() {
return this.goto('BACKOFF');
},
success: function() {},
"try": function() {}
},
BACKOFF: {
Enter: function() {
return this.backoff();
},
backoff: function() {
return this.backoff();
},
success: function() {},
"try": function() {
return this.goto('TRY_ONE');
}
}
};
ReaderRdy.prototype.transitions = {
'*': {
'*': function(data, callback) {
this.log('');
return callback(data);
}
}
};
return ReaderRdy;
})(NodeState);
module.exports = {
ReaderRdy: ReaderRdy,
ConnectionRdy: ConnectionRdy
};
| 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, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
_ = require('underscore');
EventEmitter = require('events').EventEmitter;
BackoffTimer = require('./backofftimer');
NodeState = require('node-state');
NSQDConnection = require('./nsqdconnection').NSQDConnection;
RoundRobinList = require('./roundrobinlist');
StateChangeLogger = require('./logging');
/*
Maintains the RDY and in-flight counts for a nsqd connection. ConnectionRdy
ensures that the RDY count will not exceed the max set for this connection.
The max for the connection can be adjusted at any time.
Usage:
connRdy = ConnectionRdy conn
connRdy.setConnectionRdyMax 10
conn.on 'message', ->
# On a successful message, bump up the RDY count for this connection.
connRdy.raise 'bump'
conn.on 'requeue', ->
# We're backing off when we encounter a requeue. Wait 5 seconds to try
# again.
connRdy.raise 'backoff'
setTimeout (-> connRdy.raise 'bump'), 5000
*/
ConnectionRdy = (function(_super) {
__extends(ConnectionRdy, _super);
ConnectionRdy.READY = 'ready';
ConnectionRdy.STATE_CHANGE = 'statechange';
function ConnectionRdy(conn) {
var _this = this;
this.conn = conn;
this.maxConnRdy = 0;
this.inFlight = 0;
this.lastRdySent = 0;
this.availableRdy = 0;
this.statemachine = new ConnectionRdyState(this);
this.conn.on(NSQDConnection.ERROR, function(err) {
return _this.log(err);
});
this.conn.on(NSQDConnection.MESSAGE, function() {
if (_this.idleId != null) {
clearTimeout(_this.idleId);
}
_this.idleId = null;
_this.inFlight += 1;
return _this.availableRdy -= 1;
});
this.conn.on(NSQDConnection.FINISHED, function() {
return _this.inFlight -= 1;
});
this.conn.on(NSQDConnection.REQUEUED, function() {
return _this.inFlight -= 1;
});
this.conn.on(NSQDConnection.READY, function() {
return _this.start();
});
}
ConnectionRdy.prototype.name = function() {
return String(this.conn.conn.localPort);
};
ConnectionRdy.prototype.start = function() {
this.statemachine.start();
return this.emit(ConnectionRdy.READY);
};
ConnectionRdy.prototype.setConnectionRdyMax = function(maxConnRdy) {
this.log("setConnectionRdyMax " + maxConnRdy);
this.maxConnRdy = Math.min(maxConnRdy, this.conn.maxRdyCount);
return this.statemachine.raise('adjustMax');
};
ConnectionRdy.prototype.bump = function() {
return this.statemachine.raise('bump');
};
ConnectionRdy.prototype.backoff = function() {
return this.statemachine.raise('backoff');
};
ConnectionRdy.prototype.isStarved = function() {
if (!(this.inFlight <= this.maxConnRdy)) {
throw new Error('isStarved check is failing');
}
return this.inFlight === this.lastRdySent;
};
ConnectionRdy.prototype.setRdy = function(rdyCount) {
this.log("RDY " + rdyCount);
if (rdyCount < 0 || rdyCount > this.maxConnRdy) {
return;
}
this.conn.setRdy(rdyCount);
return this.availableRdy = this.lastRdySent = rdyCount;
};
ConnectionRdy.prototype.log = function(message) {
return StateChangeLogger.log('ConnectionRdy', this.statemachine.current_state_name, this.name(), message);
};
return ConnectionRdy;
})(EventEmitter);
ConnectionRdyState = (function(_super) {
__extends(ConnectionRdyState, _super);
function ConnectionRdyState(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.states = {
INIT: {
bump: function() {
if (this.connRdy.maxConnRdy > 0) {
return this.goto('MAX');
}
},
backoff: function() {},
adjustMax: function() {}
},
BACKOFF: {
Enter: function() {
return this.connRdy.setRdy(0);
},
bump: function() {
if (this.connRdy.maxConnRdy > 0) {
return this.goto('ONE');
}
},
backoff: function() {},
adjustMax: function() {}
},
ONE: {
Enter: function() {
return this.connRdy.setRdy(1);
},
bump: function() {
return this.goto('MAX');
},
backoff: function() {
return this.goto('BACKOFF');
},
adjustMax: function() {}
},
MAX: {
Enter: function() {
return this.raise('bump');
},
bump: function() {
if (this.connRdy.availableRdy <= this.connRdy.lastRdySent * 0.25) {
return this.connRdy.setRdy(this.connRdy.maxConnRdy);
}
},
backoff: function() {
return this.goto('BACKOFF');
},
adjustMax: function() {
this.log("adjustMax RDY " + this.connRdy.maxConnRdy);
return this.connRdy.setRdy(this.connRdy.maxConnRdy);
}
}
};
ConnectionRdyState.prototype.transitions = {
'*': {
'*': function(data, callback) {
this.log('');
callback(data);
return this.connRdy.emit(ConnectionRdy.STATE_CHANGE);
}
}
};
return ConnectionRdyState;
})(NodeState);
/*
Usage:
backoffTime = 90
heartbeat = 30
[topic, channel] = ['sample', 'default']
[host1, port1] = ['127.0.0.1', '4150']
c1 = new NSQDConnection host1, port1, topic, channel, backoffTime, heartbeat
readerRdy = new ReaderRdy 1, 128
readerRdy.addConnection c1
message = (msg) ->
console.log "Callback [message]: #{msg.attempts}, #{msg.body.toString()}"
if msg.attempts >= 5
msg.finish()
return
if msg.body.toString() is 'requeue'
msg.requeue()
else
msg.finish()
discard = (msg) ->
console.log "Giving up on this message: #{msg.id}"
msg.finish()
c1.on NSQDConnection.MESSAGE, message
c1.connect()
*/
READER_COUNT = 0;
ReaderRdy = (function(_super) {
__extends(ReaderRdy, _super);
ReaderRdy.getId = function() {
READER_COUNT += 1;
return READER_COUNT - 1;
};
/*
Parameters:
- maxInFlight : Maximum number of messages in-flight across all
connections.
- maxBackoffDuration : The longest amount of time (secs) for a backoff event.
- lowRdyTimeout : Time (secs) to rebalance RDY count among connections
during low RDY conditions.
*/
function ReaderRdy(maxInFlight, maxBackoffDuration, lowRdyTimeout) {
this.maxInFlight = maxInFlight;
this.maxBackoffDuration = maxBackoffDuration;
this.lowRdyTimeout = lowRdyTimeout != null ? lowRdyTimeout : 1.5;
ReaderRdy.__super__.constructor.call(this, {
autostart: true,
initial_state: 'ZERO',
sync_goto: true
});
this.id = ReaderRdy.getId();
this.backoffTimer = new BackoffTimer(0, this.maxBackoffDuration);
this.backoffId = null;
this.balanceId = null;
this.connections = [];
this.roundRobinConnections = new RoundRobinList([]);
}
ReaderRdy.prototype.close = function() {
clearTimeout(this.backoffId);
return clearTimeout(this.balanceId);
};
ReaderRdy.prototype.log = function(message) {
return StateChangeLogger.log('ReaderRdy', this.current_state_name, this.id, message);
};
ReaderRdy.prototype.isStarved = function() {
var c;
if (_.isEmpty(this.connections)) {
return false;
}
return !_.isEmpty(((function() {
var _i, _len, _ref, _results;
if (c.isStarved()) {
_ref = this.connections;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
c = _ref[_i];
_results.push(c);
}
return _results;
}
}).call(this)));
};
ReaderRdy.prototype.createConnectionRdy = function(conn) {
return new ConnectionRdy(conn);
};
ReaderRdy.prototype.isLowRdy = function() {
return this.maxInFlight < this.connections.length;
};
ReaderRdy.prototype.addConnection = function(conn) {
var connectionRdy,
_this = this;
connectionRdy = this.createConnectionRdy(conn);
conn.on(NSQDConnection.CLOSED, function() {
_this.removeConnection(connectionRdy);
return _this.balance();
});
conn.on(NSQDConnection.FINISHED, function() {
_this.backoffTimer.success();
if (_this.isLowRdy()) {
_this.balance();
} else {
connectionRdy.bump();
}
return _this.raise('success');
});
conn.on(NSQDConnection.REQUEUED, function() {
if (_this.current_state_name !== 'BACKOFF') {
return connectionRdy.bump();
}
});
conn.on(NSQDConnection.BACKOFF, function() {
return _this.raise('backoff');
});
return connectionRdy.on(ConnectionRdy.READY, function() {
var _ref;
_this.connections.push(connectionRdy);
_this.roundRobinConnections.add(connectionRdy);
_this.balance();
if (_this.current_state_name === 'ZERO') {
return _this.goto('MAX');
} else if ((_ref = _this.current_state_name) === 'TRY_ONE' || _ref === 'MAX') {
return connectionRdy.bump();
}
});
};
ReaderRdy.prototype.removeConnection = function(conn) {
this.connections.splice(this.connections.indexOf(conn), 1);
this.roundRobinConnections.remove(conn);
if (this.connections.length === 0) {
return this.goto('ZERO');
}
};
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"] = function() {
return this.balance();
};
ReaderRdy.prototype.backoff = function() {
var conn, delay, onTimeout, _i, _len, _ref,
_this = this;
this.backoffTimer.failure();
_ref = this.connections;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
conn = _ref[_i];
conn.backoff();
}
if (this.backoffId) {
clearTimeout(this.backoffId);
}
onTimeout = function() {
return _this.raise('try');
};
delay = new Number(this.backoffTimer.getInterval().valueOf()) * 1000;
return this.backoffId = setTimeout(onTimeout, delay);
};
ReaderRdy.prototype.inFlight = function() {
var add;
add = function(previous, conn) {
return previous + conn.inFlight;
};
return this.connections.reduce(add, 0);
};
/*
Evenly or fairly distributes RDY count based on the maxInFlight across
all nsqd connections.
*/
ReaderRdy.prototype.balance = function() {
/*
In the perverse situation where there are more connections than max in
flight, we do the following:
There is a sliding window where each of the connections gets a RDY count
of 1. When the connection has processed it's single message, then the RDY
count is distributed to the next waiting connection. If the connection
does nothing with it's RDY count, then it should timeout and give it's
RDY count to another connection.
*/
var c, connMax, i, max, perConnectionMax, rdyRemainder, _i, _j, _k, _len, _len1, _ref, _ref1, _ref2, _results;
StateChangeLogger.log('ReaderRdy', this.current_state_name, this.id, 'balance');
if (this.balanceId != null) {
clearTimeout(this.balanceId);
this.balanceId = null;
}
max = this.current_state_name === 'TRY_ONE' ? 1 : this.maxInFlight;
perConnectionMax = Math.floor(max / this.connections.length);
if (perConnectionMax === 0) {
_ref = this.connections;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
c = _ref[_i];
c.backoff();
}
_ref1 = this.roundRobinConnections.next(max - this.inFlight());
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
c = _ref1[_j];
c.setConnectionRdyMax(1);
c.bump();
}
return this.balanceId = setTimeout(this.balance.bind(this), this.lowRdyTimeout * 1000);
} else {
rdyRemainder = this.maxInFlight % this.connectionsLength;
_results = [];
for (i = _k = 0, _ref2 = this.connections.length; 0 <= _ref2 ? _k < _ref2 : _k > _ref2; i = 0 <= _ref2 ? ++_k : --_k) {
connMax = perConnectionMax;
if (rdyRemainder > 0) {
connMax += 1;
rdyRemainder -= 1;
}
this.connections[i].setConnectionRdyMax(connMax);
_results.push(this.connections[i].bump());
}
return _results;
}
};
/*
The following events results in transitions in the ReaderRdy state machine:
1. Adding the first connection
2. Remove the last connections
3. Finish event from message handling
4. Backoff event from message handling
5. Backoff timeout
*/
ReaderRdy.prototype.states = {
ZERO: {
Enter: function() {
if (this.backoffId) {
return clearTimeout(this.backoffId);
}
},
backoff: function() {},
success: function() {},
"try": function() {}
},
TRY_ONE: {
Enter: function() {
return this["try"]();
},
backoff: function() {
return this.goto('BACKOFF');
},
success: function() {
return this.goto('MAX');
},
"try": function() {}
},
MAX: {
Enter: function() {
return this.bump();
},
backoff: function() {
return this.goto('BACKOFF');
},
success: function() {},
"try": function() {}
},
BACKOFF: {
Enter: function() {
return this.backoff();
},
backoff: function() {
return this.backoff();
},
success: function() {},
"try": function() {
return this.goto('TRY_ONE');
}
}
};
ReaderRdy.prototype.transitions = {
'*': {
'*': function(data, callback) {
this.log('');
return callback(data);
}
}
};
return ReaderRdy;
})(NodeState);
module.exports = {
ReaderRdy: ReaderRdy,
ConnectionRdy: ConnectionRdy
}; | 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
this.winning_array = []; // Winning (chips) array
this.iterations = 0; // Iteration count
that = this;
that.init();
}
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_board[i][j] = null;
}
}
// Create from board object (see board.js)
this.board = new Board(this, game_board, 0);
// Generate visual board
var game_board = "<col/><col/><col/><col/><col/><col/><col/>";
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 td = document.getElementById('game_board').getElementsByTagName("td");
for (var i = 0; i < td.length; i++) |
}
/**
* 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);
}
}
}
/**
* Place coin
*/
Game.prototype.place = function(column) {
// If not finished
if (that.board.score() != that.score && that.board.score() != -that.score && !that.board.isFull()) {
for (var y = that.rows - 1; y >= 0; y--) {
if (document.getElementById('game_board').rows[y].cells[column].className == 'empty') {
if (that.round == 1) {
var coin_x = column * 51;
var coin_y = y * 51;
$('#coin').attr('class', 'cpu-coin').css({'left': coin_x}).fadeIn('fast').animate({'top': coin_y + 'px'}, 700, 'easeOutBounce', function() {
document.getElementById('game_board').rows[y].cells[column].className = 'coin cpu-coin';
$('#coin').hide().css({'top': '0px'});
if (!that.board.place(column)) {
return alert("Invalid move!");
}
that.round = that.switchRound(that.round);
that.updateStatus();
});
} else {
var coin_x = column * 51;
var coin_y = y * 51;
$('#coin').attr('class', 'human-coin').css({'left': coin_x}).fadeIn('fast').animate({'top': coin_y + 'px'}, 700, 'easeOutBounce', function() {
document.getElementById('game_board').rows[y].cells[column].className = 'coin human-coin';
$('#coin').hide().css({'top': '0px'});
that.generateComputerDecision();
if (!that.board.place(column)) {
return alert("Invalid move!");
}
that.round = that.switchRound(that.round);
that.updateStatus();
});
}
break;
}
}
}
}
Game.prototype.generateComputerDecision = function() {
if (that.board.score() != that.score && that.board.score() != -that.score && !that.board.isFull()) {
that.iterations = 0; // Reset iteration count
document.getElementById('loading').style.display = "block"; // Loading message
// AI is thinking
setTimeout(function() {
// Debug time
var startzeit = new Date().getTime();
// Algorithm call
var ai_move = that.maximizePlay(that.board, that.depth);
var laufzeit = new Date().getTime() - startzeit;
document.getElementById('ai-time').innerHTML = laufzeit.toFixed(2) + 'ms';
// Place ai decision
that.place(ai_move[0]);
// Debug
document.getElementById('ai-column').innerHTML = 'Column: ' + parseInt(ai_move[0] + 1);
document.getElementById('ai-score').innerHTML = 'Score: ' + ai_move[1];
document.getElementById('ai-iterations').innerHTML = that.iterations;
document.getElementById('loading').style.display = "none"; // Remove loading message
}, 100);
}
}
/**
* Algorithm
* Minimax principle
*/
Game.prototype.maximizePlay = function(board, depth) {
// Call score of our board
var score = board.score();
// Break
if (board.isFinished(depth, score)) return [null, score];
// Column, Score
var max = [null, -99999];
// For all possible moves
for (var column = 0; column < that.columns; column++) {
var new_board = board.copy(); // Create new board
if (new_board.place(column)) {
that.iterations++; // Debug
var next_move = that.minimizePlay(new_board, depth - 1); // Recursive calling
// Evaluate new move
if (max[0] == null || next_move[1] > max[1]) {
max[0] = column;
max[1] = next_move[1];
}
}
}
return max;
}
Game.prototype.minimizePlay = function(board, depth) {
var score = board.score();
if (board.isFinished(depth, score)) return [null, score];
// Column, score
var min = [null, 99999];
for (var column = 0; column < that.columns; column++) {
var new_board = board.copy();
if (new_board.place(column)) {
that.iterations++;
var next_move = that.maximizePlay(new_board, depth - 1);
if (min[0] == null || next_move[1] < min[1]) {
min[0] = column;
min[1] = next_move[1];
}
}
}
return min;
}
Game.prototype.switchRound = function(round) {
// 0 Human, 1 Computer
if (round == 0) {
return 1;
} else {
return 0;
}
}
Game.prototype.updateStatus = function() {
// Human won
if (that.board.score() == -that.score) {
that.status = 1;
that.markWin();
alert("You have won!");
}
// Computer won
if (that.board.score() == that.score) {
that.status = 2;
that.markWin();
alert("You have lost!");
}
// Tie
if (that.board.isFull()) {
that.status = 3;
alert("Tie!");
}
var html = document.getElementById('status');
if (that.status == 0) {
html.className = "status-running";
html.innerHTML = "running";
} else if (that.status == 1) {
html.className = "status-won";
html.innerHTML = "won";
} else if (that.status == 2) {
html.className = "status-lost";
html.innerHTML = "lost";
} else {
html.className = "status-tie";
html.innerHTML = "tie";
}
}
Game.prototype.markWin = function() {
for (var i = 0; i < that.winning_array.length; i++) {
var name = document.getElementById('game_board').rows[that.winning_array[i][0]].cells[that.winning_array[i][1]].className;
document.getElementById('game_board').rows[that.winning_array[i][0]].cells[that.winning_array[i][1]].className = name + " win";
}
}
Game.prototype.restartGame = function() {
if (confirm('Game is going to be restarted.\nAre you sure?')) {
// Dropdown value
var difficulty = document.getElementById('difficulty');
var depth = difficulty.options[difficulty.selectedIndex].value;
that.depth = depth;
that.status = 0;
that.round = 0;
that.init();
document.getElementById('ai-iterations').innerHTML = "?";
document.getElementById('ai-time').innerHTML = "?";
document.getElementById('ai-column').innerHTML = "Column: ?";
document.getElementById('ai-score').innerHTML = "Score: ?";
document.getElementById('game_board').className = "";
that.updateStatus();
// Re-assign hover
$('td').hover(function() {
$(this).parents('table').find('col:eq('+$(this).index()+')').toggleClass('hover');
});
}
}
/**
* Start game
*/
function Start() {
window.Game = new Game();
// Hover background, now using jQuery
$('td').hover(function() {
$(this).parents('table').find('col:eq('+$(this).index()+')').toggleClass('hover');
});
}
window.onload = function() {
Start()
};
| {
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_board[i][j] = null;
}
}
// Create from board object (see board.js)
this.board = new Board(this, game_board, 0);
// Generate visual board
var game_board = "<col/><col/><col/><col/><col/><col/><col/>";
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 td = document.getElementById('game_board').getElementsByTagName("td");
for (var i = 0; i < td.length; i++) {
if (td[i].addEventListener) {
td[i].addEventListener('click', that.act, false);
} else if (td[i].attachEvent) {
td[i].attachEvent('click', that.act)
}
}
}
/**
* 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);
}
}
}
/**
* Place coin
*/
Game.prototype.place = function(column) {
// If not finished
if (that.board.score() != that.score && that.board.score() != -that.score && !that.board.isFull()) {
for (var y = that.rows - 1; y >= 0; y--) {
if (document.getElementById('game_board').rows[y].cells[column].className == 'empty') {
if (that.round == 1) {
var coin_x = column * 51;
var coin_y = y * 51;
$('#coin').attr('class', 'cpu-coin').css({'left': coin_x}).fadeIn('fast').animate({'top': coin_y + 'px'}, 700, 'easeOutBounce', function() {
document.getElementById('game_board').rows[y].cells[column].className = 'coin cpu-coin';
$('#coin').hide().css({'top': '0px'});
if (!that.board.place(column)) {
return alert("Invalid move!");
}
that.round = that.switchRound(that.round);
that.updateStatus();
});
} else {
var coin_x = column * 51;
var coin_y = y * 51;
$('#coin').attr('class', 'human-coin').css({'left': coin_x}).fadeIn('fast').animate({'top': coin_y + 'px'}, 700, 'easeOutBounce', function() {
document.getElementById('game_board').rows[y].cells[column].className = 'coin human-coin';
$('#coin').hide().css({'top': '0px'});
that.generateComputerDecision();
if (!that.board.place(column)) {
return alert("Invalid move!");
}
that.round = that.switchRound(that.round);
that.updateStatus();
});
}
break;
}
}
}
}
Game.prototype.generateComputerDecision = function() {
if (that.board.score() != that.score && that.board.score() != -that.score && !that.board.isFull()) {
that.iterations = 0; // Reset iteration count
document.getElementById('loading').style.display = "block"; // Loading message
// AI is thinking
setTimeout(function() {
// Debug time
var startzeit = new Date().getTime();
// Algorithm call
var ai_move = that.maximizePlay(that.board, that.depth);
var laufzeit = new Date().getTime() - startzeit;
document.getElementById('ai-time').innerHTML = laufzeit.toFixed(2) + 'ms';
// Place ai decision
that.place(ai_move[0]);
// Debug
document.getElementById('ai-column').innerHTML = 'Column: ' + parseInt(ai_move[0] + 1);
document.getElementById('ai-score').innerHTML = 'Score: ' + ai_move[1];
document.getElementById('ai-iterations').innerHTML = that.iterations;
document.getElementById('loading').style.display = "none"; // Remove loading message
}, 100);
}
}
/**
* Algorithm
* Minimax principle
*/
Game.prototype.maximizePlay = function(board, depth) {
// Call score of our board
var score = board.score();
// Break
if (board.isFinished(depth, score)) return [null, score];
// Column, Score
var max = [null, -99999];
// For all possible moves
for (var column = 0; column < that.columns; column++) {
var new_board = board.copy(); // Create new board
if (new_board.place(column)) {
that.iterations++; // Debug
var next_move = that.minimizePlay(new_board, depth - 1); // Recursive calling
// Evaluate new move
if (max[0] == null || next_move[1] > max[1]) {
max[0] = column;
max[1] = next_move[1];
}
}
}
return max;
}
Game.prototype.minimizePlay = function(board, depth) {
var score = board.score();
if (board.isFinished(depth, score)) return [null, score];
// Column, score
var min = [null, 99999];
for (var column = 0; column < that.columns; column++) {
var new_board = board.copy();
if (new_board.place(column)) {
that.iterations++;
var next_move = that.maximizePlay(new_board, depth - 1);
if (min[0] == null || next_move[1] < min[1]) {
min[0] = column;
min[1] = next_move[1];
}
}
}
return min;
}
Game.prototype.switchRound = function(round) {
// 0 Human, 1 Computer
if (round == 0) {
return 1;
} else {
return 0;
}
}
Game.prototype.updateStatus = function() {
// Human won
if (that.board.score() == -that.score) {
that.status = 1;
that.markWin();
alert("You have won!");
}
// Computer won
if (that.board.score() == that.score) {
that.status = 2;
that.markWin();
alert("You have lost!");
}
// Tie
if (that.board.isFull()) {
that.status = 3;
alert("Tie!");
}
var html = document.getElementById('status');
if (that.status == 0) {
html.className = "status-running";
html.innerHTML = "running";
} else if (that.status == 1) {
html.className = "status-won";
html.innerHTML = "won";
} else if (that.status == 2) {
html.className = "status-lost";
html.innerHTML = "lost";
} else {
html.className = "status-tie";
html.innerHTML = "tie";
}
}
Game.prototype.markWin = function() {
for (var i = 0; i < that.winning_array.length; i++) {
var name = document.getElementById('game_board').rows[that.winning_array[i][0]].cells[that.winning_array[i][1]].className;
document.getElementById('game_board').rows[that.winning_array[i][0]].cells[that.winning_array[i][1]].className = name + " win";
}
}
Game.prototype.restartGame = function() {
if (confirm('Game is going to be restarted.\nAre you sure?')) {
// Dropdown value
var difficulty = document.getElementById('difficulty');
var depth = difficulty.options[difficulty.selectedIndex].value;
that.depth = depth;
that.status = 0;
that.round = 0;
that.init();
document.getElementById('ai-iterations').innerHTML = "?";
document.getElementById('ai-time').innerHTML = "?";
document.getElementById('ai-column').innerHTML = "Column: ?";
document.getElementById('ai-score').innerHTML = "Score: ?";
document.getElementById('game_board').className = "";
that.updateStatus();
// Re-assign hover
$('td').hover(function() {
$(this).parents('table').find('col:eq('+$(this).index()+')').toggleClass('hover');
});
}
}
/**
* Start game
*/
function Start() {
window.Game = new Game();
// Hover background, now using jQuery
$('td').hover(function() {
$(this).parents('table').find('col:eq('+$(this).index()+')').toggleClass('hover');
});
}
window.onload = function() {
Start()
};
| {
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 = 0; // Iteration count
that = this;
that.init();
} | 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
this.winning_array = []; // Winning (chips) array
this.iterations = 0; // Iteration count
that = this;
that.init();
}
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_board[i][j] = null;
}
}
// Create from board object (see board.js) | 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 td = document.getElementById('game_board').getElementsByTagName("td");
for (var i = 0; i < td.length; i++) {
if (td[i].addEventListener) {
td[i].addEventListener('click', that.act, false);
} else if (td[i].attachEvent) {
td[i].attachEvent('click', that.act)
}
}
}
/**
* 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);
}
}
}
/**
* Place coin
*/
Game.prototype.place = function(column) {
// If not finished
if (that.board.score() != that.score && that.board.score() != -that.score && !that.board.isFull()) {
for (var y = that.rows - 1; y >= 0; y--) {
if (document.getElementById('game_board').rows[y].cells[column].className == 'empty') {
if (that.round == 1) {
var coin_x = column * 51;
var coin_y = y * 51;
$('#coin').attr('class', 'cpu-coin').css({'left': coin_x}).fadeIn('fast').animate({'top': coin_y + 'px'}, 700, 'easeOutBounce', function() {
document.getElementById('game_board').rows[y].cells[column].className = 'coin cpu-coin';
$('#coin').hide().css({'top': '0px'});
if (!that.board.place(column)) {
return alert("Invalid move!");
}
that.round = that.switchRound(that.round);
that.updateStatus();
});
} else {
var coin_x = column * 51;
var coin_y = y * 51;
$('#coin').attr('class', 'human-coin').css({'left': coin_x}).fadeIn('fast').animate({'top': coin_y + 'px'}, 700, 'easeOutBounce', function() {
document.getElementById('game_board').rows[y].cells[column].className = 'coin human-coin';
$('#coin').hide().css({'top': '0px'});
that.generateComputerDecision();
if (!that.board.place(column)) {
return alert("Invalid move!");
}
that.round = that.switchRound(that.round);
that.updateStatus();
});
}
break;
}
}
}
}
Game.prototype.generateComputerDecision = function() {
if (that.board.score() != that.score && that.board.score() != -that.score && !that.board.isFull()) {
that.iterations = 0; // Reset iteration count
document.getElementById('loading').style.display = "block"; // Loading message
// AI is thinking
setTimeout(function() {
// Debug time
var startzeit = new Date().getTime();
// Algorithm call
var ai_move = that.maximizePlay(that.board, that.depth);
var laufzeit = new Date().getTime() - startzeit;
document.getElementById('ai-time').innerHTML = laufzeit.toFixed(2) + 'ms';
// Place ai decision
that.place(ai_move[0]);
// Debug
document.getElementById('ai-column').innerHTML = 'Column: ' + parseInt(ai_move[0] + 1);
document.getElementById('ai-score').innerHTML = 'Score: ' + ai_move[1];
document.getElementById('ai-iterations').innerHTML = that.iterations;
document.getElementById('loading').style.display = "none"; // Remove loading message
}, 100);
}
}
/**
* Algorithm
* Minimax principle
*/
Game.prototype.maximizePlay = function(board, depth) {
// Call score of our board
var score = board.score();
// Break
if (board.isFinished(depth, score)) return [null, score];
// Column, Score
var max = [null, -99999];
// For all possible moves
for (var column = 0; column < that.columns; column++) {
var new_board = board.copy(); // Create new board
if (new_board.place(column)) {
that.iterations++; // Debug
var next_move = that.minimizePlay(new_board, depth - 1); // Recursive calling
// Evaluate new move
if (max[0] == null || next_move[1] > max[1]) {
max[0] = column;
max[1] = next_move[1];
}
}
}
return max;
}
Game.prototype.minimizePlay = function(board, depth) {
var score = board.score();
if (board.isFinished(depth, score)) return [null, score];
// Column, score
var min = [null, 99999];
for (var column = 0; column < that.columns; column++) {
var new_board = board.copy();
if (new_board.place(column)) {
that.iterations++;
var next_move = that.maximizePlay(new_board, depth - 1);
if (min[0] == null || next_move[1] < min[1]) {
min[0] = column;
min[1] = next_move[1];
}
}
}
return min;
}
Game.prototype.switchRound = function(round) {
// 0 Human, 1 Computer
if (round == 0) {
return 1;
} else {
return 0;
}
}
Game.prototype.updateStatus = function() {
// Human won
if (that.board.score() == -that.score) {
that.status = 1;
that.markWin();
alert("You have won!");
}
// Computer won
if (that.board.score() == that.score) {
that.status = 2;
that.markWin();
alert("You have lost!");
}
// Tie
if (that.board.isFull()) {
that.status = 3;
alert("Tie!");
}
var html = document.getElementById('status');
if (that.status == 0) {
html.className = "status-running";
html.innerHTML = "running";
} else if (that.status == 1) {
html.className = "status-won";
html.innerHTML = "won";
} else if (that.status == 2) {
html.className = "status-lost";
html.innerHTML = "lost";
} else {
html.className = "status-tie";
html.innerHTML = "tie";
}
}
Game.prototype.markWin = function() {
for (var i = 0; i < that.winning_array.length; i++) {
var name = document.getElementById('game_board').rows[that.winning_array[i][0]].cells[that.winning_array[i][1]].className;
document.getElementById('game_board').rows[that.winning_array[i][0]].cells[that.winning_array[i][1]].className = name + " win";
}
}
Game.prototype.restartGame = function() {
if (confirm('Game is going to be restarted.\nAre you sure?')) {
// Dropdown value
var difficulty = document.getElementById('difficulty');
var depth = difficulty.options[difficulty.selectedIndex].value;
that.depth = depth;
that.status = 0;
that.round = 0;
that.init();
document.getElementById('ai-iterations').innerHTML = "?";
document.getElementById('ai-time').innerHTML = "?";
document.getElementById('ai-column').innerHTML = "Column: ?";
document.getElementById('ai-score').innerHTML = "Score: ?";
document.getElementById('game_board').className = "";
that.updateStatus();
// Re-assign hover
$('td').hover(function() {
$(this).parents('table').find('col:eq('+$(this).index()+')').toggleClass('hover');
});
}
}
/**
* Start game
*/
function Start() {
window.Game = new Game();
// Hover background, now using jQuery
$('td').hover(function() {
$(this).parents('table').find('col:eq('+$(this).index()+')').toggleClass('hover');
});
}
window.onload = function() {
Start()
}; | 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.iterations = 0; // Iteration count
that = this;
that.init();
}
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_board[i][j] = null;
}
}
// Create from board object (see board.js)
this.board = new Board(this, game_board, 0);
// Generate visual board
var game_board = "<col/><col/><col/><col/><col/><col/><col/>";
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 td = document.getElementById('game_board').getElementsByTagName("td");
for (var i = 0; i < td.length; i++) {
if (td[i].addEventListener) {
td[i].addEventListener('click', that.act, false);
} else if (td[i].attachEvent) {
td[i].attachEvent('click', that.act)
}
}
}
/**
* 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);
}
}
}
/**
* Place coin
*/
Game.prototype.place = function(column) {
// If not finished
if (that.board.score() != that.score && that.board.score() != -that.score && !that.board.isFull()) {
for (var y = that.rows - 1; y >= 0; y--) {
if (document.getElementById('game_board').rows[y].cells[column].className == 'empty') {
if (that.round == 1) {
var coin_x = column * 51;
var coin_y = y * 51;
$('#coin').attr('class', 'cpu-coin').css({'left': coin_x}).fadeIn('fast').animate({'top': coin_y + 'px'}, 700, 'easeOutBounce', function() {
document.getElementById('game_board').rows[y].cells[column].className = 'coin cpu-coin';
$('#coin').hide().css({'top': '0px'});
if (!that.board.place(column)) {
return alert("Invalid move!");
}
that.round = that.switchRound(that.round);
that.updateStatus();
});
} else {
var coin_x = column * 51;
var coin_y = y * 51;
$('#coin').attr('class', 'human-coin').css({'left': coin_x}).fadeIn('fast').animate({'top': coin_y + 'px'}, 700, 'easeOutBounce', function() {
document.getElementById('game_board').rows[y].cells[column].className = 'coin human-coin';
$('#coin').hide().css({'top': '0px'});
that.generateComputerDecision();
if (!that.board.place(column)) {
return alert("Invalid move!");
}
that.round = that.switchRound(that.round);
that.updateStatus();
});
}
break;
}
}
}
}
Game.prototype.generateComputerDecision = function() {
if (that.board.score() != that.score && that.board.score() != -that.score && !that.board.isFull()) {
that.iterations = 0; // Reset iteration count
document.getElementById('loading').style.display = "block"; // Loading message
// AI is thinking
setTimeout(function() {
// Debug time
var startzeit = new Date().getTime();
// Algorithm call
var ai_move = that.maximizePlay(that.board, that.depth);
var laufzeit = new Date().getTime() - startzeit;
document.getElementById('ai-time').innerHTML = laufzeit.toFixed(2) + 'ms';
// Place ai decision
that.place(ai_move[0]);
// Debug
document.getElementById('ai-column').innerHTML = 'Column: ' + parseInt(ai_move[0] + 1);
document.getElementById('ai-score').innerHTML = 'Score: ' + ai_move[1];
document.getElementById('ai-iterations').innerHTML = that.iterations;
document.getElementById('loading').style.display = "none"; // Remove loading message
}, 100);
}
}
/**
* Algorithm
* Minimax principle
*/
Game.prototype.maximizePlay = function(board, depth) {
// Call score of our board
var score = board.score();
// Break
if (board.isFinished(depth, score)) return [null, score];
// Column, Score
var max = [null, -99999];
// For all possible moves
for (var column = 0; column < that.columns; column++) {
var new_board = board.copy(); // Create new board
if (new_board.place(column)) {
that.iterations++; // Debug
var next_move = that.minimizePlay(new_board, depth - 1); // Recursive calling
// Evaluate new move
if (max[0] == null || next_move[1] > max[1]) {
max[0] = column;
max[1] = next_move[1];
}
}
}
return max;
}
Game.prototype.minimizePlay = function(board, depth) {
var score = board.score();
if (board.isFinished(depth, score)) return [null, score];
// Column, score
var min = [null, 99999];
for (var column = 0; column < that.columns; column++) {
var new_board = board.copy();
if (new_board.place(column)) {
that.iterations++;
var next_move = that.maximizePlay(new_board, depth - 1);
if (min[0] == null || next_move[1] < min[1]) {
min[0] = column;
min[1] = next_move[1];
}
}
}
return min;
}
Game.prototype.switchRound = function(round) {
// 0 Human, 1 Computer
if (round == 0) {
return 1;
} else {
return 0;
}
}
Game.prototype.updateStatus = function() {
// Human won
if (that.board.score() == -that.score) {
that.status = 1;
that.markWin();
alert("You have won!");
}
// Computer won
if (that.board.score() == that.score) {
that.status = 2;
that.markWin();
alert("You have lost!");
}
// Tie
if (that.board.isFull()) {
that.status = 3;
alert("Tie!");
}
var html = document.getElementById('status');
if (that.status == 0) {
html.className = "status-running";
html.innerHTML = "running";
} else if (that.status == 1) {
html.className = "status-won";
html.innerHTML = "won";
} else if (that.status == 2) {
html.className = "status-lost";
html.innerHTML = "lost";
} else {
html.className = "status-tie";
html.innerHTML = "tie";
}
}
Game.prototype.markWin = function() {
for (var i = 0; i < that.winning_array.length; i++) {
var name = document.getElementById('game_board').rows[that.winning_array[i][0]].cells[that.winning_array[i][1]].className;
document.getElementById('game_board').rows[that.winning_array[i][0]].cells[that.winning_array[i][1]].className = name + " win";
}
}
Game.prototype.restartGame = function() {
if (confirm('Game is going to be restarted.\nAre you sure?')) {
// Dropdown value
var difficulty = document.getElementById('difficulty');
var depth = difficulty.options[difficulty.selectedIndex].value;
that.depth = depth;
that.status = 0;
that.round = 0;
that.init();
document.getElementById('ai-iterations').innerHTML = "?";
document.getElementById('ai-time').innerHTML = "?";
document.getElementById('ai-column').innerHTML = "Column: ?";
document.getElementById('ai-score').innerHTML = "Score: ?";
document.getElementById('game_board').className = "";
that.updateStatus();
// Re-assign hover
$('td').hover(function() {
$(this).parents('table').find('col:eq('+$(this).index()+')').toggleClass('hover');
});
}
}
/**
* Start game
*/
function Start() {
window.Game = new Game();
// Hover background, now using jQuery
$('td').hover(function() {
$(this).parents('table').find('col:eq('+$(this).index()+')').toggleClass('hover');
});
}
window.onload = function() {
Start()
};
| 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.isClient = utils.isClient
exports.UUID = utils.UUID
exports.register = function(name, helper) {
implode.register(name, helper, [])
}
if (isClient) {
var page = require('page')
, qs = require('qs')
window.swac = {
debug: false,
State: exports.State,
navigate: function(path, opts) {
if (!opts) opts = {}
var ctx = new page.Context(path, null)
if (opts.trigger !== false) {
page.dispatch(ctx)
}
if (!ctx.unhandled) {
if (opts.replaceState === true)
ctx.save()
else if (!opts.silent)
ctx.pushState()
}
}
}
function | (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
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 to `true`, do not
// intercept this link
if (Boolean(el.dataset.external)) return
// ensure protocol
if (el.protocol !== 'http:' && el.protocol !== 'https:') return
// ensure non has for the same path
var href = el.getAttribute('href')
if (el.hash || !href || href == '#') return
// do not intercept x-orgin links
if (!sameOrigin(href)) return
// intercept link
e.preventDefault()
var path = el.pathname + el.search
// provide confirm functionality through `data-confirm`
if (el.dataset.confirm && !confirm(el.dataset.confirm)) return
// trigger route
var ctx = new page.Context(path, {
// whether to actually execute the route
trigger: typeof el.dataset.trigger === 'undefined' ? true : Boolean(el.dataset.trigger)
})
page.dispatch(ctx)
if (!ctx.unhandled && !Boolean(el.dataset.silent)) {
ctx.pushState()
}
})
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.method
, path = el.action
, ctx
// remove origin from path (action)
if (path.indexOf(origin) === 0) {
path = path.substr(origin.length)
}
// POST submits
if (method === 'post') {
// support method overwrite
var _method = el.querySelector('input[name=_method]')
if (_method) method = _method.value
// non GET submits are reworked to /_VERB/..
path = '/_' + method + (path === '' ? '/' : path)
// serialize form elements
var body = qs.parse(utils.serializeForm(el))
// execute route
ctx = new page.Context(path, { body: body })
page.dispatch(ctx)
}
// GET submits
else {
// serialize form elements
if (path.indexOf('?') > -1) path += '&'
else path += '?'
path += utils.serializeForm(el)
// execute route
ctx = new page.Context(path)
page.dispatch(ctx)
if (!ctx.unhandled && !Boolean(el.dataset.silent)) {
ctx.pushState()
}
}
// if no route found, send POST request to server
if (!ctx.unhandled) {
e.preventDefault()
}
})
var routing = require('./routing')
exports.init = routing.init
exports.get = routing.get
exports.post = routing.post
exports.put = routing.put
exports.delete = routing.delete
} | 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.isClient = utils.isClient
exports.UUID = utils.UUID
exports.register = function(name, helper) {
implode.register(name, helper, [])
}
if (isClient) {
var page = require('page')
, qs = require('qs')
window.swac = {
debug: false,
State: exports.State,
navigate: function(path, opts) {
if (!opts) opts = {}
var ctx = new page.Context(path, null)
if (opts.trigger !== false) {
page.dispatch(ctx)
}
if (!ctx.unhandled) {
if (opts.replaceState === true)
ctx.save()
else if (!opts.silent)
ctx.pushState()
}
}
}
function sameOrigin(href) |
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 to `true`, do not
// intercept this link
if (Boolean(el.dataset.external)) return
// ensure protocol
if (el.protocol !== 'http:' && el.protocol !== 'https:') return
// ensure non has for the same path
var href = el.getAttribute('href')
if (el.hash || !href || href == '#') return
// do not intercept x-orgin links
if (!sameOrigin(href)) return
// intercept link
e.preventDefault()
var path = el.pathname + el.search
// provide confirm functionality through `data-confirm`
if (el.dataset.confirm && !confirm(el.dataset.confirm)) return
// trigger route
var ctx = new page.Context(path, {
// whether to actually execute the route
trigger: typeof el.dataset.trigger === 'undefined' ? true : Boolean(el.dataset.trigger)
})
page.dispatch(ctx)
if (!ctx.unhandled && !Boolean(el.dataset.silent)) {
ctx.pushState()
}
})
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.method
, path = el.action
, ctx
// remove origin from path (action)
if (path.indexOf(origin) === 0) {
path = path.substr(origin.length)
}
// POST submits
if (method === 'post') {
// support method overwrite
var _method = el.querySelector('input[name=_method]')
if (_method) method = _method.value
// non GET submits are reworked to /_VERB/..
path = '/_' + method + (path === '' ? '/' : path)
// serialize form elements
var body = qs.parse(utils.serializeForm(el))
// execute route
ctx = new page.Context(path, { body: body })
page.dispatch(ctx)
}
// GET submits
else {
// serialize form elements
if (path.indexOf('?') > -1) path += '&'
else path += '?'
path += utils.serializeForm(el)
// execute route
ctx = new page.Context(path)
page.dispatch(ctx)
if (!ctx.unhandled && !Boolean(el.dataset.silent)) {
ctx.pushState()
}
}
// if no route found, send POST request to server
if (!ctx.unhandled) {
e.preventDefault()
}
})
var routing = require('./routing')
exports.init = routing.init
exports.get = routing.get
exports.post = routing.post
exports.put = routing.put
exports.delete = routing.delete
} | {
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.isClient = utils.isClient
exports.UUID = utils.UUID
exports.register = function(name, helper) {
implode.register(name, helper, [])
}
if (isClient) {
var page = require('page')
, qs = require('qs')
window.swac = {
debug: false,
State: exports.State,
navigate: function(path, opts) {
if (!opts) opts = {}
var ctx = new page.Context(path, null)
if (opts.trigger !== false) {
page.dispatch(ctx)
}
if (!ctx.unhandled) {
if (opts.replaceState === true)
ctx.save()
else if (!opts.silent)
ctx.pushState()
}
}
}
function sameOrigin(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
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 to `true`, do not
// intercept this link
if (Boolean(el.dataset.external)) return
// ensure protocol
if (el.protocol !== 'http:' && el.protocol !== 'https:') return
// ensure non has for the same path
var href = el.getAttribute('href')
if (el.hash || !href || href == '#') return
// do not intercept x-orgin links
if (!sameOrigin(href)) return
// intercept link
e.preventDefault()
var path = el.pathname + el.search
// provide confirm functionality through `data-confirm`
if (el.dataset.confirm && !confirm(el.dataset.confirm)) return
// trigger route
var ctx = new page.Context(path, {
// whether to actually execute the route
trigger: typeof el.dataset.trigger === 'undefined' ? true : Boolean(el.dataset.trigger) | })
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.method
, path = el.action
, ctx
// remove origin from path (action)
if (path.indexOf(origin) === 0) {
path = path.substr(origin.length)
}
// POST submits
if (method === 'post') {
// support method overwrite
var _method = el.querySelector('input[name=_method]')
if (_method) method = _method.value
// non GET submits are reworked to /_VERB/..
path = '/_' + method + (path === '' ? '/' : path)
// serialize form elements
var body = qs.parse(utils.serializeForm(el))
// execute route
ctx = new page.Context(path, { body: body })
page.dispatch(ctx)
}
// GET submits
else {
// serialize form elements
if (path.indexOf('?') > -1) path += '&'
else path += '?'
path += utils.serializeForm(el)
// execute route
ctx = new page.Context(path)
page.dispatch(ctx)
if (!ctx.unhandled && !Boolean(el.dataset.silent)) {
ctx.pushState()
}
}
// if no route found, send POST request to server
if (!ctx.unhandled) {
e.preventDefault()
}
})
var routing = require('./routing')
exports.init = routing.init
exports.get = routing.get
exports.post = routing.post
exports.put = routing.put
exports.delete = routing.delete
} | })
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://biit.cs.ut.ee/gprofiler/",
GMT_ARCHIVE_URL: 'https://biit.cs.ut.ee/gprofiler/static/gprofiler_hsapiens.name.zip',
IDENTIFIERS_URL: 'https://identifiers.org',
NCBI_EUTILS_BASE_URL: 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils',
NCBI_API_KEY: 'b99e10ebe0f90d815a7a99f18403aab08008', // for dev testing only (baderlabsysmonitor ncbi key)
HGNC_BASE_URL: 'https://rest.genenames.org',
UNIPROT_API_BASE_URL: 'https://www.ebi.ac.uk/proteins/api',
PC_IMAGE_CACHE_MAX_SIZE: 10000,
PC_CACHE_MAX_SIZE: 1000,
PUB_CACHE_MAX_SIZE: 1000000,
ENT_CACHE_MAX_SIZE: 1000000,
ENT_SUMMARY_CACHE_MAX_SIZE: 1000000,
MAX_SIF_NODES: 25,
CLIENT_FETCH_TIMEOUT: 15000,
SERVER_FETCH_TIMEOUT: 5000,
// DB config values
DB_NAME: 'appui',
DB_HOST: '127.0.0.1',
DB_PORT: '28015',
DB_USER: undefined,
DB_PASS: undefined,
DB_CERT: undefined,
// factoid specific urls
FACTOID_URL: 'http://unstable.factoid.baderlab.org/',
NS_CHEBI: 'chebi',
NS_ENSEMBL: 'ensembl',
NS_GENECARDS: 'genecards',
NS_GENE_ONTOLOGY: 'go',
NS_HGNC: 'hgnc',
NS_HGNC_SYMBOL: 'hgnc.symbol',
NS_NCBI_GENE: 'ncbigene',
NS_PUBMED: 'pubmed',
NS_REACTOME: 'reactome',
NS_UNIPROT: 'uniprot'
};
let envVars = _.pick( process.env, Object.keys( defaults ) );
// these vars are always included in the bundle because they ref `process.env.${name}` directly
// NB DO NOT include passwords etc. here
let clientVars = {
NODE_ENV: process.env.NODE_ENV,
PC_URL: process.env.PC_URL,
FACTOID_URL: process.env.FACTOID_URL
};
_.assign(envVars, clientVars);
for( let key in envVars ){
let val = envVars[key];
if( val === '' || val == null ) |
}
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.cs.ut.ee/gprofiler/static/gprofiler_hsapiens.name.zip',
IDENTIFIERS_URL: 'https://identifiers.org',
NCBI_EUTILS_BASE_URL: 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils',
NCBI_API_KEY: 'b99e10ebe0f90d815a7a99f18403aab08008', // for dev testing only (baderlabsysmonitor ncbi key)
HGNC_BASE_URL: 'https://rest.genenames.org',
UNIPROT_API_BASE_URL: 'https://www.ebi.ac.uk/proteins/api',
PC_IMAGE_CACHE_MAX_SIZE: 10000,
PC_CACHE_MAX_SIZE: 1000,
PUB_CACHE_MAX_SIZE: 1000000,
ENT_CACHE_MAX_SIZE: 1000000,
ENT_SUMMARY_CACHE_MAX_SIZE: 1000000,
MAX_SIF_NODES: 25,
CLIENT_FETCH_TIMEOUT: 15000,
SERVER_FETCH_TIMEOUT: 5000,
// DB config values
DB_NAME: 'appui',
DB_HOST: '127.0.0.1',
DB_PORT: '28015',
DB_USER: undefined,
DB_PASS: undefined,
DB_CERT: undefined,
// factoid specific urls
FACTOID_URL: 'http://unstable.factoid.baderlab.org/',
NS_CHEBI: 'chebi',
NS_ENSEMBL: 'ensembl',
NS_GENECARDS: 'genecards',
NS_GENE_ONTOLOGY: 'go',
NS_HGNC: 'hgnc',
NS_HGNC_SYMBOL: 'hgnc.symbol',
NS_NCBI_GENE: 'ncbigene',
NS_PUBMED: 'pubmed',
NS_REACTOME: 'reactome',
NS_UNIPROT: 'uniprot'
};
let envVars = _.pick( process.env, Object.keys( defaults ) );
// these vars are always included in the bundle because they ref `process.env.${name}` directly
// NB DO NOT include passwords etc. here
let clientVars = {
NODE_ENV: process.env.NODE_ENV,
PC_URL: process.env.PC_URL,
FACTOID_URL: process.env.FACTOID_URL
};
_.assign(envVars, clientVars);
for( let key in envVars ){
let val = envVars[key];
if( val === '' || val == null ){
delete envVars[key];
}
}
let conf = Object.assign( {}, defaults, envVars );
Object.freeze( conf );
module.exports = conf; | 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 float(hi) >= 1.0:
self.tk.call("grid", "remove", self)
else:
self.grid()
Scrollbar.set(self, lo, hi)
def pack(self, **kw):
raise(TclError, "can't pack this widget")
def place(self, **kw):
|
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, column=0, sticky=N+S+E+W)
vscrollbar.config(command=canvas.yview)
hscrollbar.config(command=canvas.xview)
# make the canvas expandable
fenetre.grid_rowconfigure(0, weight=1)
fenetre.grid_columnconfigure(0, weight=1)
#
# create canvas contents
frame = Frame(canvas, background="white", borderwidth=0)
#enigma_image
image = PhotoImage(file="enigma.gif")
Label(frame, image=image, background="white", borderwidth=0).pack(padx=10, pady=10, side=TOP)
#help_button
def help():
showinfo("The Enigma Machine Quick Start", "Hello World!\nThis is a quick tutorial on how to use this app!\nFirst, you need to choose the order of the rotors.\nThen you need to set the rotors' position\nYou can finally write your message and encrypt it by pressing the Return key!\nThat's it, you've just encrypt your first enigma message!\n Have fun!")
helpButton = Button(frame, text ="Help! Quick Start", command = help, background="white")
helpButton.pack(padx=5, pady=5)
#spinboxes_choose_rotors
frameRotor = Frame(frame, background='white')
var4 = StringVar()
spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]",
"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]"), textvariable=var4, width=44)
var4.set("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]")
spinbox.grid(row=0, column=1)
var5 = StringVar()
spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]",
"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]"), textvariable=var5, width=44)
var5.set("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]")
spinbox.grid(row=1, column=1)
var6 = StringVar()
spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]",
"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]"), textvariable=var6, width=44)
var6.set("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]")
spinbox.grid(row=2, column=1)
var7 = StringVar()
spinbox = Spinbox(frameRotor, values = ("reflec=[Y,R,U,H,Q,S,L,D,P,X,N,G,O,K,M,I,E,B,F,Z,C,W,V,J,A,T]"), textvariable=var7, width=44)
var7.set("reflec=[Y,R,U,H,Q,S,L,D,P,X,N,G,O,K,M,I,E,B,F,Z,C,W,V,J,A,T]")
spinbox.grid(row=3, column=1)
rotorn1 = Label(frameRotor, text='Slot n°=1:', padx=10, pady=5, background="white")
rotorn1.grid(row=0, column=0)
rotorn2 = Label(frameRotor, text='Slot n°=2:', padx=10, pady=5, background="white")
rotorn2.grid(row=1, column=0)
rotorn3 = Label(frameRotor, text='Slot n°=3:', padx=10, pady=5, background="white")
rotorn3.grid(row=2, column=0)
reflectorn = Label(frameRotor, text='Reflector:', padx=10, pady=5, background="white")
reflectorn.grid(row=3, column=0)
frameRotor.pack()
#frame_to_set_rotor_position
frame1 = Frame(frame, borderwidth=0, relief=FLAT, background='white')
frame1.pack(side=TOP, padx=10, pady=10)
def update1(x):
x = int(x)
alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lab1.configure(text='position : {}'.format(alphabetList[x-1]))
def update2(x):
x = int(x)
alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lab2.configure(text='position : {}'.format(alphabetList[x-1]))
def update3(x):
x = int(x)
alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lab3.configure(text='position : {}'.format(alphabetList[x-1]))
rotor1lab = Label(frame1, text='Rotor 1', padx=10, pady=5, background="white")
rotor1lab.grid(row=0, column=0)
rotor2lab = Label(frame1, text='Rotor 2', padx=10, pady=5, background="white")
rotor2lab.grid(row=0, column=1)
rotor3lab = Label(frame1, text='Rotor 3', padx=10, pady=5, background="white")
rotor3lab.grid(row=0, column=2)
#scales_choose_position
var1 = DoubleVar()
scale = Scale(frame1, from_=1, to=26, variable = var1, cursor='dot', showvalue=0, command=update1, length= 100, background="white")
scale.grid(row=1, column=0, padx=60, pady=10)
var2 = DoubleVar()
scale = Scale(frame1, from_=1, to=26, variable = var2, cursor='dot', showvalue=0, command=update2, length= 100, background="white")
scale.grid(row=1, column=1, padx=60, pady=10)
var3 = DoubleVar()
scale = Scale(frame1, from_=1, to=26, variable = var3, cursor='dot', showvalue=0, command=update3, length= 100, background="white")
scale.grid(row=1, column=2, padx=60, pady=10)
lab1 = Label(frame1, background="white")
lab1.grid(row=2, column=0)
lab2 = Label(frame1, background="white")
lab2.grid(row=2, column=1)
lab3 = Label(frame1, background="white")
lab3.grid(row=2, column=2)
#function_code
def code(event=None):
a = int(var1.get())
b = int(var2.get())
c = int(var3.get())
def rotationRotor(liste1):
liste1.append(liste1[0])
del liste1[0]
return liste1
def estValide(liste1):
if liste1 == []:
return False
for elt in liste1:
if alphabetList.count(elt.upper()) < 1:
return False
return True
sortie = entryvar.get()
var4str = var4.get()
var4list = list(var4str)
var5str = var5.get()
var5list = list(var5str)
var6str = var6.get()
var6list = list(var6str)
if var4list[5] == '1':
rotor1 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H']
elif var4list[5] == '2':
rotor1 = ['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']
elif var4list[5] == '3':
rotor1 = ['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']
if var5list[5] == '1':
rotor2 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H']
elif var5list[5] == '2':
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']
elif var5list[5] == '3':
rotor2 = ['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']
if var6list[5] == '1':
rotor3 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H']
elif var6list[5] == '2':
rotor3 = ['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']
elif var6list[5] == '3':
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']
alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',' ']
alphabetDict = {'G': 7, 'U': 21, 'T': 20, 'L': 12, 'Y': 25, 'Q': 17, 'V': 22, 'J': 10, 'O': 15, 'W': 23, 'N': 14, 'R': 18, 'Z': 26, 'S': 19, 'X': 24, 'A': 1, 'M': 13, 'E': 5, 'D': 4, 'I': 9, 'F': 6, 'P': 16, 'B': 2, 'H': 8, 'K': 11, 'C': 3}
#rotor1 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H']
#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', 'K', 'M', 'I', 'E', 'B', 'F', 'Z', 'C', 'W', 'V', 'J', 'A', 'T']
for loop1 in range(a):
rotationRotor(rotor1)
for loop2 in range(b):
rotationRotor(rotor2)
for loop3 in range(c):
rotationRotor(rotor3)
sortieListe = list(sortie)
print(sortieListe)
sortieListe = [x for x in sortieListe if x != " "]
print(sortieListe)
if not estValide(sortieListe):
value = StringVar()
value.set('Please enter only letters and spaces!')
liste.insert(END, value.get())
liste.itemconfig(END, {'bg':'red'})
liste.see("end")
elif (var4list[5] == var5list[5] == var6list[5]) or (var4list[5] == var5list[5]) or (var4list[5] == var6list[5]) or (var5list[5] == var6list[5]):
value = StringVar()
value.set('You can only use a rotor once!')
liste.insert(END, value.get())
liste.itemconfig(END, {'bg':'red'})
liste.see("end")
else:
s = []
for i in range(0,len(sortieListe),1):
a = 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]
l = rotor2.index(k)
m = alphabetList[l]
n = rotor1.index(m)
o = alphabetList[n]
s.append(o)
if (i+1) % 1 == 0:
rotationRotor(rotor1)
if (i+1) % 26 == 0:
rotationRotor(rotor2)
if (i+1) % 676 == 0:
rotationRotor(rotor3)
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_listbox
def clear():
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(yscrollcommand = s1.set)
liste.pack(side = LEFT, fill = Y, padx=5, pady=5)
s1.pack(side = RIGHT, fill = Y)
f1.pack()
#button_to_clear_listbox
b2 = Button(frame, text="clear list", width=10, command=clear, background='white')
b2.pack(padx=5, pady=5)
#credits
credits = Label(frame, text = "coded with <3 by omnitrogen",background="white")
credits.pack(side = BOTTOM, padx=10, pady=10)
#quit_button
quitButton = Button(frame, text="quit", width=10, command=frame.quit, background='white')
quitButton.pack(side = BOTTOM)
canvas.create_window(0, 0, anchor=NW, window=frame)
frame.update_idletasks()
canvas.config(scrollregion=canvas.bbox("all"))
mainloop()
| 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 float(hi) >= 1.0:
self.tk.call("grid", "remove", self)
else:
self.grid()
Scrollbar.set(self, lo, hi)
def pack(self, **kw):
raise(TclError, "can't pack this widget")
def place(self, **kw):
raise(TclError, "can't grid this widget")
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, column=0, sticky=N+S+E+W)
vscrollbar.config(command=canvas.yview)
hscrollbar.config(command=canvas.xview)
# make the canvas expandable
fenetre.grid_rowconfigure(0, weight=1)
fenetre.grid_columnconfigure(0, weight=1)
#
# create canvas contents
frame = Frame(canvas, background="white", borderwidth=0)
#enigma_image
image = PhotoImage(file="enigma.gif")
Label(frame, image=image, background="white", borderwidth=0).pack(padx=10, pady=10, side=TOP)
#help_button
def help():
showinfo("The Enigma Machine Quick Start", "Hello World!\nThis is a quick tutorial on how to use this app!\nFirst, you need to choose the order of the rotors.\nThen you need to set the rotors' position\nYou can finally write your message and encrypt it by pressing the Return key!\nThat's it, you've just encrypt your first enigma message!\n Have fun!")
helpButton = Button(frame, text ="Help! Quick Start", command = help, background="white")
helpButton.pack(padx=5, pady=5)
#spinboxes_choose_rotors
frameRotor = Frame(frame, background='white')
var4 = StringVar()
spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]",
"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]"), textvariable=var4, width=44)
var4.set("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]")
spinbox.grid(row=0, column=1)
var5 = StringVar()
spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]",
"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]"), textvariable=var5, width=44)
var5.set("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]")
spinbox.grid(row=1, column=1)
var6 = StringVar()
spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]",
"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]"), textvariable=var6, width=44)
var6.set("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]")
spinbox.grid(row=2, column=1)
var7 = StringVar()
spinbox = Spinbox(frameRotor, values = ("reflec=[Y,R,U,H,Q,S,L,D,P,X,N,G,O,K,M,I,E,B,F,Z,C,W,V,J,A,T]"), textvariable=var7, width=44)
var7.set("reflec=[Y,R,U,H,Q,S,L,D,P,X,N,G,O,K,M,I,E,B,F,Z,C,W,V,J,A,T]")
spinbox.grid(row=3, column=1)
rotorn1 = Label(frameRotor, text='Slot n°=1:', padx=10, pady=5, background="white")
rotorn1.grid(row=0, column=0)
rotorn2 = Label(frameRotor, text='Slot n°=2:', padx=10, pady=5, background="white")
rotorn2.grid(row=1, column=0)
rotorn3 = Label(frameRotor, text='Slot n°=3:', padx=10, pady=5, background="white")
rotorn3.grid(row=2, column=0)
reflectorn = Label(frameRotor, text='Reflector:', padx=10, pady=5, background="white")
reflectorn.grid(row=3, column=0)
frameRotor.pack()
#frame_to_set_rotor_position
frame1 = Frame(frame, borderwidth=0, relief=FLAT, background='white')
frame1.pack(side=TOP, padx=10, pady=10)
def update1(x):
x = int(x)
alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lab1.configure(text='position : {}'.format(alphabetList[x-1]))
def update2(x):
x = int(x)
alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lab2.configure(text='position : {}'.format(alphabetList[x-1]))
def update3(x):
x = int(x)
alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lab3.configure(text='position : {}'.format(alphabetList[x-1]))
rotor1lab = Label(frame1, text='Rotor 1', padx=10, pady=5, background="white")
rotor1lab.grid(row=0, column=0)
rotor2lab = Label(frame1, text='Rotor 2', padx=10, pady=5, background="white")
rotor2lab.grid(row=0, column=1)
rotor3lab = Label(frame1, text='Rotor 3', padx=10, pady=5, background="white")
rotor3lab.grid(row=0, column=2)
#scales_choose_position
var1 = DoubleVar()
scale = Scale(frame1, from_=1, to=26, variable = var1, cursor='dot', showvalue=0, command=update1, length= 100, background="white")
scale.grid(row=1, column=0, padx=60, pady=10)
var2 = DoubleVar()
scale = Scale(frame1, from_=1, to=26, variable = var2, cursor='dot', showvalue=0, command=update2, length= 100, background="white")
scale.grid(row=1, column=1, padx=60, pady=10)
var3 = DoubleVar()
scale = Scale(frame1, from_=1, to=26, variable = var3, cursor='dot', showvalue=0, command=update3, length= 100, background="white")
scale.grid(row=1, column=2, padx=60, pady=10)
lab1 = Label(frame1, background="white")
lab1.grid(row=2, column=0)
lab2 = Label(frame1, background="white")
lab2.grid(row=2, column=1)
lab3 = Label(frame1, background="white")
lab3.grid(row=2, column=2)
#function_code
def code(event=None):
a = int(var1.get())
b = int(var2.get())
c = int(var3.get())
def rotationRotor(liste1):
liste1.append(liste1[0])
del liste1[0]
return liste1
def estValide(liste1):
if liste1 == []:
return False
for elt in liste1:
if alphabetList.count(elt.upper()) < 1:
return False
return True
sortie = entryvar.get()
var4str = var4.get()
var4list = list(var4str)
var5str = var5.get()
var5list = list(var5str)
var6str = var6.get()
var6list = list(var6str)
if var4list[5] == '1':
rotor1 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H']
elif var4list[5] == '2':
rotor1 = ['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']
elif var4list[5] == '3':
rotor1 = ['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']
if var5list[5] == '1':
rotor2 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H']
elif var5list[5] == '2':
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']
elif var5list[5] == '3':
rotor2 = ['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']
if var6list[5] == '1':
rotor3 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H']
elif var6list[5] == '2':
rotor3 = ['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']
elif var6list[5] == '3':
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']
alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',' ']
alphabetDict = {'G': 7, 'U': 21, 'T': 20, 'L': 12, 'Y': 25, 'Q': 17, 'V': 22, 'J': 10, 'O': 15, 'W': 23, 'N': 14, 'R': 18, 'Z': 26, 'S': 19, 'X': 24, 'A': 1, 'M': 13, 'E': 5, 'D': 4, 'I': 9, 'F': 6, 'P': 16, 'B': 2, 'H': 8, 'K': 11, 'C': 3}
#rotor1 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H']
#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', 'K', 'M', 'I', 'E', 'B', 'F', 'Z', 'C', 'W', 'V', 'J', 'A', 'T']
for loop1 in range(a):
rotationRotor(rotor1)
for loop2 in range(b):
rotationRotor(rotor2)
for loop3 in range(c):
rotationRotor(rotor3)
sortieListe = list(sortie)
print(sortieListe)
sortieListe = [x for x in sortieListe if x != " "]
print(sortieListe)
if not estValide(sortieListe):
value = StringVar()
value.set('Please enter only letters and spaces!')
liste.insert(END, value.get())
liste.itemconfig(END, {'bg':'red'})
liste.see("end")
elif (var4list[5] == var5list[5] == var6list[5]) or (var4list[5] == var5list[5]) or (var4list[5] == var6list[5]) or (var5list[5] == var6list[5]):
value = StringVar()
value.set('You can only use a rotor once!')
liste.insert(END, value.get())
liste.itemconfig(END, {'bg':'red'})
liste.see("end")
else:
s = []
for i in range(0,len(sortieListe),1):
a = 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]
l = rotor2.index(k)
m = alphabetList[l]
n = rotor1.index(m)
o = alphabetList[n]
s.append(o)
if (i+1) % 1 == 0:
rotationRotor(rotor1)
if (i+1) % 26 == 0:
rotationRotor(rotor2)
if (i+1) % 676 == 0:
rotationRotor(rotor3)
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_listbox
def cle |
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(yscrollcommand = s1.set)
liste.pack(side = LEFT, fill = Y, padx=5, pady=5)
s1.pack(side = RIGHT, fill = Y)
f1.pack()
#button_to_clear_listbox
b2 = Button(frame, text="clear list", width=10, command=clear, background='white')
b2.pack(padx=5, pady=5)
#credits
credits = Label(frame, text = "coded with <3 by omnitrogen",background="white")
credits.pack(side = BOTTOM, padx=10, pady=10)
#quit_button
quitButton = Button(frame, text="quit", width=10, command=frame.quit, background='white')
quitButton.pack(side = BOTTOM)
canvas.create_window(0, 0, anchor=NW, window=frame)
frame.update_idletasks()
canvas.config(scrollregion=canvas.bbox("all"))
mainloop()
| 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 float(hi) >= 1.0:
self.tk.call("grid", "remove", self)
else:
self.grid()
Scrollbar.set(self, lo, hi)
def pack(self, **kw):
raise(TclError, "can't pack this widget")
def place(self, **kw):
raise(TclError, "can't grid this widget")
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, column=0, sticky=N+S+E+W)
vscrollbar.config(command=canvas.yview)
hscrollbar.config(command=canvas.xview)
# make the canvas expandable
fenetre.grid_rowconfigure(0, weight=1)
fenetre.grid_columnconfigure(0, weight=1)
#
# create canvas contents
frame = Frame(canvas, background="white", borderwidth=0)
#enigma_image
image = PhotoImage(file="enigma.gif")
Label(frame, image=image, background="white", borderwidth=0).pack(padx=10, pady=10, side=TOP)
#help_button
def help():
showinfo("The Enigma Machine Quick Start", "Hello World!\nThis is a quick tutorial on how to use this app!\nFirst, you need to choose the order of the rotors.\nThen you need to set the rotors' position\nYou can finally write your message and encrypt it by pressing the Return key!\nThat's it, you've just encrypt your first enigma message!\n Have fun!")
helpButton = Button(frame, text ="Help! Quick Start", command = help, background="white")
helpButton.pack(padx=5, pady=5)
#spinboxes_choose_rotors
frameRotor = Frame(frame, background='white')
var4 = StringVar()
spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]",
"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]"), textvariable=var4, width=44)
var4.set("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]")
spinbox.grid(row=0, column=1)
var5 = StringVar()
spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]",
"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]"), textvariable=var5, width=44)
var5.set("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]")
spinbox.grid(row=1, column=1)
var6 = StringVar()
spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]",
"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]"), textvariable=var6, width=44)
var6.set("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]")
spinbox.grid(row=2, column=1)
var7 = StringVar()
spinbox = Spinbox(frameRotor, values = ("reflec=[Y,R,U,H,Q,S,L,D,P,X,N,G,O,K,M,I,E,B,F,Z,C,W,V,J,A,T]"), textvariable=var7, width=44)
var7.set("reflec=[Y,R,U,H,Q,S,L,D,P,X,N,G,O,K,M,I,E,B,F,Z,C,W,V,J,A,T]")
spinbox.grid(row=3, column=1)
rotorn1 = Label(frameRotor, text='Slot n°=1:', padx=10, pady=5, background="white")
rotorn1.grid(row=0, column=0)
rotorn2 = Label(frameRotor, text='Slot n°=2:', padx=10, pady=5, background="white")
rotorn2.grid(row=1, column=0)
rotorn3 = Label(frameRotor, text='Slot n°=3:', padx=10, pady=5, background="white")
rotorn3.grid(row=2, column=0)
reflectorn = Label(frameRotor, text='Reflector:', padx=10, pady=5, background="white")
reflectorn.grid(row=3, column=0)
frameRotor.pack()
#frame_to_set_rotor_position
frame1 = Frame(frame, borderwidth=0, relief=FLAT, background='white')
frame1.pack(side=TOP, padx=10, pady=10)
def update1(x):
x = int(x)
alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lab1.configure(text='position : {}'.format(alphabetList[x-1]))
def update2(x):
x = int(x)
alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lab2.configure(text='position : {}'.format(alphabetList[x-1]))
def update3(x):
x = int(x)
alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lab3.configure(text='position : {}'.format(alphabetList[x-1]))
rotor1lab = Label(frame1, text='Rotor 1', padx=10, pady=5, background="white")
rotor1lab.grid(row=0, column=0)
rotor2lab = Label(frame1, text='Rotor 2', padx=10, pady=5, background="white")
rotor2lab.grid(row=0, column=1)
rotor3lab = Label(frame1, text='Rotor 3', padx=10, pady=5, background="white")
rotor3lab.grid(row=0, column=2)
#scales_choose_position
var1 = DoubleVar()
scale = Scale(frame1, from_=1, to=26, variable = var1, cursor='dot', showvalue=0, command=update1, length= 100, background="white")
scale.grid(row=1, column=0, padx=60, pady=10)
var2 = DoubleVar()
scale = Scale(frame1, from_=1, to=26, variable = var2, cursor='dot', showvalue=0, command=update2, length= 100, background="white")
scale.grid(row=1, column=1, padx=60, pady=10)
var3 = DoubleVar()
scale = Scale(frame1, from_=1, to=26, variable = var3, cursor='dot', showvalue=0, command=update3, length= 100, background="white")
scale.grid(row=1, column=2, padx=60, pady=10)
lab1 = Label(frame1, background="white")
lab1.grid(row=2, column=0)
lab2 = Label(frame1, background="white")
lab2.grid(row=2, column=1)
lab3 = Label(frame1, background="white")
lab3.grid(row=2, column=2)
#function_code
def code(event=None):
a = int(var1.get())
b = int(var2.get())
c = int(var3.get())
def rotationRotor(liste1):
liste1.append(liste1[0])
del liste1[0]
return liste1
def estValide(liste1):
if liste1 == []:
return False
for elt in liste1:
if alphabetList.count(elt.upper()) < 1:
return False
return True
sortie = entryvar.get()
var4str = var4.get()
var4list = list(var4str)
var5str = var5.get()
var5list = list(var5str)
var6str = var6.get()
var6list = list(var6str)
if var4list[5] == '1':
rotor1 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H']
elif var4list[5] == '2':
rotor1 = ['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']
elif var4list[5] == '3':
rotor1 = ['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']
if var5list[5] == '1':
rotor2 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H']
elif var5list[5] == '2':
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']
elif var5list[5] == '3':
rotor2 = ['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']
if var6list[5] == '1':
rotor3 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H']
elif var6list[5] == '2':
rotor3 = ['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']
elif var6list[5] == '3':
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']
alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',' ']
alphabetDict = {'G': 7, 'U': 21, 'T': 20, 'L': 12, 'Y': 25, 'Q': 17, 'V': 22, 'J': 10, 'O': 15, 'W': 23, 'N': 14, 'R': 18, 'Z': 26, 'S': 19, 'X': 24, 'A': 1, 'M': 13, 'E': 5, 'D': 4, 'I': 9, 'F': 6, 'P': 16, 'B': 2, 'H': 8, 'K': 11, 'C': 3}
#rotor1 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H'] | #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', 'K', 'M', 'I', 'E', 'B', 'F', 'Z', 'C', 'W', 'V', 'J', 'A', 'T']
for loop1 in range(a):
rotationRotor(rotor1)
for loop2 in range(b):
rotationRotor(rotor2)
for loop3 in range(c):
rotationRotor(rotor3)
sortieListe = list(sortie)
print(sortieListe)
sortieListe = [x for x in sortieListe if x != " "]
print(sortieListe)
if not estValide(sortieListe):
value = StringVar()
value.set('Please enter only letters and spaces!')
liste.insert(END, value.get())
liste.itemconfig(END, {'bg':'red'})
liste.see("end")
elif (var4list[5] == var5list[5] == var6list[5]) or (var4list[5] == var5list[5]) or (var4list[5] == var6list[5]) or (var5list[5] == var6list[5]):
value = StringVar()
value.set('You can only use a rotor once!')
liste.insert(END, value.get())
liste.itemconfig(END, {'bg':'red'})
liste.see("end")
else:
s = []
for i in range(0,len(sortieListe),1):
a = 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]
l = rotor2.index(k)
m = alphabetList[l]
n = rotor1.index(m)
o = alphabetList[n]
s.append(o)
if (i+1) % 1 == 0:
rotationRotor(rotor1)
if (i+1) % 26 == 0:
rotationRotor(rotor2)
if (i+1) % 676 == 0:
rotationRotor(rotor3)
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_listbox
def clear():
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(yscrollcommand = s1.set)
liste.pack(side = LEFT, fill = Y, padx=5, pady=5)
s1.pack(side = RIGHT, fill = Y)
f1.pack()
#button_to_clear_listbox
b2 = Button(frame, text="clear list", width=10, command=clear, background='white')
b2.pack(padx=5, pady=5)
#credits
credits = Label(frame, text = "coded with <3 by omnitrogen",background="white")
credits.pack(side = BOTTOM, padx=10, pady=10)
#quit_button
quitButton = Button(frame, text="quit", width=10, command=frame.quit, background='white')
quitButton.pack(side = BOTTOM)
canvas.create_window(0, 0, anchor=NW, window=frame)
frame.update_idletasks()
canvas.config(scrollregion=canvas.bbox("all"))
mainloop() | 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 float(hi) >= 1.0:
self.tk.call("grid", "remove", self)
else:
self.grid()
Scrollbar.set(self, lo, hi)
def pack(self, **kw):
raise(TclError, "can't pack this widget")
def place(self, **kw):
raise(TclError, "can't grid this widget")
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, column=0, sticky=N+S+E+W)
vscrollbar.config(command=canvas.yview)
hscrollbar.config(command=canvas.xview)
# make the canvas expandable
fenetre.grid_rowconfigure(0, weight=1)
fenetre.grid_columnconfigure(0, weight=1)
#
# create canvas contents
frame = Frame(canvas, background="white", borderwidth=0)
#enigma_image
image = PhotoImage(file="enigma.gif")
Label(frame, image=image, background="white", borderwidth=0).pack(padx=10, pady=10, side=TOP)
#help_button
def help():
showinfo("The Enigma Machine Quick Start", "Hello World!\nThis is a quick tutorial on how to use this app!\nFirst, you need to choose the order of the rotors.\nThen you need to set the rotors' position\nYou can finally write your message and encrypt it by pressing the Return key!\nThat's it, you've just encrypt your first enigma message!\n Have fun!")
helpButton = Button(frame, text ="Help! Quick Start", command = help, background="white")
helpButton.pack(padx=5, pady=5)
#spinboxes_choose_rotors
frameRotor = Frame(frame, background='white')
var4 = StringVar()
spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]",
"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]"), textvariable=var4, width=44)
var4.set("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]")
spinbox.grid(row=0, column=1)
var5 = StringVar()
spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]",
"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]"), textvariable=var5, width=44)
var5.set("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]")
spinbox.grid(row=1, column=1)
var6 = StringVar()
spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]",
"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]"), textvariable=var6, width=44)
var6.set("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]")
spinbox.grid(row=2, column=1)
var7 = StringVar()
spinbox = Spinbox(frameRotor, values = ("reflec=[Y,R,U,H,Q,S,L,D,P,X,N,G,O,K,M,I,E,B,F,Z,C,W,V,J,A,T]"), textvariable=var7, width=44)
var7.set("reflec=[Y,R,U,H,Q,S,L,D,P,X,N,G,O,K,M,I,E,B,F,Z,C,W,V,J,A,T]")
spinbox.grid(row=3, column=1)
rotorn1 = Label(frameRotor, text='Slot n°=1:', padx=10, pady=5, background="white")
rotorn1.grid(row=0, column=0)
rotorn2 = Label(frameRotor, text='Slot n°=2:', padx=10, pady=5, background="white")
rotorn2.grid(row=1, column=0)
rotorn3 = Label(frameRotor, text='Slot n°=3:', padx=10, pady=5, background="white")
rotorn3.grid(row=2, column=0)
reflectorn = Label(frameRotor, text='Reflector:', padx=10, pady=5, background="white")
reflectorn.grid(row=3, column=0)
frameRotor.pack()
#frame_to_set_rotor_position
frame1 = Frame(frame, borderwidth=0, relief=FLAT, background='white')
frame1.pack(side=TOP, padx=10, pady=10)
def update1(x):
x = int(x)
alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lab1.configure(text='position : {}'.format(alphabetList[x-1]))
def update2(x):
x = int(x)
alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lab2.configure(text='position : {}'.format(alphabetList[x-1]))
def update3(x):
x = int(x)
alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lab3.configure(text='position : {}'.format(alphabetList[x-1]))
rotor1lab = Label(frame1, text='Rotor 1', padx=10, pady=5, background="white")
rotor1lab.grid(row=0, column=0)
rotor2lab = Label(frame1, text='Rotor 2', padx=10, pady=5, background="white")
rotor2lab.grid(row=0, column=1)
rotor3lab = Label(frame1, text='Rotor 3', padx=10, pady=5, background="white")
rotor3lab.grid(row=0, column=2)
#scales_choose_position
var1 = DoubleVar()
scale = Scale(frame1, from_=1, to=26, variable = var1, cursor='dot', showvalue=0, command=update1, length= 100, background="white")
scale.grid(row=1, column=0, padx=60, pady=10)
var2 = DoubleVar()
scale = Scale(frame1, from_=1, to=26, variable = var2, cursor='dot', showvalue=0, command=update2, length= 100, background="white")
scale.grid(row=1, column=1, padx=60, pady=10)
var3 = DoubleVar()
scale = Scale(frame1, from_=1, to=26, variable = var3, cursor='dot', showvalue=0, command=update3, length= 100, background="white")
scale.grid(row=1, column=2, padx=60, pady=10)
lab1 = Label(frame1, background="white")
lab1.grid(row=2, column=0)
lab2 = Label(frame1, background="white")
lab2.grid(row=2, column=1)
lab3 = Label(frame1, background="white")
lab3.grid(row=2, column=2)
#function_code
def code(event=None):
a = int(var1.get())
b = int(var2.get())
c = int(var3.get())
def rotationRotor(liste1):
liste1.append(liste1[0])
del liste1[0]
return liste1
def estValide(liste1):
if liste1 == []:
return False
for elt in liste1:
if alphabetList.count(elt.upper()) < 1:
return False
return True
sortie = entryvar.get()
var4str = var4.get()
var4list = list(var4str)
var5str = var5.get()
var5list = list(var5str)
var6str = var6.get()
var6list = list(var6str)
if var4list[5] == '1':
rotor1 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H']
elif var4list[5] == '2':
rotor1 = ['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']
elif var4list[5] == '3':
rotor1 = ['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']
if var5list[5] == '1':
rotor2 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H']
elif var5list[5] == '2':
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']
elif var5list[5] == '3':
rotor2 = ['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']
if var6list[5] == '1':
rotor3 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H']
elif var6list[5] == '2':
rotor3 = ['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']
elif var6list[5] == '3':
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']
alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',' ']
alphabetDict = {'G': 7, 'U': 21, 'T': 20, 'L': 12, 'Y': 25, 'Q': 17, 'V': 22, 'J': 10, 'O': 15, 'W': 23, 'N': 14, 'R': 18, 'Z': 26, 'S': 19, 'X': 24, 'A': 1, 'M': 13, 'E': 5, 'D': 4, 'I': 9, 'F': 6, 'P': 16, 'B': 2, 'H': 8, 'K': 11, 'C': 3}
#rotor1 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H']
#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', 'K', 'M', 'I', 'E', 'B', 'F', 'Z', 'C', 'W', 'V', 'J', 'A', 'T']
for loop1 in range(a):
rotationRotor(rotor1)
for loop2 in range(b):
rotationRotor(rotor2)
for loop3 in range(c):
rotationRotor(rotor3)
sortieListe = list(sortie)
print(sortieListe)
sortieListe = [x for x in sortieListe if x != " "]
print(sortieListe)
if not estValide(sortieListe):
value = StringVar()
value.set('Please enter only letters and spaces!')
liste.insert(END, value.get())
liste.itemconfig(END, {'bg':'red'})
liste.see("end")
elif (var4list[5] == var5list[5] == var6list[5]) or (var4list[5] == var5list[5]) or (var4list[5] == var6list[5]) or (var5list[5] == var6list[5]):
value = StringVar()
value.set('You can only use a rotor once!')
liste.insert(END, value.get())
liste.itemconfig(END, {'bg':'red'})
liste.see("end")
else:
s = []
for i in range(0,len(sortieListe),1):
a = | 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_listbox
def clear():
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(yscrollcommand = s1.set)
liste.pack(side = LEFT, fill = Y, padx=5, pady=5)
s1.pack(side = RIGHT, fill = Y)
f1.pack()
#button_to_clear_listbox
b2 = Button(frame, text="clear list", width=10, command=clear, background='white')
b2.pack(padx=5, pady=5)
#credits
credits = Label(frame, text = "coded with <3 by omnitrogen",background="white")
credits.pack(side = BOTTOM, padx=10, pady=10)
#quit_button
quitButton = Button(frame, text="quit", width=10, command=frame.quit, background='white')
quitButton.pack(side = BOTTOM)
canvas.create_window(0, 0, anchor=NW, window=frame)
frame.update_idletasks()
canvas.config(scrollregion=canvas.bbox("all"))
mainloop()
| 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]
l = rotor2.index(k)
m = alphabetList[l]
n = rotor1.index(m)
o = alphabetList[n]
s.append(o)
if (i+1) % 1 == 0:
rotationRotor(rotor1)
if (i+1) % 26 == 0:
rotationRotor(rotor2)
if (i+1) % 676 == 0:
rotationRotor(rotor3)
| 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 writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {Request, Response} from 'koa';
import {describe, it} from 'mocha';
import {koaRequestInformationExtractor} from '../../../src/request-extractors/koa';
import {Fuzzer} from '../../../utils/fuzzer';
import {deepStrictEqual} from '../../util';
describe('koaRequestInformationExtractor', () => {
describe('Behaviour under invalid input', () => {
it('Should produce a default value', () => {
const DEFAULT_RETURN_VALUE = {
method: '',
url: '',
userAgent: '',
referrer: '',
statusCode: 0,
remoteAddress: '',
};
const f = new Fuzzer();
const cbFn = (value: {}) => {
deepStrictEqual(value, DEFAULT_RETURN_VALUE);
};
f.fuzzFunctionForTypes(
koaRequestInformationExtractor,
['object', 'object'],
cbFn
);
});
});
describe('Behaviour under valid input', () => {
it('Should produce the expected value', () => {
const FULL_REQ_DERIVATION_VALUE = {
method: 'STUB_METHOD',
url: 'www.TEST-URL.com',
headers: {
'user-agent': 'Something like Mozilla',
referrer: 'www.ANOTHER-TEST.com',
}, | 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.0.0.0',
statusCode: 200,
};
deepStrictEqual(
koaRequestInformationExtractor(
FULL_REQ_DERIVATION_VALUE as unknown as Request,
FULL_RES_DERIVATION_VALUE as Response
),
FULL_REQ_EXPECTED_VALUE
);
});
});
}); | 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.mgmtRequestAsync("plugin/" + cmd, data)
};
}
export function deploymentKey(): string {
var mg = mgmtUrl("")
var m = mg ? mg.match(/^.*?\/-tdevmgmt-\/([a-z0-9]+)$/) : undefined;
return m ? m[1] : undefined;
}
export function url(): string {
var mg = mgmtUrl("")
var m = mg ? mg.match(/^(.*?\/)-tdevmgmt-\/[a-z0-9]+$/) : undefined;
return m ? m[1] : undefined;
}
export function mgmtUrl(path: string): string |
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 = undefined;
export function runShellAsync(data: any): Promise {
Util.log('shell run {0}', JSON.stringify(data));
if (lastShell) {
Util.log('killing previous shell process');
lastShell.send(JSON.stringify({ op: "kill" }));
lastShell.close();
lastShell = undefined;
}
var res = new PromiseInv()
var wsurl = mgmtUrl("").replace(/^http/, "ws");
Util.log('shell socket: {0}', wsurl);
var ws = lastShell = new WebSocket(wsurl);
Util.log('socket created')
ws.onopen = () => {
data = Util.jsonClone(data)
data.op = "shell"
ws.send(JSON.stringify(data))
}
ws.onerror = e => {
if (res.isPending())
res.error(e);
}
ws.onclose = e => {
if (res.isPending())
res.error("shell connection closed")
}
var stdout: string[] = []; var stdoutbuf = "";
var stderr: string[] = []; var stderrbuf = "";
ws.onmessage = msg => {
var d = JSON.parse(msg.data)
if (d.op == "stdout") {
stdout.push(d.data)
// characters may come letter by letter...
stdoutbuf += d.data;
if (/\r?\n$/.test(stdoutbuf)) {
stdoutbuf.split(/\r?\n/).filter(s => !!s).forEach(s => RT.App.logEvent(RT.App.DEBUG, "", s, undefined))
stdoutbuf = ""
}
} else if (d.op == "stderr") {
stderr.push(d.data)
stderrbuf += d.data;
if (/\r?\n$/.test(stderrbuf)) {
stderrbuf.split(/\r?\n/).filter(s => !!s).forEach(s => RT.App.logEvent(RT.App.WARNING, "", s, undefined))
stderrbuf = ""
}
} else if (d.op == "error") {
RT.App.logEvent(RT.App.ERROR, "", d.message, undefined)
if (res.isPending())
res.error(d.message)
ws.close()
lastShell = undefined;
} else if (d.op == "exit") {
RT.App.logEvent(d.code == 0 ? RT.App.INFO : RT.App.WARNING, "", "exited with " + d.code, undefined)
if (res.isPending())
res.success({
stdout: stdout.join(""),
stderr: stderr.join(""),
code: d.code,
})
ws.close()
lastShell = undefined;
}
}
return res
}
}
}
| {
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 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 url {0}', baseUrl);
return null
}
var r = m[1] + "-tdevmgmt-/" + tok + path
Util.log('shell: mgmturl {0}', r);
return r
} | 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.mgmtRequestAsync("plugin/" + cmd, data)
};
}
export function deploymentKey(): string {
var mg = mgmtUrl("")
var m = mg ? mg.match(/^.*?\/-tdevmgmt-\/([a-z0-9]+)$/) : undefined;
return m ? m[1] : undefined;
}
export function url(): string {
var mg = mgmtUrl("")
var m = mg ? mg.match(/^(.*?\/)-tdevmgmt-\/[a-z0-9]+$/) : undefined;
return m ? m[1] : undefined;
}
export function mgmtUrl(path: string): string {
if (path && !/^\//.test(path)) path = "/" + path
var localProxy = window.localStorage.getItem("local_proxy")
if (localProxy) |
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 url {0}', baseUrl);
return null
}
var r = m[1] + "-tdevmgmt-/" + tok + path
Util.log('shell: mgmturl {0}', r);
return r
}
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 = undefined;
export function runShellAsync(data: any): Promise {
Util.log('shell run {0}', JSON.stringify(data));
if (lastShell) {
Util.log('killing previous shell process');
lastShell.send(JSON.stringify({ op: "kill" }));
lastShell.close();
lastShell = undefined;
}
var res = new PromiseInv()
var wsurl = mgmtUrl("").replace(/^http/, "ws");
Util.log('shell socket: {0}', wsurl);
var ws = lastShell = new WebSocket(wsurl);
Util.log('socket created')
ws.onopen = () => {
data = Util.jsonClone(data)
data.op = "shell"
ws.send(JSON.stringify(data))
}
ws.onerror = e => {
if (res.isPending())
res.error(e);
}
ws.onclose = e => {
if (res.isPending())
res.error("shell connection closed")
}
var stdout: string[] = []; var stdoutbuf = "";
var stderr: string[] = []; var stderrbuf = "";
ws.onmessage = msg => {
var d = JSON.parse(msg.data)
if (d.op == "stdout") {
stdout.push(d.data)
// characters may come letter by letter...
stdoutbuf += d.data;
if (/\r?\n$/.test(stdoutbuf)) {
stdoutbuf.split(/\r?\n/).filter(s => !!s).forEach(s => RT.App.logEvent(RT.App.DEBUG, "", s, undefined))
stdoutbuf = ""
}
} else if (d.op == "stderr") {
stderr.push(d.data)
stderrbuf += d.data;
if (/\r?\n$/.test(stderrbuf)) {
stderrbuf.split(/\r?\n/).filter(s => !!s).forEach(s => RT.App.logEvent(RT.App.WARNING, "", s, undefined))
stderrbuf = ""
}
} else if (d.op == "error") {
RT.App.logEvent(RT.App.ERROR, "", d.message, undefined)
if (res.isPending())
res.error(d.message)
ws.close()
lastShell = undefined;
} else if (d.op == "exit") {
RT.App.logEvent(d.code == 0 ? RT.App.INFO : RT.App.WARNING, "", "exited with " + d.code, undefined)
if (res.isPending())
res.success({
stdout: stdout.join(""),
stderr: stderr.join(""),
code: d.code,
})
ws.close()
lastShell = undefined;
}
}
return res
}
}
}
| {
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.mgmtRequestAsync("plugin/" + cmd, data)
};
}
export function deploymentKey(): string {
var mg = mgmtUrl("")
var m = mg ? mg.match(/^.*?\/-tdevmgmt-\/([a-z0-9]+)$/) : undefined;
return m ? m[1] : undefined;
}
export function url(): string {
var mg = mgmtUrl("")
var m = mg ? mg.match(/^(.*?\/)-tdevmgmt-\/[a-z0-9]+$/) : undefined;
return m ? m[1] : undefined;
}
export function mgmtUrl(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
}
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 url {0}', baseUrl);
return null
}
var r = m[1] + "-tdevmgmt-/" + tok + path
Util.log('shell: mgmturl {0}', r);
return r
}
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 = undefined;
export function runShellAsync(data: any): Promise {
Util.log('shell run {0}', JSON.stringify(data));
if (lastShell) {
Util.log('killing previous shell process');
lastShell.send(JSON.stringify({ op: "kill" }));
lastShell.close();
lastShell = undefined;
}
var res = new PromiseInv()
var wsurl = mgmtUrl("").replace(/^http/, "ws");
Util.log('shell socket: {0}', wsurl);
var ws = lastShell = new WebSocket(wsurl);
Util.log('socket created')
ws.onopen = () => {
data = Util.jsonClone(data)
data.op = "shell"
ws.send(JSON.stringify(data))
}
ws.onerror = e => {
if (res.isPending())
res.error(e);
}
ws.onclose = e => {
if (res.isPending())
res.error("shell connection closed")
}
var stdout: string[] = []; var stdoutbuf = "";
var stderr: string[] = []; var stderrbuf = "";
ws.onmessage = msg => {
var d = JSON.parse(msg.data)
if (d.op == "stdout") {
stdout.push(d.data)
// characters may come letter by letter...
stdoutbuf += d.data;
if (/\r?\n$/.test(stdoutbuf)) {
stdoutbuf.split(/\r?\n/).filter(s => !!s).forEach(s => RT.App.logEvent(RT.App.DEBUG, "", s, undefined))
stdoutbuf = ""
}
} else if (d.op == "stderr") {
stderr.push(d.data)
stderrbuf += d.data;
if (/\r?\n$/.test(stderrbuf)) {
stderrbuf.split(/\r?\n/).filter(s => !!s).forEach(s => RT.App.logEvent(RT.App.WARNING, "", s, undefined))
stderrbuf = ""
}
} else if (d.op == "error") {
RT.App.logEvent(RT.App.ERROR, "", d.message, undefined)
if (res.isPending())
res.error(d.message)
ws.close()
lastShell = undefined;
} else if (d.op == "exit") {
RT.App.logEvent(d.code == 0 ? RT.App.INFO : RT.App.WARNING, "", "exited with " + d.code, undefined)
if (res.isPending())
res.success({
stdout: stdout.join(""),
stderr: stderr.join(""),
code: d.code,
})
ws.close()
lastShell = undefined;
}
}
return res
}
} | } | 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.mgmtRequestAsync("plugin/" + cmd, data)
};
}
export function deploymentKey(): string {
var mg = mgmtUrl("")
var m = mg ? mg.match(/^.*?\/-tdevmgmt-\/([a-z0-9]+)$/) : undefined;
return m ? m[1] : undefined;
}
export function url(): string {
var mg = mgmtUrl("")
var m = mg ? mg.match(/^(.*?\/)-tdevmgmt-\/[a-z0-9]+$/) : undefined;
return m ? m[1] : undefined;
}
export function | (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
}
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 url {0}', baseUrl);
return null
}
var r = m[1] + "-tdevmgmt-/" + tok + path
Util.log('shell: mgmturl {0}', r);
return r
}
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 = undefined;
export function runShellAsync(data: any): Promise {
Util.log('shell run {0}', JSON.stringify(data));
if (lastShell) {
Util.log('killing previous shell process');
lastShell.send(JSON.stringify({ op: "kill" }));
lastShell.close();
lastShell = undefined;
}
var res = new PromiseInv()
var wsurl = mgmtUrl("").replace(/^http/, "ws");
Util.log('shell socket: {0}', wsurl);
var ws = lastShell = new WebSocket(wsurl);
Util.log('socket created')
ws.onopen = () => {
data = Util.jsonClone(data)
data.op = "shell"
ws.send(JSON.stringify(data))
}
ws.onerror = e => {
if (res.isPending())
res.error(e);
}
ws.onclose = e => {
if (res.isPending())
res.error("shell connection closed")
}
var stdout: string[] = []; var stdoutbuf = "";
var stderr: string[] = []; var stderrbuf = "";
ws.onmessage = msg => {
var d = JSON.parse(msg.data)
if (d.op == "stdout") {
stdout.push(d.data)
// characters may come letter by letter...
stdoutbuf += d.data;
if (/\r?\n$/.test(stdoutbuf)) {
stdoutbuf.split(/\r?\n/).filter(s => !!s).forEach(s => RT.App.logEvent(RT.App.DEBUG, "", s, undefined))
stdoutbuf = ""
}
} else if (d.op == "stderr") {
stderr.push(d.data)
stderrbuf += d.data;
if (/\r?\n$/.test(stderrbuf)) {
stderrbuf.split(/\r?\n/).filter(s => !!s).forEach(s => RT.App.logEvent(RT.App.WARNING, "", s, undefined))
stderrbuf = ""
}
} else if (d.op == "error") {
RT.App.logEvent(RT.App.ERROR, "", d.message, undefined)
if (res.isPending())
res.error(d.message)
ws.close()
lastShell = undefined;
} else if (d.op == "exit") {
RT.App.logEvent(d.code == 0 ? RT.App.INFO : RT.App.WARNING, "", "exited with " + d.code, undefined)
if (res.isPending())
res.success({
stdout: stdout.join(""),
stderr: stderr.join(""),
code: d.code,
})
ws.close()
lastShell = undefined;
}
}
return res
}
}
}
| 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::{SizeCache, View};
use crate::{Printer, Vec2, With, XY};
// Content type used internally for caching and storage
type InnerContentType = Arc<StyledString>;
/// Provides access to the content of a [`TextView`].
///
/// [`TextView`]: struct.TextView.html
///
/// Cloning this object will still point to the same content.
///
/// # Examples
///
/// ```rust
/// # use cursive_core::views::{TextView, TextContent};
/// let mut content = TextContent::new("content");
/// let view = TextView::new_with_content(content.clone());
///
/// // Later, possibly in a different thread
/// content.set_content("new content");
/// assert!(view.get_content().source().contains("new"));
/// ```
#[derive(Clone)]
pub struct TextContent {
content: Arc<Mutex<TextContentInner>>,
}
impl TextContent {
/// Creates a new text content around the given value.
///
/// Parses the given value.
pub fn new<S>(content: S) -> Self
where
S: Into<StyledString>,
{
let content = Arc::new(content.into());
TextContent {
content: Arc::new(Mutex::new(TextContentInner {
content_value: content,
content_cache: Arc::new(StyledString::default()),
size_cache: None,
})),
}
}
}
/// A reference to the text content.
///
/// This can be deref'ed into a [`StyledString`].
///
/// [`StyledString`]: ../utils/markup/type.StyledString.html
///
/// This keeps the content locked. Do not store this!
pub struct TextContentRef {
_handle: OwningHandle<
ArcRef<Mutex<TextContentInner>>,
MutexGuard<'static, TextContentInner>,
>,
// 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 the content with the given value.
pub fn set_content<S>(&self, content: S)
where
S: Into<StyledString>,
{
self.with_content(|c| {
*Arc::make_mut(&mut c.content_value) = content.into();
});
}
/// Append `content` to the end of a `TextView`.
pub fn append<S>(&self, content: S)
where
S: Into<StyledString>,
{
self.with_content(|c| {
// This will only clone content if content_cached and content_value
// are sharing the same underlying Rc.
Arc::make_mut(&mut c.content_value).append(content);
})
}
/// Returns a reference to the content.
///
/// This locks the data while the returned value is alive,
/// so don't keep it too long.
pub fn get_content(&self) -> TextContentRef {
TextContentInner::get_content(&self.content)
}
/// Apply the given closure to the inner content, and bust the cache afterward.
fn with_content<F, O>(&self, f: F) -> O
where
F: FnOnce(&mut TextContentInner) -> O,
{
let mut content = self.content.lock().unwrap();
let out = f(&mut content);
content.size_cache = None;
out
}
}
/// Internel representation of the content for a `TextView`.
///
/// This is mostly just a `StyledString`.
///
/// Can be shared (through a `Arc<Mutex>`).
struct TextContentInner {
// content: String,
content_value: InnerContentType,
content_cache: InnerContentType,
// We keep the cache here so it can be busted when we change the content.
size_cache: Option<XY<SizeCache>>,
}
impl TextContentInner {
/// From a shareable content (Arc + Mutex), return a
fn get_content(content: &Arc<Mutex<TextContentInner>>) -> TextContentRef {
let arc_ref: ArcRef<Mutex<TextContentInner>> =
ArcRef::new(Arc::clone(content));
let _handle = OwningHandle::new_with_fn(arc_ref, |mutex| unsafe {
(*mutex).lock().unwrap()
});
let data = Arc::clone(&_handle.content_value);
TextContentRef { _handle, data }
}
fn is_cache_valid(&self, size: Vec2) -> bool {
match self.size_cache {
None => false,
Some(ref last) => last.x.accept(size.x) && last.y.accept(size.y),
}
}
fn get_cache(&self) -> &InnerContentType {
&self.content_cache
}
}
/// A simple view showing a fixed text.
///
/// # Examples
///
/// ```rust
/// # use cursive_core::Cursive;
/// # use cursive_core::views::TextView;
/// let mut siv = Cursive::dummy();
///
/// siv.add_layer(TextView::new("Hello world!"));
/// ```
pub struct TextView {
// content: String,
content: TextContent,
rows: Vec<Row>,
align: Align,
// TODO: remove now that we have styled text?
effect: Effect,
// True if we can wrap long lines.
wrap: bool,
// ScrollBase make many scrolling-related things easier
last_size: Vec2,
width: Option<usize>,
}
impl TextView {
/// Creates a new TextView with the given content.
pub fn new<S>(content: S) -> Self
where
S: Into<StyledString>,
{
Self::new_with_content(TextContent::new(content))
}
/// Creates a new TextView using the given `TextContent`.
///
/// If you kept a clone of the given content, you'll be able to update it
/// remotely.
///
/// # Examples
///
/// ```rust
/// # use cursive_core::views::{TextView, TextContent};
/// let mut content = TextContent::new("content");
/// let view = TextView::new_with_content(content.clone());
///
/// // Later, possibly in a different thread
/// content.set_content("new content");
/// assert!(view.get_content().source().contains("new"));
/// ```
pub fn new_with_content(content: TextContent) -> Self {
TextView {
content,
effect: Effect::Simple,
rows: Vec::new(),
wrap: true,
align: Align::top_left(),
last_size: Vec2::zero(),
width: None,
}
}
/// Creates a new empty `TextView`.
pub fn empty() -> Self {
TextView::new("")
}
/// Sets the effect for the entire content.
pub fn set_effect(&mut self, effect: Effect) {
self.effect = effect;
}
/// Sets the effect for the entire content.
///
/// Chainable variant.
pub fn effect(self, effect: Effect) -> Self {
self.with(|s| s.set_effect(effect))
}
/// Disables content wrap for this view.
///
/// This may be useful if you want horizontal scrolling.
pub fn no_wrap(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 alignment for this view.
pub fn h_align(mut self, h: HAlign) -> Self {
self.align.h = h;
self
}
/// Sets the vertical alignment for this view.
pub fn v_align(mut self, v: VAlign) -> Self |
/// 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 text in this view.
///
/// Chainable variant.
pub fn content<S>(self, content: S) -> Self
where
S: Into<StyledString>,
{
self.with(|s| s.set_content(content))
}
/// Replace the text in this view.
pub fn set_content<S>(&mut self, content: S)
where
S: Into<StyledString>,
{
self.content.set_content(content);
}
/// Append `content` to the end of a `TextView`.
pub fn append<S>(&mut self, content: S)
where
S: Into<StyledString>,
{
self.content.append(content);
}
/// Returns the current text in this view.
pub fn get_content(&self) -> TextContentRef {
TextContentInner::get_content(&self.content.content)
}
/// Returns a shared reference to the content, allowing content mutation.
pub fn get_shared_content(&mut self) -> TextContent {
// We take &mut here without really needing it,
// because it sort of "makes sense".
TextContent {
content: Arc::clone(&self.content.content),
}
}
// This must be non-destructive, as it may be called
// multiple times during layout.
fn compute_rows(&mut self, size: Vec2) {
let size = if self.wrap { size } else { Vec2::max_value() };
let mut content = self.content.content.lock().unwrap();
if content.is_cache_valid(size) {
return;
}
// Completely bust the cache
// Just in case we fail, we don't want to leave a bad cache.
content.size_cache = None;
content.content_cache = Arc::clone(&content.content_value);
if size.x == 0 {
// Nothing we can do at this point.
return;
}
self.rows =
LinesIterator::new(content.get_cache().as_ref(), size.x).collect();
// Desired width
self.width = self.rows.iter().map(|row| row.width).max();
}
}
impl View for TextView {
fn draw(&self, printer: &Printer) {
let h = self.rows.len();
// If the content is smaller than the view, align it somewhere.
let offset = self.align.v.get_offset(h, printer.size.y);
let printer = &printer.offset((0, offset));
let content = self.content.content.lock().unwrap();
printer.with_effect(self.effect, |printer| {
for (y, row) in self.rows.iter().enumerate() {
let l = row.width;
let mut x = self.align.h.get_offset(l, printer.size.x);
for span in row.resolve(content.get_cache().as_ref()) {
printer.with_style(*span.attr, |printer| {
printer.print((x, y), span.content);
x += span.content.width();
});
}
}
});
}
fn needs_relayout(&self) -> bool {
let content = self.content.content.lock().unwrap();
content.size_cache.is_none()
}
fn required_size(&mut self, size: Vec2) -> Vec2 {
self.compute_rows(size);
Vec2::new(self.width.unwrap_or(0), self.rows.len())
}
fn layout(&mut self, size: Vec2) {
// Compute the text rows.
self.last_size = size;
self.compute_rows(size);
// The entire "virtual" size (includes all rows)
let my_size = Vec2::new(self.width.unwrap_or(0), self.rows.len());
// Build a fresh cache.
let mut content = self.content.content.lock().unwrap();
content.size_cache = Some(SizeCache::build(my_size, size));
}
}
| {
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::{SizeCache, View};
use crate::{Printer, Vec2, With, XY};
// Content type used internally for caching and storage
type InnerContentType = Arc<StyledString>;
/// Provides access to the content of a [`TextView`].
///
/// [`TextView`]: struct.TextView.html
///
/// Cloning this object will still point to the same content.
///
/// # Examples
///
/// ```rust
/// # use cursive_core::views::{TextView, TextContent};
/// let mut content = TextContent::new("content");
/// let view = TextView::new_with_content(content.clone());
///
/// // Later, possibly in a different thread
/// content.set_content("new content");
/// assert!(view.get_content().source().contains("new"));
/// ```
#[derive(Clone)]
pub struct TextContent {
content: Arc<Mutex<TextContentInner>>,
}
impl TextContent {
/// Creates a new text content around the given value.
///
/// Parses the given value.
pub fn new<S>(content: S) -> Self
where
S: Into<StyledString>,
{
let content = Arc::new(content.into());
TextContent {
content: Arc::new(Mutex::new(TextContentInner {
content_value: content,
content_cache: Arc::new(StyledString::default()),
size_cache: None,
})),
}
}
}
/// A reference to the text content.
///
/// This can be deref'ed into a [`StyledString`].
///
/// [`StyledString`]: ../utils/markup/type.StyledString.html
///
/// This keeps the content locked. Do not store this!
pub struct TextContentRef {
_handle: OwningHandle<
ArcRef<Mutex<TextContentInner>>,
MutexGuard<'static, TextContentInner>,
>,
// 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 the content with the given value.
pub fn set_content<S>(&self, content: S)
where
S: Into<StyledString>,
{
self.with_content(|c| {
*Arc::make_mut(&mut c.content_value) = content.into();
});
}
/// Append `content` to the end of a `TextView`.
pub fn append<S>(&self, content: S)
where
S: Into<StyledString>,
{
self.with_content(|c| {
// This will only clone content if content_cached and content_value
// are sharing the same underlying Rc.
Arc::make_mut(&mut c.content_value).append(content);
})
}
/// Returns a reference to the content.
///
/// This locks the data while the returned value is alive,
/// so don't keep it too long.
pub fn get_content(&self) -> TextContentRef {
TextContentInner::get_content(&self.content)
}
/// Apply the given closure to the inner content, and bust the cache afterward.
fn with_content<F, O>(&self, f: F) -> O
where
F: FnOnce(&mut TextContentInner) -> O,
{
let mut content = self.content.lock().unwrap();
let out = f(&mut content);
content.size_cache = None;
out
}
}
/// Internel representation of the content for a `TextView`.
///
/// This is mostly just a `StyledString`.
///
/// Can be shared (through a `Arc<Mutex>`).
struct TextContentInner {
// content: String,
content_value: InnerContentType,
content_cache: InnerContentType,
// We keep the cache here so it can be busted when we change the content.
size_cache: Option<XY<SizeCache>>,
}
impl TextContentInner {
/// From a shareable content (Arc + Mutex), return a
fn get_content(content: &Arc<Mutex<TextContentInner>>) -> TextContentRef {
let arc_ref: ArcRef<Mutex<TextContentInner>> =
ArcRef::new(Arc::clone(content));
let _handle = OwningHandle::new_with_fn(arc_ref, |mutex| unsafe {
(*mutex).lock().unwrap()
});
let data = Arc::clone(&_handle.content_value);
TextContentRef { _handle, data }
}
fn is_cache_valid(&self, size: Vec2) -> bool {
match self.size_cache {
None => false,
Some(ref last) => last.x.accept(size.x) && last.y.accept(size.y),
}
}
fn get_cache(&self) -> &InnerContentType {
&self.content_cache
}
}
/// A simple view showing a fixed text.
///
/// # Examples
///
/// ```rust
/// # use cursive_core::Cursive;
/// # use cursive_core::views::TextView;
/// let mut siv = Cursive::dummy();
///
/// siv.add_layer(TextView::new("Hello world!"));
/// ```
pub struct TextView {
// content: String,
content: TextContent,
rows: Vec<Row>,
align: Align,
// TODO: remove now that we have styled text?
effect: Effect,
// True if we can wrap long lines.
wrap: bool,
// ScrollBase make many scrolling-related things easier
last_size: Vec2,
width: Option<usize>,
}
impl TextView {
/// Creates a new TextView with the given content.
pub fn new<S>(content: S) -> Self
where
S: Into<StyledString>,
{
Self::new_with_content(TextContent::new(content))
}
/// Creates a new TextView using the given `TextContent`.
///
/// If you kept a clone of the given content, you'll be able to update it
/// remotely.
///
/// # Examples
///
/// ```rust
/// # use cursive_core::views::{TextView, TextContent};
/// let mut content = TextContent::new("content");
/// let view = TextView::new_with_content(content.clone());
///
/// // Later, possibly in a different thread
/// content.set_content("new content");
/// assert!(view.get_content().source().contains("new"));
/// ```
pub fn new_with_content(content: TextContent) -> Self {
TextView {
content,
effect: Effect::Simple,
rows: Vec::new(),
wrap: true,
align: Align::top_left(),
last_size: Vec2::zero(),
width: None,
}
}
/// Creates a new empty `TextView`.
pub fn empty() -> Self {
TextView::new("")
}
/// Sets the effect for the entire content.
pub fn set_effect(&mut self, effect: Effect) {
self.effect = effect;
}
/// Sets the effect for the entire content.
///
/// Chainable variant.
pub fn effect(self, effect: Effect) -> Self {
self.with(|s| s.set_effect(effect))
}
/// Disables content wrap for this view.
///
/// This may be useful if you want horizontal scrolling.
pub fn | (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 alignment for this view.
pub fn h_align(mut self, h: HAlign) -> Self {
self.align.h = h;
self
}
/// Sets the vertical alignment for this view.
pub fn v_align(mut self, v: VAlign) -> Self {
self.align.v = v;
self
}
/// 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 text in this view.
///
/// Chainable variant.
pub fn content<S>(self, content: S) -> Self
where
S: Into<StyledString>,
{
self.with(|s| s.set_content(content))
}
/// Replace the text in this view.
pub fn set_content<S>(&mut self, content: S)
where
S: Into<StyledString>,
{
self.content.set_content(content);
}
/// Append `content` to the end of a `TextView`.
pub fn append<S>(&mut self, content: S)
where
S: Into<StyledString>,
{
self.content.append(content);
}
/// Returns the current text in this view.
pub fn get_content(&self) -> TextContentRef {
TextContentInner::get_content(&self.content.content)
}
/// Returns a shared reference to the content, allowing content mutation.
pub fn get_shared_content(&mut self) -> TextContent {
// We take &mut here without really needing it,
// because it sort of "makes sense".
TextContent {
content: Arc::clone(&self.content.content),
}
}
// This must be non-destructive, as it may be called
// multiple times during layout.
fn compute_rows(&mut self, size: Vec2) {
let size = if self.wrap { size } else { Vec2::max_value() };
let mut content = self.content.content.lock().unwrap();
if content.is_cache_valid(size) {
return;
}
// Completely bust the cache
// Just in case we fail, we don't want to leave a bad cache.
content.size_cache = None;
content.content_cache = Arc::clone(&content.content_value);
if size.x == 0 {
// Nothing we can do at this point.
return;
}
self.rows =
LinesIterator::new(content.get_cache().as_ref(), size.x).collect();
// Desired width
self.width = self.rows.iter().map(|row| row.width).max();
}
}
impl View for TextView {
fn draw(&self, printer: &Printer) {
let h = self.rows.len();
// If the content is smaller than the view, align it somewhere.
let offset = self.align.v.get_offset(h, printer.size.y);
let printer = &printer.offset((0, offset));
let content = self.content.content.lock().unwrap();
printer.with_effect(self.effect, |printer| {
for (y, row) in self.rows.iter().enumerate() {
let l = row.width;
let mut x = self.align.h.get_offset(l, printer.size.x);
for span in row.resolve(content.get_cache().as_ref()) {
printer.with_style(*span.attr, |printer| {
printer.print((x, y), span.content);
x += span.content.width();
});
}
}
});
}
fn needs_relayout(&self) -> bool {
let content = self.content.content.lock().unwrap();
content.size_cache.is_none()
}
fn required_size(&mut self, size: Vec2) -> Vec2 {
self.compute_rows(size);
Vec2::new(self.width.unwrap_or(0), self.rows.len())
}
fn layout(&mut self, size: Vec2) {
// Compute the text rows.
self.last_size = size;
self.compute_rows(size);
// The entire "virtual" size (includes all rows)
let my_size = Vec2::new(self.width.unwrap_or(0), self.rows.len());
// Build a fresh cache.
let mut content = self.content.content.lock().unwrap();
content.size_cache = Some(SizeCache::build(my_size, size));
}
}
| 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::{SizeCache, View};
use crate::{Printer, Vec2, With, XY};
// Content type used internally for caching and storage
type InnerContentType = Arc<StyledString>;
/// Provides access to the content of a [`TextView`].
///
/// [`TextView`]: struct.TextView.html
///
/// Cloning this object will still point to the same content.
///
/// # Examples
///
/// ```rust
/// # use cursive_core::views::{TextView, TextContent};
/// let mut content = TextContent::new("content");
/// let view = TextView::new_with_content(content.clone());
///
/// // Later, possibly in a different thread
/// content.set_content("new content");
/// assert!(view.get_content().source().contains("new"));
/// ```
#[derive(Clone)]
pub struct TextContent {
content: Arc<Mutex<TextContentInner>>,
}
impl TextContent {
/// Creates a new text content around the given value.
///
/// Parses the given value.
pub fn new<S>(content: S) -> Self
where
S: Into<StyledString>,
{
let content = Arc::new(content.into());
TextContent {
content: Arc::new(Mutex::new(TextContentInner {
content_value: content,
content_cache: Arc::new(StyledString::default()),
size_cache: None,
})),
}
}
}
/// A reference to the text content.
///
/// This can be deref'ed into a [`StyledString`].
///
/// [`StyledString`]: ../utils/markup/type.StyledString.html
///
/// This keeps the content locked. Do not store this!
pub struct TextContentRef {
_handle: OwningHandle< | >,
// 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 the content with the given value.
pub fn set_content<S>(&self, content: S)
where
S: Into<StyledString>,
{
self.with_content(|c| {
*Arc::make_mut(&mut c.content_value) = content.into();
});
}
/// Append `content` to the end of a `TextView`.
pub fn append<S>(&self, content: S)
where
S: Into<StyledString>,
{
self.with_content(|c| {
// This will only clone content if content_cached and content_value
// are sharing the same underlying Rc.
Arc::make_mut(&mut c.content_value).append(content);
})
}
/// Returns a reference to the content.
///
/// This locks the data while the returned value is alive,
/// so don't keep it too long.
pub fn get_content(&self) -> TextContentRef {
TextContentInner::get_content(&self.content)
}
/// Apply the given closure to the inner content, and bust the cache afterward.
fn with_content<F, O>(&self, f: F) -> O
where
F: FnOnce(&mut TextContentInner) -> O,
{
let mut content = self.content.lock().unwrap();
let out = f(&mut content);
content.size_cache = None;
out
}
}
/// Internel representation of the content for a `TextView`.
///
/// This is mostly just a `StyledString`.
///
/// Can be shared (through a `Arc<Mutex>`).
struct TextContentInner {
// content: String,
content_value: InnerContentType,
content_cache: InnerContentType,
// We keep the cache here so it can be busted when we change the content.
size_cache: Option<XY<SizeCache>>,
}
impl TextContentInner {
/// From a shareable content (Arc + Mutex), return a
fn get_content(content: &Arc<Mutex<TextContentInner>>) -> TextContentRef {
let arc_ref: ArcRef<Mutex<TextContentInner>> =
ArcRef::new(Arc::clone(content));
let _handle = OwningHandle::new_with_fn(arc_ref, |mutex| unsafe {
(*mutex).lock().unwrap()
});
let data = Arc::clone(&_handle.content_value);
TextContentRef { _handle, data }
}
fn is_cache_valid(&self, size: Vec2) -> bool {
match self.size_cache {
None => false,
Some(ref last) => last.x.accept(size.x) && last.y.accept(size.y),
}
}
fn get_cache(&self) -> &InnerContentType {
&self.content_cache
}
}
/// A simple view showing a fixed text.
///
/// # Examples
///
/// ```rust
/// # use cursive_core::Cursive;
/// # use cursive_core::views::TextView;
/// let mut siv = Cursive::dummy();
///
/// siv.add_layer(TextView::new("Hello world!"));
/// ```
pub struct TextView {
// content: String,
content: TextContent,
rows: Vec<Row>,
align: Align,
// TODO: remove now that we have styled text?
effect: Effect,
// True if we can wrap long lines.
wrap: bool,
// ScrollBase make many scrolling-related things easier
last_size: Vec2,
width: Option<usize>,
}
impl TextView {
/// Creates a new TextView with the given content.
pub fn new<S>(content: S) -> Self
where
S: Into<StyledString>,
{
Self::new_with_content(TextContent::new(content))
}
/// Creates a new TextView using the given `TextContent`.
///
/// If you kept a clone of the given content, you'll be able to update it
/// remotely.
///
/// # Examples
///
/// ```rust
/// # use cursive_core::views::{TextView, TextContent};
/// let mut content = TextContent::new("content");
/// let view = TextView::new_with_content(content.clone());
///
/// // Later, possibly in a different thread
/// content.set_content("new content");
/// assert!(view.get_content().source().contains("new"));
/// ```
pub fn new_with_content(content: TextContent) -> Self {
TextView {
content,
effect: Effect::Simple,
rows: Vec::new(),
wrap: true,
align: Align::top_left(),
last_size: Vec2::zero(),
width: None,
}
}
/// Creates a new empty `TextView`.
pub fn empty() -> Self {
TextView::new("")
}
/// Sets the effect for the entire content.
pub fn set_effect(&mut self, effect: Effect) {
self.effect = effect;
}
/// Sets the effect for the entire content.
///
/// Chainable variant.
pub fn effect(self, effect: Effect) -> Self {
self.with(|s| s.set_effect(effect))
}
/// Disables content wrap for this view.
///
/// This may be useful if you want horizontal scrolling.
pub fn no_wrap(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 alignment for this view.
pub fn h_align(mut self, h: HAlign) -> Self {
self.align.h = h;
self
}
/// Sets the vertical alignment for this view.
pub fn v_align(mut self, v: VAlign) -> Self {
self.align.v = v;
self
}
/// 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 text in this view.
///
/// Chainable variant.
pub fn content<S>(self, content: S) -> Self
where
S: Into<StyledString>,
{
self.with(|s| s.set_content(content))
}
/// Replace the text in this view.
pub fn set_content<S>(&mut self, content: S)
where
S: Into<StyledString>,
{
self.content.set_content(content);
}
/// Append `content` to the end of a `TextView`.
pub fn append<S>(&mut self, content: S)
where
S: Into<StyledString>,
{
self.content.append(content);
}
/// Returns the current text in this view.
pub fn get_content(&self) -> TextContentRef {
TextContentInner::get_content(&self.content.content)
}
/// Returns a shared reference to the content, allowing content mutation.
pub fn get_shared_content(&mut self) -> TextContent {
// We take &mut here without really needing it,
// because it sort of "makes sense".
TextContent {
content: Arc::clone(&self.content.content),
}
}
// This must be non-destructive, as it may be called
// multiple times during layout.
fn compute_rows(&mut self, size: Vec2) {
let size = if self.wrap { size } else { Vec2::max_value() };
let mut content = self.content.content.lock().unwrap();
if content.is_cache_valid(size) {
return;
}
// Completely bust the cache
// Just in case we fail, we don't want to leave a bad cache.
content.size_cache = None;
content.content_cache = Arc::clone(&content.content_value);
if size.x == 0 {
// Nothing we can do at this point.
return;
}
self.rows =
LinesIterator::new(content.get_cache().as_ref(), size.x).collect();
// Desired width
self.width = self.rows.iter().map(|row| row.width).max();
}
}
impl View for TextView {
fn draw(&self, printer: &Printer) {
let h = self.rows.len();
// If the content is smaller than the view, align it somewhere.
let offset = self.align.v.get_offset(h, printer.size.y);
let printer = &printer.offset((0, offset));
let content = self.content.content.lock().unwrap();
printer.with_effect(self.effect, |printer| {
for (y, row) in self.rows.iter().enumerate() {
let l = row.width;
let mut x = self.align.h.get_offset(l, printer.size.x);
for span in row.resolve(content.get_cache().as_ref()) {
printer.with_style(*span.attr, |printer| {
printer.print((x, y), span.content);
x += span.content.width();
});
}
}
});
}
fn needs_relayout(&self) -> bool {
let content = self.content.content.lock().unwrap();
content.size_cache.is_none()
}
fn required_size(&mut self, size: Vec2) -> Vec2 {
self.compute_rows(size);
Vec2::new(self.width.unwrap_or(0), self.rows.len())
}
fn layout(&mut self, size: Vec2) {
// Compute the text rows.
self.last_size = size;
self.compute_rows(size);
// The entire "virtual" size (includes all rows)
let my_size = Vec2::new(self.width.unwrap_or(0), self.rows.len());
// Build a fresh cache.
let mut content = self.content.content.lock().unwrap();
content.size_cache = Some(SizeCache::build(my_size, size));
}
} | 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, onMkdir);
});
function onMkdir(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 mkDirpAgain();
});
}
// tests that no errors are thrown if you mkdirp a bunch of dirs that exist
function mkDirpAgain(err, win) {
con.mkdirp(PATH, finish);
}
function finish(err) {
assert.ifError(err);
console.log('TEST PASSED!', __filename);
var dirs = [
'/mkdirp/test/path/of/death/n/destruction'
, '/mkdirp/test/path/of/death/n'
, '/mkdirp/test/path/of/death'
, '/mkdirp/test/path/of'
, '/mkdirp/test/path'
, '/mkdirp/test'
, '/mkdirp'
];
// can't easily delete the path, b/c haven't written rm -rf :)
async.series([
function (cb) { con.a_delete_(dirs[0], 0, normalizeCb(cb)); }
, function (cb) { con.a_delete_(dirs[1], 0, normalizeCb(cb)); }
, function (cb) { con.a_delete_(dirs[2], 0, normalizeCb(cb)); }
, function (cb) { con.a_delete_(dirs[3], 0, normalizeCb(cb)); }
, function (cb) { con.a_delete_(dirs[4], 0, normalizeCb(cb)); }
, 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 expects to be called like this:
// cb()
// to instead be called like this:
// cb(rc, error)
// and then have the original callback only be called with an Error, or
// nothing at all if there was no Error.
function normalizeCb(callback) {
return function(rc, error) {
if(!callback) return;
if(rc != 0) {
return callback(new Error('Zookeeper Error: code='+rc+' '+error));
}
return callback(null, true);
};
}
}
| {
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.timeout && typeof(options.timeout) !== 'number')
throw new TypeError('options.timeout (Number) required');
if(typeof(callback) !== 'function')
throw new TypeError('callback (Function) required');
var log = options.log4js.getLogger('mkdirp-test');
var zkLogLevel = ZK.ZOO_LOG_LEVEL_WARNING;
if(log.isTraceEnabled())
zkLogLevel = ZK.ZOO_LOG_LEVEL_DEBUG;
var zk = new ZK({
connect: options.zookeeper,
timeout: options.timeout || 1000,
debug_level: zkLogLevel,
host_order_deterministic: false
});
log.debug('connecting to zookeeper');
return zk.connect(function(err) {
if(err)
return callback(err);
log.debug('connected to zookeeper.');
return callback && callback(null, zk);
});
} | 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')
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.timeout && typeof(options.timeout) !== 'number')
throw new TypeError('options.timeout (Number) required');
if(typeof(callback) !== 'function')
throw new TypeError('callback (Function) required');
var log = options.log4js.getLogger('mkdirp-test');
var zkLogLevel = ZK.ZOO_LOG_LEVEL_WARNING;
if(log.isTraceEnabled())
zkLogLevel = ZK.ZOO_LOG_LEVEL_DEBUG;
var zk = new ZK({
connect: options.zookeeper,
timeout: options.timeout || 1000,
debug_level: zkLogLevel,
host_order_deterministic: false
});
log.debug('connecting to zookeeper');
return zk.connect(function(err) {
if(err)
return callback(err);
log.debug('connected to zookeeper.');
return callback && callback(null, zk);
});
}
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, onMkdir);
});
function onMkdir(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 mkDirpAgain();
});
}
// tests that no errors are thrown if you mkdirp a bunch of dirs that exist
function mkDirpAgain(err, win) {
con.mkdirp(PATH, finish);
}
function finish(err) {
assert.ifError(err);
console.log('TEST PASSED!', __filename);
var dirs = [
'/mkdirp/test/path/of/death/n/destruction'
, '/mkdirp/test/path/of/death/n'
, '/mkdirp/test/path/of/death'
, '/mkdirp/test/path/of'
, '/mkdirp/test/path'
, '/mkdirp/test'
, '/mkdirp'
];
// can't easily delete the path, b/c haven't written rm -rf :)
async.series([
function (cb) { con.a_delete_(dirs[0], 0, normalizeCb(cb)); }
, function (cb) { con.a_delete_(dirs[1], 0, normalizeCb(cb)); }
, function (cb) { con.a_delete_(dirs[2], 0, normalizeCb(cb)); } | , 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 expects to be called like this:
// cb()
// to instead be called like this:
// cb(rc, error)
// and then have the original callback only be called with an Error, or
// nothing at all if there was no Error.
function normalizeCb(callback) {
return function(rc, error) {
if(!callback) return;
if(rc != 0) {
return callback(new Error('Zookeeper Error: code='+rc+' '+error));
}
return callback(null, true);
};
}
} | , 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')
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.timeout && typeof(options.timeout) !== 'number')
throw new TypeError('options.timeout (Number) required');
if(typeof(callback) !== 'function')
throw new TypeError('callback (Function) required');
var log = options.log4js.getLogger('mkdirp-test');
var zkLogLevel = ZK.ZOO_LOG_LEVEL_WARNING;
if(log.isTraceEnabled())
zkLogLevel = ZK.ZOO_LOG_LEVEL_DEBUG;
var zk = new ZK({
connect: options.zookeeper,
timeout: options.timeout || 1000,
debug_level: zkLogLevel,
host_order_deterministic: false
});
log.debug('connecting to zookeeper');
return zk.connect(function(err) {
if(err)
return callback(err);
log.debug('connected to zookeeper.');
return callback && callback(null, zk);
});
}
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, onMkdir);
});
function | (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 mkDirpAgain();
});
}
// tests that no errors are thrown if you mkdirp a bunch of dirs that exist
function mkDirpAgain(err, win) {
con.mkdirp(PATH, finish);
}
function finish(err) {
assert.ifError(err);
console.log('TEST PASSED!', __filename);
var dirs = [
'/mkdirp/test/path/of/death/n/destruction'
, '/mkdirp/test/path/of/death/n'
, '/mkdirp/test/path/of/death'
, '/mkdirp/test/path/of'
, '/mkdirp/test/path'
, '/mkdirp/test'
, '/mkdirp'
];
// can't easily delete the path, b/c haven't written rm -rf :)
async.series([
function (cb) { con.a_delete_(dirs[0], 0, normalizeCb(cb)); }
, function (cb) { con.a_delete_(dirs[1], 0, normalizeCb(cb)); }
, function (cb) { con.a_delete_(dirs[2], 0, normalizeCb(cb)); }
, function (cb) { con.a_delete_(dirs[3], 0, normalizeCb(cb)); }
, function (cb) { con.a_delete_(dirs[4], 0, normalizeCb(cb)); }
, 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 expects to be called like this:
// cb()
// to instead be called like this:
// cb(rc, error)
// and then have the original callback only be called with an Error, or
// nothing at all if there was no Error.
function normalizeCb(callback) {
return function(rc, error) {
if(!callback) return;
if(rc != 0) {
return callback(new Error('Zookeeper Error: code='+rc+' '+error));
}
return callback(null, true);
};
}
}
| 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 */
'use strict';
angular.module('gantt.resizeSensor', ['gantt']).directive('ganttResizeSensor', [function() {
return {
restrict: 'E',
require: '^gantt',
scope: {
enabled: '=?'
},
link: function(scope, element, attrs, ganttCtrl) {
var api = ganttCtrl.gantt.api;
// Load options from global options attribute.
if (scope.options && typeof(scope.options.progress) === 'object') {
for (var option in scope.options.progress) {
scope[option] = scope.options[option];
}
}
if (scope.enabled === undefined) {
scope.enabled = true;
}
function buildSensor() { |
var rendered = false;
api.core.on.rendered(scope, function() {
rendered = true;
if (sensor !== undefined) {
sensor.detach();
}
if (scope.enabled) {
ElementQueries.update();
sensor = buildSensor();
}
});
var sensor;
scope.$watch('enabled', function(newValue) {
if (rendered) {
if (newValue && sensor === undefined) {
ElementQueries.update();
sensor = buildSensor();
} else if (!newValue && sensor !== undefined) {
sensor.detach();
sensor = undefined;
}
}
});
}
};
}]);
}());
angular.module('gantt.resizeSensor.templates', []).run(['$templateCache', function($templateCache) {
}]);
//# sourceMappingURL=angular-gantt-resizeSensor-plugin.js.map |
var ganttElement = element.parent().parent().parent()[0].querySelectorAll('div.gantt')[0];
return new ResizeSensor(ganttElement, function() {
ganttCtrl.gantt.$scope.ganttElementWidth = ganttElement.clientWidth;
ganttCtrl.gantt.$scope.$apply();
});
}
| 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 */
'use strict';
angular.module('gantt.resizeSensor', ['gantt']).directive('ganttResizeSensor', [function() {
return {
restrict: 'E',
require: '^gantt',
scope: {
enabled: '=?'
},
link: function(scope, element, attrs, ganttCtrl) {
var api = ganttCtrl.gantt.api;
// Load options from global options attribute.
if (scope.options && typeof(scope.options.progress) === 'object') {
for (var option in scope.options.progress) {
scope[option] = scope.options[option];
}
}
if (scope.enabled === undefined) {
scope.enabled = true;
}
function b | ) {
var ganttElement = element.parent().parent().parent()[0].querySelectorAll('div.gantt')[0];
return new ResizeSensor(ganttElement, function() {
ganttCtrl.gantt.$scope.ganttElementWidth = ganttElement.clientWidth;
ganttCtrl.gantt.$scope.$apply();
});
}
var rendered = false;
api.core.on.rendered(scope, function() {
rendered = true;
if (sensor !== undefined) {
sensor.detach();
}
if (scope.enabled) {
ElementQueries.update();
sensor = buildSensor();
}
});
var sensor;
scope.$watch('enabled', function(newValue) {
if (rendered) {
if (newValue && sensor === undefined) {
ElementQueries.update();
sensor = buildSensor();
} else if (!newValue && sensor !== undefined) {
sensor.detach();
sensor = undefined;
}
}
});
}
};
}]);
}());
angular.module('gantt.resizeSensor.templates', []).run(['$templateCache', function($templateCache) {
}]);
//# sourceMappingURL=angular-gantt-resizeSensor-plugin.js.map | 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 */
'use strict';
angular.module('gantt.resizeSensor', ['gantt']).directive('ganttResizeSensor', [function() {
return {
restrict: 'E',
require: '^gantt',
scope: {
enabled: '=?'
},
link: function(scope, element, attrs, ganttCtrl) {
var api = ganttCtrl.gantt.api;
// Load options from global options attribute.
if (scope.options && typeof(scope.options.progress) === 'object') {
for (var option in scope.options.progress) {
scope[option] = scope.options[option];
}
}
if (scope.enabled === undefined) {
scope.enabled = true;
}
function buildSensor() {
var ganttElement = element.parent().parent().parent()[0].querySelectorAll('div.gantt')[0];
return new ResizeSensor(ganttElement, function() {
ganttCtrl.gantt.$scope.ganttElementWidth = ganttElement.clientWidth;
ganttCtrl.gantt.$scope.$apply();
});
}
var rendered = false;
api.core.on.rendered(scope, function() {
rendered = true;
if (sensor !== undefined) { | if (scope.enabled) {
ElementQueries.update();
sensor = buildSensor();
}
});
var sensor;
scope.$watch('enabled', function(newValue) {
if (rendered) {
if (newValue && sensor === undefined) {
ElementQueries.update();
sensor = buildSensor();
} else if (!newValue && sensor !== undefined) {
sensor.detach();
sensor = undefined;
}
}
});
}
};
}]);
}());
angular.module('gantt.resizeSensor.templates', []).run(['$templateCache', function($templateCache) {
}]);
//# sourceMappingURL=angular-gantt-resizeSensor-plugin.js.map |
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 */
'use strict'; | restrict: 'E',
require: '^gantt',
scope: {
enabled: '=?'
},
link: function(scope, element, attrs, ganttCtrl) {
var api = ganttCtrl.gantt.api;
// Load options from global options attribute.
if (scope.options && typeof(scope.options.progress) === 'object') {
for (var option in scope.options.progress) {
scope[option] = scope.options[option];
}
}
if (scope.enabled === undefined) {
scope.enabled = true;
}
function buildSensor() {
var ganttElement = element.parent().parent().parent()[0].querySelectorAll('div.gantt')[0];
return new ResizeSensor(ganttElement, function() {
ganttCtrl.gantt.$scope.ganttElementWidth = ganttElement.clientWidth;
ganttCtrl.gantt.$scope.$apply();
});
}
var rendered = false;
api.core.on.rendered(scope, function() {
rendered = true;
if (sensor !== undefined) {
sensor.detach();
}
if (scope.enabled) {
ElementQueries.update();
sensor = buildSensor();
}
});
var sensor;
scope.$watch('enabled', function(newValue) {
if (rendered) {
if (newValue && sensor === undefined) {
ElementQueries.update();
sensor = buildSensor();
} else if (!newValue && sensor !== undefined) {
sensor.detach();
sensor = undefined;
}
}
});
}
};
}]);
}());
angular.module('gantt.resizeSensor.templates', []).run(['$templateCache', function($templateCache) {
}]);
//# sourceMappingURL=angular-gantt-resizeSensor-plugin.js.map | 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Issue #2263.
// Here, `f` is a function that takes a pointer `x` and a function
// `g`, where `g` requires its argument `y` to be in the same region
// that `x` is in. | 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Issue #2263.
// Here, `f` is a function that takes a pointer `x` and a function
// `g`, where `g` requires its argument `y` to be in the same region
// that `x` is in.
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 | 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Issue #2263.
// Here, `f` is a function that takes a pointer `x` and a function
// `g`, where `g` requires its argument `y` to be in the same region
// that `x` is in.
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() {
}
| {
} | 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 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import tabs
from neutronclient.common import exceptions as neutron_exc
from openstack_dashboard.api import keystone
from openstack_dashboard.api import network
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_security.\
keypairs.tables import KeypairsTable
from openstack_dashboard.dashboards.project.access_and_security.\
security_groups.tables import SecurityGroupsTable
class SecurityGroupsTab(tabs.TableTab):
table_classes = (SecurityGroupsTable,)
name = _("Security Groups")
slug = "security_groups_tab"
template_name = "horizon/common/_detail_table.html"
permissions = ('openstack.services.compute',)
def get_security_groups_data(self):
try:
security_groups = network.security_group_list(self.request)
except neutron_exc.ConnectionFailed:
security_groups = []
exceptions.handle(self.request)
except Exception:
security_groups = []
exceptions.handle(self.request,
_('Unable to retrieve security groups.'))
return sorted(security_groups, key=lambda group: group.name)
class KeypairsTab(tabs.TableTab):
table_classes = (KeypairsTable,)
name = _("Key Pairs")
slug = "keypairs_tab"
template_name = "horizon/common/_detail_table.html"
permissions = ('openstack.services.compute',)
def get_keypairs_data(self):
try:
keypairs = nova.keypair_list(self.request)
except Exception:
keypairs = []
exceptions.handle(self.request,
_('Unable to retrieve key pair list.'))
return keypairs
class FloatingIPsTab(tabs.TableTab):
table_classes = (FloatingIPsTable,)
name = _("Floating IPs")
slug = "floating_ips_tab"
template_name = "horizon/common/_detail_table.html"
permissions = ('openstack.services.compute',)
def get_floating_ips_data(self):
|
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):
services = []
for i, service in enumerate(self.request.user.service_catalog):
service['id'] = i
services.append(
keystone.Service(service, self.request.user.services_region))
return services
class AccessAndSecurityTabs(tabs.TabGroup):
slug = "access_security_tabs"
tabs = (SecurityGroupsTab, KeypairsTab, FloatingIPsTab, APIAccessTab)
sticky = True
| 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,
_('Unable to retrieve floating IP addresses.'))
try:
floating_ip_pools = network.floating_ip_pools_list(self.request)
except neutron_exc.ConnectionFailed:
floating_ip_pools = []
exceptions.handle(self.request)
except Exception:
floating_ip_pools = []
exceptions.handle(self.request,
_('Unable to retrieve floating IP pools.'))
pool_dict = dict([(obj.id, obj.name) for obj in floating_ip_pools])
instances = []
try:
instances, has_more = nova.server_list(self.request)
except Exception:
exceptions.handle(self.request,
_('Unable to retrieve instance list.'))
instances_dict = dict([(obj.id, obj.name) for obj in instances])
for ip in floating_ips:
ip.instance_name = instances_dict.get(ip.instance_id)
ip.pool_name = pool_dict.get(ip.pool, ip.pool)
return floating_ips | 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 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import tabs | 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_security.\
keypairs.tables import KeypairsTable
from openstack_dashboard.dashboards.project.access_and_security.\
security_groups.tables import SecurityGroupsTable
class SecurityGroupsTab(tabs.TableTab):
table_classes = (SecurityGroupsTable,)
name = _("Security Groups")
slug = "security_groups_tab"
template_name = "horizon/common/_detail_table.html"
permissions = ('openstack.services.compute',)
def get_security_groups_data(self):
try:
security_groups = network.security_group_list(self.request)
except neutron_exc.ConnectionFailed:
security_groups = []
exceptions.handle(self.request)
except Exception:
security_groups = []
exceptions.handle(self.request,
_('Unable to retrieve security groups.'))
return sorted(security_groups, key=lambda group: group.name)
class KeypairsTab(tabs.TableTab):
table_classes = (KeypairsTable,)
name = _("Key Pairs")
slug = "keypairs_tab"
template_name = "horizon/common/_detail_table.html"
permissions = ('openstack.services.compute',)
def get_keypairs_data(self):
try:
keypairs = nova.keypair_list(self.request)
except Exception:
keypairs = []
exceptions.handle(self.request,
_('Unable to retrieve key pair list.'))
return keypairs
class FloatingIPsTab(tabs.TableTab):
table_classes = (FloatingIPsTable,)
name = _("Floating IPs")
slug = "floating_ips_tab"
template_name = "horizon/common/_detail_table.html"
permissions = ('openstack.services.compute',)
def get_floating_ips_data(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,
_('Unable to retrieve floating IP addresses.'))
try:
floating_ip_pools = network.floating_ip_pools_list(self.request)
except neutron_exc.ConnectionFailed:
floating_ip_pools = []
exceptions.handle(self.request)
except Exception:
floating_ip_pools = []
exceptions.handle(self.request,
_('Unable to retrieve floating IP pools.'))
pool_dict = dict([(obj.id, obj.name) for obj in floating_ip_pools])
instances = []
try:
instances, has_more = nova.server_list(self.request)
except Exception:
exceptions.handle(self.request,
_('Unable to retrieve instance list.'))
instances_dict = dict([(obj.id, obj.name) for obj in instances])
for ip in floating_ips:
ip.instance_name = instances_dict.get(ip.instance_id)
ip.pool_name = pool_dict.get(ip.pool, ip.pool)
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_endpoints_data(self):
services = []
for i, service in enumerate(self.request.user.service_catalog):
service['id'] = i
services.append(
keystone.Service(service, self.request.user.services_region))
return services
class AccessAndSecurityTabs(tabs.TabGroup):
slug = "access_security_tabs"
tabs = (SecurityGroupsTab, KeypairsTab, FloatingIPsTab, APIAccessTab)
sticky = True |
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 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import tabs
from neutronclient.common import exceptions as neutron_exc
from openstack_dashboard.api import keystone
from openstack_dashboard.api import network
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_security.\
keypairs.tables import KeypairsTable
from openstack_dashboard.dashboards.project.access_and_security.\
security_groups.tables import SecurityGroupsTable
class SecurityGroupsTab(tabs.TableTab):
table_classes = (SecurityGroupsTable,)
name = _("Security Groups")
slug = "security_groups_tab"
template_name = "horizon/common/_detail_table.html"
permissions = ('openstack.services.compute',)
def get_security_groups_data(self):
try:
security_groups = network.security_group_list(self.request)
except neutron_exc.ConnectionFailed:
security_groups = []
exceptions.handle(self.request)
except Exception:
security_groups = []
exceptions.handle(self.request,
_('Unable to retrieve security groups.'))
return sorted(security_groups, key=lambda group: group.name)
class KeypairsTab(tabs.TableTab):
table_classes = (KeypairsTable,)
name = _("Key Pairs")
slug = "keypairs_tab"
template_name = "horizon/common/_detail_table.html"
permissions = ('openstack.services.compute',)
def get_keypairs_data(self):
try:
keypairs = nova.keypair_list(self.request)
except Exception:
keypairs = []
exceptions.handle(self.request,
_('Unable to retrieve key pair list.'))
return keypairs
class FloatingIPsTab(tabs.TableTab):
table_classes = (FloatingIPsTable,)
name = _("Floating IPs")
slug = "floating_ips_tab"
template_name = "horizon/common/_detail_table.html"
permissions = ('openstack.services.compute',)
def get_floating_ips_data(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,
_('Unable to retrieve floating IP addresses.'))
try:
floating_ip_pools = network.floating_ip_pools_list(self.request)
except neutron_exc.ConnectionFailed:
floating_ip_pools = []
exceptions.handle(self.request)
except Exception:
floating_ip_pools = []
exceptions.handle(self.request,
_('Unable to retrieve floating IP pools.'))
pool_dict = dict([(obj.id, obj.name) for obj in floating_ip_pools])
instances = []
try:
instances, has_more = nova.server_list(self.request)
except Exception:
exceptions.handle(self.request,
_('Unable to retrieve instance list.'))
instances_dict = dict([(obj.id, obj.name) for obj in instances])
for ip in floating_ips:
|
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_endpoints_data(self):
services = []
for i, service in enumerate(self.request.user.service_catalog):
service['id'] = i
services.append(
keystone.Service(service, self.request.user.services_region))
return services
class AccessAndSecurityTabs(tabs.TabGroup):
slug = "access_security_tabs"
tabs = (SecurityGroupsTab, KeypairsTab, FloatingIPsTab, APIAccessTab)
sticky = True
| 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 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import tabs
from neutronclient.common import exceptions as neutron_exc
from openstack_dashboard.api import keystone
from openstack_dashboard.api import network
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_security.\
keypairs.tables import KeypairsTable
from openstack_dashboard.dashboards.project.access_and_security.\
security_groups.tables import SecurityGroupsTable
class SecurityGroupsTab(tabs.TableTab):
table_classes = (SecurityGroupsTable,)
name = _("Security Groups")
slug = "security_groups_tab"
template_name = "horizon/common/_detail_table.html"
permissions = ('openstack.services.compute',)
def get_security_groups_data(self):
try:
security_groups = network.security_group_list(self.request)
except neutron_exc.ConnectionFailed:
security_groups = []
exceptions.handle(self.request)
except Exception:
security_groups = []
exceptions.handle(self.request,
_('Unable to retrieve security groups.'))
return sorted(security_groups, key=lambda group: group.name)
class KeypairsTab(tabs.TableTab):
table_classes = (KeypairsTable,)
name = _("Key Pairs")
slug = "keypairs_tab"
template_name = "horizon/common/_detail_table.html"
permissions = ('openstack.services.compute',)
def get_keypairs_data(self):
try:
keypairs = nova.keypair_list(self.request)
except Exception:
keypairs = []
exceptions.handle(self.request,
_('Unable to retrieve key pair list.'))
return keypairs
class FloatingIPsTab(tabs.TableTab):
table_classes = (FloatingIPsTable,)
name = _("Floating IPs")
slug = "floating_ips_tab"
template_name = "horizon/common/_detail_table.html"
permissions = ('openstack.services.compute',)
def | (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,
_('Unable to retrieve floating IP addresses.'))
try:
floating_ip_pools = network.floating_ip_pools_list(self.request)
except neutron_exc.ConnectionFailed:
floating_ip_pools = []
exceptions.handle(self.request)
except Exception:
floating_ip_pools = []
exceptions.handle(self.request,
_('Unable to retrieve floating IP pools.'))
pool_dict = dict([(obj.id, obj.name) for obj in floating_ip_pools])
instances = []
try:
instances, has_more = nova.server_list(self.request)
except Exception:
exceptions.handle(self.request,
_('Unable to retrieve instance list.'))
instances_dict = dict([(obj.id, obj.name) for obj in instances])
for ip in floating_ips:
ip.instance_name = instances_dict.get(ip.instance_id)
ip.pool_name = pool_dict.get(ip.pool, ip.pool)
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_endpoints_data(self):
services = []
for i, service in enumerate(self.request.user.service_catalog):
service['id'] = i
services.append(
keystone.Service(service, self.request.user.services_region))
return services
class AccessAndSecurityTabs(tabs.TabGroup):
slug = "access_security_tabs"
tabs = (SecurityGroupsTab, KeypairsTab, FloatingIPsTab, APIAccessTab)
sticky = True
| 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: "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(floatEqPL(fn(pln(100), pls('g'), pls('t')), pln(0.0001))).toBe(true)
expect(floatEqPL(fn(pln(360), pls('deg'), pls('rad')), pln(2 * Math.PI))).toBe(true)
expect(floatEqPL(fn(pln(100), pls('mm^2'), pls('cm^2')), pln(1))).toBe(true)
expect(floatEqPL(fn(pln(1000), pls('mm^3'), pls('cm^3')), pln(1))).toBe(true)
expect(floatEqPL(fn(pln(100), pls('cl'), pls('dm^3')), pln(1))).toBe(true)
})
})
| 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'))
}).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(floatEqPL(fn(pln(100), pls('g'), pls('t')), pln(0.0001))).toBe(true)
expect(floatEqPL(fn(pln(360), pls('deg'), pls('rad')), pln(2 * Math.PI))).toBe(true)
expect(floatEqPL(fn(pln(100), pls('mm^2'), pls('cm^2')), pln(1))).toBe(true)
expect(floatEqPL(fn(pln(1000), pls('mm^3'), pls('cm^3')), pln(1))).toBe(true)
expect(floatEqPL(fn(pln(100), pls('cl'), pls('dm^3')), pln(1))).toBe(true)
})
})
| {
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('convert utils', () => { | }).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(floatEqPL(fn(pln(100), pls('g'), pls('t')), pln(0.0001))).toBe(true)
expect(floatEqPL(fn(pln(360), pls('deg'), pls('rad')), pln(2 * Math.PI))).toBe(true)
expect(floatEqPL(fn(pln(100), pls('mm^2'), pls('cm^2')), pln(1))).toBe(true)
expect(floatEqPL(fn(pln(1000), pls('mm^3'), pls('cm^3')), pln(1))).toBe(true)
expect(floatEqPL(fn(pln(100), pls('cl'), pls('dm^3')), pln(1))).toBe(true)
})
}) | 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(Clone, Debug)]
pub struct Param {
pub ponder: bool,
pub search_moves: Option<Vec<Move>>,
pub depth: Option<NumPlies>,
pub nodes: Option<NumNodes>,
pub mate: Option<NumMoves>,
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, Clone, Debug)]
pub enum Cmd {
SetDebug(bool),
PonderHit,
Stop,
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct BestMove(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 {
pub nodes: NumNodes,
}
impl InnerData {
pub fn one_node() -> InnerData { InnerData { nodes: NumNodes(1) } }
pub fn combine(self, other: InnerData) -> InnerData {
InnerData { nodes: NumNodes(self.nodes.0 + other.nodes.0) }
}
pub fn increment(self) -> InnerData |
}
| {
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(Clone, Debug)]
pub struct Param {
pub ponder: bool,
pub search_moves: Option<Vec<Move>>,
pub depth: Option<NumPlies>,
pub nodes: Option<NumNodes>,
pub mate: Option<NumMoves>,
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, Clone, Debug)]
pub enum Cmd {
SetDebug(bool),
PonderHit,
Stop,
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct | (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 {
pub nodes: NumNodes,
}
impl InnerData {
pub fn one_node() -> InnerData { InnerData { nodes: NumNodes(1) } }
pub fn combine(self, other: InnerData) -> InnerData {
InnerData { nodes: NumNodes(self.nodes.0 + other.nodes.0) }
}
pub fn increment(self) -> InnerData {
InnerData { nodes: NumNodes(self.nodes.0 + 1) }
}
}
| 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(Clone, Debug)]
pub struct Param {
pub ponder: bool,
pub search_moves: Option<Vec<Move>>,
pub depth: Option<NumPlies>,
pub nodes: Option<NumNodes>, | 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, Clone, Debug)]
pub enum Cmd {
SetDebug(bool),
PonderHit,
Stop,
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct BestMove(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 {
pub nodes: NumNodes,
}
impl InnerData {
pub fn one_node() -> InnerData { InnerData { nodes: NumNodes(1) } }
pub fn combine(self, other: InnerData) -> InnerData {
InnerData { nodes: NumNodes(self.nodes.0 + other.nodes.0) }
}
pub fn increment(self) -> InnerData {
InnerData { nodes: NumNodes(self.nodes.0 + 1) }
}
} | 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 TextMultiSelectField(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, self).__init__(*args, **kwargs)
def contribute_to_class(self, cls, name):
super(TextMultiSelectField, self).contribute_to_class(cls, name)
if self.choices:
def _func(self, fieldname=name):
return self.separate_values_by.join([
self.choices.get(value, value) for value in
getattr(self, fieldname)
])
setattr(cls, 'get_%s_display' % self.name, _func)
def deconstruct(self):
name, path, args, kwargs = super(TextMultiSelectField, self).deconstruct()
kwargs['separate_values_by'] = self.separate_values_by
if kwargs.get('separate_values_by', None) == '\n':
del kwargs['separate_values_by']
return name, path, args, kwargs
def formfield(self, **kwargs):
# don't call super, as that overrides default widget if it has choices
defaults = {
'choices': self.choices,
'help_text': self.help_text,
'label': capfirst(self.verbose_name),
'required': not self.blank,
'separate_values_by': self.separate_values_by,
}
if self.has_default():
defaults['initial'] = self.get_default()
defaults.update(kwargs)
defaults['widget'] = self.widget
return MultiSelectFormField(**defaults)
def get_db_prep_value(self, value, connection=None, prepared=False):
if isinstance(value, six.string_types):
return value
elif isinstance(value, list):
return self.separate_values_by.join(value)
def get_choices_default(self):
return self.get_choices(include_blank=False)
def get_choices_selected(self, arr_choices=''):
if not arr_choices:
return False
chces = []
for choice_selected in arr_choices:
chces.append(choice_selected[0])
return chces
def get_prep_value(self, value):
return value
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 choice
"""
arr_choices = self.get_choices_selected(self.get_choices_default())
for opt_select in value:
|
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 TextMultiSelectField(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, self).__init__(*args, **kwargs)
def contribute_to_class(self, cls, name):
super(TextMultiSelectField, self).contribute_to_class(cls, name)
if self.choices:
def _func(self, fieldname=name):
return self.separate_values_by.join([
self.choices.get(value, value) for value in
getattr(self, fieldname)
])
setattr(cls, 'get_%s_display' % self.name, _func)
def deconstruct(self):
name, path, args, kwargs = super(TextMultiSelectField, self).deconstruct()
kwargs['separate_values_by'] = self.separate_values_by
if kwargs.get('separate_values_by', None) == '\n':
del kwargs['separate_values_by']
return name, path, args, kwargs
def formfield(self, **kwargs):
# don't call super, as that overrides default widget if it has choices
defaults = {
'choices': self.choices,
'help_text': self.help_text,
'label': capfirst(self.verbose_name),
'required': not self.blank,
'separate_values_by': self.separate_values_by,
}
if self.has_default():
defaults['initial'] = self.get_default()
defaults.update(kwargs)
defaults['widget'] = self.widget
return MultiSelectFormField(**defaults)
def get_db_prep_value(self, value, connection=None, prepared=False):
if isinstance(value, six.string_types):
return value
elif isinstance(value, list):
return self.separate_values_by.join(value)
def get_choices_default(self):
return self.get_choices(include_blank=False)
def get_choices_selected(self, arr_choices=''):
if not arr_choices:
return False
chces = []
for choice_selected in arr_choices:
chces.append(choice_selected[0])
return chces
def get_prep_value(self, value):
return value
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):
|
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_messages['invalid_choice'] % value)
return | 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, self).__init__(*args, **kwargs)
def contribute_to_class(self, cls, name):
super(TextMultiSelectField, self).contribute_to_class(cls, name)
if self.choices:
def _func(self, fieldname=name):
return self.separate_values_by.join([
self.choices.get(value, value) for value in
getattr(self, fieldname)
])
setattr(cls, 'get_%s_display' % self.name, _func)
def deconstruct(self):
name, path, args, kwargs = super(TextMultiSelectField, self).deconstruct()
kwargs['separate_values_by'] = self.separate_values_by
if kwargs.get('separate_values_by', None) == '\n':
del kwargs['separate_values_by']
return name, path, args, kwargs
def formfield(self, **kwargs):
# don't call super, as that overrides default widget if it has choices
defaults = {
'choices': self.choices,
'help_text': self.help_text,
'label': capfirst(self.verbose_name),
'required': not self.blank,
'separate_values_by': self.separate_values_by,
}
if self.has_default():
defaults['initial'] = self.get_default()
defaults.update(kwargs)
defaults['widget'] = self.widget
return MultiSelectFormField(**defaults)
def get_db_prep_value(self, value, connection=None, prepared=False):
if isinstance(value, six.string_types):
return value
elif isinstance(value, list):
return self.separate_values_by.join(value)
def get_choices_default(self):
return self.get_choices(include_blank=False)
def get_choices_selected(self, arr_choices=''):
if not arr_choices:
return False
chces = []
for choice_selected in arr_choices:
chces.append(choice_selected[0])
return chces
def get_prep_value(self, value):
return value
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 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_messages['invalid_choice'] % value)
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"
| 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 TextMultiSelectField(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, self).__init__(*args, **kwargs)
def contribute_to_class(self, cls, name):
super(TextMultiSelectField, self).contribute_to_class(cls, name)
if self.choices:
def _func(self, fieldname=name):
return self.separate_values_by.join([
self.choices.get(value, value) for value in
getattr(self, fieldname)
])
setattr(cls, 'get_%s_display' % self.name, _func)
def deconstruct(self):
name, path, args, kwargs = super(TextMultiSelectField, self).deconstruct()
kwargs['separate_values_by'] = self.separate_values_by
if kwargs.get('separate_values_by', None) == '\n':
del kwargs['separate_values_by']
return name, path, args, kwargs
def formfield(self, **kwargs):
# don't call super, as that overrides default widget if it has choices
defaults = {
'choices': self.choices,
'help_text': self.help_text,
'label': capfirst(self.verbose_name),
'required': not self.blank,
'separate_values_by': self.separate_values_by,
}
if self.has_default():
defaults['initial'] = self.get_default()
defaults.update(kwargs)
defaults['widget'] = self.widget
return MultiSelectFormField(**defaults)
def get_db_prep_value(self, value, connection=None, prepared=False):
if isinstance(value, six.string_types):
return value
elif isinstance(value, list):
return self.separate_values_by.join(value)
def get_choices_default(self):
return self.get_choices(include_blank=False)
def get_choices_selected(self, arr_choices=''):
if not arr_choices:
return False
chces = []
for choice_selected in arr_choices:
chces.append(choice_selected[0]) |
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 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_messages['invalid_choice'] % value)
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" | 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 = factory());
}(this, function () { 'use strict';
var NO_RENDER = 'NO_RENDER';
// Runs only once in applications lifetime
var isBrowser = typeof window !== 'undefined' && window.document;
function isArray(obj) {
return obj instanceof Array;
}
function isNullOrUndefined(obj) {
return isUndefined(obj) || isNull(obj);
}
function isNull(obj) {
return obj === null;
}
function isUndefined(obj) {
return obj === undefined;
}
function VNode(blueprint) {
this.bp = blueprint;
this.dom = null;
this.instance = null;
this.tag = null;
this.children = null;
this.style = null;
this.className = null;
this.attrs = null;
this.events = null;
this.hooks = null;
this.key = null;
this.clipData = null;
}
VNode.prototype = {
setAttrs: function setAttrs(attrs) {
this.attrs = attrs;
return this;
},
setTag: function setTag(tag) {
this.tag = tag;
return this;
},
setStyle: function setStyle(style) {
this.style = style;
return this;
},
setClassName: function setClassName(className) {
this.className = className;
return this;
},
setChildren: function setChildren(children) {
this.children = children;
return this;
},
setHooks: function setHooks(hooks) {
this.hooks = hooks;
return this;
},
setEvents: function setEvents(events) {
this.events = events;
return this;
},
setKey: function setKey(key) {
this.key = key;
return this;
}
};
function createVNode(bp) {
return new VNode(bp);
}
function VPlaceholder() {
this.placeholder = true;
this.dom = null;
}
function createVPlaceholder() {
return new VPlaceholder();
}
function | (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 = {};
var namespaces = {};
var isUnitlessNumber = {};
constructDefaults('xlink:href,xlink:arcrole,xlink:actuate,xlink:role,xlink:titlef,xlink:type', namespaces, xlinkNS);
constructDefaults('xml:base,xml:lang,xml:space', namespaces, xmlNS);
constructDefaults('volume,value', strictProps, true);
constructDefaults('muted,scoped,loop,open,checked,default,capture,disabled,selected,readonly,multiple,required,autoplay,controls,seamless,reversed,allowfullscreen,novalidate', booleanProps, true);
constructDefaults('animationIterationCount,borderImageOutset,borderImageSlice,borderImageWidth,boxFlex,boxFlexGroup,boxOrdinalGroup,columnCount,flex,flexGrow,flexPositive,flexShrink,flexNegative,flexOrder,gridRow,gridColumn,fontWeight,lineClamp,lineHeight,opacity,order,orphans,tabSize,widows,zIndex,zoom,fillOpacity,floodOpacity,stopOpacity,strokeDasharray,strokeDashoffset,strokeMiterlimit,strokeOpacity,strokeWidth,', isUnitlessNumber, true);
var screenWidth = isBrowser && window.screen.width;
var screenHeight = isBrowser && window.screen.height;
var scrollX = 0;
var scrollY = 0;
var lastScrollTime = 0;
if (isBrowser) {
window.onscroll = function () {
scrollX = window.scrollX;
scrollY = window.scrollY;
lastScrollTime = performance.now();
};
window.resize = function () {
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.screenHeight = screenHeight;
this.screenWidth = screenWidth;
}
Lifecycle.prototype = {
refresh: function refresh() {
this.scrollX = isBrowser && window.scrollX;
this.scrollY = isBrowser && window.scrollY;
},
addListener: function addListener(callback) {
this._listeners.push(callback);
},
trigger: function trigger() {
var this$1 = this;
for (var i = 0; i < this._listeners.length; i++) {
this$1._listeners[i]();
}
}
};
var noOp = 'Inferno Error: Can only update a mounted or mounting component. This usually means you called setState() or forceUpdate() on an unmounted component. This is a no-op.';
// Copy of the util from dom/util, otherwise it makes massive bundles
function getActiveNode() {
return document.activeElement;
}
// Copy of the util from dom/util, otherwise it makes massive bundles
function resetActiveNode(activeNode) {
if (activeNode !== document.body && document.activeElement !== activeNode) {
activeNode.focus(); // TODO: verify are we doing new focus event, if user has focus listener this might trigger it
}
}
function queueStateChanges(component, newState, callback) {
for (var stateKey in newState) {
component._pendingState[stateKey] = newState[stateKey];
}
if (!component._pendingSetState) {
component._pendingSetState = true;
applyState(component, false, callback);
} else {
var pendingState = component._pendingState;
var oldState = component.state;
component.state = Object.assign({}, oldState, pendingState);
component._pendingState = {};
}
}
function applyState(component, force, callback) {
if (!component._deferSetState || force) {
component._pendingSetState = false;
var pendingState = component._pendingState;
var oldState = component.state;
var nextState = Object.assign({}, oldState, pendingState);
component._pendingState = {};
var nextNode = component._updateComponent(oldState, nextState, component.props, component.props, force);
if (nextNode === NO_RENDER) {
nextNode = component._lastNode;
} else if (isNullOrUndefined(nextNode)) {
nextNode = createVPlaceholder();
}
var lastNode = component._lastNode;
var parentDom = lastNode.dom.parentNode;
var activeNode = getActiveNode();
var subLifecycle = new Lifecycle();
component._patch(lastNode, nextNode, parentDom, subLifecycle, component.context, component, null);
component._lastNode = nextNode;
component._componentToDOMNodeMap.set(component, nextNode.dom);
component._parentNode.dom = nextNode.dom;
subLifecycle.trigger();
if (!isNullOrUndefined(callback)) {
callback();
}
resetActiveNode(activeNode);
}
}
var Component = function Component(props) {
/** @type {object} */
this.props = props || {};
/** @type {object} */
this.state = {};
/** @type {object} */
this.refs = {};
this._blockSetState = false;
this._deferSetState = false;
this._pendingSetState = false;
this._pendingState = {};
this._parentNode = null;
this._lastNode = null;
this._unmounted = true;
this.context = {};
this._patch = null;
this._parentComponent = null;
this._componentToDOMNodeMap = null;
};
Component.prototype.render = function render () {
};
Component.prototype.forceUpdate = function forceUpdate (callback) {
if (this._unmounted) {
throw Error(noOp);
}
applyState(this, true, callback);
};
Component.prototype.setState = function setState (newState, callback) {
if (this._unmounted) {
throw Error(noOp);
}
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.prototype.componentWillMount = function componentWillMount () {
};
Component.prototype.componentWillUnmount = function componentWillUnmount () {
};
Component.prototype.componentDidUpdate = function componentDidUpdate () {
};
Component.prototype.shouldComponentUpdate = function shouldComponentUpdate () {
return true;
};
Component.prototype.componentWillReceiveProps = function componentWillReceiveProps () {
};
Component.prototype.componentWillUpdate = function componentWillUpdate () {
};
Component.prototype.getChildContext = function getChildContext () {
};
Component.prototype._updateComponent = function _updateComponent (prevState, nextState, prevProps, nextProps, force) {
if (this._unmounted === true) {
this._unmounted = false;
return false;
}
if (!isNullOrUndefined(nextProps) && isNullOrUndefined(nextProps.children)) {
nextProps.children = prevProps.children;
}
if (prevProps !== nextProps || prevState !== nextState || force) {
if (prevProps !== nextProps) {
this._blockSetState = true;
this.componentWillReceiveProps(nextProps);
this._blockSetState = false;
}
var shouldUpdate = this.shouldComponentUpdate(nextProps, nextState);
if (shouldUpdate !== false) {
this._blockSetState = true;
this.componentWillUpdate(nextProps, nextState);
this._blockSetState = false;
this.props = nextProps;
this.state = nextState;
var node = this.render();
this.componentDidUpdate(prevProps, prevState);
return node;
}
}
return NO_RENDER;
};
var ASYNC_STATUS = {
pending: 'pending',
fulfilled: 'fulfilled',
rejected: 'rejected'
};
var Route = (function (Component) {
function Route(props) {
Component.call(this, props);
this.state = {
async: null
};
}
if ( Component ) Route.__proto__ = Component;
Route.prototype = Object.create( Component && Component.prototype );
Route.prototype.constructor = Route;
Route.prototype.async = function async () {
var this$1 = this;
var async = this.props.async;
if (async) {
this.setState({
async: { status: ASYNC_STATUS.pending }
});
async(this.props.params).then(function (value) {
this$1.setState({
async: {
status: ASYNC_STATUS.fulfilled,
value: value
}
});
}, this.reject).catch(this.reject);
}
};
Route.prototype.reject = function reject (value) {
this.setState({
async: {
status: ASYNC_STATUS.rejected,
value: value
}
});
};
Route.prototype.componentWillReceiveProps = function componentWillReceiveProps () {
this.async();
};
Route.prototype.componentWillMount = function componentWillMount () {
this.async();
};
Route.prototype.render = function render () {
var ref = this.props;
var component = ref.component;
var params = ref.params;
return createVNode().setTag(component).setAttrs({ params: params, async: this.state.async });
};
return Route;
}(Component));
var EMPTY$1 = {};
function segmentize(url) {
return strip(url).split('/');
}
function strip(url) {
return url.replace(/(^\/+|\/+$)/g, '');
}
function convertToHashbang(url) {
if (url.indexOf('#') === -1) {
url = '/';
} else {
var splitHashUrl = url.split('#!');
splitHashUrl.shift();
url = splitHashUrl.join('');
}
return url;
}
// Thanks goes to Preact for this function: https://github.com/developit/preact-router/blob/master/src/util.js#L4
function exec(url, route, opts) {
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])] = decodeURIComponent(r.slice(1).join('='));
}
}
url = segmentize(url.replace(reg, ''));
route = segmentize(route || '');
var max = Math.max(url.length, route.length);
var hasWildcard = false;
for (var i$1 = 0; i$1 < max; i$1++) {
if (route[i$1] && route[i$1].charAt(0) === ':') {
var param = route[i$1].replace(/(^\:|[+*?]+$)/g, ''),
flags = (route[i$1].match(/[+*?]+$/) || EMPTY$1)[0] || '',
plus = ~flags.indexOf('+'),
star = ~flags.indexOf('*'),
val = url[i$1] || '';
if (!val && !star && (flags.indexOf('?') < 0 || plus)) {
ret = false;
break;
}
matches[param] = decodeURIComponent(val);
if (plus || star) {
matches[param] = url.slice(i$1).map(decodeURIComponent).join('/');
break;
}
}
else if (route[i$1] !== url[i$1] && !hasWildcard) {
if (route[i$1] === '*' && route.length === i$1 + 1) {
hasWildcard = true;
} else {
ret = false;
break;
}
}
}
if (opts.default !== true && ret === false) {
return false;
}
return matches;
}
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 Router = (function (Component) {
function Router(props) {
Component.call(this, props);
if (!props.history) {
throw new Error('Inferno Error: "inferno-router" Router components require a "history" prop passed.');
}
this._didRoute = false;
this.state = {
url: props.url || props.history.getCurrentUrl()
};
}
if ( Component ) Router.__proto__ = Component;
Router.prototype = Object.create( Component && Component.prototype );
Router.prototype.constructor = Router;
Router.prototype.getChildContext = function getChildContext () {
return {
history: this.props.history,
hashbang: this.props.hashbang
};
};
Router.prototype.componentWillMount = function componentWillMount () {
this.props.history.addRouter(this);
};
Router.prototype.componentWillUnmount = function componentWillUnmount () {
this.props.history.removeRouter(this);
};
Router.prototype.routeTo = function routeTo (url) {
this._didRoute = false;
this.setState({ url: url });
return this._didRoute;
};
Router.prototype.render = function render () {
var children = toArray(this.props.children);
var url = this.props.url || this.state.url;
var wrapperComponent = this.props.component;
var hashbang = this.props.hashbang;
return handleRoutes(children, url, hashbang, wrapperComponent, '');
};
return Router;
}(Component));
function toArray(children) {
return isArray(children) ? children : (children ? [children] : children);
}
function handleRoutes(routes, url, hashbang, wrapperComponent, lastPath) {
routes.sort(pathRankSort);
for (var i = 0; i < routes.length; i++) {
var route = routes[i];
var ref = route.attrs;
var path = ref.path;
var fullPath = lastPath + path;
var params = exec(hashbang ? convertToHashbang(url) : url, fullPath);
var children = toArray(route.children);
if (children) {
var subRoute = handleRoutes(children, url, hashbang, wrapperComponent, fullPath);
if (!isNull(subRoute)) {
return subRoute;
}
}
if (params) {
if (wrapperComponent) {
return createVNode().setTag(wrapperComponent).setChildren(route).setAttrs({
params: params
});
}
return route.setAttrs(Object.assign({}, { params: params }, route.attrs));
}
}
return !lastPath && wrapperComponent ? createVNode().setTag(wrapperComponent) : null;
}
function Link(ref, ref$1) {
var to = ref.to;
var children = ref.children;
var hashbang = ref$1.hashbang;
var history = ref$1.history;
return (createVNode().setAttrs({
href: hashbang ? history.getHashbangRoot() + convertToHashbang('#!' + to) : to
}).setTag('a').setChildren(children));
}
var routers = [];
function getCurrentUrl() {
var url = typeof location !== 'undefined' ? location : EMPTY;
return ("" + (url.pathname || '') + (url.search || '') + (url.hash || ''));
}
function getHashbangRoot() {
var url = typeof location !== 'undefined' ? location : EMPTY;
return ("" + (url.protocol + '//' || '') + (url.host || '') + (url.pathname || '') + (url.search || '') + "#!");
}
function routeTo(url) {
var didRoute = false;
for (var i = 0; i < routers.length; i++) {
if (routers[i].routeTo(url) === true) {
didRoute = true;
}
}
return didRoute;
}
if (isBrowser) {
window.addEventListener('popstate', function () { return routeTo(getCurrentUrl()); });
}
var browserHistory = {
addRouter: function addRouter(router) {
routers.push(router);
},
removeRouter: function removeRouter(router) {
routers.splice(routers.indexOf(router), 1);
},
getCurrentUrl: getCurrentUrl,
getHashbangRoot: getHashbangRoot
};
var index = {
Route: Route,
Router: Router,
Link: Link,
browserHistory: browserHistory
};
return index;
})); | 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 = factory());
}(this, function () { 'use strict';
var NO_RENDER = 'NO_RENDER';
// Runs only once in applications lifetime
var isBrowser = typeof window !== 'undefined' && window.document;
function isArray(obj) {
return obj instanceof Array;
}
function isNullOrUndefined(obj) {
return isUndefined(obj) || isNull(obj);
}
function isNull(obj) {
return obj === null;
}
function isUndefined(obj) {
return obj === undefined;
}
function VNode(blueprint) {
this.bp = blueprint;
this.dom = null;
this.instance = null;
this.tag = null;
this.children = null;
this.style = null;
this.className = null;
this.attrs = null;
this.events = null;
this.hooks = null;
this.key = null;
this.clipData = null;
}
VNode.prototype = {
setAttrs: function setAttrs(attrs) {
this.attrs = attrs;
return this;
},
setTag: function setTag(tag) {
this.tag = tag;
return this;
},
setStyle: function setStyle(style) {
this.style = style;
return this;
},
setClassName: function setClassName(className) {
this.className = className;
return this;
},
setChildren: function setChildren(children) {
this.children = children;
return this;
},
setHooks: function setHooks(hooks) {
this.hooks = hooks;
return this;
},
setEvents: function setEvents(events) {
this.events = events;
return this;
},
setKey: function setKey(key) {
this.key = key;
return this;
}
};
function createVNode(bp) {
return new VNode(bp);
}
function VPlaceholder() {
this.placeholder = true;
this.dom = null;
}
function createVPlaceholder() {
return new VPlaceholder();
}
function constructDefaults(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 = {};
var namespaces = {};
var isUnitlessNumber = {};
constructDefaults('xlink:href,xlink:arcrole,xlink:actuate,xlink:role,xlink:titlef,xlink:type', namespaces, xlinkNS);
constructDefaults('xml:base,xml:lang,xml:space', namespaces, xmlNS);
constructDefaults('volume,value', strictProps, true);
constructDefaults('muted,scoped,loop,open,checked,default,capture,disabled,selected,readonly,multiple,required,autoplay,controls,seamless,reversed,allowfullscreen,novalidate', booleanProps, true);
constructDefaults('animationIterationCount,borderImageOutset,borderImageSlice,borderImageWidth,boxFlex,boxFlexGroup,boxOrdinalGroup,columnCount,flex,flexGrow,flexPositive,flexShrink,flexNegative,flexOrder,gridRow,gridColumn,fontWeight,lineClamp,lineHeight,opacity,order,orphans,tabSize,widows,zIndex,zoom,fillOpacity,floodOpacity,stopOpacity,strokeDasharray,strokeDashoffset,strokeMiterlimit,strokeOpacity,strokeWidth,', isUnitlessNumber, true);
var screenWidth = isBrowser && window.screen.width;
var screenHeight = isBrowser && window.screen.height;
var scrollX = 0;
var scrollY = 0;
var lastScrollTime = 0;
if (isBrowser) {
window.onscroll = function () {
scrollX = window.scrollX;
scrollY = window.scrollY;
lastScrollTime = performance.now();
};
window.resize = function () {
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.screenHeight = screenHeight;
this.screenWidth = screenWidth;
}
Lifecycle.prototype = {
refresh: function refresh() {
this.scrollX = isBrowser && window.scrollX;
this.scrollY = isBrowser && window.scrollY;
},
addListener: function addListener(callback) {
this._listeners.push(callback);
},
trigger: function trigger() {
var this$1 = this;
for (var i = 0; i < this._listeners.length; i++) {
this$1._listeners[i]();
}
}
};
var noOp = 'Inferno Error: Can only update a mounted or mounting component. This usually means you called setState() or forceUpdate() on an unmounted component. This is a no-op.';
// Copy of the util from dom/util, otherwise it makes massive bundles
function getActiveNode() {
return document.activeElement;
}
// Copy of the util from dom/util, otherwise it makes massive bundles
function resetActiveNode(activeNode) {
if (activeNode !== document.body && document.activeElement !== activeNode) {
activeNode.focus(); // TODO: verify are we doing new focus event, if user has focus listener this might trigger it
}
}
function queueStateChanges(component, newState, callback) {
for (var stateKey in newState) {
component._pendingState[stateKey] = newState[stateKey];
}
if (!component._pendingSetState) {
component._pendingSetState = true;
applyState(component, false, callback);
} else {
var pendingState = component._pendingState;
var oldState = component.state;
component.state = Object.assign({}, oldState, pendingState);
component._pendingState = {};
}
}
function applyState(component, force, callback) {
if (!component._deferSetState || force) {
component._pendingSetState = false;
var pendingState = component._pendingState;
var oldState = component.state;
var nextState = Object.assign({}, oldState, pendingState);
component._pendingState = {};
var nextNode = component._updateComponent(oldState, nextState, component.props, component.props, force);
if (nextNode === NO_RENDER) {
nextNode = component._lastNode;
} else if (isNullOrUndefined(nextNode)) {
nextNode = createVPlaceholder();
}
var lastNode = component._lastNode;
var parentDom = lastNode.dom.parentNode;
var activeNode = getActiveNode();
var subLifecycle = new Lifecycle();
component._patch(lastNode, nextNode, parentDom, subLifecycle, component.context, component, null);
component._lastNode = nextNode;
component._componentToDOMNodeMap.set(component, nextNode.dom);
component._parentNode.dom = nextNode.dom;
subLifecycle.trigger();
if (!isNullOrUndefined(callback)) {
callback();
}
resetActiveNode(activeNode);
}
}
var Component = function Component(props) {
/** @type {object} */
this.props = props || {};
/** @type {object} */
this.state = {};
/** @type {object} */
this.refs = {};
this._blockSetState = false;
this._deferSetState = false;
this._pendingSetState = false;
this._pendingState = {};
this._parentNode = null;
this._lastNode = null;
this._unmounted = true;
this.context = {};
this._patch = null;
this._parentComponent = null;
this._componentToDOMNodeMap = null;
};
Component.prototype.render = function render () {
};
Component.prototype.forceUpdate = function forceUpdate (callback) {
if (this._unmounted) {
throw Error(noOp);
}
applyState(this, true, callback);
};
Component.prototype.setState = function setState (newState, callback) {
if (this._unmounted) {
throw Error(noOp);
}
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.prototype.componentWillMount = function componentWillMount () {
};
Component.prototype.componentWillUnmount = function componentWillUnmount () {
};
Component.prototype.componentDidUpdate = function componentDidUpdate () {
};
Component.prototype.shouldComponentUpdate = function shouldComponentUpdate () {
return true;
};
Component.prototype.componentWillReceiveProps = function componentWillReceiveProps () {
};
Component.prototype.componentWillUpdate = function componentWillUpdate () {
};
Component.prototype.getChildContext = function getChildContext () {
};
Component.prototype._updateComponent = function _updateComponent (prevState, nextState, prevProps, nextProps, force) {
if (this._unmounted === true) {
this._unmounted = false;
return false;
}
if (!isNullOrUndefined(nextProps) && isNullOrUndefined(nextProps.children)) {
nextProps.children = prevProps.children;
}
if (prevProps !== nextProps || prevState !== nextState || force) {
if (prevProps !== nextProps) {
this._blockSetState = true;
this.componentWillReceiveProps(nextProps);
this._blockSetState = false;
}
var shouldUpdate = this.shouldComponentUpdate(nextProps, nextState);
if (shouldUpdate !== false) {
this._blockSetState = true;
this.componentWillUpdate(nextProps, nextState);
this._blockSetState = false;
this.props = nextProps;
this.state = nextState;
var node = this.render();
this.componentDidUpdate(prevProps, prevState);
return node;
}
}
return NO_RENDER;
};
var ASYNC_STATUS = {
pending: 'pending',
fulfilled: 'fulfilled',
rejected: 'rejected'
};
var Route = (function (Component) {
function Route(props) {
Component.call(this, props);
this.state = {
async: null
};
}
if ( Component ) Route.__proto__ = Component;
Route.prototype = Object.create( Component && Component.prototype );
Route.prototype.constructor = Route;
Route.prototype.async = function async () {
var this$1 = this;
var async = this.props.async;
if (async) {
this.setState({
async: { status: ASYNC_STATUS.pending }
});
async(this.props.params).then(function (value) {
this$1.setState({
async: {
status: ASYNC_STATUS.fulfilled,
value: value
}
});
}, this.reject).catch(this.reject);
}
};
Route.prototype.reject = function reject (value) {
this.setState({
async: {
status: ASYNC_STATUS.rejected,
value: value
}
});
};
Route.prototype.componentWillReceiveProps = function componentWillReceiveProps () {
this.async();
};
Route.prototype.componentWillMount = function componentWillMount () {
this.async();
};
Route.prototype.render = function render () {
var ref = this.props;
var component = ref.component;
var params = ref.params;
return createVNode().setTag(component).setAttrs({ params: params, async: this.state.async });
};
return Route;
}(Component));
var EMPTY$1 = {};
function segmentize(url) {
return strip(url).split('/');
}
function strip(url) {
return url.replace(/(^\/+|\/+$)/g, '');
}
function convertToHashbang(url) {
if (url.indexOf('#') === -1) {
url = '/';
} else {
var splitHashUrl = url.split('#!');
splitHashUrl.shift();
url = splitHashUrl.join('');
}
return url;
}
// Thanks goes to Preact for this function: https://github.com/developit/preact-router/blob/master/src/util.js#L4
function exec(url, route, opts) |
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 Router = (function (Component) {
function Router(props) {
Component.call(this, props);
if (!props.history) {
throw new Error('Inferno Error: "inferno-router" Router components require a "history" prop passed.');
}
this._didRoute = false;
this.state = {
url: props.url || props.history.getCurrentUrl()
};
}
if ( Component ) Router.__proto__ = Component;
Router.prototype = Object.create( Component && Component.prototype );
Router.prototype.constructor = Router;
Router.prototype.getChildContext = function getChildContext () {
return {
history: this.props.history,
hashbang: this.props.hashbang
};
};
Router.prototype.componentWillMount = function componentWillMount () {
this.props.history.addRouter(this);
};
Router.prototype.componentWillUnmount = function componentWillUnmount () {
this.props.history.removeRouter(this);
};
Router.prototype.routeTo = function routeTo (url) {
this._didRoute = false;
this.setState({ url: url });
return this._didRoute;
};
Router.prototype.render = function render () {
var children = toArray(this.props.children);
var url = this.props.url || this.state.url;
var wrapperComponent = this.props.component;
var hashbang = this.props.hashbang;
return handleRoutes(children, url, hashbang, wrapperComponent, '');
};
return Router;
}(Component));
function toArray(children) {
return isArray(children) ? children : (children ? [children] : children);
}
function handleRoutes(routes, url, hashbang, wrapperComponent, lastPath) {
routes.sort(pathRankSort);
for (var i = 0; i < routes.length; i++) {
var route = routes[i];
var ref = route.attrs;
var path = ref.path;
var fullPath = lastPath + path;
var params = exec(hashbang ? convertToHashbang(url) : url, fullPath);
var children = toArray(route.children);
if (children) {
var subRoute = handleRoutes(children, url, hashbang, wrapperComponent, fullPath);
if (!isNull(subRoute)) {
return subRoute;
}
}
if (params) {
if (wrapperComponent) {
return createVNode().setTag(wrapperComponent).setChildren(route).setAttrs({
params: params
});
}
return route.setAttrs(Object.assign({}, { params: params }, route.attrs));
}
}
return !lastPath && wrapperComponent ? createVNode().setTag(wrapperComponent) : null;
}
function Link(ref, ref$1) {
var to = ref.to;
var children = ref.children;
var hashbang = ref$1.hashbang;
var history = ref$1.history;
return (createVNode().setAttrs({
href: hashbang ? history.getHashbangRoot() + convertToHashbang('#!' + to) : to
}).setTag('a').setChildren(children));
}
var routers = [];
function getCurrentUrl() {
var url = typeof location !== 'undefined' ? location : EMPTY;
return ("" + (url.pathname || '') + (url.search || '') + (url.hash || ''));
}
function getHashbangRoot() {
var url = typeof location !== 'undefined' ? location : EMPTY;
return ("" + (url.protocol + '//' || '') + (url.host || '') + (url.pathname || '') + (url.search || '') + "#!");
}
function routeTo(url) {
var didRoute = false;
for (var i = 0; i < routers.length; i++) {
if (routers[i].routeTo(url) === true) {
didRoute = true;
}
}
return didRoute;
}
if (isBrowser) {
window.addEventListener('popstate', function () { return routeTo(getCurrentUrl()); });
}
var browserHistory = {
addRouter: function addRouter(router) {
routers.push(router);
},
removeRouter: function removeRouter(router) {
routers.splice(routers.indexOf(router), 1);
},
getCurrentUrl: getCurrentUrl,
getHashbangRoot: getHashbangRoot
};
var index = {
Route: Route,
Router: Router,
Link: Link,
browserHistory: browserHistory
};
return index;
})); | {
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])] = decodeURIComponent(r.slice(1).join('='));
}
}
url = segmentize(url.replace(reg, ''));
route = segmentize(route || '');
var max = Math.max(url.length, route.length);
var hasWildcard = false;
for (var i$1 = 0; i$1 < max; i$1++) {
if (route[i$1] && route[i$1].charAt(0) === ':') {
var param = route[i$1].replace(/(^\:|[+*?]+$)/g, ''),
flags = (route[i$1].match(/[+*?]+$/) || EMPTY$1)[0] || '',
plus = ~flags.indexOf('+'),
star = ~flags.indexOf('*'),
val = url[i$1] || '';
if (!val && !star && (flags.indexOf('?') < 0 || plus)) {
ret = false;
break;
}
matches[param] = decodeURIComponent(val);
if (plus || star) {
matches[param] = url.slice(i$1).map(decodeURIComponent).join('/');
break;
}
}
else if (route[i$1] !== url[i$1] && !hasWildcard) {
if (route[i$1] === '*' && route.length === i$1 + 1) {
hasWildcard = true;
} else {
ret = false;
break;
}
}
}
if (opts.default !== true && ret === false) {
return false;
}
return matches;
} | 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 = factory());
}(this, function () { 'use strict';
var NO_RENDER = 'NO_RENDER';
// Runs only once in applications lifetime
var isBrowser = typeof window !== 'undefined' && window.document;
function isArray(obj) {
return obj instanceof Array;
}
function isNullOrUndefined(obj) {
return isUndefined(obj) || isNull(obj);
}
function isNull(obj) {
return obj === null;
}
function isUndefined(obj) {
return obj === undefined;
}
function VNode(blueprint) {
this.bp = blueprint;
this.dom = null;
this.instance = null;
this.tag = null;
this.children = null;
this.style = null;
this.className = null;
this.attrs = null;
this.events = null;
this.hooks = null;
this.key = null;
this.clipData = null;
}
VNode.prototype = {
setAttrs: function setAttrs(attrs) {
this.attrs = attrs;
return this;
},
setTag: function setTag(tag) {
this.tag = tag;
return this;
},
setStyle: function setStyle(style) {
this.style = style;
return this;
},
setClassName: function setClassName(className) {
this.className = className;
return this;
},
setChildren: function setChildren(children) {
this.children = children;
return this;
},
setHooks: function setHooks(hooks) {
this.hooks = hooks;
return this;
},
setEvents: function setEvents(events) {
this.events = events;
return this;
},
setKey: function setKey(key) {
this.key = key;
return this;
}
};
function createVNode(bp) {
return new VNode(bp);
}
function VPlaceholder() {
this.placeholder = true;
this.dom = null;
}
function createVPlaceholder() {
return new VPlaceholder();
}
function constructDefaults(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 = {};
var namespaces = {};
var isUnitlessNumber = {};
constructDefaults('xlink:href,xlink:arcrole,xlink:actuate,xlink:role,xlink:titlef,xlink:type', namespaces, xlinkNS);
constructDefaults('xml:base,xml:lang,xml:space', namespaces, xmlNS);
constructDefaults('volume,value', strictProps, true);
constructDefaults('muted,scoped,loop,open,checked,default,capture,disabled,selected,readonly,multiple,required,autoplay,controls,seamless,reversed,allowfullscreen,novalidate', booleanProps, true);
constructDefaults('animationIterationCount,borderImageOutset,borderImageSlice,borderImageWidth,boxFlex,boxFlexGroup,boxOrdinalGroup,columnCount,flex,flexGrow,flexPositive,flexShrink,flexNegative,flexOrder,gridRow,gridColumn,fontWeight,lineClamp,lineHeight,opacity,order,orphans,tabSize,widows,zIndex,zoom,fillOpacity,floodOpacity,stopOpacity,strokeDasharray,strokeDashoffset,strokeMiterlimit,strokeOpacity,strokeWidth,', isUnitlessNumber, true);
var screenWidth = isBrowser && window.screen.width;
var screenHeight = isBrowser && window.screen.height;
var scrollX = 0;
var scrollY = 0;
var lastScrollTime = 0;
if (isBrowser) {
window.onscroll = function () {
scrollX = window.scrollX;
scrollY = window.scrollY;
lastScrollTime = performance.now();
};
window.resize = function () {
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.screenHeight = screenHeight;
this.screenWidth = screenWidth;
}
Lifecycle.prototype = {
refresh: function refresh() {
this.scrollX = isBrowser && window.scrollX;
this.scrollY = isBrowser && window.scrollY;
},
addListener: function addListener(callback) {
this._listeners.push(callback);
},
trigger: function trigger() {
var this$1 = this;
for (var i = 0; i < this._listeners.length; i++) {
this$1._listeners[i]();
}
}
};
var noOp = 'Inferno Error: Can only update a mounted or mounting component. This usually means you called setState() or forceUpdate() on an unmounted component. This is a no-op.';
// Copy of the util from dom/util, otherwise it makes massive bundles
function getActiveNode() {
return document.activeElement;
}
// Copy of the util from dom/util, otherwise it makes massive bundles
function resetActiveNode(activeNode) {
if (activeNode !== document.body && document.activeElement !== activeNode) {
activeNode.focus(); // TODO: verify are we doing new focus event, if user has focus listener this might trigger it
}
}
function queueStateChanges(component, newState, callback) {
for (var stateKey in newState) {
component._pendingState[stateKey] = newState[stateKey];
}
if (!component._pendingSetState) {
component._pendingSetState = true;
applyState(component, false, callback);
} else {
var pendingState = component._pendingState;
var oldState = component.state;
component.state = Object.assign({}, oldState, pendingState);
component._pendingState = {};
}
}
function applyState(component, force, callback) {
if (!component._deferSetState || force) {
component._pendingSetState = false;
var pendingState = component._pendingState;
var oldState = component.state;
var nextState = Object.assign({}, oldState, pendingState);
component._pendingState = {};
var nextNode = component._updateComponent(oldState, nextState, component.props, component.props, force);
if (nextNode === NO_RENDER) {
nextNode = component._lastNode;
} else if (isNullOrUndefined(nextNode)) {
nextNode = createVPlaceholder();
}
var lastNode = component._lastNode;
var parentDom = lastNode.dom.parentNode;
var activeNode = getActiveNode();
var subLifecycle = new Lifecycle();
component._patch(lastNode, nextNode, parentDom, subLifecycle, component.context, component, null);
component._lastNode = nextNode;
component._componentToDOMNodeMap.set(component, nextNode.dom);
component._parentNode.dom = nextNode.dom;
subLifecycle.trigger();
if (!isNullOrUndefined(callback)) {
callback();
}
resetActiveNode(activeNode);
}
}
var Component = function Component(props) {
/** @type {object} */
this.props = props || {};
/** @type {object} */
this.state = {};
/** @type {object} */
this.refs = {};
this._blockSetState = false;
this._deferSetState = false;
this._pendingSetState = false;
this._pendingState = {};
this._parentNode = null;
this._lastNode = null;
this._unmounted = true;
this.context = {};
this._patch = null;
this._parentComponent = null;
this._componentToDOMNodeMap = null;
};
Component.prototype.render = function render () {
};
Component.prototype.forceUpdate = function forceUpdate (callback) {
if (this._unmounted) {
throw Error(noOp);
}
applyState(this, true, callback);
};
Component.prototype.setState = function setState (newState, callback) {
if (this._unmounted) |
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.prototype.componentWillMount = function componentWillMount () {
};
Component.prototype.componentWillUnmount = function componentWillUnmount () {
};
Component.prototype.componentDidUpdate = function componentDidUpdate () {
};
Component.prototype.shouldComponentUpdate = function shouldComponentUpdate () {
return true;
};
Component.prototype.componentWillReceiveProps = function componentWillReceiveProps () {
};
Component.prototype.componentWillUpdate = function componentWillUpdate () {
};
Component.prototype.getChildContext = function getChildContext () {
};
Component.prototype._updateComponent = function _updateComponent (prevState, nextState, prevProps, nextProps, force) {
if (this._unmounted === true) {
this._unmounted = false;
return false;
}
if (!isNullOrUndefined(nextProps) && isNullOrUndefined(nextProps.children)) {
nextProps.children = prevProps.children;
}
if (prevProps !== nextProps || prevState !== nextState || force) {
if (prevProps !== nextProps) {
this._blockSetState = true;
this.componentWillReceiveProps(nextProps);
this._blockSetState = false;
}
var shouldUpdate = this.shouldComponentUpdate(nextProps, nextState);
if (shouldUpdate !== false) {
this._blockSetState = true;
this.componentWillUpdate(nextProps, nextState);
this._blockSetState = false;
this.props = nextProps;
this.state = nextState;
var node = this.render();
this.componentDidUpdate(prevProps, prevState);
return node;
}
}
return NO_RENDER;
};
var ASYNC_STATUS = {
pending: 'pending',
fulfilled: 'fulfilled',
rejected: 'rejected'
};
var Route = (function (Component) {
function Route(props) {
Component.call(this, props);
this.state = {
async: null
};
}
if ( Component ) Route.__proto__ = Component;
Route.prototype = Object.create( Component && Component.prototype );
Route.prototype.constructor = Route;
Route.prototype.async = function async () {
var this$1 = this;
var async = this.props.async;
if (async) {
this.setState({
async: { status: ASYNC_STATUS.pending }
});
async(this.props.params).then(function (value) {
this$1.setState({
async: {
status: ASYNC_STATUS.fulfilled,
value: value
}
});
}, this.reject).catch(this.reject);
}
};
Route.prototype.reject = function reject (value) {
this.setState({
async: {
status: ASYNC_STATUS.rejected,
value: value
}
});
};
Route.prototype.componentWillReceiveProps = function componentWillReceiveProps () {
this.async();
};
Route.prototype.componentWillMount = function componentWillMount () {
this.async();
};
Route.prototype.render = function render () {
var ref = this.props;
var component = ref.component;
var params = ref.params;
return createVNode().setTag(component).setAttrs({ params: params, async: this.state.async });
};
return Route;
}(Component));
var EMPTY$1 = {};
function segmentize(url) {
return strip(url).split('/');
}
function strip(url) {
return url.replace(/(^\/+|\/+$)/g, '');
}
function convertToHashbang(url) {
if (url.indexOf('#') === -1) {
url = '/';
} else {
var splitHashUrl = url.split('#!');
splitHashUrl.shift();
url = splitHashUrl.join('');
}
return url;
}
// Thanks goes to Preact for this function: https://github.com/developit/preact-router/blob/master/src/util.js#L4
function exec(url, route, opts) {
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])] = decodeURIComponent(r.slice(1).join('='));
}
}
url = segmentize(url.replace(reg, ''));
route = segmentize(route || '');
var max = Math.max(url.length, route.length);
var hasWildcard = false;
for (var i$1 = 0; i$1 < max; i$1++) {
if (route[i$1] && route[i$1].charAt(0) === ':') {
var param = route[i$1].replace(/(^\:|[+*?]+$)/g, ''),
flags = (route[i$1].match(/[+*?]+$/) || EMPTY$1)[0] || '',
plus = ~flags.indexOf('+'),
star = ~flags.indexOf('*'),
val = url[i$1] || '';
if (!val && !star && (flags.indexOf('?') < 0 || plus)) {
ret = false;
break;
}
matches[param] = decodeURIComponent(val);
if (plus || star) {
matches[param] = url.slice(i$1).map(decodeURIComponent).join('/');
break;
}
}
else if (route[i$1] !== url[i$1] && !hasWildcard) {
if (route[i$1] === '*' && route.length === i$1 + 1) {
hasWildcard = true;
} else {
ret = false;
break;
}
}
}
if (opts.default !== true && ret === false) {
return false;
}
return matches;
}
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 Router = (function (Component) {
function Router(props) {
Component.call(this, props);
if (!props.history) {
throw new Error('Inferno Error: "inferno-router" Router components require a "history" prop passed.');
}
this._didRoute = false;
this.state = {
url: props.url || props.history.getCurrentUrl()
};
}
if ( Component ) Router.__proto__ = Component;
Router.prototype = Object.create( Component && Component.prototype );
Router.prototype.constructor = Router;
Router.prototype.getChildContext = function getChildContext () {
return {
history: this.props.history,
hashbang: this.props.hashbang
};
};
Router.prototype.componentWillMount = function componentWillMount () {
this.props.history.addRouter(this);
};
Router.prototype.componentWillUnmount = function componentWillUnmount () {
this.props.history.removeRouter(this);
};
Router.prototype.routeTo = function routeTo (url) {
this._didRoute = false;
this.setState({ url: url });
return this._didRoute;
};
Router.prototype.render = function render () {
var children = toArray(this.props.children);
var url = this.props.url || this.state.url;
var wrapperComponent = this.props.component;
var hashbang = this.props.hashbang;
return handleRoutes(children, url, hashbang, wrapperComponent, '');
};
return Router;
}(Component));
function toArray(children) {
return isArray(children) ? children : (children ? [children] : children);
}
function handleRoutes(routes, url, hashbang, wrapperComponent, lastPath) {
routes.sort(pathRankSort);
for (var i = 0; i < routes.length; i++) {
var route = routes[i];
var ref = route.attrs;
var path = ref.path;
var fullPath = lastPath + path;
var params = exec(hashbang ? convertToHashbang(url) : url, fullPath);
var children = toArray(route.children);
if (children) {
var subRoute = handleRoutes(children, url, hashbang, wrapperComponent, fullPath);
if (!isNull(subRoute)) {
return subRoute;
}
}
if (params) {
if (wrapperComponent) {
return createVNode().setTag(wrapperComponent).setChildren(route).setAttrs({
params: params
});
}
return route.setAttrs(Object.assign({}, { params: params }, route.attrs));
}
}
return !lastPath && wrapperComponent ? createVNode().setTag(wrapperComponent) : null;
}
function Link(ref, ref$1) {
var to = ref.to;
var children = ref.children;
var hashbang = ref$1.hashbang;
var history = ref$1.history;
return (createVNode().setAttrs({
href: hashbang ? history.getHashbangRoot() + convertToHashbang('#!' + to) : to
}).setTag('a').setChildren(children));
}
var routers = [];
function getCurrentUrl() {
var url = typeof location !== 'undefined' ? location : EMPTY;
return ("" + (url.pathname || '') + (url.search || '') + (url.hash || ''));
}
function getHashbangRoot() {
var url = typeof location !== 'undefined' ? location : EMPTY;
return ("" + (url.protocol + '//' || '') + (url.host || '') + (url.pathname || '') + (url.search || '') + "#!");
}
function routeTo(url) {
var didRoute = false;
for (var i = 0; i < routers.length; i++) {
if (routers[i].routeTo(url) === true) {
didRoute = true;
}
}
return didRoute;
}
if (isBrowser) {
window.addEventListener('popstate', function () { return routeTo(getCurrentUrl()); });
}
var browserHistory = {
addRouter: function addRouter(router) {
routers.push(router);
},
removeRouter: function removeRouter(router) {
routers.splice(routers.indexOf(router), 1);
},
getCurrentUrl: getCurrentUrl,
getHashbangRoot: getHashbangRoot
};
var index = {
Route: Route,
Router: Router,
Link: Link,
browserHistory: browserHistory
};
return index;
})); | {
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 = factory());
}(this, function () { 'use strict';
var NO_RENDER = 'NO_RENDER';
// Runs only once in applications lifetime
var isBrowser = typeof window !== 'undefined' && window.document;
function isArray(obj) {
return obj instanceof Array;
}
function isNullOrUndefined(obj) {
return isUndefined(obj) || isNull(obj);
}
function isNull(obj) {
return obj === null;
}
function isUndefined(obj) {
return obj === undefined;
}
function VNode(blueprint) {
this.bp = blueprint;
this.dom = null;
this.instance = null;
this.tag = null;
this.children = null;
this.style = null;
this.className = null;
this.attrs = null;
this.events = null;
this.hooks = null;
this.key = null;
this.clipData = null;
}
VNode.prototype = {
setAttrs: function setAttrs(attrs) {
this.attrs = attrs;
return this;
},
setTag: function setTag(tag) {
this.tag = tag;
return this;
},
setStyle: function setStyle(style) {
this.style = style;
return this;
},
setClassName: function setClassName(className) {
this.className = className;
return this;
},
setChildren: function setChildren(children) {
this.children = children;
return this;
},
setHooks: function setHooks(hooks) {
this.hooks = hooks;
return this;
},
setEvents: function setEvents(events) {
this.events = events;
return this;
},
setKey: function setKey(key) {
this.key = key;
return this;
}
};
function createVNode(bp) {
return new VNode(bp);
}
function VPlaceholder() {
this.placeholder = true;
this.dom = null;
}
function createVPlaceholder() {
return new VPlaceholder();
}
function constructDefaults(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 = {};
var namespaces = {};
var isUnitlessNumber = {};
constructDefaults('xlink:href,xlink:arcrole,xlink:actuate,xlink:role,xlink:titlef,xlink:type', namespaces, xlinkNS);
constructDefaults('xml:base,xml:lang,xml:space', namespaces, xmlNS);
constructDefaults('volume,value', strictProps, true);
constructDefaults('muted,scoped,loop,open,checked,default,capture,disabled,selected,readonly,multiple,required,autoplay,controls,seamless,reversed,allowfullscreen,novalidate', booleanProps, true);
constructDefaults('animationIterationCount,borderImageOutset,borderImageSlice,borderImageWidth,boxFlex,boxFlexGroup,boxOrdinalGroup,columnCount,flex,flexGrow,flexPositive,flexShrink,flexNegative,flexOrder,gridRow,gridColumn,fontWeight,lineClamp,lineHeight,opacity,order,orphans,tabSize,widows,zIndex,zoom,fillOpacity,floodOpacity,stopOpacity,strokeDasharray,strokeDashoffset,strokeMiterlimit,strokeOpacity,strokeWidth,', isUnitlessNumber, true);
var screenWidth = isBrowser && window.screen.width;
var screenHeight = isBrowser && window.screen.height;
var scrollX = 0;
var scrollY = 0;
var lastScrollTime = 0;
if (isBrowser) {
window.onscroll = function () {
scrollX = window.scrollX;
scrollY = window.scrollY;
lastScrollTime = performance.now();
};
window.resize = function () { | 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.screenHeight = screenHeight;
this.screenWidth = screenWidth;
}
Lifecycle.prototype = {
refresh: function refresh() {
this.scrollX = isBrowser && window.scrollX;
this.scrollY = isBrowser && window.scrollY;
},
addListener: function addListener(callback) {
this._listeners.push(callback);
},
trigger: function trigger() {
var this$1 = this;
for (var i = 0; i < this._listeners.length; i++) {
this$1._listeners[i]();
}
}
};
var noOp = 'Inferno Error: Can only update a mounted or mounting component. This usually means you called setState() or forceUpdate() on an unmounted component. This is a no-op.';
// Copy of the util from dom/util, otherwise it makes massive bundles
function getActiveNode() {
return document.activeElement;
}
// Copy of the util from dom/util, otherwise it makes massive bundles
function resetActiveNode(activeNode) {
if (activeNode !== document.body && document.activeElement !== activeNode) {
activeNode.focus(); // TODO: verify are we doing new focus event, if user has focus listener this might trigger it
}
}
function queueStateChanges(component, newState, callback) {
for (var stateKey in newState) {
component._pendingState[stateKey] = newState[stateKey];
}
if (!component._pendingSetState) {
component._pendingSetState = true;
applyState(component, false, callback);
} else {
var pendingState = component._pendingState;
var oldState = component.state;
component.state = Object.assign({}, oldState, pendingState);
component._pendingState = {};
}
}
function applyState(component, force, callback) {
if (!component._deferSetState || force) {
component._pendingSetState = false;
var pendingState = component._pendingState;
var oldState = component.state;
var nextState = Object.assign({}, oldState, pendingState);
component._pendingState = {};
var nextNode = component._updateComponent(oldState, nextState, component.props, component.props, force);
if (nextNode === NO_RENDER) {
nextNode = component._lastNode;
} else if (isNullOrUndefined(nextNode)) {
nextNode = createVPlaceholder();
}
var lastNode = component._lastNode;
var parentDom = lastNode.dom.parentNode;
var activeNode = getActiveNode();
var subLifecycle = new Lifecycle();
component._patch(lastNode, nextNode, parentDom, subLifecycle, component.context, component, null);
component._lastNode = nextNode;
component._componentToDOMNodeMap.set(component, nextNode.dom);
component._parentNode.dom = nextNode.dom;
subLifecycle.trigger();
if (!isNullOrUndefined(callback)) {
callback();
}
resetActiveNode(activeNode);
}
}
var Component = function Component(props) {
/** @type {object} */
this.props = props || {};
/** @type {object} */
this.state = {};
/** @type {object} */
this.refs = {};
this._blockSetState = false;
this._deferSetState = false;
this._pendingSetState = false;
this._pendingState = {};
this._parentNode = null;
this._lastNode = null;
this._unmounted = true;
this.context = {};
this._patch = null;
this._parentComponent = null;
this._componentToDOMNodeMap = null;
};
Component.prototype.render = function render () {
};
Component.prototype.forceUpdate = function forceUpdate (callback) {
if (this._unmounted) {
throw Error(noOp);
}
applyState(this, true, callback);
};
Component.prototype.setState = function setState (newState, callback) {
if (this._unmounted) {
throw Error(noOp);
}
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.prototype.componentWillMount = function componentWillMount () {
};
Component.prototype.componentWillUnmount = function componentWillUnmount () {
};
Component.prototype.componentDidUpdate = function componentDidUpdate () {
};
Component.prototype.shouldComponentUpdate = function shouldComponentUpdate () {
return true;
};
Component.prototype.componentWillReceiveProps = function componentWillReceiveProps () {
};
Component.prototype.componentWillUpdate = function componentWillUpdate () {
};
Component.prototype.getChildContext = function getChildContext () {
};
Component.prototype._updateComponent = function _updateComponent (prevState, nextState, prevProps, nextProps, force) {
if (this._unmounted === true) {
this._unmounted = false;
return false;
}
if (!isNullOrUndefined(nextProps) && isNullOrUndefined(nextProps.children)) {
nextProps.children = prevProps.children;
}
if (prevProps !== nextProps || prevState !== nextState || force) {
if (prevProps !== nextProps) {
this._blockSetState = true;
this.componentWillReceiveProps(nextProps);
this._blockSetState = false;
}
var shouldUpdate = this.shouldComponentUpdate(nextProps, nextState);
if (shouldUpdate !== false) {
this._blockSetState = true;
this.componentWillUpdate(nextProps, nextState);
this._blockSetState = false;
this.props = nextProps;
this.state = nextState;
var node = this.render();
this.componentDidUpdate(prevProps, prevState);
return node;
}
}
return NO_RENDER;
};
var ASYNC_STATUS = {
pending: 'pending',
fulfilled: 'fulfilled',
rejected: 'rejected'
};
var Route = (function (Component) {
function Route(props) {
Component.call(this, props);
this.state = {
async: null
};
}
if ( Component ) Route.__proto__ = Component;
Route.prototype = Object.create( Component && Component.prototype );
Route.prototype.constructor = Route;
Route.prototype.async = function async () {
var this$1 = this;
var async = this.props.async;
if (async) {
this.setState({
async: { status: ASYNC_STATUS.pending }
});
async(this.props.params).then(function (value) {
this$1.setState({
async: {
status: ASYNC_STATUS.fulfilled,
value: value
}
});
}, this.reject).catch(this.reject);
}
};
Route.prototype.reject = function reject (value) {
this.setState({
async: {
status: ASYNC_STATUS.rejected,
value: value
}
});
};
Route.prototype.componentWillReceiveProps = function componentWillReceiveProps () {
this.async();
};
Route.prototype.componentWillMount = function componentWillMount () {
this.async();
};
Route.prototype.render = function render () {
var ref = this.props;
var component = ref.component;
var params = ref.params;
return createVNode().setTag(component).setAttrs({ params: params, async: this.state.async });
};
return Route;
}(Component));
var EMPTY$1 = {};
function segmentize(url) {
return strip(url).split('/');
}
function strip(url) {
return url.replace(/(^\/+|\/+$)/g, '');
}
function convertToHashbang(url) {
if (url.indexOf('#') === -1) {
url = '/';
} else {
var splitHashUrl = url.split('#!');
splitHashUrl.shift();
url = splitHashUrl.join('');
}
return url;
}
// Thanks goes to Preact for this function: https://github.com/developit/preact-router/blob/master/src/util.js#L4
function exec(url, route, opts) {
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])] = decodeURIComponent(r.slice(1).join('='));
}
}
url = segmentize(url.replace(reg, ''));
route = segmentize(route || '');
var max = Math.max(url.length, route.length);
var hasWildcard = false;
for (var i$1 = 0; i$1 < max; i$1++) {
if (route[i$1] && route[i$1].charAt(0) === ':') {
var param = route[i$1].replace(/(^\:|[+*?]+$)/g, ''),
flags = (route[i$1].match(/[+*?]+$/) || EMPTY$1)[0] || '',
plus = ~flags.indexOf('+'),
star = ~flags.indexOf('*'),
val = url[i$1] || '';
if (!val && !star && (flags.indexOf('?') < 0 || plus)) {
ret = false;
break;
}
matches[param] = decodeURIComponent(val);
if (plus || star) {
matches[param] = url.slice(i$1).map(decodeURIComponent).join('/');
break;
}
}
else if (route[i$1] !== url[i$1] && !hasWildcard) {
if (route[i$1] === '*' && route.length === i$1 + 1) {
hasWildcard = true;
} else {
ret = false;
break;
}
}
}
if (opts.default !== true && ret === false) {
return false;
}
return matches;
}
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 Router = (function (Component) {
function Router(props) {
Component.call(this, props);
if (!props.history) {
throw new Error('Inferno Error: "inferno-router" Router components require a "history" prop passed.');
}
this._didRoute = false;
this.state = {
url: props.url || props.history.getCurrentUrl()
};
}
if ( Component ) Router.__proto__ = Component;
Router.prototype = Object.create( Component && Component.prototype );
Router.prototype.constructor = Router;
Router.prototype.getChildContext = function getChildContext () {
return {
history: this.props.history,
hashbang: this.props.hashbang
};
};
Router.prototype.componentWillMount = function componentWillMount () {
this.props.history.addRouter(this);
};
Router.prototype.componentWillUnmount = function componentWillUnmount () {
this.props.history.removeRouter(this);
};
Router.prototype.routeTo = function routeTo (url) {
this._didRoute = false;
this.setState({ url: url });
return this._didRoute;
};
Router.prototype.render = function render () {
var children = toArray(this.props.children);
var url = this.props.url || this.state.url;
var wrapperComponent = this.props.component;
var hashbang = this.props.hashbang;
return handleRoutes(children, url, hashbang, wrapperComponent, '');
};
return Router;
}(Component));
function toArray(children) {
return isArray(children) ? children : (children ? [children] : children);
}
function handleRoutes(routes, url, hashbang, wrapperComponent, lastPath) {
routes.sort(pathRankSort);
for (var i = 0; i < routes.length; i++) {
var route = routes[i];
var ref = route.attrs;
var path = ref.path;
var fullPath = lastPath + path;
var params = exec(hashbang ? convertToHashbang(url) : url, fullPath);
var children = toArray(route.children);
if (children) {
var subRoute = handleRoutes(children, url, hashbang, wrapperComponent, fullPath);
if (!isNull(subRoute)) {
return subRoute;
}
}
if (params) {
if (wrapperComponent) {
return createVNode().setTag(wrapperComponent).setChildren(route).setAttrs({
params: params
});
}
return route.setAttrs(Object.assign({}, { params: params }, route.attrs));
}
}
return !lastPath && wrapperComponent ? createVNode().setTag(wrapperComponent) : null;
}
function Link(ref, ref$1) {
var to = ref.to;
var children = ref.children;
var hashbang = ref$1.hashbang;
var history = ref$1.history;
return (createVNode().setAttrs({
href: hashbang ? history.getHashbangRoot() + convertToHashbang('#!' + to) : to
}).setTag('a').setChildren(children));
}
var routers = [];
function getCurrentUrl() {
var url = typeof location !== 'undefined' ? location : EMPTY;
return ("" + (url.pathname || '') + (url.search || '') + (url.hash || ''));
}
function getHashbangRoot() {
var url = typeof location !== 'undefined' ? location : EMPTY;
return ("" + (url.protocol + '//' || '') + (url.host || '') + (url.pathname || '') + (url.search || '') + "#!");
}
function routeTo(url) {
var didRoute = false;
for (var i = 0; i < routers.length; i++) {
if (routers[i].routeTo(url) === true) {
didRoute = true;
}
}
return didRoute;
}
if (isBrowser) {
window.addEventListener('popstate', function () { return routeTo(getCurrentUrl()); });
}
var browserHistory = {
addRouter: function addRouter(router) {
routers.push(router);
},
removeRouter: function removeRouter(router) {
routers.splice(routers.indexOf(router), 1);
},
getCurrentUrl: getCurrentUrl,
getHashbangRoot: getHashbangRoot
};
var index = {
Route: Route,
Router: Router,
Link: Link,
browserHistory: browserHistory
};
return index;
})); | 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::Bindings::ProgressEventBinding;
use crate::dom::bindings::codegen::Bindings::ProgressEventBinding::ProgressEventMethods;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::event::{Event, EventBubbles, EventCancelable};
use crate::dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use servo_atoms::Atom;
#[dom_struct]
pub struct ProgressEvent {
event: Event,
length_computable: bool,
loaded: u64,
total: u64,
}
impl ProgressEvent {
fn new_inherited(length_computable: bool, loaded: u64, total: u64) -> ProgressEvent {
ProgressEvent {
event: Event::new_inherited(),
length_computable: length_computable,
loaded: loaded,
total: total,
}
}
pub fn new(
global: &GlobalScope,
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_computable,
loaded,
total,
)),
global,
ProgressEventBinding::Wrap,
);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bool::from(can_bubble), bool::from(cancelable));
}
ev
}
pub fn Constructor(
global: &GlobalScope,
type_: DOMString,
init: &ProgressEventBinding::ProgressEventInit,
) -> Fallible<DomRoot<ProgressEvent>> {
let bubbles = EventBubbles::from(init.parent.bubbles);
let cancelable = EventCancelable::from(init.parent.cancelable);
let ev = ProgressEvent::new(
global,
Atom::from(type_),
bubbles,
cancelable,
init.lengthComputable,
init.loaded,
init.total,
);
Ok(ev)
}
}
impl ProgressEventMethods for ProgressEvent {
// https://xhr.spec.whatwg.org/#dom-progressevent-lengthcomputable
fn LengthComputable(&self) -> bool {
self.length_computable
}
// https://xhr.spec.whatwg.org/#dom-progressevent-loaded
fn | (&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::Bindings::ProgressEventBinding;
use crate::dom::bindings::codegen::Bindings::ProgressEventBinding::ProgressEventMethods;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::event::{Event, EventBubbles, EventCancelable};
use crate::dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use servo_atoms::Atom;
#[dom_struct]
pub struct ProgressEvent {
event: Event,
length_computable: bool,
loaded: u64,
total: u64,
}
impl ProgressEvent {
fn new_inherited(length_computable: bool, loaded: u64, total: u64) -> ProgressEvent {
ProgressEvent {
event: Event::new_inherited(),
length_computable: length_computable,
loaded: loaded,
total: total, | 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_computable,
loaded,
total,
)),
global,
ProgressEventBinding::Wrap,
);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bool::from(can_bubble), bool::from(cancelable));
}
ev
}
pub fn Constructor(
global: &GlobalScope,
type_: DOMString,
init: &ProgressEventBinding::ProgressEventInit,
) -> Fallible<DomRoot<ProgressEvent>> {
let bubbles = EventBubbles::from(init.parent.bubbles);
let cancelable = EventCancelable::from(init.parent.cancelable);
let ev = ProgressEvent::new(
global,
Atom::from(type_),
bubbles,
cancelable,
init.lengthComputable,
init.loaded,
init.total,
);
Ok(ev)
}
}
impl ProgressEventMethods for ProgressEvent {
// https://xhr.spec.whatwg.org/#dom-progressevent-lengthcomputable
fn LengthComputable(&self) -> bool {
self.length_computable
}
// https://xhr.spec.whatwg.org/#dom-progressevent-loaded
fn Loaded(&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()
}
} | }
}
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 {
"a" => self.a = val,
"b" => self.b = val,
"c" => self.c = val,
"d" => self.d = val,
_ => panic!("invalid register {}!", name),
}
}
}
fn main() {
let mut f = File::open("data.txt").expect("unable to open file");
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 usize >= instructions.len() {
break;
}
let (op, args_str) = instructions[current_ins as usize].split_at(3);
let args: Vec<&str> = args_str.trim().split(" ").collect();
match op {
"cpy" => match args[0].parse::<i32>() {
Ok(n) => regs.set(args[1], n),
Err(_) => {
let val = regs.get(args[0]);
regs.set(args[1], val);
},
},
"inc" => regs.inc(args[0]),
"dec" => regs.dec(args[0]),
"jnz" => if match args[0].parse::<i32>() {
Ok(n) => n != 0,
Err(_) => regs.get(args[0]) != 0,
} {
current_ins += args[1].parse::<i32>().unwrap();
continue;
},
_ => (),
}
current_ins += 1;
}
println!("{}", regs.a);
}
| {
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,
"c" => self.c,
"d" => self.d,
_ => panic!("invalid register {}!", name),
}
}
fn | (&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.a = val,
"b" => self.b = val,
"c" => self.c = val,
"d" => self.d = val,
_ => panic!("invalid register {}!", name),
}
}
}
fn main() {
let mut f = File::open("data.txt").expect("unable to open file");
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 usize >= instructions.len() {
break;
}
let (op, args_str) = instructions[current_ins as usize].split_at(3);
let args: Vec<&str> = args_str.trim().split(" ").collect();
match op {
"cpy" => match args[0].parse::<i32>() {
Ok(n) => regs.set(args[1], n),
Err(_) => {
let val = regs.get(args[0]);
regs.set(args[1], val);
},
},
"inc" => regs.inc(args[0]),
"dec" => regs.dec(args[0]),
"jnz" => if match args[0].parse::<i32>() {
Ok(n) => n != 0,
Err(_) => regs.get(args[0]) != 0,
} {
current_ins += args[1].parse::<i32>().unwrap();
continue;
},
_ => (),
}
current_ins += 1;
}
println!("{}", regs.a);
}
| 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,
"c" => self.c,
"d" => self.d,
_ => panic!("invalid register {}!", name),
}
}
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 {
"a" => self.a = val,
"b" => self.b = val,
"c" => self.c = val,
"d" => self.d = val,
_ => panic!("invalid register {}!", name),
} | 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 usize >= instructions.len() {
break;
}
let (op, args_str) = instructions[current_ins as usize].split_at(3);
let args: Vec<&str> = args_str.trim().split(" ").collect();
match op {
"cpy" => match args[0].parse::<i32>() {
Ok(n) => regs.set(args[1], n),
Err(_) => {
let val = regs.get(args[0]);
regs.set(args[1], val);
},
},
"inc" => regs.inc(args[0]),
"dec" => regs.dec(args[0]),
"jnz" => if match args[0].parse::<i32>() {
Ok(n) => n != 0,
Err(_) => regs.get(args[0]) != 0,
} {
current_ins += args[1].parse::<i32>().unwrap();
continue;
},
_ => (),
}
current_ins += 1;
}
println!("{}", regs.a);
} | }
}
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 = require(require('path').dirname(
require.resolve('device-detector-js')
) + '/../package.json');
const version = package.version;
let benchmark = false;
const benchmarkPos = process.argv.indexOf('--benchmark');
if (benchmarkPos >= 0) {
process.argv.splice(benchmarkPos, 1);
benchmark = true;
}
const lineReader = require('readline').createInterface({ |
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 = detector.parse(line);
} catch (err) {
error = err;
result = {
useragent: line,
parsed: {
browser: {
name: null,
version: null
},
platform: {
name: null,
version: null
},
device: {
name: null,
brand: null,
type: null,
ismobile: null
}
}
};
}
const end = process.hrtime(start)[1] / 1000000000;
output.parse_time += end;
if (benchmark) {
return;
}
if (typeof r !== 'undefined') {
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
},
platform: {
name: r.os && r.os.name ? r.os.name : null,
version: r.os && r.os.version ? r.os.version : null
},
device: {
name: r.device && r.device.model ? r.device.model : null,
brand: r.device && r.device.brand ? r.device.brand : null,
type: r.device && r.device.type ? r.device.type : null,
ismobile:
r.device &&
(r.device.type === 'mobile' ||
r.device.type === 'mobilephone' ||
r.device.type === 'tablet' ||
r.device.type === 'wearable')
? true
: false
}
},
time: end,
error: error
};
} 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));
}); | 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 = require(require('path').dirname(
require.resolve('device-detector-js')
) + '/../package.json');
const version = package.version;
let benchmark = false;
const benchmarkPos = process.argv.indexOf('--benchmark');
if (benchmarkPos >= 0) {
process.argv.splice(benchmarkPos, 1);
benchmark = true;
}
const lineReader = require('readline').createInterface({
input: require('fs').createReadStream(process.argv[2])
});
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 = detector.parse(line);
} catch (err) {
error = err;
result = {
useragent: line,
parsed: {
browser: {
name: null,
version: null
},
platform: {
name: null,
version: null
},
device: {
name: null,
brand: null,
type: null,
ismobile: null
}
}
};
}
const end = process.hrtime(start)[1] / 1000000000;
output.parse_time += end;
if (benchmark) {
return;
}
if (typeof r !== 'undefined') | 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
},
platform: {
name: r.os && r.os.name ? r.os.name : null,
version: r.os && r.os.version ? r.os.version : null
},
device: {
name: r.device && r.device.model ? r.device.model : null,
brand: r.device && r.device.brand ? r.device.brand : null,
type: r.device && r.device.type ? r.device.type : null,
ismobile:
r.device &&
(r.device.type === 'mobile' ||
r.device.type === 'mobilephone' ||
r.device.type === 'tablet' ||
r.device.type === 'wearable')
? true
: false
}
},
time: end,
error: error
};
} | 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.views.generic import RedirectView
# Wiki imports
from wiki.urls import get_pattern as get_wiki_pattern
from django_notify.urls import get_pattern as get_notify_pattern
from djangobb_forum import settings as forum_settings
admin.autodiscover()
# Setup the root url tree from /
# AJAX stuff.
from dajaxice.core import dajaxice_autodiscover, dajaxice_config
dajaxice_autodiscover()
urlpatterns = patterns('',
# User Authentication
url(r'^login/', 'web.views.login', name="login"),
url(r'^logout/', 'django.contrib.auth.views.logout', name="logout"),
url(r'^accounts/login', 'views.login_gateway'),
# News stuff
#url(r'^news/', include('src.web.news.urls')),
# Page place-holder for things that aren't implemented yet.
url(r'^tbi/', 'game.gamesrc.oasis.web.website.views.to_be_implemented'),
# Admin interface
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
# favicon
url(r'^favicon\.ico$', RedirectView.as_view(url='/media/images/favicon.ico')),
# ajax stuff
url(r'^webclient/',include('game.gamesrc.oasis.web.webclient.urls', namespace="webclient")),
# Wiki
url(r'^notify/', get_notify_pattern()),
url(r'^wiki/', get_wiki_pattern()),
# Forum
(r'^forum/', include('bb_urls', namespace='djangobb')),
# Favicon
(r'^favicon\.ico$', RedirectView.as_view(url='/media/images/favicon.ico')),
# 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/', include('haystack.urls', namespace='search')),
# AJAX stuff
url(dajaxice_config.dajaxice_url, include('dajaxice.urls')),
url(r'^selectable/', include('selectable.urls')),
# Ticket system
url(r'^tickets/', include('helpdesk.urls', namespace='helpdesk')),
url(r'^$', 'views.page_index', name='index'),
)
# 500 Errors:
handler500 = 'web.views.custom_500'
# This sets up the server if the user want to run the Django
# test server (this should normally not be needed).
if settings.SERVE_MEDIA:
|
# 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_ROOT}),
)
| 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', {'document_root': settings.STATIC_ROOT + '/wiki/'})
) | 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.views.generic import RedirectView
# Wiki imports
from wiki.urls import get_pattern as get_wiki_pattern
from django_notify.urls import get_pattern as get_notify_pattern
from djangobb_forum import settings as forum_settings
admin.autodiscover()
# Setup the root url tree from /
# AJAX stuff.
from dajaxice.core import dajaxice_autodiscover, dajaxice_config
dajaxice_autodiscover()
urlpatterns = patterns('',
# User Authentication
url(r'^login/', 'web.views.login', name="login"),
url(r'^logout/', 'django.contrib.auth.views.logout', name="logout"),
url(r'^accounts/login', 'views.login_gateway'),
# News stuff
#url(r'^news/', include('src.web.news.urls')),
# Page place-holder for things that aren't implemented yet.
url(r'^tbi/', 'game.gamesrc.oasis.web.website.views.to_be_implemented'),
# Admin interface
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
# favicon
url(r'^favicon\.ico$', RedirectView.as_view(url='/media/images/favicon.ico')),
# ajax stuff
url(r'^webclient/',include('game.gamesrc.oasis.web.webclient.urls', namespace="webclient")),
# Wiki
url(r'^notify/', get_notify_pattern()),
url(r'^wiki/', get_wiki_pattern()),
# Forum
(r'^forum/', include('bb_urls', namespace='djangobb')),
# Favicon |
# 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/', include('haystack.urls', namespace='search')),
# AJAX stuff
url(dajaxice_config.dajaxice_url, include('dajaxice.urls')),
url(r'^selectable/', include('selectable.urls')),
# Ticket system
url(r'^tickets/', include('helpdesk.urls', namespace='helpdesk')),
url(r'^$', 'views.page_index', name='index'),
)
# 500 Errors:
handler500 = 'web.views.custom_500'
# This sets up the server if the user want to run the Django
# test server (this should normally not be needed).
if settings.SERVE_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', {'document_root': settings.STATIC_ROOT + '/wiki/'})
)
# 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_ROOT}),
) | (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 = np.zeros(sh).astype(np.bool_)
actual_notnull = nan_to_zero(neg)
np.testing.assert_array_equal(neg, np.zeros(sh))
np.testing.assert_array_equal(actual_notnull, expected_notnull)
def test_nan_to_zero_with_mixed(self):
test_cases = (
(np.array([-1, np.nan, 1e6, -1e6]), np.array([0, 0, 1e6, 0])),
(np.arange(-2, 7).reshape((3, 3)), np.array([[0, 0, 0], np.arange(1, 4), np.arange(4, 7)])),
)
for input_, expected in test_cases:
nan_to_zero(input_)
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_, [])
in_ = np.array([])
notnull = nan_to_zero(in_)
self.assertSequenceEqual(in_, [])
self.assertSequenceEqual(notnull, [])
def test_quantile_threshold_ValueError(self):
test_cases = (
(np.arange(0), np.arange(0, dtype=np.bool_), -37),
(np.arange(0), np.arange(0, dtype=np.bool_), -4.4),
(np.arange(0), np.arange(0, dtype=np.bool_), 101)
)
kws = ('im', 'notnull_mask', 'q_val',)
for args in test_cases:
kwargs = {kw: val for kw, val in zip(kws, args)}
self.assertRaises(ValueError, quantile_threshold, **kwargs)
def test_quantile_threshold_trivial(self):
test_cases = (
((np.arange(10), np.ones(10, dtype=np.bool_), 100), (np.arange(10), 9)),
(
(np.arange(101, dtype=np.float32), np.ones(101, dtype=np.bool_), 100. / 3),
(np.concatenate((np.arange(34), np.repeat(100. / 3, 67))), 100. / 3),
),
(
(np.arange(20), np.repeat([True, False], 10), 100),
(np.concatenate((np.arange(10), np.repeat(9, 10))), 9)
),
)
kws = ('im', 'notnull_mask', 'q_val',)
for args, expected in test_cases:
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, decimal=6)
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[0, 0], 0)
self.assertAlmostEqual(im_out[2, 3], 63)
if __name__ == '__main__':
unittest.main()
| 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 != 0) | 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)
)
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 != 0)
def | (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_)
actual_notnull = nan_to_zero(neg)
np.testing.assert_array_equal(neg, np.zeros(sh))
np.testing.assert_array_equal(actual_notnull, expected_notnull)
def test_nan_to_zero_with_mixed(self):
test_cases = (
(np.array([-1, np.nan, 1e6, -1e6]), np.array([0, 0, 1e6, 0])),
(np.arange(-2, 7).reshape((3, 3)), np.array([[0, 0, 0], np.arange(1, 4), np.arange(4, 7)])),
)
for input_, expected in test_cases:
nan_to_zero(input_)
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_, [])
in_ = np.array([])
notnull = nan_to_zero(in_)
self.assertSequenceEqual(in_, [])
self.assertSequenceEqual(notnull, [])
def test_quantile_threshold_ValueError(self):
test_cases = (
(np.arange(0), np.arange(0, dtype=np.bool_), -37),
(np.arange(0), np.arange(0, dtype=np.bool_), -4.4),
(np.arange(0), np.arange(0, dtype=np.bool_), 101)
)
kws = ('im', 'notnull_mask', 'q_val',)
for args in test_cases:
kwargs = {kw: val for kw, val in zip(kws, args)}
self.assertRaises(ValueError, quantile_threshold, **kwargs)
def test_quantile_threshold_trivial(self):
test_cases = (
((np.arange(10), np.ones(10, dtype=np.bool_), 100), (np.arange(10), 9)),
(
(np.arange(101, dtype=np.float32), np.ones(101, dtype=np.bool_), 100. / 3),
(np.concatenate((np.arange(34), np.repeat(100. / 3, 67))), 100. / 3),
),
(
(np.arange(20), np.repeat([True, False], 10), 100),
(np.concatenate((np.arange(10), np.repeat(9, 10))), 9)
),
)
kws = ('im', 'notnull_mask', 'q_val',)
for args, expected in test_cases:
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, decimal=6)
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[0, 0], 0)
self.assertAlmostEqual(im_out[2, 3], 63)
if __name__ == '__main__':
unittest.main()
| 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)
)
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 != 0)
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 = np.zeros(sh).astype(np.bool_)
actual_notnull = nan_to_zero(neg)
np.testing.assert_array_equal(neg, np.zeros(sh))
np.testing.assert_array_equal(actual_notnull, expected_notnull)
def test_nan_to_zero_with_mixed(self):
test_cases = (
(np.array([-1, np.nan, 1e6, -1e6]), np.array([0, 0, 1e6, 0])),
(np.arange(-2, 7).reshape((3, 3)), np.array([[0, 0, 0], np.arange(1, 4), np.arange(4, 7)])),
)
for input_, expected in test_cases:
nan_to_zero(input_)
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_, [])
in_ = np.array([])
notnull = nan_to_zero(in_)
self.assertSequenceEqual(in_, [])
self.assertSequenceEqual(notnull, [])
def test_quantile_threshold_ValueError(self):
test_cases = (
(np.arange(0), np.arange(0, dtype=np.bool_), -37),
(np.arange(0), np.arange(0, dtype=np.bool_), -4.4),
(np.arange(0), np.arange(0, dtype=np.bool_), 101)
)
kws = ('im', 'notnull_mask', 'q_val',)
for args in test_cases:
kwargs = {kw: val for kw, val in zip(kws, args)}
self.assertRaises(ValueError, quantile_threshold, **kwargs)
def test_quantile_threshold_trivial(self):
test_cases = (
((np.arange(10), np.ones(10, dtype=np.bool_), 100), (np.arange(10), 9)),
(
(np.arange(101, dtype=np.float32), np.ones(101, dtype=np.bool_), 100. / 3),
(np.concatenate((np.arange(34), np.repeat(100. / 3, 67))), 100. / 3),
),
(
(np.arange(20), np.repeat([True, False], 10), 100),
(np.concatenate((np.arange(10), np.repeat(9, 10))), 9)
),
)
kws = ('im', 'notnull_mask', 'q_val',)
for args, expected in test_cases:
|
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[0, 0], 0)
self.assertAlmostEqual(im_out[2, 3], 63)
if __name__ == '__main__':
unittest.main()
| 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, decimal=6) | 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)
)
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 != 0)
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 = np.zeros(sh).astype(np.bool_)
actual_notnull = nan_to_zero(neg)
np.testing.assert_array_equal(neg, np.zeros(sh))
np.testing.assert_array_equal(actual_notnull, expected_notnull)
def test_nan_to_zero_with_mixed(self):
test_cases = (
(np.array([-1, np.nan, 1e6, -1e6]), np.array([0, 0, 1e6, 0])),
(np.arange(-2, 7).reshape((3, 3)), np.array([[0, 0, 0], np.arange(1, 4), np.arange(4, 7)])), | 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_, [])
in_ = np.array([])
notnull = nan_to_zero(in_)
self.assertSequenceEqual(in_, [])
self.assertSequenceEqual(notnull, [])
def test_quantile_threshold_ValueError(self):
test_cases = (
(np.arange(0), np.arange(0, dtype=np.bool_), -37),
(np.arange(0), np.arange(0, dtype=np.bool_), -4.4),
(np.arange(0), np.arange(0, dtype=np.bool_), 101)
)
kws = ('im', 'notnull_mask', 'q_val',)
for args in test_cases:
kwargs = {kw: val for kw, val in zip(kws, args)}
self.assertRaises(ValueError, quantile_threshold, **kwargs)
def test_quantile_threshold_trivial(self):
test_cases = (
((np.arange(10), np.ones(10, dtype=np.bool_), 100), (np.arange(10), 9)),
(
(np.arange(101, dtype=np.float32), np.ones(101, dtype=np.bool_), 100. / 3),
(np.concatenate((np.arange(34), np.repeat(100. / 3, 67))), 100. / 3),
),
(
(np.arange(20), np.repeat([True, False], 10), 100),
(np.concatenate((np.arange(10), np.repeat(9, 10))), 9)
),
)
kws = ('im', 'notnull_mask', 'q_val',)
for args, expected in test_cases:
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, decimal=6)
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[0, 0], 0)
self.assertAlmostEqual(im_out[2, 3], 63)
if __name__ == '__main__':
unittest.main() | )
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::string::ToString;
use std::{f64, str};
use super::{Json, JsonRef, JsonType};
use crate::codec::Error;
impl<'a> ToString for JsonRef<'a> {
fn to_string(&self) -> String {
serde_json::to_string(self).unwrap()
}
}
impl<'a> Serialize for JsonRef<'a> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self.get_type() {
JsonType::Literal => match self.get_literal() {
Some(b) => serializer.serialize_bool(b),
None => serializer.serialize_none(),
},
JsonType::String => match self.get_str() {
Ok(s) => serializer.serialize_str(s),
Err(_) => Err(SerError::custom("json contains invalid UTF-8 characters")),
},
JsonType::Double => serializer.serialize_f64(self.get_double()),
JsonType::I64 => serializer.serialize_i64(self.get_i64()),
JsonType::U64 => serializer.serialize_u64(self.get_u64()),
JsonType::Object => {
let elem_count = self.get_elem_count();
let mut map = serializer.serialize_map(Some(elem_count))?;
for i in 0..elem_count {
let key = self.object_get_key(i);
let val = self.object_get_val(i).map_err(SerError::custom)?;
map.serialize_entry(str::from_utf8(key).unwrap(), &val)?;
}
map.end()
}
JsonType::Array => {
let elem_count = self.get_elem_count();
let mut tup = serializer.serialize_tuple(elem_count)?;
for i in 0..elem_count {
let item = self.array_get_elem(i).map_err(SerError::custom)?;
tup.serialize_element(&item)?;
}
tup.end()
}
}
}
}
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> |
}
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::none().map_err(de::Error::custom)?)
}
fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Json::from_bool(v).map_err(de::Error::custom)?)
}
fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Json::from_i64(v).map_err(de::Error::custom)?)
}
fn visit_u64<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, v: f64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Json::from_f64(v).map_err(de::Error::custom)?)
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Json::from_string(String::from(v)).map_err(de::Error::custom)?)
}
fn visit_seq<M>(self, mut seq: M) -> Result<Self::Value, M::Error>
where
M: SeqAccess<'de>,
{
let size = seq.size_hint().unwrap_or_default();
let mut value = Vec::with_capacity(size);
while let Some(v) = seq.next_element()? {
value.push(v);
}
Ok(Json::from_array(value).map_err(de::Error::custom)?)
}
fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
where
M: MapAccess<'de>,
{
let mut map = BTreeMap::new();
while let Some((key, value)) = access.next_entry()? {
map.insert(key, value);
}
Ok(Json::from_object(map).map_err(de::Error::custom)?)
}
}
impl<'de> Deserialize<'de> for Json {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(JsonVisitor)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_from_str_for_object() {
let jstr1 = r#"{"a": [1, "2", {"aa": "bb"}, 4.0, null], "c": null,"b": true}"#;
let j1: Json = jstr1.parse().unwrap();
let jstr2 = j1.to_string();
let expect_str = r#"{"a":[1,"2",{"aa":"bb"},4.0,null],"b":true,"c":null}"#;
assert_eq!(jstr2, expect_str);
}
#[test]
fn test_from_str() {
let legal_cases = vec![
(r#"{"key":"value"}"#),
(r#"["d1","d2"]"#),
(r#"-3"#),
(r#"3"#),
(r#"3.0"#),
(r#"null"#),
(r#"true"#),
(r#"false"#),
];
for json_str in legal_cases {
let resp = Json::from_str(json_str);
assert!(resp.is_ok());
}
let cases = vec![
(
r#"9223372036854776000"#,
Json::from_f64(9223372036854776000.0),
),
(
r#"9223372036854775807"#,
Json::from_i64(9223372036854775807),
),
];
for (json_str, json) in cases {
let resp = Json::from_str(json_str);
assert!(resp.is_ok());
assert_eq!(resp.unwrap(), json.unwrap());
}
let illegal_cases = vec!["[pxx,apaa]", "hpeheh", ""];
for json_str in illegal_cases {
let resp = Json::from_str(json_str);
assert!(resp.is_err());
}
}
}
| {
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::string::ToString;
use std::{f64, str};
use super::{Json, JsonRef, JsonType};
use crate::codec::Error;
impl<'a> ToString for JsonRef<'a> {
fn to_string(&self) -> String {
serde_json::to_string(self).unwrap()
}
}
impl<'a> Serialize for JsonRef<'a> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self.get_type() {
JsonType::Literal => match self.get_literal() {
Some(b) => serializer.serialize_bool(b),
None => serializer.serialize_none(),
},
JsonType::String => match self.get_str() {
Ok(s) => serializer.serialize_str(s),
Err(_) => Err(SerError::custom("json contains invalid UTF-8 characters")),
},
JsonType::Double => serializer.serialize_f64(self.get_double()),
JsonType::I64 => serializer.serialize_i64(self.get_i64()),
JsonType::U64 => serializer.serialize_u64(self.get_u64()),
JsonType::Object => {
let elem_count = self.get_elem_count();
let mut map = serializer.serialize_map(Some(elem_count))?;
for i in 0..elem_count {
let key = self.object_get_key(i);
let val = self.object_get_val(i).map_err(SerError::custom)?;
map.serialize_entry(str::from_utf8(key).unwrap(), &val)?;
}
map.end()
}
JsonType::Array => {
let elem_count = self.get_elem_count();
let mut tup = serializer.serialize_tuple(elem_count)?;
for i in 0..elem_count {
let item = self.array_get_elem(i).map_err(SerError::custom)?;
tup.serialize_element(&item)?; | }
}
}
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),
Err(e) => Err(invalid_type!("Illegal Json text: {:?}", e)),
}
}
}
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::none().map_err(de::Error::custom)?)
}
fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Json::from_bool(v).map_err(de::Error::custom)?)
}
fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Json::from_i64(v).map_err(de::Error::custom)?)
}
fn visit_u64<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, v: f64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Json::from_f64(v).map_err(de::Error::custom)?)
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Json::from_string(String::from(v)).map_err(de::Error::custom)?)
}
fn visit_seq<M>(self, mut seq: M) -> Result<Self::Value, M::Error>
where
M: SeqAccess<'de>,
{
let size = seq.size_hint().unwrap_or_default();
let mut value = Vec::with_capacity(size);
while let Some(v) = seq.next_element()? {
value.push(v);
}
Ok(Json::from_array(value).map_err(de::Error::custom)?)
}
fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
where
M: MapAccess<'de>,
{
let mut map = BTreeMap::new();
while let Some((key, value)) = access.next_entry()? {
map.insert(key, value);
}
Ok(Json::from_object(map).map_err(de::Error::custom)?)
}
}
impl<'de> Deserialize<'de> for Json {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(JsonVisitor)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_from_str_for_object() {
let jstr1 = r#"{"a": [1, "2", {"aa": "bb"}, 4.0, null], "c": null,"b": true}"#;
let j1: Json = jstr1.parse().unwrap();
let jstr2 = j1.to_string();
let expect_str = r#"{"a":[1,"2",{"aa":"bb"},4.0,null],"b":true,"c":null}"#;
assert_eq!(jstr2, expect_str);
}
#[test]
fn test_from_str() {
let legal_cases = vec![
(r#"{"key":"value"}"#),
(r#"["d1","d2"]"#),
(r#"-3"#),
(r#"3"#),
(r#"3.0"#),
(r#"null"#),
(r#"true"#),
(r#"false"#),
];
for json_str in legal_cases {
let resp = Json::from_str(json_str);
assert!(resp.is_ok());
}
let cases = vec![
(
r#"9223372036854776000"#,
Json::from_f64(9223372036854776000.0),
),
(
r#"9223372036854775807"#,
Json::from_i64(9223372036854775807),
),
];
for (json_str, json) in cases {
let resp = Json::from_str(json_str);
assert!(resp.is_ok());
assert_eq!(resp.unwrap(), json.unwrap());
}
let illegal_cases = vec!["[pxx,apaa]", "hpeheh", ""];
for json_str in illegal_cases {
let resp = Json::from_str(json_str);
assert!(resp.is_err());
}
}
} | }
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::string::ToString;
use std::{f64, str};
use super::{Json, JsonRef, JsonType};
use crate::codec::Error;
impl<'a> ToString for JsonRef<'a> {
fn to_string(&self) -> String {
serde_json::to_string(self).unwrap()
}
}
impl<'a> Serialize for JsonRef<'a> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self.get_type() {
JsonType::Literal => match self.get_literal() {
Some(b) => serializer.serialize_bool(b),
None => serializer.serialize_none(),
},
JsonType::String => match self.get_str() {
Ok(s) => serializer.serialize_str(s),
Err(_) => Err(SerError::custom("json contains invalid UTF-8 characters")),
},
JsonType::Double => serializer.serialize_f64(self.get_double()),
JsonType::I64 => serializer.serialize_i64(self.get_i64()),
JsonType::U64 => serializer.serialize_u64(self.get_u64()),
JsonType::Object => {
let elem_count = self.get_elem_count();
let mut map = serializer.serialize_map(Some(elem_count))?;
for i in 0..elem_count {
let key = self.object_get_key(i);
let val = self.object_get_val(i).map_err(SerError::custom)?;
map.serialize_entry(str::from_utf8(key).unwrap(), &val)?;
}
map.end()
}
JsonType::Array => {
let elem_count = self.get_elem_count();
let mut tup = serializer.serialize_tuple(elem_count)?;
for i in 0..elem_count {
let item = self.array_get_elem(i).map_err(SerError::custom)?;
tup.serialize_element(&item)?;
}
tup.end()
}
}
}
}
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),
Err(e) => Err(invalid_type!("Illegal Json text: {:?}", e)),
}
}
}
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::none().map_err(de::Error::custom)?)
}
fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Json::from_bool(v).map_err(de::Error::custom)?)
}
fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Json::from_i64(v).map_err(de::Error::custom)?)
}
fn | <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, v: f64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Json::from_f64(v).map_err(de::Error::custom)?)
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(Json::from_string(String::from(v)).map_err(de::Error::custom)?)
}
fn visit_seq<M>(self, mut seq: M) -> Result<Self::Value, M::Error>
where
M: SeqAccess<'de>,
{
let size = seq.size_hint().unwrap_or_default();
let mut value = Vec::with_capacity(size);
while let Some(v) = seq.next_element()? {
value.push(v);
}
Ok(Json::from_array(value).map_err(de::Error::custom)?)
}
fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
where
M: MapAccess<'de>,
{
let mut map = BTreeMap::new();
while let Some((key, value)) = access.next_entry()? {
map.insert(key, value);
}
Ok(Json::from_object(map).map_err(de::Error::custom)?)
}
}
impl<'de> Deserialize<'de> for Json {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(JsonVisitor)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_from_str_for_object() {
let jstr1 = r#"{"a": [1, "2", {"aa": "bb"}, 4.0, null], "c": null,"b": true}"#;
let j1: Json = jstr1.parse().unwrap();
let jstr2 = j1.to_string();
let expect_str = r#"{"a":[1,"2",{"aa":"bb"},4.0,null],"b":true,"c":null}"#;
assert_eq!(jstr2, expect_str);
}
#[test]
fn test_from_str() {
let legal_cases = vec![
(r#"{"key":"value"}"#),
(r#"["d1","d2"]"#),
(r#"-3"#),
(r#"3"#),
(r#"3.0"#),
(r#"null"#),
(r#"true"#),
(r#"false"#),
];
for json_str in legal_cases {
let resp = Json::from_str(json_str);
assert!(resp.is_ok());
}
let cases = vec![
(
r#"9223372036854776000"#,
Json::from_f64(9223372036854776000.0),
),
(
r#"9223372036854775807"#,
Json::from_i64(9223372036854775807),
),
];
for (json_str, json) in cases {
let resp = Json::from_str(json_str);
assert!(resp.is_ok());
assert_eq!(resp.unwrap(), json.unwrap());
}
let illegal_cases = vec!["[pxx,apaa]", "hpeheh", ""];
for json_str in illegal_cases {
let resp = Json::from_str(json_str);
assert!(resp.is_err());
}
}
}
| 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("");
});
it("keeps white-space only string", () => {
expect(new Atbash().convert(" \n\r\t")).toBe(" \n\r\t");
});
it("keeps non-alphabet characters", () => {
expect(new Atbash().convert("1ö_<")).toBe("1ö_<");
});
it("converts normal lower-case characters", () => {
expect(new Atbash().convert("foobar")).toBe("ullyzi");
});
it("converts normal upper-case characters", () => {
expect(new Atbash().convert("FOOBAR")).toBe("ULLYZI");
});
it("converts normal mixed-case characters", () => {
expect(new Atbash().convert("FooBar")).toBe("UllYzi");
});
it("converts only normal characters in mixed string", () => { | });
describe("toJSON", () => {
it("serializes the converter", () => {
expect(new Atbash().toJSON()).toEqual({
"type": "atbash"
});
});
});
describe("fromJSON", () => {
it("deserializes a converter", () => {
const converter = Converter.fromJSON<Atbash>({ "type": "atbash" });
expect(converter).toEqual(jasmine.any(Atbash));
});
});
}); | 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',
templateUrl: './course-delete.component.html',
styleUrls: ['./course-delete.component.css']
})
export class CourseDeleteComponent implements OnInit {
public pageTitle: string = 'Courses';
public course: ICourse;
errorMessage: string;
private sub: Subscription;
constructor(private _route: ActivatedRoute,
private _router: Router,
private _courseService: CourseService) { }
| () {
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 => this.errorMessage = <any>error);
}
onBack(): void {
this._router.navigate(['/courses']);
}
submitClick(): void {
this._courseService.deleteCourse(this.course.courseID)
.subscribe(course => {
this._router.navigate(['/courses']);
},
error => this.errorMessage = <any>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',
templateUrl: './course-delete.component.html',
styleUrls: ['./course-delete.component.css']
})
export class CourseDeleteComponent implements OnInit {
public pageTitle: string = 'Courses';
public course: ICourse;
errorMessage: string;
private sub: Subscription;
constructor(private _route: ActivatedRoute,
private _router: Router,
private _courseService: CourseService) { }
ngOnInit() {
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 => this.errorMessage = <any>error);
}
onBack(): void {
this._router.navigate(['/courses']);
}
submitClick(): void {
this._courseService.deleteCourse(this.course.courseID)
.subscribe(course => {
this._router.navigate(['/courses']);
}, | 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.ret)
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, "r") as myfile:
self.ret=myfile.read()
if __name__ == "__main__":
s = ProtoServer(("192.168.1.253", 6661),"index.html")
s.serve_forever()
| 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:
self.request.sendall(self.server.ret)
else:
self.server.data=a
print a
class ProtoServer(SocketServer.TCPServer):
|
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, "r") as myfile:
self.ret=myfile.read()
if __name__ == "__main__":
s = ProtoServer(("192.168.1.253", 6661),"index.html")
s.serve_forever()
| 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:
self.request.sendall(self.server.ret)
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, "r") as myfile:
self.ret=myfile.read()
|
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;
void main() {
out_pos = in_pos * 2.0 - in_prev + acc;
out_prev = in_pos;
}
''')
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])
transform = ctx.program(tvert, ['out_pos', 'out_prev'])
def particle():
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, 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']),
])
transform.uniforms['acc'].value = (0, -0.0001)
idx = 0
ctx.point_size = 5.0
while wnd.update():
ctx.viewport = wnd.viewport
ctx.clear(0.9, 0.9, 0.9)
for i in range(8):
|
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;
void main() {
out_pos = in_pos * 2.0 - in_prev + acc;
out_prev = in_pos;
}
''')
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])
transform = ctx.program(tvert, ['out_pos', 'out_prev'])
def particle():
|
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']),
])
transform.uniforms['acc'].value = (0, -0.0001)
idx = 0
ctx.point_size = 5.0
while wnd.update():
ctx.viewport = wnd.viewport
ctx.clear(0.9, 0.9, 0.9)
for i in range(8):
vbo1.write(particle(), offset=idx * struct.calcsize('2f2f'))
idx = (idx + 1) % 1024
render_vao.render(ModernGL.POINTS, 1024)
vao1.transform(vbo2, ModernGL.POINTS, 1024)
ctx.copy_buffer(vbo1, vbo2)
| 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;
void main() {
out_pos = in_pos * 2.0 - in_prev + acc;
out_prev = in_pos;
}
''')
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])
transform = ctx.program(tvert, ['out_pos', 'out_prev'])
def | ():
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, 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']),
])
transform.uniforms['acc'].value = (0, -0.0001)
idx = 0
ctx.point_size = 5.0
while wnd.update():
ctx.viewport = wnd.viewport
ctx.clear(0.9, 0.9, 0.9)
for i in range(8):
vbo1.write(particle(), offset=idx * struct.calcsize('2f2f'))
idx = (idx + 1) % 1024
render_vao.render(ModernGL.POINTS, 1024)
vao1.transform(vbo2, ModernGL.POINTS, 1024)
ctx.copy_buffer(vbo1, vbo2)
| 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;
void main() { | 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])
transform = ctx.program(tvert, ['out_pos', 'out_prev'])
def particle():
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, 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']),
])
transform.uniforms['acc'].value = (0, -0.0001)
idx = 0
ctx.point_size = 5.0
while wnd.update():
ctx.viewport = wnd.viewport
ctx.clear(0.9, 0.9, 0.9)
for i in range(8):
vbo1.write(particle(), offset=idx * struct.calcsize('2f2f'))
idx = (idx + 1) % 1024
render_vao.render(ModernGL.POINTS, 1024)
vao1.transform(vbo2, ModernGL.POINTS, 1024)
ctx.copy_buffer(vbo1, vbo2) | 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 ( path )
break
case 'select':
newselection = op.value
newselection.stringPath = `${BASE_PATH}.${newselection.anchorPath.join('.i.')}`
break
case 'toolbox':
state.set ( TOOLBOX_PATH, op.value )
break
default:
throw new Error ( `Unkown operation '${op.op}'` )
}
}
)
if ( newselection ) {
// FIXME: global.selection is bad find another way
global.selection = newselection
return { selection: newselection }
}
} | 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':
state.unset ( path )
break
case 'select':
newselection = op.value
newselection.stringPath = `${BASE_PATH}.${newselection.anchorPath.join('.i.')}`
break
case 'toolbox':
state.set ( TOOLBOX_PATH, op.value )
break
default:
throw new Error ( `Unkown operation '${op.op}'` )
}
}
)
if ( newselection ) {
// FIXME: global.selection is bad find another way
global.selection = newselection
return { selection: newselection }
}
}
| processOps | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.