text stringlengths 0 1.05M | meta dict |
|---|---|
from functools import partial
import os
import unittest
from nose.tools import assert_equal, assert_list_equal, nottest, raises
from py_stringmatching.tokenizer.delimiter_tokenizer import DelimiterTokenizer
from py_stringmatching.tokenizer.qgram_tokenizer import QgramTokenizer
from six import iteritems
import pandas as pd
from py_stringsimjoin.join.cosine_join import cosine_join
from py_stringsimjoin.join.dice_join import dice_join
from py_stringsimjoin.join.jaccard_join import jaccard_join
from py_stringsimjoin.join.overlap_coefficient_join import overlap_coefficient_join
from py_stringsimjoin.join.overlap_join import overlap_join
from py_stringsimjoin.utils.converter import dataframe_column_to_str
from py_stringsimjoin.utils.generic_helper import COMP_OP_MAP, \
remove_redundant_attrs
from py_stringsimjoin.utils.simfunctions import get_sim_function
JOIN_FN_MAP = {'COSINE': cosine_join,
'DICE': dice_join,
'JACCARD': jaccard_join,
'OVERLAP_COEFFICIENT': overlap_coefficient_join}
DEFAULT_COMP_OP = '>='
DEFAULT_L_OUT_PREFIX = 'l_'
DEFAULT_R_OUT_PREFIX = 'r_'
@nottest
def test_valid_join(scenario, sim_measure_type, args, convert_to_str=False):
(ltable_path, l_key_attr, l_join_attr) = scenario[0]
(rtable_path, r_key_attr, r_join_attr) = scenario[1]
join_fn = JOIN_FN_MAP[sim_measure_type]
# load input tables for the tests.
ltable = pd.read_csv(os.path.join(os.path.dirname(__file__),
ltable_path))
rtable = pd.read_csv(os.path.join(os.path.dirname(__file__),
rtable_path))
if convert_to_str:
dataframe_column_to_str(ltable, l_join_attr, inplace=True)
dataframe_column_to_str(rtable, r_join_attr, inplace=True)
missing_pairs = set()
# if allow_missing flag is set, compute missing pairs.
if len(args) > 4 and args[4]:
for l_idx, l_row in ltable.iterrows():
for r_idx, r_row in rtable.iterrows():
if (pd.isnull(l_row[l_join_attr]) or
pd.isnull(r_row[r_join_attr])):
missing_pairs.add(','.join((str(l_row[l_key_attr]),
str(r_row[r_key_attr]))))
# remove rows with missing value in join attribute and create new dataframes
# consisting of rows with non-missing values.
ltable_not_missing = ltable[pd.notnull(ltable[l_join_attr])].copy()
rtable_not_missing = rtable[pd.notnull(rtable[r_join_attr])].copy()
if len(args) > 3 and (not args[3]):
ltable_not_missing = ltable_not_missing[ltable_not_missing.apply(
lambda row: len(args[0].tokenize(str(row[l_join_attr]))), 1) > 0]
rtable_not_missing = rtable_not_missing[rtable_not_missing.apply(
lambda row: len(args[0].tokenize(str(row[r_join_attr]))), 1) > 0]
# generate cartesian product to be used as candset
ltable_not_missing['tmp_join_key'] = 1
rtable_not_missing['tmp_join_key'] = 1
cartprod = pd.merge(ltable_not_missing[[l_key_attr,
l_join_attr,
'tmp_join_key']],
rtable_not_missing[[r_key_attr,
r_join_attr,
'tmp_join_key']],
on='tmp_join_key').drop('tmp_join_key', 1)
ltable_not_missing.drop('tmp_join_key', 1)
rtable_not_missing.drop('tmp_join_key', 1)
sim_func = get_sim_function(sim_measure_type)
# apply sim function to the entire cartesian product to obtain
# the expected set of pairs satisfying the threshold.
cartprod['sim_score'] = cartprod.apply(lambda row: round(sim_func(
args[0].tokenize(str(row[l_join_attr])),
args[0].tokenize(str(row[r_join_attr]))), 4),
axis=1)
comp_fn = COMP_OP_MAP[DEFAULT_COMP_OP]
# Check for comp_op in args.
if len(args) > 2:
comp_fn = COMP_OP_MAP[args[2]]
expected_pairs = set()
for idx, row in cartprod.iterrows():
if comp_fn(float(row['sim_score']), args[1]):
expected_pairs.add(','.join((str(row[l_key_attr]),
str(row[r_key_attr]))))
expected_pairs = expected_pairs.union(missing_pairs)
orig_return_set_flag = args[0].get_return_set()
# use join function to obtain actual output pairs.
actual_candset = join_fn(ltable, rtable,
l_key_attr, r_key_attr,
l_join_attr, r_join_attr,
*args)
assert_equal(args[0].get_return_set(), orig_return_set_flag)
expected_output_attrs = ['_id']
l_out_prefix = DEFAULT_L_OUT_PREFIX
r_out_prefix = DEFAULT_R_OUT_PREFIX
# Check for l_out_prefix in args.
if len(args) > 7:
l_out_prefix = args[7]
expected_output_attrs.append(l_out_prefix + l_key_attr)
# Check for r_out_prefix in args.
if len(args) > 8:
r_out_prefix = args[8]
expected_output_attrs.append(r_out_prefix + r_key_attr)
# Check for l_out_attrs in args.
if len(args) > 5:
if args[5]:
l_out_attrs = remove_redundant_attrs(args[5], l_key_attr)
for attr in l_out_attrs:
expected_output_attrs.append(l_out_prefix + attr)
# Check for r_out_attrs in args.
if len(args) > 6:
if args[6]:
r_out_attrs = remove_redundant_attrs(args[6], r_key_attr)
for attr in r_out_attrs:
expected_output_attrs.append(r_out_prefix + attr)
# Check for out_sim_score in args.
if len(args) > 9:
if args[9]:
expected_output_attrs.append('_sim_score')
else:
expected_output_attrs.append('_sim_score')
# verify whether the output table has the necessary attributes.
assert_list_equal(list(actual_candset.columns.values),
expected_output_attrs)
actual_pairs = set()
for idx, row in actual_candset.iterrows():
actual_pairs.add(','.join((str(row[l_out_prefix + l_key_attr]),
str(row[r_out_prefix + r_key_attr]))))
# verify whether the actual pairs and the expected pairs match.
assert_equal(len(expected_pairs), len(actual_pairs))
common_pairs = actual_pairs.intersection(expected_pairs)
assert_equal(len(common_pairs), len(expected_pairs))
def test_set_sim_join():
# data to be tested.
test_scenario_1 = [(os.sep.join(['data', 'table_A.csv']), 'A.ID', 'A.name'),
(os.sep.join(['data', 'table_B.csv']), 'B.ID', 'B.name')]
data = {'TEST_SCENARIO_1' : test_scenario_1}
# similarity measures to be tested.
sim_measure_types = ['COSINE', 'DICE', 'JACCARD', 'OVERLAP_COEFFICIENT']
# similarity thresholds to be tested.
thresholds = {'JACCARD' : [0.3, 0.5, 0.7, 0.85, 1],
'COSINE' : [0.3, 0.5, 0.7, 0.85, 1],
'DICE' : [0.3, 0.5, 0.7, 0.85, 1],
'OVERLAP_COEFFICIENT' : [0.3, 0.5, 0.7, 0.85, 1]}
# tokenizers to be tested.
tokenizers = {'SPACE_DELIMITER': DelimiterTokenizer(delim_set=[' '],
return_set=True),
'2_GRAM': QgramTokenizer(qval=2, return_set=True),
'3_GRAM': QgramTokenizer(qval=3, return_set=True)}
# Test each combination of similarity measure, threshold and tokenizer for different test scenarios.
for label, scenario in iteritems(data):
for sim_measure_type in sim_measure_types:
for threshold in thresholds.get(sim_measure_type):
for tok_type, tok in iteritems(tokenizers):
test_function = partial(test_valid_join, scenario,
sim_measure_type, (tok, threshold))
test_function.description = 'Test ' + sim_measure_type + \
' with ' + str(threshold) + ' threshold and ' + \
tok_type + ' tokenizer for ' + label + '.'
yield test_function,
# Test each similarity measure with different comparison operators.
for sim_measure_type in sim_measure_types:
for comp_op in ['>', '=']:
test_function = partial(test_valid_join, test_scenario_1,
sim_measure_type,
(tokenizers['SPACE_DELIMITER'],
0.3, comp_op, False))
test_function.description = 'Test ' + sim_measure_type + \
' with comp_op ' + comp_op + '.'
yield test_function,
# Test each similarity measure with allow_missing set to True.
for sim_measure_type in sim_measure_types:
test_function = partial(test_valid_join, test_scenario_1,
sim_measure_type,
(tokenizers['SPACE_DELIMITER'],
0.7, '>=', False, True))
test_function.description = 'Test ' + sim_measure_type + \
' with allow_missing set to True.'
yield test_function,
# Test each similarity measure with output attributes added.
for sim_measure_type in sim_measure_types:
test_function = partial(test_valid_join, test_scenario_1,
sim_measure_type,
(tokenizers['SPACE_DELIMITER'],
0.3, '>=', False, False,
['A.ID', 'A.birth_year', 'A.zipcode'],
['B.ID', 'B.name', 'B.zipcode']))
test_function.description = 'Test ' + sim_measure_type + \
' with output attributes.'
yield test_function,
# Test each similarity measure with a different output prefix.
for sim_measure_type in sim_measure_types:
test_function = partial(test_valid_join, test_scenario_1,
sim_measure_type,
(tokenizers['SPACE_DELIMITER'],
0.7, '>=', False, False,
['A.birth_year', 'A.zipcode'],
['B.name', 'B.zipcode'],
'ltable.', 'rtable.'))
test_function.description = 'Test ' + sim_measure_type + \
' with output attributes and prefix.'
yield test_function,
# Test each similarity measure with output_sim_score disabled.
for sim_measure_type in sim_measure_types:
test_function = partial(test_valid_join, test_scenario_1,
sim_measure_type,
(tokenizers['SPACE_DELIMITER'],
0.7, '>=', False, False,
['A.birth_year', 'A.zipcode'],
['B.name', 'B.zipcode'],
'ltable.', 'rtable.',
False))
test_function.description = 'Test ' + sim_measure_type + \
' with sim_score disabled.'
yield test_function,
# Test each similarity measure with n_jobs above 1.
for sim_measure_type in sim_measure_types:
test_function = partial(test_valid_join, test_scenario_1,
sim_measure_type,
(tokenizers['SPACE_DELIMITER'],
0.3, '>=', False, False,
['A.birth_year', 'A.zipcode'],
['B.name', 'B.zipcode'],
'ltable.', 'rtable.',
False, 2))
test_function.description = 'Test ' + sim_measure_type + \
' with n_jobs above 1.'
yield test_function,
# scenario where join attributes are of type int
test_scenario_2 = [(os.sep.join(['data', 'table_A.csv']), 'A.ID', 'A.zipcode'),
(os.sep.join(['data', 'table_B.csv']), 'B.ID', 'B.zipcode')]
# Test each similarity measure with join attribute of type int.
for sim_measure_type in sim_measure_types:
test_function = partial(test_valid_join, test_scenario_2,
sim_measure_type,
(tokenizers['2_GRAM'],
0.3), True)
test_function.description = 'Test ' + sim_measure_type + \
' with join attribute of type int.'
yield test_function,
# scenario where join attributes are of type float
test_scenario_3 = [(os.sep.join(['data', 'table_A.csv']), 'A.ID', 'A.hourly_wage'),
(os.sep.join(['data', 'table_B.csv']), 'B.ID', 'B.hourly_wage')]
# Test each similarity measure with join attribute of type float.
for sim_measure_type in sim_measure_types:
test_function = partial(test_valid_join, test_scenario_3,
sim_measure_type,
(tokenizers['2_GRAM'],
0.3), True)
test_function.description = 'Test ' + sim_measure_type + \
' with join attribute of type float.'
yield test_function,
# Test each similarity measure with a tokenizer with return_set flag set to False.
for sim_measure_type in sim_measure_types:
tok = QgramTokenizer(2)
test_function = partial(test_valid_join, test_scenario_1,
sim_measure_type, (tok, 0.3))
test_function.description = 'Test ' + sim_measure_type + \
' with a tokenizer with return_set flag set to False .'
yield test_function,
# Test each similarity measure with allow_empty set to True.
for sim_measure_type in sim_measure_types:
test_function = partial(test_valid_join, test_scenario_1,
sim_measure_type,
(tokenizers['SPACE_DELIMITER'],
0.7, '>=', True))
test_function.description = 'Test ' + sim_measure_type + \
' with allow_empty set to True.'
yield test_function,
# Test each similarity measure with allow_empty set to True and with output attributes.
for sim_measure_type in sim_measure_types:
test_function = partial(test_valid_join, test_scenario_1,
sim_measure_type,
(tokenizers['SPACE_DELIMITER'],
0.7, '>=', True, False,
['A.name'], ['B.name']))
test_function.description = 'Test ' + sim_measure_type + \
' with allow_empty set to True and with output attributes.'
yield test_function,
class JaccardJoinInvalidTestCases(unittest.TestCase):
def setUp(self):
self.A = pd.DataFrame([{'A.id':1, 'A.attr':'hello', 'A.int_attr':5}])
self.B = pd.DataFrame([{'B.id':1, 'B.attr':'world', 'B.int_attr':6}])
self.tokenizer = DelimiterTokenizer(delim_set=[' '], return_set=True)
self.threshold = 0.8
@raises(TypeError)
def test_jaccard_join_invalid_ltable(self):
jaccard_join([], self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(TypeError)
def test_jaccard_join_invalid_rtable(self):
jaccard_join(self.A, [], 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_jaccard_join_invalid_l_key_attr(self):
jaccard_join(self.A, self.B, 'A.invalid_id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_jaccard_join_invalid_r_key_attr(self):
jaccard_join(self.A, self.B, 'A.id', 'B.invalid_id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_jaccard_join_invalid_l_join_attr(self):
jaccard_join(self.A, self.B, 'A.id', 'B.id', 'A.invalid_attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_jaccard_join_invalid_r_join_attr(self):
jaccard_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.invalid_attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_jaccard_join_numeric_l_join_attr(self):
jaccard_join(self.A, self.B, 'A.id', 'B.id', 'A.int_attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_jaccard_join_numeric_r_join_attr(self):
jaccard_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.int_attr',
self.tokenizer, self.threshold)
@raises(TypeError)
def test_jaccard_join_invalid_tokenizer(self):
jaccard_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
[], self.threshold)
@raises(AssertionError)
def test_jaccard_join_invalid_threshold_above(self):
jaccard_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, 1.5)
@raises(AssertionError)
def test_jaccard_join_invalid_threshold_below(self):
jaccard_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, -0.1)
@raises(AssertionError)
def test_jaccard_join_invalid_threshold_zero(self):
jaccard_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, 0)
@raises(AssertionError)
def test_jaccard_join_invalid_comp_op_lt(self):
jaccard_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold, '<')
@raises(AssertionError)
def test_jaccard_join_invalid_comp_op_le(self):
jaccard_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold, '<=')
@raises(AssertionError)
def test_jaccard_join_invalid_l_out_attr(self):
jaccard_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold, '>=', True, False,
['A.invalid_attr'], ['B.attr'])
@raises(AssertionError)
def test_jaccard_join_invalid_r_out_attr(self):
jaccard_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold, '>=', True, False,
['A.attr'], ['B.invalid_attr'])
class CosineJoinInvalidTestCases(unittest.TestCase):
def setUp(self):
self.A = pd.DataFrame([{'A.id':1, 'A.attr':'hello', 'A.int_attr':5}])
self.B = pd.DataFrame([{'B.id':1, 'B.attr':'world', 'B.int_attr':6}])
self.tokenizer = DelimiterTokenizer(delim_set=[' '], return_set=True)
self.threshold = 0.8
@raises(TypeError)
def test_cosine_join_invalid_ltable(self):
cosine_join([], self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(TypeError)
def test_cosine_join_invalid_rtable(self):
cosine_join(self.A, [], 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_cosine_join_invalid_l_key_attr(self):
cosine_join(self.A, self.B, 'A.invalid_id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_cosine_join_invalid_r_key_attr(self):
cosine_join(self.A, self.B, 'A.id', 'B.invalid_id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_cosine_join_invalid_l_join_attr(self):
cosine_join(self.A, self.B, 'A.id', 'B.id', 'A.invalid_attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_cosine_join_invalid_r_join_attr(self):
cosine_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.invalid_attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_cosine_join_numeric_l_join_attr(self):
cosine_join(self.A, self.B, 'A.id', 'B.id', 'A.int_attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_cosine_join_numeric_r_join_attr(self):
cosine_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.int_attr',
self.tokenizer, self.threshold)
@raises(TypeError)
def test_cosine_join_invalid_tokenizer(self):
cosine_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
[], self.threshold)
@raises(AssertionError)
def test_cosine_join_invalid_threshold_above(self):
cosine_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, 1.5)
@raises(AssertionError)
def test_cosine_join_invalid_threshold_below(self):
cosine_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, -0.1)
@raises(AssertionError)
def test_cosine_join_invalid_threshold_zero(self):
cosine_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, 0)
@raises(AssertionError)
def test_cosine_join_invalid_comp_op_lt(self):
cosine_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold, '<')
@raises(AssertionError)
def test_cosine_join_invalid_comp_op_le(self):
cosine_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold, '<=')
@raises(AssertionError)
def test_cosine_join_invalid_l_out_attr(self):
cosine_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold, '>=', True, False,
['A.invalid_attr'], ['B.attr'])
@raises(AssertionError)
def test_cosine_join_invalid_r_out_attr(self):
cosine_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold, '>=', True, False,
['A.attr'], ['B.invalid_attr'])
class DiceJoinInvalidTestCases(unittest.TestCase):
def setUp(self):
self.A = pd.DataFrame([{'A.id':1, 'A.attr':'hello', 'A.int_attr':5}])
self.B = pd.DataFrame([{'B.id':1, 'B.attr':'world', 'B.int_attr':6}])
self.tokenizer = DelimiterTokenizer(delim_set=[' '], return_set=True)
self.threshold = 0.8
@raises(TypeError)
def test_dice_join_invalid_ltable(self):
dice_join([], self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(TypeError)
def test_dice_join_invalid_rtable(self):
dice_join(self.A, [], 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_dice_join_invalid_l_key_attr(self):
dice_join(self.A, self.B, 'A.invalid_id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_dice_join_invalid_r_key_attr(self):
dice_join(self.A, self.B, 'A.id', 'B.invalid_id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_dice_join_invalid_l_join_attr(self):
dice_join(self.A, self.B, 'A.id', 'B.id', 'A.invalid_attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_dice_join_invalid_r_join_attr(self):
dice_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.invalid_attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_dice_join_numeric_l_join_attr(self):
dice_join(self.A, self.B, 'A.id', 'B.id', 'A.int_attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_dice_join_numeric_r_join_attr(self):
dice_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.int_attr',
self.tokenizer, self.threshold)
@raises(TypeError)
def test_dice_join_invalid_tokenizer(self):
dice_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
[], self.threshold)
@raises(AssertionError)
def test_dice_join_invalid_threshold_above(self):
dice_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, 1.5)
@raises(AssertionError)
def test_dice_join_invalid_threshold_below(self):
dice_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, -0.1)
@raises(AssertionError)
def test_dice_join_invalid_threshold_zero(self):
dice_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, 0)
@raises(AssertionError)
def test_dice_join_invalid_comp_op_lt(self):
dice_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold, '<')
@raises(AssertionError)
def test_dice_join_invalid_comp_op_le(self):
dice_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold, '<=')
@raises(AssertionError)
def test_dice_join_invalid_l_out_attr(self):
dice_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold, '>=', True, False,
['A.invalid_attr'], ['B.attr'])
@raises(AssertionError)
def test_dice_join_invalid_r_out_attr(self):
dice_join(self.A, self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold, '>=', True, False,
['A.attr'], ['B.invalid_attr'])
class OverlapCoefficientJoinInvalidTestCases(unittest.TestCase):
def setUp(self):
self.A = pd.DataFrame([{'A.id':1, 'A.attr':'hello', 'A.int_attr':5}])
self.B = pd.DataFrame([{'B.id':1, 'B.attr':'world', 'B.int_attr':6}])
self.tokenizer = DelimiterTokenizer(delim_set=[' '], return_set=True)
self.threshold = 0.8
@raises(TypeError)
def test_overlap_coefficient_join_invalid_ltable(self):
overlap_coefficient_join([], self.B, 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(TypeError)
def test_overlap_coefficient_join_invalid_rtable(self):
overlap_coefficient_join(self.A, [], 'A.id', 'B.id', 'A.attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_overlap_coefficient_join_invalid_l_key_attr(self):
overlap_coefficient_join(self.A, self.B, 'A.invalid_id', 'B.id',
'A.attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_overlap_coefficient_join_invalid_r_key_attr(self):
overlap_coefficient_join(self.A, self.B, 'A.id', 'B.invalid_id',
'A.attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_overlap_coefficient_join_invalid_l_join_attr(self):
overlap_coefficient_join(self.A, self.B, 'A.id', 'B.id',
'A.invalid_attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_overlap_coefficient_join_invalid_r_join_attr(self):
overlap_coefficient_join(self.A, self.B, 'A.id', 'B.id',
'A.attr', 'B.invalid_attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_overlap_coefficient_join_numeric_l_join_attr(self):
overlap_coefficient_join(self.A, self.B, 'A.id', 'B.id',
'A.int_attr', 'B.attr',
self.tokenizer, self.threshold)
@raises(AssertionError)
def test_overlap_coefficient_join_numeric_r_join_attr(self):
overlap_coefficient_join(self.A, self.B, 'A.id', 'B.id',
'A.attr', 'B.int_attr',
self.tokenizer, self.threshold)
@raises(TypeError)
def test_overlap_coefficient_join_invalid_tokenizer(self):
overlap_coefficient_join(self.A, self.B, 'A.id', 'B.id',
'A.attr', 'B.attr', [], self.threshold)
@raises(AssertionError)
def test_overlap_coefficient_join_invalid_threshold_above(self):
overlap_coefficient_join(self.A, self.B, 'A.id', 'B.id',
'A.attr', 'B.attr', self.tokenizer, 1.5)
@raises(AssertionError)
def test_overlap_coefficient_join_invalid_threshold_below(self):
overlap_coefficient_join(self.A, self.B, 'A.id', 'B.id',
'A.attr', 'B.attr', self.tokenizer, -0.1)
@raises(AssertionError)
def test_overlap_coefficient_join_invalid_threshold_zero(self):
overlap_coefficient_join(self.A, self.B, 'A.id', 'B.id',
'A.attr', 'B.attr', self.tokenizer, 0)
@raises(AssertionError)
def test_overlap_coefficient_join_invalid_comp_op_lt(self):
overlap_coefficient_join(self.A, self.B, 'A.id', 'B.id',
'A.attr', 'B.attr',
self.tokenizer, self.threshold, '<')
@raises(AssertionError)
def test_overlap_coefficient_join_invalid_comp_op_le(self):
overlap_coefficient_join(self.A, self.B, 'A.id', 'B.id',
'A.attr', 'B.attr',
self.tokenizer, self.threshold, '<=')
@raises(AssertionError)
def test_overlap_coefficient_join_invalid_l_out_attr(self):
overlap_coefficient_join(self.A, self.B, 'A.id', 'B.id',
'A.attr', 'B.attr',
self.tokenizer, self.threshold, '>=',
True, False, ['A.invalid_attr'], ['B.attr'])
@raises(AssertionError)
def test_overlap_coefficient_join_invalid_r_out_attr(self):
overlap_coefficient_join(self.A, self.B, 'A.id', 'B.id',
'A.attr', 'B.attr',
self.tokenizer, self.threshold, '>=',
True, False, ['A.attr'], ['B.invalid_attr'])
| {
"repo_name": "anhaidgroup/py_stringsimjoin",
"path": "py_stringsimjoin/tests/test_join.py",
"copies": "1",
"size": "32925",
"license": "bsd-3-clause",
"hash": 9047506546981536000,
"line_mean": 46.3060344828,
"line_max": 104,
"alpha_frac": 0.5162034928,
"autogenerated": false,
"ratio": 3.7081878589931296,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9701753340032511,
"avg_score": 0.004527602352123807,
"num_lines": 696
} |
from functools import partial
import os
import unittest
import nose
import numpy as np
try:
import matplotlib.pyplot as plt
except ImportError:
pass
from hyperopt import pyll
from hyperopt.pyll import scope
from hyperopt import Trials
from hyperopt.base import miscs_to_idxs_vals, STATUS_OK
from hyperopt import hp
from hyperopt.tpe import adaptive_parzen_normal_orig
from hyperopt.tpe import GMM1
from hyperopt.tpe import GMM1_lpdf
from hyperopt.tpe import LGMM1
from hyperopt.tpe import LGMM1_lpdf
import hyperopt.rand as rand
import hyperopt.tpe as tpe
from hyperopt import fmin
from test_domains import (
domain_constructor,
CasePerDomain)
DO_SHOW = int(os.getenv('HYPEROPT_SHOW', '0'))
def passthrough(x):
return x
def test_adaptive_parzen_normal_orig():
rng = np.random.RandomState(123)
prior_mu = 7
prior_sigma = 2
mus = rng.randn(10) + 5
weights2, mus2, sigmas2 = adaptive_parzen_normal_orig(
mus, 3.3, prior_mu, prior_sigma)
print weights2
print mus2
print sigmas2
assert len(weights2) == len(mus2) == len(sigmas2) == 11
assert np.all(weights2[0] > weights2[1:])
assert mus2[0] == 7
assert np.all(mus2[1:] == mus)
assert sigmas2[0] == 2
class TestGMM1(unittest.TestCase):
def setUp(self):
self.rng = np.random.RandomState(234)
def test_mu_is_used_correctly(self):
assert np.allclose(10,
GMM1([1], [10.0], [0.0000001], rng=self.rng))
def test_sigma_is_used_correctly(self):
samples = GMM1([1], [0.0], [10.0], size=[1000], rng=self.rng)
assert 9 < np.std(samples) < 11
def test_mus_make_variance(self):
samples = GMM1([.5, .5], [0.0, 1.0], [0.000001, 0.000001],
rng=self.rng, size=[1000])
print samples.shape
#import matplotlib.pyplot as plt
#plt.hist(samples)
#plt.show()
assert .45 < np.mean(samples) < .55, np.mean(samples)
assert .2 < np.var(samples) < .3, np.var(samples)
def test_weights(self):
samples = GMM1([.9999, .0001], [0.0, 1.0], [0.000001, 0.000001],
rng=self.rng,
size=[1000])
assert samples.shape == (1000,)
#import matplotlib.pyplot as plt
#plt.hist(samples)
#plt.show()
assert -.001 < np.mean(samples) < .001, np.mean(samples)
assert np.var(samples) < .0001, np.var(samples)
def test_mat_output(self):
samples = GMM1([.9999, .0001], [0.0, 1.0], [0.000001, 0.000001],
rng=self.rng,
size=[40, 20])
assert samples.shape == (40, 20)
assert -.001 < np.mean(samples) < .001, np.mean(samples)
assert np.var(samples) < .0001, np.var(samples)
def test_lpdf_scalar_one_component(self):
llval = GMM1_lpdf(1.0, # x
[1.], # weights
[1.0], # mu
[2.0], # sigma
)
assert llval.shape == ()
assert np.allclose(llval,
np.log(1.0 / np.sqrt(2 * np.pi * 2.0 ** 2)))
def test_lpdf_scalar_N_components(self):
llval = GMM1_lpdf(1.0, # x
[0.25, 0.25, .5], # weights
[0.0, 1.0, 2.0], # mu
[1.0, 2.0, 5.0], # sigma
)
a = (.25 / np.sqrt(2 * np.pi * 1.0 ** 2)
* np.exp(-.5 * (1.0) ** 2))
a += (.25 / np.sqrt(2 * np.pi * 2.0 ** 2))
a += (.5 / np.sqrt(2 * np.pi * 5.0 ** 2)
* np.exp(-.5 * (1.0 / 5.0) ** 2))
def test_lpdf_vector_N_components(self):
llval = GMM1_lpdf([1.0, 0.0], # x
[0.25, 0.25, .5], # weights
[0.0, 1.0, 2.0], # mu
[1.0, 2.0, 5.0], # sigma
)
# case x = 1.0
a = (.25 / np.sqrt(2 * np.pi * 1.0 ** 2)
* np.exp(-.5 * (1.0) ** 2))
a += (.25 / np.sqrt(2 * np.pi * 2.0 ** 2))
a += (.5 / np.sqrt(2 * np.pi * 5.0 ** 2)
* np.exp(-.5 * (1.0 / 5.0) ** 2))
assert llval.shape == (2,)
assert np.allclose(llval[0], np.log(a))
# case x = 0.0
a = (.25 / np.sqrt(2 * np.pi * 1.0 ** 2))
a += (.25 / np.sqrt(2 * np.pi * 2.0 ** 2)
* np.exp(-.5 * (1.0 / 2.0) ** 2))
a += (.5 / np.sqrt(2 * np.pi * 5.0 ** 2)
* np.exp(-.5 * (2.0 / 5.0) ** 2))
assert np.allclose(llval[1], np.log(a))
def test_lpdf_matrix_N_components(self):
llval = GMM1_lpdf(
[
[1.0, 0.0, 0.0],
[0, 0, 1],
[0, 0, 1000],
],
[0.25, 0.25, .5], # weights
[0.0, 1.0, 2.0], # mu
[1.0, 2.0, 5.0], # sigma
)
print llval
assert llval.shape == (3, 3)
a = (.25 / np.sqrt(2 * np.pi * 1.0 ** 2)
* np.exp(-.5 * (1.0) ** 2))
a += (.25 / np.sqrt(2 * np.pi * 2.0 ** 2))
a += (.5 / np.sqrt(2 * np.pi * 5.0 ** 2)
* np.exp(-.5 * (1.0 / 5.0) ** 2))
assert np.allclose(llval[0, 0], np.log(a))
assert np.allclose(llval[1, 2], np.log(a))
# case x = 0.0
a = (.25 / np.sqrt(2 * np.pi * 1.0 ** 2))
a += (.25 / np.sqrt(2 * np.pi * 2.0 ** 2)
* np.exp(-.5 * (1.0 / 2.0) ** 2))
a += (.5 / np.sqrt(2 * np.pi * 5.0 ** 2)
* np.exp(-.5 * (2.0 / 5.0) ** 2))
assert np.allclose(llval[0, 1], np.log(a))
assert np.allclose(llval[0, 2], np.log(a))
assert np.allclose(llval[1, 0], np.log(a))
assert np.allclose(llval[1, 1], np.log(a))
assert np.allclose(llval[2, 0], np.log(a))
assert np.allclose(llval[2, 1], np.log(a))
assert np.isfinite(llval[2, 2])
class TestGMM1Math(unittest.TestCase):
def setUp(self):
self.rng = np.random.RandomState(234)
self.weights = [.1, .3, .4, .2]
self.mus = [1.0, 2.0, 3.0, 4.0]
self.sigmas = [.1, .4, .8, 2.0]
self.q = None
self.low = None
self.high = None
self.n_samples = 10001
self.samples_per_bin = 500
self.show = False
# -- triggers error if test case forgets to call work()
self.worked = False
def tearDown(self):
assert self.worked
def work(self):
self.worked = True
kwargs = dict(
weights=self.weights,
mus=self.mus,
sigmas=self.sigmas,
low=self.low,
high=self.high,
q=self.q,
)
samples = GMM1(rng=self.rng,
size=(self.n_samples,),
**kwargs)
samples = np.sort(samples)
edges = samples[::self.samples_per_bin]
#print samples
pdf = np.exp(GMM1_lpdf(edges[:-1], **kwargs))
dx = edges[1:] - edges[:-1]
y = 1 / dx / len(dx)
if self.show:
plt.scatter(edges[:-1], y)
plt.plot(edges[:-1], pdf)
plt.show()
err = (pdf - y) ** 2
print np.max(err)
print np.mean(err)
print np.median(err)
if not self.show:
assert np.max(err) < .1
assert np.mean(err) < .01
assert np.median(err) < .01
def test_basic(self):
self.work()
def test_bounded(self):
self.low = 2.5
self.high = 3.5
self.work()
class TestQGMM1Math(unittest.TestCase):
def setUp(self):
self.rng = np.random.RandomState(234)
self.weights = [.1, .3, .4, .2]
self.mus = [1.0, 2.0, 3.0, 4.0]
self.sigmas = [.1, .4, .8, 2.0]
self.low = None
self.high = None
self.n_samples = 1001
self.show = DO_SHOW # or put a string
# -- triggers error if test case forgets to call work()
self.worked = False
def tearDown(self):
assert self.worked
def work(self, **kwargs):
self.__dict__.update(kwargs)
del kwargs
self.worked = True
gkwargs = dict(
weights=self.weights,
mus=self.mus,
sigmas=self.sigmas,
low=self.low,
high=self.high,
q=self.q,
)
samples = GMM1(rng=self.rng,
size=(self.n_samples,),
**gkwargs) / self.q
print 'drew', len(samples), 'samples'
assert np.all(samples == samples.astype('int'))
min_max = int(samples.min()), int(samples.max())
counts = np.bincount(samples.astype('int') - min_max[0])
print counts
xcoords = np.arange(min_max[0], min_max[1] + 1) * self.q
prob = np.exp(GMM1_lpdf(xcoords, **gkwargs))
assert counts.sum() == self.n_samples
y = counts / float(self.n_samples)
if self.show:
plt.scatter(xcoords, y, c='r', label='empirical')
plt.scatter(xcoords, prob, c='b', label='predicted')
plt.legend()
plt.title(str(self.show))
plt.show()
err = (prob - y) ** 2
print np.max(err)
print np.mean(err)
print np.median(err)
if self.show:
raise nose.SkipTest()
else:
assert np.max(err) < .1
assert np.mean(err) < .01
assert np.median(err) < .01
def test_basic_1(self):
self.work(q=1)
def test_basic_2(self):
self.work(q=2)
def test_basic_pt5(self):
self.work(q=0.5)
def test_bounded_1(self):
self.work(q=1, low=2, high=4)
def test_bounded_2(self):
self.work(q=2, low=2, high=4)
def test_bounded_1b(self):
self.work(q=1, low=1, high=4.1)
def test_bounded_2b(self):
self.work(q=2, low=1, high=4.1)
def test_bounded_3(self):
self.work(
weights=[0.14285714, 0.28571429, 0.28571429, 0.28571429],
mus=[5.505, 7., 2., 10.],
sigmas=[8.99, 5., 8., 8.],
q=1,
low=1.01,
high=10,
n_samples=10000,
#show='bounded_3',
)
def test_bounded_3b(self):
self.work(
weights=[0.33333333, 0.66666667],
mus=[5.505, 5.],
sigmas=[8.99, 5.19],
q=1,
low=1.01,
high=10,
n_samples=10000,
#show='bounded_3b',
)
class TestLGMM1Math(unittest.TestCase):
def setUp(self):
self.rng = np.random.RandomState(234)
self.weights = [.1, .3, .4, .2]
self.mus = [-2.0, 1.0, 0.0, 3.0]
self.sigmas = [.1, .4, .8, 2.0]
self.low = None
self.high = None
self.n_samples = 10001
self.samples_per_bin = 200
self.show = False
# -- triggers error if test case forgets to call work()
self.worked = False
def tearDown(self):
assert self.worked
@property
def LGMM1_kwargs(self):
return dict(
weights=self.weights,
mus=self.mus,
sigmas=self.sigmas,
low=self.low,
high=self.high,
)
def LGMM1_lpdf(self, samples):
return self.LGMM1(samples, **self.LGMM1_kwargs)
def work(self, **kwargs):
self.__dict__.update(kwargs)
self.worked = True
samples = LGMM1(rng=self.rng,
size=(self.n_samples,),
**self.LGMM1_kwargs)
samples = np.sort(samples)
edges = samples[::self.samples_per_bin]
centers = .5 * edges[:-1] + .5 * edges[1:]
print edges
pdf = np.exp(LGMM1_lpdf(centers, **self.LGMM1_kwargs))
dx = edges[1:] - edges[:-1]
y = 1 / dx / len(dx)
if self.show:
plt.scatter(centers, y)
plt.plot(centers, pdf)
plt.show()
err = (pdf - y) ** 2
print np.max(err)
print np.mean(err)
print np.median(err)
if not self.show:
assert np.max(err) < .1
assert np.mean(err) < .01
assert np.median(err) < .01
def test_basic(self):
self.work()
def test_bounded(self):
self.work(low=2, high=4)
class TestQLGMM1Math(unittest.TestCase):
def setUp(self):
self.rng = np.random.RandomState(234)
self.weights = [.1, .3, .4, .2]
self.mus = [-2, 0.0, -3.0, 1.0]
self.sigmas = [2.1, .4, .8, 2.1]
self.low = None
self.high = None
self.n_samples = 1001
self.show = DO_SHOW
# -- triggers error if test case forgets to call work()
self.worked = False
def tearDown(self):
assert self.worked
@property
def kwargs(self):
return dict(
weights=self.weights,
mus=self.mus,
sigmas=self.sigmas,
low=self.low,
high=self.high,
q=self.q)
def QLGMM1_lpdf(self, samples):
return self.LGMM1(samples, **self.kwargs)
def work(self, **kwargs):
self.__dict__.update(kwargs)
self.worked = True
samples = LGMM1(rng=self.rng,
size=(self.n_samples,),
**self.kwargs) / self.q
# -- we've divided the LGMM1 by self.q to get ints here
assert np.all(samples == samples.astype('int'))
min_max = int(samples.min()), int(samples.max())
print 'SAMPLES RANGE', min_max
counts = np.bincount(samples.astype('int') - min_max[0])
#print samples
#print counts
xcoords = np.arange(min_max[0], min_max[1] + 0.5) * self.q
prob = np.exp(LGMM1_lpdf(xcoords, **self.kwargs))
print xcoords
print prob
assert counts.sum() == self.n_samples
y = counts / float(self.n_samples)
if self.show:
plt.scatter(xcoords, y, c='r', label='empirical')
plt.scatter(xcoords, prob, c='b', label='predicted')
plt.legend()
plt.show()
# -- calculate errors on the low end, don't take a mean
# over all the range spanned by a few outliers.
err = ((prob - y) ** 2)[:20]
print np.max(err)
print np.mean(err)
print np.median(err)
if self.show:
raise nose.SkipTest()
else:
assert np.max(err) < .1
assert np.mean(err) < .01
assert np.median(err) < .01
def test_basic_1(self):
self.work(q=1)
def test_basic_2(self):
self.work(q=2)
def test_basic_pt5(self):
self.work(q=0.5)
def test_basic_pt125(self):
self.work(q=0.125)
def test_bounded_1(self):
self.work(q=1, low=2, high=4)
def test_bounded_2(self):
self.work(q=2, low=2, high=4)
def test_bounded_1b(self):
self.work(q=1, low=1, high=4.1)
def test_bounded_2b(self):
self.work(q=2, low=1, high=4.1)
class TestSuggest(unittest.TestCase, CasePerDomain):
def work(self):
# -- smoke test that things simply run,
# for each type of several search spaces.
trials = Trials()
fmin(passthrough,
space=self.bandit.expr,
algo=partial(tpe.suggest, n_EI_candidates=3),
trials=trials,
max_evals=10)
class TestOpt(unittest.TestCase, CasePerDomain):
thresholds = dict(
quadratic1=1e-5,
q1_lognormal=0.01,
distractor=-1.96,
gauss_wave=-2.0,
gauss_wave2=-2.0,
n_arms=-2.5,
many_dists=.0005,
branin=0.7,
)
LEN = dict(
# -- running a long way out tests overflow/underflow
# to some extent
quadratic1=1000,
many_dists=200,
distractor=100,
#XXX
q1_lognormal=250,
gauss_wave2=75, # -- boosted from 50 on Nov/2013 after new
# sampling order made thresh test fail.
branin=200,
)
gammas = dict(
distractor=.05,
)
prior_weights = dict(
distractor=.01,
)
n_EIs = dict(
#XXX
# -- this can be low in a few dimensions
quadratic1=5,
# -- lower number encourages exploration
# XXX: this is a damned finicky way to get TPE
# to solve the Distractor problem
distractor=15,
)
def setUp(self):
self.olderr = np.seterr('raise')
np.seterr(under='ignore')
def tearDown(self, *args):
np.seterr(**self.olderr)
def work(self):
bandit = self.bandit
assert bandit.name is not None
algo = partial(tpe.suggest,
gamma=self.gammas.get(bandit.name,
tpe._default_gamma),
prior_weight=self.prior_weights.get(bandit.name,
tpe._default_prior_weight),
n_EI_candidates=self.n_EIs.get(bandit.name,
tpe._default_n_EI_candidates),
)
LEN = self.LEN.get(bandit.name, 50)
trials = Trials()
fmin(passthrough,
space=bandit.expr,
algo=algo,
trials=trials,
max_evals=LEN,
rstate=np.random.RandomState(123),
catch_eval_exceptions=False)
assert len(trials) == LEN
if 1:
rtrials = Trials()
fmin(passthrough,
space=bandit.expr,
algo=rand.suggest,
trials=rtrials,
max_evals=LEN)
print 'RANDOM MINS', list(sorted(rtrials.losses()))[:6]
#logx = np.log([s['x'] for s in rtrials.specs])
#print 'RND MEAN', np.mean(logx)
#print 'RND STD ', np.std(logx)
if 0:
plt.subplot(2, 2, 1)
plt.scatter(range(LEN), trials.losses())
plt.title('TPE losses')
plt.subplot(2, 2, 2)
plt.scatter(range(LEN), ([s['x'] for s in trials.specs]))
plt.title('TPE x')
plt.subplot(2, 2, 3)
plt.title('RND losses')
plt.scatter(range(LEN), rtrials.losses())
plt.subplot(2, 2, 4)
plt.title('RND x')
plt.scatter(range(LEN), ([s['x'] for s in rtrials.specs]))
plt.show()
if 0:
plt.hist(
[t['x'] for t in self.experiment.trials],
bins=20)
#print trials.losses()
print 'TPE MINS', list(sorted(trials.losses()))[:6]
#logx = np.log([s['x'] for s in trials.specs])
#print 'TPE MEAN', np.mean(logx)
#print 'TPE STD ', np.std(logx)
thresh = self.thresholds[bandit.name]
print 'Thresh', thresh
assert min(trials.losses()) < thresh
@domain_constructor(loss_target=0)
def opt_q_uniform(target):
rng = np.random.RandomState(123)
x = hp.quniform('x', 1.01, 10, 1)
return {'loss': (x - target) ** 2 + scope.normal(0, 1, rng=rng),
'status': STATUS_OK}
class TestOptQUniform():
show_steps = False
show_vars = DO_SHOW
LEN = 25
def work(self, **kwargs):
self.__dict__.update(kwargs)
bandit = opt_q_uniform(self.target)
prior_weight = 2.5
gamma = 0.20
algo = partial(tpe.suggest,
prior_weight=prior_weight,
n_startup_jobs=2,
n_EI_candidates=128,
gamma=gamma)
#print algo.opt_idxs['x']
#print algo.opt_vals['x']
trials = Trials()
fmin(passthrough,
space=bandit.expr,
algo=algo,
trials=trials,
max_evals=self.LEN)
if self.show_vars:
import hyperopt.plotting
hyperopt.plotting.main_plot_vars(trials, bandit, do_show=1)
idxs, vals = miscs_to_idxs_vals(trials.miscs)
idxs = idxs['x']
vals = vals['x']
losses = trials.losses()
from hyperopt.tpe import ap_filter_trials
from hyperopt.tpe import adaptive_parzen_samplers
qu = scope.quniform(1.01, 10, 1)
fn = adaptive_parzen_samplers['quniform']
fn_kwargs = dict(size=(4,), rng=np.random)
s_below = pyll.Literal()
s_above = pyll.Literal()
b_args = [s_below, prior_weight] + qu.pos_args
b_post = fn(*b_args, **fn_kwargs)
a_args = [s_above, prior_weight] + qu.pos_args
a_post = fn(*a_args, **fn_kwargs)
#print b_post
#print a_post
fn_lpdf = getattr(scope, a_post.name + '_lpdf')
print fn_lpdf
# calculate the llik of b_post under both distributions
a_kwargs = dict([(n, a) for n, a in a_post.named_args
if n not in ('rng', 'size')])
b_kwargs = dict([(n, a) for n, a in b_post.named_args
if n not in ('rng', 'size')])
below_llik = fn_lpdf(*([b_post] + b_post.pos_args), **b_kwargs)
above_llik = fn_lpdf(*([b_post] + a_post.pos_args), **a_kwargs)
new_node = scope.broadcast_best(b_post, below_llik, above_llik)
print '=' * 80
do_show = self.show_steps
for ii in range(2, 9):
if ii > len(idxs):
break
print '-' * 80
print 'ROUND', ii
print '-' * 80
all_vals = [2, 3, 4, 5, 6, 7, 8, 9, 10]
below, above = ap_filter_trials(idxs[:ii],
vals[:ii], idxs[:ii], losses[:ii], gamma)
below = below.astype('int')
above = above.astype('int')
print 'BB0', below
print 'BB1', above
#print 'BELOW', zip(range(100), np.bincount(below, minlength=11))
#print 'ABOVE', zip(range(100), np.bincount(above, minlength=11))
memo = {b_post: all_vals, s_below: below, s_above: above}
bl, al, nv = pyll.rec_eval([below_llik, above_llik, new_node],
memo=memo)
#print bl - al
print 'BB2', dict(zip(all_vals, bl - al))
print 'BB3', dict(zip(all_vals, bl))
print 'BB4', dict(zip(all_vals, al))
print 'ORIG PICKED', vals[ii]
print 'PROPER OPT PICKS:', nv
#assert np.allclose(below, [3, 3, 9])
#assert len(below) + len(above) == len(vals)
if do_show:
plt.subplot(8, 1, ii)
#plt.scatter(all_vals,
# np.bincount(below, minlength=11)[2:], c='b')
#plt.scatter(all_vals,
# np.bincount(above, minlength=11)[2:], c='c')
plt.scatter(all_vals, bl, c='g')
plt.scatter(all_vals, al, c='r')
if do_show:
plt.show()
def test4(self):
self.work(target=4, LEN=100)
def test2(self):
self.work(target=2, LEN=100)
def test6(self):
self.work(target=6, LEN=100)
def test10(self):
self.work(target=10, LEN=100)
| {
"repo_name": "dallascard/hyperopt",
"path": "hyperopt/tests/test_tpe.py",
"copies": "7",
"size": "23399",
"license": "bsd-3-clause",
"hash": 512372169384028700,
"line_mean": 29.5071707953,
"line_max": 78,
"alpha_frac": 0.4914312577,
"autogenerated": false,
"ratio": 3.2399612295762945,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0045940216995377595,
"num_lines": 767
} |
from functools import partial
import os
import warnings
import numpy as np
from scipy import sparse, linalg, stats
from numpy.testing import (assert_equal, assert_array_equal,
assert_array_almost_equal)
from nose.tools import assert_true, assert_raises
from mne.parallel import _force_serial
from mne.stats.cluster_level import (permutation_cluster_test,
permutation_cluster_1samp_test,
spatio_temporal_cluster_test,
spatio_temporal_cluster_1samp_test,
ttest_1samp_no_p, summarize_clusters_stc)
from mne.utils import run_tests_if_main, slow_test, _TempDir, catch_logging
warnings.simplefilter('always') # enable b/c these tests throw warnings
n_space = 50
def _get_conditions():
noise_level = 20
n_time_1 = 20
n_time_2 = 13
normfactor = np.hanning(20).sum()
rng = np.random.RandomState(42)
condition1_1d = rng.randn(n_time_1, n_space) * noise_level
for c in condition1_1d:
c[:] = np.convolve(c, np.hanning(20), mode="same") / normfactor
condition2_1d = rng.randn(n_time_2, n_space) * noise_level
for c in condition2_1d:
c[:] = np.convolve(c, np.hanning(20), mode="same") / normfactor
pseudoekp = 10 * np.hanning(25)[None, :]
condition1_1d[:, 25:] += pseudoekp
condition2_1d[:, 25:] -= pseudoekp
condition1_2d = condition1_1d[:, :, np.newaxis]
condition2_2d = condition2_1d[:, :, np.newaxis]
return condition1_1d, condition2_1d, condition1_2d, condition2_2d
def test_cache_dir():
"""Test use of cache dir."""
tempdir = _TempDir()
orig_dir = os.getenv('MNE_CACHE_DIR', None)
orig_size = os.getenv('MNE_MEMMAP_MIN_SIZE', None)
rng = np.random.RandomState(0)
X = rng.randn(9, 2, 10)
try:
os.environ['MNE_MEMMAP_MIN_SIZE'] = '1K'
os.environ['MNE_CACHE_DIR'] = tempdir
# Fix error for #1507: in-place when memmapping
with catch_logging() as log_file:
permutation_cluster_1samp_test(
X, buffer_size=None, n_jobs=2, n_permutations=1,
seed=0, stat_fun=ttest_1samp_no_p, verbose=False)
# ensure that non-independence yields warning
stat_fun = partial(ttest_1samp_no_p, sigma=1e-3)
assert_true('independently' not in log_file.getvalue())
with warnings.catch_warnings(record=True): # independently
permutation_cluster_1samp_test(
X, buffer_size=10, n_jobs=2, n_permutations=1,
seed=0, stat_fun=stat_fun, verbose=False)
assert_true('independently' in log_file.getvalue())
finally:
if orig_dir is not None:
os.environ['MNE_CACHE_DIR'] = orig_dir
else:
del os.environ['MNE_CACHE_DIR']
if orig_size is not None:
os.environ['MNE_MEMMAP_MIN_SIZE'] = orig_size
else:
del os.environ['MNE_MEMMAP_MIN_SIZE']
def test_permutation_step_down_p():
"""Test cluster level permutations with step_down_p."""
try:
try:
from sklearn.feature_extraction.image import grid_to_graph
except ImportError:
from scikits.learn.feature_extraction.image import grid_to_graph # noqa: F401,E501
except ImportError:
return
rng = np.random.RandomState(0)
# subjects, time points, spatial points
X = rng.randn(9, 2, 10)
# add some significant points
X[:, 0:2, 0:2] += 2 # span two time points and two spatial points
X[:, 1, 5:9] += 0.5 # span four time points with 4x smaller amplitude
thresh = 2
# make sure it works when we use ALL points in step-down
t, clusters, p, H0 = \
permutation_cluster_1samp_test(X, threshold=thresh,
step_down_p=1.0)
# make sure using step-down will actually yield improvements sometimes
t, clusters, p_old, H0 = \
permutation_cluster_1samp_test(X, threshold=thresh,
step_down_p=0.0)
assert_equal(np.sum(p_old < 0.05), 1) # just spatial cluster
t, clusters, p_new, H0 = \
permutation_cluster_1samp_test(X, threshold=thresh,
step_down_p=0.05)
assert_equal(np.sum(p_new < 0.05), 2) # time one rescued
assert_true(np.all(p_old >= p_new))
def test_cluster_permutation_test():
"""Test cluster level permutations tests."""
condition1_1d, condition2_1d, condition1_2d, condition2_2d = \
_get_conditions()
for condition1, condition2 in zip((condition1_1d, condition1_2d),
(condition2_1d, condition2_2d)):
T_obs, clusters, cluster_p_values, hist = permutation_cluster_test(
[condition1, condition2], n_permutations=100, tail=1, seed=1,
buffer_size=None)
assert_equal(np.sum(cluster_p_values < 0.05), 1)
T_obs, clusters, cluster_p_values, hist = permutation_cluster_test(
[condition1, condition2], n_permutations=100, tail=0, seed=1,
buffer_size=None)
assert_equal(np.sum(cluster_p_values < 0.05), 1)
# test with 2 jobs and buffer_size enabled
buffer_size = condition1.shape[1] // 10
T_obs, clusters, cluster_p_values_buff, hist =\
permutation_cluster_test([condition1, condition2],
n_permutations=100, tail=0, seed=1,
n_jobs=2, buffer_size=buffer_size)
assert_array_equal(cluster_p_values, cluster_p_values_buff)
@slow_test
def test_cluster_permutation_t_test():
"""Test cluster level permutations T-test."""
condition1_1d, condition2_1d, condition1_2d, condition2_2d = \
_get_conditions()
# use a very large sigma to make sure Ts are not independent
stat_funs = [ttest_1samp_no_p,
partial(ttest_1samp_no_p, sigma=1e-1)]
for stat_fun in stat_funs:
for condition1 in (condition1_1d, condition1_2d):
# these are so significant we can get away with fewer perms
T_obs, clusters, cluster_p_values, hist =\
permutation_cluster_1samp_test(condition1, n_permutations=100,
tail=0, seed=1,
buffer_size=None)
assert_equal(np.sum(cluster_p_values < 0.05), 1)
T_obs_pos, c_1, cluster_p_values_pos, _ =\
permutation_cluster_1samp_test(condition1, n_permutations=100,
tail=1, threshold=1.67, seed=1,
stat_fun=stat_fun,
buffer_size=None)
T_obs_neg, _, cluster_p_values_neg, _ =\
permutation_cluster_1samp_test(-condition1, n_permutations=100,
tail=-1, threshold=-1.67,
seed=1, stat_fun=stat_fun,
buffer_size=None)
assert_array_equal(T_obs_pos, -T_obs_neg)
assert_array_equal(cluster_p_values_pos < 0.05,
cluster_p_values_neg < 0.05)
# test with 2 jobs and buffer_size enabled
buffer_size = condition1.shape[1] // 10
with warnings.catch_warnings(record=True): # independently
T_obs_neg_buff, _, cluster_p_values_neg_buff, _ = \
permutation_cluster_1samp_test(
-condition1, n_permutations=100, tail=-1,
threshold=-1.67, seed=1, n_jobs=2, stat_fun=stat_fun,
buffer_size=buffer_size)
assert_array_equal(T_obs_neg, T_obs_neg_buff)
assert_array_equal(cluster_p_values_neg, cluster_p_values_neg_buff)
@slow_test
def test_cluster_permutation_with_connectivity():
"""Test cluster level permutations with connectivity matrix."""
try:
try:
from sklearn.feature_extraction.image import grid_to_graph
except ImportError:
from scikits.learn.feature_extraction.image import grid_to_graph
except ImportError:
return
condition1_1d, condition2_1d, condition1_2d, condition2_2d = \
_get_conditions()
n_pts = condition1_1d.shape[1]
# we don't care about p-values in any of these, so do fewer permutations
args = dict(seed=None, max_step=1, exclude=None,
step_down_p=0, t_power=1, threshold=1.67,
check_disjoint=False, n_permutations=50)
did_warn = False
for X1d, X2d, func, spatio_temporal_func in \
[(condition1_1d, condition1_2d,
permutation_cluster_1samp_test,
spatio_temporal_cluster_1samp_test),
([condition1_1d, condition2_1d],
[condition1_2d, condition2_2d],
permutation_cluster_test,
spatio_temporal_cluster_test)]:
out = func(X1d, **args)
connectivity = grid_to_graph(1, n_pts)
out_connectivity = func(X1d, connectivity=connectivity, **args)
assert_array_equal(out[0], out_connectivity[0])
for a, b in zip(out_connectivity[1], out[1]):
assert_array_equal(out[0][a], out[0][b])
assert_true(np.all(a[b]))
# test spatio-temporal w/o time connectivity (repeat spatial pattern)
connectivity_2 = sparse.coo_matrix(
linalg.block_diag(connectivity.asfptype().todense(),
connectivity.asfptype().todense()))
if isinstance(X1d, list):
X1d_2 = [np.concatenate((x, x), axis=1) for x in X1d]
else:
X1d_2 = np.concatenate((X1d, X1d), axis=1)
out_connectivity_2 = func(X1d_2, connectivity=connectivity_2, **args)
# make sure we were operating on the same values
split = len(out[0])
assert_array_equal(out[0], out_connectivity_2[0][:split])
assert_array_equal(out[0], out_connectivity_2[0][split:])
# make sure we really got 2x the number of original clusters
n_clust_orig = len(out[1])
assert_true(len(out_connectivity_2[1]) == 2 * n_clust_orig)
# Make sure that we got the old ones back
data_1 = set([np.sum(out[0][b[:n_pts]]) for b in out[1]])
data_2 = set([np.sum(out_connectivity_2[0][a]) for a in
out_connectivity_2[1][:]])
assert_true(len(data_1.intersection(data_2)) == len(data_1))
# now use the other algorithm
if isinstance(X1d, list):
X1d_3 = [np.reshape(x, (-1, 2, n_space)) for x in X1d_2]
else:
X1d_3 = np.reshape(X1d_2, (-1, 2, n_space))
out_connectivity_3 = spatio_temporal_func(X1d_3, n_permutations=50,
connectivity=connectivity,
max_step=0, threshold=1.67,
check_disjoint=True)
# make sure we were operating on the same values
split = len(out[0])
assert_array_equal(out[0], out_connectivity_3[0][0])
assert_array_equal(out[0], out_connectivity_3[0][1])
# make sure we really got 2x the number of original clusters
assert_true(len(out_connectivity_3[1]) == 2 * n_clust_orig)
# Make sure that we got the old ones back
data_1 = set([np.sum(out[0][b[:n_pts]]) for b in out[1]])
data_2 = set([np.sum(out_connectivity_3[0][a[0], a[1]]) for a in
out_connectivity_3[1]])
assert_true(len(data_1.intersection(data_2)) == len(data_1))
# test new versus old method
out_connectivity_4 = spatio_temporal_func(X1d_3, n_permutations=50,
connectivity=connectivity,
max_step=2, threshold=1.67)
out_connectivity_5 = spatio_temporal_func(X1d_3, n_permutations=50,
connectivity=connectivity,
max_step=1, threshold=1.67)
# clusters could be in a different order
sums_4 = [np.sum(out_connectivity_4[0][a])
for a in out_connectivity_4[1]]
sums_5 = [np.sum(out_connectivity_4[0][a])
for a in out_connectivity_5[1]]
sums_4 = np.sort(sums_4)
sums_5 = np.sort(sums_5)
assert_array_almost_equal(sums_4, sums_5)
if not _force_serial:
assert_raises(ValueError, spatio_temporal_func, X1d_3,
n_permutations=1, connectivity=connectivity,
max_step=1, threshold=1.67, n_jobs=-1000)
# not enough TFCE params
assert_raises(KeyError, spatio_temporal_func, X1d_3,
connectivity=connectivity, threshold=dict(me='hello'))
# too extreme a start threshold
with warnings.catch_warnings(record=True) as w:
spatio_temporal_func(X1d_3, connectivity=connectivity,
threshold=dict(start=10, step=1))
if not did_warn:
assert_true(len(w) == 1)
did_warn = True
# too extreme a start threshold
assert_raises(ValueError, spatio_temporal_func, X1d_3,
connectivity=connectivity, tail=-1,
threshold=dict(start=1, step=-1))
assert_raises(ValueError, spatio_temporal_func, X1d_3,
connectivity=connectivity, tail=-1,
threshold=dict(start=-1, step=1))
# wrong type for threshold
assert_raises(TypeError, spatio_temporal_func, X1d_3,
connectivity=connectivity, threshold=[])
# wrong value for tail
assert_raises(ValueError, spatio_temporal_func, X1d_3,
connectivity=connectivity, tail=2)
# make sure it actually found a significant point
out_connectivity_6 = spatio_temporal_func(X1d_3, n_permutations=50,
connectivity=connectivity,
max_step=1,
threshold=dict(start=1,
step=1))
assert_true(np.min(out_connectivity_6[2]) < 0.05)
@slow_test
def test_permutation_connectivity_equiv():
"""Test cluster level permutations with and without connectivity."""
try:
try:
from sklearn.feature_extraction.image import grid_to_graph
except ImportError:
from scikits.learn.feature_extraction.image import grid_to_graph
except ImportError:
return
rng = np.random.RandomState(0)
# subjects, time points, spatial points
n_time = 2
n_space = 4
X = rng.randn(6, n_time, n_space)
# add some significant points
X[:, :, 0:2] += 10 # span two time points and two spatial points
X[:, 1, 3] += 20 # span one time point
max_steps = [1, 1, 1, 2]
# This will run full algorithm in two ways, then the ST-algorithm in 2 ways
# All of these should give the same results
conns = [None, grid_to_graph(n_time, n_space),
grid_to_graph(1, n_space), grid_to_graph(1, n_space)]
stat_map = None
thresholds = [2, dict(start=1.5, step=1.0)]
sig_counts = [2, 5]
sdps = [0, 0.05, 0.05]
ots = ['mask', 'mask', 'indices']
stat_fun = partial(ttest_1samp_no_p, sigma=1e-3)
for thresh, count in zip(thresholds, sig_counts):
cs = None
ps = None
for max_step, conn in zip(max_steps, conns):
for sdp, ot in zip(sdps, ots):
t, clusters, p, H0 = \
permutation_cluster_1samp_test(
X, threshold=thresh, connectivity=conn, n_jobs=2,
max_step=max_step, stat_fun=stat_fun,
step_down_p=sdp, out_type=ot)
# make sure our output datatype is correct
if ot == 'mask':
assert_true(isinstance(clusters[0], np.ndarray))
assert_true(clusters[0].dtype == bool)
assert_array_equal(clusters[0].shape, X.shape[1:])
else: # ot == 'indices'
assert_true(isinstance(clusters[0], tuple))
# make sure all comparisons were done; for TFCE, no perm
# should come up empty
if count == 8:
assert_true(not np.any(H0 == 0))
inds = np.where(p < 0.05)[0]
assert_true(len(inds) == count)
this_cs = [clusters[ii] for ii in inds]
this_ps = p[inds]
this_stat_map = np.zeros((n_time, n_space), dtype=bool)
for ci, c in enumerate(this_cs):
if isinstance(c, tuple):
this_c = np.zeros((n_time, n_space), bool)
for x, y in zip(c[0], c[1]):
this_stat_map[x, y] = True
this_c[x, y] = True
this_cs[ci] = this_c
c = this_c
this_stat_map[c] = True
if cs is None:
ps = this_ps
cs = this_cs
if stat_map is None:
stat_map = this_stat_map
assert_array_equal(ps, this_ps)
assert_true(len(cs) == len(this_cs))
for c1, c2 in zip(cs, this_cs):
assert_array_equal(c1, c2)
assert_array_equal(stat_map, this_stat_map)
@slow_test
def spatio_temporal_cluster_test_connectivity():
"""Test spatio-temporal cluster permutations."""
try:
try:
from sklearn.feature_extraction.image import grid_to_graph
except ImportError:
from scikits.learn.feature_extraction.image import grid_to_graph
except ImportError:
return
condition1_1d, condition2_1d, condition1_2d, condition2_2d = \
_get_conditions()
rng = np.random.RandomState(0)
noise1_2d = rng.randn(condition1_2d.shape[0], condition1_2d.shape[1], 10)
data1_2d = np.transpose(np.dstack((condition1_2d, noise1_2d)), [0, 2, 1])
noise2_d2 = rng.randn(condition2_2d.shape[0], condition2_2d.shape[1], 10)
data2_2d = np.transpose(np.dstack((condition2_2d, noise2_d2)), [0, 2, 1])
conn = grid_to_graph(data1_2d.shape[-1], 1)
threshold = dict(start=4.0, step=2)
T_obs, clusters, p_values_conn, hist = \
spatio_temporal_cluster_test([data1_2d, data2_2d], connectivity=conn,
n_permutations=50, tail=1, seed=1,
threshold=threshold, buffer_size=None)
buffer_size = data1_2d.size // 10
T_obs, clusters, p_values_no_conn, hist = \
spatio_temporal_cluster_test([data1_2d, data2_2d],
n_permutations=50, tail=1, seed=1,
threshold=threshold, n_jobs=2,
buffer_size=buffer_size)
assert_equal(np.sum(p_values_conn < 0.05), np.sum(p_values_no_conn < 0.05))
# make sure results are the same without buffer_size
T_obs, clusters, p_values2, hist2 = \
spatio_temporal_cluster_test([data1_2d, data2_2d],
n_permutations=50, tail=1, seed=1,
threshold=threshold, n_jobs=2,
buffer_size=None)
assert_array_equal(p_values_no_conn, p_values2)
assert_raises(ValueError, spatio_temporal_cluster_test,
[data1_2d, data2_2d], tail=1, threshold=-2.)
assert_raises(ValueError, spatio_temporal_cluster_test,
[data1_2d, data2_2d], tail=-1, threshold=2.)
assert_raises(ValueError, spatio_temporal_cluster_test,
[data1_2d, data2_2d], tail=0, threshold=-1)
def ttest_1samp(X):
"""Return T-values."""
return stats.ttest_1samp(X, 0)[0]
def test_summarize_clusters():
"""Test cluster summary stcs."""
clu = (np.random.random([1, 20484]),
[(np.array([0]), np.array([0, 2, 4]))],
np.array([0.02, 0.1]),
np.array([12, -14, 30]))
stc_sum = summarize_clusters_stc(clu)
assert_true(stc_sum.data.shape[1] == 2)
clu[2][0] = 0.3
assert_raises(RuntimeError, summarize_clusters_stc, clu)
run_tests_if_main()
| {
"repo_name": "nicproulx/mne-python",
"path": "mne/stats/tests/test_cluster_level.py",
"copies": "3",
"size": "20846",
"license": "bsd-3-clause",
"hash": -8897307510832922000,
"line_mean": 42.7023060797,
"line_max": 95,
"alpha_frac": 0.5498416962,
"autogenerated": false,
"ratio": 3.6507880910683013,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5700629787268301,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import os
from django.contrib.auth import get_user_model
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.utils import override_settings
from .factories import UserFactory, VoterFactory, SiteFactory, DebateFactory
# Force the reverse() used here in the tests to always use the full
# urlconf, despite whatever machinations have taken place due to the
# DebateMiddleware.
old_reverse = reverse
reverse = partial(old_reverse, urlconf='opendebates.urls')
class RegisterTest(TestCase):
def setUp(self):
self.site = SiteFactory()
self.debate = DebateFactory(site=self.site)
self.url = reverse('registration_register', kwargs={'prefix': self.debate.prefix})
self.data = {
'username': 'gwash',
'password1': 'secretpassword',
'password2': 'secretpassword',
'first_name': 'George',
'last_name': 'Washington',
'email': 'gwash@example.com',
'zip': '12345',
'g-recaptcha-response': 'PASSED'
}
os.environ['NORECAPTCHA_TESTING'] = 'True'
def tearDown(self):
Site.objects.clear_cache()
os.environ.pop('NORECAPTCHA_TESTING', '')
def test_registration_get(self):
"GET the form successfully."
with self.assertTemplateUsed('registration/registration_form.html'):
rsp = self.client.get(self.url)
self.assertEqual(200, rsp.status_code)
def test_toggle_form_display_name(self):
with override_settings(ENABLE_USER_DISPLAY_NAME=True):
rsp = self.client.get(self.url)
self.assertContains(rsp, 'Display name')
with override_settings(ENABLE_USER_DISPLAY_NAME=False):
rsp = self.client.get(self.url)
self.assertNotContains(rsp, 'Display name')
def test_toggle_form_phone_number(self):
with override_settings(ENABLE_USER_PHONE_NUMBER=True):
rsp = self.client.get(self.url)
self.assertContains(rsp, 'Phone number')
with override_settings(ENABLE_USER_PHONE_NUMBER=False):
rsp = self.client.get(self.url)
self.assertNotContains(rsp, 'Phone number')
def test_post_success(self):
"POST the form with all required values."
home_url = reverse('list_ideas', kwargs={'prefix': self.debate.prefix})
rsp = self.client.post(self.url, data=self.data, follow=True)
self.assertRedirects(rsp, home_url)
new_user = get_user_model().objects.first()
self.assertEqual(new_user.first_name, self.data['first_name'])
def test_post_missing_variable(self):
"POST with a missing required value."
# delete each required key and POST
for key in self.data:
if key == 'g-recaptcha-response':
continue
data = self.data.copy()
del data[key]
rsp = self.client.post(self.url)
self.assertEqual(200, rsp.status_code)
form = rsp.context['form']
self.assertIn(key, form.errors)
self.assertIn('field is required', str(form.errors))
def test_email_must_be_unique(self):
# case insensitive
UserFactory(email=self.data['email'].upper())
rsp = self.client.post(self.url, data=self.data)
self.assertRedirects(rsp, reverse('registration_duplicate',
kwargs={'prefix': self.debate.prefix}))
def test_twitter_handle_gets_cleaned(self):
"Various forms of twitter_handle entries are cleaned to canonical form."
data = {}
for twitter_handle in [
'@twitter',
'twitter',
'https://twitter.com/twitter',
'http://twitter.com/twitter',
'twitter.com/twitter',
]:
data['twitter_handle'] = twitter_handle
rsp = self.client.post(self.url, data=data)
form = rsp.context['form']
self.assertEqual('twitter', form.cleaned_data['twitter_handle'])
@override_settings(USE_CAPTCHA=False)
def test_disabling_captcha(self):
del self.data['g-recaptcha-response']
del os.environ['NORECAPTCHA_TESTING']
home_url = reverse('list_ideas', kwargs={'prefix': self.debate.prefix})
rsp = self.client.post(self.url, data=self.data, follow=True)
self.assertRedirects(rsp, home_url)
new_user = get_user_model().objects.first()
self.assertEqual(new_user.first_name, self.data['first_name'])
class LoginLogoutTest(TestCase):
def setUp(self):
self.site = SiteFactory()
self.debate = DebateFactory(site=self.site)
self.username = 'gwash'
self.email = 'gwash@example.com'
self.password = 'secretpassword'
# use VoterFactory so we have a Debate to authenticate against in
# our custom auth backend when logging in via email
self.voter = VoterFactory(
user__username=self.username,
user__email=self.email,
user__password=self.password,
)
self.login_url = reverse('auth_login', kwargs={'prefix': self.debate.prefix})
self.home_url = reverse('list_ideas', kwargs={'prefix': self.debate.prefix})
def tearDown(self):
Site.objects.clear_cache()
def test_login_with_username(self):
rsp = self.client.post(
self.login_url,
data={'username': self.username, 'password': self.password,
'next': '/{}/'.format(self.debate.prefix)}
)
self.assertRedirects(rsp, self.home_url)
def test_login_with_email(self):
rsp = self.client.post(
self.login_url,
data={'username': self.email, 'password': self.password,
'next': '/{}/'.format(self.debate.prefix)}
)
self.assertRedirects(rsp, self.home_url)
def test_failed_login(self):
rsp = self.client.post(
self.login_url,
data={'username': self.username, 'password': self.password + 'bad',
'next': '/{}/'.format(self.debate.prefix)}
)
self.assertEqual(200, rsp.status_code)
form = rsp.context['form']
self.assertIn('enter a correct username and password', str(form.errors))
def test_logout(self):
self.assertTrue(self.client.login(username=self.username, password=self.password))
logout_url = reverse('auth_logout', kwargs={'prefix': self.debate.prefix})
rsp = self.client.get(logout_url)
self.assertRedirects(rsp, self.home_url)
rsp = self.client.get(self.home_url)
self.assertIn('Log in', rsp.content)
| {
"repo_name": "caktus/django-opendebates",
"path": "opendebates/tests/test_registration.py",
"copies": "1",
"size": "6816",
"license": "apache-2.0",
"hash": -6475071851491655000,
"line_mean": 38.1724137931,
"line_max": 90,
"alpha_frac": 0.6132629108,
"autogenerated": false,
"ratio": 3.885974914481186,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4999237825281186,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import os
import cobble
from .. import results, lists, zips
from .document_xml import read_document_xml_element
from .content_types_xml import empty_content_types, read_content_types_xml_element
from .relationships_xml import read_relationships_xml_element, Relationships
from .numbering_xml import read_numbering_xml_element, Numbering
from .styles_xml import read_styles_xml_element, Styles
from .notes_xml import read_endnotes_xml_element, read_footnotes_xml_element
from .comments_xml import read_comments_xml_element
from .files import Files
from . import body_xml, office_xml
from ..zips import open_zip
_empty_result = results.success([])
def read(fileobj):
zip_file = open_zip(fileobj, "r")
part_paths = _find_part_paths(zip_file)
read_part_with_body = _part_with_body_reader(
getattr(fileobj, "name", None),
zip_file,
part_paths=part_paths,
)
return results.combine([
_read_notes(read_part_with_body, part_paths),
_read_comments(read_part_with_body, part_paths),
]).bind(lambda referents:
_read_document(zip_file, read_part_with_body, notes=referents[0], comments=referents[1], part_paths=part_paths)
)
@cobble.data
class _PartPaths(object):
main_document = cobble.field()
comments = cobble.field()
endnotes = cobble.field()
footnotes = cobble.field()
numbering = cobble.field()
styles = cobble.field()
def _find_part_paths(zip_file):
package_relationships = _read_relationships(zip_file, "_rels/.rels")
document_filename = _find_document_filename(zip_file, package_relationships)
document_relationships = _read_relationships(
zip_file,
_find_relationships_path_for(document_filename),
)
def find(name):
return _find_part_path(
zip_file=zip_file,
relationships=document_relationships,
relationship_type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/" + name,
fallback_path="word/{0}.xml".format(name),
base_path=zips.split_path(document_filename)[0],
)
return _PartPaths(
main_document=document_filename,
comments=find("comments"),
endnotes=find("endnotes"),
footnotes=find("footnotes"),
numbering=find("numbering"),
styles=find("styles"),
)
def _find_document_filename(zip_file, relationships):
path = _find_part_path(
zip_file,
relationships,
relationship_type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
base_path="",
fallback_path="word/document.xml",
)
if zip_file.exists(path):
return path
else:
raise IOError("Could not find main document part. Are you sure this is a valid .docx file?")
def _find_part_path(zip_file, relationships, relationship_type, base_path, fallback_path):
targets = [
zips.join_path(base_path, target).lstrip("/")
for target in relationships.find_targets_by_type(relationship_type)
]
valid_targets = list(filter(lambda target: zip_file.exists(target), targets))
if len(valid_targets) == 0:
return fallback_path
else:
return valid_targets[0]
def _read_notes(read_part_with_body, part_paths):
footnotes = read_part_with_body(
part_paths.footnotes,
lambda root, body_reader: read_footnotes_xml_element(root, body_reader=body_reader),
default=_empty_result,
)
endnotes = read_part_with_body(
part_paths.endnotes,
lambda root, body_reader: read_endnotes_xml_element(root, body_reader=body_reader),
default=_empty_result,
)
return results.combine([footnotes, endnotes]).map(lists.flatten)
def _read_comments(read_part_with_body, part_paths):
return read_part_with_body(
part_paths.comments,
lambda root, body_reader: read_comments_xml_element(root, body_reader=body_reader),
default=_empty_result,
)
def _read_document(zip_file, read_part_with_body, notes, comments, part_paths):
return read_part_with_body(
part_paths.main_document,
partial(
read_document_xml_element,
notes=notes,
comments=comments,
),
)
def _part_with_body_reader(document_path, zip_file, part_paths):
content_types = _try_read_entry_or_default(
zip_file,
"[Content_Types].xml",
read_content_types_xml_element,
empty_content_types,
)
styles = _try_read_entry_or_default(
zip_file,
part_paths.styles,
read_styles_xml_element,
Styles.EMPTY,
)
numbering = _try_read_entry_or_default(
zip_file,
part_paths.numbering,
lambda element: read_numbering_xml_element(element, styles=styles),
default=Numbering.EMPTY,
)
def read_part(name, reader, default=_undefined):
relationships = _read_relationships(zip_file, _find_relationships_path_for(name))
body_reader = body_xml.reader(
numbering=numbering,
content_types=content_types,
relationships=relationships,
styles=styles,
docx_file=zip_file,
files=Files(None if document_path is None else os.path.dirname(document_path)),
)
if default is _undefined:
return _read_entry(zip_file, name, partial(reader, body_reader=body_reader))
else:
return _try_read_entry_or_default(zip_file, name, partial(reader, body_reader=body_reader), default=default)
return read_part
def _find_relationships_path_for(name):
dirname, basename = zips.split_path(name)
return zips.join_path(dirname, "_rels", basename + ".rels")
def _read_relationships(zip_file, name):
return _try_read_entry_or_default(
zip_file,
name,
read_relationships_xml_element,
default=Relationships.EMPTY,
)
def _try_read_entry_or_default(zip_file, name, reader, default):
if zip_file.exists(name):
return _read_entry(zip_file, name, reader)
else:
return default
def _read_entry(zip_file, name, reader):
with zip_file.open(name) as fileobj:
return reader(office_xml.read(fileobj))
_undefined = object()
| {
"repo_name": "mwilliamson/python-mammoth",
"path": "mammoth/docx/__init__.py",
"copies": "1",
"size": "6342",
"license": "bsd-2-clause",
"hash": 3352100776425140000,
"line_mean": 29.9365853659,
"line_max": 120,
"alpha_frac": 0.6542100284,
"autogenerated": false,
"ratio": 3.5749718151071024,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47291818435071026,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import os
import numpy as np
from six.moves import range
from tqdm import tqdm
from cloudfiles import CloudFiles, reset_connection_pools, compression
from cloudvolume import lib, chunks
from cloudvolume.exceptions import AlignmentError
from cloudvolume.lib import (
mkdir, clamp, xyzrange, Vec,
Bbox, min2, max2
)
from cloudvolume.scheduler import schedule_jobs
from cloudvolume.threaded_queue import DEFAULT_THREADS
from cloudvolume.volumecutout import VolumeCutout
import cloudvolume.sharedmemory as shm
from ... import check_grid_aligned
from .common import (
fs_lock, parallel_execution, chunknames,
shade
)
from ..common import (
content_type, cdn_cache_control,
should_compress
)
from .rx import download_chunks_threaded
def upload(
meta, cache,
image, offset, mip,
compress=None,
compress_level=None,
cdn_cache=None,
parallel=1,
progress=False,
delete_black_uploads=False,
background_color=0,
non_aligned_writes=False,
location=None, location_bbox=None, location_order='F',
use_shared_memory=False, use_file=False,
green=False, fill_missing=False, secrets=None
):
"""Upload img to vol with offset. This is the primary entry point for uploads."""
if not np.issubdtype(image.dtype, np.dtype(meta.dtype).type):
raise ValueError("""
The uploaded image data type must match the volume data type.
Volume: {}
Image: {}
""".format(meta.dtype, image.dtype)
)
shape = Vec(*image.shape)[:3]
offset = Vec(*offset)[:3]
bounds = Bbox( offset, shape + offset)
is_aligned = check_grid_aligned(
meta, image, bounds, mip,
throw_error=(non_aligned_writes == False)
)
options = {
"compress": compress,
"compress_level": compress_level,
"cdn_cache": cdn_cache,
"parallel": parallel,
"progress": progress,
"location": location,
"location_bbox": location_bbox,
"location_order": location_order,
"use_shared_memory": use_shared_memory,
"use_file": use_file,
"delete_black_uploads": delete_black_uploads,
"background_color": background_color,
"green": green,
"secrets": secrets,
}
if is_aligned:
upload_aligned(
meta, cache,
image, offset, mip,
**options
)
return
# Upload the aligned core
expanded = bounds.expand_to_chunk_size(meta.chunk_size(mip), meta.voxel_offset(mip))
retracted = bounds.shrink_to_chunk_size(meta.chunk_size(mip), meta.voxel_offset(mip))
core_bbox = retracted.clone() - bounds.minpt
if not core_bbox.subvoxel():
core_img = image[ core_bbox.to_slices() ]
upload_aligned(
meta, cache,
core_img, retracted.minpt, mip,
**options
)
# Download the shell, paint, and upload
all_chunks = set(chunknames(expanded, meta.bounds(mip), meta.key(mip), meta.chunk_size(mip)))
core_chunks = set(chunknames(retracted, meta.bounds(mip), meta.key(mip), meta.chunk_size(mip)))
shell_chunks = all_chunks.difference(core_chunks)
def shade_and_upload(img3d, bbox):
# decode is returning non-writable chunk
# we're throwing them away so safe to write
img3d.setflags(write=1)
shade(img3d, bbox, image, bounds)
threaded_upload_chunks(
meta, cache,
img3d, mip,
(( Vec(0,0,0), Vec(*img3d.shape[:3]), bbox.minpt, bbox.maxpt),),
compress=compress, cdn_cache=cdn_cache,
progress=False, n_threads=0,
delete_black_uploads=delete_black_uploads,
green=green, secrets=secrets
)
compress_cache = should_compress(meta.encoding(mip), compress, cache, iscache=True)
download_chunks_threaded(
meta, cache, mip, shell_chunks, fn=shade_and_upload,
fill_missing=fill_missing,
progress=("Shading Border" if progress else None),
compress_cache=compress_cache,
green=green, secrets=secrets
)
def upload_aligned(
meta, cache,
img, offset, mip,
compress=None,
compress_level=None,
cdn_cache=None,
progress=False,
parallel=1,
location=None,
location_bbox=None,
location_order='F',
use_shared_memory=False,
use_file=False,
delete_black_uploads=False,
background_color=0,
green=False,
secrets=None,
):
global fs_lock
chunk_ranges = list(generate_chunks(meta, img, offset, mip))
if parallel == 1:
threaded_upload_chunks(
meta, cache,
img, mip, chunk_ranges,
progress=progress,
compress=compress, cdn_cache=cdn_cache,
delete_black_uploads=delete_black_uploads,
background_color=background_color,
green=green, compress_level=compress_level,
secrets=secrets
)
return
length = (len(chunk_ranges) // parallel) or 1
chunk_ranges_by_process = []
for i in range(0, len(chunk_ranges), length):
chunk_ranges_by_process.append(
chunk_ranges[i:i+length]
)
# use_shared_memory means use a predetermined
# shared memory location, not no shared memory
# at all.
if not use_shared_memory:
array_like, renderbuffer = shm.ndarray(
shape=img.shape, dtype=img.dtype,
location=location, order=location_order,
lock=fs_lock
)
renderbuffer[:] = img
cup = partial(child_upload_process,
meta, cache,
img.shape, offset, mip,
compress, cdn_cache, progress,
location, location_bbox, location_order,
delete_black_uploads, background_color,
green, compress_level=compress_level,
secrets=secrets
)
parallel_execution(cup, chunk_ranges_by_process, parallel, cleanup_shm=location)
# If manual mode is enabled, it's the
# responsibilty of the user to clean up
if not use_shared_memory:
array_like.close()
shm.unlink(location)
def child_upload_process(
meta, cache,
img_shape, offset, mip,
compress, cdn_cache, progress,
location, location_bbox, location_order,
delete_black_uploads, background_color,
green, chunk_ranges, compress_level=None,
secrets=None
):
global fs_lock
reset_connection_pools()
shared_shape = img_shape
if location_bbox:
shared_shape = list(location_bbox.size3()) + [ meta.num_channels ]
array_like, renderbuffer = shm.ndarray(
shape=shared_shape,
dtype=meta.dtype,
location=location,
order=location_order,
lock=fs_lock,
readonly=True
)
if location_bbox:
cutout_bbox = Bbox( offset, offset + img_shape[:3] )
delta_box = cutout_bbox.clone() - location_bbox.minpt
renderbuffer = renderbuffer[ delta_box.to_slices() ]
threaded_upload_chunks(
meta, cache,
renderbuffer, mip, chunk_ranges,
compress=compress, cdn_cache=cdn_cache, progress=progress,
delete_black_uploads=delete_black_uploads,
background_color=background_color,
green=green, compress_level=compress_level,
secrets=secrets
)
array_like.close()
def threaded_upload_chunks(
meta, cache,
img, mip, chunk_ranges,
compress, cdn_cache, progress,
n_threads=DEFAULT_THREADS,
delete_black_uploads=False,
background_color=0,
green=False,
compress_level=None,
secrets=None,
):
if cache.enabled:
mkdir(cache.path)
while img.ndim < 4:
img = img[ ..., np.newaxis ]
remote = CloudFiles(meta.cloudpath, secrets=secrets)
local = CloudFiles('file://' + cache.path, secrets=secrets)
def do_upload(imgchunk, cloudpath):
encoded = chunks.encode(imgchunk, meta.encoding(mip), meta.compressed_segmentation_block_size(mip))
remote_compress = should_compress(meta.encoding(mip), compress, cache)
cache_compress = should_compress(meta.encoding(mip), compress, cache, iscache=True)
remote_compress = compression.normalize_encoding(remote_compress)
cache_compress = compression.normalize_encoding(cache_compress)
encoded = compression.compress(encoded, remote_compress)
cache_encoded = encoded
if remote_compress != cache_compress:
cache_encoded = compression.compress(encoded, cache_compress)
remote.put(
path=cloudpath,
content=encoded,
content_type=content_type(meta.encoding(mip)),
compress=remote_compress,
compression_level=compress_level,
cache_control=cdn_cache_control(cdn_cache),
raw=True,
)
if cache.enabled:
local.put(
path=cloudpath,
content=cache_encoded,
content_type=content_type(meta.encoding(mip)),
compress=cache_compress,
raw=True,
)
def do_delete(cloudpath):
remote.delete(cloudpath)
if cache.enabled:
local.delete(cloudpath)
def process(startpt, endpt, spt, ept):
if np.array_equal(spt, ept):
return
imgchunk = img[ startpt.x:endpt.x, startpt.y:endpt.y, startpt.z:endpt.z, : ]
# handle the edge of the dataset
clamp_ept = min2(ept, meta.bounds(mip).maxpt)
newept = clamp_ept - spt
imgchunk = imgchunk[ :newept.x, :newept.y, :newept.z, : ]
filename = "{}-{}_{}-{}_{}-{}".format(
spt.x, clamp_ept.x,
spt.y, clamp_ept.y,
spt.z, clamp_ept.z
)
cloudpath = meta.join(meta.key(mip), filename)
if delete_black_uploads:
if np.any(imgchunk != background_color):
do_upload(imgchunk, cloudpath)
else:
do_delete(cloudpath)
else:
do_upload(imgchunk, cloudpath)
schedule_jobs(
fns=( partial(process, *vals) for vals in chunk_ranges ),
concurrency=n_threads,
progress=('Uploading' if progress else None),
total=len(chunk_ranges),
green=green,
)
def generate_chunks(meta, img, offset, mip):
shape = Vec(*img.shape)[:3]
offset = Vec(*offset)[:3]
bounds = Bbox( offset, shape + offset)
alignment_check = bounds.round_to_chunk_size(meta.chunk_size(mip), meta.voxel_offset(mip))
if not np.all(alignment_check.minpt == bounds.minpt):
raise AlignmentError("""
Only chunk aligned writes are supported by this function.
Got: {}
Volume Offset: {}
Nearest Aligned: {}
""".format(
bounds, meta.voxel_offset(mip), alignment_check)
)
bounds = Bbox.clamp(bounds, meta.bounds(mip))
img_offset = bounds.minpt - offset
img_end = Vec.clamp(bounds.size3() + img_offset, Vec(0,0,0), shape)
for startpt in xyzrange( img_offset, img_end, meta.chunk_size(mip) ):
startpt = startpt.clone()
endpt = min2(startpt + meta.chunk_size(mip), shape)
spt = (startpt + bounds.minpt).astype(int)
ept = (endpt + bounds.minpt).astype(int)
yield (startpt, endpt, spt, ept)
| {
"repo_name": "seung-lab/cloud-volume",
"path": "cloudvolume/datasource/precomputed/image/tx.py",
"copies": "1",
"size": "10525",
"license": "bsd-3-clause",
"hash": 4800593986127833000,
"line_mean": 27.3692722372,
"line_max": 103,
"alpha_frac": 0.6658432304,
"autogenerated": false,
"ratio": 3.418317635595973,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.45841608659959726,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import os
import numpy as np
from sklearn.preprocessing import LabelEncoder
from .. import SDC, NuSDC, Features
data_dir = os.path.join(os.path.dirname(__file__), 'data')
################################################################################
# TODO: add *real* tests
def _check_acc(acc):
assert acc >= .85, "accuracy is only {}".format(acc)
def test_simple():
div_funcs = ['hellinger', 'kl', 'l2',
'renyi:0.7', 'renyi:0.9', 'renyi:0.99']
Ks = [3, 8]
for name in ['gaussian-2d-mean0-std1,2']: # , 'gaussian-20d-mean0-std1,2']:
feats = Features.load_from_hdf5(os.path.join(data_dir, name + '.h5'))
le = LabelEncoder()
y = le.fit_transform(feats.categories)
for div_func in div_funcs:
for K in Ks:
for cls in [SDC, NuSDC]:
for wts in [None, np.random.uniform(.7, 1.3, len(feats))]:
clf = cls(div_func=div_func, K=K, n_proc=1)
acc, preds = clf.crossvalidate(
feats, y, sample_weight=wts, num_folds=3)
fn = partial(_check_acc, acc)
fn.description = "CV: {} - {}, K={}".format(
name, div_func, K)
yield fn
################################################################################
if __name__ == '__main__':
import warnings
warnings.filterwarnings('error', module='sdm')
import nose
nose.main()
| {
"repo_name": "dougalsutherland/py-sdm",
"path": "sdm/tests/test_sdm.py",
"copies": "1",
"size": "1555",
"license": "bsd-3-clause",
"hash": -108620780588993180,
"line_mean": 30.7346938776,
"line_max": 80,
"alpha_frac": 0.4655948553,
"autogenerated": false,
"ratio": 3.684834123222749,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4650428978522749,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import os.path
import sys
import time
from clint.textui import colored, puts
import git
from blame import is_older_than, Blame
class FormatterBase(object):
def __init__(self, directory, min_lines, months, stream=sys.stdout):
"""
Coloring of dates will depend on how far the commit is after the
age in months by multiples of 3.
For instance, if ``5`` is passed, commits older than 5 months will be
colored green, commits older than 10 months will be colored yellow,
and commits older than 15 months will be colored red.
"""
self.update_stream(stream)
self.min_lines = min_lines
self.months = months
self.repo = git.Repo(directory)
self.latest_commit = self.repo.commits()[0]
self.blobs = self.latest_commit.tree.values()
def _get_relative_age(self, commit):
# Used for determining what visual style the commit should have.
if is_older_than(commit, self.months * 3):
return 'old'
if is_older_than(commit, self.months * 2):
return 'medium'
else:
return 'new'
def update_stream(self, stream):
"""
Created to allow on-the-fly injecting of new streams, such as when
splitting output across multiple files.
"""
self.p = partial(puts, newline=False, stream=stream.write)
def format_blob(self, blob):
blame = git.Blob.blame(self.repo, self.latest_commit, blob.name)
blame = Blame(blame)
buckets = blame.filter(min_lines=self.min_lines,
months=self.months)
# Discard empty buckets
buckets = filter(lambda b: len(b) > 0, buckets)
# Do the formatting
for bucket in buckets:
for commit, lines_changed in bucket:
first = True
for line in lines_changed:
self.format_line(commit, line, first=first)
first = False
def format_line(self, commit, line, first=False):
self.p("")
def format(self):
for blob in self.blobs:
self.format_blob(blob)
class TextFormatter(FormatterBase):
def _color_date(self, commit, text):
age = self._get_relative_age(commit)
ages_to_colors = {
'old': colored.red,
'medium': colored.yellow,
'new': colored.green,
}
return str(ages_to_colors.get(age)(text))
def format_blob(self, blob):
self.p("/" + "-" * 78 + "\n")
self.p("| {} \n".format(blob.name))
super(TextFormatter, self).format_blob(blob)
self.p("\\" + "-" * 78 + "\n\n")
def format_line(self, commit, line, first=False):
# Left column
pre_first = "{}\t{}\t".format(
commit.id[:10],
time.strftime("%m/%d/%y", commit.authored_date))
pre_first = self._color_date(commit, pre_first)
pre_empty = "{}\t{}\t".format("." * 10, "." * 8)
# Print the line
self.p(pre_first if first else pre_empty)
self.p(line)
if "\n" not in line:
self.p("\n")
class HtmlFormatter(FormatterBase):
def format(self, *args, **kwargs):
self.p("<style>{}</style>".format(self._get_css()))
super(HtmlFormatter, self).format(*args, **kwargs)
def _get_css(self):
basepath = os.path.dirname(__file__)
filepath = os.path.abspath(os.path.join(
basepath, "assets", "style.css"))
with open(filepath, 'rb') as f:
return "".join(f.readlines())
def format_blob(self, blob):
self.p("<table>")
self.p("<thead><td colspan=3>{}</td></thead>".format(blob.name))
self.p("<tbody>")
super(HtmlFormatter, self).format_blob(blob)
self.p("</tbody>")
self.p("</table>")
def format_line(self, commit, line, first=False):
self.p("<tr class='{} {}'>".format(
self._get_relative_age(commit),
"first" if first else "", # allow for shading of the "..."
))
if first:
cols = (commit.id[:10],
time.strftime("%m/%d/%y", commit.authored_date))
else:
cols = ("." * 10, "." * 8)
cols = cols + (line,)
self.p("<td>{}</td><td>{}</td><td>{}</td>".format(*cols))
self.p("</tr>")
| {
"repo_name": "saucelabs/docrot",
"path": "docrot/formatter.py",
"copies": "1",
"size": "4429",
"license": "apache-2.0",
"hash": 8005039712178454000,
"line_mean": 31.3284671533,
"line_max": 77,
"alpha_frac": 0.5513659968,
"autogenerated": false,
"ratio": 3.7438715131022824,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47952375099022826,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import os.path
def deleteContent(pfile):
pfile.seek(0)
pfile.truncate()
def next_move(bot_x, bot_y, board):
is_present = os.path.isfile('bot-building.txt')
if is_present:
f = open('bot-building.txt', 'r+')
else:
f = open('bot-building.txt', 'w')
l = [['o' for j in range(5)] for i in range(5)]
if is_present:
i = 0
for line in f:
for j in range(5):
l[i][j] = line[j]
i += 1
dirty_cells = []
for i in range(5):
for j in range(5):
if board[i][j] == 'd':
dirty_cells.append((i, j))
l[i][j] = '-'
elif board[i][j] == '-' or board[i][j] == 'b':
l[i][j] = '-'
# print l
x = bot_x
y = bot_y
if dirty_cells:
# Get closest cell
dist = lambda s, d: (s[0] - d[0]) ** 2 + (s[1] - d[1]) ** 2
closest_dirty_cell = min(dirty_cells,
key=partial(dist, (bot_x, bot_y)))
x = closest_dirty_cell[0]
y = closest_dirty_cell[1]
if len(dirty_cells) > 1:
for i in dirty_cells:
l[i[0]][i[1]] = 'o'
else:
undiscovered_cells = []
for i in range(5):
for j in range(5):
if l[i][j] == 'o':
undiscovered_cells.append((i, j))
if undiscovered_cells:
dist = lambda s, d: (s[0] - d[0]) ** 2 + (s[1] - d[1]) ** 2
closest_dirty_cell = min(undiscovered_cells,
key=partial(dist, (bot_x, bot_y)))
x = closest_dirty_cell[0]
y = closest_dirty_cell[1]
deleteContent(f)
for line in l:
f.write("".join(line) + "\n")
# print x, y
move = ""
if bot_y != y:
if bot_y > y:
move = "LEFT"
else:
move = "RIGHT"
elif bot_x != x:
if bot_x > x:
move = "UP"
else:
move = "DOWN"
else:
move = "CLEAN"
print move
if __name__ == "__main__":
pos = [int(i) for i in raw_input().strip().split()]
board = [[j for j in raw_input().strip()] for i in range(5)]
next_move(pos[0], pos[1], board)
| {
"repo_name": "spradeepv/dive-into-python",
"path": "hackerrank/domain/artificial_intelligence/bot_building/bot_clean_partially_observable.py",
"copies": "1",
"size": "2274",
"license": "mit",
"hash": -7391442541459939000,
"line_mean": 27.7848101266,
"line_max": 71,
"alpha_frac": 0.437994723,
"autogenerated": false,
"ratio": 3.1893408134642356,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4127335536464235,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import pandas as pd
# the following functions should be easy:
# a function that just gets all the component collections it requires.
# useful for pandas.
# a function that gets the component collections, filtered by the
# intersection of entity_id. Useful for Python, not useful for pandas.
# a function that gets a single instance of each component it requests.
# useful for Python update functions, not useful for pandas.
# a pure function that gets all component collections it requires, and
# must return new copies of those component collections, including having
# done any add and removal.
# a pure function that gets the component collections, filtered by the
# interaction of entity_ids, and returns collections with updated components,
# plus component_id / entity_ids to remove, plus component / entity_ids to add.
# Useful for Pandas and Python.
# a pure function that *returns* a new single instance of each component it
# requests. This is going to be stored in the collection.
class DictContainer(dict):
"""Component container backed by dict.
This is in fact a Python dict.
"""
def value(self):
"""Get the underlying container object.
"""
return self
class DataFrameContainer:
"""Component container backed by pandas DataFrame.
This can give a performance boost when you have a large
amount of components and you use vectorized functionality to query
and update components.
adds and removes are buffered for efficiency, only once
the container is accessed for its value is the buffer flushed;
typically this happens before the next system runs that requires
this component container.
"""
def __init__(self):
self.df = pd.DataFrame([])
self.to_add_entity_ids = []
self.to_add_components = []
self.to_remove_entity_ids = []
def __setitem__(self, entity_id, component):
self.to_add_entity_ids.append(entity_id)
self.to_add_components.append(component)
def __delitem__(self, entity_id):
self.to_remove.append(entity_id)
def _complete(self):
self._complete_remove()
self._complete_add()
def _complete_add(self):
if not self.to_add_entity_ids:
return
add_df = self._create(self.to_add_components,
self.to_add_entity_ids)
self.df = pd.concat([self.df, add_df])
self.to_add_entity_ids = []
self.to_add_components = []
def _complete_remove(self):
if not self.to_remove_entity_ids:
return
self.df = self.df.drop(self.to_remove_entity_ids)
def _create(self, components, entity_ids):
return pd.DataFrame(components, index=entity_ids)
def __getitem__(self, entity_id):
self._complete()
return self.df.loc[entity_id]
def __contains__(self, entity_id):
# cannot call self._complete here as we do not want
# to trigger it during tracking checks
if entity_id in self.to_remove_entity_ids:
return False
return (entity_id in self.df.index or
entity_id in self.to_add_entity_ids)
def value(self):
"""Backing value is a pandas DataFrame
"""
self._complete()
return self.df
class Registry:
"""Entity component system registry.
"""
def __init__(self):
self.components = {}
self.systems = []
self.component_to_systems = {}
self.entity_id_counter = 0
def register_component(self, component_id, container=None):
"""Register a component container that contains components.
"""
if container is None:
container = DictContainer()
self.components[component_id] = container
self.component_to_systems[component_id] = []
def register_system(self, system):
"""Register a system that processes components.
"""
# XXX add topological sort options so you can design system
# execution order where this matters
self.systems.append(system)
self._update_component_to_systems(system, system.component_ids)
def _update_component_to_systems(self, system, component_ids):
"""Maintain map of component_ids to systems that are interested.
"""
for component_id in component_ids:
self.component_to_systems.setdefault(component_id, []).append(
system)
def has_components(self, entity_id, component_ids):
"""Check whether an entity has the listed component_ids.
"""
for component_id in component_ids:
if entity_id not in self.components[component_id]:
return False
return True
def get(self, entity_id, component_id):
"""Get a specific component for an entity.
KeyError if this component doesn't exist for this entity.
"""
return self.components[component_id][entity_id]
def create_entity_id(self):
"""Create a new entity id.
"""
result = self.entity_id_counter
self.entity_id_counter += 1
return result
def add_entity(self, **components):
"""Add a new entity with a bunch of associated components.
"""
entity_id = self.create_entity_id()
self.add_components(entity_id, **components)
return entity_id
def add_components(self, entity_id, **components):
"""Add a bunch of components for an entity.
"""
for component_id, component in components.items():
self.add_component(entity_id, component_id, component)
def add_component(self, entity_id, component_id, component):
"""Add a component to an entity.
This makes sure all interested systems track this entity.
"""
self.components[component_id][entity_id] = component
for system in self.component_to_systems[component_id]:
if self.has_components(entity_id, system.component_ids):
system.track(entity_id)
def remove_component(self, entity_id, component_id):
"""Remove a component from an entity.
This makes sure interested systems stop tracking this entity.
"""
del self.components[component_id][entity_id]
for system in self.component_to_systems[component_id]:
system.forget(entity_id)
def component_containers(self, component_ids):
"""Get component containers.
"""
return [self.components[component_id]
for component_id in component_ids]
def execute(self, update):
"""Execute all systems.
The update argument is passed through to all systems. It can
contain information about the current state of the game, including
an API to add components.
"""
for system in self.systems:
containers = self.component_containers(system.component_ids)
system.execute(update, self, containers)
class System:
def __init__(self, func, component_ids):
"""
:param func: a function that takes the update and component
container arguments and updates the state accordingly.
:param component_ids: the component ids that this system cares about.
"""
self.func = func
self.component_ids = component_ids
self.entity_ids = set()
def execute(self, update, registry, component_containers):
"""Execute this system.
Passed in are the component containers that this system can
consult and update.
"""
args = ([self.entity_ids] +
[container.value() for container in component_containers])
self.func(update, registry, *args)
def track(self, entity_id):
"""Track entity_id with this system."""
self.entity_ids.add(entity_id)
def forget(self, entity_id):
"""Stop tracking entity_id with this system."""
self.entity_ids.remove(entity_id)
def _entity_ids_func(func, update, r, entity_ids, *containers):
entity_ids_containers = [
[container[entity_id] for entity_id in entity_ids]
for container in containers]
func(update, r, entity_ids, *entity_ids_containers)
def entity_ids_system(func, component_ids):
return System(partial(_entity_ids_func, func), component_ids)
def _item_func(func, update, r, *lists):
for items in zip(*lists):
func(update, r, *items)
def item_system(func, component_ids):
"""A system where you update individual items, not collections of them.
"""
return System(partial(_entity_ids_func, partial(_item_func, func)),
component_ids)
| {
"repo_name": "faassen/secundus",
"path": "secundus/registry.py",
"copies": "1",
"size": "8757",
"license": "bsd-3-clause",
"hash": 3366596166881506300,
"line_mean": 32.9418604651,
"line_max": 79,
"alpha_frac": 0.6399451867,
"autogenerated": false,
"ratio": 4.2717073170731705,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.541165250377317,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import pickle
import argparse
import googlemaps
from multiprocessing import Pool
def get_arguments():
parser = argparse.ArgumentParser(description='')
parser.add_argument('--filtered_photo_metadata', type=str, default="filtered_photo_metadata.pkl")
parser.add_argument('--google_maps_api_key', type=str)
parser.add_argument('--state_output', type=str, default="states.pkl")
return parser.parse_args()
def get_state(gmaps, item):
lat = item['lat']
lng = -item['lon']
try:
reverse_geocode_result = gmaps.reverse_geocode((lat, lng))
except googlemaps.exceptions.Timeout:
return item.key.name, None
for result in reverse_geocode_result:
for address_component in result['address_components']:
if u'administrative_area_level_1' in address_component['types'] :
state = address_component['short_name']
return item.key.name, state
return item.key.name, None
def main():
args = get_arguments()
TIMEOUT=30
RETRY_TIMEOUT=30
gmaps = googlemaps.Client(key=args.google_maps_api_key,
timeout=TIMEOUT,
retry_timeout=RETRY_TIMEOUT)
# Load photo points
r = pickle.load(open(args.filtered_photo_metadata))
f = partial(get_state, gmaps)
p = Pool(5)
results = p.map(f, r)
pickle.dump(dict(results), open(args.state_output, "wb"))
if __name__ == '__main__':
main()
| {
"repo_name": "google/eclipse2017",
"path": "src/export_eclipse_dataset/determine_state.py",
"copies": "1",
"size": "1509",
"license": "apache-2.0",
"hash": 391825703004229400,
"line_mean": 33.2954545455,
"line_max": 101,
"alpha_frac": 0.6348575215,
"autogenerated": false,
"ratio": 3.801007556675063,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49358650781750635,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import pprint
import click
from jarvis_cli import file_helper as fh
from jarvis_cli import client, formatting
from jarvis_cli.client import log_entry as cle
@click.group(name="show")
def do_action_show():
"""Display a Jarvis resource"""
pass
def _get_and_show_resource(conn, get_func, show_file_func, resource_id):
resource = get_func(conn, resource_id)
show_file_func(resource, resource_id)
@do_action_show.command(name="log")
@click.argument('log-entry-id')
@click.option('-e', '--event-id', prompt=True, help="Associated event")
@click.pass_context
def show_log_entry(ctx, log_entry_id, event_id):
"""Display a log entry"""
conn = ctx.obj["connection"]
# TODO: There must be a easier way to get event id.
get_func = partial(cle.get_log_entry, event_id)
_get_and_show_resource(conn, get_func, fh.show_file_log, log_entry_id)
@do_action_show.command(name="tag")
@click.argument('tag-name')
@click.pass_context
def show_tag(ctx, tag_name):
"""Display a tag"""
conn = ctx.obj["connection"]
_get_and_show_resource(conn, client.get_tag, fh.show_file_tag, tag_name)
@do_action_show.command(name="event")
@click.argument('event-id')
@click.pass_context
def show_event(ctx, event_id):
"""Display an event"""
conn = ctx.obj["connection"]
event = client.get_event(conn, event_id)
pprint.pprint(formatting.format_event(event), width=120)
print("\n")
section = input("Show more [description]?: ")
if section == "description":
tmpfile = fh.create_event_description_path(event_id)
with open(tmpfile, 'w') as f:
f.write(event[section])
fh.just_show_file(tmpfile)
| {
"repo_name": "clb6/jarvis-cli",
"path": "jarvis_cli/commands/action_show.py",
"copies": "1",
"size": "1702",
"license": "apache-2.0",
"hash": 3481766801354754000,
"line_mean": 29.9454545455,
"line_max": 76,
"alpha_frac": 0.678613396,
"autogenerated": false,
"ratio": 3.1460258780036967,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9312454590946627,
"avg_score": 0.0024369366114139006,
"num_lines": 55
} |
from functools import partial
import pprint
import click
import jarvis_cli as jc
from jarvis_cli import client, config, formatting
from jarvis_cli import file_helper as fh
from jarvis_cli import interactive as jci
from jarvis_cli.client import log_entry as cle
@click.group(name="edit")
def do_action_edit():
"""Edit an existing Jarvis resource"""
pass
def _edit_resource(conn, get_func, put_func, edit_file_func, show_file_func,
post_edit_func, resource_id):
resource = get_func(conn, resource_id)
if resource:
filepath = edit_file_func(resource, resource_id)
if filepath:
json_object = fh.convert_file_to_json(filepath)
json_object = post_edit_func(json_object)
resource = put_func(conn, resource_id, json_object)
if resource:
show_file_func(resource, resource_id)
print("Editted: {0}".format(resource_id))
@do_action_edit.command(name="log")
@click.argument('log-entry-id')
@click.option('-e', '--event-id', prompt=True, help="Associated event")
@click.pass_context
def edit_log_entry(ctx, log_entry_id, event_id):
"""Edit an existing log entry"""
author = config.get_author(ctx.obj["config_map"])
conn = ctx.obj["connection"]
def post_edit_log(json_object):
# WATCH! This specialty code here because the LogEntry.id
# is a number.
json_object["id"] = int(json_object["id"])
fh.check_and_create_missing_tags(conn, author, json_object)
# Change from log entry to log entry request
json_object.pop('created', None)
json_object.pop('id', None)
json_object.pop('version', None)
return json_object
# TODO: There must be a easier way to get event id.
get_func = partial(cle.get_log_entry, event_id)
put_func = partial(cle.put_log_entry, event_id)
_edit_resource(conn, get_func, put_func, fh.edit_file_log,
fh.show_file_log, post_edit_log, log_entry_id)
@do_action_edit.command(name="tag")
@click.argument('tag-name')
@click.pass_context
def edit_tag(ctx, tag_name):
"""Edit an existing tag"""
author = config.get_author(ctx.obj["config_map"])
conn = ctx.obj["connection"]
def post_edit_tag(json_object):
fh.check_and_create_missing_tags(conn, author, json_object)
# Change from tag to tag request
json_object.pop("created", None)
json_object.pop("version", None)
return json_object
conn = ctx.obj["connection"]
_edit_resource(conn, client.get_tag, client.put_tag, fh.edit_file_tag,
fh.show_file_tag, post_edit_tag, tag_name)
@do_action_edit.command(name="event")
@click.argument('event-id')
@click.pass_context
def edit_event(ctx, event_id):
"""Edit an existing event"""
conn = ctx.obj["connection"]
event = client.get_event(conn, event_id)
occurred = jci.prompt_event_occurred(event["occurred"])
category = jci.prompt_event_category(event["category"])
weight = jci.prompt_event_weight(category, event["weight"])
description = jci.edit_event_description(occurred, event["description"])
artifacts = jci.prompt_event_artifacts(event["artifactLinks"])
# TODO: DRY request creation with action_new.event
request = { "occurred": occurred.isoformat(), "category": category,
"source": jc.EVENT_SOURCE, "weight": weight, "description": description,
"artifacts": artifacts }
pprint.pprint(formatting.format_event_request(request), width=120)
while True:
should_publish = input("Publish update? [Y/N]: ")
if should_publish == "Y":
response = client.put_event(conn, event_id, request)
if response:
print("Updated event: {0}".format(response.get("eventId")))
break
elif should_publish == "N":
print("Canceled event update")
break
| {
"repo_name": "clb6/jarvis-cli",
"path": "jarvis_cli/commands/action_edit.py",
"copies": "1",
"size": "3923",
"license": "apache-2.0",
"hash": 448289813507053060,
"line_mean": 33.4122807018,
"line_max": 84,
"alpha_frac": 0.645679327,
"autogenerated": false,
"ratio": 3.5152329749103943,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46609123019103943,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import pyecore.ecore as Ecore
from pyecore.ecore import *
name = 'library'
nsURI = 'http://emf.wikipedia.org/2011/Library'
nsPrefix = 'lib'
eClass = EPackage(name=name, nsURI=nsURI, nsPrefix=nsPrefix)
eClassifiers = {}
getEClassifier = partial(Ecore.getEClassifier, searchspace=eClassifiers)
BookCategory = EEnum('BookCategory', literals=['ScienceFiction', 'Biographie', 'Mistery']) # noqa
class Employee(EObject, metaclass=MetaEClass):
name = EAttribute(eType=EString)
age = EAttribute(eType=EInt)
def __init__(self, name=None, age=None, **kwargs):
if kwargs:
raise AttributeError('unexpected arguments: {}'.format(kwargs))
super().__init__()
if name is not None:
self.name = name
if age is not None:
self.age = age
class Library(EObject, metaclass=MetaEClass):
name = EAttribute(eType=EString)
address = EAttribute(eType=EString)
employees = EReference(upper=-1, containment=True)
writers = EReference(upper=-1, containment=True)
books = EReference(upper=-1, containment=True)
def __init__(self, name=None, address=None, employees=None, writers=None, books=None, **kwargs):
if kwargs:
raise AttributeError('unexpected arguments: {}'.format(kwargs))
super().__init__()
if name is not None:
self.name = name
if address is not None:
self.address = address
if employees:
self.employees.extend(employees)
if writers:
self.writers.extend(writers)
if books:
self.books.extend(books)
class Writer(EObject, metaclass=MetaEClass):
name = EAttribute(eType=EString)
books = EReference(upper=-1)
def __init__(self, name=None, books=None, **kwargs):
if kwargs:
raise AttributeError('unexpected arguments: {}'.format(kwargs))
super().__init__()
if name is not None:
self.name = name
if books:
self.books.extend(books)
class Book(EObject, metaclass=MetaEClass):
title = EAttribute(eType=EString)
pages = EAttribute(eType=EInt)
category = EAttribute(eType=BookCategory)
authors = EReference(upper=-1)
def __init__(self, title=None, pages=None, category=None, authors=None, **kwargs):
if kwargs:
raise AttributeError('unexpected arguments: {}'.format(kwargs))
super().__init__()
if title is not None:
self.title = title
if pages is not None:
self.pages = pages
if category is not None:
self.category = category
if authors:
self.authors.extend(authors)
| {
"repo_name": "pyecore/pyecore",
"path": "examples/library/library.py",
"copies": "4",
"size": "2728",
"license": "bsd-3-clause",
"hash": -7601238010249333000,
"line_mean": 29.3111111111,
"line_max": 100,
"alpha_frac": 0.6257331378,
"autogenerated": false,
"ratio": 3.8422535211267608,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6467986658926761,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import random
from typing import Iterable, Callable
from mockfirestore._helpers import generate_random_string, Timestamp
from mockfirestore.document import DocumentReference, DocumentSnapshot
from mockfirestore.query import Query
MAX_ATTEMPTS = 5
_MISSING_ID_TEMPLATE = "The transaction has no transaction ID, so it cannot be {}."
_CANT_BEGIN = "The transaction has already begun. Current transaction ID: {!r}."
_CANT_ROLLBACK = _MISSING_ID_TEMPLATE.format("rolled back")
_CANT_COMMIT = _MISSING_ID_TEMPLATE.format("committed")
class WriteResult:
def __init__(self):
self.update_time = Timestamp.from_now()
class Transaction:
"""
This mostly follows the model from
https://googleapis.dev/python/firestore/latest/transaction.html
"""
def __init__(self, client,
max_attempts=MAX_ATTEMPTS, read_only=False):
self._client = client
self._max_attempts = max_attempts
self._read_only = read_only
self._id = None
self._write_ops = []
self.write_results = None
@property
def in_progress(self):
return self._id is not None
@property
def id(self):
return self._id
def _begin(self, retry_id=None):
# generate a random ID to set the transaction as in_progress
self._id = generate_random_string()
def _clean_up(self):
self._write_ops.clear()
self._id = None
def _rollback(self):
if not self.in_progress:
raise ValueError(_CANT_ROLLBACK)
self._clean_up()
def _commit(self) -> Iterable[WriteResult]:
if not self.in_progress:
raise ValueError(_CANT_COMMIT)
results = []
for write_op in self._write_ops:
write_op()
results.append(WriteResult())
self.write_results = results
self._clean_up()
return results
def get_all(self,
references: Iterable[DocumentReference]) -> Iterable[DocumentSnapshot]:
return self._client.get_all(references)
def get(self, ref_or_query) -> Iterable[DocumentSnapshot]:
if isinstance(ref_or_query, DocumentReference):
return self._client.get_all([ref_or_query])
elif isinstance(ref_or_query, Query):
return ref_or_query.stream()
else:
raise ValueError(
'Value for argument "ref_or_query" must be a DocumentReference or a Query.'
)
# methods from
# https://googleapis.dev/python/firestore/latest/batch.html#google.cloud.firestore_v1.batch.WriteBatch
def _add_write_op(self, write_op: Callable):
if self._read_only:
raise ValueError(
"Cannot perform write operation in read-only transaction."
)
self._write_ops.append(write_op)
def create(self, reference: DocumentReference, document_data):
# this is a no-op, because if we have a DocumentReference
# it's already in the MockFirestore
...
def set(self, reference: DocumentReference, document_data: dict,
merge=False):
write_op = partial(reference.set, document_data, merge=merge)
self._add_write_op(write_op)
def update(self, reference: DocumentReference,
field_updates: dict, option=None):
write_op = partial(reference.update, field_updates)
self._add_write_op(write_op)
def delete(self, reference: DocumentReference, option=None):
write_op = reference.delete
self._add_write_op(write_op)
def commit(self):
return self._commit()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
self.commit()
| {
"repo_name": "mdowds/python-mock-firestore",
"path": "mockfirestore/transaction.py",
"copies": "1",
"size": "3794",
"license": "mit",
"hash": -5158213225358560000,
"line_mean": 30.8823529412,
"line_max": 106,
"alpha_frac": 0.6278334212,
"autogenerated": false,
"ratio": 4.010570824524313,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5138404245724313,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import random
import string
class DockerBuildCommand(object):
""" Generates a `docker build` command to run in a subprocess.
"""
def __init__(self, docker_repo, tag, dockerfile='Dockerfile', build_args=None):
self.docker_repo = docker_repo
self.tag = tag
self.dockerfile = dockerfile
self.build_args = build_args or {}
def build(self):
def docker_build_command(process_num):
build_arg_flags = " ".join(
"--build-arg {}='{}'".format(k, v) for k, v in self.build_args.items())
return "docker build -f {0} -t {1}:{2} {3} .".format(
self.dockerfile, self.docker_repo, self.tag, build_arg_flags)
return docker_build_command
def full_image_name(self):
return "{0}:{1}".format(self.docker_repo, self.tag)
class DockerCommand(object):
def __init__(self, docker_command, container_name_prefix):
self.docker_command = docker_command
self.container_name_prefix = container_name_prefix
def build(self, cmd):
def docker_command(process_num):
cmd_string = cmd(process_num) if hasattr(cmd, '__call__') else cmd
return "docker {0} {1}{2} {3}".format(
self.docker_command, self.container_name_prefix, process_num, cmd_string)
return docker_command
class DockerComposeCommand(object):
""" Generates docker or docker-compose commands to run in a subprocess.
"""
def __init__(self, docker_compose_file='docker-compose.yml',
project_name_base=None, env_vars=None):
self.docker_compose_file = docker_compose_file
self.env_vars = env_vars or {}
self.project_name_base = project_name_base or self._random_project_name()
def _random_project_name(self, length=12):
chars = string.ascii_lowercase + string.digits
return 'cirunner' + ''.join(random.choice(chars) for i in range(length))
def _default_env_vars(self, process_num):
return {
'PROJECT_NAME': self._project_name(process_num),
'CI_COMMAND_NUMBER': process_num,
}
def _project_name(self, command_num):
if self.project_name_base is None:
return None
return self.project_name_base + str(command_num)
def _build_cmd(self, app, cmd_string, docker_compose_command, process_num):
""" Builds the docker-compose command running cmd_string
process_num gets appended to the project name which lets you run
in parallel on separate docker-compose clusters of containers.
"""
output = self._env_vars_prefix(process_num)
output += self._compose_with_file_and_project_name(process_num)
output += " {0}".format(docker_compose_command)
if app:
output += " {0}".format(app)
if cmd_string:
output += " {0}".format(cmd_string)
return output
def _cleanup_cmd(self, process_num):
tmp = self._env_vars_prefix(process_num)
tmp += self._compose_with_file_and_project_name(process_num)
return "{0} stop && {0} rm --force".format(tmp)
def _compose_with_file_and_project_name(self, process_num):
output = "docker-compose"
output += " -f {0}".format(self.docker_compose_file)
if self._project_name(process_num):
output += " -p {0}".format(self._project_name(process_num))
return output
def _env_vars_prefix(self, process_num):
output = ""
env_vars = self._default_env_vars(process_num)
env_vars.update(self.env_vars)
if env_vars:
output += ' '.join("{0}={1}".format(k, v) for k, v in env_vars.items())
output += " "
return output
def build(self, app, docker_compose_command, cmd_string=None):
return partial(self._build_cmd, app, cmd_string, docker_compose_command)
def cleanup(self):
return self._cleanup_cmd
| {
"repo_name": "dcosson/parallel-ci-runner",
"path": "parallel_ci_runner/docker_commands.py",
"copies": "1",
"size": "4006",
"license": "mit",
"hash": 4909173378530065000,
"line_mean": 37.5192307692,
"line_max": 89,
"alpha_frac": 0.6095856216,
"autogenerated": false,
"ratio": 3.7265116279069765,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9832098655696391,
"avg_score": 0.0007997187621171362,
"num_lines": 104
} |
from functools import partial
import random
from adder.utils import InvalidArgumentError
class Node:
def __init__(self, state, parent, action, path_cost):
self.__state = state
self.__parent = parent
self.__action = action
self.__path_cost = path_cost
def __eq__(self, other):
return self.state == other.state
def __ne__(self, other):
return not self == other
def __hash__(self):
return hash(self.state)
def __str__(self):
parent_name = self.parent.state if self.parent else "None"
return self.state
return "(State: {0}, Parent: {1}, Action: {2})"\
.format(self.state, parent_name, self.action)
def __repr__(self):
return str(self)
@property
def state(self):
return self.__state
@property
def parent(self):
return self.__parent
@property
def action(self):
return self.__action
@property
def path_cost(self):
return self.__path_cost
FAILURE = "FAILURE"
SOLUTION_UNKNOWN = "SOLUTION_UNKNOWN"
class Problem:
def child_node(self, node, action):
parent = node
state = self.result(node.state, action)
action = action
path_cost = node.path_cost + self.step_cost(node.state, action)
child = Node(state, parent, action, path_cost)
return child
def actions_iter(self, state):
raise NotImplementedError("_Problem is abc")
def step_cost(state, action):
raise NotImplementedError("_Problem is abc")
def result(self, state, action):
raise NotImplementedError("_Problem is abc")
def goal_test(self, state):
raise NotImplementedError("_Problem is abc")
def construct_solution(self, end_node):
path = []
while end_node != self.initial:
parent = end_node.parent
path.append((end_node.state, end_node.action))
end_node = parent
path.append((self.initial.state, None))
path.reverse()
return path
def solution_cost(self, solution):
if solution is FAILURE or solution is SOLUTION_UNKNOWN:
return 0
cost = 0
previous_state = None
for state, action in solution:
if previous_state:
cost += self.step_cost(previous_state, action)
previous_state = state
return cost
class _GraphProblem(Problem):
def __init__(self, graph, root, goal):
if root not in graph.get_nodes():
raise InvalidArgumentError("root must be be a node in the graph")
if goal not in graph.get_nodes():
raise InvalidArgumentError("goal must be be a node in the graph")
self.graph = graph
self.initial = Node(root, None, None, 0)
self.goal = goal
def actions_iter(self, state):
return self.graph.children_iter(state)
def step_cost(self, state, action):
return self.graph.edge_cost(state, action)
def result(self, state, action):
return action if action in self.graph.children_iter(state) else None
def goal_test(self, state):
return state == self.goal
class _NPuzzleProblem(Problem):
UP = "UP"
DOWN = "DOWN"
LEFT = "LEFT"
RIGHT = "RIGHT"
def __init__(self, initial, goal):
initial = tuple(initial.split())
goal = tuple(goal.split())
self.board_size = len(initial) ** 0.5
if not self.board_size.is_integer():
msg = "The size of the board must be a exact square!"
raise InvalidArgumentError(msg)
self.board_size = int(self.board_size)
self.initial = Node(initial, None, None, 0)
self.goal = goal
def _swap_letters(self, state, first, second):
next = list(state)
next[first], next[second] = next[second], next[first]
return tuple(next)
def coords_of(self, state, number):
number = str(number)
index = state.index(number)
# index = i * size + j
j = index % self.board_size
i = (index - j) / self.board_size
return (i, int(j))
def actions_iter(self, state):
i, j = self.coords_of(state, 0)
index = int(i * self.board_size + j)
neighbours = []
if i < self.board_size - 1:
neighbours.append(_NPuzzleProblem.UP)
if i > 0:
neighbours.append(_NPuzzleProblem.DOWN)
if j < self.board_size - 1:
neighbours.append(_NPuzzleProblem.RIGHT)
if j > 0:
neighbours.append(_NPuzzleProblem.LEFT)
return iter(neighbours)
def step_cost(self, state, action):
return 1
def result(self, state, action):
index = state.index("0")
if action == _NPuzzleProblem.UP:
return self._swap_letters(state, index, index + self.board_size)
if action == _NPuzzleProblem.DOWN:
return self._swap_letters(state, index, index - self.board_size)
if action == _NPuzzleProblem.RIGHT:
return self._swap_letters(state, index, index + 1)
if action == _NPuzzleProblem.LEFT:
return self._swap_letters(state, index, index - 1)
def goal_test(self, state):
return state == self.goal
class _NQueensProblem(Problem):
def __init__(self, size, initial=None):
self.size = size
initial = initial
if not initial:
initial = _NQueensProblem.generate_random_state(size)
self.initial = Node(initial, None, None, 0)
def generate_random_state(size):
return tuple(random.randint(0, size) for i in range(size))
def attacking(state):
size = len(state)
attacking = 0
for col, row in enumerate(state):
for other_col in range(col + 1, size):
# Row
if row == state[other_col]:
attacking += 1
# Diag 1
if row == state[other_col] + (col - other_col):
attacking += 1
# Diag 2
if row == state[other_col] - (col - other_col):
attacking += 1
return attacking
def actions_iter(self, state):
for col in range(self.size):
for row in range(self.size):
if row == state[col]:
continue
yield (col, row)
def step_cost(self, state, action):
return 1
def result(self, state, action):
col_index, row_index = action
next_state = list(state)
next_state[col_index] = row_index
return tuple(next_state)
def goal_test(self, state):
return _NQueensProblem.attacking(state) == 0
class ProblemFactory:
def from_graph(self, graph, root, goal):
return _GraphProblem(graph, root, goal)
def from_functions(self, initial_state, actions,
step_cost, result, goal_test):
problem = Problem()
problem.initial = Node(initial_state, None, None, 0)
problem.actions_iter = actions
problem.step_cost = step_cost
problem.result = result
problem.goal_test = goal_test
return problem
def from_npuzzle(self, initial, goal):
return _NPuzzleProblem(initial, goal)
def from_nqueens(self, size, initial=None):
return _NQueensProblem(size, initial)
def _manhattan_heuristic(problem_instance, state):
scoords = [problem_instance.coords_of(state, num) for num in state]
gcoords = [problem_instance.coords_of(state, num)
for num in problem_instance.goal]
diff = [abs(scoords[i][0] - gcoords[i][0]) +
abs(scoords[i][1] - gcoords[i][1])
for i in range(0, len(state) - 1)]
return sum(diff)
def heuristic_for(self, problem):
if isinstance(problem, _NPuzzleProblem):
return partial(ProblemFactory._manhattan_heuristic, problem)
elif isinstance(problem, _NQueensProblem):
return _NQueensProblem.attacking
else:
raise TypeError("No heuristic exists for this type of problem")
| {
"repo_name": "NikolaDimitroff/Adder",
"path": "adder/problem.py",
"copies": "1",
"size": "8207",
"license": "mit",
"hash": -2043770520185591000,
"line_mean": 28.6281588448,
"line_max": 77,
"alpha_frac": 0.5793834531,
"autogenerated": false,
"ratio": 3.923040152963671,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5002423606063671,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import random
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, \
Type, TypeVar, Union
from unittest import loader, runner
from unittest.result import TestResult
from django.conf import settings
from django.db import connections, ProgrammingError
from django.urls.resolvers import RegexURLPattern
from django.test import TestCase
from django.test import runner as django_runner
from django.test.runner import DiscoverRunner
from django.test.signals import template_rendered
from zerver.lib import test_helpers
from zerver.lib.cache import bounce_key_prefix_for_testing
from zerver.lib.rate_limiter import bounce_redis_key_prefix_for_testing
from zerver.lib.sqlalchemy_utils import get_sqlalchemy_connection
from zerver.lib.test_helpers import (
write_instrumentation_reports,
append_instrumentation_data
)
import os
import time
import unittest
import shutil
from multiprocessing.sharedctypes import Synchronized
from scripts.lib.zulip_tools import get_dev_uuid_var_path, TEMPLATE_DATABASE_DIR, \
get_or_create_dev_uuid_var_path
# We need to pick an ID for this test-backend invocation, and store it
# in this global so it can be used in init_worker; this is used to
# ensure the database IDs we select are unique for each `test-backend`
# run. This probably should use a locking mechanism rather than the
# below hack, which fails 1/10000000 of the time.
random_id_range_start = random.randint(1, 10000000) * 100
# The root directory for this run of the test suite.
TEST_RUN_DIR = get_or_create_dev_uuid_var_path(
os.path.join('test-backend', 'run_{}'.format(random_id_range_start)))
_worker_id = 0 # Used to identify the worker process.
ReturnT = TypeVar('ReturnT') # Constrain return type to match
def slow(slowness_reason: str) -> Callable[[Callable[..., ReturnT]], Callable[..., ReturnT]]:
'''
This is a decorate that annotates a test as being "known
to be slow." The decorator will set expected_run_time and slowness_reason
as attributes of the function. Other code can use this annotation
as needed, e.g. to exclude these tests in "fast" mode.
'''
def decorator(f: Callable[..., ReturnT]) -> Callable[..., ReturnT]:
setattr(f, 'slowness_reason', slowness_reason)
return f
return decorator
def is_known_slow_test(test_method: Callable[..., ReturnT]) -> bool:
return hasattr(test_method, 'slowness_reason')
def full_test_name(test: TestCase) -> str:
test_module = test.__module__
test_class = test.__class__.__name__
test_method = test._testMethodName
return '%s.%s.%s' % (test_module, test_class, test_method)
def get_test_method(test: TestCase) -> Callable[[], None]:
return getattr(test, test._testMethodName)
# Each tuple is delay, test_name, slowness_reason
TEST_TIMINGS = [] # type: List[Tuple[float, str, str]]
def report_slow_tests() -> None:
timings = sorted(TEST_TIMINGS, reverse=True)
print('SLOWNESS REPORT')
print(' delay test')
print(' ---- ----')
for delay, test_name, slowness_reason in timings[:15]:
if not slowness_reason:
slowness_reason = 'UNKNOWN WHY SLOW, please investigate'
print(' %0.3f %s\n %s\n' % (delay, test_name, slowness_reason))
print('...')
for delay, test_name, slowness_reason in timings[100:]:
if slowness_reason:
print(' %.3f %s is not that slow' % (delay, test_name))
print(' consider removing @slow decorator')
print(' This may no longer be true: %s' % (slowness_reason,))
def enforce_timely_test_completion(test_method: Callable[..., ReturnT], test_name: str,
delay: float, result: unittest.TestResult) -> None:
if hasattr(test_method, 'slowness_reason'):
max_delay = 2.0 # seconds
else:
max_delay = 0.4 # seconds
assert isinstance(result, TextTestResult) or isinstance(result, RemoteTestResult)
if delay > max_delay:
msg = '** Test is TOO slow: %s (%.3f s)\n' % (test_name, delay)
result.addInfo(test_method, msg)
def fast_tests_only() -> bool:
return "FAST_TESTS_ONLY" in os.environ
def run_test(test: TestCase, result: TestResult) -> bool:
failed = False
test_method = get_test_method(test)
if fast_tests_only() and is_known_slow_test(test_method):
return failed
test_name = full_test_name(test)
bounce_key_prefix_for_testing(test_name)
bounce_redis_key_prefix_for_testing(test_name)
if not hasattr(test, "_pre_setup"):
msg = "Test doesn't have _pre_setup; something is wrong."
error_pre_setup = (Exception, Exception(msg), None)
result.addError(test, error_pre_setup)
return True
test._pre_setup()
start_time = time.time()
test(result) # unittest will handle skipping, error, failure and success.
delay = time.time() - start_time
enforce_timely_test_completion(test_method, test_name, delay, result)
slowness_reason = getattr(test_method, 'slowness_reason', '')
TEST_TIMINGS.append((delay, test_name, slowness_reason))
test._post_teardown()
return failed
class TextTestResult(runner.TextTestResult):
"""
This class has unpythonic function names because base class follows
this style.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.failed_tests = [] # type: List[str]
def addInfo(self, test: TestCase, msg: str) -> None:
self.stream.write(msg) # type: ignore # https://github.com/python/typeshed/issues/3139
self.stream.flush() # type: ignore # https://github.com/python/typeshed/issues/3139
def addInstrumentation(self, test: TestCase, data: Dict[str, Any]) -> None:
append_instrumentation_data(data)
def startTest(self, test: TestCase) -> None:
TestResult.startTest(self, test)
self.stream.writeln("Running {}".format(full_test_name(test))) # type: ignore # https://github.com/python/typeshed/issues/3139
self.stream.flush() # type: ignore # https://github.com/python/typeshed/issues/3139
def addSuccess(self, *args: Any, **kwargs: Any) -> None:
TestResult.addSuccess(self, *args, **kwargs)
def addError(self, *args: Any, **kwargs: Any) -> None:
TestResult.addError(self, *args, **kwargs)
test_name = full_test_name(args[0])
self.failed_tests.append(test_name)
def addFailure(self, *args: Any, **kwargs: Any) -> None:
TestResult.addFailure(self, *args, **kwargs)
test_name = full_test_name(args[0])
self.failed_tests.append(test_name)
def addSkip(self, test: TestCase, reason: str) -> None:
TestResult.addSkip(self, test, reason)
self.stream.writeln("** Skipping {}: {}".format( # type: ignore # https://github.com/python/typeshed/issues/3139
full_test_name(test),
reason))
self.stream.flush() # type: ignore # https://github.com/python/typeshed/issues/3139
class RemoteTestResult(django_runner.RemoteTestResult):
"""
The class follows the unpythonic style of function names of the
base class.
"""
def addInfo(self, test: TestCase, msg: str) -> None:
self.events.append(('addInfo', self.test_index, msg))
def addInstrumentation(self, test: TestCase, data: Dict[str, Any]) -> None:
# Some elements of data['info'] cannot be serialized.
if 'info' in data:
del data['info']
self.events.append(('addInstrumentation', self.test_index, data))
def process_instrumented_calls(func: Callable[[Dict[str, Any]], None]) -> None:
for call in test_helpers.INSTRUMENTED_CALLS:
func(call)
SerializedSubsuite = Tuple[Type['TestSuite'], List[str]]
SubsuiteArgs = Tuple[Type['RemoteTestRunner'], int, SerializedSubsuite, bool]
def run_subsuite(args: SubsuiteArgs) -> Tuple[int, Any]:
# Reset the accumulated INSTRUMENTED_CALLS before running this subsuite.
test_helpers.INSTRUMENTED_CALLS = []
# The first argument is the test runner class but we don't need it
# because we run our own version of the runner class.
_, subsuite_index, subsuite, failfast = args
runner = RemoteTestRunner(failfast=failfast)
result = runner.run(deserialize_suite(subsuite))
# Now we send instrumentation related events. This data will be
# appended to the data structure in the main thread. For Mypy,
# type of Partial is different from Callable. All the methods of
# TestResult are passed TestCase as the first argument but
# addInstrumentation does not need it.
process_instrumented_calls(partial(result.addInstrumentation, None))
return subsuite_index, result.events
# Monkey-patch database creation to fix unnecessary sleep(1)
from django.db.backends.postgresql.creation import DatabaseCreation
def _replacement_destroy_test_db(self: DatabaseCreation,
test_database_name: str,
verbosity: int) -> None:
"""Replacement for Django's _destroy_test_db that removes the
unnecessary sleep(1)."""
with self.connection._nodb_connection.cursor() as cursor:
cursor.execute("DROP DATABASE %s"
% (self.connection.ops.quote_name(test_database_name),))
DatabaseCreation._destroy_test_db = _replacement_destroy_test_db
def destroy_test_databases(worker_id: Optional[int]=None) -> None:
for alias in connections:
connection = connections[alias]
try:
# In the parallel mode, the test databases are created
# through the N=self.parallel child processes, and in the
# parent process (which calls `destroy_test_databases`),
# `settings_dict` remains unchanged, with the original
# template database name (zulip_test_template). So to
# delete the database zulip_test_template_<number>, we
# need to pass `number` to `destroy_test_db`.
#
# When we run in serial mode (self.parallel=1), we don't
# fork and thus both creation and destruction occur in the
# same process, which means `settings_dict` has been
# updated to have `zulip_test_template_<number>` as its
# database name by the creation code. As a result, to
# delete that database, we need to not pass a number
# argument to destroy_test_db.
if worker_id is not None:
"""Modified from the Django original to """
database_id = random_id_range_start + worker_id
connection.creation.destroy_test_db(number=database_id)
else:
connection.creation.destroy_test_db()
except ProgrammingError:
# DB doesn't exist. No need to do anything.
pass
def create_test_databases(worker_id: int) -> None:
database_id = random_id_range_start + worker_id
for alias in connections:
connection = connections[alias]
connection.creation.clone_test_db(
number=database_id,
keepdb=True,
)
settings_dict = connection.creation.get_test_db_clone_settings(database_id)
# connection.settings_dict must be updated in place for changes to be
# reflected in django.db.connections. If the following line assigned
# connection.settings_dict = settings_dict, new threads would connect
# to the default database instead of the appropriate clone.
connection.settings_dict.update(settings_dict)
connection.close()
def init_worker(counter: Synchronized) -> None:
"""
This function runs only under parallel mode. It initializes the
individual processes which are also called workers.
"""
global _worker_id
with counter.get_lock():
counter.value += 1
_worker_id = counter.value
"""
You can now use _worker_id.
"""
# Clear the cache
from zerver.lib.cache import get_cache_backend
cache = get_cache_backend(None)
cache.clear()
# Close all connections
connections.close_all()
destroy_test_databases(_worker_id)
create_test_databases(_worker_id)
initialize_worker_path(_worker_id)
def is_upload_avatar_url(url: RegexURLPattern) -> bool:
if url.regex.pattern == r'^user_avatars/(?P<path>.*)$':
return True
return False
# We manually update the upload directory path in the url regex.
from zproject import dev_urls
found = False
for url in dev_urls.urls:
if is_upload_avatar_url(url):
found = True
new_root = os.path.join(settings.LOCAL_UPLOADS_DIR, "avatars")
url.default_args['document_root'] = new_root
if not found:
print("*** Upload directory not found.")
class TestSuite(unittest.TestSuite):
def run(self, result: TestResult, debug: Optional[bool]=False) -> TestResult:
"""
This function mostly contains the code from
unittest.TestSuite.run. The need to override this function
occurred because we use run_test to run the testcase.
"""
topLevel = False
if getattr(result, '_testRunEntered', False) is False:
result._testRunEntered = topLevel = True # type: ignore
for test in self:
# but this is correct. Taken from unittest.
if result.shouldStop:
break
if isinstance(test, TestSuite):
test.run(result, debug=debug)
else:
self._tearDownPreviousClass(test, result) # type: ignore
self._handleModuleFixture(test, result) # type: ignore
self._handleClassSetUp(test, result) # type: ignore
result._previousTestClass = test.__class__ # type: ignore
if (getattr(test.__class__, '_classSetupFailed', False) or
getattr(result, '_moduleSetUpFailed', False)):
continue
failed = run_test(test, result)
if failed or result.shouldStop:
result.shouldStop = True
break
if topLevel:
self._tearDownPreviousClass(None, result) # type: ignore
self._handleModuleTearDown(result) # type: ignore
result._testRunEntered = False # type: ignore
return result
class TestLoader(loader.TestLoader):
suiteClass = TestSuite
class ParallelTestSuite(django_runner.ParallelTestSuite):
run_subsuite = run_subsuite
init_worker = init_worker
def __init__(self, suite: TestSuite, processes: int, failfast: bool) -> None:
super().__init__(suite, processes, failfast)
# We can't specify a consistent type for self.subsuites, since
# the whole idea here is to monkey-patch that so we can use
# most of django_runner.ParallelTestSuite with our own suite
# definitions.
self.subsuites = SubSuiteList(self.subsuites) # type: ignore # Type of self.subsuites changes.
def check_import_error(test_name: str) -> None:
try:
# Directly using __import__ is not recommeded, but here it gives
# clearer traceback as compared to importlib.import_module.
__import__(test_name)
except ImportError as exc:
raise exc from exc # Disable exception chaining in Python 3.
def initialize_worker_path(worker_id: int) -> None:
# Allow each test worker process to write to a unique directory
# within `TEST_RUN_DIR`.
worker_path = os.path.join(TEST_RUN_DIR, 'worker_{}'.format(_worker_id))
os.makedirs(worker_path, exist_ok=True)
settings.TEST_WORKER_DIR = worker_path
# Every process should upload to a separate directory so that
# race conditions can be avoided.
settings.LOCAL_UPLOADS_DIR = get_or_create_dev_uuid_var_path(
os.path.join("test-backend",
os.path.basename(TEST_RUN_DIR),
os.path.basename(worker_path),
"test_uploads"))
class Runner(DiscoverRunner):
test_suite = TestSuite
test_loader = TestLoader()
parallel_test_suite = ParallelTestSuite
def __init__(self, *args: Any, **kwargs: Any) -> None:
DiscoverRunner.__init__(self, *args, **kwargs)
# `templates_rendered` holds templates which were rendered
# in proper logical tests.
self.templates_rendered = set() # type: Set[str]
# `shallow_tested_templates` holds templates which were rendered
# in `zerver.tests.test_templates`.
self.shallow_tested_templates = set() # type: Set[str]
template_rendered.connect(self.on_template_rendered)
def get_resultclass(self) -> Type[TestResult]:
return TextTestResult
def on_template_rendered(self, sender: Any, context: Dict[str, Any], **kwargs: Any) -> None:
if hasattr(sender, 'template'):
template_name = sender.template.name
if template_name not in self.templates_rendered:
if context.get('shallow_tested') and template_name not in self.templates_rendered:
self.shallow_tested_templates.add(template_name)
else:
self.templates_rendered.add(template_name)
self.shallow_tested_templates.discard(template_name)
def get_shallow_tested_templates(self) -> Set[str]:
return self.shallow_tested_templates
def setup_test_environment(self, *args: Any, **kwargs: Any) -> Any:
settings.DATABASES['default']['NAME'] = settings.BACKEND_DATABASE_TEMPLATE
# We create/destroy the test databases in run_tests to avoid
# duplicate work when running in parallel mode.
# Write the template database ids to a file that we can
# reference for cleaning them up if they leak.
filepath = os.path.join(get_dev_uuid_var_path(),
TEMPLATE_DATABASE_DIR,
str(random_id_range_start))
os.makedirs(os.path.dirname(filepath), exist_ok=True)
with open(filepath, "w") as f:
if self.parallel > 1:
for index in range(self.parallel):
f.write(str(random_id_range_start + (index + 1)) + "\n")
else:
f.write(str(random_id_range_start) + "\n")
# Check if we are in serial mode to avoid unnecessarily making a directory.
# We add "worker_0" in the path for consistency with parallel mode.
if self.parallel == 1:
initialize_worker_path(0)
return super().setup_test_environment(*args, **kwargs)
def teardown_test_environment(self, *args: Any, **kwargs: Any) -> Any:
# The test environment setup clones the zulip_test_template
# database, creating databases with names:
# 'zulip_test_template_<N, N + self.parallel - 1>',
# where N is random_id_range_start.
#
# We need to delete those databases to avoid leaking disk
# (Django is smart and calls this on SIGINT too).
if self.parallel > 1:
for index in range(self.parallel):
destroy_test_databases(index + 1)
else:
destroy_test_databases()
# Clean up our record of which databases this process created.
filepath = os.path.join(get_dev_uuid_var_path(),
TEMPLATE_DATABASE_DIR,
str(random_id_range_start))
os.remove(filepath)
# Clean up our test runs root directory.
try:
shutil.rmtree(TEST_RUN_DIR)
except OSError:
print("Unable to clean up the test run's directory.")
pass
return super().teardown_test_environment(*args, **kwargs)
def test_imports(self, test_labels: List[str], suite: Union[TestSuite, ParallelTestSuite]) -> None:
prefix_old = 'unittest.loader.ModuleImportFailure.' # Python <= 3.4
prefix_new = 'unittest.loader._FailedTest.' # Python > 3.4
error_prefixes = [prefix_old, prefix_new]
for test_name in get_test_names(suite):
for prefix in error_prefixes:
if test_name.startswith(prefix):
test_name = test_name[len(prefix):]
for label in test_labels:
# This code block is for Python 3.5 when test label is
# directly provided, for example:
# ./tools/test-backend zerver.tests.test_alert_words.py
#
# In this case, the test name is of this form:
# 'unittest.loader._FailedTest.test_alert_words'
#
# Whereas check_import_error requires test names of
# this form:
# 'unittest.loader._FailedTest.zerver.tests.test_alert_words'.
if test_name in label:
test_name = label
break
check_import_error(test_name)
def run_tests(self, test_labels: List[str],
extra_tests: Optional[List[TestCase]]=None,
full_suite: bool=False,
include_webhooks: bool=False,
**kwargs: Any) -> Tuple[bool, List[str]]:
self.setup_test_environment()
try:
suite = self.build_suite(test_labels, extra_tests)
except AttributeError:
# We are likely to get here only when running tests in serial
# mode on Python 3.4 or lower.
# test_labels are always normalized to include the correct prefix.
# If we run the command with ./tools/test-backend test_alert_words,
# test_labels will be equal to ['zerver.tests.test_alert_words'].
for test_label in test_labels:
check_import_error(test_label)
# I think we won't reach this line under normal circumstances, but
# for some unforeseen scenario in which the AttributeError was not
# caused by an import error, let's re-raise the exception for
# debugging purposes.
raise
self.test_imports(test_labels, suite)
if self.parallel == 1:
# We are running in serial mode so create the databases here.
# For parallel mode, the databases are created in init_worker.
# We don't want to create and destroy DB in setup_test_environment
# because it will be called for both serial and parallel modes.
# However, at this point we know in which mode we would be running
# since that decision has already been made in build_suite().
#
# We pass a _worker_id, which in this code path is always 0
destroy_test_databases(_worker_id)
create_test_databases(_worker_id)
# We have to do the next line to avoid flaky scenarios where we
# run a single test and getting an SA connection causes data from
# a Django connection to be rolled back mid-test.
get_sqlalchemy_connection()
result = self.run_suite(suite)
self.teardown_test_environment()
failed = self.suite_result(suite, result)
if not failed:
write_instrumentation_reports(full_suite=full_suite, include_webhooks=include_webhooks)
return failed, result.failed_tests
def get_test_names(suite: Union[TestSuite, ParallelTestSuite]) -> List[str]:
if isinstance(suite, ParallelTestSuite):
# suite is ParallelTestSuite. It will have a subsuites parameter of
# type SubSuiteList. Each element of a SubsuiteList is a tuple whose
# first element is the type of TestSuite and the second element is a
# list of test names in that test suite. See serialize_suite() for the
# implementation details.
return [name for subsuite in suite.subsuites for name in subsuite[1]]
else:
return [full_test_name(t) for t in get_tests_from_suite(suite)]
def get_tests_from_suite(suite: unittest.TestSuite) -> TestCase:
for test in suite:
if isinstance(test, TestSuite):
for child in get_tests_from_suite(test):
yield child
else:
yield test
def serialize_suite(suite: TestSuite) -> Tuple[Type[TestSuite], List[str]]:
return type(suite), get_test_names(suite)
def deserialize_suite(args: Tuple[Type[TestSuite], List[str]]) -> TestSuite:
suite_class, test_names = args
suite = suite_class()
tests = TestLoader().loadTestsFromNames(test_names)
for test in get_tests_from_suite(tests):
suite.addTest(test)
return suite
class RemoteTestRunner(django_runner.RemoteTestRunner):
resultclass = RemoteTestResult
class SubSuiteList(List[Tuple[Type[TestSuite], List[str]]]):
"""
This class allows us to avoid changing the main logic of
ParallelTestSuite and still make it serializable.
"""
def __init__(self, suites: List[TestSuite]) -> None:
serialized_suites = [serialize_suite(s) for s in suites]
super().__init__(serialized_suites)
def __getitem__(self, index: Any) -> Any:
suite = super().__getitem__(index)
return deserialize_suite(suite)
| {
"repo_name": "rht/zulip",
"path": "zerver/lib/test_runner.py",
"copies": "1",
"size": "25531",
"license": "apache-2.0",
"hash": 7287917159464103000,
"line_mean": 41.4808652246,
"line_max": 135,
"alpha_frac": 0.6348360816,
"autogenerated": false,
"ratio": 4.0551143583227445,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5189950439922745,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import random
import django
import jsonfield
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import UserManager
from django.contrib.sites.models import Site
from django.db import models, connection
from django.db.models.fields.related import create_many_related_manager, ManyToManyRel
from django.utils.translation import ugettext_lazy as _
from .compat import AUTH_USER_MODEL
from south.modelsinspector import add_introspection_rules
def sid_creator(prefix):
try:
sid_creator.limit
except AttributeError:
sid_creator.limit = 16**SIDField.SID_LENGTH
# http://stackoverflow.com/a/2782859/440060
return prefix + '_' + ('%0{}x'.format(SIDField.SID_LENGTH) % random.randrange(sid_creator.limit))
class SIDField(models.CharField):
SID_LENGTH = 16
def __init__(self, *args, **kwargs):
kwargs['max_length'] = SIDField.SID_LENGTH + 4
kwargs['unique'] = True
kwargs['db_index'] = True
kwargs['editable'] = False
kwargs['primary_key'] = True
if 'prefix' in kwargs:
self.prefix = kwargs.pop('prefix')
super(SIDField, self).__init__(*args, **kwargs)
def contribute_to_class(self, cls, name, virtual_only=False):
if not hasattr(self, 'prefix'):
self.prefix = cls.__name__[0].upper()
self.default = partial(sid_creator, self.prefix)
super(SIDField, self).contribute_to_class(cls, name, virtual_only=virtual_only)
rules = [
(
(SIDField,),
[],
{
"db_index": [True, {"is_value": True}],
"max_length": [SIDField.SID_LENGTH + 4, {"is_value": True}],
"unique": [True, {"is_value": True}],
"primary_key": [True, {"is_value": True}]
},
)
]
add_introspection_rules(rules, ["^relationships\.models\.SIDField"])
class RelationshipStatusManager(models.Manager):
# convenience methods to handle some default statuses
def following(self):
return self.get(from_slug='following')
def blocking(self):
return self.get(from_slug='blocking')
def by_slug(self, status_slug):
return self.get(
models.Q(from_slug=status_slug) |
models.Q(to_slug=status_slug) |
models.Q(symmetrical_slug=status_slug)
)
class RelationshipStatus(models.Model):
id = SIDField(prefix='RS')
name = models.CharField(_('name'), max_length=100)
verb = models.CharField(_('verb'), max_length=100, unique=True)
from_slug = models.CharField(_('from slug'), max_length=100,
help_text=_("Denote the relationship from the user, i.e. 'following'"),
unique=True)
to_slug = models.CharField(_('to slug'), max_length=100,
help_text=_("Denote the relationship to the user, i.e. 'followers'"),
unique=True)
symmetrical_slug = models.CharField(_('symmetrical slug'), max_length=100,
help_text=_("When a mutual relationship exists, i.e. 'friends'"),
unique=True)
login_required = models.BooleanField(_('login required'), default=False,
help_text=_("Users must be logged in to see these relationships"))
private = models.BooleanField(_('private'), default=False,
help_text=_("Only the user who owns these relationships can see them"))
objects = RelationshipStatusManager()
class Meta:
ordering = ('name',)
verbose_name = _('Relationship status')
verbose_name_plural = _('Relationship statuses')
def __unicode__(self):
return self.name
class Relationship(models.Model):
id = SIDField()
from_user = models.ForeignKey(AUTH_USER_MODEL,
related_name='from_relationships', verbose_name=_('from user'))
to_user = models.ForeignKey(AUTH_USER_MODEL,
related_name='to_relationships', verbose_name=_('to user'),
null=True, blank=True)
status = models.ForeignKey(RelationshipStatus, verbose_name=_('status'))
created = models.DateTimeField(_('created'), auto_now_add=True)
weight = models.FloatField(_('weight'), default=1.0, blank=True, null=True)
site = models.ForeignKey(Site, default=settings.SITE_ID,
verbose_name=_('site'), related_name='relationships')
extra_data = jsonfield.JSONField(_('extra data'), default=None, blank=True,
null=True, serialize=False)
class Meta:
unique_together = (('from_user', 'to_user', 'status', 'site'),)
ordering = ('created',)
verbose_name = _('Relationship')
verbose_name_plural = _('Relationships')
def __unicode__(self):
return (_('Relationship from %(from_user)s to %(to_user)s')
% {'from_user': self.from_user.username,
'to_user': self.to_user.username if self.to_user else 'None'})
@staticmethod
def get_owner_fields():
return ('to_user', 'from_user')
def is_owner(self, user):
return user.pk in (self.to_user_id, self.from_user_id)
field = models.ManyToManyField(AUTH_USER_MODEL, through=Relationship,
symmetrical=False, related_name='related_to')
class RelationshipManager(UserManager.__class__):
def __init__(self, instance=None, *args, **kwargs):
super(RelationshipManager, self).__init__(*args, **kwargs)
self.instance = instance
def add(self, user, status=None, symmetrical=False, extra_data=None):
"""
Add a relationship from one user to another with the given status,
which defaults to "following".
Adding a relationship is by default asymmetrical (akin to following
someone on twitter). Specify a symmetrical relationship (akin to being
friends on facebook) by passing in :param:`symmetrical` = True
.. note::
If :param:`symmetrical` is set, the function will return a tuple
containing the two relationship objects created
"""
if not status:
status = RelationshipStatus.objects.following()
try:
relationship = Relationship.objects.get(
from_user=self.instance,
to_user=user,
status=status,
site=Site.objects.get_current(),
)
except Relationship.DoesNotExist:
relationship = Relationship.objects.create(
from_user=self.instance,
to_user=user,
status=status,
site=Site.objects.get_current(),
extra_data=extra_data
)
if symmetrical:
return (relationship, user.relationships.add(self.instance, status, False, extra_data))
else:
return relationship
def remove(self, user, status=None, symmetrical=False):
"""
Remove a relationship from one user to another, with the same caveats
and behavior as adding a relationship.
"""
if not status:
status = RelationshipStatus.objects.following()
res = Relationship.objects.filter(
from_user=self.instance,
to_user=user,
status=status,
site__pk=settings.SITE_ID
).delete()
if symmetrical:
return (res, user.relationships.remove(self.instance, status, False))
else:
return res
def _get_from_query(self, status):
return dict(
to_relationships__from_user=self.instance,
to_relationships__status=status,
to_relationships__site__pk=settings.SITE_ID,
)
def _get_to_query(self, status):
return dict(
from_relationships__to_user=self.instance,
from_relationships__status=status,
from_relationships__site__pk=settings.SITE_ID
)
def get_relationships(self, status, symmetrical=False):
"""
Returns a QuerySet of user objects with which the given user has
established a relationship.
"""
query = self._get_from_query(status)
if symmetrical:
query.update(self._get_to_query(status))
return get_user_model().objects.filter(**query)
def get_related_to(self, status):
"""
Returns a QuerySet of user objects which have created a relationship to
the given user.
"""
return get_user_model().objects.filter(**self._get_to_query(status))
def only_to(self, status):
"""
Returns a QuerySet of user objects who have created a relationship to
the given user, but which the given user has not reciprocated
"""
from_relationships = self.get_relationships(status)
to_relationships = self.get_related_to(status)
return to_relationships.exclude(pk__in=from_relationships.values_list('pk'))
def only_from(self, status):
"""
Like :method:`only_to`, returns user objects with whom the given user
has created a relationship, but which have not reciprocated
"""
from_relationships = self.get_relationships(status)
to_relationships = self.get_related_to(status)
return from_relationships.exclude(pk__in=to_relationships.values_list('pk'))
def exists(self, user, status=None, symmetrical=False):
"""
Returns boolean whether or not a relationship exists between the given
users. An optional :class:`RelationshipStatus` instance can be specified.
"""
query = dict(
to_relationships__from_user=self.instance,
to_relationships__to_user=user,
to_relationships__site__pk=settings.SITE_ID,
)
if status:
query.update(to_relationships__status=status)
if symmetrical:
query.update(
from_relationships__to_user=self.instance,
from_relationships__from_user=user,
from_relationships__site__pk=settings.SITE_ID
)
if status:
query.update(from_relationships__status=status)
return get_user_model().objects.filter(**query).exists()
# some defaults
def following(self):
return self.get_relationships(RelationshipStatus.objects.following())
def followers(self):
return self.get_related_to(RelationshipStatus.objects.following())
def blocking(self):
return self.get_relationships(RelationshipStatus.objects.blocking())
def blockers(self):
return self.get_related_to(RelationshipStatus.objects.blocking())
def friends(self):
return self.get_relationships(RelationshipStatus.objects.following(), True)
if django.VERSION < (1, 2):
RelatedManager = create_many_related_manager(RelationshipManager, Relationship)
class RelationshipsDescriptor(object):
def __get__(self, instance, instance_type=None):
qn = connection.ops.quote_name
manager = RelatedManager(
model=get_user_model(),
core_filters={'related_to__pk': instance._get_pk_val()},
instance=instance,
symmetrical=False,
join_table=qn('relationships_relationship'),
source_col_name=qn('from_user_id'),
target_col_name=qn('to_user_id'),
)
return manager
elif django.VERSION > (1, 2) and django.VERSION < (1, 4):
fake_rel = ManyToManyRel(
to=AUTH_USER_MODEL,
through=Relationship)
RelatedManager = create_many_related_manager(RelationshipManager, fake_rel)
class RelationshipsDescriptor(object):
def __get__(self, instance, instance_type=None):
manager = RelatedManager(
model=get_user_model(),
core_filters={'related_to__pk': instance._get_pk_val()},
instance=instance,
symmetrical=False,
source_field_name='from_user',
target_field_name='to_user'
)
return manager
else:
fake_rel = ManyToManyRel(
to=AUTH_USER_MODEL,
through=Relationship)
RelatedManager = create_many_related_manager(RelationshipManager, fake_rel)
class RelationshipsDescriptor(object):
def __get__(self, instance, instance_type=None):
manager = RelatedManager(
model=get_user_model(),
query_field_name='related_to',
instance=instance,
symmetrical=False,
source_field_name='from_user',
target_field_name='to_user',
through=Relationship,
)
return manager
# HACK
#field.contribute_to_class(User, 'relationships')
#setattr(User, 'relationships', RelationshipsDescriptor())
| {
"repo_name": "maroux/django-relationships",
"path": "relationships/models.py",
"copies": "1",
"size": "12897",
"license": "mit",
"hash": -7406760327028736000,
"line_mean": 34.5289256198,
"line_max": 101,
"alpha_frac": 0.6138636892,
"autogenerated": false,
"ratio": 4.253627968337731,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5367491657537731,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import random
# better named alias, used as gen.* in templates
integer = random.randint
choice = random.choice
def var_name(n=1):
var_names = ['x', 'y', 'z']
if n == 1:
return random.choice(var_names)
return random.sample(var_names, n)
def nested_list(length=2, sublist_length=2, make_value=partial(integer, 1, 5), with_flat=True):
nested = [random_list(sublist_length, make_value) for _ in range(length)]
if with_flat:
return nested, sum(nested, [])
return nested
def random_list(length, make_value):
return [make_value() for _ in range(length)]
class Graph(object):
def __init__(self, nodes):
self.nodes = nodes
class Node(object):
def __init__(self, value, connected=None):
if connected is None:
connected = []
self.value = value
self.connected = connected
def __repr__(self):
return 'Node(value={!r}, connected={!r})'.format(self.value, self.connected)
def get_animals():
scooby = Node('Scooby')
human = Node('Human')
monkey = Node('Monkey', connected=[human])
smart = Node('Smart', connected=[monkey, human])
cat = Node('Cat')
dog = Node('Dog', connected=[scooby])
animal = Node('Animal', connected=[dog, cat, monkey, scooby])
return Graph([animal, dog, cat, smart, monkey, human])
def class_hierarchy(graph):
not_connected = {node.value: node for node in graph.nodes}
for node in graph.nodes:
for cn in node.connected:
not_connected.pop(cn.value, None)
roots = not_connected.values()
root = random.choice(roots)
path = [root]
while root.connected:
root = random.choice(root.connected)
path.append(root)
return path
| {
"repo_name": "alexandershov/pydrill",
"path": "pydrill/gen.py",
"copies": "1",
"size": "1772",
"license": "mit",
"hash": 1411112346630083000,
"line_mean": 25.8484848485,
"line_max": 95,
"alpha_frac": 0.6286681716,
"autogenerated": false,
"ratio": 3.5228628230616303,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9649850587650342,
"avg_score": 0.0003360814022578728,
"num_lines": 66
} |
from functools import partial
import random
class GameOverException(Exception):
def __init__(self, board):
self.score = board.score
def board_move(move_func):
def wrapper(*args, **kwargs):
board = args[0]
board.move_count += 1
board_state_before = board.serialize()
return_value = move_func(*args, **kwargs)
board_state_changed = board.serialize() != board_state_before
if 0 not in board.serialize() and not board_state_changed:
raise GameOverException(board)
board.add_random()
return return_value
return wrapper
class Board(object):
"""
Represents a 4x4 game board
"""
def __init__(self, state=None):
if state is None:
self.state = self._get_random_init_state()
else:
self.state = state
self.move_count = 0
def _get_random_init_state(self):
"""
Returns an initial board state with everything being zeroes except
two '2's
"""
initial_board = [0]*16
for index in random.sample(range(16), 2):
initial_board[index] = 2
return self.deserialize(initial_board)
def serialize(self):
"""
Returns the serialized state of the board being the rows joined
into one flat list
"""
return sum(self.state, [])
def deserialize(self, flat_list):
"""
Returns a 'deserialized' board state from the given flat list
"""
split_indices = map(lambda x: 4*x, range(4))
return [flat_list[index:index+4] for index in split_indices]
def rotate(self):
"""
Rotates the board by 90 deegrees clockwise
"""
self.state = rotate(self.state)
@board_move
def move_left(self):
"""
Performs the 'left' move on the board, increments the move counter and
adds a new random element
"""
self._move_left()
def _move_left(self):
"""
Performs the 'left' move on the board
"""
self.apply([partial(map, move)])
@board_move
def move_right(self):
"""
Performs the 'right' move on the board, increments the move counter and
adds a new random element
"""
self._move_right()
def _move_right(self):
"""
Performs the 'right' move on the board
"""
self.apply([rotate, rotate, partial(map, move), rotate, rotate])
@board_move
def move_down(self):
"""
Performs the 'down' move on the board, increments the move counter and
adds a new random element
"""
self._move_down()
def _move_down(self):
"""
Performs the 'down' move on the board
"""
self.apply([rotate, partial(map, move), rotate, rotate, rotate])
@board_move
def move_up(self):
"""
Performs the 'up' move on the board, increments the move counter and
adds a new random element
"""
self._move_up()
def _move_up(self):
"""
Performs the 'up' move on the board
"""
self.apply([rotate, rotate, rotate, partial(map, move), rotate])
def apply(self, functions):
"""
Applies the list of functions to the board's state in the given order
"""
state = list(self.state)
for function in functions:
state = function(state)
self.state = list(state)
def __repr__(self):
return '<Board {}>'.format(self.state)
def add_random(self):
"""
Adds a random digit(either 2 or 4) to the board
"""
serialized = self.serialize()
indexed = zip(range(len(serialized)), serialized)
zeroes = filter(lambda x: not bool(x[1]), indexed)
index, _ = random.choice(list(zeroes))
digit = random.choice((2, 4))
serialized[index] = digit
self.state = self.deserialize(serialized)
@property
def score(self):
"""
Returns the Board's score
"""
return sum(self.serialize())
def move(row):
without_zeroes = filter(bool, row)
return right_pad(merge(without_zeroes))
def merge(row):
result = []
row = list(row) # copy the row
row.reverse()
digit_stack = row
while digit_stack:
if len(digit_stack) == 1:
result.append(digit_stack.pop())
break
a = digit_stack.pop()
b = digit_stack.pop()
if a == b:
result.append(a+b)
else:
result.append(a)
digit_stack.append(b)
return result
def right_pad(input_list, size=4):
result = input_list[:]
extension = [0, ] * (size - len(result))
result.extend(extension)
return result
def rotate(board):
"""
Returns the given board rotated by 90 degrees clockwise.
"""
board = list(board) # copy the board
board.reverse()
rotated_board = map(list, zip(*board))
return list(rotated_board)
| {
"repo_name": "mamachanko/2048",
"path": "p2048.py",
"copies": "1",
"size": "5068",
"license": "mit",
"hash": 3673080489496234500,
"line_mean": 25.2590673575,
"line_max": 79,
"alpha_frac": 0.5623520126,
"autogenerated": false,
"ratio": 4.0414673046252,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.51038193172252,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import re
from .exceptions import UnknownFPSError
from .ssaevent import SSAEvent
from .ssastyle import SSAStyle
from .formatbase import FormatBase
from .substation import parse_tags
from .time import ms_to_frames, frames_to_ms
#: Matches a MicroDVD line.
MICRODVD_LINE = re.compile(r" *\{ *(\d+) *\} *\{ *(\d+) *\}(.+)")
class MicroDVDFormat(FormatBase):
@classmethod
def guess_format(cls, text):
if any(map(MICRODVD_LINE.match, text.splitlines())):
return "microdvd"
@classmethod
def from_file(cls, subs, fp, format_, fps=None, **kwargs):
for line in fp:
match = MICRODVD_LINE.match(line)
if not match:
continue
fstart, fend, text = match.groups()
fstart, fend = map(int, (fstart, fend))
if fps is None:
# We don't know the framerate, but it is customary to include
# it as text of the first subtitle. In that case, we skip
# this auxiliary subtitle and proceed with reading.
try:
fps = float(text)
subs.fps = fps
continue
except ValueError:
raise UnknownFPSError("Framerate was not specified and "
"cannot be read from "
"the MicroDVD file.")
start, end = map(partial(frames_to_ms, fps=fps), (fstart, fend))
def prepare_text(text):
text = text.replace("|", r"\N")
def style_replacer(match):
tags = [c for c in "biu" if c in match.group(0)]
return "{%s}" % "".join(r"\%s1" % c for c in tags)
text = re.sub(r"\{[Yy]:[^}]+\}", style_replacer, text)
text = re.sub(r"\{[Ff]:([^}]+)\}", r"{\\fn\1}", text)
text = re.sub(r"\{[Ss]:([^}]+)\}", r"{\\fs\1}", text)
text = re.sub(r"\{P:(\d+),(\d+)\}", r"{\\pos(\1,\2)}", text)
return text.strip()
ev = SSAEvent(start=start, end=end, text=prepare_text(text))
subs.append(ev)
@classmethod
def to_file(cls, subs, fp, format_, fps=None, write_fps_declaration=True, **kwargs):
if fps is None:
fps = subs.fps
if fps is None:
raise UnknownFPSError("Framerate must be specified when writing MicroDVD.")
to_frames = partial(ms_to_frames, fps=fps)
def is_entirely_italic(line):
style = subs.styles.get(line.style, SSAStyle.DEFAULT_STYLE)
for fragment, sty in parse_tags(line.text, style, subs.styles):
fragment = fragment.replace(r"\h", " ")
fragment = fragment.replace(r"\n", "\n")
fragment = fragment.replace(r"\N", "\n")
if not sty.italic and fragment and not fragment.isspace():
return False
return True
# insert an artificial first line telling the framerate
if write_fps_declaration:
subs.insert(0, SSAEvent(start=0, end=0, text=str(fps)))
for line in subs:
if line.is_comment or line.is_drawing:
continue
text = "|".join(line.plaintext.splitlines())
if is_entirely_italic(line):
text = "{Y:i}" + text
start, end = map(to_frames, (line.start, line.end))
# XXX warn on underflow?
if start < 0: start = 0
if end < 0: end = 0
print("{%d}{%d}%s" % (start, end, text), file=fp)
# remove the artificial framerate-telling line
if write_fps_declaration:
subs.pop(0)
| {
"repo_name": "tkarabela/pysubs2",
"path": "pysubs2/microdvd.py",
"copies": "1",
"size": "3786",
"license": "mit",
"hash": -9045680592102676000,
"line_mean": 35.7572815534,
"line_max": 88,
"alpha_frac": 0.5192815637,
"autogenerated": false,
"ratio": 3.816532258064516,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48358138217645164,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import re
from gooey.gui.lang import i18n
from gooey.gui.util.filedrop import FileDrop
from gooey.gui.util.quoting import maybe_quote
__author__ = 'Chris'
from abc import ABCMeta, abstractmethod
import os
import wx
import wx.lib.agw.multidirdialog as MDD
from gooey.gui.widgets.calender_dialog import CalendarDlg
class WidgetPack(object):
"""
Interface specifying the contract to which
all `WidgetPack`s will adhere
"""
__metaclass__ = ABCMeta
@abstractmethod
def build(self, parent, data):
pass
@abstractmethod
def getValue(self):
pass
def onResize(self, evt):
pass
@staticmethod
def get_command(data):
return data['commands'][0] if data['commands'] else ''
class BaseChooser(WidgetPack):
def __init__(self, button_text=''):
self.button_text = i18n._('browse')
self.option_string = None
self.parent = None
self.text_box = None
self.button = None
def build(self, parent, data=None):
self.parent = parent
self.option_string = data['commands'][0] if data['commands'] else ''
self.text_box = wx.TextCtrl(self.parent)
self.text_box.AppendText(safe_default(data, ''))
self.text_box.SetMinSize((0, -1))
dt = FileDrop(self.text_box)
self.text_box.SetDropTarget(dt)
self.button = wx.Button(self.parent, label=self.button_text, size=(73, 23))
widget_sizer = wx.BoxSizer(wx.HORIZONTAL)
widget_sizer.Add(self.text_box, 1, wx.EXPAND)
widget_sizer.AddSpacer(10)
widget_sizer.Add(self.button, 0)
parent.Bind(wx.EVT_BUTTON, self.onButton, self.button)
return widget_sizer
def getValue(self):
value = self.text_box.GetValue()
if self.option_string and value:
return '{0} {1}'.format(self.option_string, maybe_quote(value))
else:
return maybe_quote(value) if value else ''
def onButton(self, evt):
raise NotImplementedError
def __repr__(self):
return self.__class__.__name__
class BaseFileChooser(BaseChooser):
def __init__(self, dialog):
BaseChooser.__init__(self)
self.dialog = dialog
def onButton(self, evt):
dlg = self.dialog(self.parent)
result = (self.get_path(dlg)
if dlg.ShowModal() == wx.ID_OK
else None)
if result:
self.text_box.SetValue(result)
def get_path(self, dlg):
if isinstance(dlg, wx.DirDialog):
return maybe_quote(dlg.GetPath())
else:
paths = dlg.GetPaths()
return maybe_quote(paths[0]) if len(paths) < 2 else ' '.join(map(maybe_quote, paths))
class MyMultiDirChooser(MDD.MultiDirDialog):
def __init(self, *args, **kwargs):
super(MyMultiDirChooser,self).__init__(*args, **kwargs)
def GetPaths(self):
return self.dirCtrl.GetPaths()
def build_dialog(style, exist_constraint=True, **kwargs):
if exist_constraint:
return lambda panel: wx.FileDialog(panel, style=style | wx.FD_FILE_MUST_EXIST, **kwargs)
else:
return lambda panel: wx.FileDialog(panel, style=style, **kwargs)
FileChooserPayload = partial(BaseFileChooser, dialog=build_dialog(wx.FD_OPEN))
FileSaverPayload = partial(BaseFileChooser, dialog=build_dialog(wx.FD_SAVE, False, defaultFile="Enter Filename"))
MultiFileSaverPayload = partial(BaseFileChooser, dialog=build_dialog(wx.FD_MULTIPLE, False))
DirChooserPayload = partial(BaseFileChooser, dialog=lambda parent: wx.DirDialog(parent, 'Select Directory', style=wx.DD_DEFAULT_STYLE))
DateChooserPayload = partial(BaseFileChooser, dialog=CalendarDlg)
MultiDirChooserPayload = partial(BaseFileChooser, dialog=lambda parent: MyMultiDirChooser(parent, title="Select Directories", defaultPath=os.getcwd(), agwStyle=MDD.DD_MULTIPLE|MDD.DD_DIR_MUST_EXIST))
class TextInputPayload(WidgetPack):
def __init__(self):
self.widget = None
self.option_string = None
def build(self, parent, data):
self.option_string = self.get_command(data)
self.widget = wx.TextCtrl(parent)
dt = FileDrop(self.widget)
self.widget.SetDropTarget(dt)
self.widget.SetMinSize((0, -1))
self.widget.SetDoubleBuffered(True)
self.widget.AppendText(safe_default(data, ''))
return self.widget
def getValue(self):
value = self.widget.GetValue()
if value and self.option_string:
return '{} {}'.format(self.option_string, value)
else:
return '"{}"'.format(value) if value else ''
def _SetValue(self, text):
# used for testing
self.widget.SetLabelText(text)
class DropdownPayload(WidgetPack):
default_value = 'Select Option'
def __init__(self):
self.option_string = None
self.widget = None
def build(self, parent, data):
self.option_string = self.get_command(data)
self.widget = wx.ComboBox(
parent=parent,
id=-1,
value=safe_default(data, self.default_value),
choices=data['choices'],
style=wx.CB_DROPDOWN
)
return self.widget
def getValue(self):
if self.widget.GetValue() == self.default_value:
return ''
elif self.widget.GetValue() and self.option_string:
return '{} {}'.format(self.option_string, self.widget.GetValue())
else:
return self.widget.GetValue()
def _SetValue(self, text):
# used for testing
self.widget.SetLabelText(text)
class CounterPayload(WidgetPack):
def __init__(self):
self.option_string = None
self.widget = None
def build(self, parent, data):
self.option_string = self.get_command(data)
self.widget = wx.ComboBox(
parent=parent,
id=-1,
value=safe_default(data, ''),
choices=map(str, range(1, 11)),
style=wx.CB_DROPDOWN
)
return self.widget
def getValue(self):
'''
Returns
str(option_string * DropDown Value)
e.g.
-vvvvv
'''
dropdown_value = self.widget.GetValue()
if not str(dropdown_value).isdigit():
return ''
arg = str(self.option_string).replace('-', '')
repeated_args = arg * int(dropdown_value)
return '-' + repeated_args
def safe_default(data, default):
# str(None) is 'None'!? Whaaaaat...?
return str(data['default']) if data['default'] else ''
| {
"repo_name": "lrq3000/pyFileFixity",
"path": "pyFileFixity/lib/gooey/gui/widgets/widget_pack.py",
"copies": "1",
"size": "6102",
"license": "mit",
"hash": 741055081364891800,
"line_mean": 27.3813953488,
"line_max": 199,
"alpha_frac": 0.6738774172,
"autogenerated": false,
"ratio": 3.447457627118644,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4621335044318644,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import re
import logging
from collections import OrderedDict
import io
import six
SEND = 'SEND'
CONNECT = 'CONNECT'
MESSAGE = 'MESSAGE'
ERROR = 'ERROR'
CONNECTED = 'CONNECTED'
SUBSCRIBE = 'SUBSCRIBE'
UNSUBSCRIBE = 'UNSUBSCRIBE'
BEGIN = 'BEGIN'
COMMIT = 'COMMIT'
ABORT = 'ABORT'
ACK = 'ACK'
NACK = 'NACK'
DISCONNECT = 'DISCONNECT'
VALID_COMMANDS = ['message', 'connect', 'connected', 'error', 'send',
'subscribe', 'unsubscribe', 'begin', 'commit', 'abort', 'ack', 'disconnect', 'nack']
TEXT_PLAIN = 'text/plain'
class IncompleteFrame(Exception):
"""The frame has incomplete body"""
class BodyNotTerminated(Exception):
"""The frame's body is not terminated with the NULL character"""
class EmptyBuffer(Exception):
"""The buffer is empty"""
def parse_headers(buff):
"""
Parses buffer and returns command and headers as strings
"""
preamble_lines = list(map(
lambda x: six.u(x).decode(),
iter(lambda: buff.readline().strip(), b''))
)
if not preamble_lines:
raise EmptyBuffer()
return preamble_lines[0], OrderedDict([l.split(':') for l in preamble_lines[1:]])
def parse_body(buff, headers):
content_length = int(headers.get('content-length', -1))
body = buff.read(content_length)
if content_length >= 0:
if len(body) < content_length:
raise IncompleteFrame()
terminator = six.u(buff.read(1)).decode()
if not terminator:
raise BodyNotTerminated()
else:
# no content length
body, terminator, rest = body.partition(b'\x00')
if not terminator:
raise BodyNotTerminated()
else:
buff.seek(-len(rest), 2)
return body
class Frame(object):
"""
A STOMP frame (or message).
:param cmd: the protocol command
:param headers: a map of headers for the frame
:param body: the content of the frame.
"""
def __init__(self, cmd, headers=None, body=None):
self.cmd = cmd
self.headers = headers or {}
self.body = body or ''
def __str__(self):
return '{{cmd={0},headers=[{1}],body={2}}}'.format(
self.cmd,
self.headers,
self.body if isinstance(
self.body, six.binary_type) else six.b(self.body)
)
def __eq__(self, other):
""" Override equality checking to test for matching command, headers, and body. """
return all([isinstance(other, Frame),
self.cmd == other.cmd,
self.headers == other.headers,
self.body == other.body])
@property
def transaction(self):
return self.headers.get('transaction')
@classmethod
def from_buffer(cls, buff):
cmd, headers = parse_headers(buff)
body = parse_body(buff, headers)
return cls(cmd, headers=headers, body=body)
def pack(self):
"""
Create a string representation from object state.
@return: The string (bytes) for this stomp frame.
@rtype: C{str}
"""
self.headers.setdefault('content-length', len(self.body))
# Convert and append any existing headers to a string as the
# protocol describes.
headerparts = ("{0}:{1}\n".format(key, value)
for key, value in self.headers.items())
# Frame is Command + Header + EOF marker.
return six.b("{0}\n{1}\n".format(self.cmd, "".join(headerparts))) + (self.body if isinstance(self.body, six.binary_type) else six.b(self.body)) + six.b('\x00')
class ConnectedFrame(Frame):
""" A CONNECTED server frame (response to CONNECT).
@ivar session: The (throw-away) session ID to include in response.
@type session: C{str}
"""
def __init__(self, session, extra_headers=None):
"""
@param session: The (throw-away) session ID to include in response.
@type session: C{str}
"""
super(ConnectedFrame, self).__init__(
cmd='connected', headers=extra_headers or {})
self.headers['session'] = session
class HeaderValue(object):
"""
An descriptor class that can be used when a calculated header value is needed.
This class is a descriptor, implementing __get__ to return the calculated value.
While according to U{http://docs.codehaus.org/display/STOMP/Character+Encoding} there
seems to some general idea about having UTF-8 as the character encoding for headers;
however the C{stomper} lib does not support this currently.
For example, to use this class to generate the content-length header:
>>> body = 'asdf'
>>> headers = {}
>>> headers['content-length'] = HeaderValue(calculator=lambda: len(body))
>>> str(headers['content-length'])
'4'
@ivar calc: The calculator function.
@type calc: C{callable}
"""
def __init__(self, calculator):
"""
@param calculator: The calculator callable that will yield the desired value.
@type calculator: C{callable}
"""
if not callable(calculator):
raise ValueError("Non-callable param: %s" % calculator)
self.calc = calculator
def __get__(self, obj, objtype):
return self.calc()
def __str__(self):
return str(self.calc())
def __set__(self, obj, value):
self.calc = value
def __repr__(self):
return '<%s calculator=%s>' % (self.__class__.__name__, self.calc)
class ErrorFrame(Frame):
""" An ERROR server frame. """
def __init__(self, message, body=None, extra_headers=None):
"""
@param body: The message body bytes.
@type body: C{str}
"""
super(ErrorFrame, self).__init__(cmd='error',
headers=extra_headers or {}, body=body)
self.headers['message'] = message
self.headers[
'content-length'] = HeaderValue(calculator=lambda: len(self.body))
def __repr__(self):
return '<%s message=%r>' % (self.__class__.__name__, self.headers['message'])
class ReceiptFrame(Frame):
""" A RECEIPT server frame. """
def __init__(self, receipt, extra_headers=None):
"""
@param receipt: The receipt message ID.
@type receipt: C{str}
"""
super(ReceiptFrame, self).__init__(
'RECEIPT', headers=extra_headers or {})
self.headers['receipt-id'] = receipt
class FrameBuffer(object):
"""
A customized version of the StompBuffer class from Stomper project that returns frame objects
and supports iteration.
This version of the parser also assumes that stomp messages with no content-lengh
end in a simple \\x00 char, not \\x00\\n as is assumed by
C{stomper.stompbuffer.StompBuffer}. Additionally, this class differs from Stomper version
by conforming to PEP-8 coding style.
This class can be used to smooth over a transport that may provide partial frames (or
may provide multiple frames in one data buffer).
@ivar _buffer: The internal byte buffer.
@type _buffer: C{str}
@ivar debug: Log extra parsing debug (logs will be DEBUG level).
@type debug: C{bool}
"""
# regexp to check that the buffer starts with a command.
command_re = re.compile('^(.+?)\n')
# regexp to remove everything up to and including the first
# instance of '\x00' (used in resynching the buffer).
sync_re = re.compile('^.*?\x00')
# regexp to determine the content length. The buffer should always start
# with a command followed by the headers, so the content-length header will
# always be preceded by a newline. It may not always proceeded by a
# newline, though!
content_length_re = re.compile('\ncontent-length\s*:\s*(\d+)\s*(\n|$)')
def __init__(self):
self._buffer = io.BytesIO()
self._pointer = 0
self.debug = False
self.log = logging.getLogger('%s.%s' % (
self.__module__, self.__class__.__name__))
def clear(self):
"""
Clears (empties) the internal buffer.
"""
self._buffer = io
def buffer_len(self):
"""
@return: Number of bytes in the internal buffer.
@rtype: C{int}
"""
return len(self._buffer)
def buffer_empty(self):
"""
@return: C{True} if buffer is empty, C{False} otherwise.
@rtype: C{bool}
"""
return not bool(self._buffer)
def append(self, data):
"""
Appends bytes to the internal buffer (may or may not contain full stomp frames).
@param data: The bytes to append.
@type data: C{str}
"""
self._buffer.write(data)
def extract_frame(self):
"""
Pulls one complete frame off the buffer and returns it.
If there is no complete message in the buffer, returns None.
Note that the buffer can contain more than once message. You
should therefore call this method in a loop (or use iterator
functionality exposed by class) until None returned.
@return: The next complete frame in the buffer.
@rtype: L{stomp.frame.Frame}
"""
# (mbytes, hbytes) = self._find_message_bytes(self.buffer)
# if not mbytes:
# return None
#
# msgdata = self.buffer[:mbytes]
# self.buffer = self.buffer[mbytes:]
# hdata = msgdata[:hbytes]
# # Strip off any leading whitespace from headers; this is necessary, because
# # we do not (any longer) expect a trailing \n after the \x00 byte (which means
# # it will become a leading \n to the next frame).
# hdata = hdata.lstrip()
# elems = hdata.split('\n')
# cmd = elems.pop(0)
# headers = {}
#
# for e in elems:
# try:
# (k,v) = e.split(':', 1) # header values may contain ':' so specify maxsplit
# except ValueError:
# continue
# headers[k.strip()] = v.strip()
#
# # hbytes points to the start of the '\n\n' at the end of the header,
# # so 2 bytes beyond this is the start of the body. The body EXCLUDES
# # the final byte, which is '\x00'.
# body = msgdata[hbytes + 2:-1]
self._buffer.seek(self._pointer, 0)
try:
f = Frame.from_buffer(self._buffer)
self._pointer = self._buffer.tell()
except (IncompleteFrame, EmptyBuffer):
self._buffer.seek(self._pointer, 0)
return None
return f
def __iter__(self):
"""
Returns an iterator object.
"""
return self
def __next__(self):
"""
Return the next STOMP message in the buffer (supporting iteration).
@rtype: L{stomp.frame.Frame}
"""
msg = self.extract_frame()
if not msg:
raise StopIteration()
return msg
def next(self):
return self.__next__()
| {
"repo_name": "sekikn/ambari",
"path": "ambari-common/src/test/python/coilmq/util/frames.py",
"copies": "3",
"size": "11110",
"license": "apache-2.0",
"hash": 7504226794579157000,
"line_mean": 29.9470752089,
"line_max": 167,
"alpha_frac": 0.5883888389,
"autogenerated": false,
"ratio": 4.003603603603604,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0007922988027829318,
"num_lines": 359
} |
from functools import partial
import re
import logging
from sets import Set
import lib.visit as v
import lib.const as C
from .. import util
from ..meta import methods, classes, class_lookup
from ..meta.template import Template
from ..meta.clazz import Clazz
from ..meta.method import Method, find_formals
from ..meta.field import Field
from ..meta.statement import Statement, to_statements
from ..meta.expression import Expression
class AccessorUni(object):
__aux_name = C.ACC.AUX+"Uni"
regex_log = r"log::check_log::(-)(\d+)"
_invoked = Set()
@staticmethod
def is_method_log(msg):
return re.match(AccessorUni.regex_log, msg)
def add_invoked(self, msg):
m = re.match(AccessorUni.regex_log, msg)
self._invoked.add(int(m.group(2)))
## hole assignments for roles
## glblInit_accessor_????,StmtAssign,accessor_???? = n
regex_role = r"(({})_\S+_{})__.* = (\d+)$".format('|'.join(C.acc_roles), __aux_name)
@staticmethod
def simple_role_of_interest(msg):
return re.match(AccessorUni.regex_role, msg)
# add a mapping from role variable to its value chosen by sketch
def add_simple_role(self, msg):
m = re.match(AccessorUni.regex_role, msg)
v, n = m.group(1), m.group(3)
self._role[v] = n
# initializer
def __init__(self, cmd, output_path, acc_conf):
self._cmd = cmd
self._output = output_path
self._demo = util.pure_base(output_path)
self._acc_conf = acc_conf
self._cur_mtd = None
self._role = {} # { v : n }
# class roles
self._accessors = {} # { Aux... : {key1 : accessor1, key2 : accessor2} }
self._implicits = {} # { Aux... : {key1 : implicit1, key2 : implicit2} }
# method roles
self._getters = {} # { Aux... : {key1 : getter1, key2 : getter2 ...} }
self._setters = {} # { Aux... : {key1 : setter1, key2 : setter2 ...} }
self._cons = {} # { Aux... : {key1 : cons1, key2 : cons2 ...} }
# getter/setter fields
self._gs = {}
# interpret the synthesis result
with open(self._output, 'r') as f:
for line in f:
line = line.strip()
try:
if AccessorUni.is_method_log(line): self.add_invoked(line)
items = line.split(',')
func, kind, msg = items[0], items[1], ','.join(items[2:])
#if func == "AuxAccessorUni": print items
if AccessorUni.simple_role_of_interest(msg): self.add_simple_role(msg)
except IndexError: # not a line generated by custom codegen
pass # if "Total time" in line: logging.info(line)
@property
def demo(self):
return self._demo
@v.on("node")
def visit(self, node):
"""
This is the generic method to initialize the dynamic dispatcher
"""
# add a private field
@staticmethod
def add_prvt_fld(acc, k, typ, num):
name = u'_'.join([C.ACC.prvt, unicode(num), k, u"for", acc.name])
fld = acc.fld_by_name(name)
if fld and fld.typ != typ:
fld.typ = typ
if not fld:
logging.debug("adding private field {} for {} of type {}".format(name, acc.name, typ))
fld = Field(clazz=acc, typ=typ, name=name)
acc.add_fld(fld)
return fld
# getter code
@staticmethod
def def_getter(mtd, fld):
logging.debug("adding getter code into {}".format(repr(mtd)))
get = u"return {};".format(fld.name)
mtd.body = to_statements(mtd, get)
# setter code
@staticmethod
def def_setter(mtd, fld, typ):
arg = find_formals(mtd.params, [typ])[0]
logging.debug("adding setter code into {}".format(repr(mtd)))
set = u"{} = {};".format(fld.name, arg)
mtd.body = to_statements(mtd, set)
# constructor code
@staticmethod
def def_constructor(mtd, flds, imp):
if len(mtd.params) > len(flds): return
logging.debug("adding constructor code into {}".format(repr(mtd)))
for (_, nm), fld in zip(mtd.params, flds[:len(mtd.params)]):
init = u"{} = {};".format(fld.name, nm)
mtd.body += to_statements(mtd, init)
for i in range(len(imp)-len(mtd.params)):
hidden = imp[len(mtd.params)+i]
fldnm = flds[len(mtd.params)+i].name
init = u"{} = new {}();".format(fldnm, hidden.name)
mtd.body += to_statements(mtd, init)
@v.when(Template)
def visit(self, node):
def find_role(lst, aux_name, role):
try:
_id = self._role['_'.join([role, aux_name])]
return lst[int(_id)]
except KeyError:
# ignore what Sketch thought not critical for log conformity
return None
aux_name = self.__aux_name
aux = class_lookup(aux_name)
# find and store class roles
find_cls_role = partial(find_role, classes(), aux_name)
# find and store method roles
find_mtd_role = partial(find_role, methods(), aux_name)
cons = {}
for key in self._acc_conf.iterkeys():
cons[key] = find_mtd_role('_'.join([C.ACC.CONS, key]))
#cons_params = []
#for key in self._acc_conf.iterkeys():
# if self._acc_conf[key][0] >= 0:
# cons_params += map(find_mtd_role, map(lambda x: '_'.join([C.ACC.CONS, key, x]), range(self._acc_conf[key][0])))
implicits = {}
for key in self._acc_conf.iterkeys():
implicits[key] = {}
for x in xrange(self._acc_conf[key][0]):
implicits[key][x] = find_cls_role('_'.join([C.ACC.IMP, key, str(x)]))
getters = {}
for key in self._acc_conf.iterkeys():
getters[key] = {}
for x in xrange(self._acc_conf[key][1]):
getters[key][x] = find_mtd_role('_'.join([C.ACC.GET, key, str(x)]))
setters = {}
for key in self._acc_conf.iterkeys():
setters[key] = {}
for x in xrange(self._acc_conf[key][2]):
setters[key][x] = find_mtd_role('_'.join([C.ACC.SET, key, str(x)]))
gs = {}
for key in self._acc_conf.iterkeys():
gs[key] = {}
for x in xrange(max(self._acc_conf[key][1], self._acc_conf[key][2])):
try:
gs[key][x] = self._role['_'.join([C.ACC.GS, key, str(x), aux_name])]
except KeyError:
# ignore what Sketch thought not critical for log conformity
pass
self._cons[aux.name] = cons
self._implicits[aux.name] = implicits
self._getters[aux.name] = getters
self._setters[aux.name] = setters
self._gs[aux.name] = gs
# add private fields for constructors
for k in cons.iterkeys():
c = cons[k]
i = implicits[k]
if not c: continue
if util.exists(lambda m: m.id in self._invoked, c.clazz.mtds):
flds = []
for n, t in enumerate(c.param_typs):
fld = AccessorUni.add_prvt_fld(c.clazz, k, t, n)
flds.append(fld)
for dif in range(len(i.keys()) - len(c.params)):
fld = AccessorUni.add_prvt_fld(c.clazz, k, i[len(c.params)+dif].name, len(c.params)+dif)
flds.append(fld)
AccessorUni.def_constructor(c, flds, i)
# add private fields for getters/setters
# insert or move code snippets from Aux classes to actual participants
for k in gs.iterkeys():
for e in gs[k].iterkeys():
getr = getters[k][e]
setr = setters[k][e] if e in setters[k].keys() else None
effective = getr.id in self._invoked
if not effective: effective = (setr != None and setr.id in self._invoked)
if effective:
fld = AccessorUni.add_prvt_fld(getr.clazz, k, getr.typ, int(gs[k][e]))
logging.debug("getter: {}_{}: {}".format(k, e, repr(getr)))
AccessorUni.def_getter(getr, fld)
if setr != None:
fld = AccessorUni.add_prvt_fld(setr.clazz, k, setr.param_typs[0], int(gs[k][e]))
logging.debug("setter: {}_{}: {}".format(k, e, repr(setr)))
AccessorUni.def_setter(setr, fld, setr.param_typs[0])
# remove Aux class
node.classes.remove(aux)
@v.when(Clazz)
def visit(self, node): pass
@v.when(Field)
def visit(self, node): pass
@v.when(Method)
def visit(self, node):
self._cur_mtd = node
@v.when(Statement)
def visit(self, node):
if node.kind == C.S.EXP and node.e.kind == C.E.CALL:
call = unicode(node)
if call.startswith(C.ACC.AUX+"Uni"):
logging.debug("removing {}".format(call))
if "setterInOne" in call or "SetterInOne" in call:
## Aux.....setterInOne(...);
return []
else:
## Aux...constructor...
return []
if node.kind == C.S.RETURN:
call = unicode(node)
## return Aux....getterInOne(...);
if call.startswith(u"return " + C.ACC.AUX+"Uni") and "etterInOne" in call:
logging.debug("removing {}".format(call))
return []
return [node]
@v.when(Expression)
def visit(self, node): return node
| {
"repo_name": "plum-umd/pasket",
"path": "pasket/decode/accessor_uni.py",
"copies": "1",
"size": "8646",
"license": "mit",
"hash": 929165180315926700,
"line_mean": 31.75,
"line_max": 120,
"alpha_frac": 0.5931066389,
"autogenerated": false,
"ratio": 3.136017410228509,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4229124049128509,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import re
import logging
import lib.visit as v
import lib.const as C
from .. import util
from ..meta import methods, class_lookup
from ..meta.template import Template
from ..meta.clazz import Clazz
from ..meta.method import Method
from ..meta.field import Field
from ..meta.statement import Statement, to_statements
from ..meta.expression import Expression
class Adapter(object):
__aux_name = C.ADP.AUX
## hole assignments for roles
## glblInit_accessor_????,StmtAssign,accessor_???? = n
regex_role = r"(({})_{}).* = (\d+)$".format('|'.join(C.adp_roles), __aux_name)
@staticmethod
def simple_role_of_interest(msg):
return re.match(Adapter.regex_role, msg)
# add a mapping from role variable to its value chosen by sketch
def add_simple_role(self, msg):
m = re.match(Adapter.regex_role, msg)
v, n = m.group(1), m.group(3)
self._role[v] = n
# initializer
def __init__(self, output_path):
self._output = output_path
self._demo = util.pure_base(output_path)
self._cur_mtd = None
self._role = {} # { v : n }
# method roles
self._adapter = {} # { Aux... : Adapter }
self._adaptee = {} # { Aux... : Adaptee }
# interpret the synthesis result
with open(self._output, 'r') as f:
for line in f:
line = line.strip()
try:
items = line.split(',')
func, kind, msg = items[0], items[1], ','.join(items[2:])
if Adapter.simple_role_of_interest(msg): self.add_simple_role(msg)
except IndexError: # not a line generated by custom codegen
pass # if "Total time" in line: logging.info(line)
@property
def demo(self):
return self._demo
@v.on("node")
def visit(self, node):
"""
This is the generic method to initialize the dynamic dispatcher
"""
# adapter code
@staticmethod
def def_adapter(adapter, adaptee, adpfield):
logging.debug("adding adapter code into {}".format(repr(adapter)))
rcv = u"{}_{}_{}".format(C.ADP.FLD, adpfield, adapter.clazz.name)
adpe_call = u"{}.{}();".format(rcv, adaptee.name)
adapter.body = to_statements(adapter, adpe_call)
# add a private field
@staticmethod
def add_prvt_fld(acc, inst, typ, num):
name = u'_'.join([C.ADP.FLD, unicode(num), acc.name])
fld = acc.fld_by_name(name)
if not fld:
logging.debug("adding private field {} for {} of type {}".format(str(num), acc.name, typ))
fld = Field(clazz=acc, typ=typ, name=name)
acc.add_fld(fld)
setattr(acc, C.ACC.CONS+"_"+inst+"_"+str(num), fld)
# constructor code
@staticmethod
def def_constructor(mtd, acc):
logging.debug("adding constructor code into {}".format(repr(mtd)))
for i, (ty, nm) in enumerate(mtd.params):
init = u"{}_{}_{} = {};".format(C.ADP.FLD, unicode(i), acc.name, nm)
mtd.body += to_statements(mtd, init)
@v.when(Template)
def visit(self, node):
def find_role(lst, aux_name, role):
try:
_id = self._role['_'.join([role, aux_name])]
return lst[int(_id)]
except KeyError: return None
aux_name = self.__aux_name
aux = class_lookup(aux_name)
# find and store method roles
find_mtd_role = partial(find_role, methods(), aux_name)
adpt, adpe, adpf = map(find_mtd_role, C.adp_roles)
adpf = int(self._role['_'.join([C.ADP.FLD, aux_name])])
logging.debug("adapter: {}".format(repr(adpt)))
logging.debug("adaptee: {}".format(repr(adpe)))
self._adapter[aux.name] = adpt
self._adaptee[aux.name] = adpe
# insert code snippets for adapter
adpt_cls = adpt.clazz
for init in adpt_cls.inits:
for n, t in enumerate(init.param_typs):
Adapter.add_prvt_fld(adpt_cls, adpt_cls.name, t, n)
Adapter.def_constructor(init, adpt_cls)
Adapter.def_adapter(adpt, adpe, adpf)
# remove Aux class
node.classes.remove(aux)
@v.when(Clazz)
def visit(self, node): pass
@v.when(Field)
def visit(self, node): pass
@v.when(Method)
def visit(self, node):
self._cur_mtd = node
@v.when(Statement)
def visit(self, node):
if node.kind == C.S.EXP and node.e.kind == C.E.CALL:
call = unicode(node)
if call.startswith(C.ADP.AUX):
logging.debug("removing {}".format(call))
return []
return [node]
@v.when(Expression)
def visit(self, node): return node
| {
"repo_name": "plum-umd/pasket",
"path": "pasket/decode/adapter.py",
"copies": "1",
"size": "4384",
"license": "mit",
"hash": -4846524842747567000,
"line_mean": 27.6535947712,
"line_max": 96,
"alpha_frac": 0.6222627737,
"autogenerated": false,
"ratio": 3.15850144092219,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.428076421462219,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import re
import sys
import logging
import flatdict
import collections
import os
logger = logging.getLogger(__name__)
def resolve_yamls(yaml_templates, environ=os.environ):
logger.debug("Merging following yaml_templates: %s" % yaml_templates)
logger.debug("Using environ: %s" % environ)
merged_yaml = _merge_dicts(reversed(yaml_templates + [environ]))
flattened = flatdict.FlatDict(merged_yaml, delimiter=".")
keep_resolving = True
loops = 0
while keep_resolving and loops < len(flattened):
loops += 1
keep_resolving = False
for key, value in flattened.items():
keys_to_resolve = re.findall("\$\{(.*?)\}", str(value))
if len(keys_to_resolve) > 0: keep_resolving = True
resolved_keys = _resolve_key_substition(flattened, keys_to_resolve)
for sub_key, resolved_key in resolved_keys:
flattened[key] = flattened[key].replace(
"${%s}" % sub_key, str(resolved_key))
return flattened
def _resolve_key_substition(flattened, keys_to_resolve):
#this function returns array of tuples to replace strings later
resolved_keys = []
if len(keys_to_resolve) > 0:
for key_default in keys_to_resolve:
key_default_split = key_default.split(":")
sub_key = key_default_split[0]
default = key_default_split[1] if len(key_default_split) == 2 else sub_key
resolved = flattened.get(sub_key, default)
resolved_keys.append((key_default,resolved))
return resolved_keys
else:
return resolved_keys
def _merge_dicts(dicts):
result = {}
for dictionary in dicts:
_merge_dict(result, dictionary)
return result
def _merge_dict(dct, merge_dct):
for k, v in merge_dct.items():
if (k in dct and isinstance(dct[k], dict)
and isinstance(merge_dct[k], collections.Mapping)):
_merge_dict(dct[k], merge_dct[k])
else:
dct[k] = merge_dct[k]
| {
"repo_name": "armory-io/yaml-tools",
"path": "yamltools/resolver.py",
"copies": "1",
"size": "2057",
"license": "apache-2.0",
"hash": -3616460210970553000,
"line_mean": 36.4,
"line_max": 86,
"alpha_frac": 0.6217792902,
"autogenerated": false,
"ratio": 3.7882136279926337,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4909992918192634,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import re
import sys
try:
import colorama
colorama.init()
pre = (colorama.Fore.CYAN + colorama.Style.BRIGHT +
"AutoImport: " + colorama.Style.NORMAL +
colorama.Fore.WHITE)
except:
pre = "AutoImport: "
common_others = {"pd": "pandas", "np": "numpy", "sp": "scipy"}
class pipUnsuccessfulException(Exception):
pass
def custom_exc(ipython, shell, etype, evalue, tb, tb_offset=None):
shell.showtraceback((etype, evalue, tb), tb_offset)
while tb.tb_next:
tb = tb.tb_next
if not re.match("\\A<ipython-input-.*>\\Z", tb.tb_frame.f_code.co_filename):
# Innermost frame is not the IPython interactive environment.
return
try:
# Get the name of the module you tried to import
results = re.match("\\Aname '(.*)' is not defined\\Z", str(evalue))
if not results:
return
name = results.group(1)
custom_exc.last_name = name
try:
__import__(name)
except:
if common_others.get(name):
new_name = common_others.get(name)
try:
__import__(new_name)
r = ipython.ask_yes_no(
pre +
"{0} isn't a module, but {1} is. "
"Import {1} as {0}? (Y/n)".format(name, new_name))
if r:
name = "{} as {}".format(new_name, name)
else:
return
except Exception as e:
print(pre +
"{} isn't a module and nor is {}"
.format(name, new_name))
print(e)
return
else:
print(pre + "{} isn't a module".format(name))
try:
last_name = custom_exc.last_name
if ipython.ask_yes_no(pre + "Attempt to pip-install {}? (Y/n)"
.format(last_name)):
if __import__("pip").main(["install", last_name]) != 0:
raise pipUnsuccessfulException
else:
return
print(pre + "Installation completed successfully, importing...")
try:
res = ipython.run_cell("import {}".format(last_name))
print(pre + "Imported referenced module {}".format(last_name))
except:
print(pre + "{} isn't a module".format(last_name))
except pipUnsuccessfulException:
print(pre + "Installation with pip failed")
except AttributeError:
print(pre + "No module to install")
except ImportError:
print(pre + "pip not found")
return
# Import the module
ipython.run_code("import {}".format(name))
print(pre + "Imported referenced module {!r}, will retry".format(name))
print("".join("-" for _ in range(75)))
except Exception as e:
print(pre + ("Attempted to import {!r}"
"but an exception occured".format(name)))
try:
# Run the failed line again
res = ipython.run_cell(
list(ipython.history_manager.get_range())[-1][-1])
except Exception as e:
print(pre + "Another exception occured while retrying")
shell.showtraceback((type(e), e, None), None)
def load_ipython_extension(ipython):
# Bind the function we created to IPython's exception handler
ipython.set_custom_exc((NameError,), partial(custom_exc, ipython))
| {
"repo_name": "OrangeFlash81/ipython-auto-import",
"path": "import_wrapper.py",
"copies": "1",
"size": "3786",
"license": "mit",
"hash": -8184834965980081000,
"line_mean": 35.0571428571,
"line_max": 86,
"alpha_frac": 0.4936608558,
"autogenerated": false,
"ratio": 4.397212543554007,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5390873399354007,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import re
import uuid
from caliper import metric, reservoir, snapshot
from caliper.metric import (
Counter,
EWMA,
Gauge,
Histogram,
Meter,
Timer,
)
from caliper.reservoir import (
ExponentiallyDecayingReservoir,
Reservoir,
SlidingWindowReservoir,
UniformReservoir,
)
from caliper.snapshot import Snapshot, WeightedSnapshot
__all__ = [
'metric', 'registry', 'reservoir', 'snapshot',
'Counter', 'Gauge', 'Histogram', 'Timer', 'Meter', 'EWMA',
'Reservoir', 'SlidingWindowReservoir', 'UniformReservoir',
'ExponentiallyDecayingReservoir', 'Registry',
'Snapshot', 'WeightedSnapshot',
'create_metric', 'counter', 'gauge', 'histogram', 'meter', 'timer',
]
_registry = {}
def get_or_create_metric(cls, name=None, *args, **kwargs):
name = name or ('a%s' % uuid.uuid4().hex)
key = _split_registry_key('%s.%s' % (name, cls.__name__))
metric = _registry.get(key)
if metric:
if not type(metric) is cls:
raise TypeError('A metric with key %s already exists with type %s' %
('.'.join(key), metric.__class__))
else:
metric = cls(*args, **kwargs)
_registry[key] = metric
return metric
counter = partial(get_or_create_metric, Counter)
gauge = partial(get_or_create_metric, Gauge)
histogram = partial(get_or_create_metric, Histogram)
meter = partial(get_or_create_metric, Meter)
timer = partial(get_or_create_metric, Timer)
def _split_registry_key(keystr):
match = re.match('^([a-zA-Z][a-zA-Z0-9_]*)(?:\.([a-zA-Z][a-zA-Z0-9_]*))*$', keystr)
if not match:
raise ValueError("'%s' is in invalid registry key" % keystr)
return tuple(keystr.split('.'))
| {
"repo_name": "blubber/caliper",
"path": "caliper/__init__.py",
"copies": "1",
"size": "1736",
"license": "apache-2.0",
"hash": -5077252275924904000,
"line_mean": 26.125,
"line_max": 87,
"alpha_frac": 0.6394009217,
"autogenerated": false,
"ratio": 3.1853211009174314,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9320561493717319,
"avg_score": 0.0008321057800224467,
"num_lines": 64
} |
from functools import partial
import re
from streamlink.plugin import Plugin
from streamlink.plugin.api import http, validate
from streamlink.stream import HDSStream, HLSStream, HTTPStream
from streamlink.utils import parse_json, update_scheme
class Bloomberg(Plugin):
VOD_API_URL = 'https://www.bloomberg.com/api/embed?id={0}'
PLAYER_URL = 'https://cdn.gotraffic.net/projector/latest/bplayer.js'
CHANNEL_MAP = {
'audio': 'BBG_RADIO',
'live/europe': 'EU',
'live/us': 'US',
'live/asia': 'ASIA',
'live/stream': 'EVENT',
'live/emea': 'EMEA_EVENT',
'live/asia_stream': 'ASIA_EVENT'
}
_url_re = re.compile(r'''
https?://www\.bloomberg\.com/(
news/videos/[^/]+/[^/]+ |
(?P<channel>live/(?:stream|emea|asia_stream|europe|us|asia)|audio)/?
)
''', re.VERBOSE)
_live_player_re = re.compile(r'{APP_BUNDLE:"(?P<live_player_url>.+?/app.js)"')
_js_to_json_re = partial(re.compile(r'(\w+):(["\']|\d?\.?\d+,|true|false|\[|{)').sub, r'"\1":\2')
_video_id_re = re.compile(r'data-bmmr-id=\\"(?P<video_id>.+?)\\"')
_mp4_bitrate_re = re.compile(r'.*_(?P<bitrate>[0-9]+)\.mp4')
_live_streams_schema = validate.Schema(
validate.transform(_js_to_json_re),
validate.transform(lambda x: x.replace(':.', ':0.')),
validate.transform(parse_json),
validate.Schema(
{
'cdns': validate.all(
[
validate.Schema(
{
'streams': validate.all([
validate.Schema(
{'url': validate.transform(lambda x: re.sub(r'(https?:/)([^/])', r'\1/\2', x))},
validate.get('url'),
validate.url()
)
]),
},
validate.get('streams')
)
],
validate.transform(lambda x: [i for y in x for i in y])
)
},
validate.get('cdns')
)
)
_vod_api_schema = validate.Schema(
{
'secureStreams': validate.all([
validate.Schema(
{'url': validate.url()},
validate.get('url')
)
]),
'streams': validate.all([
validate.Schema(
{'url': validate.url()},
validate.get('url')
)
]),
'contentLoc': validate.url(),
},
validate.transform(lambda x: list(set(x['secureStreams'] + x['streams'] + [x['contentLoc']])))
)
@classmethod
def can_handle_url(cls, url):
return Bloomberg._url_re.match(url)
def _get_live_streams(self):
# Get channel id
match = self._url_re.match(self.url)
channel = match.group('channel')
# Retrieve live player URL
res = http.get(self.PLAYER_URL)
match = self._live_player_re.search(res.text)
if match is None:
return []
live_player_url = update_scheme(self.url, match.group('live_player_url'))
# Extract streams from the live player page
res = http.get(live_player_url)
stream_datas = re.findall(r'{0}(?:_MINI)?:({{.+?}}]}}]}})'.format(self.CHANNEL_MAP[channel]), res.text)
streams = []
for s in stream_datas:
for u in self._live_streams_schema.validate(s):
if u not in streams:
streams.append(u)
return streams
def _get_vod_streams(self):
# Retrieve URL page and search for video ID
res = http.get(self.url)
match = self._video_id_re.search(res.text)
if match is None:
return []
video_id = match.group('video_id')
res = http.get(self.VOD_API_URL.format(video_id))
streams = http.json(res, schema=self._vod_api_schema)
return streams
def _get_streams(self):
if '/news/videos/' in self.url:
# VOD
streams = self._get_vod_streams()
else:
# Live
streams = self._get_live_streams()
for video_url in streams:
if '.f4m' in video_url:
for stream in HDSStream.parse_manifest(self.session, video_url).items():
yield stream
elif '.m3u8' in video_url:
for stream in HLSStream.parse_variant_playlist(self.session, video_url).items():
yield stream
if '.mp4' in video_url:
match = self._mp4_bitrate_re.match(video_url)
if match is not None:
bitrate = match.group('bitrate') + 'k'
else:
bitrate = 'vod'
yield bitrate, HTTPStream(self.session, video_url)
__plugin__ = Bloomberg
| {
"repo_name": "javiercantero/streamlink",
"path": "src/streamlink/plugins/bloomberg.py",
"copies": "1",
"size": "5104",
"license": "bsd-2-clause",
"hash": -8962499869759382000,
"line_mean": 34.4444444444,
"line_max": 120,
"alpha_frac": 0.484130094,
"autogenerated": false,
"ratio": 3.8318318318318316,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48159619258318315,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import re
from streamlink.plugin import Plugin
from streamlink.plugin.api import validate
from streamlink.stream import HDSStream, HLSStream, HTTPStream
from streamlink.utils import parse_json, update_scheme
class Bloomberg(Plugin):
VOD_API_URL = 'https://www.bloomberg.com/api/embed?id={0}'
PLAYER_URL = 'https://cdn.gotraffic.net/projector/latest/bplayer.js'
CHANNEL_MAP = {
'audio': 'BBG_RADIO',
'live/europe': 'EU',
'live/us': 'US',
'live/asia': 'ASIA',
'live/stream': 'EVENT',
'live/emea': 'EMEA_EVENT',
'live/asia_stream': 'ASIA_EVENT'
}
_url_re = re.compile(r'''
https?://www\.bloomberg\.com/(
news/videos/[^/]+/[^/]+ |
(?P<channel>live/(?:stream|emea|asia_stream|europe|us|asia)|audio)/?
)
''', re.VERBOSE)
_live_player_re = re.compile(r'{APP_BUNDLE:"(?P<live_player_url>.+?/app.js)"')
_js_to_json_re = partial(re.compile(r'(\w+):(["\']|\d?\.?\d+,|true|false|\[|{)').sub, r'"\1":\2')
_video_id_re = re.compile(r'data-bmmr-id=\\"(?P<video_id>.+?)\\"')
_mp4_bitrate_re = re.compile(r'.*_(?P<bitrate>[0-9]+)\.mp4')
_live_streams_schema = validate.Schema(
validate.transform(_js_to_json_re),
validate.transform(lambda x: x.replace(':.', ':0.')),
validate.transform(parse_json),
validate.Schema(
{
'cdns': validate.all(
[
validate.Schema(
{
'streams': validate.all([
validate.Schema(
{'url': validate.transform(lambda x: re.sub(r'(https?:/)([^/])', r'\1/\2', x))},
validate.get('url'),
validate.url()
)
]),
},
validate.get('streams')
)
],
validate.transform(lambda x: [i for y in x for i in y])
)
},
validate.get('cdns')
)
)
_vod_api_schema = validate.Schema(
{
'secureStreams': validate.all([
validate.Schema(
{'url': validate.url()},
validate.get('url')
)
]),
'streams': validate.all([
validate.Schema(
{'url': validate.url()},
validate.get('url')
)
]),
'contentLoc': validate.url(),
},
validate.transform(lambda x: list(set(x['secureStreams'] + x['streams'] + [x['contentLoc']])))
)
@classmethod
def can_handle_url(cls, url):
return Bloomberg._url_re.match(url)
def _get_live_streams(self):
# Get channel id
match = self._url_re.match(self.url)
channel = match.group('channel')
# Retrieve live player URL
res = self.session.http.get(self.PLAYER_URL)
match = self._live_player_re.search(res.text)
if match is None:
return []
live_player_url = update_scheme(self.url, match.group('live_player_url'))
# Extract streams from the live player page
res = self.session.http.get(live_player_url)
stream_datas = re.findall(r'{0}(?:_MINI)?:({{.+?}}]}}]}})'.format(self.CHANNEL_MAP[channel]), res.text)
streams = []
for s in stream_datas:
for u in self._live_streams_schema.validate(s):
if u not in streams:
streams.append(u)
return streams
def _get_vod_streams(self):
# Retrieve URL page and search for video ID
res = self.session.http.get(self.url)
match = self._video_id_re.search(res.text)
if match is None:
return []
video_id = match.group('video_id')
res = self.session.http.get(self.VOD_API_URL.format(video_id))
streams = self.session.http.json(res, schema=self._vod_api_schema)
return streams
def _get_streams(self):
if '/news/videos/' in self.url:
# VOD
streams = self._get_vod_streams()
else:
# Live
streams = self._get_live_streams()
for video_url in streams:
if '.f4m' in video_url:
for stream in HDSStream.parse_manifest(self.session, video_url).items():
yield stream
elif '.m3u8' in video_url:
for stream in HLSStream.parse_variant_playlist(self.session, video_url).items():
yield stream
if '.mp4' in video_url:
match = self._mp4_bitrate_re.match(video_url)
if match is not None:
bitrate = match.group('bitrate') + 'k'
else:
bitrate = 'vod'
yield bitrate, HTTPStream(self.session, video_url)
__plugin__ = Bloomberg
| {
"repo_name": "back-to/streamlink",
"path": "src/streamlink/plugins/bloomberg.py",
"copies": "1",
"size": "5163",
"license": "bsd-2-clause",
"hash": 3650728214076073000,
"line_mean": 34.8541666667,
"line_max": 120,
"alpha_frac": 0.4884756924,
"autogenerated": false,
"ratio": 3.8244444444444445,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48129201368444446,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import re
import iso3166
from schwifty.common import Base
from schwifty import registry
_bic_re = re.compile(r'[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}(?:[A-Z0-9]{3})?')
class BIC(Base):
"""The BIC object.
Examples:
You can either create a new BIC object by providing a code as text::
>>> bic = BIC('GENODEM1GLS')
>>> bic.country_code
'DE'
>>> bic.location_code
'M1'
>>> bic.bank_code
'GENO'
or by using the :meth:`from_bank_code` classmethod::
>>> bic = BIC.from_bank_code('DE', '43060967')
>>> bic.formatted
'GENO DE M1 GLS'
Args:
bic (str): The BIC number.
allow_invalid (bool): If set to ``True`` validation is skipped on instantiation.
"""
def __init__(self, bic, allow_invalid=False):
super(BIC, self).__init__(bic)
if not allow_invalid:
self.validate()
@classmethod
def from_bank_code(cls, country_code, bank_code):
"""Create a new BIC object from country- and bank-code.
Examples:
>>> bic = BIC.from_bank_code('DE', '20070000')
>>> bic.country_code
'DE'
>>> bic.bank_code
'DEUT'
>>> bic.location_code
'HH'
>>> BIC.from_bank_code('DE', '01010101')
Traceback (most recent call last):
...
ValueError: Invalid bank code '01010101' for country 'DE'
Args:
country_code (str): ISO 3166 alpha2 country-code.
bank_code (str): Country specific bank-code.
Returns:
BIC: a BIC object generated from the given country code and bank code.
Raises:
ValueError: If the given bank code wasn't found in the registry
Note:
This currently only works for German bank-codes.
"""
try:
return cls(registry.get('bank_code')[(country_code, bank_code)]['bic'])
except KeyError:
raise ValueError("Invalid bank code {!r} for country {!r}".format(bank_code,
country_code))
def validate(self):
self._validate_length()
self._validate_structure()
self._validate_country_code()
return True
def _validate_length(self):
if self.length not in (8, 11):
raise ValueError("Invalid length '{}'".format(self.length))
def _validate_structure(self):
if not _bic_re.match(self.compact):
raise ValueError("Invalid structure '{}'".format(self.compact))
def _validate_country_code(self):
country_code = self.country_code
try:
iso3166.countries_by_alpha2[country_code]
except KeyError:
raise ValueError("Invalid country code '{}'".format(country_code))
@property
def formatted(self):
"""str: The BIC separated in the blocks bank-, country- and location-code."""
formatted = ' '.join([self.bank_code, self.country_code, self.location_code])
if self.branch_code:
formatted += ' ' + self.branch_code
return formatted
@property
def country_bank_code(self):
"""str or None: The country specific bank-code associated with the BIC."""
entry = registry.get('bic').get(self.compact)
if entry:
return entry.get('bank_code')
@property
def bank_name(self):
"""str or None: The name of the bank associated with the BIC."""
entry = registry.get('bic').get(self.compact)
if entry:
return entry.get('name')
@property
def bank_short_name(self):
"""str or None: The short name of the bank associated with the BIC."""
entry = registry.get('bic').get(self.compact)
if entry:
return entry.get('short_name')
@property
def exists(self):
"""bool: Indicates if the BIC is available in Schwifty's registry."""
return bool(registry.get('bic').get(self.compact))
@property
def type(self):
"""Indicates the type of BIC.
This can be one of 'testing', 'passive', 'reverse billing' or 'default'
Returns:
str: The BIC type.
"""
if self.location_code[1] == '0':
return 'testing'
elif self.location_code[1] == '1':
return 'passive'
elif self.location_code[1] == '2':
return 'reverse billing'
else:
return 'default'
bank_code = property(partial(Base._get_component, start=0, end=4),
doc="str: The bank-code part of the BIC.")
country_code = property(partial(Base._get_component, start=4, end=6),
doc="str: The ISO 3166 alpha2 country-code.")
location_code = property(partial(Base._get_component, start=6, end=8),
doc="str: The location code of the BIC.")
branch_code = property(partial(Base._get_component, start=8, end=11),
doc="str or None: The branch-code part of the BIC (if available)")
registry.build_index('bank', 'bic', 'bic')
registry.build_index('bank', 'bank_code', ('country_code', 'bank_code'), primary=True)
| {
"repo_name": "figo-connect/schwifty",
"path": "schwifty/bic.py",
"copies": "1",
"size": "5372",
"license": "mit",
"hash": 1469489582286984400,
"line_mean": 31.3614457831,
"line_max": 93,
"alpha_frac": 0.5558451229,
"autogenerated": false,
"ratio": 3.9645756457564576,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5020420768656457,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import re
import sublime
from Vintageous import PluginLogger
from Vintageous.state import _init_vintageous
from Vintageous.state import State
from Vintageous.vi import cmd_base
from Vintageous.vi import cmd_defs
from Vintageous.vi import mappings
from Vintageous.vi import search
from Vintageous.vi import units
from Vintageous.vi import utils
from Vintageous.vi.constants import regions_transformer_reversed
from Vintageous.vi.core import ViTextCommandBase
from Vintageous.vi.core import ViWindowCommandBase
from Vintageous.vi.keys import key_names
from Vintageous.vi.keys import KeySequenceTokenizer
from Vintageous.vi.keys import to_bare_command_name
from Vintageous.vi.mappings import Mappings
from Vintageous.vi.utils import first_sel
from Vintageous.vi.utils import gluing_undo_groups
from Vintageous.vi.utils import IrreversibleTextCommand
from Vintageous.vi.utils import is_view
from Vintageous.vi.utils import modes
from Vintageous.vi.utils import R
from Vintageous.vi.utils import regions_transformer
from Vintageous.vi.utils import resolve_insertion_point_at_b
from Vintageous.vi.utils import restoring_sel
_logger = PluginLogger(__name__)
class _vi_g_big_u(ViTextCommandBase):
'''
Command: gU
'''
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, motion=None):
def f(view, s):
view.replace(edit, s, view.substr(s).upper())
# Reverse the resulting region so that _enter_normal_mode
# collapses the selection as we want it.
return R(s.b, s.a)
if mode not in (modes.INTERNAL_NORMAL,
modes.VISUAL,
modes.VISUAL_LINE,
modes.VISUAL_BLOCK):
raise ValueError('bad mode: ' + mode)
if motion is None and mode == modes.INTERNAL_NORMAL:
raise ValueError('motion data required')
if mode == modes.INTERNAL_NORMAL:
self.save_sel()
self.view.run_command(motion['motion'], motion['motion_args'])
if self.has_sel_changed():
regions_transformer(self.view, f)
else:
utils.blink()
else:
regions_transformer(self.view, f)
self.enter_normal_mode(mode)
class _vi_gu(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, motion=None):
def f(view, s):
view.replace(edit, s, view.substr(s).lower())
# reverse the resulting region so that _enter_normal_mode collapses the
# selection as we want it.
return R(s.b, s.a)
if mode not in (modes.INTERNAL_NORMAL,
modes.VISUAL,
modes.VISUAL_LINE,
modes.VISUAL_BLOCK):
raise ValueError('bad mode: ' + mode)
if motion is None and mode == modes.INTERNAL_NORMAL:
raise ValueError('motion data required')
if mode == modes.INTERNAL_NORMAL:
self.save_sel()
self.view.run_command(motion['motion'], motion['motion_args'])
if self.has_sel_changed():
regions_transformer(self.view, f)
else:
utils.blink()
else:
regions_transformer(self.view, f)
self.enter_normal_mode(mode)
class _vi_gq(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, motion=None):
def reverse(view, s):
return R(s.end(), s.begin())
def shrink(view, s):
if view.substr(s.b - 1) == '\n':
return R(s.a, s.b - 1)
return s
if mode in (modes.VISUAL, modes.VISUAL_LINE):
# TODO: ST seems to always reformat whole paragraphs with
# 'wrap_lines'.
regions_transformer(self.view, shrink)
regions_transformer(self.view, reverse)
self.view.run_command('wrap_lines')
self.enter_normal_mode(mode)
return
elif mode == modes.INTERNAL_NORMAL:
if motion is None:
raise ValueError('motion data required')
self.save_sel()
self.view.run_command(motion['motion'], motion['motion_args'])
if self.has_sel_changed():
self.save_sel()
self.view.run_command('wrap_lines')
self.view.sel().clear()
self.view.sel().add_all(self.old_sel)
else:
utils.blink()
self.enter_normal_mode(mode)
else:
raise ValueError('bad mode: ' + mode)
class _vi_u(ViWindowCommandBase):
'''
Undoes last change.
'''
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# TODO: surely must accept a mode?
def run(self, count=1):
for i in range(count):
self._view.run_command('undo')
if self._view.has_non_empty_selection_region():
def reverse(view, s):
return R(s.end(), s.begin())
# TODO: xpos is misaligned after this.
regions_transformer(self._view, reverse)
# FIXME: why from modes.VISUAL?
self.window.run_command('_enter_normal_mode', {
'mode': modes.VISUAL
})
# If we yy, then u, we might end up with outlined regions if we
# don't erase them here, because ST will restore them when undoing.
self._view.erase_regions('vi_yy_target')
class _vi_ctrl_r(ViWindowCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, count=1, mode=None):
for i in range(count):
self._view.run_command('redo')
class _vi_a(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, count=1, mode=None):
def f(view, s):
if view.substr(s.b) != '\n' and s.b < view.size():
return R(s.b + 1)
return s
state = State(self.view)
# Abort if the *actual* mode is insert mode. This prevents
# _vi_a from adding spaces between text fragments when used with a
# count, as in 5aFOO. In that case, we only need to run 'a' the first
# time, not for every iteration.
if state.mode == modes.INSERT:
return
if mode is None:
raise ValueError('mode required')
# TODO: We should probably not define the keys for these modes
# in the first place.
elif mode != modes.INTERNAL_NORMAL:
return
regions_transformer(self.view, f)
# TODO(guillermooo): derive this class from ViTextCommandBase ???
self.view.window().run_command('_enter_insert_mode', {'mode': mode,
'count': state.normal_insert_count})
class _vi_c(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
_can_yank = True
_populates_small_delete_register = True
def run(self, edit, count=1, mode=None, motion=None, register=None):
def compact(view, s):
if view.substr(s).strip():
if s.b > s.a:
pt = utils.previous_non_white_space_char(
view, s.b - 1, white_space=' \t\n')
return R(s.a, pt + 1)
pt = utils.previous_non_white_space_char(
view, s.a - 1, white_space=' \t\n')
return R(pt + 1, s.b)
return s
if mode is None:
raise ValueError('mode required')
if (mode == modes.INTERNAL_NORMAL) and (motion is None):
raise ValueError('motion required')
self.save_sel()
if motion:
self.view.run_command(motion['motion'], motion['motion_args'])
# Vim ignores trailing white space for c. XXX Always?
if mode == modes.INTERNAL_NORMAL:
regions_transformer(self.view, compact)
if not self.has_sel_changed():
self.enter_insert_mode(mode)
return
# If we ci' and the target is an empty pair of quotes, we should
# not delete anything.
# FIXME: This will not work well with multiple selections.
if all(s.empty() for s in self.view.sel()):
self.enter_insert_mode(mode)
return
self.state.registers.yank(self, register)
self.view.run_command('right_delete')
self.enter_insert_mode(mode)
class _enter_normal_mode(ViTextCommandBase):
"""
The equivalent of pressing the Esc key in Vim.
@mode
The mode we're coming from, which should still be the current mode.
@from_init
Whether _enter_normal_mode has been called from _init_vintageous. This
is important to know in order to not hide output panels when the user
is only navigating files or clicking around, not pressing Esc.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, from_init=False):
state = self.state
self.view.window().run_command('hide_auto_complete')
self.view.window().run_command('hide_overlay')
if ((not from_init and (mode == modes.NORMAL) and not state.sequence) or
not is_view(self.view)):
# When _enter_normal_mode is requested from _init_vintageous, we
# should not hide output panels; hide them only if the user
# pressed Esc and we're not cancelling partial state data, or if a
# panel has the focus.
# XXX: We are assuming that state.sequence will always be empty
# when we do the check above. Is that so?
# XXX: The 'not is_view(self.view)' check above seems to be
# redundant, since those views should be ignored by
# Vintageous altogether.
self.view.window().run_command('hide_panel', {'cancel': True})
self.view.settings().set('command_mode', True)
self.view.settings().set('inverse_caret_state', True)
# Exit replace mode.
self.view.set_overwrite_status(False)
state.enter_normal_mode()
# XXX: st bug? if we don't do this, selections won't be redrawn
self.view.run_command('_enter_normal_mode_impl', {'mode': mode})
if state.glue_until_normal_mode and not state.processing_notation:
if self.view.is_dirty():
self.view.window().run_command('glue_marked_undo_groups')
# We're exiting from insert mode or replace mode. Capture
# the last native command as repeat data.
state.repeat_data = ('native', self.view.command_history(0)[:2], mode, None)
# Required here so that the macro gets recorded.
state.glue_until_normal_mode = False
state.add_macro_step(*self.view.command_history(0)[:2])
state.add_macro_step('_enter_normal_mode', {'mode': mode,
'from_init': from_init})
else:
state.add_macro_step('_enter_normal_mode', {'mode': mode,
'from_init': from_init})
self.view.window().run_command('unmark_undo_groups_for_gluing')
state.glue_until_normal_mode = False
if mode == modes.INSERT and int(state.normal_insert_count) > 1:
state.enter_insert_mode()
# TODO: Calculate size the view has grown by and place the caret
# after the newly inserted text.
sels = list(self.view.sel())
self.view.sel().clear()
new_sels = [R(s.b + 1) if self.view.substr(s.b) != '\n'
else s
for s in sels]
self.view.sel().add_all(new_sels)
times = int(state.normal_insert_count) - 1
state.normal_insert_count = '1'
self.view.window().run_command('_vi_dot', {
'count': times,
'mode': mode,
'repeat_data': state.repeat_data,
})
self.view.sel().clear()
self.view.sel().add_all(new_sels)
state.update_xpos(force=True)
sublime.status_message('')
class _enter_normal_mode_impl(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None):
def f(view, s):
_logger.info(
'[_enter_normal_mode_impl] entering normal mode from {0}'
.format(mode))
if mode == modes.INSERT:
if view.line(s.b).a != s.b:
return R(s.b - 1)
return R(s.b)
if mode == modes.INTERNAL_NORMAL:
return R(s.b)
if mode == modes.VISUAL:
if s.a < s.b:
pt = s.b - 1
if view.line(pt).empty():
return R(pt)
if view.substr(pt) == '\n':
pt -= 1
return R(pt)
return R(s.b)
if mode in (modes.VISUAL_LINE, modes.VISUAL_BLOCK):
# save selections for gv
# But only if there are non-empty sels. We might be in visual
# mode and not have non-empty sels because we've just existed
# from an action.
if self.view.has_non_empty_selection_region():
self.view.add_regions('visual_sel', list(self.view.sel()))
if s.a < s.b:
pt = s.b - 1
if (view.substr(pt) == '\n') and not view.line(pt).empty():
pt -= 1
return R(pt)
else:
return R(s.b)
if mode == modes.SELECT:
return R(s.begin())
return R(s.b)
if mode == modes.UNKNOWN:
return
if (len(self.view.sel()) > 1) and (mode == modes.NORMAL):
sel = self.view.sel()[0]
self.view.sel().clear()
self.view.sel().add(sel)
regions_transformer(self.view, f)
self.view.erase_regions('vi_search')
self.view.run_command('_vi_adjust_carets', {'mode': mode})
class _enter_select_mode(ViWindowCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, mode=None, count=1):
self.state.enter_select_mode()
view = self.window.active_view()
# If there are no visual selections, do some work work for the user.
if not view.has_non_empty_selection_region():
self.window.run_command('find_under_expand')
state = State(view)
state.display_status()
class _enter_insert_mode(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1):
self.view.settings().set('inverse_caret_state', False)
self.view.settings().set('command_mode', False)
self.state.enter_insert_mode()
self.state.normal_insert_count = str(count)
self.state.display_status()
class _enter_visual_mode(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None):
state = self.state
# TODO(guillermooo): If all selections are non-zero-length, we may be
# looking at a pseudo-visual selection, like the ones that are
# created pressing Alt+Enter when using ST's built-in search dialog.
# What shall we really do in that case?
# XXX: In response to the above, we would probably already be in
# visual mode, but we should double-check that.
if state.mode == modes.VISUAL:
self.view.run_command('_enter_normal_mode', {'mode': mode})
return
self.view.run_command('_enter_visual_mode_impl', {'mode': mode})
if any(s.empty() for s in self.view.sel()):
return
# Sometimes we'll call this command without the global state knowing
# its metadata. For example, when shift-clicking with the mouse to
# create visual selections. Always update xpos to cover this case.
state.update_xpos(force=True)
state.enter_visual_mode()
state.display_status()
class _enter_visual_mode_impl(ViTextCommandBase):
"""
Transforms the view's selections. We don't do this inside the
EnterVisualMode window command because ST seems to neglect to repaint the
selections. (bug?)
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None):
def f(view, s):
if mode == modes.VISUAL_LINE:
return R(s.a, s.b)
else:
if s.empty() and (s.b == self.view.size()):
utils.blink()
return s
# Extending from s.a to s.b because we may be looking at
# selections with len>0. For example, if it's been created
# using the mouse. Normally, though, the selection will be
# empty when we reach here.
end = s.b
# Only extend .b by 1 if we're looking at empty sels.
if not view.has_non_empty_selection_region():
end += 1
return R(s.a, end)
regions_transformer(self.view, f)
class _enter_visual_line_mode(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None):
state = self.state
if state.mode == modes.VISUAL_LINE:
self.view.run_command('_enter_normal_mode', {'mode': mode})
return
# FIXME: 'V' from normal mode sets mode to internal normal.
if mode in (modes.NORMAL, modes.INTERNAL_NORMAL):
# Abort if we are at EOF -- no newline char to hold on to.
if any(s.b == self.view.size() for s in self.view.sel()):
utils.blink()
return
self.view.run_command('_enter_visual_line_mode_impl', {'mode': mode})
state.enter_visual_line_mode()
state.display_status()
class _enter_visual_line_mode_impl(ViTextCommandBase):
"""
Transforms the view's selections.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None):
def f(view, s):
if mode == modes.VISUAL:
if s.a < s.b:
if view.substr(s.b - 1) != '\n':
return R(view.line(s.a).a,
view.full_line(s.b - 1).b)
else:
return R(view.line(s.a).a, s.b)
else:
if view.substr(s.a - 1) != '\n':
return R(view.full_line(s.a - 1).b,
view.line(s.b).a)
else:
return R(s.a, view.line(s.b).a)
else:
return view.full_line(s.b)
regions_transformer(self.view, f)
class _enter_replace_mode(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit):
def f(view, s):
return R(s.b)
state = self.state
state.settings.view['command_mode'] = False
state.settings.view['inverse_caret_state'] = False
state.view.set_overwrite_status(True)
state.enter_replace_mode()
regions_transformer(self.view, f)
state.display_status()
state.reset()
# TODO: Remove this command once we don't need it any longer.
class ToggleMode(ViWindowCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self):
value = self.window.active_view().settings().get('command_mode')
self.window.active_view().settings().set('command_mode', not value)
self.window.active_view().settings().set('inverse_caret_state', not value)
print("command_mode status:", not value)
state = self.state
if not self.window.active_view().settings().get('command_mode'):
state.mode = modes.INSERT
sublime.status_message('command mode status: %s' % (not value))
class ProcessNotation(ViWindowCommandBase):
"""
Runs sequences of keys representing Vim commands.
For example: fngU5l
@keys
Key sequence to be run.
@repeat_count
Count to be applied when repeating through the '.' command.
@check_user_mappings
Whether user mappings should be consulted to expand key sequences.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, keys, repeat_count=None, check_user_mappings=True):
state = self.state
_logger.info("[ProcessNotation] seq received: {0} mode: {1}"
.format(keys, state.mode))
initial_mode = state.mode
# Disable interactive prompts. For example, to supress interactive
# input collection in /foo<CR>.
state.non_interactive = True
# First, run any motions coming before the first action. We don't keep
# these in the undo stack, but they will still be repeated via '.'.
# This ensures that undoing will leave the caret where the first
# editing action started. For example, 'lldl' would skip 'll' in the
# undo history, but store the full sequence for '.' to use.
leading_motions = ''
for key in KeySequenceTokenizer(keys).iter_tokenize():
self.window.run_command('press_key', {
'key': key,
'do_eval': False,
'repeat_count': repeat_count,
'check_user_mappings': check_user_mappings
})
if state.action:
# The last key press has caused an action to be primed. That
# means there are no more leading motions. Break out of here.
_logger.info('[ProcessNotation] first action found in {0}'
.format(state.sequence))
state.reset_command_data()
if state.mode == modes.OPERATOR_PENDING:
state.mode = modes.NORMAL
break
elif state.runnable():
# Run any primed motion.
leading_motions += state.sequence
state.eval()
state.reset_command_data()
else:
# XXX: When do we reach here?
state.eval()
if state.must_collect_input:
# State is requesting more input, so this is the last command in
# the sequence and it needs more input.
self.collect_input()
return
# Strip the already run commands.
if leading_motions:
if ((len(leading_motions) == len(keys)) and
(not state.must_collect_input)):
return
_logger.info('[ProcessNotation] original seq/leading motions: {0}/{1}'
.format(keys, leading_motions))
keys = keys[len(leading_motions):]
_logger.info('[ProcessNotation] seq stripped to {0}'.format(keys))
if not (state.motion and not state.action):
with gluing_undo_groups(self.window.active_view(), state):
try:
for key in KeySequenceTokenizer(keys).iter_tokenize():
if key.lower() == key_names.ESC:
# XXX: We should pass a mode here?
self.window.run_command('_enter_normal_mode')
continue
elif state.mode not in (modes.INSERT, modes.REPLACE):
self.window.run_command('press_key', {
'key': key,
'repeat_count': repeat_count,
'check_user_mappings': check_user_mappings
})
else:
self.window.run_command('insert', {
'characters': utils.translate_char(key)})
if not state.must_collect_input:
return
finally:
state.non_interactive = False
# Ensure we set the full command for '.' to use, but don't
# store '.' alone.
if (leading_motions + keys) not in ('.', 'u', '<C-r>'):
state.repeat_data = (
'vi', (leading_motions + keys),
initial_mode, None)
# We'll reach this point if we have a command that requests input
# whose input parser isn't satistied. For example, `/foo`. Note that
# `/foo<CR>`, on the contrary, would have satisfied the parser.
_logger.info('[ProcessNotation] unsatisfied parser: {0} {1}'
.format(state.action, state.motion))
if (state.action and state.motion):
# We have a parser an a motion that can collect data. Collect data
# interactively.
motion_data = state.motion.translate(state) or None
if motion_data is None:
utils.blink()
state.reset_command_data()
return
motion_data['motion_args']['default'] = state.motion._inp
self.window.run_command(motion_data['motion'],
motion_data['motion_args'])
return
self.collect_input()
def collect_input(self):
try:
command = None
if self.state.motion and self.state.action:
if self.state.motion.accept_input:
command = self.state.motion
else:
command = self.state.action
else:
command = self.state.action or self.state.motion
parser_def = command.input_parser
_logger.info('[ProcessNotation] last attemp to collect input: {0}'
.format(parser_def.command))
if parser_def.interactive_command:
self.window.run_command(parser_def.interactive_command,
{parser_def.input_param: command._inp}
)
except IndexError:
_logger.info('[Vintageous] could not find a command to collect'
'more user input')
utils.blink()
finally:
self.state.non_interactive = False
class PressKey(ViWindowCommandBase):
"""
Core command. It interacts with the global state each time a key is
pressed.
@key
Key pressed.
@repeat_count
Count to be used when repeating through the '.' command.
@do_eval
Whether to evaluate the global state when it's in a runnable
state. Most of the time, the default value of `True` should be
used. Set to `False` when you want to manually control
the global state's evaluation. For example, this is what the
PressKey command does.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, key, repeat_count=None, do_eval=True, check_user_mappings=True):
_logger.info("[PressKey] pressed: {0}".format(key))
state = self.state
# If the user has made selections with the mouse, we may be in an
# inconsistent state. Try to remedy that.
if (state.view.has_non_empty_selection_region() and
state.mode not in (modes.VISUAL,
modes.VISUAL_LINE,
modes.VISUAL_BLOCK,
modes.SELECT)):
_init_vintageous(state.view)
if key.lower() == '<esc>':
self.window.run_command('_enter_normal_mode', {'mode': state.mode})
state.reset_command_data()
return
state.sequence += key
state.display_status()
if state.must_capture_register_name:
state.register = key
state.partial_sequence = ''
return
# if capturing input, we shall not pass this point
if state.must_collect_input:
state.process_user_input2(key)
if state.runnable():
_logger.info('[PressKey] state holds a complete command.')
if do_eval:
_logger.info('[PressKey] evaluating complete command')
state.eval()
state.reset_command_data()
return
if repeat_count:
state.action_count = str(repeat_count)
if self.handle_counts(key, repeat_count):
return
state.partial_sequence += key
_logger.info("[PressKey] sequence {0}".format(state.sequence))
_logger.info("[PressKey] partial sequence {0}".format(state.partial_sequence))
# key_mappings = KeyMappings(self.window.active_view())
key_mappings = Mappings(state)
if check_user_mappings and key_mappings.incomplete_user_mapping():
_logger.info("[PressKey] incomplete user mapping: {0}".format(state.partial_sequence))
# for example, we may have typed 'aa' and there's an 'aaa' mapping.
# we need to keep collecting input.
return
_logger.info('[PressKey] getting cmd for seq/partial seq in (mode): {0}/{1} ({2})'.format(state.sequence,
state.partial_sequence,
state.mode))
command = key_mappings.resolve(check_user_mappings=check_user_mappings)
if isinstance(command, cmd_defs.ViOpenRegister):
_logger.info('[PressKey] requesting register name')
state.must_capture_register_name = True
return
# XXX: This doesn't seem to be correct. If we are in OPERATOR_PENDING mode, we should
# most probably not have to wipe the state.
if isinstance(command, mappings.Mapping):
if do_eval:
new_keys = command.mapping
if state.mode == modes.OPERATOR_PENDING:
command_name = command.mapping
new_keys = state.sequence[:-len(state.partial_sequence)] + command.mapping
reg = state.register
acount = state.action_count
mcount = state.motion_count
state.reset_command_data()
state.register = reg
state.motion_count = mcount
state.action_count = acount
state.mode = modes.NORMAL
_logger.info('[PressKey] running user mapping {0} via process_notation starting in mode {1}'.format(new_keys, state.mode))
self.window.run_command('process_notation', {'keys': new_keys, 'check_user_mappings': False})
return
if isinstance(command, cmd_defs.ViOpenNameSpace):
# Keep collecing input to complete the sequence. For example, we
# may have typed 'g'.
_logger.info("[PressKey] opening namespace: {0}".format(state.partial_sequence))
return
elif isinstance(command, cmd_base.ViMissingCommandDef):
bare_seq = to_bare_command_name(state.sequence)
if state.mode == modes.OPERATOR_PENDING:
# We might be looking at a command like 'dd'. The first 'd' is
# mapped for normal mode, but the second is missing in
# operator pending mode, so we get a missing command. Try to
# build the full command now.
#
# Exclude user mappings, since they've already been given a
# chance to evaluate.
command = key_mappings.resolve(sequence=bare_seq,
mode=modes.NORMAL,
check_user_mappings=False)
else:
command = key_mappings.resolve(sequence=bare_seq)
if isinstance(command, cmd_base.ViMissingCommandDef):
_logger.info('[PressKey] unmapped sequence: {0}'.format(state.sequence))
utils.blink()
state.mode = modes.NORMAL
state.reset_command_data()
return
if (state.mode == modes.OPERATOR_PENDING and
isinstance(command, cmd_defs.ViOperatorDef)):
# TODO: This may be unreachable code by now. ???
# we're expecting a motion, but we could still get an action.
# For example, dd, g~g~ or g~~
# remove counts
action_seq = to_bare_command_name(state.sequence)
_logger.info('[PressKey] action seq: {0}'.format(action_seq))
command = key_mappings.resolve(sequence=action_seq, mode=modes.NORMAL)
# TODO: Make _missing a command.
if isinstance(command, cmd_base.ViMissingCommandDef):
_logger.info("[PressKey] unmapped sequence: {0}".format(state.sequence))
state.reset_command_data()
return
if not command['motion_required']:
state.mode = modes.NORMAL
state.set_command(command)
_logger.info("[PressKey] '{0}'' mapped to '{1}'".format(state.partial_sequence, command))
if state.mode == modes.OPERATOR_PENDING:
state.reset_partial_sequence()
if do_eval:
state.eval()
def handle_counts(self, key, repeat_count):
"""
Returns `True` if the processing of the current key needs to stop.
"""
state = State(self.window.active_view())
if not state.action and key.isdigit():
if not repeat_count and (key != '0' or state.action_count) :
_logger.info('[PressKey] action count digit: {0}'.format(key))
state.action_count += key
return True
if (state.action and (state.mode == modes.OPERATOR_PENDING) and
key.isdigit()):
if not repeat_count and (key != '0' or state.motion_count):
_logger.info('[PressKey] motion count digit: {0}'.format(key))
state.motion_count += key
return True
class _vi_dot(ViWindowCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, mode=None, count=None, repeat_data=None):
state = self.state
state.reset_command_data()
if state.mode == modes.INTERNAL_NORMAL:
state.mode = modes.NORMAL
if repeat_data is None:
_logger.info('[_vi_dot] nothing to repeat')
return
# TODO: Find out if the user actually meant '1'.
if count and count == 1:
count = None
type_, seq_or_cmd, old_mode, visual_data = repeat_data
_logger.info(
'[_vi_dot] type: {0} seq or cmd: {1} old mode: {2}'
.format(type_, seq_or_cmd, old_mode))
if visual_data and (mode != modes.VISUAL):
state.restore_visual_data(visual_data)
elif not visual_data and (mode == modes.VISUAL):
# Can't repeat normal mode commands in visual mode.
utils.blink()
return
elif mode not in (modes.VISUAL, modes.VISUAL_LINE, modes.NORMAL,
modes.INTERNAL_NORMAL, modes.INSERT):
utils.blink()
return
if type_ == 'vi':
self.window.run_command('process_notation', {'keys': seq_or_cmd,
'repeat_count': count})
elif type_ == 'native':
sels = list(self.window.active_view().sel())
# FIXME: We're not repeating as we should. It's the motion that
# should receive this count.
for i in range(count or 1):
self.window.run_command(*seq_or_cmd)
# FIXME: What happens in visual mode?
self.window.active_view().sel().clear()
self.window.active_view().sel().add_all(sels)
else:
raise ValueError('bad repeat data')
self.window.run_command('_enter_normal_mode', {'mode': mode})
state.repeat_data = repeat_data
state.update_xpos()
class _vi_dd(ViTextCommandBase):
_can_yank = True
_yanks_linewise = True
_populates_small_delete_register = False
_synthetize_new_line_at_eof = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, register='"'):
def do_motion(view, s):
if mode != modes.INTERNAL_NORMAL:
return s
return units.lines(view, s, count)
def do_action(view, s):
if mode != modes.INTERNAL_NORMAL:
return s
view.erase(edit, s)
pt = utils.next_non_white_space_char(view, view.line(s.a).a,
white_space=' \t')
return R(pt)
def set_sel():
old = [s.a for s in list(self.view.sel())]
self.view.sel().clear()
new = [utils.next_non_white_space_char(self.view, pt) for pt in old]
self.view.sel().add_all([R(pt) for pt in new])
regions_transformer(self.view, do_motion)
self.state.registers.yank(self, register, operation='delete')
self.view.run_command('right_delete')
set_sel()
# TODO(guillermooo): deleting last line leaves the caret at \n
class _vi_cc(ViTextCommandBase):
_can_yank = True
_yanks_linewise = True
_populates_small_delete_register = False
_synthetize_new_line_at_eof = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, register='"'):
def motion(view, s):
if mode != modes.INTERNAL_NORMAL:
return s
if view.line(s.b).empty():
return s
return units.inner_lines(view, s, count)
regions_transformer(self.view, motion)
self.state.registers.yank(self, register)
if not all(s.empty() for s in self.view.sel()):
self.view.run_command ('right_delete')
self.enter_insert_mode(mode)
self.set_xpos(self.state)
class _vi_visual_o(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1):
def f(view, s):
# FIXME: In Vim, o doesn't work in modes.VISUAL_LINE, but ST can't move the caret while
# in modes.VISUAL_LINE, so we enable this for convenience. Change when/if ST can move
# the caret while in modes.VISUAL_LINE.
if mode in (modes.VISUAL, modes.VISUAL_LINE):
return R(s.b, s.a)
return s
regions_transformer(self.view, f)
self.view.show(self.view.sel()[0].b, False)
# TODO: is this really a text command?
class _vi_yy(ViTextCommandBase):
_can_yank = True
_synthetize_new_line_at_eof = True
_yanks_linewise = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, register=None):
def select(view, s):
if count > 1:
row, col = self.view.rowcol(s.b)
end = view.text_point(row + count - 1, 0)
return R(view.line(s.a).a, view.full_line(end).b)
if view.line(s.b).empty():
return R(s.b, min(view.size(), s.b + 1))
return view.full_line(s.b)
def restore():
self.view.sel().clear()
self.view.sel().add_all(list(self.old_sel))
if mode != modes.INTERNAL_NORMAL:
utils.blink()
raise ValueError('wrong mode')
self.save_sel()
regions_transformer(self.view, select)
state = self.state
self.outline_target()
state.registers.yank(self, register)
restore()
self.enter_normal_mode(mode)
class _vi_y(ViTextCommandBase):
_can_yank = True
_populates_small_delete_register = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, motion=None, register=None):
def f(view, s):
return R(s.end(), s.begin())
if mode == modes.INTERNAL_NORMAL:
if motion is None:
raise ValueError('bad args')
self.view.run_command(motion['motion'], motion['motion_args'])
self.outline_target()
elif mode not in (modes.VISUAL, modes.VISUAL_LINE, modes.VISUAL_BLOCK):
return
state = self.state
state.registers.yank(self, register)
regions_transformer(self.view, f)
self.enter_normal_mode(mode)
class _vi_d(ViTextCommandBase):
_can_yank = True
_populates_small_delete_register = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, motion=None, register=None):
def reverse(view, s):
return R(s.end(), s.begin())
if mode not in (modes.INTERNAL_NORMAL, modes.VISUAL,
modes.VISUAL_LINE):
raise ValueError('wrong mode')
if mode == modes.INTERNAL_NORMAL and not motion:
raise ValueError('missing motion')
if motion:
self.save_sel()
self.view.run_command(motion['motion'], motion['motion_args'])
# The motion has failed, so abort.
if not self.has_sel_changed():
utils.blink()
self.enter_normal_mode(mode)
return
# If the target's an empty pair of quotes, don't delete.
# FIXME: This won't work well with multiple sels.
if all(s.empty() for s in self.view.sel()):
self.enter_normal_mode(mode)
return
state = self.state
state.registers.yank(self, register, operation='delete')
self.view.run_command('left_delete')
self.view.run_command('_vi_adjust_carets')
self.enter_normal_mode(mode)
# XXX: abstract this out for all types of selections.
def advance_to_text_start(view, s):
pt = utils.next_non_white_space_char(self.view, s.b)
return R(pt)
if mode == modes.INTERNAL_NORMAL:
regions_transformer(self.view, advance_to_text_start)
class _vi_big_a(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1):
def f(view, s):
if mode == modes.VISUAL_BLOCK:
if self.view.substr(s.b - 1) == '\n':
return R(s.end() - 1)
return R(s.end())
elif mode == modes.VISUAL:
pt = s.b
if self.view.substr(s.b - 1) == '\n':
pt -= 1
if s.a > s.b:
pt = view.line(s.a).a
return R(pt)
elif mode == modes.VISUAL_LINE:
if s.a < s.b:
if s.b < view.size():
return R(s.end() - 1)
return R(s.end())
return R(s.begin())
elif mode != modes.INTERNAL_NORMAL:
return s
if s.b == view.size():
return s
hard_eol = self.view.line(s.b).end()
return R(hard_eol, hard_eol)
if mode == modes.SELECT:
self.view.window().run_command('find_all_under')
return
regions_transformer(self.view, f)
self.enter_insert_mode(mode)
class _vi_big_i(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, count=1, mode=None):
def f(view, s):
if mode == modes.VISUAL_BLOCK:
return R(s.begin())
elif mode == modes.VISUAL:
pt = view.line(s.a).a
if s.a > s.b:
pt = s.b
return R(pt)
elif mode == modes.VISUAL_LINE:
line = view.line(s.a)
pt = utils.next_non_white_space_char(view, line.a)
return R(pt)
elif mode != modes.INTERNAL_NORMAL:
return s
line = view.line(s.b)
pt = utils.next_non_white_space_char(view, line.a)
return R(pt, pt)
regions_transformer(self.view, f)
self.enter_insert_mode(mode)
class _vi_m(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, character=None):
state = self.state
state.marks.add(character, self.view)
# TODO: What if we are in visual mode?
self.enter_normal_mode(mode)
class _vi_quote(ViTextCommandBase):
"""
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, character=None, count=1):
def f(view, s):
if mode == modes.VISUAL:
if s.a <= s.b:
if address.b < s.b:
return R(s.a + 1, address.b)
else:
return R(s.a, address.b)
else:
return R(s.a + 1, address.b)
elif mode == modes.NORMAL:
return address
elif mode == modes.INTERNAL_NORMAL:
if s.a < address.a:
return R(view.full_line(s.b).a,
view.line(address.b).b)
return R(view.full_line(s.b).b,
view.line(address.b).a)
return s
state = self.state
address = state.marks.get_as_encoded_address(character)
if address is None:
return
if isinstance(address, str):
if not address.startswith('<command'):
self.view.window().open_file(address, sublime.ENCODED_POSITION)
else:
# We get a command in this form: <command _vi_double_quote>
self.view.run_command(address.split(' ')[1][:-1])
return
regions_transformer(self.view, f)
if not self.view.visible_region().intersects(address):
self.view.show_at_center(address)
class _vi_backtick(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, count=1, mode=None, character=None):
def f(view, s):
if mode == modes.VISUAL:
if s.a <= s.b:
if address.b < s.b:
return R(s.a + 1, address.b)
else:
return R(s.a, address.b)
else:
return R(s.a + 1, address.b)
elif mode == modes.NORMAL:
return address
elif mode == modes.INTERNAL_NORMAL:
return R(s.a, address.b)
return s
state = self.state
address = state.marks.get_as_encoded_address(character, exact=True)
if address is None:
return
if isinstance(address, str):
if not address.startswith('<command'):
self.view.window().open_file(address, sublime.ENCODED_POSITION)
return
# This is a motion in a composite command.
regions_transformer(self.view, f)
class _vi_quote_quote(IrreversibleTextCommand):
next_command = 'jump_back'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self):
current = _vi_quote_quote.next_command
self.view.window().run_command(current)
_vi_quote_quote.next_command = ('jump_forward' if (current ==
'jump_back')
else 'jump_back')
class _vi_big_d(ViTextCommandBase):
_can_yank = True
_synthetize_new_line_at_eof = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, register=None):
def f(view, s):
if mode == modes.INTERNAL_NORMAL:
if count == 1:
if view.line(s.b).size() > 0:
eol = view.line(s.b).b
return R(s.b, eol)
return s
return s
self.save_sel()
regions_transformer(self.view, f)
state = self.state
state.registers.yank(self)
self.view.run_command('left_delete')
self.enter_normal_mode(mode)
class _vi_big_c(ViTextCommandBase):
_can_yank = True
_synthetize_new_line_at_eof = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, register=None):
def f(view, s):
if mode == modes.INTERNAL_NORMAL:
if count == 1:
if view.line(s.b).size() > 0:
eol = view.line(s.b).b
return R(s.b, eol)
return s
return s
self.save_sel()
regions_transformer(self.view, f)
state = self.state
state.registers.yank(self)
empty = [s for s in list(self.view.sel()) if s.empty()]
self.view.add_regions('vi_empty_sels', empty)
for r in empty:
self.view.sel().subtract(r)
self.view.run_command('right_delete')
self.view.sel().add_all(self.view.get_regions('vi_empty_sels'))
self.view.erase_regions('vi_empty_sels')
self.enter_insert_mode(mode)
class _vi_big_s_action(ViTextCommandBase):
_can_yank = True
_synthetize_new_line_at_eof = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, register=None):
def sel_line(view, s):
if mode == modes.INTERNAL_NORMAL:
if count == 1:
if view.line(s.b).size() > 0:
eol = view.line(s.b).b
begin = view.line(s.b).a
begin = utils.next_non_white_space_char(view, begin, white_space=' \t')
return R(begin, eol)
return s
return s
regions_transformer(self.view, sel_line)
state = self.state
state.registers.yank(self, register)
empty = [s for s in list(self.view.sel()) if s.empty()]
self.view.add_regions('vi_empty_sels', empty)
for r in empty:
self.view.sel().subtract(r)
self.view.run_command('right_delete')
self.view.sel().add_all(self.view.get_regions('vi_empty_sels'))
self.view.erase_regions('vi_empty_sels')
self.view.run_command('reindent', {'force_indent': False})
self.enter_insert_mode(mode)
class _vi_s(ViTextCommandBase):
"""
Implementation of Vim's 's' action.
"""
# Yank config data.
_can_yank = True
_populates_small_delete_register = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, register=None):
def select(view, s):
if mode == modes.INTERNAL_NORMAL:
if view.line(s.b).empty():
return R(s.b)
return R(s.b, s.b + count)
return R(s.begin(), s.end())
if mode not in (modes.VISUAL,
modes.VISUAL_LINE,
modes.VISUAL_BLOCK,
modes.INTERNAL_NORMAL):
# error?
utils.blink()
self.enter_normal_mode(mode)
self.save_sel()
regions_transformer(self.view, select)
if not self.has_sel_changed() and mode == modes.INTERNAL_NORMAL:
self.enter_insert_mode(mode)
return
state = self.state
state.registers.yank(self, register)
self.view.run_command('right_delete')
self.enter_insert_mode(mode)
class _vi_x(ViTextCommandBase):
"""
Implementation of Vim's x action.
"""
_can_yank = True
_populates_small_delete_register = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def line_end(self, pt):
return self.view.line(pt).end()
def run(self, edit, mode=None, count=1, register=None):
def select(view, s):
nonlocal abort
if mode == modes.INTERNAL_NORMAL:
eol = utils.get_eol(view, s.b)
return R(s.b, min(s.b + count, eol))
if s.size() == 1:
b = s.b - 1 if s.a < s.b else s.b
return s
if mode not in (modes.VISUAL,
modes.VISUAL_LINE,
modes.VISUAL_BLOCK,
modes.INTERNAL_NORMAL):
# error?
utils.blink()
self.enter_normal_mode(mode)
if mode == modes.INTERNAL_NORMAL:
if all(self.view.line(s.b).empty() for s in self.view.sel()):
utils.blink()
return
abort = False
regions_transformer(self.view, select)
if not abort:
self.state.registers.yank(self, register)
self.view.run_command('right_delete')
self.enter_normal_mode(mode)
class _vi_r(ViTextCommandBase):
_can_yank = True
_synthetize_new_line_at_eof = True
_populates_small_delete_register = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def make_replacement_text(self, char, r):
frags = self.view.split_by_newlines(r)
new_frags = []
for fr in frags:
new_frags.append(char * len(fr))
return '\n'.join(new_frags)
def run(self, edit, mode=None, count=1, register=None, char=None):
def f(view, s):
if mode == modes.INTERNAL_NORMAL:
pt = s.b + count
text = self.make_replacement_text(char, R(s.a, pt))
view.replace(edit, R(s.a, pt), text)
if char == '\n':
return R(s.b + 1)
else:
return R(s.b)
if mode in (modes.VISUAL, modes.VISUAL_LINE, modes.VISUAL_BLOCK):
ends_in_newline = (view.substr(s.end() - 1) == '\n')
text = self.make_replacement_text (char, s)
if ends_in_newline:
text += '\n'
view.replace(edit, s, text)
if char == '\n':
return R(s.begin() + 1)
else:
return R(s.begin())
if char is None:
raise ValueError('bad parameters')
char = utils.translate_char(char)
self.state.registers.yank(self, register)
regions_transformer(self.view, f)
self.enter_normal_mode(mode)
class _vi_less_than_less_than(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=None):
def motion(view, s):
if mode != modes.INTERNAL_NORMAL:
return s
if count <= 1:
return s
a = utils.get_bol(view, s.a)
pt = view.text_point(utils.row_at(view, a) + (count - 1), 0)
return R(a, utils.get_eol(view, pt))
def action(view, s):
bol = utils.get_bol(view, s.begin())
pt = utils.next_non_white_space_char(view, bol, white_space='\t ')
return R(pt)
regions_transformer(self.view, motion)
self.view.run_command('unindent')
regions_transformer(self.view, action)
class _vi_equal_equal(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1):
def f(view, s):
return R(s.begin())
def select(view):
s0 = utils.first_sel(self.view)
end_row = utils.row_at(view, s0.b) + (count - 1)
view.sel().clear()
view.sel().add(R(s0.begin(), view.text_point(end_row, 1)))
if count > 1:
select(self.view)
self.view.run_command('reindent', {'force_indent': False})
regions_transformer(self.view, f)
self.enter_normal_mode(mode)
class _vi_greater_than_greater_than(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1):
def f(view, s):
bol = utils.get.bol(view, s.begin())
pt = utils.next_non_white_space_char(view, bol, white_space='\t ')
return R(pt)
def select(view):
s0 = utils.first_sel(view)
end_row = utils.row_at(view, s0.b) + (count - 1)
utils.replace_sel(view, R(s0.begin(), view.text_point(end_row, 1)))
if count > 1:
select(self.view)
self.view.run_command('indent')
regions_transformer(self.view, f)
self.enter_normal_mode(mode)
class _vi_greater_than(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, motion=None):
def f(view, s):
return R(s.begin())
def indent_from_begin(view, s, level=1):
block = '\t' if not translate else ' ' * size
self.view.insert(edit, s.begin(), block * level)
return R(s.begin() + 1)
if mode == modes.VISUAL_BLOCK:
translate = self.view.settings().get('translate_tabs_to_spaces')
size = self.view.settings().get('tab_size')
indent = partial(indent_from_begin, level=count)
regions_transformer_reversed(self.view, indent)
regions_transformer(self.view, f)
# Restore only the first sel.
utils.replace_sel(self.view, utils.first_sel(self.view))
self.enter_normal_mode(mode)
return
if motion:
self.view.run_command(motion['motion'], motion['motion_args'])
elif mode not in (modes.VISUAL, modes.VISUAL_LINE):
utils.blink()
return
for i in range(count):
self.view.run_command('indent')
regions_transformer(self.view, f)
self.enter_normal_mode(mode)
class _vi_less_than(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, motion=None):
def f(view, s):
return R(s.begin())
# Note: Vim does not unindent in visual block mode.
if motion:
self.view.run_command(motion['motion'], motion['motion_args'])
elif mode not in (modes.VISUAL, modes.VISUAL_LINE):
utils.blink()
return
for i in range(count):
self.view.run_command('unindent')
regions_transformer(self.view, f)
self.enter_normal_mode(mode)
class _vi_equal(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, motion=None):
def f(view, s):
return R(s.begin())
if motion:
self.view.run_command(motion['motion'], motion['motion_args'])
elif mode not in (modes.VISUAL, modes.VISUAL_LINE):
utils.blink()
return
self.view.run_command('reindent', {'force_indent': False})
regions_transformer(self.view, f)
self.enter_normal_mode(mode)
class _vi_big_o(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, count=1, mode=None):
if mode == modes.INTERNAL_NORMAL:
self.view.run_command('run_macro_file', {'file': 'res://Packages/Default/Add Line Before.sublime-macro'})
self.enter_insert_mode(mode)
class _vi_o(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, count=1, mode=None):
if mode == modes.INTERNAL_NORMAL:
self.view.run_command('run_macro_file', {'file': 'res://Packages/Default/Add Line.sublime-macro'})
self.enter_insert_mode(mode)
class _vi_big_x(ViTextCommandBase):
_can_yank = True
_populates_small_delete_register = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def line_start(self, pt):
return self.view.line(pt).begin()
def run(self, edit, mode=None, count=1, register=None):
def select(view, s):
nonlocal abort
if mode == modes.INTERNAL_NORMAL:
if view.line(s.b).empty():
abort = True
return R(s.b, max(s.b - count,
self.line_start(s.b)))
elif mode == modes.VISUAL:
if s.a < s.b:
if view.line(s.b - 1).empty() and s.size() == 1:
abort = True
return R(view.full_line(s.b - 1).b,
view.line(s.a).a)
if view.line(s.b).empty() and s.size() == 1:
abort = True
return R(view.line(s.b).a,
view.full_line(s.a - 1).b)
return R(s.begin(), s.end())
abort = False
regions_transformer(self.view, select)
state = self.state
state.registers.yank(self, register)
if not abort:
self.view.run_command('left_delete')
self.enter_normal_mode(mode)
class _vi_big_p(ViTextCommandBase):
_can_yank = True
_synthetize_new_line_at_eof = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, register=None, count=1, mode=None):
state = self.state
if state.mode == modes.VISUAL:
prev_text = state.registers.get_selected_text(self)
if register:
fragments = state.registers[register]
else:
# TODO: There should be a simpler way of getting the unnamed
# register's content.
fragments = state.registers['"']
if state.mode == modes.VISUAL:
# Populate registers with the text we're about to paste.
state.registers['"'] = prev_text
# TODO: Enable pasting to multiple selections.
sel = list(self.view.sel())[0]
text_block, linewise = self.merge(fragments)
if mode == modes.INTERNAL_NORMAL:
if not linewise:
self.view.insert(edit, sel.a, text_block)
self.view.sel().clear()
pt = sel.a + len(text_block) - 1
self.view.sel().add(R(pt))
else:
pt = self.view.line(sel.a).a
self.view.insert(edit, pt, text_block)
self.view.sel().clear()
row = utils.row_at(self.view, pt)
pt = self.view.text_point(row, 0)
self.view.sel().add(R(pt))
elif mode == modes.VISUAL:
if not linewise:
self.view.replace(edit, sel, text_block)
else:
pt = sel.a
if text_block[0] != '\n':
text_block = '\n' + text_block
self.view.replace(edit, sel, text_block)
self.view.sel().clear()
row = utils.row_at(self.view, pt + len(text_block))
pt = self.view.text_point(row - 1, 0)
self.view.sel().add(R(pt))
else:
return
self.enter_normal_mode(mode=mode)
def merge(self, fragments):
"""Merges a list of strings.
Returns a block of text and a bool indicating whether it's a linewise
block.
"""
block = ''.join(fragments)
if '\n' in fragments[0]:
if block[-1] != '\n':
return (block + '\n'), True
return block, True
return block, False
class _vi_p(ViTextCommandBase):
_can_yank = True
_synthetize_new_line_at_eof = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, register=None, count=1, mode=None):
state = self.state
register = register or '"'
fragments = state.registers[register]
if not fragments:
print("Vintageous: Nothing in register \".")
return
if state.mode == modes.VISUAL:
prev_text = state.registers.get_selected_text(self)
state.registers['"'] = prev_text
sels = list(self.view.sel())
# If we have the same number of pastes and selections, map 1:1. Otherwise paste paste[0]
# to all target selections.
if len(sels) == len(fragments):
sel_to_frag_mapped = zip(sels, fragments)
else:
sel_to_frag_mapped = zip(sels, [fragments[0],] * len(sels))
# FIXME: Fix this mess. Separate linewise from charwise pasting.
pasting_linewise = True
offset = 0
paste_locations = []
for selection, fragment in reversed(list(sel_to_frag_mapped)):
fragment = self.prepare_fragment(fragment)
if fragment.startswith('\n'):
# Pasting linewise...
# If pasting at EOL or BOL, make sure we paste before the newline character.
if (utils.is_at_eol(self.view, selection) or
utils.is_at_bol(self.view, selection)):
l = self.paste_all(edit, selection,
self.view.line(selection.b).b,
fragment,
count)
paste_locations.append(l)
else:
l = self.paste_all(edit, selection,
self.view.line(selection.b - 1).b,
fragment,
count)
paste_locations.append(l)
else:
pasting_linewise = False
# Pasting charwise...
# If pasting at EOL, make sure we don't paste after the newline character.
if self.view.substr(selection.b) == '\n':
l = self.paste_all(edit, selection, selection.b + offset,
fragment, count)
paste_locations.append(l)
else:
l = self.paste_all(edit, selection, selection.b + offset + 1,
fragment, count)
paste_locations.append(l)
offset += len(fragment) * count
if pasting_linewise:
self.reset_carets_linewise(paste_locations)
else:
self.reset_carets_charwise(paste_locations, len(fragment))
self.enter_normal_mode(mode)
def reset_carets_charwise(self, pts, paste_len):
# FIXME: Won't work for multiple jagged pastes...
b_pts = [s.b for s in list(self.view.sel())]
if len(b_pts) > 1:
self.view.sel().clear()
self.view.sel().add_all([R(ploc + paste_len - 1,
ploc + paste_len - 1)
for ploc in pts])
else:
self.view.sel().clear()
self.view.sel().add(R(pts[0] + paste_len - 1,
pts[0] + paste_len - 1))
def reset_carets_linewise(self, pts):
self.view.sel().clear()
if self.state.mode == modes.VISUAL_LINE:
self.view.sel().add_all([R(loc) for loc in pts])
return
pts = [utils.next_non_white_space_char(self.view, pt + 1)
for pt in pts]
self.view.sel().add_all([R(pt) for pt in pts])
def prepare_fragment(self, text):
if text.endswith('\n') and text != '\n':
text = '\n' + text[0:-1]
return text
# TODO: Improve this signature.
def paste_all(self, edit, sel, at, text, count):
state = self.state
if state.mode not in (modes.VISUAL, modes.VISUAL_LINE):
# TODO: generate string first, then insert?
# Make sure we can paste at EOF.
at = at if at <= self.view.size() else self.view.size()
for x in range(count):
self.view.insert(edit, at, text)
return at
else:
if text.startswith('\n'):
text = text * count
if not text.endswith('\n'):
text = text + '\n'
else:
text = text * count
if state.mode == modes.VISUAL_LINE:
if text.startswith('\n'):
text = text[1:]
self.view.replace(edit, sel, text)
return sel.begin()
class _vi_gt(ViWindowCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, count=1, mode=None):
self.window.run_command('tab_control', {'command': 'next'})
self.window.run_command('_enter_normal_mode', {'mode': mode})
class _vi_g_big_t(ViWindowCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, count=1, mode=None):
self.window.run_command('tab_control', {'command': 'prev'})
self.window.run_command('_enter_normal_mode', {'mode': mode})
class _vi_ctrl_w_q(IrreversibleTextCommand):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, count=1, mode=None):
if self.view.is_dirty():
sublime.status_message('Unsaved changes.')
return
self.view.close()
class _vi_ctrl_w_v(ViWindowCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, count=1, mode=None):
self.window.run_command('ex_vsplit')
class _vi_ctrl_w_l(ViWindowCommandBase):
# TODO: Should be a window command instead.
# TODO: Should focus the group to the right only, not the 'next' group.
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, mode=None, count=None):
current_group = self.window.active_group()
if self.window.num_groups() > 1:
self.window.focus_group(current_group + 1)
class _vi_ctrl_w_big_l(ViWindowCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, mode=None, count=1):
current_group = self.window.active_group()
if self.window.num_groups() > 1:
self.window.set_view_index(self.view, current_group + 1, 0)
self.window.focus_group(current_group + 1)
class _vi_ctrl_w_h(ViWindowCommandBase):
# TODO: Should be a window command instead.
# TODO: Should focus the group to the left only, not the 'previous' group.
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, mode=None, count=1):
current_group = self.window.active_group()
if current_group > 0:
self.window.focus_group(current_group - 1)
class _vi_ctrl_w_big_h(ViWindowCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, mode=None, count=1):
current_group = self.window.active_group()
if current_group > 0:
self.window.set_view_index(self.view, current_group - 1, 0)
self.window.focus_group(current_group - 1)
# TODO: z<CR> != zt
class _vi_z_enter(IrreversibleTextCommand):
'''
Command: z<cr>
http://vimdoc.sourceforge.net/htmldoc/scroll.html#z<CR>
'''
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, count=1, mode=None):
pt = resolve_insertion_point_at_b(first_sel(self.view))
home_line = self.view.line(pt)
taget_pt = self.view.text_to_layout(home_line.begin())
self.view.set_viewport_position(taget_pt)
class _vi_z_minus(IrreversibleTextCommand):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, count=1, mode=None):
layout_coord = self.view.text_to_layout(first_sel(self.view).b)
viewport_extent = self.view.viewport_extent()
new_pos = (0.0, layout_coord[1] - viewport_extent[1])
self.view.set_viewport_position(new_pos)
class _vi_zz(IrreversibleTextCommand):
def __init__(self, view):
IrreversibleTextCommand.__init__(self, view)
def run(self, count=1, mode=None):
first_sel = self.view.sel()[0]
current_position = self.view.text_to_layout(first_sel.b)
viewport_dim = self.view.viewport_extent()
new_pos =(0.0, current_position[1] - viewport_dim[1] / 2)
self.view.set_viewport_position(new_pos)
class _vi_modify_numbers(ViTextCommandBase):
"""
Base class for Ctrl-x and Ctrl-a.
"""
DIGIT_PAT = re.compile('(\D+?)?(-)?(\d+)(\D+)?')
NUM_PAT = re.compile('\d')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def get_editable_data(self, pt):
sign = -1 if (self.view.substr(pt - 1) == '-') else 1
end = pt
while self.view.substr(end).isdigit():
end += 1
return (sign, int(self.view.substr(R(pt, end))),
R(end, self.view.line(pt).b))
def find_next_num(self, regions):
# Modify selections that are inside a number already.
for i, r in enumerate(regions):
a = r.b
if self.view.substr(r.b).isdigit():
while self.view.substr(a).isdigit():
a -=1
regions[i] = R(a)
lines = [self.view.substr(R(r.b, self.view.line(r.b).b)) for r in regions]
matches = [_vi_modify_numbers.NUM_PAT.search(text) for text in lines]
if all(matches):
return [(reg.b + ma.start()) for (reg, ma) in zip(regions, matches)]
return []
def run(self, edit, count=1, mode=None, subtract=False):
if mode != modes.INTERNAL_NORMAL:
return
# TODO: Deal with octal, hex notations.
# TODO: Improve detection of numbers.
regs = list(self.view.sel())
pts = self.find_next_num(regs)
if not pts:
utils.blink()
return
count = count if not subtract else -count
end_sels = []
for pt in reversed(pts):
sign, num, tail = self.get_editable_data(pt)
num_as_text = str((sign * num) + count)
new_text = num_as_text + self.view.substr(tail)
offset = 0
if sign == -1:
offset = -1
self.view.replace(edit, R(pt - 1, tail.b), new_text)
else:
self.view.replace(edit, R(pt, tail.b), new_text)
rowcol = self.view.rowcol(pt + len(num_as_text) - 1 + offset)
end_sels.append(rowcol)
self.view.sel().clear()
for (row, col) in end_sels:
self.view.sel().add(R(self.view.text_point(row, col)))
class _vi_select_big_j(IrreversibleTextCommand):
"""
Active in select mode. Clears multiple selections and returns to normal
mode. Should be more convenient than having to reach for Esc.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, mode=None, count=1):
s = self.view.sel()[0]
self.view.sel().clear()
self.view.sel().add(s)
self.view.run_command('_enter_normal_mode', {'mode': mode})
class _vi_big_j(ViTextCommandBase):
WHITE_SPACE = ' \t'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, separator=' ', count=1):
sels = self.view.sel()
s = R(sels[0].a, sels[-1].b)
if mode == modes.INTERNAL_NORMAL:
end_pos = self.view.line(s.b).b
start = end = s.b
if count > 2:
end = self.view.text_point(utils.row_at(self.view, s.b) + (count - 1), 0)
end = self.view.line(end).b
else:
# Join current line and the next.
end = self.view.text_point(utils.row_at(self.view, s.b) + 1, 0)
end = self.view.line(end).b
elif mode in [modes.VISUAL, modes.VISUAL_LINE, modes.VISUAL_BLOCK]:
if s.a < s.b:
end_pos = self.view.line(s.a).b
start = s.a
if utils.row_at(self.view, s.b - 1) == utils.row_at(self.view, s.a):
end = self.view.text_point(utils.row_at(self.view, s.a) + 1, 0)
else:
end = self.view.text_point(utils.row_at(self.view, s.b - 1), 0)
end = self.view.line(end).b
else:
end_pos = self.view.line(s.b).b
start = s.b
if utils.row_at(self.view, s.b) == utils.row_at(self.view, s.a - 1):
end = self.view.text_point(utils.row_at(self.view, s.a - 1) + 1, 0)
else:
end = self.view.text_point(utils.row_at(self.view, s.a - 1), 0)
end = self.view.line(end).b
else:
return s
text_to_join = self.view.substr(R(start, end))
lines = text_to_join.split('\n')
if separator:
# J
joined_text = lines[0]
for line in lines[1:]:
line = line.lstrip()
if joined_text and joined_text[-1] not in self.WHITE_SPACE:
line = ' ' + line
joined_text += line
else:
# gJ
joined_text = ''.join(lines)
self.view.replace(edit, R(start, end), joined_text)
sels.clear()
sels.add(R(end_pos))
class _vi_gv(IrreversibleTextCommand):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, mode=None, count=None):
sels = self.view.get_regions('visual_sel')
if not sels:
return
self.view.window().run_command('_enter_visual_mode', {'mode': mode})
self.view.sel().clear()
self.view.sel().add_all(sels)
class _vi_ctrl_e(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1):
# TODO: Implement this motion properly; don't use built-in commands.
# We're using an action because we don't care too much right now and we don't want the
# motion to utils.blink every time we issue it (it does because the selections don't change and
# Vintageous rightfully thinks it has failed.)
if mode == modes.VISUAL_LINE:
return
extend = True if mode == modes.VISUAL else False
self.view.run_command('scroll_lines', {'amount': -1, 'extend': extend})
class _vi_ctrl_y(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1):
# TODO: Implement this motion properly; don't use built-in commands.
# We're using an action because we don't care too much right now and we don't want the
# motion to utils.blink every time we issue it (it does because the selections don't change and
# Vintageous rightfully thinks it has failed.)
if mode == modes.VISUAL_LINE:
return
extend = True if mode == modes.VISUAL else False
self.view.run_command('scroll_lines', {'amount': 1, 'extend': extend})
class _vi_ctrl_r_equal(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, insert=False, next_mode=None):
def on_done(s):
state = State(self.view)
try:
rv = [str(eval(s, None, None)),]
if not insert:
state.registers[REG_EXPRESSION] = rv
else:
self.view.run_command('insert_snippet', {'contents': str(rv[0])})
state.reset()
except:
sublime.status_message("Vintageous: Invalid expression.")
on_cancel()
def on_cancel():
state = State(self.view)
state.reset()
self.view.window().show_input_panel('', '', on_done, None, on_cancel)
class _vi_q(IrreversibleTextCommand):
_register_name = None
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, name=None, mode=None, count=1):
state = State(self.view)
if state.is_recording:
State.macro_registers[_vi_q._register_name] = list(State.macro_steps)
state.stop_recording()
_vi_q._register_name = None
return
# TODO(guillermooo): What happens when we change views?
state.start_recording()
_vi_q._register_name = name
class _vi_at(IrreversibleTextCommand):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, name=None, mode=None, count=1):
# TODO(guillermooo): Do we need to glue all these edits?
cmds = State.macro_steps
if name != '@':
try:
cmds = State.macro_registers[name]
State.macro_steps = cmds
except ValueError as e:
print('Vintageous: error: %s' % e)
return
state = State(self.view)
for cmd, args in cmds:
# TODO(guillermooo): Is this robust enough?
if 'xpos' in args:
state.update_xpos(force=True)
args['xpos'] = State(self.view).xpos
elif args.get('motion') and 'xpos' in args.get('motion'):
state.update_xpos(force=True)
motion = args.get('motion')
motion['motion_args']['xpos'] = State(self.view).xpos
args['motion'] = motion
self.view.run_command(cmd, args)
class _enter_visual_block_mode(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None):
def f(view, s):
return R(s.b, s.b + 1)
if mode in (modes.VISUAL_LINE,):
return
if mode == modes.VISUAL_BLOCK:
self.enter_normal_mode(mode)
return
if mode == modes.VISUAL:
first = utils.first_sel(self.view)
if self.view.line(first.end() - 1).empty():
self.enter_normal_mode(mode)
utils.blink()
return
self.view.sel().clear()
lhs_edge = self.view.rowcol(first.b)[1]
regs = self.view.split_by_newlines(first)
offset_a, offset_b = self.view.rowcol(first.a)[1], self.view.rowcol(first.b)[1]
min_offset_x = min(offset_a, offset_b)
max_offset_x = max(offset_a, offset_b)
new_regs = []
for r in regs:
if r.empty():
break
row, _ = self.view.rowcol(r.end() - 1)
a = self.view.text_point(row, min_offset_x)
eol = self.view.rowcol(self.view.line(r.end() - 1).b)[1]
b = self.view.text_point(row, min(max_offset_x, eol))
if first.a <= first.b:
if offset_b < offset_a:
new_r = R(a - 1, b + 1, eol)
else:
new_r = R(a, b, eol)
elif offset_b < offset_a:
new_r = R(a, b, eol)
else:
new_r = R(a - 1, b + 1, eol)
new_regs.append(new_r)
if not new_regs:
new_regs.append(first)
self.view.sel().add_all(new_regs)
state = State(self.view)
state.enter_visual_block_mode()
return
# Handling multiple visual blocks seems quite hard, so ensure we only
# have one.
first = list(self.view.sel())[0]
self.view.sel().clear()
self.view.sel().add(first)
state = State(self.view)
state.enter_visual_block_mode()
if not self.view.has_non_empty_selection_region():
regions_transformer(self.view, f)
class _vi_select_j(ViWindowCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, count=1, mode=None):
if mode != modes.SELECT:
raise ValueError('wrong mode')
for i in range(count):
self.window.run_command('find_under_expand')
class _vi_tilde(ViTextCommandBase):
"""
Implemented as if 'notildeopt' was `True`.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, count=1, mode=None, motion=None):
def select(view, s):
if mode == modes.VISUAL:
return R(s.end(), s.begin())
return R(s.begin(), s.end() + count)
def after(view, s):
return R(s.begin())
regions_transformer(self.view, select)
self.view.run_command('swap_case')
if mode in (modes.VISUAL, modes.VISUAL_LINE, modes.VISUAL_BLOCK):
regions_transformer(self.view, after)
self.enter_normal_mode(mode)
class _vi_g_tilde(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, count=1, mode=None, motion=None):
def f(view, s):
return R(s.end(), s.begin())
if motion:
self.save_sel()
self.view.run_command(motion['motion'], motion['motion_args'])
if not self.has_sel_changed():
utils.blink()
self.enter_normal_mode(mode)
return
self.view.run_command('swap_case')
if motion:
regions_transformer(self.view, f)
self.enter_normal_mode(mode)
class _vi_visual_u(ViTextCommandBase):
"""
'u' action in visual modes.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1):
for s in self.view.sel():
self.view.replace(edit, s, self.view.substr(s).lower())
def after(view, s):
return R(s.begin())
regions_transformer(self.view, after)
self.enter_normal_mode(mode)
class _vi_visual_big_u(ViTextCommandBase):
"""
'U' action in visual modes.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1):
for s in self.view.sel():
self.view.replace(edit, s, self.view.substr(s).upper())
def after(view, s):
return R(s.begin())
regions_transformer(self.view, after)
self.enter_normal_mode(mode)
class _vi_g_tilde_g_tilde(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, count=1, mode=None):
def select(view, s):
l = view.line(s.b)
return R(l.end(), l.begin())
if mode != modes.INTERNAL_NORMAL:
raise ValueError('wrong mode')
regions_transformer(self.view, select)
self.view.run_command('swap_case')
# Ensure we leave the sel .b end where we want it.
regions_transformer(self.view, select)
self.enter_normal_mode(mode)
class _vi_g_big_u_big_u(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1):
def select(view, s):
return units.lines(view, s, count)
def to_upper(view, s):
view.replace(edit, s, view.substr(s).upper())
return R(s.a)
regions_transformer(self.view, select)
regions_transformer(self.view, to_upper)
self.enter_normal_mode(mode)
class _vi_guu(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1):
def select(view, s):
l = view.line(s.b)
return R(l.end(), l.begin())
def to_lower(view, s):
view.replace(edit, s, view.substr(s).lower())
return s
regions_transformer(self.view, select)
regions_transformer(self.view, to_lower)
self.enter_normal_mode(mode)
class _vi_g_big_h(ViWindowCommandBase):
"""
Non-standard command.
After a search has been performed via '/' or '?', selects all matches and
enters select mode.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, mode=None, count=1):
view = self.window.active_view()
regs = view.get_regions('vi_search')
if regs:
view.sel().add_all(view.get_regions('vi_search'))
self.state.enter_select_mode()
self.state.display_status()
return
utils.blink()
sublime.status_message('Vintageous: No available search matches')
self.state.reset_command_data()
class _vi_ctrl_x_ctrl_l(ViTextCommandBase):
"""
http://vimdoc.sourceforge.net/htmldoc/insert.html#i_CTRL-X_CTRL-L
"""
MAX_MATCHES = 20
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def find_matches(self, prefix, end):
escaped = re.escape(prefix)
matches = []
while end > 0:
match = search.reverse_search(self.view,
r'^\s*{0}'.format(escaped),
0, end, flags=0)
if (match is None) or (len(matches) == self.MAX_MATCHES):
break
line = self.view.line(match.begin())
end = line.begin()
text = self.view.substr(line).lstrip()
if text not in matches:
matches.append(text)
return matches
def run(self, edit, mode=None, register='"'):
# TODO: Must exit to insert mode. As we're using a quick panel, the
# mode is being reset in _init_vintageous.
assert mode == modes.INSERT, 'bad mode'
if (len(self.view.sel()) > 1 or
not self.view.sel()[0].empty()):
utils.blink()
return
s = self.view.sel()[0]
line_begin = self.view.text_point(utils.row_at(self.view, s.b), 0)
prefix = self.view.substr(R(line_begin, s.b)).lstrip()
self._matches = self.find_matches(prefix, end=self.view.line(s.b).a)
if self._matches:
self.show_matches(self._matches)
state = State(self.view)
state.reset_during_init = False
state.reset_command_data()
return
utils.blink()
def show_matches(self, items):
self.view.window().show_quick_panel(items, self.replace,
sublime.MONOSPACE_FONT)
def replace(self, s):
self.view.run_command('__replace_line',
{'with_what': self._matches[s]})
del self.__dict__['_matches']
pt = self.view.sel()[0].b
self.view.sel().clear()
self.view.sel().add(R(pt))
class __replace_line(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, with_what):
b = self.view.line(self.view.sel()[0].b).a
pt = utils.next_non_white_space_char(self.view, b, white_space=' \t')
self.view.replace(edit, R(pt, self.view.line(pt).b),
with_what)
class _vi_gc(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, motion=None):
def f(view, s):
return R(s.begin())
if motion:
self.view.run_command(motion['motion'], motion['motion_args'])
elif mode not in (modes.VISUAL, modes.VISUAL_LINE):
utils.blink()
return
self.view.run_command('toggle_comment', {'block': False})
regions_transformer(self.view, f)
self.enter_normal_mode(mode)
class _vi_g_big_c(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, motion=None):
def f(view, s):
return R(s.begin())
if motion:
self.view.run_command(motion['motion'], motion['motion_args'])
elif mode not in (modes.VISUAL, modes.VISUAL_LINE):
utils.blink()
return
self.view.run_command('toggle_comment', {'block': True})
regions_transformer(self.view, f)
self.enter_normal_mode(mode)
class _vi_gcc_action(ViTextCommandBase):
_can_yank = True
_synthetize_new_line_at_eof = True
_yanks_linewise = False
_populates_small_delete_register = False
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1):
def f(view, s):
if mode == modes.INTERNAL_NORMAL:
view.run_command('toggle_comment')
if utils.row_at(self.view, s.a) != utils.row_at(self.view, self.view.size()):
pt = utils.next_non_white_space_char(view, s.a, white_space=' \t')
else:
pt = utils.next_non_white_space_char(view,
self.view.line(s.a).a,
white_space=' \t')
return R(pt, pt)
return s
self.view.run_command('_vi_gcc_motion', {'mode': mode, 'count': count})
state = self.state
state.registers.yank(self)
row = [self.view.rowcol(s.begin())[0] for s in self.view.sel()][0]
regions_transformer_reversed(self.view, f)
self.view.sel().clear()
self.view.sel().add(R(self.view.text_point(row, 0)))
class _vi_gcc_motion(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1):
def f(view, s):
if mode == modes.INTERNAL_NORMAL:
end = view.text_point(utils.row_at(self.view, s.b) + (count - 1), 0)
begin = view.line(s.b).a
if ((utils.row_at(self.view, end) == utils.row_at(self.view, view.size())) and
(view.substr(begin - 1) == '\n')):
begin -= 1
return R(begin, view.full_line(end).b)
return s
regions_transformer(self.view, f)
| {
"repo_name": "himacro/Vintageous",
"path": "xactions.py",
"copies": "5",
"size": "97859",
"license": "mit",
"hash": -3382807985632849400,
"line_mean": 33.3124123422,
"line_max": 138,
"alpha_frac": 0.5296293647,
"autogenerated": false,
"ratio": 3.83896277117414,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0007210096181572569,
"num_lines": 2852
} |
from functools import partial
import re
"""
This class is used to simulate MIPS. It does several things:
1) Binds variable names to registers
2) Verification of variable bindings
3) simulate the stack in a MIPS processer.
"""
class RegisterNotDefined(Exception):
def __init__(self, register):
self.value = register
def __str_(self):
return repr(self.value)
class StackPointerOutOfBoundsError(Exception):
def __init__(self, amount):
self.value = amount
def __str__(self):
return 'Placement of element: ' + str(self.value)
class StackElementNotBoundedError(Exception):
def __init__(self, stackLocation):
self.value = stackLocation
class MIPSRegisters:
def __init__(self):
self.register_names = ['$v0', '$v1', '$zero', '$a0', '$a1', '$a2', '$a3', '$t0', '$t1', '$t2', '$t3', '$t4', '$t5', '$t6', '$t7', '$s0', '$s1', '$s2', '$s3', '$s4', '$s5', '$s6', '$s7', '$t8', '$t9', '$ra']
self.registers = {register_name:'' for register_name in register_names}
def bindRegister(self, register, variableName):
if register in self.register_names:
self.registers[register] = variableName
else:
raise RegisterNotDefined(register)
def unbindRegister(self, register):
if register in self.registers_names:
self.registers[register] = ''
else:
raise RegisterNotDefined(register)
def verifyRegisterBinding(self, register, variableName):
if register not in self.register_names:
raise RegisterNotDefined(register)
else:
if self.registers[register] == variableName:
return True
else:
return False
"""
This holds the stack, as well as what the stack pointer is pointing to
"""
class MIPStack:
#stacksize is the size of the stack in bytes
def __init__(self, stackSize):
self.stack = dict()
self.stackPointer = 0
#stack size is in bytes, but let's convert it to elements
self.stackSize = stackSize/4
def addToStackPointer(self, amount):
"""
You use this method to change where the stack pointer is. For example, if we were at an instruction like:
addi $sp, $sp, -8
This call would usually be used to push two items to the stack. You would call addToStackPointer(-8)
Args:
amount: The number of bytes to move the stack by.
Raises:
StackPointerOutOfBoundsError: If the movement of the stack pointer would place it before or after the bounds of the stack.
"""
#Divide by -4.
numElements = amount/-4
stackLocation = self.stackPointer + numElements
if stackLocation < 0 or stackLocation >= stackSize:
raise StackPointerOutOfBoundsError(stackLocation)
else:
self.stackPointer = stackLocation
def bindStackElement(self, stackPointerOffset, varName):
""" Binds an element of the MIPS stack to a variable name.
Args:
stackPointerOffset: The offset of the stack pointer (the same value as if you were placing a value into that part of the stack)
varName: The name to bind the element to.
Raises:
StackPointerOutOfBoundsError: If the stack element is out of the bounds of the stack.
"""
numElements = stackPointerOffset/-4
elementLocation = self.stackPointer + numElements
if elementLocation < 0 or elementLocation >= self.stackSize:
raise StackPointerOutOfBoundsError(elementLocation)
else:
self.stack[elementLocation] = varName
def unbindStackElement(self, stackPointerOffset):
""" Unbinds an element of the MIPS stack from a variable name.
Args:
stackPointerOffset: The offset of the stack pointer (the same value as if you were placing a value into that part of the stack)
Raises:
StackPointerOutOfBoundsError: If the stack element is out of the bounds of the stack
StackElementNotBoundedError: If the stack element isn't bound to a variable name
"""
numElements = stackPointerOffset/-4
elementLocation = self.stackPointer + numElements
if elementLocation < 0 or elementLocation >= self.stackSize:
raise StackPointerOutOfBoundsError(elementLocation)
else:
try:
self.stack.pop(elementLocation)
except KeyError:
raise StackElementNotBoundedError(self.stackPointerOffset)
def verifyStackElementBinding(self, stackPointerOffset, variableName):
""" Use this method to verify that a stack element is bound to a given variable.
Args:
stackPointerOffset: The offset of the stack pointer
variableName: Check that the stack element is bound to the given variable
Returns:
True if the stack element is bounded to the given variable, false if it is bound to a different variable, and
Raises:
StackPointerOutOfBoundsError: If the stack element is out of the bounds of the stack
StackElementNotBoundedError: If the stack element isn't bound to a variable name
"""
numElements = stackPointerOffset/-4
elementLocation = self.stackPointer + numElements
if elementLocation < 0 or elementLocation >= self.stackSize:
raise StackPointerOutOfBoundsError(elementLocation)
else:
try:
varName = self.stack[elementLocation]
return (varName == variableName)
except KeyError:
raise StackElementNotBoundedError(self.stackPointerOffset)
def getStackElementBinding(self, stackPointerOffset):
""" Use this method to get the variable name that stack element is bound to.
Args:
stackPointerOffset: The offset of the stack pointer
Returns:
Returns the binding if the stack element is bound to something. Raises a StackElementNotBoundedError if the element is not bound to anything.
Raises:
StackPointerOutOfBoundsError: If the stack element is out of the bounds of the stack
StackElementNotBoundedError: If the stack element isn't bound to a variable name
"""
numElements = stackPointerOffset/-4
elementLocation = self.stackPointer + numElements
if elementLocation < 0 or elementLocation >= self.stackSize:
raise StackPointerOutOfBoundsError(elementLocation)
else:
try:
varName = self.stack[elementLocation]
return varName
except KeyError:
raise StackElementNotBoundedError(self.stackPointerOffset)
class MIPSMemory:
def __init__(self, registers, stack):
self.registers = registers
self.stack = stack
def getRegisters(self):
return self.registers
def getStack(self):
return self.stack
def bindRegister(register, varName, mipsMemory):
#todo: fill this in
pass
def bindStackElement(stackLocation, varName, mipsMemory):
#todo: fill this in
pass
def parseComment(comment):
"""
Args:
comment: the comment; a string.
Returns:
A list of functions to execute. Can be empty. The arg of each function is an instance of the MIPSMemory class
Raises:
BadElementError -- if the element given by a bind, verify or unbind statement is non-sensical.
"""
bindRe = re.compile('\$BIND:([^\:]*):(\S+)') #We should allow for some space in the element location (especially if we're accessing the stack)
unbindRe = re.compile('\$UNBIND:(\S+)')
verifyRe = re.compile('\$VERIFY:([^\:]*):(\S+)')
isStackElementRe = re.compile('\s*(\d+)\s*\(\s*(\S{,5})\s*\)')
actions = list() # a list of tuples, of format (charIndex, actionFuntion)
registers = ['$v0', '$v1', '$zero', '$a0', '$a1', '$a2', '$a3', '$t0', '$t1', '$t2', '$t3', '$t4', '$t5', '$t6', '$t7', '$s0', '$s1', '$s2', '$s3', '$s4', '$s5', '$s6', '$s7', '$t8', '$t9', '$ra']
for m in bindRe.finditer(comment):
charIndex = m.start(1)
element = m.group(1)
varName = m.group(2)
#if element is one of the registers, then create a bindRegister partial function
if varName in registers:
actions.append(partial(bindRegister, register=element, varName=varName))
else:
stackElement = isStackElementRe.match(element)
if
unbinds = [(m.start(1), m.group(1)) for m in unbindRe.finditer(comment)]
verifies = [(m.start(1), m.group(1), m.group(2)) for m in verifyRe.finditer(comment)]
class MIPSMachine:
| {
"repo_name": "mrForce/VarSPIM",
"path": "MIPSMachine.py",
"copies": "1",
"size": "8972",
"license": "mit",
"hash": 5394025578687420000,
"line_mean": 35.1774193548,
"line_max": 214,
"alpha_frac": 0.6238296924,
"autogenerated": false,
"ratio": 4.272380952380952,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.017241411559178358,
"num_lines": 248
} |
from functools import partial
import requests
DEFAULT_ROOT_RES_PATH = '/'
class HTTPResponse(object):
"""
Wrapper around :class:`requests.Response`.
Parses ``Content-Type`` header and makes it available as a list of fields
in the :attr:`content_type` member.
"""
def __init__(self, raw_response):
self.raw_response = raw_response
content_type = raw_response.headers.get('content-type', '')
ct_fields = [f.strip() for f in content_type.split(';')]
self.content_type = ct_fields
def __getattr__(self, name):
return getattr(self.raw_response, name)
class HTTPClient(object):
"""
Convenience wrapper around Requests.
:param str endpoint: URL for the API endpoint. E.g. ``https://blah.org``.
:param dict extra_headers: When specified, these key-value pairs are added
to the default HTTP headers passed in with each request.
"""
def __init__(
self,
endpoint='',
extra_headers=None,
):
self.endpoint = endpoint
s = requests.session()
# Disable keepalives. They're unsafe in threaded apps that potentially
# re-use very old connection objects from the urllib3 connection pool.
s.headers['Accept'] = 'application/json'
s.headers['Connection'] = 'close'
if extra_headers:
s.headers.update(extra_headers)
self.s = s
# convenience methods
self.delete = partial(self.request, 'delete')
self.get = partial(self.request, 'get')
self.head = partial(self.request, 'head')
self.post = partial(self.request, 'post')
self.put = partial(self.request, 'put')
def request(self, method, path='/', url=None, ignore_codes=[], **kwargs):
"""
Performs HTTP request.
:param str method: An HTTP method (e.g. 'get', 'post', 'PUT', etc...)
:param str path: A path component of the target URL. This will be
appended to the value of ``self.endpoint``. If both :attr:`path`
and :attr:`url` are specified, the value in :attr:`url` is used and
the :attr:`path` is ignored.
:param str url: The target URL (e.g. ``http://server.tld/somepath/``).
If both :attr:`path` and :attr:`url` are specified, the value in
:attr:`url` is used and the :attr:`path` is ignored.
:param ignore_codes: List of HTTP error codes (e.g. 404, 500) that
should be ignored. If an HTTP error occurs and it is *not* in
:attr:`ignore_codes`, then an exception is raised.
:type ignore_codes: list of int
:param kwargs: Any other kwargs to pass to :meth:`requests.request()`.
Returns a :class:`requests.Response` object.
"""
_url = url if url else (self.endpoint + path)
r = self.s.request(method, _url, **kwargs)
if not r.ok and r.status_code not in ignore_codes:
r.raise_for_status()
return HTTPResponse(r)
| {
"repo_name": "diranged/python-rightscale-1",
"path": "rightscale/httpclient.py",
"copies": "1",
"size": "3055",
"license": "mit",
"hash": -6655988466710524000,
"line_mean": 32.5714285714,
"line_max": 79,
"alpha_frac": 0.6,
"autogenerated": false,
"ratio": 3.99869109947644,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.509869109947644,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import sdl2ui
import sdl2ui.mixins
from meldnafen.config.controls import Controls
from .list_roms import ListRoms
from .menu import Menu
class Emulator(sdl2ui.Component, sdl2ui.mixins.ImmutableMixin):
def init(self):
self.logger.debug(
"Loading emulator %s: %d players",
self.props['console'],
self.props['players_number'])
self.list = self.add_component(ListRoms,
show_menu=self.show_menu,
hide_menu=self.hide_menu,
**self.props)
self.menu = self.add_component(Menu,
menu=self.generate_menu(),
highlight=self.props['highlight'],
line_space=10,
x=self.props['x'],
y=self.props['y'],
on_quit=self.hide_menu)
self.load_joystick_components()
self.list.enable()
def load_joystick_components(self):
self.joystick_configure = {}
for player in range(1, self.props['players_number'] + 1):
controls = self.props['controls'].copy()
if player == 1:
controls.extend([
("enable_hotkey", "Emulator Hotkey"),
("menu_toggle",
"Emulator Menu (after pressing the hotkey)"),
])
# NOTE: add the component to self.app, we don't want it to be
# deactivated when the rest of the application is disabled
self.joystick_configure[str(player)] = self.app.add_component(
Controls,
line_space=10,
on_finish=self.finish_joystick_configuration,
controls=controls,
x=self.props['x'],
y=self.props['y'])
def show_menu(self, vars):
self.menu.start(vars)
self.list.disable()
self.props['on_menu_activated']()
def hide_menu(self):
self.menu.disable()
self.list.enable()
self.props['on_menu_deactivated']()
def generate_menu(self):
return [
("Controls", "submenu", [
("Controls: {}".format(self.props['name']),
"submenu", [
("Configure player %s" % i, "call",
partial(self.confgure_controls,
target='console', player=str(i)))
for i in range(1, self.props['players_number'] + 1)
]),
("Controls: {game}",
"submenu", [
("Configure player %s" % i, "call",
partial(self.confgure_controls,
target='game', player=str(i)))
for i in range(1, self.props['players_number'] + 1)
] + [
("Clear all", "call", self.remove_game_controls),
]),
("Controls: {app.name}", "call",
self.app.activate_joystick_configuration)
]),
("Smooth: {app.settings[smooth]}", "call", self.app.toggle_smooth),
("FPS: {app.debugger.active}", "call", self.app.debugger.toggle),
]
def confgure_controls(self, **kwargs):
self.app.lock()
self.joystick_configure[kwargs['player']].start(**kwargs)
def finish_joystick_configuration(self, **kwargs):
if kwargs:
self.update_joystick_configuration(**kwargs)
self.app.unlock()
def update_joystick_configuration(self,
joystick=None, player=None, target=None, config=None):
if target == 'console':
self.app.settings.setdefault('controls', {})\
.setdefault(target, {})\
.setdefault(self.props['console'], {})\
.setdefault(player, {})\
[joystick.guid] = config
else:
self.app.settings.setdefault('controls', {})\
.setdefault(target, {})\
.setdefault(self.props['console'], {})\
.setdefault(self.list.game, {})\
.setdefault(player, {})\
[joystick.guid] = config
def remove_game_controls(self):
self.app.settings['controls']\
.setdefault('game', {})\
.pop(self.props['console'], None)
self.hide_menu()
| {
"repo_name": "cecton/meldnafen",
"path": "meldnafen/emulator/__init__.py",
"copies": "1",
"size": "4391",
"license": "mit",
"hash": 846114970417691500,
"line_mean": 37.1826086957,
"line_max": 79,
"alpha_frac": 0.5055795946,
"autogenerated": false,
"ratio": 4.209971236816874,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0018388220435971302,
"num_lines": 115
} |
from functools import partial
import simplejson as json
import os
import tempfile
from celery.exceptions import RetryTaskError
from celery.task import task
import pandas as pd
from bamboo.lib.async import call_async
from bamboo.lib.datetools import recognize_dates
from bamboo.lib.schema_builder import filter_schema
@task(ignore_result=True)
def import_dataset(dataset, file_reader, delete=False):
"""For reading a URL and saving the corresponding dataset.
Import a DataFrame using the provided `file_reader` function. All
exceptions are caught and on exception the dataset is marked as failed and
set for deletion after 24 hours.
:param dataset: The dataset to import into.
:param file_reader: Function for reading the dataset.
:param delete: Delete filepath_or_buffer after import, default False.
"""
try:
dframe = file_reader()
dataset.save_observations(dframe)
except Exception as e:
if isinstance(e, RetryTaskError):
raise e
else:
dataset.failed(e.__str__())
dataset.delete(countdown=86400)
def csv_file_reader(name, na_values=[], delete=False):
try:
return recognize_dates(
pd.read_csv(name, encoding='utf-8', na_values=na_values))
finally:
if delete:
os.unlink(name)
def json_file_reader(content):
return recognize_dates(pd.DataFrame(json.loads(content)))
class ImportableDataset(object):
def import_from_url(self, url, na_values=[], allow_local_file=False):
"""Load a URL, read from a CSV, add data to dataset.
:param url: URL to load file from.
:param allow_local_file: Allow URL to refer to a local file.
:raises: `IOError` for an unreadable file or a bad URL.
:returns: The created dataset.
"""
if not allow_local_file and isinstance(url, basestring)\
and url[0:4] == 'file':
raise IOError
call_async(
import_dataset, self, partial(
csv_file_reader, url, na_values=na_values))
return self
def import_from_csv(self, csv_file, na_values=[]):
"""Import data from a CSV file.
.. note::
Write to a named tempfile in order to get a handle for pandas'
`read_csv` function.
:param csv_file: The CSV File to create a dataset from.
:returns: The created dataset.
"""
if 'file' in dir(csv_file):
csv_file = csv_file.file
tmpfile = tempfile.NamedTemporaryFile(delete=False)
tmpfile.write(csv_file.read())
# pandas needs a closed file for *read_csv*
tmpfile.close()
call_async(import_dataset, self, partial(
csv_file_reader, tmpfile.name, na_values=na_values, delete=True))
return self
def import_from_json(self, json_file):
"""Impor data from a JSON file.
:param json_file: JSON file to import.
"""
content = json_file.file.read()
call_async(import_dataset, self, partial(json_file_reader, content))
return self
def import_schema(self, schema):
"""Create a dataset from a SDF schema file (JSON).
:param schema: The SDF (JSON) file to create a dataset from.
:returns: The created dataset.
"""
try:
schema = json.loads(schema.file.read())
except AttributeError:
schema = json.loads(schema)
self.set_schema(filter_schema(schema))
self.ready()
return self
| {
"repo_name": "pld/bamboo",
"path": "bamboo/lib/readers.py",
"copies": "2",
"size": "3579",
"license": "bsd-3-clause",
"hash": -2309678361377404000,
"line_mean": 28.0975609756,
"line_max": 78,
"alpha_frac": 0.6275495949,
"autogenerated": false,
"ratio": 4.057823129251701,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.56853727241517,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import six
from django.conf import settings
from django.contrib.auth import get_permission_codename
from django_auth_ldap.backend import LDAPBackend
class NestedLDAPGroupsBackend(LDAPBackend):
use_reconnecting_client = getattr(
settings, 'BAYA_USE_RECONNECTING_CLIENT', False)
def _get_ldap(self):
if self.use_reconnecting_client:
if self._ldap is None:
ldap_module = super(NestedLDAPGroupsBackend, self).ldap
self._ldap = ReconnectingLDAP(ldap_module)
return self._ldap
else:
return super(NestedLDAPGroupsBackend, self).ldap
ldap = property(_get_ldap)
def get_all_permissions(self, user, obj=None):
"""Return a set of <app_label>.<permission> for this user.
Note that these results will only be applicable to the admin panel.
<permission> is something like add_mymodel or change_mymodel.
"""
if hasattr(user, '_baya_cached_all_permissions'):
return user._baya_cached_all_permissions
permissions = super(NestedLDAPGroupsBackend, self).get_all_permissions(
user, obj)
from baya.admin.sites import _admin_registry
for admin_site in _admin_registry:
for model, opts in six.iteritems(admin_site._registry):
app = model._meta.app_label
perm_name = partial(get_permission_codename, opts=model._meta)
if (hasattr(opts, 'user_has_add_permission') and
opts.user_has_add_permission(user)):
permissions.add("%s.%s" % (app, perm_name('add')))
if (hasattr(opts, 'user_has_change_permission') and
opts.user_has_change_permission(user)):
permissions.add("%s.%s" % (app, perm_name('change')))
if (hasattr(opts, 'user_has_delete_permission') and
opts.user_has_delete_permission(user)):
permissions.add("%s.%s" % (app, perm_name('delete')))
user._baya_cached_all_permissions = permissions
return permissions
class ReconnectingLDAP(object):
"""
An object that makes the standard ldap.initialize function use
ldap.ldapobject.ReconnectLDAPObject instead.
The django_auth_ldap library does not provide a simple way to
override how the LDAP connection is created. The actual method
that initiates the connection is on the _get_connection method
on the hidden _LDAPUser class.
Instances of this class take the original ldap module instance
and provide the same set of attributes, except that the initialize
attribute returns ReconnectLDAPObject instead of the original
initialize function (which just instantiates a SimpleLDAPObject).
"""
retry_max = 6
def __init__(self, original_module):
self._original_module = original_module
def __getattr__(self, name):
"""
Return the requested value from the original module.
This is called when ordinary attribute lookups fail.
Since initialize is defined below, it will not be called
for accesses to that attribute.
"""
return getattr(self._original_module, name)
def initialize(self, uri, bytes_mode=False):
# `bytes_mode` is used by `initialize` but not by
# `ReconnectLDAPObject`: since `ReconnectingLDAP` tries to mimic
# `initialize` by wrapping `ReconnectLDAPObject`, it makes sense that
# the kwarg would be accepted but discarded. As of version 1.6.1,
# there is only one call to `initialize` in `django-auth-ldap`, and the
# only kwarg used is `bytes_mode=False`.
return self._original_module.ldapobject.ReconnectLDAPObject(
uri, retry_max=self.retry_max)
| {
"repo_name": "counsyl/baya",
"path": "baya/backend.py",
"copies": "1",
"size": "3862",
"license": "mit",
"hash": -7457249613857194000,
"line_mean": 41.4395604396,
"line_max": 79,
"alpha_frac": 0.6481097877,
"autogenerated": false,
"ratio": 4.319910514541387,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5468020302241388,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import six
from google.appengine.ext import ndb
from google.appengine.ext.db import BadArgumentError, Timeout
from google.appengine.runtime import DeadlineExceededError
from graphql_relay import to_global_id
from graphql_relay.connection.connectiontypes import Edge
from graphene import Argument, Boolean, Int, String, Field, List, NonNull, Dynamic
from graphene.relay import Connection
from graphene.relay.connection import PageInfo, ConnectionField
from .registry import get_global_registry
__author__ = 'ekampf'
def generate_edges_page(ndb_iter, page_size, keys_only, edge_type):
edges = []
timeouts = 0
while len(edges) < page_size:
try:
entity = ndb_iter.next()
except StopIteration:
break
except Timeout:
timeouts += 1
if timeouts > 2:
break
continue
except DeadlineExceededError:
break
if keys_only:
# entity is actualy an ndb.Key and we need to create an empty entity to hold it
entity = edge_type._meta.fields['node']._type._meta.model(key=entity)
edges.append(edge_type(node=entity, cursor=ndb_iter.cursor_after().urlsafe()))
return edges
def connection_from_ndb_query(query, args=None, connection_type=None, edge_type=None, pageinfo_type=None,
transform_edges=None, context=None, **kwargs):
'''
A simple function that accepts an ndb Query and used ndb QueryIterator object(https://cloud.google.com/appengine/docs/python/ndb/queries#iterators)
to returns a connection object for use in GraphQL.
It uses array offsets as pagination,
so pagination will only work if the array is static.
'''
args = args or {}
connection_type = connection_type or Connection
edge_type = edge_type or Edge
pageinfo_type = pageinfo_type or PageInfo
full_args = dict(args, **kwargs)
first = full_args.get('first')
after = full_args.get('after')
has_previous_page = bool(after)
keys_only = full_args.get('keys_only', False)
batch_size = full_args.get('batch_size', 20)
page_size = first if first else full_args.get('page_size', 20)
start_cursor = ndb.Cursor(urlsafe=after) if after else None
ndb_iter = query.iter(produce_cursors=True, start_cursor=start_cursor, batch_size=batch_size, keys_only=keys_only, projection=query.projection)
edges = []
while len(edges) < page_size:
missing_edges_count = page_size - len(edges)
edges_page = generate_edges_page(ndb_iter, missing_edges_count, keys_only, edge_type)
edges.extend(transform_edges(edges_page, args, context) if transform_edges else edges_page)
if len(edges_page) < missing_edges_count:
break
try:
end_cursor = ndb_iter.cursor_after().urlsafe()
except BadArgumentError:
end_cursor = None
# Construct the connection
return connection_type(
edges=edges,
page_info=pageinfo_type(
start_cursor=start_cursor.urlsafe() if start_cursor else '',
end_cursor=end_cursor,
has_previous_page=has_previous_page,
has_next_page=ndb_iter.has_next()
)
)
class NdbConnectionField(ConnectionField):
def __init__(self, type, transform_edges=None, *args, **kwargs):
super(NdbConnectionField, self).__init__(
type,
*args,
keys_only=Boolean(),
batch_size=Int(),
page_size=Int(),
**kwargs
)
self.transform_edges = transform_edges
@property
def type(self):
from .types import NdbObjectType
_type = super(ConnectionField, self).type
assert issubclass(_type, NdbObjectType), (
"NdbConnectionField only accepts NdbObjectType types"
)
assert _type._meta.connection, "The type {} doesn't have a connection".format(_type.__name__)
return _type._meta.connection
@property
def model(self):
return self.type._meta.node._meta.model
@staticmethod
def connection_resolver(resolver, connection, model, transform_edges, root, info, **args):
ndb_query = resolver(root, info, **args)
if ndb_query is None:
ndb_query = model.query()
return connection_from_ndb_query(
ndb_query,
args=args,
connection_type=connection,
edge_type=connection.Edge,
pageinfo_type=PageInfo,
transform_edges=transform_edges,
context=info.context
)
def get_resolver(self, parent_resolver):
return partial(
self.connection_resolver, parent_resolver, self.type, self.model, self.transform_edges
)
class DynamicNdbKeyStringField(Dynamic):
def __init__(self, ndb_key_prop, registry=None, *args, **kwargs):
kind = ndb_key_prop._kind
if not registry:
registry = get_global_registry()
def get_type():
kind_name = kind if isinstance(kind, six.string_types) else kind.__name__
_type = registry.get_type_for_model_name(kind_name)
if not _type:
return None
return NdbKeyStringField(ndb_key_prop, _type._meta.name)
super(DynamicNdbKeyStringField, self).__init__(
get_type,
*args, **kwargs
)
class DynamicNdbKeyReferenceField(Dynamic):
def __init__(self, ndb_key_prop, registry=None, *args, **kwargs):
kind = ndb_key_prop._kind
if not registry:
registry = get_global_registry()
def get_type():
kind_name = kind if isinstance(kind, six.string_types) else kind.__name__
_type = registry.get_type_for_model_name(kind_name)
if not _type:
return None
return NdbKeyReferenceField(ndb_key_prop, _type)
super(DynamicNdbKeyReferenceField, self).__init__(
get_type,
*args, **kwargs
)
class NdbKeyStringField(Field):
def __init__(self, ndb_key_prop, graphql_type_name, *args, **kwargs):
self.__ndb_key_prop = ndb_key_prop
self.__graphql_type_name = graphql_type_name
is_repeated = ndb_key_prop._repeated
is_required = ndb_key_prop._required
_type = String
if is_repeated:
_type = List(_type)
if is_required:
_type = NonNull(_type)
kwargs['args'] = {
'ndb': Argument(Boolean, False, description="Return an NDB id (key.id()) instead of a GraphQL global id")
}
super(NdbKeyStringField, self).__init__(_type, *args, **kwargs)
def resolve_key_to_string(self, entity, info, ndb=False):
is_global_id = not ndb
key_value = self.__ndb_key_prop._get_user_value(entity)
if not key_value:
return None
if isinstance(key_value, list):
return [to_global_id(self.__graphql_type_name, k.urlsafe()) for k in key_value] if is_global_id else [k.id() for k in key_value]
return to_global_id(self.__graphql_type_name, key_value.urlsafe()) if is_global_id else key_value.id()
def get_resolver(self, parent_resolver):
return self.resolve_key_to_string
class NdbKeyReferenceField(Field):
def __init__(self, ndb_key_prop, graphql_type, *args, **kwargs):
self.__ndb_key_prop = ndb_key_prop
self.__graphql_type = graphql_type
is_repeated = ndb_key_prop._repeated
is_required = ndb_key_prop._required
_type = self.__graphql_type
if is_repeated:
_type = List(_type)
if is_required:
_type = NonNull(_type)
super(NdbKeyReferenceField, self).__init__(_type, *args, **kwargs)
def resolve_key_reference(self, entity, info):
key_value = self.__ndb_key_prop._get_user_value(entity)
if not key_value:
return None
if isinstance(key_value, list):
return ndb.get_multi(key_value)
return key_value.get()
def get_resolver(self, parent_resolver):
return self.resolve_key_reference
| {
"repo_name": "graphql-python/graphene-gae",
"path": "graphene_gae/ndb/fields.py",
"copies": "2",
"size": "8224",
"license": "bsd-3-clause",
"hash": 8032684937732383000,
"line_mean": 31.5059288538,
"line_max": 151,
"alpha_frac": 0.6163667315,
"autogenerated": false,
"ratio": 3.837610825944937,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5453977557444937,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import StringIO
import os
import sys
DEVNULL = open(os.devnull, 'w')
class Record(object):
def __init__(self, *fds):
self.dupe = StringIO.StringIO()
self.them = fds
self.fileno = partial(self._dupe, 'fileno')
self.flush = partial(self._both, 'flush')
self.isatty = partial(self._them, 'isatty')
self.name = partial(self._them, 'name')
self.write = partial(self._both, 'write')
self.writelines = partial(self._both, 'writelines')
def __str__(self):
return self.getvalue()
def _both(self, operation, *args, **kwargs):
self._dupe(operation, *args, **kwargs)
self._them(operation, *args, **kwargs)
def _dupe(self, operation, *args, **kwargs):
getattr(self.dupe, operation)(*args, **kwargs)
def _them(self, operation, *args, **kwargs):
for fd in self.them:
getattr(fd, operation)(*args, **kwargs)
def getvalue(self):
return self.dupe.getvalue()
class Recorder(object):
def __init__(self, merged=False, *fds):
self.fds = list(fds)
self.output = {}
self.merged = StringIO.StringIO() if merged else None
def add(self, name):
out = getattr(sys, name)
if self.merged:
fds = self.fds + [out, self.merged]
else:
fds = self.fds + [out]
# Store original file descriptor
self.output[name] = (out, Record(*fds))
# Proxy original file descriptor
setattr(sys, name, self.output[name][1])
# Inject convenience method
setattr(self, name, self.output[name][1])
def restore(self):
# Restore original file descriptors
for name in self.output:
setattr(sys, name, self.output[name][0])
def __str__(self):
if self.merged:
return self.merged.getvalue()
elif hasattr(self, 'stdout'):
return self.stdout.getvalue()
elif hasattr(self, 'stderr'):
return self.stderr.getvalue()
else:
raise ValueError('Recorder inactive')
class Proxy(object):
def __init__(self, stdout, stderr, merged, *fds):
self.proxy_stdout = bool(stdout)
self.proxy_stderr = bool(stderr)
self.proxy_merged = bool(merged)
self.fds = fds
def __enter__(self):
self.recorder = Recorder(self.proxy_merged, *self.fds)
if self.proxy_stdout:
self.recorder.add('stdout')
if self.proxy_stderr:
self.recorder.add('stderr')
return self.recorder
def __exit__(self, *args, **kwargs):
self.recorder.restore()
capture = Proxy(1, 1, 1)
stdout = Proxy(1, 0, 0)
stderr = Proxy(0, 1, 0)
def tee(filename, stdout=True, stderr=True, append=False):
if append:
fd = open(filename, 'a')
else:
fd = open(filename, 'w')
return Proxy(stdout, stderr, 1, fd)
| {
"repo_name": "tehmaze/capture",
"path": "capture/__init__.py",
"copies": "1",
"size": "2984",
"license": "mit",
"hash": 213223109299858600,
"line_mean": 25.407079646,
"line_max": 62,
"alpha_frac": 0.5733914209,
"autogenerated": false,
"ratio": 3.7393483709273183,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48127397918273185,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import subprocess
from time import sleep
from kivy.clock import Clock
from kivy.properties import StringProperty
from kivy.uix.stacklayout import StackLayout
from service.lib.smbutils import smb_connect
__author__ = "Nicklas Boerjesson"
import ConfigParser
import re
from kivy.lib import osc
from kivy.utils import platform
platform = platform()
from kivy.lang import Builder
Builder.load_file("gui/settings.kv")
class SettingsFrame(StackLayout):
"""Settingsframe is the main frame of the application"""
cfg_file = None
"""The config file to use"""
service_status = None
"""The status of the service"""
service_progress = None
"""The progress of the current job"""
def init(self, _cfg_file=None):
self.ids.destination_host.ids.input_selection.bind(text=self._update_host)
self.ids.destination_path.on_status = self.do_on_smbselector_status
self.load_settings(_cfg_file)
self.service = None
osc.init()
self.oscid = osc.listen(port=3002)
osc.bind(self.oscid, self.progress_callback, "/progress_callback")
osc.bind(self.oscid, self.status_callback, "/status_callback")
# Check if service is running
self.service_running = False
osc.sendMsg("/status", [], port=3000)
osc.sendMsg("/progress", [], port=3000)
sleep(0.3)
osc.readQueue(self.oscid)
Clock.schedule_interval(self.process_messages, 1)
####### Service #################
#######################################################################################
def do_on_smbselector_status(self, _message):
"""
:param _message: A string message
"""
self.ids.l_test_smbselector_result.text = re.sub("(.{40})", "\\1\n", _message, 0, re.DOTALL)
def process_messages(self, *args):
"""Receive messages"""
osc.readQueue(self.oscid)
def status_callback(self, *args):
"""If the client receives a status message, reflect that in the label_status widget
:param args: Message arguments.
"""
self.service_running = True
self.service_status = str(args[0][2])
self.ids.label_status.text = self.service_status
def progress_callback(self, *args):
"""If the client receives a progress message, reflect that in the label_progress widget
:param args: Message arguments.
"""
self.service_running = True
self.service_progress = str(args[0][2])
self.ids.label_progress.text = re.sub("(.{40})", "\\1\n", self.service_progress, 0, re.DOTALL)
def start_service(self):
"""Start the service"""
self.save_settings()
print("Starting service")
self.service_running = False
osc.sendMsg("/status", [], port=3000)
osc.sendMsg("/progress", [], port=3000)
sleep(0.1)
osc.readQueue(self.oscid)
if not self.service_status:
# Wait a little longer and try again
sleep(0.5)
osc.readQueue(self.oscid)
if not self.service_status:
print("Start_service: Service is not running, starting")
if self.service is None:
if platform == "android":
from android import AndroidService
self.service = AndroidService("Optimal file sync service", "running")
self.service.start("service started")
else:
# Start process on linux.
print("Running on !android initializing service using Popen.")
self.service = subprocess.Popen(args = ["python", "./service/main.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
else:
print("Start_service: Service is already running, not starting.")
def stop_service(self):
"""Stop the service"""
print("Asking service to stop.")
self.service_running = False
osc.sendMsg("/status", [], port=3000)
sleep(0.2)
osc.readQueue(self.oscid)
osc.sendMsg("/stop", [], port=3000)
sleep(0.2)
osc.readQueue(self.oscid)
if self.service is not None and platform == "android":
self.service.stop()
self.service = None
####### GUI #################
#######################################################################################
def _update_host(self, *args):
"""If the host selection is changed, set the host."""
self.ids.destination_path.host = self.ids.destination_host.ids.input_selection.text
def reload_settings(self):
"""Reload settings from current settings file"""
self.load_settings(self.cfg_file)
def load_settings(self, _cfg_file=None):
"""
Load settings from a settings file
:param _cfg_file: A file with settings
"""
self.cfg_file = _cfg_file
cfg = ConfigParser.SafeConfigParser()
cfg.read(_cfg_file)
self.ids.sourcedir_select.selection = cfg.get("Job_Default", "source_folder")
self.ids.destination_host.selection = cfg.get("Job_Default", "destination_hostname")
self.ids.destination_path.selection = cfg.get("Job_Default", "destination_folder")
self.ids.destination_username.text = cfg.get("Job_Default", "destination_username")
self.ids.destination_password.text = cfg.get("Job_Default", "destination_password")
def save_settings(self):
"""Save settings to file"""
cfg = ConfigParser.SafeConfigParser()
cfg.read(self.cfg_file)
cfg.set("Job_Default", "source_folder", self.ids.sourcedir_select.selection)
cfg.set("Job_Default", "destination_hostname", self.ids.destination_host.selection)
cfg.set("Job_Default", "destination_folder", self.ids.destination_path.selection)
cfg.set("Job_Default", "destination_username", self.ids.destination_username.text)
cfg.set("Job_Default", "destination_password", self.ids.destination_password.text)
f = open(self.cfg_file, "wb")
cfg.write(f)
f.close()
def test_connection(self):
"""Test SMB connection by connecting to a server"""
try:
self.ids.l_test_connection_result.text = "Testing..."
_smb = smb_connect(_hostname=self.ids.destination_host.selection,
_username=self.ids.destination_username.text,
_password=self.ids.destination_password.text )
self.ids.l_test_connection_result.text = "Connection successful!"
except Exception as e:
self.ids.l_test_connection_result.text = "Test failed, error connecting: " + str(e)
try:
_shares = _smb.listShares()
self.ids.l_test_connection_result.text = "Listing shares (" + str(len(_shares)) + ") successful!"
except Exception as e:
self.ids.l_test_connection_result.text = "Test failed, error listing shares: " + str(e)
| {
"repo_name": "OptimalBPM/optimal_file_sync",
"path": "gui/settings.py",
"copies": "1",
"size": "7100",
"license": "apache-2.0",
"hash": 3134778117671585300,
"line_mean": 36.9679144385,
"line_max": 162,
"alpha_frac": 0.5991549296,
"autogenerated": false,
"ratio": 4.0781160252728315,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5177270954872831,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import subprocess
import tornado.ioloop
import tornado.web
import tempfile
import os
import base64
from tornado.log import enable_pretty_logging
def execute_cmd(cmd, **kwargs):
"""
Call given command, yielding output line by line
"""
kwargs["stdout"] = subprocess.PIPE
kwargs["stderr"] = subprocess.STDOUT
proc = subprocess.Popen(cmd, **kwargs)
# Capture output for logging.
# Each line will be yielded as text.
# This should behave the same as .readline(), but splits on `\r` OR `\n`,
# not just `\n`.
buf = []
def flush():
line = b"".join(buf).decode("utf8", "replace")
buf[:] = []
return line
c_last = ""
try:
for c in iter(partial(proc.stdout.read, 1), b""):
if c_last == b"\r" and buf and c != b"\n":
yield flush()
buf.append(c)
if c == b"\n":
yield flush()
c_last = c
finally:
ret = proc.wait()
if ret != 0:
raise subprocess.CalledProcessError(ret, cmd)
class DeployHandler(tornado.web.RequestHandler):
def initialize(self, auth_token):
self.auth_token = auth_token
def prepare(self):
super().prepare()
auth_header = self.request.headers.get("Authorization", "")
if auth_header != "Bearer {}".format(self.auth_token):
raise tornado.web.HTTPError(403)
def post(self):
repo = self.get_argument("repo")
commit = self.get_argument("commit")
release = self.get_argument("release")
# We might lose some '+' (part of base64) into spaces from our
# POST processing. Put 'em back.
crypt_key = base64.standard_b64decode(
self.get_argument("crypt-key").replace(" ", "+")
)
curdir = os.getcwd()
try:
with tempfile.TemporaryDirectory() as git_dir:
for line in execute_cmd(
["git", "clone", "--recursive", repo, git_dir]
):
self.write(line)
self.flush()
os.chdir(git_dir)
for line in execute_cmd(["git", "reset", "--hard", commit]):
self.write(line)
self.flush()
with open("key", "wb") as f:
f.write(crypt_key)
for line in execute_cmd(["git", "crypt", "unlock", "key"]):
self.write(line)
self.flush()
for line in execute_cmd(["./build.py", "deploy", release]):
self.write(line)
self.flush()
finally:
os.chdir(curdir)
if __name__ == "__main__":
auth_token = os.environ["DEPLOY_HOOK_TOKEN"]
app = tornado.web.Application(
[(r"/deploy", DeployHandler, {"auth_token": auth_token})]
)
app.listen(8888)
enable_pretty_logging()
tornado.ioloop.IOLoop.current().start()
| {
"repo_name": "yuvipanda/paws",
"path": "images/deploy-hook/app.py",
"copies": "1",
"size": "3016",
"license": "mit",
"hash": 6438394966548442000,
"line_mean": 28.8613861386,
"line_max": 77,
"alpha_frac": 0.5281830239,
"autogenerated": false,
"ratio": 4.1034013605442174,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5131584384444218,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import sys
from nose.tools import assert_equal, assert_greater
from nose import SkipTest
import asyncio
import time as ttime
from bluesky import Msg
from bluesky.tests.utils import setup_test_run_engine
from bluesky.testing.noseclasses import KnownFailureTest
RE = setup_test_run_engine()
loop = asyncio.get_event_loop()
def test_epics_smoke():
try:
import epics
except ImportError:
raise SkipTest
pv = epics.PV('BSTEST:VAL')
pv.value = 123456
print(pv)
print(pv.value)
print(pv.connect())
assert pv.connect()
for j in range(1, 15):
pv.put(j, wait=True)
ret = pv.get(use_monitor=False)
assert_equal(ret, j)
def _test_suspender(suspender_class, sc_args, start_val, fail_val,
resume_val, wait_time):
try:
import epics
except ImportError:
raise SkipTest
if sys.platform == 'darwin':
# OSX event loop is different; resolve this later
raise KnownFailureTest()
my_suspender = suspender_class(RE, 'BSTEST:VAL', *sc_args, sleep=wait_time)
print(my_suspender._lock)
pv = epics.PV('BSTEST:VAL')
putter = partial(pv.put, wait=True)
# make sure we start at good value!
putter(start_val)
# dumb scan
scan = [Msg('checkpoint'), Msg('sleep', None, .2)]
# paranoid
assert_equal(RE.state, 'idle')
start = ttime.time()
# queue up fail and resume conditions
loop.call_later(.1, putter, fail_val)
loop.call_later(1, putter, resume_val)
# start the scan
RE(scan)
stop = ttime.time()
# paranoid clean up of pv call back
my_suspender._pv.disconnect()
# assert we waited at least 2 seconds + the settle time
print(stop - start)
assert_greater(stop - start, 1 + wait_time + .2)
def test_suspending():
try:
from bluesky.suspenders import (PVSuspendBoolHigh,
PVSuspendBoolLow,
PVSuspendFloor,
PVSuspendCeil,
PVSuspendInBand,
PVSuspendOutBand)
except ImportError:
raise SkipTest
yield _test_suspender, PVSuspendBoolHigh, (), 0, 1, 0, .5
yield _test_suspender, PVSuspendBoolLow, (), 1, 0, 1, .5
yield _test_suspender, PVSuspendFloor, (.5,), 1, 0, 1, .5
yield _test_suspender, PVSuspendCeil, (.5,), 0, 1, 0, .5
yield _test_suspender, PVSuspendInBand, (.5, 1.5), 1, 0, 1, .5
yield _test_suspender, PVSuspendOutBand, (.5, 1.5), 0, 1, 0, .5
| {
"repo_name": "ericdill/bluesky",
"path": "bluesky/tests/test_suspenders.py",
"copies": "1",
"size": "2625",
"license": "bsd-3-clause",
"hash": -6982440138003081000,
"line_mean": 30.25,
"line_max": 79,
"alpha_frac": 0.6022857143,
"autogenerated": false,
"ratio": 3.404669260700389,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9506954975000389,
"avg_score": 0,
"num_lines": 84
} |
from functools import partial
import sys
from PySide2.QtWidgets import *
from nebula_libs.nicon import Icon
class onOffPushButton(QPushButton):
def __init__(self, parent=None, label=None, checked=False):
"""
Special pushbutton for internal use only really
"""
QPushButton.__init__(self, parent)
self.setText(label)
self.setCheckable(True)
self.checked = checked
self.setChecked(self.checked)
self.unticked = 'iconmonstr-x-mark-4-240'
self.ticked = 'iconmonstr-check-mark-5-240'
self._checkState()
self.setStyleSheet("QPushButton {border: 0px solid gray;border-radius: 5px;margin-top: 1ex;}")
self.toggled.connect(self._checkState)
self.resize(25,25)
def _checkState(self):
if self.isChecked():
self.setIcon(Icon(self.ticked))
else:
self.setIcon(Icon(self.unticked))
if hasattr(self.parent(), 'AllButton'):
self.parent().AllButton.setChecked(False)
class GroupBox(QGroupBox):
def __init__(self, parent=None, label=None):
QGroupBox.__init__(self, parent)
self.setStyleSheet("QGroupBox {border: 2px solid gray;border-radius: 5px;margin-top: 1ex;}")
self.setTitle(label)
self.setMaximumSize(170, 200)
self.mainLayout = QHBoxLayout(self)
self.XButton = onOffPushButton(self, label='X', checked=False)
self.XButton.setMaximumWidth(45)
self.YButton = onOffPushButton(self, label='Y', checked=False)
self.YButton.setMaximumWidth(45)
self.ZButton = onOffPushButton(self, label='Z', checked=False)
self.ZButton.setMaximumWidth(45)
self.AllButton = onOffPushButton(self, label='ALL', checked=False)
self.AllButton.toggled.connect(partial(self._switchButtons, buttons=[self.XButton, self.YButton, self.ZButton]))
self.mainLayout.addWidget(self.XButton)
self.mainLayout.addWidget(self.YButton)
self.mainLayout.addWidget(self.ZButton)
self.mainLayout.addWidget(self.AllButton)
def _switchButtons(self, sender, buttons=None):
buttons = buttons or []
if self.AllButton.isChecked():
for eachButton in buttons:
if not eachButton.isChecked():
eachButton.setChecked(True)
eachButton._checkState()
else:
for eachButton in buttons:
if eachButton.isChecked():
eachButton.setChecked(False)
eachButton._checkState()
class TransRotScaleCheckBoxes(QWidget):
'''
Standalone window for a selection box setup for Trans Rot and Scale
Usage for this is pretty straight forward. You can call in the UI and if you don't need trans or scale just set those to false and
they will not show up in the widget.
To get the current states use the .getAllTrans() methods etc
'''
def __init__(self, winName='transforms', trans=True, rot=True, scale=True, parent=None):
QWidget.__init__(self, parent)
self.setStyleSheet("QWidget{background-color: #303030}")
self.myMainLayout = QHBoxLayout(self)
self.winName = winName
self.setObjectName(self.winName)
self.setWindowTitle(self.winName)
if trans:
self.t = GroupBox(label='Translation')
self.myMainLayout.addWidget(self.t)
if rot:
self.r = GroupBox(label='Rotation')
self.myMainLayout.addWidget(self.r)
if scale:
self.s = GroupBox(label='Scale')
self.myMainLayout.addWidget(self.s)
@property
def tx(self):
return self.t.XButton.isChecked()
@property
def ty(self):
return self.t.YButton.isChecked()
@property
def tz(self):
return self.t.ZButton.isChecked()
@property
def rx(self):
return self.r.XButton.isChecked()
@property
def ry(self):
return self.r.YButton.isChecked()
@property
def rz(self):
return self.r.ZButton.isChecked()
@property
def sx(self):
return self.s.XButton.isChecked()
@property
def sy(self):
return self.s.YButton.isChecked()
@property
def sz(self):
return self.s.ZButton.isChecked()
if __name__ == '__main__':
qtapp = QApplication(sys.argv)
myUI = TransRotScaleCheckBoxes()
myUI.show()
qtapp.exec_()
| {
"repo_name": "jamesbdunlop/Nebula",
"path": "nebula_ui/nMayaui_core/trsChxBox.py",
"copies": "2",
"size": "4474",
"license": "apache-2.0",
"hash": 6241864490265388000,
"line_mean": 31.1870503597,
"line_max": 134,
"alpha_frac": 0.6267322307,
"autogenerated": false,
"ratio": 3.870242214532872,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0039473366114961,
"num_lines": 139
} |
from functools import partial
import sys
import cherrypy
class HandlerException(Exception):
def __init__(self, wrapped_exception):
self.wrapped_exception = wrapped_exception
def raise_wrapped(self):
"""
Raises the 'wrapped' exception, preserving the original
traceback. This must be called from within an `except` block.
"""
# The first item is a class instance, so the second item must
# be None. The third item is the traceback object, which is why
# this method must be called from within an `except` block.
raise (
self.wrapped_exception(),
None,
sys.exc_info()[2])
def http_301(download_url):
return HandlerException(wrapped_exception=partial(
cherrypy.HTTPRedirect,
urls=download_url,
status=301))
def http_302(download_url):
return HandlerException(wrapped_exception=partial(
cherrypy.HTTPRedirect,
urls=download_url,
status=302))
def http_404(message):
return HandlerException(wrapped_exception=partial(
cherrypy.HTTPError,
status=404,
message=message))
| {
"repo_name": "teamfruit/defend_against_fruit",
"path": "pypi_redirect/pypi_redirect/server_app/handler/_exception.py",
"copies": "1",
"size": "1171",
"license": "apache-2.0",
"hash": -8181259779215959000,
"line_mean": 26.880952381,
"line_max": 71,
"alpha_frac": 0.6464560205,
"autogenerated": false,
"ratio": 4.469465648854962,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 42
} |
from functools import partial
import sys
import textwrap
from .loader import Loader
from .parser import Parser, Context, Argument
from .executor import Executor
from .exceptions import Failure, CollectionNotFound, ParseError
from .util import debug, pty_size
from ._version import __version__
def depth(name):
return len(name.split('.'))
def cmp_task_name(a, b):
return cmp(depth(a), depth(b)) or cmp(a, b)
sort_names = partial(sorted, cmp=cmp_task_name)
def parse_gracefully(parser, argv):
"""
Run ``parser.parse_argv(argv)`` & gracefully handle ``ParseError``.
'Gracefully' meaning to print a useful human-facing error message instead
of a traceback; the program will still exit if an error is raised.
If no error is raised, returns the result of the ``parse_argv`` call.
"""
try:
return parser.parse_argv(argv)
except ParseError, e:
print str(e)
sys.exit(1)
def parse(argv, collection=None):
# Initial/core parsing (core options can affect the rest of the parsing)
initial_context = Context(args=(
# TODO: make '--collection' a list-building arg, not a string
Argument(
names=('collection', 'c'),
help="Specify collection name to load. May be given >1 time."
),
Argument(
names=('root', 'r'),
help="Change root directory used for finding task modules."
),
Argument(
names=('help', 'h'),
kind=bool,
default=False,
help="Show this help message and exit."
),
Argument(
names=('version', 'V'),
kind=bool,
default=False,
help="Show version and exit"
),
Argument(
names=('list', 'l'),
kind=bool,
default=False,
help="List available tasks."
),
Argument(
names=('no-dedupe',),
kind=bool,
default=False,
help="Disable task deduplication"
)
))
# 'core' will result an .unparsed attribute with what was left over.
debug("Parsing initial context (core args)")
parser = Parser(initial=initial_context, ignore_unknown=True)
core = parse_gracefully(parser, argv)
debug("After core-args pass, leftover argv: %r" % (core.unparsed,))
args = core[0].args
# Print version & exit if necessary
if args.version.value:
print "Invoke %s" % __version__
sys.exit(0)
# Core --help output
# TODO: if this wants to display context sensitive help (e.g. a combo help
# and available tasks listing; or core flags modified by plugins/task
# modules) it will have to move farther down.
if args.help.value:
print "Usage: inv[oke] [--core-opts] task1 [--task1-opts] ... taskN [--taskN-opts]"
print
print "Core options:"
indent = 2
padding = 3
# Calculate column sizes: don't wrap flag specs, give what's left over
# to the descriptions
tuples = initial_context.help_tuples()
flag_width = max(map(lambda x: len(x[0]), tuples))
desc_width = pty_size()[0] - flag_width - indent - padding - 1
wrapper = textwrap.TextWrapper(width=desc_width)
for flag_spec, help_str in tuples:
# Wrap descriptions/help text
help_chunks = wrapper.wrap(help_str)
# Print flag spec + padding
flag_padding = flag_width - len(flag_spec)
spec = ''.join((
indent * ' ',
flag_spec,
flag_padding * ' ',
padding * ' '
))
# Print help text as needed
if help_chunks:
print spec + help_chunks[0]
for chunk in help_chunks[1:]:
print (' ' * len(spec)) + chunk
else:
print spec
print
# Load collection (default or specified) and parse leftovers
# (Skip loading if somebody gave us an explicit task collection.)
if not collection:
debug("No collection given, loading from %r" % args.root.value)
loader = Loader(root=args.root.value)
collection = loader.load_collection(args.collection.value)
parser = Parser(contexts=collection.to_contexts())
debug("Parsing actual tasks against collection %r" % collection)
tasks = parse_gracefully(parser, core.unparsed)
# Print discovered tasks if necessary
if args.list.value:
print "Available tasks:\n"
# Sort in depth, then alpha, order
task_names = collection.task_names
names = sort_names(task_names.keys())
for primary in names:
aliases = sort_names(task_names[primary])
out = primary
if aliases:
out += " (%s)" % ', '.join(aliases)
print " %s" % out
print ""
sys.exit(0)
return args, collection, tasks
def main():
# Parse command line
argv = sys.argv[1:]
debug("Base argv from sys: %r" % (argv,))
args, collection, tasks = parse(argv)
# Take action based on 'core' options and the 'tasks' found
for context in tasks:
kwargs = {}
for name, arg in context.args.iteritems():
kwargs[name] = arg.value
try:
# TODO: allow swapping out of Executor subclasses based on core
# config options
# TODO: friggin dashes vs underscores
Executor(collection).execute(name=context.name, kwargs=kwargs, dedupe=not args['no-dedupe'])
except Failure, f:
sys.exit(f.result.exited)
| {
"repo_name": "alex/invoke",
"path": "invoke/cli.py",
"copies": "1",
"size": "5690",
"license": "bsd-2-clause",
"hash": -7836632194670063000,
"line_mean": 33.2771084337,
"line_max": 104,
"alpha_frac": 0.5808435852,
"autogenerated": false,
"ratio": 4.1899852724594995,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.52708288576595,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import sys
import textwrap
from .vendor import six
from .context import Context
from .loader import Loader
from .parser import Parser, Context as ParserContext, Argument
from .executor import Executor
from .exceptions import Failure, CollectionNotFound, ParseError
from .util import debug, pty_size
from ._version import __version__
def task_name_to_key(x):
return (x.count('.'), x)
sort_names = partial(sorted, key=task_name_to_key)
indent_num = 2
indent = " " * indent_num
def print_help(tuples):
padding = 3
# Calculate column sizes: don't wrap flag specs, give what's left over
# to the descriptions.
flag_width = max(len(x[0]) for x in tuples)
desc_width = pty_size()[0] - flag_width - indent_num - padding - 1
wrapper = textwrap.TextWrapper(width=desc_width)
for flag_spec, help_str in tuples:
# Wrap descriptions/help text
help_chunks = wrapper.wrap(help_str)
# Print flag spec + padding
flag_padding = flag_width - len(flag_spec)
spec = ''.join((
indent,
flag_spec,
flag_padding * ' ',
padding * ' '
))
# Print help text as needed
if help_chunks:
print(spec + help_chunks[0])
for chunk in help_chunks[1:]:
print((' ' * len(spec)) + chunk)
else:
print(spec)
print('')
def parse_gracefully(parser, argv):
"""
Run ``parser.parse_argv(argv)`` & gracefully handle ``ParseError``.
'Gracefully' meaning to print a useful human-facing error message instead
of a traceback; the program will still exit if an error is raised.
If no error is raised, returns the result of the ``parse_argv`` call.
"""
try:
return parser.parse_argv(argv)
except ParseError as e:
sys.exit(str(e))
def parse(argv, collection=None):
"""
Parse ``argv`` list-of-strings into useful core & per-task structures.
:returns:
Three-tuple of ``args`` (core, non-task `.Argument` objects), ``collection``
(compiled `.Collection` of tasks, using defaults or core arguments
affecting collection generation) and ``tasks`` (a list of
`~.parser.context.Context` objects representing the requested task
executions).
"""
# Initial/core parsing (core options can affect the rest of the parsing)
initial_context = ParserContext(args=(
# TODO: make '--collection' a list-building arg, not a string
Argument(
names=('collection', 'c'),
help="Specify collection name to load. May be given >1 time."
),
Argument(
names=('root', 'r'),
help="Change root directory used for finding task modules."
),
Argument(
names=('help', 'h'),
optional=True,
help="Show core or per-task help and exit."
),
Argument(
names=('version', 'V'),
kind=bool,
default=False,
help="Show version and exit."
),
Argument(
names=('list', 'l'),
kind=bool,
default=False,
help="List available tasks."
),
Argument(
names=('no-dedupe',),
kind=bool,
default=False,
help="Disable task deduplication."
),
Argument(
names=('echo', 'e'),
kind=bool,
default=False,
help="Echo executed commands before running.",
),
Argument(
names=('warn-only', 'w'),
kind=bool,
default=False,
help="Warn, instead of failing, when shell commands fail.",
),
Argument(
names=('pty', 'p'),
kind=bool,
default=False,
help="Use a pty when executing shell commands.",
),
Argument(
names=('hide', 'H'),
help="Set default value of run()'s 'hide' kwarg.",
)
))
# 'core' will result an .unparsed attribute with what was left over.
debug("Parsing initial context (core args)")
parser = Parser(initial=initial_context, ignore_unknown=True)
core = parse_gracefully(parser, argv)
debug("After core-args pass, leftover argv: %r" % (core.unparsed,))
args = core[0].args
# Print version & exit if necessary
if args.version.value:
print("Invoke %s" % __version__)
sys.exit(0)
# Core (no value given) --help output
# TODO: if this wants to display context sensitive help (e.g. a combo help
# and available tasks listing; or core flags modified by plugins/task
# modules) it will have to move farther down.
if args.help.value == True:
print("Usage: inv[oke] [--core-opts] task1 [--task1-opts] ... taskN [--taskN-opts]")
print("")
print("Core options:")
print_help(initial_context.help_tuples())
sys.exit(0)
# Load collection (default or specified) and parse leftovers
# (Skip loading if somebody gave us an explicit task collection.)
if not collection:
debug("No collection given, loading from %r" % args.root.value)
loader = Loader(root=args.root.value)
collection = loader.load_collection(args.collection.value)
parser = Parser(contexts=collection.to_contexts())
debug("Parsing actual tasks against collection %r" % collection)
tasks = parse_gracefully(parser, core.unparsed)
# Per-task help. Use the parser's contexts dict as that's the easiest way
# to obtain Context objects here - which are what help output needs.
name = args.help.value
if name in parser.contexts:
# Setup
ctx = parser.contexts[name]
tuples = ctx.help_tuples()
docstring = collection[name].__doc__
header = "Usage: inv[oke] [--core-opts] %s %%s[other tasks here ...]" % name
print(header % ("[--options] " if tuples else ""))
print("")
print("Docstring:")
if docstring:
# Really wish textwrap worked better for this.
doclines = docstring.lstrip().splitlines()
for line in doclines:
print(indent + textwrap.dedent(line))
# Print trailing blank line if docstring didn't end with one
if textwrap.dedent(doclines[-1]):
print("")
else:
print(indent + "none")
print("")
print("Options:")
if tuples:
print_help(tuples)
else:
print(indent + "none")
print("")
sys.exit(0)
# Print discovered tasks if necessary
if args.list.value:
print("Available tasks:\n")
# Sort in depth, then alpha, order
task_names = collection.task_names
names = sort_names(task_names.keys())
for primary in names:
aliases = sort_names(task_names[primary])
out = primary
if aliases:
out += " (%s)" % ', '.join(aliases)
print(" %s" % out)
print("")
sys.exit(0)
# Return to caller so they can handle the results
return args, collection, tasks
def derive_opts(args):
run = {}
if args['warn-only'].value:
run['warn'] = True
if args.pty.value:
run['pty'] = True
if args.hide.value:
run['hide'] = args.hide.value
if args.echo.value:
run['echo'] = True
return {'run': run}
def dispatch(argv):
args, collection, tasks = parse(argv)
results = []
executor = Executor(collection, Context(**derive_opts(args)))
# Take action based on 'core' options and the 'tasks' found
for context in tasks:
kwargs = {}
for _, arg in six.iteritems(context.args):
# Use the arg obj's internal name - not what was necessarily given
# on the CLI. (E.g. --my-option vs --my_option for
# mytask(my_option=xxx) requires this.)
# TODO: store 'given' name somewhere in case somebody wants to see
# it when handling args.
kwargs[arg.name] = arg.value
try:
# TODO: allow swapping out of Executor subclasses based on core
# config options
results.append(executor.execute(
name=context.name,
kwargs=kwargs,
dedupe=not args['no-dedupe']
))
except Failure as f:
sys.exit(f.result.exited)
return results
def main():
# Parse command line
argv = sys.argv[1:]
debug("Base argv from sys: %r" % (argv,))
dispatch(argv)
| {
"repo_name": "thedrow/invoke",
"path": "invoke/cli.py",
"copies": "1",
"size": "8712",
"license": "bsd-2-clause",
"hash": -5722951377510803000,
"line_mean": 32.1254752852,
"line_max": 92,
"alpha_frac": 0.5724288338,
"autogenerated": false,
"ratio": 4.186448822681403,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5258877656481403,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import sys
import textwrap
from .vendor import six
from .loader import Loader
from .parser import Parser, Context, Argument
from .executor import Executor
from .exceptions import Failure, CollectionNotFound, ParseError
from .util import debug, pty_size
from ._version import __version__
def task_name_to_key(x):
return (x.count('.'), x)
sort_names = partial(sorted, key=task_name_to_key)
def parse_gracefully(parser, argv):
"""
Run ``parser.parse_argv(argv)`` & gracefully handle ``ParseError``.
'Gracefully' meaning to print a useful human-facing error message instead
of a traceback; the program will still exit if an error is raised.
If no error is raised, returns the result of the ``parse_argv`` call.
"""
try:
return parser.parse_argv(argv)
except ParseError as e:
sys.exit(str(e))
def parse(argv, collection=None):
# Initial/core parsing (core options can affect the rest of the parsing)
initial_context = Context(args=(
# TODO: make '--collection' a list-building arg, not a string
Argument(
names=('collection', 'c'),
help="Specify collection name to load. May be given >1 time."
),
Argument(
names=('root', 'r'),
help="Change root directory used for finding task modules."
),
Argument(
names=('help', 'h'),
kind=bool,
default=False,
help="Show this help message and exit."
),
Argument(
names=('version', 'V'),
kind=bool,
default=False,
help="Show version and exit"
),
Argument(
names=('list', 'l'),
kind=bool,
default=False,
help="List available tasks."
),
Argument(
names=('no-dedupe',),
kind=bool,
default=False,
help="Disable task deduplication"
)
))
# 'core' will result an .unparsed attribute with what was left over.
debug("Parsing initial context (core args)")
parser = Parser(initial=initial_context, ignore_unknown=True)
core = parse_gracefully(parser, argv)
debug("After core-args pass, leftover argv: %r" % (core.unparsed,))
args = core[0].args
# Print version & exit if necessary
if args.version.value:
six.print_("Invoke %s" % __version__)
sys.exit(0)
# Core --help output
# TODO: if this wants to display context sensitive help (e.g. a combo help
# and available tasks listing; or core flags modified by plugins/task
# modules) it will have to move farther down.
if args.help.value:
six.print_("Usage: inv[oke] [--core-opts] task1 [--task1-opts] ... taskN [--taskN-opts]")
six.print_("")
six.print_("Core options:")
indent = 2
padding = 3
# Calculate column sizes: don't wrap flag specs, give what's left over
# to the descriptions.
tuples = initial_context.help_tuples()
flag_width = max(len(x[0]) for x in tuples)
desc_width = pty_size()[0] - flag_width - indent - padding - 1
wrapper = textwrap.TextWrapper(width=desc_width)
for flag_spec, help_str in tuples:
# Wrap descriptions/help text
help_chunks = wrapper.wrap(help_str)
# Print flag spec + padding
flag_padding = flag_width - len(flag_spec)
spec = ''.join((
indent * ' ',
flag_spec,
flag_padding * ' ',
padding * ' '
))
# Print help text as needed
if help_chunks:
six.print_(spec + help_chunks[0])
for chunk in help_chunks[1:]:
six.print_((' ' * len(spec)) + chunk)
else:
six.print_(spec)
six.print_('')
sys.exit(0)
# Load collection (default or specified) and parse leftovers
# (Skip loading if somebody gave us an explicit task collection.)
if not collection:
debug("No collection given, loading from %r" % args.root.value)
loader = Loader(root=args.root.value)
collection = loader.load_collection(args.collection.value)
parser = Parser(contexts=collection.to_contexts())
debug("Parsing actual tasks against collection %r" % collection)
tasks = parse_gracefully(parser, core.unparsed)
# Print discovered tasks if necessary
if args.list.value:
six.print_("Available tasks:\n")
# Sort in depth, then alpha, order
task_names = collection.task_names
names = sort_names(task_names.keys())
for primary in names:
aliases = sort_names(task_names[primary])
out = primary
if aliases:
out += " (%s)" % ', '.join(aliases)
six.print_(" %s" % out)
six.print_("")
sys.exit(0)
return args, collection, tasks
def main():
# Parse command line
argv = sys.argv[1:]
debug("Base argv from sys: %r" % (argv,))
args, collection, tasks = parse(argv)
# Take action based on 'core' options and the 'tasks' found
for context in tasks:
kwargs = {}
for name, arg in six.iteritems(context.args):
kwargs[name] = arg.value
try:
# TODO: allow swapping out of Executor subclasses based on core
# config options
# TODO: friggin dashes vs underscores
Executor(collection).execute(name=context.name, kwargs=kwargs, dedupe=not args['no-dedupe'])
except Failure as f:
sys.exit(f.result.exited)
| {
"repo_name": "mikewesner-wf/glasshouse",
"path": "appengine/lib/invoke/cli.py",
"copies": "1",
"size": "5726",
"license": "apache-2.0",
"hash": 84474374618056740,
"line_mean": 33.703030303,
"line_max": 104,
"alpha_frac": 0.5798113867,
"autogenerated": false,
"ratio": 4.149275362318841,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00023839838965889385,
"num_lines": 165
} |
from functools import partial
import sys
from filesystems import Path
import click
import filesystems.click
from venvs.common import _FILESYSTEM, _ROOT
def run(
locator,
filesystem,
binary=None,
directory=None,
name=None,
existing_only=False,
):
"""
Find the virtualenv associated with a given project given its name or path.
If an optional binary is provided, the binary's path within the virtualenv
is returned.
"""
if directory is not None:
virtualenv = locator.for_directory(directory=directory)
else:
if name is None:
sys.stdout.write(str(locator.root))
sys.stdout.write("\n")
return
virtualenv = locator.for_name(name=name)
if existing_only and not virtualenv.exists_on(filesystem=filesystem):
return 1
if binary is not None:
sys.stdout.write(str(virtualenv.binary(binary)))
else:
sys.stdout.write(str(virtualenv.path))
sys.stdout.write("\n")
@click.group(
context_settings=dict(help_option_names=["-h", "--help"]),
invoke_without_command=True,
)
@_FILESYSTEM
@_ROOT
@click.option(
"-E", "--existing-only",
flag_value=True,
help="Only consider existing virtualenvs.",
)
@click.pass_context
def main(context, locator, existing_only, filesystem):
"""
Find a virtualenv in the store.
"""
if context.invoked_subcommand is None:
click.echo(locator.root)
else:
context.obj = dict(
locate=partial(
run,
locator=locator,
existing_only=existing_only,
filesystem=filesystem,
),
)
@main.command()
@click.argument("directory", required=False, type=filesystems.click.PATH)
@click.argument("binary", required=False)
@click.pass_context
def directory(context, directory, binary):
"""
Find the virtualenv given the project's path.
"""
locate = context.obj["locate"]
context.exit(
locate(directory=directory or Path.cwd(), binary=binary) or 0,
)
@main.command()
@click.argument("name")
@click.argument("binary", required=False)
@click.pass_context
def name(context, name, binary):
"""
Find the virtualenv given the project's name.
"""
locate = context.obj["locate"]
context.exit(locate(name=name, binary=binary) or 0)
| {
"repo_name": "Julian/mkenv",
"path": "venvs/find.py",
"copies": "1",
"size": "2381",
"license": "mit",
"hash": 3457270083925842400,
"line_mean": 22.5742574257,
"line_max": 79,
"alpha_frac": 0.6396472071,
"autogenerated": false,
"ratio": 3.90327868852459,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.504292589562459,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import sys
class SpecCommandInGroups(object):
"""
Given a spec_command, generates the string of the actual command to execute.
This class can append data of the group to run by slicing a statically determined list of
specs_to_distribute based on the number of total runners and index of the current runner, if
you are calling a spec command that takes a list of e.g. specific spec files to run.
TODO - Or, spec_command can be a function that gets called with args:
total_number, current_index
where total_number is number of groups and current_index is a 1-indexed index of the
current runner.
"""
def __init__(self, spec_command):
self.spec_command = spec_command
self.specs_to_distribute = []
self.specs_to_run_separately = []
def load_specs(self, spec_files, run_separately=None):
if run_separately is None:
run_separately = []
_individual_for_own_procs = set([
f for specs in run_separately for f in specs.split()])
for sf in spec_files:
if sf not in _individual_for_own_procs:
self.specs_to_distribute.append(sf)
self.specs_to_run_separately.extend(run_separately)
# if we got no output, treat as failure and return False
return len(self.specs_to_distribute + self.specs_to_run_separately) > 0
def _spec_groups(self, num_groups):
separate_results = [[s] for s in self.specs_to_run_separately]
num_groups_to_distribute = num_groups - len(self.specs_to_run_separately)
distributed_results = [[] for _ in range(num_groups_to_distribute)]
for i, val in enumerate(self.specs_to_distribute):
distributed_results[i % num_groups_to_distribute].append(val)
return separate_results + distributed_results
def _build_cmd(self, number, total_number):
files = ' '.join(self._spec_groups(total_number)[number - 1])
return "{0} {1}".format(self.spec_command, files)
def build(self, total_number):
return partial(self._build_cmd, total_number=total_number)
def is_string(value):
""" Python 2 & 3 compatible method to determine if a string is string-like
(either a unicode or byte string).
"""
if sys.version_info[0] == 2:
string_types = (str,)
else:
string_types = (basestring,)
return isinstance(value, string_types)
def convert_command_to_function(command):
if is_string(command):
def wrapped_command(command_number):
return command
return wrapped_command
else:
return command
def and_commands(*commands):
""" Concatenates multiple commands with a shell '&&'
"""
command_fns = [convert_command_to_function(c) for c in commands]
def wrapped_and_command(command_number):
return ' && '.join(command_fn(command_number) for command_fn in command_fns)
return wrapped_and_command
| {
"repo_name": "dcosson/parallel-ci-runner",
"path": "parallel_ci_runner/shell_commands.py",
"copies": "1",
"size": "3023",
"license": "mit",
"hash": -2184408096623241500,
"line_mean": 36.7875,
"line_max": 100,
"alpha_frac": 0.6506781343,
"autogenerated": false,
"ratio": 3.9158031088082903,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.506648124310829,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import tensorflow as tf
from .. import slmc, batch, collections
from ..embedding import bidirectional_id_vector_to_embeddings
from ..embedding.embeddings import word_embeddings as _word_embeddings
from ..dynamic_length import id_vector_to_length
from ..softmax import softmax
from ..flags import FLAGS
from ..optimize import minimize
from ..util import static_rank, func_scope
from ..model import Model
from ..math import softmax_inverse
class AttentionSumReader(Model):
@func_scope("attention_sum_reader")
def __init__(self,
document: ("batch", "words"),
query: ("batch", "words"),
answer: ("batch",)):
assert static_rank(document) == 2
assert static_rank(query) == 2
assert static_rank(answer) == 1
collections.add_metric(tf.shape(document)[1], "document_2nd_dim")
collections.add_metric(tf.reduce_max(id_vector_to_length(document)),
"max_document_length")
collections.add_metric(tf.reduce_min(id_vector_to_length(document)),
"min_document_length")
word_embeddings = _word_embeddings()
bi_rnn = partial(bidirectional_id_vector_to_embeddings,
embeddings=word_embeddings,
dynamic_length=True,
output_size=FLAGS.word_embedding_size)
with tf.variable_scope("query"):
query_embedding = bi_rnn(query, output_state=True)
assert static_rank(query_embedding) == 2
with tf.variable_scope("document_to_attention"):
attentions = _calculate_attention(
bi_rnn(document), query_embedding, id_vector_to_length(document))
logits = softmax_inverse(_sum_attentions(attentions, document))
answer -= FLAGS.first_entity_index
loss = slmc.loss(logits, answer)
self._train_op = minimize(loss)
self._labels = slmc.label(logits)
collections.add_metric(loss, "loss")
collections.add_metric(slmc.accuracy(logits, answer), "accuracy")
@property
def train_op(self):
return self._train_op
@property
def labels(self):
return self._labels
@func_scope()
def _sum_attentions(attentions, document):
assert static_rank(attentions) == 2 and static_rank(document) == 2
num_entities = tf.reduce_max(document) + 1
@func_scope()
def _sum_attention(args):
attentions, document = args
assert static_rank(attentions) == 1 and static_rank(document) == 1
return tf.unsorted_segment_sum(attentions, document, num_entities)
attentions = tf.map_fn(_sum_attention,
[attentions, document],
dtype=FLAGS.float_type)
return attentions[:, FLAGS.first_entity_index:FLAGS.last_entity_index + 1]
@func_scope()
def _calculate_attention(document: ("batch", "sequence", "embedding"),
query: ("batch", "embedding"),
sequence_length):
assert static_rank(document) == 3
assert static_rank(query) == 2
return softmax(batch.mat_vec_mul(document, query), sequence_length)
| {
"repo_name": "raviqqe/tensorflow-extenteten",
"path": "extenteten/_experimental/models/attention_sum_reader.py",
"copies": "1",
"size": "3242",
"license": "unlicense",
"hash": 7321345860908866000,
"line_mean": 34.2391304348,
"line_max": 81,
"alpha_frac": 0.6196792104,
"autogenerated": false,
"ratio": 4.0986093552465235,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5218288565646524,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import threading
import os
from PyQt5.QtCore import Qt, QStandardPaths
from PyQt5.QtGui import QImage, QBitmap, qRed, qGreen, qBlue
from PyQt5.QtWidgets import QGridLayout, QInputDialog, QPushButton
from PyQt5.QtWidgets import QVBoxLayout, QLabel
from electroncash_gui.qt.util import *
from electroncash.i18n import _
from electroncash.plugins import hook, DeviceMgr
from electroncash.util import PrintError, UserCancelled, bh2u
from electroncash.wallet import Wallet, Standard_Wallet
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
from .trezor import (TrezorPlugin, TIM_NEW, TIM_RECOVER,
RECOVERY_TYPE_SCRAMBLED_WORDS, RECOVERY_TYPE_MATRIX,
PASSPHRASE_ON_DEVICE)
PASSPHRASE_HELP_SHORT =_(
"Passphrases allow you to access new wallets, each "
"hidden behind a particular case-sensitive passphrase.")
PASSPHRASE_HELP = PASSPHRASE_HELP_SHORT + " " + _(
"You need to create a separate Electron Cash wallet for each passphrase "
"you use as they each generate different addresses. Changing "
"your passphrase does not lose other wallets, each is still "
"accessible behind its own passphrase.")
RECOMMEND_PIN = _(
"You should enable PIN protection. Your PIN is the only protection "
"for your bitcoins if your device is lost or stolen.")
PASSPHRASE_NOT_PIN = _(
"If you forget a passphrase you will be unable to access any "
"bitcoins in the wallet behind it. A passphrase is not a PIN. "
"Only change this if you are sure you understand it.")
MATRIX_RECOVERY = _(
"Enter the recovery words by pressing the buttons according to what "
"the device shows on its display. You can also use your NUMPAD.\n"
"Press BACKSPACE to go back a choice or word.\n")
class MatrixDialog(WindowModalDialog):
def __init__(self, parent):
super(MatrixDialog, self).__init__(parent)
self.setWindowTitle(_("Trezor Matrix Recovery"))
self.num = 9
self.loop = QEventLoop()
vbox = QVBoxLayout(self)
vbox.addWidget(WWLabel(MATRIX_RECOVERY))
grid = QGridLayout()
grid.setSpacing(0)
self.char_buttons = []
for y in range(3):
for x in range(3):
button = QPushButton('?')
button.clicked.connect(partial(self.process_key, ord('1') + y * 3 + x))
grid.addWidget(button, 3 - y, x)
self.char_buttons.append(button)
vbox.addLayout(grid)
self.backspace_button = QPushButton("<=")
self.backspace_button.clicked.connect(partial(self.process_key, Qt.Key_Backspace))
self.cancel_button = QPushButton(_("Cancel"))
self.cancel_button.clicked.connect(partial(self.process_key, Qt.Key_Escape))
buttons = Buttons(self.backspace_button, self.cancel_button)
vbox.addSpacing(40)
vbox.addLayout(buttons)
self.refresh()
self.show()
def refresh(self):
for y in range(3):
self.char_buttons[3 * y + 1].setEnabled(self.num == 9)
def is_valid(self, key):
return key >= ord('1') and key <= ord('9')
def process_key(self, key):
self.data = None
if key == Qt.Key_Backspace:
self.data = '\010'
elif key == Qt.Key_Escape:
self.data = 'x'
elif self.is_valid(key):
self.char_buttons[key - ord('1')].setFocus()
self.data = '%c' % key
if self.data:
self.loop.exit(0)
def keyPressEvent(self, event):
self.process_key(event.key())
if not self.data:
QDialog.keyPressEvent(self, event)
def get_matrix(self, num):
self.num = num
self.refresh()
self.loop.exec_()
class QtHandler(QtHandlerBase):
pin_signal = pyqtSignal(object)
matrix_signal = pyqtSignal(object)
close_matrix_dialog_signal = pyqtSignal()
def __init__(self, win, pin_matrix_widget_class, device):
super(QtHandler, self).__init__(win, device)
self.pin_signal.connect(self.pin_dialog)
self.matrix_signal.connect(self.matrix_recovery_dialog)
self.close_matrix_dialog_signal.connect(self._close_matrix_dialog)
self.pin_matrix_widget_class = pin_matrix_widget_class
self.matrix_dialog = None
self.passphrase_on_device = False
def get_pin(self, msg):
self.done.clear()
self.pin_signal.emit(msg)
self.done.wait()
return self.response
def get_matrix(self, msg):
self.done.clear()
self.matrix_signal.emit(msg)
self.done.wait()
data = self.matrix_dialog.data
if data == 'x':
self.close_matrix_dialog()
return data
def _close_matrix_dialog(self):
if self.matrix_dialog:
self.matrix_dialog.accept()
self.matrix_dialog = None
def close_matrix_dialog(self):
self.close_matrix_dialog_signal.emit()
def pin_dialog(self, msg):
# Needed e.g. when resetting a device
self.clear_dialog()
dialog = WindowModalDialog(self.top_level_window(), _("Enter PIN"))
matrix = self.pin_matrix_widget_class()
vbox = QVBoxLayout()
vbox.addWidget(QLabel(msg))
vbox.addWidget(matrix)
vbox.addLayout(Buttons(CancelButton(dialog), OkButton(dialog)))
dialog.setLayout(vbox)
dialog.exec_()
self.response = str(matrix.get_value())
self.done.set()
def matrix_recovery_dialog(self, msg):
if not self.matrix_dialog:
self.matrix_dialog = MatrixDialog(self.top_level_window())
self.matrix_dialog.get_matrix(msg)
self.done.set()
def passphrase_dialog(self, msg, confirm):
# If confirm is true, require the user to enter the passphrase twice
parent = self.top_level_window()
d = WindowModalDialog(parent, _('Enter Passphrase'))
OK_button = OkButton(d, _('Enter Passphrase'))
OnDevice_button = QPushButton(_('Enter Passphrase on Device'))
new_pw = QLineEdit()
new_pw.setEchoMode(2)
conf_pw = QLineEdit()
conf_pw.setEchoMode(2)
vbox = QVBoxLayout()
label = QLabel(msg + "\n")
label.setWordWrap(True)
grid = QGridLayout()
grid.setSpacing(8)
grid.setColumnMinimumWidth(0, 150)
grid.setColumnMinimumWidth(1, 100)
grid.setColumnStretch(1,1)
vbox.addWidget(label)
grid.addWidget(QLabel(_('Passphrase:')), 0, 0)
grid.addWidget(new_pw, 0, 1)
if confirm:
grid.addWidget(QLabel(_('Confirm Passphrase:')), 1, 0)
grid.addWidget(conf_pw, 1, 1)
vbox.addLayout(grid)
def enable_OK():
if not confirm:
ok = True
else:
ok = new_pw.text() == conf_pw.text()
OK_button.setEnabled(ok)
new_pw.textChanged.connect(enable_OK)
conf_pw.textChanged.connect(enable_OK)
vbox.addWidget(OK_button)
if self.passphrase_on_device:
vbox.addWidget(OnDevice_button)
d.setLayout(vbox)
self.passphrase = None
def ok_clicked():
self.passphrase = new_pw.text()
def on_device_clicked():
self.passphrase = PASSPHRASE_ON_DEVICE
OK_button.clicked.connect(ok_clicked)
OnDevice_button.clicked.connect(on_device_clicked)
OnDevice_button.clicked.connect(d.accept)
d.exec_()
self.done.set()
class QtPlugin(QtPluginBase):
# Derived classes must provide the following class-static variables:
# icon_file
# pin_matrix_widget_class
def create_handler(self, window):
return QtHandler(window, self.pin_matrix_widget_class(), self.device)
@hook
def receive_menu(self, menu, addrs, wallet):
if len(addrs) != 1:
return
for keystore in wallet.get_keystores():
if type(keystore) == self.keystore_class:
def show_address():
keystore.thread.add(partial(self.show_address, wallet, addrs[0], keystore))
menu.addAction(_("Show on {}").format(self.device), show_address)
break
def show_settings_dialog(self, window, keystore):
device_id = self.choose_device(window, keystore)
if device_id:
SettingsDialog(window, self, keystore, device_id).exec_()
def request_trezor_init_settings(self, wizard, method, model):
vbox = QVBoxLayout()
next_enabled = True
label = QLabel(_("Enter a label to name your device:"))
name = QLineEdit()
hl = QHBoxLayout()
hl.addWidget(label)
hl.addWidget(name)
hl.addStretch(1)
vbox.addLayout(hl)
def clean_text(widget):
text = widget.toPlainText().strip()
return ' '.join(text.split())
gb = QGroupBox()
hbox1 = QHBoxLayout()
gb.setLayout(hbox1)
vbox.addWidget(gb)
gb.setTitle(_("Select your seed length:"))
bg_numwords = QButtonGroup()
for i, count in enumerate([12, 18, 24]):
rb = QRadioButton(gb)
rb.setText(_("%d words") % count)
bg_numwords.addButton(rb)
bg_numwords.setId(rb, i)
hbox1.addWidget(rb)
rb.setChecked(True)
cb_pin = QCheckBox(_('Enable PIN protection'))
cb_pin.setChecked(True)
vbox.addWidget(WWLabel(RECOMMEND_PIN))
vbox.addWidget(cb_pin)
passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
cb_phrase = QCheckBox(_('Enable passphrases'))
cb_phrase.setChecked(False)
vbox.addWidget(passphrase_msg)
vbox.addWidget(passphrase_warning)
vbox.addWidget(cb_phrase)
# ask for recovery type (random word order OR matrix)
if method == TIM_RECOVER and not model == 'T':
gb_rectype = QGroupBox()
hbox_rectype = QHBoxLayout()
gb_rectype.setLayout(hbox_rectype)
vbox.addWidget(gb_rectype)
gb_rectype.setTitle(_("Select recovery type:"))
bg_rectype = QButtonGroup()
rb1 = QRadioButton(gb_rectype)
rb1.setText(_('Scrambled words'))
bg_rectype.addButton(rb1)
bg_rectype.setId(rb1, RECOVERY_TYPE_SCRAMBLED_WORDS)
hbox_rectype.addWidget(rb1)
rb1.setChecked(True)
rb2 = QRadioButton(gb_rectype)
rb2.setText(_('Matrix'))
bg_rectype.addButton(rb2)
bg_rectype.setId(rb2, RECOVERY_TYPE_MATRIX)
hbox_rectype.addWidget(rb2)
else:
bg_rectype = None
wizard.exec_layout(vbox, next_enabled=next_enabled)
item = bg_numwords.checkedId()
pin = cb_pin.isChecked()
recovery_type = bg_rectype.checkedId() if bg_rectype else None
return (item, name.text(), pin, cb_phrase.isChecked(), recovery_type)
class Plugin(TrezorPlugin, QtPlugin):
icon_unpaired = ":icons/trezor_unpaired.png"
icon_paired = ":icons/trezor.png"
@classmethod
def pin_matrix_widget_class(self):
from trezorlib.qt.pinmatrix import PinMatrixWidget
return PinMatrixWidget
class SettingsDialog(WindowModalDialog):
'''This dialog doesn't require a device be paired with a wallet.
We want users to be able to wipe a device even if they've forgotten
their PIN.'''
last_hs_dir = None
def __init__(self, window, plugin, keystore, device_id):
title = _("{} Settings").format(plugin.device)
super(SettingsDialog, self).__init__(window, title)
self.setMaximumWidth(540)
devmgr = plugin.device_manager()
config = devmgr.config
handler = keystore.handler
thread = keystore.thread
is_model_T = devmgr.client_by_id(device_id) and devmgr.client_by_id(device_id).features.model == 'T'
if is_model_T:
hs_cols, hs_rows, hs_mono = 144, 144, False
else:
hs_cols, hs_rows, hs_mono = 128, 64, True
def invoke_client(method, *args, **kw_args):
unpair_after = kw_args.pop('unpair_after', False)
def task():
client = devmgr.client_by_id(device_id)
if not client:
raise RuntimeError("Device not connected")
if method:
getattr(client, method)(*args, **kw_args)
if unpair_after:
devmgr.unpair_id(device_id)
return client.features
thread.add(task, on_success=update)
def update(features):
self.features = features
set_label_enabled()
if features.bootloader_hash:
bl_hash = bh2u(features.bootloader_hash)
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
else:
bl_hash = "N/A"
noyes = [_("No"), _("Yes")]
endis = [_("Enable Passphrases"), _("Disable Passphrases")]
disen = [_("Disabled"), _("Enabled")]
setchange = [_("Set a PIN"), _("Change PIN")]
version = "%d.%d.%d" % (features.major_version,
features.minor_version,
features.patch_version)
device_label.setText(features.label)
pin_set_label.setText(noyes[features.pin_protection])
passphrases_label.setText(disen[features.passphrase_protection])
bl_hash_label.setText(bl_hash)
label_edit.setText(features.label)
device_id_label.setText(features.device_id)
initialized_label.setText(noyes[features.initialized])
version_label.setText(version)
clear_pin_button.setVisible(features.pin_protection)
clear_pin_warning.setVisible(features.pin_protection)
pin_button.setText(setchange[features.pin_protection])
pin_msg.setVisible(not features.pin_protection)
passphrase_button.setText(endis[features.passphrase_protection])
language_label.setText(features.language)
def set_label_enabled():
label_apply.setEnabled(label_edit.text() != self.features.label)
def rename():
invoke_client('change_label', label_edit.text())
def toggle_passphrase():
title = _("Confirm Toggle Passphrase Protection")
currently_enabled = self.features.passphrase_protection
if currently_enabled:
msg = _("After disabling passphrases, you can only pair this "
"Electron Cash wallet if it had an empty passphrase. "
"If its passphrase was not empty, you will need to "
"create a new wallet with the install wizard. You "
"can use this wallet again at any time by re-enabling "
"passphrases and entering its passphrase.")
else:
msg = _("Your current Electron Cash wallet can only be used "
"with an empty passphrase. You must create a separate "
"wallet with the install wizard for other passphrases "
"as each one generates a new set of addresses.")
msg += "\n\n" + _("Are you sure you want to proceed?")
if not self.question(msg, title=title):
return
invoke_client('toggle_passphrase', unpair_after=currently_enabled)
def change_homescreen():
le_dir = ((__class__.last_hs_dir and [__class__.last_hs_dir])
or QStandardPaths.standardLocations(QStandardPaths.DesktopLocation)
or QStandardPaths.standardLocations(QStandardPaths.PicturesLocation)
or QStandardPaths.standardLocations(QStandardPaths.HomeLocation)
or [''])[0]
filename, __ = QFileDialog.getOpenFileName(self, _("Choose Homescreen"), le_dir)
if not filename:
return # user cancelled
__class__.last_hs_dir = os.path.dirname(filename) # remember previous location
if filename.lower().endswith('.toif') or filename.lower().endswith('.toig'):
which = filename.lower()[-1].encode('ascii') # .toif or .toig = f or g in header
if which == b'g':
# For now I couldn't get Grayscale TOIG to work on any device, disabled
handler.show_error(_('Grayscale TOI files are not currently supported. Try a PNG or JPG file instead.'))
return
if not is_model_T:
handler.show_error(_('At this time, only the Trezor Model T supports the direct loading of TOIF files. Try a PNG or JPG file instead.'))
return
try:
img = open(filename, 'rb').read()
if img[:8] != b'TOI' + which + int(hs_cols).to_bytes(2, byteorder='little') + int(hs_rows).to_bytes(2, byteorder='little'):
handler.show_error(_('Image must be a TOI{} file of size {}x{}').format(which.decode('ascii').upper(), hs_cols, hs_rows))
return
except OSError as e:
handler.show_error('Error reading {}: {}'.format(filename, e))
return
else:
def read_and_convert_using_qt_to_raw_mono(handler, filename, hs_cols, hs_rows, invert=True):
img = QImage(filename)
if img.isNull():
handler.show_error(_('Could not load the image {} -- unknown format or other error').format(os.path.basename(filename)))
return
if (img.width(), img.height()) != (hs_cols, hs_rows): # do we need to scale it ?
img = img.scaled(hs_cols, hs_rows, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) # force to our dest size. Note that IgnoreAspectRatio guarantess the right size. Ther other modes don't
if img.isNull() or (img.width(), img.height()) != (hs_cols, hs_rows):
handler.show_error(_("Could not scale image to {} x {} pixels").format(hs_cols, hs_rows))
return
bm = QBitmap.fromImage(img, Qt.MonoOnly) # ensures 1bpp, dithers any colors
if bm.isNull():
handler.show_error(_('Could not convert image to monochrome'))
return
target_fmt = QImage.Format_Mono
img = bm.toImage().convertToFormat(target_fmt, Qt.MonoOnly|Qt.ThresholdDither|Qt.AvoidDither) # ensures MSB bytes again (above steps may have twiddled the bytes)
lineSzOut = hs_cols // 8 # bits -> num bytes per line
bimg = bytearray(hs_rows * lineSzOut) # 1024 bytes for a 128x64 img
bpl = img.bytesPerLine()
if bpl < lineSzOut:
handler.show_error(_("Internal error converting image"))
return
# read in 1 scan line at a time since the scan lines may be > our target packed image
for row in range(hs_rows):
# copy image scanlines 1 line at a time to destination buffer
ucharptr = img.constScanLine(row) # returned type is basically void*
ucharptr.setsize(bpl) # inform python how big this C array is
b = bytes(ucharptr) # aaand.. work with bytes.
begin = row * lineSzOut
end = begin + lineSzOut
bimg[begin:end] = b[0:lineSzOut]
if invert:
for i in range(begin, end):
bimg[i] = ~bimg[i] & 0xff # invert b/w
return bytes(bimg)
def read_and_convert_using_qt_to_toif(handler, filename, hs_cols, hs_rows):
img = QImage(filename)
if img.isNull():
handler.show_error(_('Could not load the image {} -- unknown format or other error').format(os.path.basename(filename)))
return
if (img.width(), img.height()) != (hs_cols, hs_rows): # do we need to scale it ?
img = img.scaled(hs_cols, hs_rows, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) # force to our dest size. Note that IgnoreAspectRatio guarantess the right size. Ther other modes don't
if img.isNull() or (img.width(), img.height()) != (hs_cols, hs_rows):
handler.show_error(_("Could not scale image to {} x {} pixels").format(hs_cols, hs_rows))
return
target_fmt = QImage.Format_RGB888
img = img.convertToFormat(QImage.Format_Indexed8).convertToFormat(target_fmt) # dither it down to 256 colors to reduce image complexity then back up to 24 bit for easy reading
if img.isNull():
handler.show_error(_("Could not dither or re-render image"))
return
def qimg_to_toif(img, handler):
try:
import struct, zlib
except ImportError as e:
handler.show_error(_("Could not convert image, a required library is missing: {}").format(e))
return
data, pixeldata = bytearray(), bytearray()
data += b'TOIf'
for y in range(img.width()):
for x in range(img.height()):
rgb = img.pixel(x,y)
r, g, b = qRed(rgb), qGreen(rgb), qBlue(rgb)
c = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | ((b & 0xF8) >> 3)
pixeldata += struct.pack(">H", c)
z = zlib.compressobj(level=9, wbits=10)
zdata = z.compress(bytes(pixeldata)) + z.flush()
zdata = zdata[2:-4] # strip header and checksum
data += struct.pack("<HH", img.width(), img.height())
data += struct.pack("<I", len(zdata))
data += zdata
return bytes(data)
return qimg_to_toif(img, handler)
# /read_and_convert_using_qt
if hs_mono and not is_model_T:
img = read_and_convert_using_qt_to_raw_mono(handler, filename, hs_cols, hs_rows)
else:
img = read_and_convert_using_qt_to_toif(handler, filename, hs_cols, hs_rows)
if not img:
return
invoke_client('change_homescreen', img)
def clear_homescreen():
invoke_client('change_homescreen', b'\x00')
def set_pin():
invoke_client('set_pin', remove=False)
def clear_pin():
invoke_client('set_pin', remove=True)
def wipe_device():
wallet = window.wallet
if wallet and sum(wallet.get_balance()):
title = _("Confirm Device Wipe")
msg = _("Are you SURE you want to wipe the device?\n"
"Your wallet still has bitcoins in it!")
if not self.question(msg, title=title,
icon=QMessageBox.Critical):
return
invoke_client('wipe_device', unpair_after=True)
def slider_moved():
mins = timeout_slider.sliderPosition()
timeout_minutes.setText(_("%2d minutes") % mins)
def slider_released():
config.set_session_timeout(timeout_slider.sliderPosition() * 60)
# Information tab
info_tab = QWidget()
info_layout = QVBoxLayout(info_tab)
info_glayout = QGridLayout()
info_glayout.setColumnStretch(2, 1)
device_label = QLabel()
pin_set_label = QLabel()
passphrases_label = QLabel()
version_label = QLabel()
device_id_label = QLabel()
bl_hash_label = QLabel()
bl_hash_label.setWordWrap(True)
language_label = QLabel()
initialized_label = QLabel()
rows = [
(_("Device Label"), device_label),
(_("PIN set"), pin_set_label),
(_("Passphrases"), passphrases_label),
(_("Firmware Version"), version_label),
(_("Device ID"), device_id_label),
(_("Bootloader Hash"), bl_hash_label),
(_("Language"), language_label),
(_("Initialized"), initialized_label),
]
for row_num, (label, widget) in enumerate(rows):
info_glayout.addWidget(QLabel(label), row_num, 0)
info_glayout.addWidget(widget, row_num, 1)
info_layout.addLayout(info_glayout)
# Settings tab
settings_tab = QWidget()
settings_layout = QVBoxLayout(settings_tab)
settings_glayout = QGridLayout()
# Settings tab - Label
label_msg = QLabel(_("Name this {}. If you have multiple devices "
"their labels help distinguish them.")
.format(plugin.device))
label_msg.setWordWrap(True)
label_label = QLabel(_("Device Label"))
label_edit = QLineEdit()
label_edit.setMinimumWidth(150)
label_edit.setMaxLength(plugin.MAX_LABEL_LEN)
label_apply = QPushButton(_("Apply"))
label_apply.clicked.connect(rename)
label_edit.textChanged.connect(set_label_enabled)
settings_glayout.addWidget(label_label, 0, 0)
settings_glayout.addWidget(label_edit, 0, 1, 1, 2)
settings_glayout.addWidget(label_apply, 0, 3)
settings_glayout.addWidget(label_msg, 1, 1, 1, -1)
# Settings tab - PIN
pin_label = QLabel(_("PIN Protection"))
pin_button = QPushButton()
pin_button.clicked.connect(set_pin)
settings_glayout.addWidget(pin_label, 2, 0)
settings_glayout.addWidget(pin_button, 2, 1)
pin_msg = QLabel(_("PIN protection is strongly recommended. "
"A PIN is your only protection against someone "
"stealing your bitcoins if they obtain physical "
"access to your {}.").format(plugin.device))
pin_msg.setWordWrap(True)
pin_msg.setStyleSheet("color: red")
settings_glayout.addWidget(pin_msg, 3, 1, 1, -1)
# Settings tab - Homescreen
homescreen_label = QLabel(_("Homescreen"))
homescreen_change_button = QPushButton(_("Change..."))
homescreen_clear_button = QPushButton(_("Reset"))
homescreen_change_button.clicked.connect(change_homescreen)
homescreen_clear_button.clicked.connect(clear_homescreen)
homescreen_msg = QLabel(_("You can set the homescreen on your "
"device to personalize it. You can choose any "
"image and it will be dithered, scaled and "
"converted to {} x {} {} "
"for the device.").format(hs_cols, hs_rows,
_("monochrome") if hs_mono
else _("color")))
homescreen_msg.setWordWrap(True)
settings_glayout.addWidget(homescreen_label, 4, 0)
settings_glayout.addWidget(homescreen_change_button, 4, 1)
settings_glayout.addWidget(homescreen_clear_button, 4, 2)
settings_glayout.addWidget(homescreen_msg, 5, 1, 1, -1)
# Settings tab - Session Timeout
timeout_label = QLabel(_("Session Timeout"))
timeout_minutes = QLabel()
timeout_slider = QSlider(Qt.Horizontal)
timeout_slider.setRange(1, 60)
timeout_slider.setSingleStep(1)
timeout_slider.setTickInterval(5)
timeout_slider.setTickPosition(QSlider.TicksBelow)
timeout_slider.setTracking(True)
timeout_msg = QLabel(
_("Clear the session after the specified period "
"of inactivity. Once a session has timed out, "
"your PIN and passphrase (if enabled) must be "
"re-entered to use the device."))
timeout_msg.setWordWrap(True)
timeout_slider.setSliderPosition(config.get_session_timeout() // 60)
slider_moved()
timeout_slider.valueChanged.connect(slider_moved)
timeout_slider.sliderReleased.connect(slider_released)
settings_glayout.addWidget(timeout_label, 6, 0)
settings_glayout.addWidget(timeout_slider, 6, 1, 1, 3)
settings_glayout.addWidget(timeout_minutes, 6, 4)
settings_glayout.addWidget(timeout_msg, 7, 1, 1, -1)
settings_layout.addLayout(settings_glayout)
settings_layout.addStretch(1)
# Advanced tab
advanced_tab = QWidget()
advanced_layout = QVBoxLayout(advanced_tab)
advanced_glayout = QGridLayout()
# Advanced tab - clear PIN
clear_pin_button = QPushButton(_("Disable PIN"))
clear_pin_button.clicked.connect(clear_pin)
clear_pin_warning = QLabel(
_("If you disable your PIN, anyone with physical access to your "
"{} device can spend your bitcoins.").format(plugin.device))
clear_pin_warning.setWordWrap(True)
clear_pin_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(clear_pin_button, 0, 2)
advanced_glayout.addWidget(clear_pin_warning, 1, 0, 1, 5)
# Advanced tab - toggle passphrase protection
passphrase_button = QPushButton()
passphrase_button.clicked.connect(toggle_passphrase)
passphrase_msg = WWLabel(PASSPHRASE_HELP)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(passphrase_button, 3, 2)
advanced_glayout.addWidget(passphrase_msg, 4, 0, 1, 5)
advanced_glayout.addWidget(passphrase_warning, 5, 0, 1, 5)
# Advanced tab - wipe device
wipe_device_button = QPushButton(_("Wipe Device"))
wipe_device_button.clicked.connect(wipe_device)
wipe_device_msg = QLabel(
_("Wipe the device, removing all data from it. The firmware "
"is left unchanged."))
wipe_device_msg.setWordWrap(True)
wipe_device_warning = QLabel(
_("Only wipe a device if you have the recovery seed written down "
"and the device wallet(s) are empty, otherwise the bitcoins "
"will be lost forever."))
wipe_device_warning.setWordWrap(True)
wipe_device_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(wipe_device_button, 6, 2)
advanced_glayout.addWidget(wipe_device_msg, 7, 0, 1, 5)
advanced_glayout.addWidget(wipe_device_warning, 8, 0, 1, 5)
advanced_layout.addLayout(advanced_glayout)
advanced_layout.addStretch(1)
tabs = QTabWidget(self)
tabs.addTab(info_tab, _("Information"))
tabs.addTab(settings_tab, _("Settings"))
tabs.addTab(advanced_tab, _("Advanced"))
dialog_vbox = QVBoxLayout(self)
dialog_vbox.addWidget(tabs)
dialog_vbox.addLayout(Buttons(CloseButton(self)))
# Update information
invoke_client(None)
| {
"repo_name": "fyookball/electrum",
"path": "plugins/trezor/qt.py",
"copies": "1",
"size": "32125",
"license": "mit",
"hash": 4931258013632729000,
"line_mean": 42.4709066306,
"line_max": 209,
"alpha_frac": 0.572233463,
"autogenerated": false,
"ratio": 4.061314791403287,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0010429663440114278,
"num_lines": 739
} |
from functools import partial
import threading
from PyQt4.Qt import Qt
from PyQt4.Qt import QGridLayout, QInputDialog, QPushButton
from PyQt4.Qt import QVBoxLayout, QLabel, SIGNAL
from electrum_arg_gui.qt.util import *
from .plugin import TIM_NEW, TIM_RECOVER, TIM_MNEMONIC
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
from electrum_arg_gui.i18n import _
from electrum_arg_gui.plugins import hook, DeviceMgr
from electrum_arg_gui.util import PrintError, UserCancelled
from electrum_arg_gui.wallet import Wallet, Standard_Wallet
PASSPHRASE_HELP_SHORT =_(
"Passphrases allow you to access new wallets, each "
"hidden behind a particular case-sensitive passphrase.")
PASSPHRASE_HELP = PASSPHRASE_HELP_SHORT + " " + _(
"You need to create a separate Electrum wallet for each passphrase "
"you use as they each generate different addresses. Changing "
"your passphrase does not lose other wallets, each is still "
"accessible behind its own passphrase.")
RECOMMEND_PIN = _(
"You should enable PIN protection. Your PIN is the only protection "
"for your argentums if your device is lost or stolen.")
PASSPHRASE_NOT_PIN = _(
"If you forget a passphrase you will be unable to access any "
"argentums in the wallet behind it. A passphrase is not a PIN. "
"Only change this if you are sure you understand it.")
CHARACTER_RECOVERY = (
"Use the recovery cipher shown on your device to input your seed words. "
"The cipher changes with every keypress.\n"
"After at most 4 letters the device will auto-complete a word.\n"
"Press SPACE or the Accept Word button to accept the device's auto-"
"completed word and advance to the next one.\n"
"Press BACKSPACE to go back a character or word.\n"
"Press ENTER or the Seed Entered button once the last word in your "
"seed is auto-completed.")
class CharacterButton(QPushButton):
def __init__(self, text=None):
QPushButton.__init__(self, text)
def keyPressEvent(self, event):
event.setAccepted(False) # Pass through Enter and Space keys
class CharacterDialog(WindowModalDialog):
def __init__(self, parent):
super(CharacterDialog, self).__init__(parent)
self.setWindowTitle(_("KeepKey Seed Recovery"))
self.character_pos = 0
self.word_pos = 0
self.loop = QEventLoop()
self.word_help = QLabel()
self.char_buttons = []
vbox = QVBoxLayout(self)
vbox.addWidget(WWLabel(CHARACTER_RECOVERY))
hbox = QHBoxLayout()
hbox.addWidget(self.word_help)
for i in range(4):
char_button = CharacterButton('*')
char_button.setMaximumWidth(36)
self.char_buttons.append(char_button)
hbox.addWidget(char_button)
self.accept_button = CharacterButton(_("Accept Word"))
self.accept_button.clicked.connect(partial(self.process_key, 32))
self.rejected.connect(partial(self.loop.exit, 1))
hbox.addWidget(self.accept_button)
hbox.addStretch(1)
vbox.addLayout(hbox)
self.finished_button = QPushButton(_("Seed Entered"))
self.cancel_button = QPushButton(_("Cancel"))
self.finished_button.clicked.connect(partial(self.process_key,
Qt.Key_Return))
self.cancel_button.clicked.connect(self.rejected)
buttons = Buttons(self.finished_button, self.cancel_button)
vbox.addSpacing(40)
vbox.addLayout(buttons)
self.refresh()
self.show()
def refresh(self):
self.word_help.setText("Enter seed word %2d:" % (self.word_pos + 1))
self.accept_button.setEnabled(self.character_pos >= 3)
self.finished_button.setEnabled((self.word_pos in (11, 17, 23)
and self.character_pos >= 3))
for n, button in enumerate(self.char_buttons):
button.setEnabled(n == self.character_pos)
if n == self.character_pos:
button.setFocus()
def is_valid_alpha_space(self, key):
# Auto-completion requires at least 3 characters
if key == ord(' ') and self.character_pos >= 3:
return True
# Firmware aborts protocol if the 5th character is non-space
if self.character_pos >= 4:
return False
return (key >= ord('a') and key <= ord('z')
or (key >= ord('A') and key <= ord('Z')))
def process_key(self, key):
self.data = None
if key == Qt.Key_Return and self.finished_button.isEnabled():
self.data = {'done': True}
elif key == Qt.Key_Backspace and (self.word_pos or self.character_pos):
self.data = {'delete': True}
elif self.is_valid_alpha_space(key):
self.data = {'character': chr(key).lower()}
if self.data:
self.loop.exit(0)
def keyPressEvent(self, event):
self.process_key(event.key())
if not self.data:
QDialog.keyPressEvent(self, event)
def get_char(self, word_pos, character_pos):
self.word_pos = word_pos
self.character_pos = character_pos
self.refresh()
if self.loop.exec_():
self.data = None # User cancelled
class QtHandler(QtHandlerBase):
char_signal = pyqtSignal(object)
pin_signal = pyqtSignal(object)
def __init__(self, win, pin_matrix_widget_class, device):
super(QtHandler, self).__init__(win, device)
self.char_signal.connect(self.update_character_dialog)
self.pin_signal.connect(self.pin_dialog)
self.pin_matrix_widget_class = pin_matrix_widget_class
self.character_dialog = None
def get_char(self, msg):
self.done.clear()
self.char_signal.emit(msg)
self.done.wait()
data = self.character_dialog.data
if not data or 'done' in data:
self.character_dialog.accept()
self.character_dialog = None
return data
def get_pin(self, msg):
self.done.clear()
self.pin_signal.emit(msg)
self.done.wait()
return self.response
def pin_dialog(self, msg):
# Needed e.g. when resetting a device
self.clear_dialog()
dialog = WindowModalDialog(self.top_level_window(), _("Enter PIN"))
matrix = self.pin_matrix_widget_class()
vbox = QVBoxLayout()
vbox.addWidget(QLabel(msg))
vbox.addWidget(matrix)
vbox.addLayout(Buttons(CancelButton(dialog), OkButton(dialog)))
dialog.setLayout(vbox)
dialog.exec_()
self.response = str(matrix.get_value())
self.done.set()
def update_character_dialog(self, msg):
if not self.character_dialog:
self.character_dialog = CharacterDialog(self.top_level_window())
self.character_dialog.get_char(msg.word_pos, msg.character_pos)
self.done.set()
class QtPlugin(QtPluginBase):
# Derived classes must provide the following class-static variables:
# icon_file
# pin_matrix_widget_class
def create_handler(self, window):
return QtHandler(window, self.pin_matrix_widget_class(), self.device)
@hook
def receive_menu(self, menu, addrs, wallet):
if type(wallet) is not Standard_Wallet:
return
keystore = wallet.get_keystore()
if type(keystore) == self.keystore_class and len(addrs) == 1:
def show_address():
keystore.thread.add(partial(self.show_address, wallet, addrs[0]))
menu.addAction(_("Show on %s") % self.device, show_address)
def show_settings_dialog(self, window, keystore):
device_id = self.choose_device(window, keystore)
if device_id:
SettingsDialog(window, self, keystore, device_id).exec_()
def request_trezor_init_settings(self, wizard, method, device):
vbox = QVBoxLayout()
next_enabled = True
label = QLabel(_("Enter a label to name your device:"))
name = QLineEdit()
hl = QHBoxLayout()
hl.addWidget(label)
hl.addWidget(name)
hl.addStretch(1)
vbox.addLayout(hl)
def clean_text(widget):
text = unicode(widget.toPlainText()).strip()
return ' '.join(text.split())
if method in [TIM_NEW, TIM_RECOVER]:
gb = QGroupBox()
hbox1 = QHBoxLayout()
gb.setLayout(hbox1)
# KeepKey recovery doesn't need a word count
if method == TIM_NEW or self.device == 'TREZOR':
vbox.addWidget(gb)
gb.setTitle(_("Select your seed length:"))
bg = QButtonGroup()
for i, count in enumerate([12, 18, 24]):
rb = QRadioButton(gb)
rb.setText(_("%d words") % count)
bg.addButton(rb)
bg.setId(rb, i)
hbox1.addWidget(rb)
rb.setChecked(True)
cb_pin = QCheckBox(_('Enable PIN protection'))
cb_pin.setChecked(True)
else:
text = QTextEdit()
text.setMaximumHeight(60)
if method == TIM_MNEMONIC:
msg = _("Enter your BIP39 mnemonic:")
else:
msg = _("Enter the master private key beginning with xprv:")
def set_enabled():
from electrum_arg.keystore import is_xprv
wizard.next_button.setEnabled(is_xprv(clean_text(text)))
text.textChanged.connect(set_enabled)
next_enabled = False
vbox.addWidget(QLabel(msg))
vbox.addWidget(text)
pin = QLineEdit()
pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,10}')))
pin.setMaximumWidth(100)
hbox_pin = QHBoxLayout()
hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):")))
hbox_pin.addWidget(pin)
hbox_pin.addStretch(1)
if method in [TIM_NEW, TIM_RECOVER]:
vbox.addWidget(WWLabel(RECOMMEND_PIN))
vbox.addWidget(cb_pin)
else:
vbox.addLayout(hbox_pin)
passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
cb_phrase = QCheckBox(_('Enable passphrases'))
cb_phrase.setChecked(False)
vbox.addWidget(passphrase_msg)
vbox.addWidget(passphrase_warning)
vbox.addWidget(cb_phrase)
wizard.exec_layout(vbox, next_enabled=next_enabled)
if method in [TIM_NEW, TIM_RECOVER]:
item = bg.checkedId()
pin = cb_pin.isChecked()
else:
item = ' '.join(str(clean_text(text)).split())
pin = str(pin.text())
return (item, unicode(name.text()), pin, cb_phrase.isChecked())
class SettingsDialog(WindowModalDialog):
'''This dialog doesn't require a device be paired with a wallet.
We want users to be able to wipe a device even if they've forgotten
their PIN.'''
def __init__(self, window, plugin, keystore, device_id):
title = _("%s Settings") % plugin.device
super(SettingsDialog, self).__init__(window, title)
self.setMaximumWidth(540)
devmgr = plugin.device_manager()
config = devmgr.config
handler = keystore.handler
thread = keystore.thread
hs_rows, hs_cols = (64, 128)
def invoke_client(method, *args, **kw_args):
unpair_after = kw_args.pop('unpair_after', False)
def task():
client = devmgr.client_by_id(device_id)
if not client:
raise RuntimeError("Device not connected")
if method:
getattr(client, method)(*args, **kw_args)
if unpair_after:
devmgr.unpair_id(device_id)
return client.features
thread.add(task, on_success=update)
def update(features):
self.features = features
set_label_enabled()
bl_hash = features.bootloader_hash.encode('hex')
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
noyes = [_("No"), _("Yes")]
endis = [_("Enable Passphrases"), _("Disable Passphrases")]
disen = [_("Disabled"), _("Enabled")]
setchange = [_("Set a PIN"), _("Change PIN")]
version = "%d.%d.%d" % (features.major_version,
features.minor_version,
features.patch_version)
coins = ", ".join(coin.coin_name for coin in features.coins)
device_label.setText(features.label)
pin_set_label.setText(noyes[features.pin_protection])
passphrases_label.setText(disen[features.passphrase_protection])
bl_hash_label.setText(bl_hash)
label_edit.setText(features.label)
device_id_label.setText(features.device_id)
initialized_label.setText(noyes[features.initialized])
version_label.setText(version)
coins_label.setText(coins)
clear_pin_button.setVisible(features.pin_protection)
clear_pin_warning.setVisible(features.pin_protection)
pin_button.setText(setchange[features.pin_protection])
pin_msg.setVisible(not features.pin_protection)
passphrase_button.setText(endis[features.passphrase_protection])
language_label.setText(features.language)
def set_label_enabled():
label_apply.setEnabled(label_edit.text() != self.features.label)
def rename():
invoke_client('change_label', unicode(label_edit.text()))
def toggle_passphrase():
title = _("Confirm Toggle Passphrase Protection")
currently_enabled = self.features.passphrase_protection
if currently_enabled:
msg = _("After disabling passphrases, you can only pair this "
"Electrum wallet if it had an empty passphrase. "
"If its passphrase was not empty, you will need to "
"create a new wallet with the install wizard. You "
"can use this wallet again at any time by re-enabling "
"passphrases and entering its passphrase.")
else:
msg = _("Your current Electrum wallet can only be used with "
"an empty passphrase. You must create a separate "
"wallet with the install wizard for other passphrases "
"as each one generates a new set of addresses.")
msg += "\n\n" + _("Are you sure you want to proceed?")
if not self.question(msg, title=title):
return
invoke_client('toggle_passphrase', unpair_after=currently_enabled)
def change_homescreen():
from PIL import Image # FIXME
dialog = QFileDialog(self, _("Choose Homescreen"))
filename = dialog.getOpenFileName()
if filename:
im = Image.open(str(filename))
if im.size != (hs_cols, hs_rows):
raise Exception('Image must be 64 x 128 pixels')
im = im.convert('1')
pix = im.load()
img = ''
for j in range(hs_rows):
for i in range(hs_cols):
img += '1' if pix[i, j] else '0'
img = ''.join(chr(int(img[i:i + 8], 2))
for i in range(0, len(img), 8))
invoke_client('change_homescreen', img)
def clear_homescreen():
invoke_client('change_homescreen', '\x00')
def set_pin():
invoke_client('set_pin', remove=False)
def clear_pin():
invoke_client('set_pin', remove=True)
def wipe_device():
wallet = window.wallet
if wallet and sum(wallet.get_balance()):
title = _("Confirm Device Wipe")
msg = _("Are you SURE you want to wipe the device?\n"
"Your wallet still has argentums in it!")
if not self.question(msg, title=title,
icon=QMessageBox.Critical):
return
invoke_client('wipe_device', unpair_after=True)
def slider_moved():
mins = timeout_slider.sliderPosition()
timeout_minutes.setText(_("%2d minutes") % mins)
def slider_released():
config.set_session_timeout(timeout_slider.sliderPosition() * 60)
# Information tab
info_tab = QWidget()
info_layout = QVBoxLayout(info_tab)
info_glayout = QGridLayout()
info_glayout.setColumnStretch(2, 1)
device_label = QLabel()
pin_set_label = QLabel()
passphrases_label = QLabel()
version_label = QLabel()
device_id_label = QLabel()
bl_hash_label = QLabel()
bl_hash_label.setWordWrap(True)
coins_label = QLabel()
coins_label.setWordWrap(True)
language_label = QLabel()
initialized_label = QLabel()
rows = [
(_("Device Label"), device_label),
(_("PIN set"), pin_set_label),
(_("Passphrases"), passphrases_label),
(_("Firmware Version"), version_label),
(_("Device ID"), device_id_label),
(_("Bootloader Hash"), bl_hash_label),
(_("Supported Coins"), coins_label),
(_("Language"), language_label),
(_("Initialized"), initialized_label),
]
for row_num, (label, widget) in enumerate(rows):
info_glayout.addWidget(QLabel(label), row_num, 0)
info_glayout.addWidget(widget, row_num, 1)
info_layout.addLayout(info_glayout)
# Settings tab
settings_tab = QWidget()
settings_layout = QVBoxLayout(settings_tab)
settings_glayout = QGridLayout()
# Settings tab - Label
label_msg = QLabel(_("Name this %s. If you have mutiple devices "
"their labels help distinguish them.")
% plugin.device)
label_msg.setWordWrap(True)
label_label = QLabel(_("Device Label"))
label_edit = QLineEdit()
label_edit.setMinimumWidth(150)
label_edit.setMaxLength(plugin.MAX_LABEL_LEN)
label_apply = QPushButton(_("Apply"))
label_apply.clicked.connect(rename)
label_edit.textChanged.connect(set_label_enabled)
settings_glayout.addWidget(label_label, 0, 0)
settings_glayout.addWidget(label_edit, 0, 1, 1, 2)
settings_glayout.addWidget(label_apply, 0, 3)
settings_glayout.addWidget(label_msg, 1, 1, 1, -1)
# Settings tab - PIN
pin_label = QLabel(_("PIN Protection"))
pin_button = QPushButton()
pin_button.clicked.connect(set_pin)
settings_glayout.addWidget(pin_label, 2, 0)
settings_glayout.addWidget(pin_button, 2, 1)
pin_msg = QLabel(_("PIN protection is strongly recommended. "
"A PIN is your only protection against someone "
"stealing your argentums if they obtain physical "
"access to your %s.") % plugin.device)
pin_msg.setWordWrap(True)
pin_msg.setStyleSheet("color: red")
settings_glayout.addWidget(pin_msg, 3, 1, 1, -1)
# Settings tab - Homescreen
if plugin.device != 'KeepKey': # Not yet supported by KK firmware
homescreen_layout = QHBoxLayout()
homescreen_label = QLabel(_("Homescreen"))
homescreen_change_button = QPushButton(_("Change..."))
homescreen_clear_button = QPushButton(_("Reset"))
homescreen_change_button.clicked.connect(change_homescreen)
homescreen_clear_button.clicked.connect(clear_homescreen)
homescreen_msg = QLabel(_("You can set the homescreen on your "
"device to personalize it. You must "
"choose a %d x %d monochrome black and "
"white image.") % (hs_rows, hs_cols))
homescreen_msg.setWordWrap(True)
settings_glayout.addWidget(homescreen_label, 4, 0)
settings_glayout.addWidget(homescreen_change_button, 4, 1)
settings_glayout.addWidget(homescreen_clear_button, 4, 2)
settings_glayout.addWidget(homescreen_msg, 5, 1, 1, -1)
# Settings tab - Session Timeout
timeout_label = QLabel(_("Session Timeout"))
timeout_minutes = QLabel()
timeout_slider = QSlider(Qt.Horizontal)
timeout_slider.setRange(1, 60)
timeout_slider.setSingleStep(1)
timeout_slider.setTickInterval(5)
timeout_slider.setTickPosition(QSlider.TicksBelow)
timeout_slider.setTracking(True)
timeout_msg = QLabel(
_("Clear the session after the specified period "
"of inactivity. Once a session has timed out, "
"your PIN and passphrase (if enabled) must be "
"re-entered to use the device."))
timeout_msg.setWordWrap(True)
timeout_slider.setSliderPosition(config.get_session_timeout() // 60)
slider_moved()
timeout_slider.valueChanged.connect(slider_moved)
timeout_slider.sliderReleased.connect(slider_released)
settings_glayout.addWidget(timeout_label, 6, 0)
settings_glayout.addWidget(timeout_slider, 6, 1, 1, 3)
settings_glayout.addWidget(timeout_minutes, 6, 4)
settings_glayout.addWidget(timeout_msg, 7, 1, 1, -1)
settings_layout.addLayout(settings_glayout)
settings_layout.addStretch(1)
# Advanced tab
advanced_tab = QWidget()
advanced_layout = QVBoxLayout(advanced_tab)
advanced_glayout = QGridLayout()
# Advanced tab - clear PIN
clear_pin_button = QPushButton(_("Disable PIN"))
clear_pin_button.clicked.connect(clear_pin)
clear_pin_warning = QLabel(
_("If you disable your PIN, anyone with physical access to your "
"%s device can spend your argentums.") % plugin.device)
clear_pin_warning.setWordWrap(True)
clear_pin_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(clear_pin_button, 0, 2)
advanced_glayout.addWidget(clear_pin_warning, 1, 0, 1, 5)
# Advanced tab - toggle passphrase protection
passphrase_button = QPushButton()
passphrase_button.clicked.connect(toggle_passphrase)
passphrase_msg = WWLabel(PASSPHRASE_HELP)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(passphrase_button, 3, 2)
advanced_glayout.addWidget(passphrase_msg, 4, 0, 1, 5)
advanced_glayout.addWidget(passphrase_warning, 5, 0, 1, 5)
# Advanced tab - wipe device
wipe_device_button = QPushButton(_("Wipe Device"))
wipe_device_button.clicked.connect(wipe_device)
wipe_device_msg = QLabel(
_("Wipe the device, removing all data from it. The firmware "
"is left unchanged."))
wipe_device_msg.setWordWrap(True)
wipe_device_warning = QLabel(
_("Only wipe a device if you have the recovery seed written down "
"and the device wallet(s) are empty, otherwise the argentums "
"will be lost forever."))
wipe_device_warning.setWordWrap(True)
wipe_device_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(wipe_device_button, 6, 2)
advanced_glayout.addWidget(wipe_device_msg, 7, 0, 1, 5)
advanced_glayout.addWidget(wipe_device_warning, 8, 0, 1, 5)
advanced_layout.addLayout(advanced_glayout)
advanced_layout.addStretch(1)
tabs = QTabWidget(self)
tabs.addTab(info_tab, _("Information"))
tabs.addTab(settings_tab, _("Settings"))
tabs.addTab(advanced_tab, _("Advanced"))
dialog_vbox = QVBoxLayout(self)
dialog_vbox.addWidget(tabs)
dialog_vbox.addLayout(Buttons(CloseButton(self)))
# Update information
invoke_client(None)
| {
"repo_name": "argentumproject/electrum-arg",
"path": "plugins/trezor/qt_generic.py",
"copies": "1",
"size": "24633",
"license": "mit",
"hash": 7361657130939525000,
"line_mean": 40.8928571429,
"line_max": 81,
"alpha_frac": 0.5902244956,
"autogenerated": false,
"ratio": 4.037534830355679,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0002801521156424093,
"num_lines": 588
} |
from functools import partial
import threading
from PyQt4.Qt import Qt
from PyQt4.Qt import QGridLayout, QInputDialog, QPushButton
from PyQt4.Qt import QVBoxLayout, QLabel, SIGNAL
from electrum_cesc_gui.qt.main_window import StatusBarButton
from electrum_cesc_gui.qt.util import *
from .plugin import TIM_NEW, TIM_RECOVER, TIM_MNEMONIC
from ..hw_wallet.qt import QtHandlerBase
from electrum_cesc.i18n import _
from electrum_cesc.plugins import hook, DeviceMgr
from electrum_cesc.util import PrintError, UserCancelled
from electrum_cesc.wallet import Wallet, BIP44_Wallet
PASSPHRASE_HELP_SHORT =_(
"Passphrases allow you to access new wallets, each "
"hidden behind a particular case-sensitive passphrase.")
PASSPHRASE_HELP = PASSPHRASE_HELP_SHORT + " " + _(
"You need to create a separate Electrum wallet for each passphrase "
"you use as they each generate different addresses. Changing "
"your passphrase does not lose other wallets, each is still "
"accessible behind its own passphrase.")
RECOMMEND_PIN = _(
"You should enable PIN protection. Your PIN is the only protection "
"for your cryptoescudos if your device is lost or stolen.")
PASSPHRASE_NOT_PIN = _(
"If you forget a passphrase you will be unable to access any "
"cryptoescudos in the wallet behind it. A passphrase is not a PIN. "
"Only change this if you are sure you understand it.")
CHARACTER_RECOVERY = (
"Use the recovery cipher shown on your device to input your seed words. "
"The cipher changes with every keypress.\n"
"After at most 4 letters the device will auto-complete a word.\n"
"Press SPACE or the Accept Word button to accept the device's auto-"
"completed word and advance to the next one.\n"
"Press BACKSPACE to go back a character or word.\n"
"Press ENTER or the Seed Entered button once the last word in your "
"seed is auto-completed.")
class CharacterButton(QPushButton):
def __init__(self, text=None):
QPushButton.__init__(self, text)
def keyPressEvent(self, event):
event.setAccepted(False) # Pass through Enter and Space keys
class CharacterDialog(WindowModalDialog):
def __init__(self, parent):
super(CharacterDialog, self).__init__(parent)
self.setWindowTitle(_("KeepKey Seed Recovery"))
self.character_pos = 0
self.word_pos = 0
self.loop = QEventLoop()
self.word_help = QLabel()
self.char_buttons = []
vbox = QVBoxLayout(self)
vbox.addWidget(WWLabel(CHARACTER_RECOVERY))
hbox = QHBoxLayout()
hbox.addWidget(self.word_help)
for i in range(4):
char_button = CharacterButton('*')
char_button.setMaximumWidth(36)
self.char_buttons.append(char_button)
hbox.addWidget(char_button)
self.accept_button = CharacterButton(_("Accept Word"))
self.accept_button.clicked.connect(partial(self.process_key, 32))
self.rejected.connect(partial(self.loop.exit, 1))
hbox.addWidget(self.accept_button)
hbox.addStretch(1)
vbox.addLayout(hbox)
self.finished_button = QPushButton(_("Seed Entered"))
self.cancel_button = QPushButton(_("Cancel"))
self.finished_button.clicked.connect(partial(self.process_key,
Qt.Key_Return))
self.cancel_button.clicked.connect(self.rejected)
buttons = Buttons(self.finished_button, self.cancel_button)
vbox.addSpacing(40)
vbox.addLayout(buttons)
self.refresh()
self.show()
def refresh(self):
self.word_help.setText("Enter seed word %2d:" % (self.word_pos + 1))
self.accept_button.setEnabled(self.character_pos >= 3)
self.finished_button.setEnabled((self.word_pos in (11, 17, 23)
and self.character_pos >= 3))
for n, button in enumerate(self.char_buttons):
button.setEnabled(n == self.character_pos)
if n == self.character_pos:
button.setFocus()
def is_valid_alpha_space(self, key):
# Auto-completion requires at least 3 characters
if key == ord(' ') and self.character_pos >= 3:
return True
# Firmware aborts protocol if the 5th character is non-space
if self.character_pos >= 4:
return False
return (key >= ord('a') and key <= ord('z')
or (key >= ord('A') and key <= ord('Z')))
def process_key(self, key):
self.data = None
if key == Qt.Key_Return and self.finished_button.isEnabled():
self.data = {'done': True}
elif key == Qt.Key_Backspace and (self.word_pos or self.character_pos):
self.data = {'delete': True}
elif self.is_valid_alpha_space(key):
self.data = {'character': chr(key).lower()}
if self.data:
self.loop.exit(0)
def keyPressEvent(self, event):
self.process_key(event.key())
if not self.data:
QDialog.keyPressEvent(self, event)
def get_char(self, word_pos, character_pos):
self.word_pos = word_pos
self.character_pos = character_pos
self.refresh()
if self.loop.exec_():
self.data = None # User cancelled
class QtHandler(QtHandlerBase):
charSig = pyqtSignal(object)
def __init__(self, win, pin_matrix_widget_class, device):
super(QtHandler, self).__init__(win, device)
win.connect(win, SIGNAL('pin_dialog'), self.pin_dialog)
self.charSig.connect(self.update_character_dialog)
self.pin_matrix_widget_class = pin_matrix_widget_class
self.character_dialog = None
def get_char(self, msg):
self.done.clear()
self.charSig.emit(msg)
self.done.wait()
data = self.character_dialog.data
if not data or 'done' in data:
self.character_dialog.accept()
self.character_dialog = None
return data
def get_pin(self, msg):
self.done.clear()
self.win.emit(SIGNAL('pin_dialog'), msg)
self.done.wait()
return self.response
def pin_dialog(self, msg):
# Needed e.g. when resetting a device
self.clear_dialog()
dialog = WindowModalDialog(self.top_level_window(), _("Enter PIN"))
matrix = self.pin_matrix_widget_class()
vbox = QVBoxLayout()
vbox.addWidget(QLabel(msg))
vbox.addWidget(matrix)
vbox.addLayout(Buttons(CancelButton(dialog), OkButton(dialog)))
dialog.setLayout(vbox)
dialog.exec_()
self.response = str(matrix.get_value())
self.done.set()
def update_character_dialog(self, msg):
if not self.character_dialog:
self.character_dialog = CharacterDialog(self.top_level_window())
self.character_dialog.get_char(msg.word_pos, msg.character_pos)
self.done.set()
def request_trezor_init_settings(self, method, device):
wizard = self.win
vbox = QVBoxLayout()
next_enabled=True
label = QLabel(_("Enter a label to name your device:"))
name = QLineEdit()
hl = QHBoxLayout()
hl.addWidget(label)
hl.addWidget(name)
hl.addStretch(1)
vbox.addLayout(hl)
def clean_text(widget):
text = unicode(widget.toPlainText()).strip()
return ' '.join(text.split())
if method in [TIM_NEW, TIM_RECOVER]:
gb = QGroupBox()
hbox1 = QHBoxLayout()
gb.setLayout(hbox1)
# KeepKey recovery doesn't need a word count
if method == TIM_NEW or self.device == 'TREZOR':
vbox.addWidget(gb)
gb.setTitle(_("Select your seed length:"))
bg = QButtonGroup()
for i, count in enumerate([12, 18, 24]):
rb = QRadioButton(gb)
rb.setText(_("%d words") % count)
bg.addButton(rb)
bg.setId(rb, i)
hbox1.addWidget(rb)
rb.setChecked(True)
cb_pin = QCheckBox(_('Enable PIN protection'))
cb_pin.setChecked(True)
else:
text = QTextEdit()
text.setMaximumHeight(60)
if method == TIM_MNEMONIC:
msg = _("Enter your BIP39 mnemonic:")
else:
msg = _("Enter the master private key beginning with xprv:")
def set_enabled():
wizard.next_button.setEnabled(Wallet.is_xprv(clean_text(text)))
text.textChanged.connect(set_enabled)
next_enabled = False
vbox.addWidget(QLabel(msg))
vbox.addWidget(text)
pin = QLineEdit()
pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,10}')))
pin.setMaximumWidth(100)
hbox_pin = QHBoxLayout()
hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):")))
hbox_pin.addWidget(pin)
hbox_pin.addStretch(1)
if method in [TIM_NEW, TIM_RECOVER]:
vbox.addWidget(WWLabel(RECOMMEND_PIN))
vbox.addWidget(cb_pin)
else:
vbox.addLayout(hbox_pin)
passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
cb_phrase = QCheckBox(_('Enable passphrases'))
cb_phrase.setChecked(False)
vbox.addWidget(passphrase_msg)
vbox.addWidget(passphrase_warning)
vbox.addWidget(cb_phrase)
wizard.set_main_layout(vbox, next_enabled=next_enabled)
if method in [TIM_NEW, TIM_RECOVER]:
item = bg.checkedId()
pin = cb_pin.isChecked()
else:
item = ' '.join(str(clean_text(text)).split())
pin = str(pin.text())
return (item, unicode(name.text()), pin, cb_phrase.isChecked())
def qt_plugin_class(base_plugin_class):
class QtPlugin(base_plugin_class):
# Derived classes must provide the following class-static variables:
# icon_file
# pin_matrix_widget_class
def create_handler(self, window):
return QtHandler(window, self.pin_matrix_widget_class(), self.device)
@hook
def load_wallet(self, wallet, window):
if type(wallet) != self.wallet_class:
return
window.tzb = StatusBarButton(QIcon(self.icon_file), self.device,
partial(self.settings_dialog, window))
window.statusBar().addPermanentWidget(window.tzb)
wallet.handler = self.create_handler(window)
# Trigger a pairing
wallet.thread.add(partial(self.get_client, wallet))
def on_create_wallet(self, wallet, wizard):
assert type(wallet) == self.wallet_class
wallet.handler = self.create_handler(wizard)
wallet.thread = TaskThread(wizard, wizard.on_error)
# Setup device and create accounts in separate thread; wait until done
loop = QEventLoop()
exc_info = []
self.setup_device(wallet, on_done=loop.quit,
on_error=lambda info: exc_info.extend(info))
loop.exec_()
# If an exception was thrown, show to user and exit install wizard
if exc_info:
wizard.on_error(exc_info)
raise UserCancelled
@hook
def receive_menu(self, menu, addrs, wallet):
if type(wallet) == self.wallet_class and len(addrs) == 1:
def show_address():
wallet.thread.add(partial(self.show_address, wallet, addrs[0]))
menu.addAction(_("Show on %s") % self.device, show_address)
def settings_dialog(self, window):
device_id = self.choose_device(window)
if device_id:
SettingsDialog(window, self, device_id).exec_()
def choose_device(self, window):
'''This dialog box should be usable even if the user has
forgotten their PIN or it is in bootloader mode.'''
device_id = self.device_manager().wallet_id(window.wallet)
if not device_id:
info = self.device_manager().select_device(window.wallet, self)
device_id = info.device.id_
return device_id
def query_choice(self, window, msg, choices):
dialog = WindowModalDialog(window)
clayout = ChoicesLayout(msg, choices)
layout = clayout.layout()
layout.addStretch(1)
layout.addLayout(Buttons(CancelButton(dialog), OkButton(dialog)))
dialog.setLayout(layout)
if not dialog.exec_():
return None
return clayout.selected_index()
return QtPlugin
class SettingsDialog(WindowModalDialog):
'''This dialog doesn't require a device be paired with a wallet.
We want users to be able to wipe a device even if they've forgotten
their PIN.'''
def __init__(self, window, plugin, device_id):
title = _("%s Settings") % plugin.device
super(SettingsDialog, self).__init__(window, title)
self.setMaximumWidth(540)
devmgr = plugin.device_manager()
config = devmgr.config
handler = window.wallet.handler
thread = window.wallet.thread
# wallet can be None, needn't be window.wallet
wallet = devmgr.wallet_by_id(device_id)
hs_rows, hs_cols = (64, 128)
def invoke_client(method, *args, **kw_args):
unpair_after = kw_args.pop('unpair_after', False)
def task():
client = devmgr.client_by_id(device_id, handler)
if not client:
raise RuntimeError("Device not connected")
if method:
getattr(client, method)(*args, **kw_args)
if unpair_after:
devmgr.unpair_id(device_id)
return client.features
thread.add(task, on_success=update)
def update(features):
self.features = features
set_label_enabled()
bl_hash = features.bootloader_hash.encode('hex')
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
noyes = [_("No"), _("Yes")]
endis = [_("Enable Passphrases"), _("Disable Passphrases")]
disen = [_("Disabled"), _("Enabled")]
setchange = [_("Set a PIN"), _("Change PIN")]
version = "%d.%d.%d" % (features.major_version,
features.minor_version,
features.patch_version)
coins = ", ".join(coin.coin_name for coin in features.coins)
device_label.setText(features.label)
pin_set_label.setText(noyes[features.pin_protection])
passphrases_label.setText(disen[features.passphrase_protection])
bl_hash_label.setText(bl_hash)
label_edit.setText(features.label)
device_id_label.setText(features.device_id)
initialized_label.setText(noyes[features.initialized])
version_label.setText(version)
coins_label.setText(coins)
clear_pin_button.setVisible(features.pin_protection)
clear_pin_warning.setVisible(features.pin_protection)
pin_button.setText(setchange[features.pin_protection])
pin_msg.setVisible(not features.pin_protection)
passphrase_button.setText(endis[features.passphrase_protection])
language_label.setText(features.language)
def set_label_enabled():
label_apply.setEnabled(label_edit.text() != self.features.label)
def rename():
invoke_client('change_label', unicode(label_edit.text()))
def toggle_passphrase():
title = _("Confirm Toggle Passphrase Protection")
currently_enabled = self.features.passphrase_protection
if currently_enabled:
msg = _("After disabling passphrases, you can only pair this "
"Electrum wallet if it had an empty passphrase. "
"If its passphrase was not empty, you will need to "
"create a new wallet with the install wizard. You "
"can use this wallet again at any time by re-enabling "
"passphrases and entering its passphrase.")
else:
msg = _("Your current Electrum wallet can only be used with "
"an empty passphrase. You must create a separate "
"wallet with the install wizard for other passphrases "
"as each one generates a new set of addresses.")
msg += "\n\n" + _("Are you sure you want to proceed?")
if not self.question(msg, title=title):
return
invoke_client('toggle_passphrase', unpair_after=currently_enabled)
def change_homescreen():
from PIL import Image # FIXME
dialog = QFileDialog(self, _("Choose Homescreen"))
filename = dialog.getOpenFileName()
if filename:
im = Image.open(str(filename))
if im.size != (hs_cols, hs_rows):
raise Exception('Image must be 64 x 128 pixels')
im = im.convert('1')
pix = im.load()
img = ''
for j in range(hs_rows):
for i in range(hs_cols):
img += '1' if pix[i, j] else '0'
img = ''.join(chr(int(img[i:i + 8], 2))
for i in range(0, len(img), 8))
invoke_client('change_homescreen', img)
def clear_homescreen():
invoke_client('change_homescreen', '\x00')
def set_pin():
invoke_client('set_pin', remove=False)
def clear_pin():
invoke_client('set_pin', remove=True)
def wipe_device():
if wallet and sum(wallet.get_balance()):
title = _("Confirm Device Wipe")
msg = _("Are you SURE you want to wipe the device?\n"
"Your wallet still has cryptoescudos in it!")
if not self.question(msg, title=title,
icon=QMessageBox.Critical):
return
invoke_client('wipe_device', unpair_after=True)
def slider_moved():
mins = timeout_slider.sliderPosition()
timeout_minutes.setText(_("%2d minutes") % mins)
def slider_released():
config.set_session_timeout(timeout_slider.sliderPosition() * 60)
# Information tab
info_tab = QWidget()
info_layout = QVBoxLayout(info_tab)
info_glayout = QGridLayout()
info_glayout.setColumnStretch(2, 1)
device_label = QLabel()
pin_set_label = QLabel()
passphrases_label = QLabel()
version_label = QLabel()
device_id_label = QLabel()
bl_hash_label = QLabel()
bl_hash_label.setWordWrap(True)
coins_label = QLabel()
coins_label.setWordWrap(True)
language_label = QLabel()
initialized_label = QLabel()
rows = [
(_("Device Label"), device_label),
(_("PIN set"), pin_set_label),
(_("Passphrases"), passphrases_label),
(_("Firmware Version"), version_label),
(_("Device ID"), device_id_label),
(_("Bootloader Hash"), bl_hash_label),
(_("Supported Coins"), coins_label),
(_("Language"), language_label),
(_("Initialized"), initialized_label),
]
for row_num, (label, widget) in enumerate(rows):
info_glayout.addWidget(QLabel(label), row_num, 0)
info_glayout.addWidget(widget, row_num, 1)
info_layout.addLayout(info_glayout)
# Settings tab
settings_tab = QWidget()
settings_layout = QVBoxLayout(settings_tab)
settings_glayout = QGridLayout()
# Settings tab - Label
label_msg = QLabel(_("Name this %s. If you have mutiple devices "
"their labels help distinguish them.")
% plugin.device)
label_msg.setWordWrap(True)
label_label = QLabel(_("Device Label"))
label_edit = QLineEdit()
label_edit.setMinimumWidth(150)
label_edit.setMaxLength(plugin.MAX_LABEL_LEN)
label_apply = QPushButton(_("Apply"))
label_apply.clicked.connect(rename)
label_edit.textChanged.connect(set_label_enabled)
settings_glayout.addWidget(label_label, 0, 0)
settings_glayout.addWidget(label_edit, 0, 1, 1, 2)
settings_glayout.addWidget(label_apply, 0, 3)
settings_glayout.addWidget(label_msg, 1, 1, 1, -1)
# Settings tab - PIN
pin_label = QLabel(_("PIN Protection"))
pin_button = QPushButton()
pin_button.clicked.connect(set_pin)
settings_glayout.addWidget(pin_label, 2, 0)
settings_glayout.addWidget(pin_button, 2, 1)
pin_msg = QLabel(_("PIN protection is strongly recommended. "
"A PIN is your only protection against someone "
"stealing your cryptoescudos if they obtain physical "
"access to your %s.") % plugin.device)
pin_msg.setWordWrap(True)
pin_msg.setStyleSheet("color: red")
settings_glayout.addWidget(pin_msg, 3, 1, 1, -1)
# Settings tab - Homescreen
if plugin.device != 'KeepKey': # Not yet supported by KK firmware
homescreen_layout = QHBoxLayout()
homescreen_label = QLabel(_("Homescreen"))
homescreen_change_button = QPushButton(_("Change..."))
homescreen_clear_button = QPushButton(_("Reset"))
homescreen_change_button.clicked.connect(change_homescreen)
homescreen_clear_button.clicked.connect(clear_homescreen)
homescreen_msg = QLabel(_("You can set the homescreen on your "
"device to personalize it. You must "
"choose a %d x %d monochrome black and "
"white image.") % (hs_rows, hs_cols))
homescreen_msg.setWordWrap(True)
settings_glayout.addWidget(homescreen_label, 4, 0)
settings_glayout.addWidget(homescreen_change_button, 4, 1)
settings_glayout.addWidget(homescreen_clear_button, 4, 2)
settings_glayout.addWidget(homescreen_msg, 5, 1, 1, -1)
# Settings tab - Session Timeout
timeout_label = QLabel(_("Session Timeout"))
timeout_minutes = QLabel()
timeout_slider = QSlider(Qt.Horizontal)
timeout_slider.setRange(1, 60)
timeout_slider.setSingleStep(1)
timeout_slider.setTickInterval(5)
timeout_slider.setTickPosition(QSlider.TicksBelow)
timeout_slider.setTracking(True)
timeout_msg = QLabel(
_("Clear the session after the specified period "
"of inactivity. Once a session has timed out, "
"your PIN and passphrase (if enabled) must be "
"re-entered to use the device."))
timeout_msg.setWordWrap(True)
timeout_slider.setSliderPosition(config.get_session_timeout() // 60)
slider_moved()
timeout_slider.valueChanged.connect(slider_moved)
timeout_slider.sliderReleased.connect(slider_released)
settings_glayout.addWidget(timeout_label, 6, 0)
settings_glayout.addWidget(timeout_slider, 6, 1, 1, 3)
settings_glayout.addWidget(timeout_minutes, 6, 4)
settings_glayout.addWidget(timeout_msg, 7, 1, 1, -1)
settings_layout.addLayout(settings_glayout)
settings_layout.addStretch(1)
# Advanced tab
advanced_tab = QWidget()
advanced_layout = QVBoxLayout(advanced_tab)
advanced_glayout = QGridLayout()
# Advanced tab - clear PIN
clear_pin_button = QPushButton(_("Disable PIN"))
clear_pin_button.clicked.connect(clear_pin)
clear_pin_warning = QLabel(
_("If you disable your PIN, anyone with physical access to your "
"%s device can spend your cryptoescudos.") % plugin.device)
clear_pin_warning.setWordWrap(True)
clear_pin_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(clear_pin_button, 0, 2)
advanced_glayout.addWidget(clear_pin_warning, 1, 0, 1, 5)
# Advanced tab - toggle passphrase protection
passphrase_button = QPushButton()
passphrase_button.clicked.connect(toggle_passphrase)
passphrase_msg = WWLabel(PASSPHRASE_HELP)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(passphrase_button, 3, 2)
advanced_glayout.addWidget(passphrase_msg, 4, 0, 1, 5)
advanced_glayout.addWidget(passphrase_warning, 5, 0, 1, 5)
# Advanced tab - wipe device
wipe_device_button = QPushButton(_("Wipe Device"))
wipe_device_button.clicked.connect(wipe_device)
wipe_device_msg = QLabel(
_("Wipe the device, removing all data from it. The firmware "
"is left unchanged."))
wipe_device_msg.setWordWrap(True)
wipe_device_warning = QLabel(
_("Only wipe a device if you have the recovery seed written down "
"and the device wallet(s) are empty, otherwise the cryptoescudos "
"will be lost forever."))
wipe_device_warning.setWordWrap(True)
wipe_device_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(wipe_device_button, 6, 2)
advanced_glayout.addWidget(wipe_device_msg, 7, 0, 1, 5)
advanced_glayout.addWidget(wipe_device_warning, 8, 0, 1, 5)
advanced_layout.addLayout(advanced_glayout)
advanced_layout.addStretch(1)
tabs = QTabWidget(self)
tabs.addTab(info_tab, _("Information"))
tabs.addTab(settings_tab, _("Settings"))
tabs.addTab(advanced_tab, _("Advanced"))
dialog_vbox = QVBoxLayout(self)
dialog_vbox.addWidget(tabs)
dialog_vbox.addLayout(Buttons(CloseButton(self)))
# Update information
invoke_client(None)
| {
"repo_name": "Marcdnd/electrum-cesc",
"path": "plugins/trezor/qt_generic.py",
"copies": "1",
"size": "26552",
"license": "mit",
"hash": -7655816218707595000,
"line_mean": 40.748427673,
"line_max": 83,
"alpha_frac": 0.5929120217,
"autogenerated": false,
"ratio": 4.029746547275763,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0004840502897464599,
"num_lines": 636
} |
from functools import partial
import threading
from PyQt4.Qt import Qt
from PyQt4.Qt import QGridLayout, QInputDialog, QPushButton
from PyQt4.Qt import QVBoxLayout, QLabel, SIGNAL
from electrum_dgb_gui.qt.util import *
from .plugin import TIM_NEW, TIM_RECOVER, TIM_MNEMONIC
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
from electrum_dgb_gui.i18n import _
from electrum_dgb_gui.plugins import hook, DeviceMgr
from electrum_dgb_gui.util import PrintError, UserCancelled
from electrum_dgb_gui.wallet import Wallet, Standard_Wallet
PASSPHRASE_HELP_SHORT =_(
"Passphrases allow you to access new wallets, each "
"hidden behind a particular case-sensitive passphrase.")
PASSPHRASE_HELP = PASSPHRASE_HELP_SHORT + " " + _(
"You need to create a separate Electrum wallet for each passphrase "
"you use as they each generate different addresses. Changing "
"your passphrase does not lose other wallets, each is still "
"accessible behind its own passphrase.")
RECOMMEND_PIN = _(
"You should enable PIN protection. Your PIN is the only protection "
"for your digibytes if your device is lost or stolen.")
PASSPHRASE_NOT_PIN = _(
"If you forget a passphrase you will be unable to access any "
"digibytes in the wallet behind it. A passphrase is not a PIN. "
"Only change this if you are sure you understand it.")
CHARACTER_RECOVERY = (
"Use the recovery cipher shown on your device to input your seed words. "
"The cipher changes with every keypress.\n"
"After at most 4 letters the device will auto-complete a word.\n"
"Press SPACE or the Accept Word button to accept the device's auto-"
"completed word and advance to the next one.\n"
"Press BACKSPACE to go back a character or word.\n"
"Press ENTER or the Seed Entered button once the last word in your "
"seed is auto-completed.")
class CharacterButton(QPushButton):
def __init__(self, text=None):
QPushButton.__init__(self, text)
def keyPressEvent(self, event):
event.setAccepted(False) # Pass through Enter and Space keys
class CharacterDialog(WindowModalDialog):
def __init__(self, parent):
super(CharacterDialog, self).__init__(parent)
self.setWindowTitle(_("KeepKey Seed Recovery"))
self.character_pos = 0
self.word_pos = 0
self.loop = QEventLoop()
self.word_help = QLabel()
self.char_buttons = []
vbox = QVBoxLayout(self)
vbox.addWidget(WWLabel(CHARACTER_RECOVERY))
hbox = QHBoxLayout()
hbox.addWidget(self.word_help)
for i in range(4):
char_button = CharacterButton('*')
char_button.setMaximumWidth(36)
self.char_buttons.append(char_button)
hbox.addWidget(char_button)
self.accept_button = CharacterButton(_("Accept Word"))
self.accept_button.clicked.connect(partial(self.process_key, 32))
self.rejected.connect(partial(self.loop.exit, 1))
hbox.addWidget(self.accept_button)
hbox.addStretch(1)
vbox.addLayout(hbox)
self.finished_button = QPushButton(_("Seed Entered"))
self.cancel_button = QPushButton(_("Cancel"))
self.finished_button.clicked.connect(partial(self.process_key,
Qt.Key_Return))
self.cancel_button.clicked.connect(self.rejected)
buttons = Buttons(self.finished_button, self.cancel_button)
vbox.addSpacing(40)
vbox.addLayout(buttons)
self.refresh()
self.show()
def refresh(self):
self.word_help.setText("Enter seed word %2d:" % (self.word_pos + 1))
self.accept_button.setEnabled(self.character_pos >= 3)
self.finished_button.setEnabled((self.word_pos in (11, 17, 23)
and self.character_pos >= 3))
for n, button in enumerate(self.char_buttons):
button.setEnabled(n == self.character_pos)
if n == self.character_pos:
button.setFocus()
def is_valid_alpha_space(self, key):
# Auto-completion requires at least 3 characters
if key == ord(' ') and self.character_pos >= 3:
return True
# Firmware aborts protocol if the 5th character is non-space
if self.character_pos >= 4:
return False
return (key >= ord('a') and key <= ord('z')
or (key >= ord('A') and key <= ord('Z')))
def process_key(self, key):
self.data = None
if key == Qt.Key_Return and self.finished_button.isEnabled():
self.data = {'done': True}
elif key == Qt.Key_Backspace and (self.word_pos or self.character_pos):
self.data = {'delete': True}
elif self.is_valid_alpha_space(key):
self.data = {'character': chr(key).lower()}
if self.data:
self.loop.exit(0)
def keyPressEvent(self, event):
self.process_key(event.key())
if not self.data:
QDialog.keyPressEvent(self, event)
def get_char(self, word_pos, character_pos):
self.word_pos = word_pos
self.character_pos = character_pos
self.refresh()
if self.loop.exec_():
self.data = None # User cancelled
class QtHandler(QtHandlerBase):
char_signal = pyqtSignal(object)
pin_signal = pyqtSignal(object)
def __init__(self, win, pin_matrix_widget_class, device):
super(QtHandler, self).__init__(win, device)
self.char_signal.connect(self.update_character_dialog)
self.pin_signal.connect(self.pin_dialog)
self.pin_matrix_widget_class = pin_matrix_widget_class
self.character_dialog = None
def get_char(self, msg):
self.done.clear()
self.char_signal.emit(msg)
self.done.wait()
data = self.character_dialog.data
if not data or 'done' in data:
self.character_dialog.accept()
self.character_dialog = None
return data
def get_pin(self, msg):
self.done.clear()
self.pin_signal.emit(msg)
self.done.wait()
return self.response
def pin_dialog(self, msg):
# Needed e.g. when resetting a device
self.clear_dialog()
dialog = WindowModalDialog(self.top_level_window(), _("Enter PIN"))
matrix = self.pin_matrix_widget_class()
vbox = QVBoxLayout()
vbox.addWidget(QLabel(msg))
vbox.addWidget(matrix)
vbox.addLayout(Buttons(CancelButton(dialog), OkButton(dialog)))
dialog.setLayout(vbox)
dialog.exec_()
self.response = str(matrix.get_value())
self.done.set()
def update_character_dialog(self, msg):
if not self.character_dialog:
self.character_dialog = CharacterDialog(self.top_level_window())
self.character_dialog.get_char(msg.word_pos, msg.character_pos)
self.done.set()
class QtPlugin(QtPluginBase):
# Derived classes must provide the following class-static variables:
# icon_file
# pin_matrix_widget_class
def create_handler(self, window):
return QtHandler(window, self.pin_matrix_widget_class(), self.device)
@hook
def receive_menu(self, menu, addrs, wallet):
if type(wallet) is not Standard_Wallet:
return
keystore = wallet.get_keystore()
if type(keystore) == self.keystore_class and len(addrs) == 1:
def show_address():
keystore.thread.add(partial(self.show_address, wallet, addrs[0]))
menu.addAction(_("Show on %s") % self.device, show_address)
def show_settings_dialog(self, window, keystore):
device_id = self.choose_device(window, keystore)
if device_id:
SettingsDialog(window, self, keystore, device_id).exec_()
def request_trezor_init_settings(self, wizard, method, device):
vbox = QVBoxLayout()
next_enabled = True
label = QLabel(_("Enter a label to name your device:"))
name = QLineEdit()
hl = QHBoxLayout()
hl.addWidget(label)
hl.addWidget(name)
hl.addStretch(1)
vbox.addLayout(hl)
def clean_text(widget):
text = unicode(widget.toPlainText()).strip()
return ' '.join(text.split())
if method in [TIM_NEW, TIM_RECOVER]:
gb = QGroupBox()
hbox1 = QHBoxLayout()
gb.setLayout(hbox1)
# KeepKey recovery doesn't need a word count
if method == TIM_NEW or self.device == 'TREZOR':
vbox.addWidget(gb)
gb.setTitle(_("Select your seed length:"))
bg = QButtonGroup()
for i, count in enumerate([12, 18, 24]):
rb = QRadioButton(gb)
rb.setText(_("%d words") % count)
bg.addButton(rb)
bg.setId(rb, i)
hbox1.addWidget(rb)
rb.setChecked(True)
cb_pin = QCheckBox(_('Enable PIN protection'))
cb_pin.setChecked(True)
else:
text = QTextEdit()
text.setMaximumHeight(60)
if method == TIM_MNEMONIC:
msg = _("Enter your BIP39 mnemonic:")
else:
msg = _("Enter the master private key beginning with xprv:")
def set_enabled():
from electrum.keystore import is_xprv
wizard.next_button.setEnabled(is_xprv(clean_text(text)))
text.textChanged.connect(set_enabled)
next_enabled = False
vbox.addWidget(QLabel(msg))
vbox.addWidget(text)
pin = QLineEdit()
pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,10}')))
pin.setMaximumWidth(100)
hbox_pin = QHBoxLayout()
hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):")))
hbox_pin.addWidget(pin)
hbox_pin.addStretch(1)
if method in [TIM_NEW, TIM_RECOVER]:
vbox.addWidget(WWLabel(RECOMMEND_PIN))
vbox.addWidget(cb_pin)
else:
vbox.addLayout(hbox_pin)
passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
cb_phrase = QCheckBox(_('Enable passphrases'))
cb_phrase.setChecked(False)
vbox.addWidget(passphrase_msg)
vbox.addWidget(passphrase_warning)
vbox.addWidget(cb_phrase)
wizard.set_main_layout(vbox, next_enabled=next_enabled)
if method in [TIM_NEW, TIM_RECOVER]:
item = bg.checkedId()
pin = cb_pin.isChecked()
else:
item = ' '.join(str(clean_text(text)).split())
pin = str(pin.text())
return (item, unicode(name.text()), pin, cb_phrase.isChecked())
class SettingsDialog(WindowModalDialog):
'''This dialog doesn't require a device be paired with a wallet.
We want users to be able to wipe a device even if they've forgotten
their PIN.'''
def __init__(self, window, plugin, keystore, device_id):
title = _("%s Settings") % plugin.device
super(SettingsDialog, self).__init__(window, title)
self.setMaximumWidth(540)
devmgr = plugin.device_manager()
config = devmgr.config
handler = keystore.handler
thread = keystore.thread
hs_rows, hs_cols = (64, 128)
def invoke_client(method, *args, **kw_args):
unpair_after = kw_args.pop('unpair_after', False)
def task():
client = devmgr.client_by_id(device_id)
if not client:
raise RuntimeError("Device not connected")
if method:
getattr(client, method)(*args, **kw_args)
if unpair_after:
devmgr.unpair_id(device_id)
return client.features
thread.add(task, on_success=update)
def update(features):
self.features = features
set_label_enabled()
bl_hash = features.bootloader_hash.encode('hex')
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
noyes = [_("No"), _("Yes")]
endis = [_("Enable Passphrases"), _("Disable Passphrases")]
disen = [_("Disabled"), _("Enabled")]
setchange = [_("Set a PIN"), _("Change PIN")]
version = "%d.%d.%d" % (features.major_version,
features.minor_version,
features.patch_version)
coins = ", ".join(coin.coin_name for coin in features.coins)
device_label.setText(features.label)
pin_set_label.setText(noyes[features.pin_protection])
passphrases_label.setText(disen[features.passphrase_protection])
bl_hash_label.setText(bl_hash)
label_edit.setText(features.label)
device_id_label.setText(features.device_id)
initialized_label.setText(noyes[features.initialized])
version_label.setText(version)
coins_label.setText(coins)
clear_pin_button.setVisible(features.pin_protection)
clear_pin_warning.setVisible(features.pin_protection)
pin_button.setText(setchange[features.pin_protection])
pin_msg.setVisible(not features.pin_protection)
passphrase_button.setText(endis[features.passphrase_protection])
language_label.setText(features.language)
def set_label_enabled():
label_apply.setEnabled(label_edit.text() != self.features.label)
def rename():
invoke_client('change_label', unicode(label_edit.text()))
def toggle_passphrase():
title = _("Confirm Toggle Passphrase Protection")
currently_enabled = self.features.passphrase_protection
if currently_enabled:
msg = _("After disabling passphrases, you can only pair this "
"Electrum wallet if it had an empty passphrase. "
"If its passphrase was not empty, you will need to "
"create a new wallet with the install wizard. You "
"can use this wallet again at any time by re-enabling "
"passphrases and entering its passphrase.")
else:
msg = _("Your current Electrum wallet can only be used with "
"an empty passphrase. You must create a separate "
"wallet with the install wizard for other passphrases "
"as each one generates a new set of addresses.")
msg += "\n\n" + _("Are you sure you want to proceed?")
if not self.question(msg, title=title):
return
invoke_client('toggle_passphrase', unpair_after=currently_enabled)
def change_homescreen():
from PIL import Image # FIXME
dialog = QFileDialog(self, _("Choose Homescreen"))
filename = dialog.getOpenFileName()
if filename:
im = Image.open(str(filename))
if im.size != (hs_cols, hs_rows):
raise Exception('Image must be 64 x 128 pixels')
im = im.convert('1')
pix = im.load()
img = ''
for j in range(hs_rows):
for i in range(hs_cols):
img += '1' if pix[i, j] else '0'
img = ''.join(chr(int(img[i:i + 8], 2))
for i in range(0, len(img), 8))
invoke_client('change_homescreen', img)
def clear_homescreen():
invoke_client('change_homescreen', '\x00')
def set_pin():
invoke_client('set_pin', remove=False)
def clear_pin():
invoke_client('set_pin', remove=True)
def wipe_device():
wallet = window.wallet
if wallet and sum(wallet.get_balance()):
title = _("Confirm Device Wipe")
msg = _("Are you SURE you want to wipe the device?\n"
"Your wallet still has digibytes in it!")
if not self.question(msg, title=title,
icon=QMessageBox.Critical):
return
invoke_client('wipe_device', unpair_after=True)
def slider_moved():
mins = timeout_slider.sliderPosition()
timeout_minutes.setText(_("%2d minutes") % mins)
def slider_released():
config.set_session_timeout(timeout_slider.sliderPosition() * 60)
# Information tab
info_tab = QWidget()
info_layout = QVBoxLayout(info_tab)
info_glayout = QGridLayout()
info_glayout.setColumnStretch(2, 1)
device_label = QLabel()
pin_set_label = QLabel()
passphrases_label = QLabel()
version_label = QLabel()
device_id_label = QLabel()
bl_hash_label = QLabel()
bl_hash_label.setWordWrap(True)
coins_label = QLabel()
coins_label.setWordWrap(True)
language_label = QLabel()
initialized_label = QLabel()
rows = [
(_("Device Label"), device_label),
(_("PIN set"), pin_set_label),
(_("Passphrases"), passphrases_label),
(_("Firmware Version"), version_label),
(_("Device ID"), device_id_label),
(_("Bootloader Hash"), bl_hash_label),
(_("Supported Coins"), coins_label),
(_("Language"), language_label),
(_("Initialized"), initialized_label),
]
for row_num, (label, widget) in enumerate(rows):
info_glayout.addWidget(QLabel(label), row_num, 0)
info_glayout.addWidget(widget, row_num, 1)
info_layout.addLayout(info_glayout)
# Settings tab
settings_tab = QWidget()
settings_layout = QVBoxLayout(settings_tab)
settings_glayout = QGridLayout()
# Settings tab - Label
label_msg = QLabel(_("Name this %s. If you have mutiple devices "
"their labels help distinguish them.")
% plugin.device)
label_msg.setWordWrap(True)
label_label = QLabel(_("Device Label"))
label_edit = QLineEdit()
label_edit.setMinimumWidth(150)
label_edit.setMaxLength(plugin.MAX_LABEL_LEN)
label_apply = QPushButton(_("Apply"))
label_apply.clicked.connect(rename)
label_edit.textChanged.connect(set_label_enabled)
settings_glayout.addWidget(label_label, 0, 0)
settings_glayout.addWidget(label_edit, 0, 1, 1, 2)
settings_glayout.addWidget(label_apply, 0, 3)
settings_glayout.addWidget(label_msg, 1, 1, 1, -1)
# Settings tab - PIN
pin_label = QLabel(_("PIN Protection"))
pin_button = QPushButton()
pin_button.clicked.connect(set_pin)
settings_glayout.addWidget(pin_label, 2, 0)
settings_glayout.addWidget(pin_button, 2, 1)
pin_msg = QLabel(_("PIN protection is strongly recommended. "
"A PIN is your only protection against someone "
"stealing your digibytes if they obtain physical "
"access to your %s.") % plugin.device)
pin_msg.setWordWrap(True)
pin_msg.setStyleSheet("color: red")
settings_glayout.addWidget(pin_msg, 3, 1, 1, -1)
# Settings tab - Homescreen
if plugin.device != 'KeepKey': # Not yet supported by KK firmware
homescreen_layout = QHBoxLayout()
homescreen_label = QLabel(_("Homescreen"))
homescreen_change_button = QPushButton(_("Change..."))
homescreen_clear_button = QPushButton(_("Reset"))
homescreen_change_button.clicked.connect(change_homescreen)
homescreen_clear_button.clicked.connect(clear_homescreen)
homescreen_msg = QLabel(_("You can set the homescreen on your "
"device to personalize it. You must "
"choose a %d x %d monochrome black and "
"white image.") % (hs_rows, hs_cols))
homescreen_msg.setWordWrap(True)
settings_glayout.addWidget(homescreen_label, 4, 0)
settings_glayout.addWidget(homescreen_change_button, 4, 1)
settings_glayout.addWidget(homescreen_clear_button, 4, 2)
settings_glayout.addWidget(homescreen_msg, 5, 1, 1, -1)
# Settings tab - Session Timeout
timeout_label = QLabel(_("Session Timeout"))
timeout_minutes = QLabel()
timeout_slider = QSlider(Qt.Horizontal)
timeout_slider.setRange(1, 60)
timeout_slider.setSingleStep(1)
timeout_slider.setTickInterval(5)
timeout_slider.setTickPosition(QSlider.TicksBelow)
timeout_slider.setTracking(True)
timeout_msg = QLabel(
_("Clear the session after the specified period "
"of inactivity. Once a session has timed out, "
"your PIN and passphrase (if enabled) must be "
"re-entered to use the device."))
timeout_msg.setWordWrap(True)
timeout_slider.setSliderPosition(config.get_session_timeout() // 60)
slider_moved()
timeout_slider.valueChanged.connect(slider_moved)
timeout_slider.sliderReleased.connect(slider_released)
settings_glayout.addWidget(timeout_label, 6, 0)
settings_glayout.addWidget(timeout_slider, 6, 1, 1, 3)
settings_glayout.addWidget(timeout_minutes, 6, 4)
settings_glayout.addWidget(timeout_msg, 7, 1, 1, -1)
settings_layout.addLayout(settings_glayout)
settings_layout.addStretch(1)
# Advanced tab
advanced_tab = QWidget()
advanced_layout = QVBoxLayout(advanced_tab)
advanced_glayout = QGridLayout()
# Advanced tab - clear PIN
clear_pin_button = QPushButton(_("Disable PIN"))
clear_pin_button.clicked.connect(clear_pin)
clear_pin_warning = QLabel(
_("If you disable your PIN, anyone with physical access to your "
"%s device can spend your digibytes.") % plugin.device)
clear_pin_warning.setWordWrap(True)
clear_pin_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(clear_pin_button, 0, 2)
advanced_glayout.addWidget(clear_pin_warning, 1, 0, 1, 5)
# Advanced tab - toggle passphrase protection
passphrase_button = QPushButton()
passphrase_button.clicked.connect(toggle_passphrase)
passphrase_msg = WWLabel(PASSPHRASE_HELP)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(passphrase_button, 3, 2)
advanced_glayout.addWidget(passphrase_msg, 4, 0, 1, 5)
advanced_glayout.addWidget(passphrase_warning, 5, 0, 1, 5)
# Advanced tab - wipe device
wipe_device_button = QPushButton(_("Wipe Device"))
wipe_device_button.clicked.connect(wipe_device)
wipe_device_msg = QLabel(
_("Wipe the device, removing all data from it. The firmware "
"is left unchanged."))
wipe_device_msg.setWordWrap(True)
wipe_device_warning = QLabel(
_("Only wipe a device if you have the recovery seed written down "
"and the device wallet(s) are empty, otherwise the digibytes "
"will be lost forever."))
wipe_device_warning.setWordWrap(True)
wipe_device_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(wipe_device_button, 6, 2)
advanced_glayout.addWidget(wipe_device_msg, 7, 0, 1, 5)
advanced_glayout.addWidget(wipe_device_warning, 8, 0, 1, 5)
advanced_layout.addLayout(advanced_glayout)
advanced_layout.addStretch(1)
tabs = QTabWidget(self)
tabs.addTab(info_tab, _("Information"))
tabs.addTab(settings_tab, _("Settings"))
tabs.addTab(advanced_tab, _("Advanced"))
dialog_vbox = QVBoxLayout(self)
dialog_vbox.addWidget(tabs)
dialog_vbox.addLayout(Buttons(CloseButton(self)))
# Update information
invoke_client(None)
| {
"repo_name": "protonn/Electrum-Cash",
"path": "plugins/trezor/qt_generic.py",
"copies": "1",
"size": "24633",
"license": "mit",
"hash": 1907503434839414500,
"line_mean": 40.8928571429,
"line_max": 81,
"alpha_frac": 0.5902244956,
"autogenerated": false,
"ratio": 4.03422862757943,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.512445312317943,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import threading
from PyQt4.Qt import Qt
from PyQt4.Qt import QGridLayout, QInputDialog, QPushButton
from PyQt4.Qt import QVBoxLayout, QLabel, SIGNAL
from electrum_gui.qt.main_window import StatusBarButton
from electrum_gui.qt.util import *
from .plugin import TIM_NEW, TIM_RECOVER, TIM_MNEMONIC
from ..hw_wallet.qt import QtHandlerBase
from electrum.i18n import _
from electrum.plugins import hook, DeviceMgr
from electrum.util import PrintError, UserCancelled
from electrum.wallet import Wallet, BIP44_Wallet
PASSPHRASE_HELP_SHORT =_(
"Passphrases allow you to access new wallets, each "
"hidden behind a particular case-sensitive passphrase.")
PASSPHRASE_HELP = PASSPHRASE_HELP_SHORT + " " + _(
"You need to create a separate Electrum wallet for each passphrase "
"you use as they each generate different addresses. Changing "
"your passphrase does not lose other wallets, each is still "
"accessible behind its own passphrase.")
RECOMMEND_PIN = _(
"You should enable PIN protection. Your PIN is the only protection "
"for your bitcoins if your device is lost or stolen.")
PASSPHRASE_NOT_PIN = _(
"If you forget a passphrase you will be unable to access any "
"bitcoins in the wallet behind it. A passphrase is not a PIN. "
"Only change this if you are sure you understand it.")
CHARACTER_RECOVERY = (
"Use the recovery cipher shown on your device to input your seed words. "
"The cipher changes with every keypress.\n"
"After at most 4 letters the device will auto-complete a word.\n"
"Press SPACE or the Accept Word button to accept the device's auto-"
"completed word and advance to the next one.\n"
"Press BACKSPACE to go back a character or word.\n"
"Press ENTER or the Seed Entered button once the last word in your "
"seed is auto-completed.")
class CharacterButton(QPushButton):
def __init__(self, text=None):
QPushButton.__init__(self, text)
def keyPressEvent(self, event):
event.setAccepted(False) # Pass through Enter and Space keys
class CharacterDialog(WindowModalDialog):
def __init__(self, parent):
super(CharacterDialog, self).__init__(parent)
self.setWindowTitle(_("KeepKey Seed Recovery"))
self.character_pos = 0
self.word_pos = 0
self.loop = QEventLoop()
self.word_help = QLabel()
self.char_buttons = []
vbox = QVBoxLayout(self)
vbox.addWidget(WWLabel(CHARACTER_RECOVERY))
hbox = QHBoxLayout()
hbox.addWidget(self.word_help)
for i in range(4):
char_button = CharacterButton('*')
char_button.setMaximumWidth(36)
self.char_buttons.append(char_button)
hbox.addWidget(char_button)
self.accept_button = CharacterButton(_("Accept Word"))
self.accept_button.clicked.connect(partial(self.process_key, 32))
self.rejected.connect(partial(self.loop.exit, 1))
hbox.addWidget(self.accept_button)
hbox.addStretch(1)
vbox.addLayout(hbox)
self.finished_button = QPushButton(_("Seed Entered"))
self.cancel_button = QPushButton(_("Cancel"))
self.finished_button.clicked.connect(partial(self.process_key,
Qt.Key_Return))
self.cancel_button.clicked.connect(self.rejected)
buttons = Buttons(self.finished_button, self.cancel_button)
vbox.addSpacing(40)
vbox.addLayout(buttons)
self.refresh()
self.show()
def refresh(self):
self.word_help.setText("Enter seed word %2d:" % (self.word_pos + 1))
self.accept_button.setEnabled(self.character_pos >= 3)
self.finished_button.setEnabled((self.word_pos in (11, 17, 23)
and self.character_pos >= 3))
for n, button in enumerate(self.char_buttons):
button.setEnabled(n == self.character_pos)
if n == self.character_pos:
button.setFocus()
def is_valid_alpha_space(self, key):
# Auto-completion requires at least 3 characters
if key == ord(' ') and self.character_pos >= 3:
return True
# Firmware aborts protocol if the 5th character is non-space
if self.character_pos >= 4:
return False
return (key >= ord('a') and key <= ord('z')
or (key >= ord('A') and key <= ord('Z')))
def process_key(self, key):
self.data = None
if key == Qt.Key_Return and self.finished_button.isEnabled():
self.data = {'done': True}
elif key == Qt.Key_Backspace and (self.word_pos or self.character_pos):
self.data = {'delete': True}
elif self.is_valid_alpha_space(key):
self.data = {'character': chr(key).lower()}
if self.data:
self.loop.exit(0)
def keyPressEvent(self, event):
self.process_key(event.key())
if not self.data:
QDialog.keyPressEvent(self, event)
def get_char(self, word_pos, character_pos):
self.word_pos = word_pos
self.character_pos = character_pos
self.refresh()
if self.loop.exec_():
self.data = None # User cancelled
class QtHandler(QtHandlerBase):
charSig = pyqtSignal(object)
def __init__(self, win, pin_matrix_widget_class, device):
super(QtHandler, self).__init__(win, device)
win.connect(win, SIGNAL('pin_dialog'), self.pin_dialog)
self.charSig.connect(self.update_character_dialog)
self.pin_matrix_widget_class = pin_matrix_widget_class
self.character_dialog = None
def get_char(self, msg):
self.done.clear()
self.charSig.emit(msg)
self.done.wait()
data = self.character_dialog.data
if not data or 'done' in data:
self.character_dialog.accept()
self.character_dialog = None
return data
def get_pin(self, msg):
self.done.clear()
self.win.emit(SIGNAL('pin_dialog'), msg)
self.done.wait()
return self.response
def pin_dialog(self, msg):
# Needed e.g. when resetting a device
self.clear_dialog()
dialog = WindowModalDialog(self.top_level_window(), _("Enter PIN"))
matrix = self.pin_matrix_widget_class()
vbox = QVBoxLayout()
vbox.addWidget(QLabel(msg))
vbox.addWidget(matrix)
vbox.addLayout(Buttons(CancelButton(dialog), OkButton(dialog)))
dialog.setLayout(vbox)
dialog.exec_()
self.response = str(matrix.get_value())
self.done.set()
def update_character_dialog(self, msg):
if not self.character_dialog:
self.character_dialog = CharacterDialog(self.top_level_window())
self.character_dialog.get_char(msg.word_pos, msg.character_pos)
self.done.set()
def request_trezor_init_settings(self, method, device):
wizard = self.win
vbox = QVBoxLayout()
next_enabled=True
label = QLabel(_("Enter a label to name your device:"))
name = QLineEdit()
hl = QHBoxLayout()
hl.addWidget(label)
hl.addWidget(name)
hl.addStretch(1)
vbox.addLayout(hl)
def clean_text(widget):
text = unicode(widget.toPlainText()).strip()
return ' '.join(text.split())
if method in [TIM_NEW, TIM_RECOVER]:
gb = QGroupBox()
hbox1 = QHBoxLayout()
gb.setLayout(hbox1)
# KeepKey recovery doesn't need a word count
if method == TIM_NEW or self.device == 'TREZOR':
vbox.addWidget(gb)
gb.setTitle(_("Select your seed length:"))
bg = QButtonGroup()
for i, count in enumerate([12, 18, 24]):
rb = QRadioButton(gb)
rb.setText(_("%d words") % count)
bg.addButton(rb)
bg.setId(rb, i)
hbox1.addWidget(rb)
rb.setChecked(True)
cb_pin = QCheckBox(_('Enable PIN protection'))
cb_pin.setChecked(True)
else:
text = QTextEdit()
text.setMaximumHeight(60)
if method == TIM_MNEMONIC:
msg = _("Enter your BIP39 mnemonic:")
else:
msg = _("Enter the master private key beginning with xprv:")
def set_enabled():
wizard.next_button.setEnabled(Wallet.is_xprv(clean_text(text)))
text.textChanged.connect(set_enabled)
next_enabled = False
vbox.addWidget(QLabel(msg))
vbox.addWidget(text)
pin = QLineEdit()
pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,10}')))
pin.setMaximumWidth(100)
hbox_pin = QHBoxLayout()
hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):")))
hbox_pin.addWidget(pin)
hbox_pin.addStretch(1)
if method in [TIM_NEW, TIM_RECOVER]:
vbox.addWidget(WWLabel(RECOMMEND_PIN))
vbox.addWidget(cb_pin)
else:
vbox.addLayout(hbox_pin)
passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
cb_phrase = QCheckBox(_('Enable passphrases'))
cb_phrase.setChecked(False)
vbox.addWidget(passphrase_msg)
vbox.addWidget(passphrase_warning)
vbox.addWidget(cb_phrase)
wizard.set_main_layout(vbox, next_enabled=next_enabled)
if method in [TIM_NEW, TIM_RECOVER]:
item = bg.checkedId()
pin = cb_pin.isChecked()
else:
item = ' '.join(str(clean_text(text)).split())
pin = str(pin.text())
return (item, unicode(name.text()), pin, cb_phrase.isChecked())
def qt_plugin_class(base_plugin_class):
class QtPlugin(base_plugin_class):
# Derived classes must provide the following class-static variables:
# icon_file
# pin_matrix_widget_class
def create_handler(self, window):
return QtHandler(window, self.pin_matrix_widget_class(), self.device)
@hook
def load_wallet(self, wallet, window):
if type(wallet) != self.wallet_class:
return
window.tzb = StatusBarButton(QIcon(self.icon_file), self.device,
partial(self.settings_dialog, window))
window.statusBar().addPermanentWidget(window.tzb)
wallet.handler = self.create_handler(window)
# Trigger a pairing
wallet.thread.add(partial(self.get_client, wallet))
def on_create_wallet(self, wallet, wizard):
assert type(wallet) == self.wallet_class
wallet.handler = self.create_handler(wizard)
wallet.thread = TaskThread(wizard, wizard.on_error)
# Setup device and create accounts in separate thread; wait until done
loop = QEventLoop()
exc_info = []
self.setup_device(wallet, on_done=loop.quit,
on_error=lambda info: exc_info.extend(info))
loop.exec_()
# If an exception was thrown, show to user and exit install wizard
if exc_info:
wizard.on_error(exc_info)
raise UserCancelled
@hook
def receive_menu(self, menu, addrs, wallet):
if type(wallet) == self.wallet_class and len(addrs) == 1:
def show_address():
wallet.thread.add(partial(self.show_address, wallet, addrs[0]))
menu.addAction(_("Show on %s") % self.device, show_address)
def settings_dialog(self, window):
device_id = self.choose_device(window)
if device_id:
SettingsDialog(window, self, device_id).exec_()
def choose_device(self, window):
'''This dialog box should be usable even if the user has
forgotten their PIN or it is in bootloader mode.'''
device_id = self.device_manager().wallet_id(window.wallet)
if not device_id:
info = self.device_manager().select_device(window.wallet, self)
device_id = info.device.id_
return device_id
def query_choice(self, window, msg, choices):
dialog = WindowModalDialog(window)
clayout = ChoicesLayout(msg, choices)
layout = clayout.layout()
layout.addStretch(1)
layout.addLayout(Buttons(CancelButton(dialog), OkButton(dialog)))
dialog.setLayout(layout)
if not dialog.exec_():
return None
return clayout.selected_index()
return QtPlugin
class SettingsDialog(WindowModalDialog):
'''This dialog doesn't require a device be paired with a wallet.
We want users to be able to wipe a device even if they've forgotten
their PIN.'''
def __init__(self, window, plugin, device_id):
title = _("%s Settings") % plugin.device
super(SettingsDialog, self).__init__(window, title)
self.setMaximumWidth(540)
devmgr = plugin.device_manager()
config = devmgr.config
handler = window.wallet.handler
thread = window.wallet.thread
# wallet can be None, needn't be window.wallet
wallet = devmgr.wallet_by_id(device_id)
hs_rows, hs_cols = (64, 128)
def invoke_client(method, *args, **kw_args):
unpair_after = kw_args.pop('unpair_after', False)
def task():
client = devmgr.client_by_id(device_id, handler)
if not client:
raise RuntimeError("Device not connected")
if method:
getattr(client, method)(*args, **kw_args)
if unpair_after:
devmgr.unpair_id(device_id)
return client.features
thread.add(task, on_success=update)
def update(features):
self.features = features
set_label_enabled()
bl_hash = features.bootloader_hash.encode('hex')
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
noyes = [_("No"), _("Yes")]
endis = [_("Enable Passphrases"), _("Disable Passphrases")]
disen = [_("Disabled"), _("Enabled")]
setchange = [_("Set a PIN"), _("Change PIN")]
version = "%d.%d.%d" % (features.major_version,
features.minor_version,
features.patch_version)
coins = ", ".join(coin.coin_name for coin in features.coins)
device_label.setText(features.label)
pin_set_label.setText(noyes[features.pin_protection])
passphrases_label.setText(disen[features.passphrase_protection])
bl_hash_label.setText(bl_hash)
label_edit.setText(features.label)
device_id_label.setText(features.device_id)
initialized_label.setText(noyes[features.initialized])
version_label.setText(version)
coins_label.setText(coins)
clear_pin_button.setVisible(features.pin_protection)
clear_pin_warning.setVisible(features.pin_protection)
pin_button.setText(setchange[features.pin_protection])
pin_msg.setVisible(not features.pin_protection)
passphrase_button.setText(endis[features.passphrase_protection])
language_label.setText(features.language)
def set_label_enabled():
label_apply.setEnabled(label_edit.text() != self.features.label)
def rename():
invoke_client('change_label', unicode(label_edit.text()))
def toggle_passphrase():
title = _("Confirm Toggle Passphrase Protection")
currently_enabled = self.features.passphrase_protection
if currently_enabled:
msg = _("After disabling passphrases, you can only pair this "
"Electrum wallet if it had an empty passphrase. "
"If its passphrase was not empty, you will need to "
"create a new wallet with the install wizard. You "
"can use this wallet again at any time by re-enabling "
"passphrases and entering its passphrase.")
else:
msg = _("Your current Electrum wallet can only be used with "
"an empty passphrase. You must create a separate "
"wallet with the install wizard for other passphrases "
"as each one generates a new set of addresses.")
msg += "\n\n" + _("Are you sure you want to proceed?")
if not self.question(msg, title=title):
return
invoke_client('toggle_passphrase', unpair_after=currently_enabled)
def change_homescreen():
from PIL import Image # FIXME
dialog = QFileDialog(self, _("Choose Homescreen"))
filename = dialog.getOpenFileName()
if filename:
im = Image.open(str(filename))
if im.size != (hs_cols, hs_rows):
raise Exception('Image must be 64 x 128 pixels')
im = im.convert('1')
pix = im.load()
img = ''
for j in range(hs_rows):
for i in range(hs_cols):
img += '1' if pix[i, j] else '0'
img = ''.join(chr(int(img[i:i + 8], 2))
for i in range(0, len(img), 8))
invoke_client('change_homescreen', img)
def clear_homescreen():
invoke_client('change_homescreen', '\x00')
def set_pin():
invoke_client('set_pin', remove=False)
def clear_pin():
invoke_client('set_pin', remove=True)
def wipe_device():
if wallet and sum(wallet.get_balance()):
title = _("Confirm Device Wipe")
msg = _("Are you SURE you want to wipe the device?\n"
"Your wallet still has bitcoins in it!")
if not self.question(msg, title=title,
icon=QMessageBox.Critical):
return
invoke_client('wipe_device', unpair_after=True)
def slider_moved():
mins = timeout_slider.sliderPosition()
timeout_minutes.setText(_("%2d minutes") % mins)
def slider_released():
config.set_session_timeout(timeout_slider.sliderPosition() * 60)
# Information tab
info_tab = QWidget()
info_layout = QVBoxLayout(info_tab)
info_glayout = QGridLayout()
info_glayout.setColumnStretch(2, 1)
device_label = QLabel()
pin_set_label = QLabel()
passphrases_label = QLabel()
version_label = QLabel()
device_id_label = QLabel()
bl_hash_label = QLabel()
bl_hash_label.setWordWrap(True)
coins_label = QLabel()
coins_label.setWordWrap(True)
language_label = QLabel()
initialized_label = QLabel()
rows = [
(_("Device Label"), device_label),
(_("PIN set"), pin_set_label),
(_("Passphrases"), passphrases_label),
(_("Firmware Version"), version_label),
(_("Device ID"), device_id_label),
(_("Bootloader Hash"), bl_hash_label),
(_("Supported Coins"), coins_label),
(_("Language"), language_label),
(_("Initialized"), initialized_label),
]
for row_num, (label, widget) in enumerate(rows):
info_glayout.addWidget(QLabel(label), row_num, 0)
info_glayout.addWidget(widget, row_num, 1)
info_layout.addLayout(info_glayout)
# Settings tab
settings_tab = QWidget()
settings_layout = QVBoxLayout(settings_tab)
settings_glayout = QGridLayout()
# Settings tab - Label
label_msg = QLabel(_("Name this %s. If you have mutiple devices "
"their labels help distinguish them.")
% plugin.device)
label_msg.setWordWrap(True)
label_label = QLabel(_("Device Label"))
label_edit = QLineEdit()
label_edit.setMinimumWidth(150)
label_edit.setMaxLength(plugin.MAX_LABEL_LEN)
label_apply = QPushButton(_("Apply"))
label_apply.clicked.connect(rename)
label_edit.textChanged.connect(set_label_enabled)
settings_glayout.addWidget(label_label, 0, 0)
settings_glayout.addWidget(label_edit, 0, 1, 1, 2)
settings_glayout.addWidget(label_apply, 0, 3)
settings_glayout.addWidget(label_msg, 1, 1, 1, -1)
# Settings tab - PIN
pin_label = QLabel(_("PIN Protection"))
pin_button = QPushButton()
pin_button.clicked.connect(set_pin)
settings_glayout.addWidget(pin_label, 2, 0)
settings_glayout.addWidget(pin_button, 2, 1)
pin_msg = QLabel(_("PIN protection is strongly recommended. "
"A PIN is your only protection against someone "
"stealing your bitcoins if they obtain physical "
"access to your %s.") % plugin.device)
pin_msg.setWordWrap(True)
pin_msg.setStyleSheet("color: red")
settings_glayout.addWidget(pin_msg, 3, 1, 1, -1)
# Settings tab - Homescreen
if plugin.device != 'KeepKey': # Not yet supported by KK firmware
homescreen_layout = QHBoxLayout()
homescreen_label = QLabel(_("Homescreen"))
homescreen_change_button = QPushButton(_("Change..."))
homescreen_clear_button = QPushButton(_("Reset"))
homescreen_change_button.clicked.connect(change_homescreen)
homescreen_clear_button.clicked.connect(clear_homescreen)
homescreen_msg = QLabel(_("You can set the homescreen on your "
"device to personalize it. You must "
"choose a %d x %d monochrome black and "
"white image.") % (hs_rows, hs_cols))
homescreen_msg.setWordWrap(True)
settings_glayout.addWidget(homescreen_label, 4, 0)
settings_glayout.addWidget(homescreen_change_button, 4, 1)
settings_glayout.addWidget(homescreen_clear_button, 4, 2)
settings_glayout.addWidget(homescreen_msg, 5, 1, 1, -1)
# Settings tab - Session Timeout
timeout_label = QLabel(_("Session Timeout"))
timeout_minutes = QLabel()
timeout_slider = QSlider(Qt.Horizontal)
timeout_slider.setRange(1, 60)
timeout_slider.setSingleStep(1)
timeout_slider.setTickInterval(5)
timeout_slider.setTickPosition(QSlider.TicksBelow)
timeout_slider.setTracking(True)
timeout_msg = QLabel(
_("Clear the session after the specified period "
"of inactivity. Once a session has timed out, "
"your PIN and passphrase (if enabled) must be "
"re-entered to use the device."))
timeout_msg.setWordWrap(True)
timeout_slider.setSliderPosition(config.get_session_timeout() // 60)
slider_moved()
timeout_slider.valueChanged.connect(slider_moved)
timeout_slider.sliderReleased.connect(slider_released)
settings_glayout.addWidget(timeout_label, 6, 0)
settings_glayout.addWidget(timeout_slider, 6, 1, 1, 3)
settings_glayout.addWidget(timeout_minutes, 6, 4)
settings_glayout.addWidget(timeout_msg, 7, 1, 1, -1)
settings_layout.addLayout(settings_glayout)
settings_layout.addStretch(1)
# Advanced tab
advanced_tab = QWidget()
advanced_layout = QVBoxLayout(advanced_tab)
advanced_glayout = QGridLayout()
# Advanced tab - clear PIN
clear_pin_button = QPushButton(_("Disable PIN"))
clear_pin_button.clicked.connect(clear_pin)
clear_pin_warning = QLabel(
_("If you disable your PIN, anyone with physical access to your "
"%s device can spend your bitcoins.") % plugin.device)
clear_pin_warning.setWordWrap(True)
clear_pin_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(clear_pin_button, 0, 2)
advanced_glayout.addWidget(clear_pin_warning, 1, 0, 1, 5)
# Advanced tab - toggle passphrase protection
passphrase_button = QPushButton()
passphrase_button.clicked.connect(toggle_passphrase)
passphrase_msg = WWLabel(PASSPHRASE_HELP)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(passphrase_button, 3, 2)
advanced_glayout.addWidget(passphrase_msg, 4, 0, 1, 5)
advanced_glayout.addWidget(passphrase_warning, 5, 0, 1, 5)
# Advanced tab - wipe device
wipe_device_button = QPushButton(_("Wipe Device"))
wipe_device_button.clicked.connect(wipe_device)
wipe_device_msg = QLabel(
_("Wipe the device, removing all data from it. The firmware "
"is left unchanged."))
wipe_device_msg.setWordWrap(True)
wipe_device_warning = QLabel(
_("Only wipe a device if you have the recovery seed written down "
"and the device wallet(s) are empty, otherwise the bitcoins "
"will be lost forever."))
wipe_device_warning.setWordWrap(True)
wipe_device_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(wipe_device_button, 6, 2)
advanced_glayout.addWidget(wipe_device_msg, 7, 0, 1, 5)
advanced_glayout.addWidget(wipe_device_warning, 8, 0, 1, 5)
advanced_layout.addLayout(advanced_glayout)
advanced_layout.addStretch(1)
tabs = QTabWidget(self)
tabs.addTab(info_tab, _("Information"))
tabs.addTab(settings_tab, _("Settings"))
tabs.addTab(advanced_tab, _("Advanced"))
dialog_vbox = QVBoxLayout(self)
dialog_vbox.addWidget(tabs)
dialog_vbox.addLayout(Buttons(CloseButton(self)))
# Update information
invoke_client(None)
| {
"repo_name": "parkbyte/electrumparkbyte",
"path": "plugins/trezor/qt_generic.py",
"copies": "7",
"size": "26492",
"license": "mit",
"hash": -6923197251069930000,
"line_mean": 40.6540880503,
"line_max": 83,
"alpha_frac": 0.5922165182,
"autogenerated": false,
"ratio": 4.035338918507235,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0004454641247094077,
"num_lines": 636
} |
from functools import partial
import threading
from PyQt4.Qt import Qt
from PyQt4.Qt import QGridLayout, QInputDialog, QPushButton
from PyQt4.Qt import QVBoxLayout, QLabel, SIGNAL
from electrum_vtc_gui.qt.util import *
from .plugin import TIM_NEW, TIM_RECOVER, TIM_MNEMONIC
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
from electrum_vtc.i18n import _
from electrum_vtc.plugins import hook, DeviceMgr
from electrum_vtc.util import PrintError, UserCancelled
from electrum_vtc.wallet import Wallet, Standard_Wallet
PASSPHRASE_HELP_SHORT =_(
"Passphrases allow you to access new wallets, each "
"hidden behind a particular case-sensitive passphrase.")
PASSPHRASE_HELP = PASSPHRASE_HELP_SHORT + " " + _(
"You need to create a separate Electrum wallet for each passphrase "
"you use as they each generate different addresses. Changing "
"your passphrase does not lose other wallets, each is still "
"accessible behind its own passphrase.")
RECOMMEND_PIN = _(
"You should enable PIN protection. Your PIN is the only protection "
"for your litecoins if your device is lost or stolen.")
PASSPHRASE_NOT_PIN = _(
"If you forget a passphrase you will be unable to access any "
"litecoins in the wallet behind it. A passphrase is not a PIN. "
"Only change this if you are sure you understand it.")
CHARACTER_RECOVERY = (
"Use the recovery cipher shown on your device to input your seed words. "
"The cipher changes with every keypress.\n"
"After at most 4 letters the device will auto-complete a word.\n"
"Press SPACE or the Accept Word button to accept the device's auto-"
"completed word and advance to the next one.\n"
"Press BACKSPACE to go back a character or word.\n"
"Press ENTER or the Seed Entered button once the last word in your "
"seed is auto-completed.")
class CharacterButton(QPushButton):
def __init__(self, text=None):
QPushButton.__init__(self, text)
def keyPressEvent(self, event):
event.setAccepted(False) # Pass through Enter and Space keys
class CharacterDialog(WindowModalDialog):
def __init__(self, parent):
super(CharacterDialog, self).__init__(parent)
self.setWindowTitle(_("KeepKey Seed Recovery"))
self.character_pos = 0
self.word_pos = 0
self.loop = QEventLoop()
self.word_help = QLabel()
self.char_buttons = []
vbox = QVBoxLayout(self)
vbox.addWidget(WWLabel(CHARACTER_RECOVERY))
hbox = QHBoxLayout()
hbox.addWidget(self.word_help)
for i in range(4):
char_button = CharacterButton('*')
char_button.setMaximumWidth(36)
self.char_buttons.append(char_button)
hbox.addWidget(char_button)
self.accept_button = CharacterButton(_("Accept Word"))
self.accept_button.clicked.connect(partial(self.process_key, 32))
self.rejected.connect(partial(self.loop.exit, 1))
hbox.addWidget(self.accept_button)
hbox.addStretch(1)
vbox.addLayout(hbox)
self.finished_button = QPushButton(_("Seed Entered"))
self.cancel_button = QPushButton(_("Cancel"))
self.finished_button.clicked.connect(partial(self.process_key,
Qt.Key_Return))
self.cancel_button.clicked.connect(self.rejected)
buttons = Buttons(self.finished_button, self.cancel_button)
vbox.addSpacing(40)
vbox.addLayout(buttons)
self.refresh()
self.show()
def refresh(self):
self.word_help.setText("Enter seed word %2d:" % (self.word_pos + 1))
self.accept_button.setEnabled(self.character_pos >= 3)
self.finished_button.setEnabled((self.word_pos in (11, 17, 23)
and self.character_pos >= 3))
for n, button in enumerate(self.char_buttons):
button.setEnabled(n == self.character_pos)
if n == self.character_pos:
button.setFocus()
def is_valid_alpha_space(self, key):
# Auto-completion requires at least 3 characters
if key == ord(' ') and self.character_pos >= 3:
return True
# Firmware aborts protocol if the 5th character is non-space
if self.character_pos >= 4:
return False
return (key >= ord('a') and key <= ord('z')
or (key >= ord('A') and key <= ord('Z')))
def process_key(self, key):
self.data = None
if key == Qt.Key_Return and self.finished_button.isEnabled():
self.data = {'done': True}
elif key == Qt.Key_Backspace and (self.word_pos or self.character_pos):
self.data = {'delete': True}
elif self.is_valid_alpha_space(key):
self.data = {'character': chr(key).lower()}
if self.data:
self.loop.exit(0)
def keyPressEvent(self, event):
self.process_key(event.key())
if not self.data:
QDialog.keyPressEvent(self, event)
def get_char(self, word_pos, character_pos):
self.word_pos = word_pos
self.character_pos = character_pos
self.refresh()
if self.loop.exec_():
self.data = None # User cancelled
class QtHandler(QtHandlerBase):
char_signal = pyqtSignal(object)
pin_signal = pyqtSignal(object)
def __init__(self, win, pin_matrix_widget_class, device):
super(QtHandler, self).__init__(win, device)
self.char_signal.connect(self.update_character_dialog)
self.pin_signal.connect(self.pin_dialog)
self.pin_matrix_widget_class = pin_matrix_widget_class
self.character_dialog = None
def get_char(self, msg):
self.done.clear()
self.char_signal.emit(msg)
self.done.wait()
data = self.character_dialog.data
if not data or 'done' in data:
self.character_dialog.accept()
self.character_dialog = None
return data
def get_pin(self, msg):
self.done.clear()
self.pin_signal.emit(msg)
self.done.wait()
return self.response
def pin_dialog(self, msg):
# Needed e.g. when resetting a device
self.clear_dialog()
dialog = WindowModalDialog(self.top_level_window(), _("Enter PIN"))
matrix = self.pin_matrix_widget_class()
vbox = QVBoxLayout()
vbox.addWidget(QLabel(msg))
vbox.addWidget(matrix)
vbox.addLayout(Buttons(CancelButton(dialog), OkButton(dialog)))
dialog.setLayout(vbox)
dialog.exec_()
self.response = str(matrix.get_value())
self.done.set()
def update_character_dialog(self, msg):
if not self.character_dialog:
self.character_dialog = CharacterDialog(self.top_level_window())
self.character_dialog.get_char(msg.word_pos, msg.character_pos)
self.done.set()
class QtPlugin(QtPluginBase):
# Derived classes must provide the following class-static variables:
# icon_file
# pin_matrix_widget_class
def create_handler(self, window):
return QtHandler(window, self.pin_matrix_widget_class(), self.device)
@hook
def receive_menu(self, menu, addrs, wallet):
if type(wallet) is not Standard_Wallet:
return
keystore = wallet.get_keystore()
if type(keystore) == self.keystore_class and len(addrs) == 1:
def show_address():
keystore.thread.add(partial(self.show_address, wallet, addrs[0]))
menu.addAction(_("Show on %s") % self.device, show_address)
def show_settings_dialog(self, window, keystore):
device_id = self.choose_device(window, keystore)
if device_id:
SettingsDialog(window, self, keystore, device_id).exec_()
def request_trezor_init_settings(self, wizard, method, device):
vbox = QVBoxLayout()
next_enabled = True
label = QLabel(_("Enter a label to name your device:"))
name = QLineEdit()
hl = QHBoxLayout()
hl.addWidget(label)
hl.addWidget(name)
hl.addStretch(1)
vbox.addLayout(hl)
def clean_text(widget):
text = unicode(widget.toPlainText()).strip()
return ' '.join(text.split())
if method in [TIM_NEW, TIM_RECOVER]:
gb = QGroupBox()
hbox1 = QHBoxLayout()
gb.setLayout(hbox1)
# KeepKey recovery doesn't need a word count
if method == TIM_NEW or self.device == 'TREZOR':
vbox.addWidget(gb)
gb.setTitle(_("Select your seed length:"))
bg = QButtonGroup()
for i, count in enumerate([12, 18, 24]):
rb = QRadioButton(gb)
rb.setText(_("%d words") % count)
bg.addButton(rb)
bg.setId(rb, i)
hbox1.addWidget(rb)
rb.setChecked(True)
cb_pin = QCheckBox(_('Enable PIN protection'))
cb_pin.setChecked(True)
else:
text = QTextEdit()
text.setMaximumHeight(60)
if method == TIM_MNEMONIC:
msg = _("Enter your BIP39 mnemonic:")
else:
msg = _("Enter the master private key beginning with xprv:")
def set_enabled():
from electrum_vtc.keystore import is_xprv
wizard.next_button.setEnabled(is_xprv(clean_text(text)))
text.textChanged.connect(set_enabled)
next_enabled = False
vbox.addWidget(QLabel(msg))
vbox.addWidget(text)
pin = QLineEdit()
pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,10}')))
pin.setMaximumWidth(100)
hbox_pin = QHBoxLayout()
hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):")))
hbox_pin.addWidget(pin)
hbox_pin.addStretch(1)
if method in [TIM_NEW, TIM_RECOVER]:
vbox.addWidget(WWLabel(RECOMMEND_PIN))
vbox.addWidget(cb_pin)
else:
vbox.addLayout(hbox_pin)
passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
cb_phrase = QCheckBox(_('Enable passphrases'))
cb_phrase.setChecked(False)
vbox.addWidget(passphrase_msg)
vbox.addWidget(passphrase_warning)
vbox.addWidget(cb_phrase)
wizard.exec_layout(vbox, next_enabled=next_enabled)
if method in [TIM_NEW, TIM_RECOVER]:
item = bg.checkedId()
pin = cb_pin.isChecked()
else:
item = ' '.join(str(clean_text(text)).split())
pin = str(pin.text())
return (item, unicode(name.text()), pin, cb_phrase.isChecked())
class SettingsDialog(WindowModalDialog):
'''This dialog doesn't require a device be paired with a wallet.
We want users to be able to wipe a device even if they've forgotten
their PIN.'''
def __init__(self, window, plugin, keystore, device_id):
title = _("%s Settings") % plugin.device
super(SettingsDialog, self).__init__(window, title)
self.setMaximumWidth(540)
devmgr = plugin.device_manager()
config = devmgr.config
handler = keystore.handler
thread = keystore.thread
hs_rows, hs_cols = (64, 128)
def invoke_client(method, *args, **kw_args):
unpair_after = kw_args.pop('unpair_after', False)
def task():
client = devmgr.client_by_id(device_id)
if not client:
raise RuntimeError("Device not connected")
if method:
getattr(client, method)(*args, **kw_args)
if unpair_after:
devmgr.unpair_id(device_id)
return client.features
thread.add(task, on_success=update)
def update(features):
self.features = features
set_label_enabled()
bl_hash = features.bootloader_hash.encode('hex')
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
noyes = [_("No"), _("Yes")]
endis = [_("Enable Passphrases"), _("Disable Passphrases")]
disen = [_("Disabled"), _("Enabled")]
setchange = [_("Set a PIN"), _("Change PIN")]
version = "%d.%d.%d" % (features.major_version,
features.minor_version,
features.patch_version)
coins = ", ".join(coin.coin_name for coin in features.coins)
device_label.setText(features.label)
pin_set_label.setText(noyes[features.pin_protection])
passphrases_label.setText(disen[features.passphrase_protection])
bl_hash_label.setText(bl_hash)
label_edit.setText(features.label)
device_id_label.setText(features.device_id)
initialized_label.setText(noyes[features.initialized])
version_label.setText(version)
coins_label.setText(coins)
clear_pin_button.setVisible(features.pin_protection)
clear_pin_warning.setVisible(features.pin_protection)
pin_button.setText(setchange[features.pin_protection])
pin_msg.setVisible(not features.pin_protection)
passphrase_button.setText(endis[features.passphrase_protection])
language_label.setText(features.language)
def set_label_enabled():
label_apply.setEnabled(label_edit.text() != self.features.label)
def rename():
invoke_client('change_label', unicode(label_edit.text()))
def toggle_passphrase():
title = _("Confirm Toggle Passphrase Protection")
currently_enabled = self.features.passphrase_protection
if currently_enabled:
msg = _("After disabling passphrases, you can only pair this "
"Electrum wallet if it had an empty passphrase. "
"If its passphrase was not empty, you will need to "
"create a new wallet with the install wizard. You "
"can use this wallet again at any time by re-enabling "
"passphrases and entering its passphrase.")
else:
msg = _("Your current Electrum wallet can only be used with "
"an empty passphrase. You must create a separate "
"wallet with the install wizard for other passphrases "
"as each one generates a new set of addresses.")
msg += "\n\n" + _("Are you sure you want to proceed?")
if not self.question(msg, title=title):
return
invoke_client('toggle_passphrase', unpair_after=currently_enabled)
def change_homescreen():
from PIL import Image # FIXME
dialog = QFileDialog(self, _("Choose Homescreen"))
filename = dialog.getOpenFileName()
if filename:
im = Image.open(str(filename))
if im.size != (hs_cols, hs_rows):
raise Exception('Image must be 64 x 128 pixels')
im = im.convert('1')
pix = im.load()
img = ''
for j in range(hs_rows):
for i in range(hs_cols):
img += '1' if pix[i, j] else '0'
img = ''.join(chr(int(img[i:i + 8], 2))
for i in range(0, len(img), 8))
invoke_client('change_homescreen', img)
def clear_homescreen():
invoke_client('change_homescreen', '\x00')
def set_pin():
invoke_client('set_pin', remove=False)
def clear_pin():
invoke_client('set_pin', remove=True)
def wipe_device():
wallet = window.wallet
if wallet and sum(wallet.get_balance()):
title = _("Confirm Device Wipe")
msg = _("Are you SURE you want to wipe the device?\n"
"Your wallet still has litecoins in it!")
if not self.question(msg, title=title,
icon=QMessageBox.Critical):
return
invoke_client('wipe_device', unpair_after=True)
def slider_moved():
mins = timeout_slider.sliderPosition()
timeout_minutes.setText(_("%2d minutes") % mins)
def slider_released():
config.set_session_timeout(timeout_slider.sliderPosition() * 60)
# Information tab
info_tab = QWidget()
info_layout = QVBoxLayout(info_tab)
info_glayout = QGridLayout()
info_glayout.setColumnStretch(2, 1)
device_label = QLabel()
pin_set_label = QLabel()
passphrases_label = QLabel()
version_label = QLabel()
device_id_label = QLabel()
bl_hash_label = QLabel()
bl_hash_label.setWordWrap(True)
coins_label = QLabel()
coins_label.setWordWrap(True)
language_label = QLabel()
initialized_label = QLabel()
rows = [
(_("Device Label"), device_label),
(_("PIN set"), pin_set_label),
(_("Passphrases"), passphrases_label),
(_("Firmware Version"), version_label),
(_("Device ID"), device_id_label),
(_("Bootloader Hash"), bl_hash_label),
(_("Supported Coins"), coins_label),
(_("Language"), language_label),
(_("Initialized"), initialized_label),
]
for row_num, (label, widget) in enumerate(rows):
info_glayout.addWidget(QLabel(label), row_num, 0)
info_glayout.addWidget(widget, row_num, 1)
info_layout.addLayout(info_glayout)
# Settings tab
settings_tab = QWidget()
settings_layout = QVBoxLayout(settings_tab)
settings_glayout = QGridLayout()
# Settings tab - Label
label_msg = QLabel(_("Name this %s. If you have mutiple devices "
"their labels help distinguish them.")
% plugin.device)
label_msg.setWordWrap(True)
label_label = QLabel(_("Device Label"))
label_edit = QLineEdit()
label_edit.setMinimumWidth(150)
label_edit.setMaxLength(plugin.MAX_LABEL_LEN)
label_apply = QPushButton(_("Apply"))
label_apply.clicked.connect(rename)
label_edit.textChanged.connect(set_label_enabled)
settings_glayout.addWidget(label_label, 0, 0)
settings_glayout.addWidget(label_edit, 0, 1, 1, 2)
settings_glayout.addWidget(label_apply, 0, 3)
settings_glayout.addWidget(label_msg, 1, 1, 1, -1)
# Settings tab - PIN
pin_label = QLabel(_("PIN Protection"))
pin_button = QPushButton()
pin_button.clicked.connect(set_pin)
settings_glayout.addWidget(pin_label, 2, 0)
settings_glayout.addWidget(pin_button, 2, 1)
pin_msg = QLabel(_("PIN protection is strongly recommended. "
"A PIN is your only protection against someone "
"stealing your litecoins if they obtain physical "
"access to your %s.") % plugin.device)
pin_msg.setWordWrap(True)
pin_msg.setStyleSheet("color: red")
settings_glayout.addWidget(pin_msg, 3, 1, 1, -1)
# Settings tab - Homescreen
if plugin.device != 'KeepKey': # Not yet supported by KK firmware
homescreen_layout = QHBoxLayout()
homescreen_label = QLabel(_("Homescreen"))
homescreen_change_button = QPushButton(_("Change..."))
homescreen_clear_button = QPushButton(_("Reset"))
homescreen_change_button.clicked.connect(change_homescreen)
homescreen_clear_button.clicked.connect(clear_homescreen)
homescreen_msg = QLabel(_("You can set the homescreen on your "
"device to personalize it. You must "
"choose a %d x %d monochrome black and "
"white image.") % (hs_rows, hs_cols))
homescreen_msg.setWordWrap(True)
settings_glayout.addWidget(homescreen_label, 4, 0)
settings_glayout.addWidget(homescreen_change_button, 4, 1)
settings_glayout.addWidget(homescreen_clear_button, 4, 2)
settings_glayout.addWidget(homescreen_msg, 5, 1, 1, -1)
# Settings tab - Session Timeout
timeout_label = QLabel(_("Session Timeout"))
timeout_minutes = QLabel()
timeout_slider = QSlider(Qt.Horizontal)
timeout_slider.setRange(1, 60)
timeout_slider.setSingleStep(1)
timeout_slider.setTickInterval(5)
timeout_slider.setTickPosition(QSlider.TicksBelow)
timeout_slider.setTracking(True)
timeout_msg = QLabel(
_("Clear the session after the specified period "
"of inactivity. Once a session has timed out, "
"your PIN and passphrase (if enabled) must be "
"re-entered to use the device."))
timeout_msg.setWordWrap(True)
timeout_slider.setSliderPosition(config.get_session_timeout() // 60)
slider_moved()
timeout_slider.valueChanged.connect(slider_moved)
timeout_slider.sliderReleased.connect(slider_released)
settings_glayout.addWidget(timeout_label, 6, 0)
settings_glayout.addWidget(timeout_slider, 6, 1, 1, 3)
settings_glayout.addWidget(timeout_minutes, 6, 4)
settings_glayout.addWidget(timeout_msg, 7, 1, 1, -1)
settings_layout.addLayout(settings_glayout)
settings_layout.addStretch(1)
# Advanced tab
advanced_tab = QWidget()
advanced_layout = QVBoxLayout(advanced_tab)
advanced_glayout = QGridLayout()
# Advanced tab - clear PIN
clear_pin_button = QPushButton(_("Disable PIN"))
clear_pin_button.clicked.connect(clear_pin)
clear_pin_warning = QLabel(
_("If you disable your PIN, anyone with physical access to your "
"%s device can spend your litecoins.") % plugin.device)
clear_pin_warning.setWordWrap(True)
clear_pin_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(clear_pin_button, 0, 2)
advanced_glayout.addWidget(clear_pin_warning, 1, 0, 1, 5)
# Advanced tab - toggle passphrase protection
passphrase_button = QPushButton()
passphrase_button.clicked.connect(toggle_passphrase)
passphrase_msg = WWLabel(PASSPHRASE_HELP)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(passphrase_button, 3, 2)
advanced_glayout.addWidget(passphrase_msg, 4, 0, 1, 5)
advanced_glayout.addWidget(passphrase_warning, 5, 0, 1, 5)
# Advanced tab - wipe device
wipe_device_button = QPushButton(_("Wipe Device"))
wipe_device_button.clicked.connect(wipe_device)
wipe_device_msg = QLabel(
_("Wipe the device, removing all data from it. The firmware "
"is left unchanged."))
wipe_device_msg.setWordWrap(True)
wipe_device_warning = QLabel(
_("Only wipe a device if you have the recovery seed written down "
"and the device wallet(s) are empty, otherwise the litecoins "
"will be lost forever."))
wipe_device_warning.setWordWrap(True)
wipe_device_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(wipe_device_button, 6, 2)
advanced_glayout.addWidget(wipe_device_msg, 7, 0, 1, 5)
advanced_glayout.addWidget(wipe_device_warning, 8, 0, 1, 5)
advanced_layout.addLayout(advanced_glayout)
advanced_layout.addStretch(1)
tabs = QTabWidget(self)
tabs.addTab(info_tab, _("Information"))
tabs.addTab(settings_tab, _("Settings"))
tabs.addTab(advanced_tab, _("Advanced"))
dialog_vbox = QVBoxLayout(self)
dialog_vbox.addWidget(tabs)
dialog_vbox.addLayout(Buttons(CloseButton(self)))
# Update information
invoke_client(None)
| {
"repo_name": "pknight007/electrum-vtc",
"path": "plugins/trezor/qt_generic.py",
"copies": "2",
"size": "24617",
"license": "mit",
"hash": 260525715068144600,
"line_mean": 40.8656462585,
"line_max": 81,
"alpha_frac": 0.5901206483,
"autogenerated": false,
"ratio": 4.032929226736567,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5623049875036567,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import threading
from PyQt5.QtCore import Qt, pyqtSignal, QRegExp
from PyQt5.QtGui import QRegExpValidator
from PyQt5.QtWidgets import (QVBoxLayout, QLabel, QGridLayout, QPushButton,
QHBoxLayout, QButtonGroup, QGroupBox,
QTextEdit, QLineEdit, QRadioButton, QCheckBox, QWidget,
QMessageBox, QFileDialog, QSlider, QTabWidget)
from electrum.gui.qt.util import (WindowModalDialog, WWLabel, Buttons, CancelButton,
OkButton, CloseButton)
from electrum.i18n import _
from electrum.plugin import hook
from electrum.util import bh2u
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
from ..hw_wallet.plugin import only_hook_if_libraries_available
from .safe_t import SafeTPlugin, TIM_NEW, TIM_RECOVER, TIM_MNEMONIC
PASSPHRASE_HELP_SHORT =_(
"Passphrases allow you to access new wallets, each "
"hidden behind a particular case-sensitive passphrase.")
PASSPHRASE_HELP = PASSPHRASE_HELP_SHORT + " " + _(
"You need to create a separate Electrum wallet for each passphrase "
"you use as they each generate different addresses. Changing "
"your passphrase does not lose other wallets, each is still "
"accessible behind its own passphrase.")
RECOMMEND_PIN = _(
"You should enable PIN protection. Your PIN is the only protection "
"for your fujicoins if your device is lost or stolen.")
PASSPHRASE_NOT_PIN = _(
"If you forget a passphrase you will be unable to access any "
"fujicoins in the wallet behind it. A passphrase is not a PIN. "
"Only change this if you are sure you understand it.")
class QtHandler(QtHandlerBase):
pin_signal = pyqtSignal(object)
def __init__(self, win, pin_matrix_widget_class, device):
super(QtHandler, self).__init__(win, device)
self.pin_signal.connect(self.pin_dialog)
self.pin_matrix_widget_class = pin_matrix_widget_class
def get_pin(self, msg):
self.done.clear()
self.pin_signal.emit(msg)
self.done.wait()
return self.response
def pin_dialog(self, msg):
# Needed e.g. when resetting a device
self.clear_dialog()
dialog = WindowModalDialog(self.top_level_window(), _("Enter PIN"))
matrix = self.pin_matrix_widget_class()
vbox = QVBoxLayout()
vbox.addWidget(QLabel(msg))
vbox.addWidget(matrix)
vbox.addLayout(Buttons(CancelButton(dialog), OkButton(dialog)))
dialog.setLayout(vbox)
dialog.exec_()
self.response = str(matrix.get_value())
self.done.set()
class QtPlugin(QtPluginBase):
# Derived classes must provide the following class-static variables:
# icon_file
# pin_matrix_widget_class
def create_handler(self, window):
return QtHandler(window, self.pin_matrix_widget_class(), self.device)
@only_hook_if_libraries_available
@hook
def receive_menu(self, menu, addrs, wallet):
if len(addrs) != 1:
return
for keystore in wallet.get_keystores():
if type(keystore) == self.keystore_class:
def show_address(keystore=keystore):
keystore.thread.add(partial(self.show_address, wallet, addrs[0], keystore))
device_name = "{} ({})".format(self.device, keystore.label)
menu.addAction(_("Show on {}").format(device_name), show_address)
def show_settings_dialog(self, window, keystore):
device_id = self.choose_device(window, keystore)
if device_id:
SettingsDialog(window, self, keystore, device_id).exec_()
def request_safe_t_init_settings(self, wizard, method, device):
vbox = QVBoxLayout()
next_enabled = True
label = QLabel(_("Enter a label to name your device:"))
name = QLineEdit()
hl = QHBoxLayout()
hl.addWidget(label)
hl.addWidget(name)
hl.addStretch(1)
vbox.addLayout(hl)
def clean_text(widget):
text = widget.toPlainText().strip()
return ' '.join(text.split())
if method in [TIM_NEW, TIM_RECOVER]:
gb = QGroupBox()
hbox1 = QHBoxLayout()
gb.setLayout(hbox1)
vbox.addWidget(gb)
gb.setTitle(_("Select your seed length:"))
bg = QButtonGroup()
for i, count in enumerate([12, 18, 24]):
rb = QRadioButton(gb)
rb.setText(_("{:d} words").format(count))
bg.addButton(rb)
bg.setId(rb, i)
hbox1.addWidget(rb)
rb.setChecked(True)
cb_pin = QCheckBox(_('Enable PIN protection'))
cb_pin.setChecked(True)
else:
text = QTextEdit()
text.setMaximumHeight(60)
if method == TIM_MNEMONIC:
msg = _("Enter your BIP39 mnemonic:")
else:
msg = _("Enter the master private key beginning with xprv:")
def set_enabled():
from electrum.bip32 import is_xprv
wizard.next_button.setEnabled(is_xprv(clean_text(text)))
text.textChanged.connect(set_enabled)
next_enabled = False
vbox.addWidget(QLabel(msg))
vbox.addWidget(text)
pin = QLineEdit()
pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,9}')))
pin.setMaximumWidth(100)
hbox_pin = QHBoxLayout()
hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):")))
hbox_pin.addWidget(pin)
hbox_pin.addStretch(1)
if method in [TIM_NEW, TIM_RECOVER]:
vbox.addWidget(WWLabel(RECOMMEND_PIN))
vbox.addWidget(cb_pin)
else:
vbox.addLayout(hbox_pin)
passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
cb_phrase = QCheckBox(_('Enable passphrases'))
cb_phrase.setChecked(False)
vbox.addWidget(passphrase_msg)
vbox.addWidget(passphrase_warning)
vbox.addWidget(cb_phrase)
wizard.exec_layout(vbox, next_enabled=next_enabled)
if method in [TIM_NEW, TIM_RECOVER]:
item = bg.checkedId()
pin = cb_pin.isChecked()
else:
item = ' '.join(str(clean_text(text)).split())
pin = str(pin.text())
return (item, name.text(), pin, cb_phrase.isChecked())
class Plugin(SafeTPlugin, QtPlugin):
icon_unpaired = "safe-t_unpaired.png"
icon_paired = "safe-t.png"
@classmethod
def pin_matrix_widget_class(self):
# We use a local updated copy of pinmatrix.py until safetlib
# releases a new version that includes https://github.com/archos-safe-t/python-safet/commit/b1eab3dba4c04fdfc1fcf17b66662c28c5f2380e
# from safetlib.qt.pinmatrix import PinMatrixWidget
from .pinmatrix import PinMatrixWidget
return PinMatrixWidget
class SettingsDialog(WindowModalDialog):
'''This dialog doesn't require a device be paired with a wallet.
We want users to be able to wipe a device even if they've forgotten
their PIN.'''
def __init__(self, window, plugin, keystore, device_id):
title = _("{} Settings").format(plugin.device)
super(SettingsDialog, self).__init__(window, title)
self.setMaximumWidth(540)
devmgr = plugin.device_manager()
config = devmgr.config
handler = keystore.handler
thread = keystore.thread
hs_cols, hs_rows = (128, 64)
def invoke_client(method, *args, **kw_args):
unpair_after = kw_args.pop('unpair_after', False)
def task():
client = devmgr.client_by_id(device_id)
if not client:
raise RuntimeError("Device not connected")
if method:
getattr(client, method)(*args, **kw_args)
if unpair_after:
devmgr.unpair_id(device_id)
return client.features
thread.add(task, on_success=update)
def update(features):
self.features = features
set_label_enabled()
if features.bootloader_hash:
bl_hash = bh2u(features.bootloader_hash)
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
else:
bl_hash = "N/A"
noyes = [_("No"), _("Yes")]
endis = [_("Enable Passphrases"), _("Disable Passphrases")]
disen = [_("Disabled"), _("Enabled")]
setchange = [_("Set a PIN"), _("Change PIN")]
version = "%d.%d.%d" % (features.major_version,
features.minor_version,
features.patch_version)
device_label.setText(features.label)
pin_set_label.setText(noyes[features.pin_protection])
passphrases_label.setText(disen[features.passphrase_protection])
bl_hash_label.setText(bl_hash)
label_edit.setText(features.label)
device_id_label.setText(features.device_id)
initialized_label.setText(noyes[features.initialized])
version_label.setText(version)
clear_pin_button.setVisible(features.pin_protection)
clear_pin_warning.setVisible(features.pin_protection)
pin_button.setText(setchange[features.pin_protection])
pin_msg.setVisible(not features.pin_protection)
passphrase_button.setText(endis[features.passphrase_protection])
language_label.setText(features.language)
def set_label_enabled():
label_apply.setEnabled(label_edit.text() != self.features.label)
def rename():
invoke_client('change_label', label_edit.text())
def toggle_passphrase():
title = _("Confirm Toggle Passphrase Protection")
currently_enabled = self.features.passphrase_protection
if currently_enabled:
msg = _("After disabling passphrases, you can only pair this "
"Electrum wallet if it had an empty passphrase. "
"If its passphrase was not empty, you will need to "
"create a new wallet with the install wizard. You "
"can use this wallet again at any time by re-enabling "
"passphrases and entering its passphrase.")
else:
msg = _("Your current Electrum wallet can only be used with "
"an empty passphrase. You must create a separate "
"wallet with the install wizard for other passphrases "
"as each one generates a new set of addresses.")
msg += "\n\n" + _("Are you sure you want to proceed?")
if not self.question(msg, title=title):
return
invoke_client('toggle_passphrase', unpair_after=currently_enabled)
def change_homescreen():
dialog = QFileDialog(self, _("Choose Homescreen"))
filename, __ = dialog.getOpenFileName()
if not filename:
return # user cancelled
if filename.endswith('.toif'):
img = open(filename, 'rb').read()
if img[:8] != b'TOIf\x90\x00\x90\x00':
handler.show_error('File is not a TOIF file with size of 144x144')
return
else:
from PIL import Image # FIXME
im = Image.open(filename)
if im.size != (128, 64):
handler.show_error('Image must be 128 x 64 pixels')
return
im = im.convert('1')
pix = im.load()
img = bytearray(1024)
for j in range(64):
for i in range(128):
if pix[i, j]:
o = (i + j * 128)
img[o // 8] |= (1 << (7 - o % 8))
img = bytes(img)
invoke_client('change_homescreen', img)
def clear_homescreen():
invoke_client('change_homescreen', b'\x00')
def set_pin():
invoke_client('set_pin', remove=False)
def clear_pin():
invoke_client('set_pin', remove=True)
def wipe_device():
wallet = window.wallet
if wallet and sum(wallet.get_balance()):
title = _("Confirm Device Wipe")
msg = _("Are you SURE you want to wipe the device?\n"
"Your wallet still has fujicoins in it!")
if not self.question(msg, title=title,
icon=QMessageBox.Critical):
return
invoke_client('wipe_device', unpair_after=True)
def slider_moved():
mins = timeout_slider.sliderPosition()
timeout_minutes.setText(_("{:2d} minutes").format(mins))
def slider_released():
config.set_session_timeout(timeout_slider.sliderPosition() * 60)
# Information tab
info_tab = QWidget()
info_layout = QVBoxLayout(info_tab)
info_glayout = QGridLayout()
info_glayout.setColumnStretch(2, 1)
device_label = QLabel()
pin_set_label = QLabel()
passphrases_label = QLabel()
version_label = QLabel()
device_id_label = QLabel()
bl_hash_label = QLabel()
bl_hash_label.setWordWrap(True)
language_label = QLabel()
initialized_label = QLabel()
rows = [
(_("Device Label"), device_label),
(_("PIN set"), pin_set_label),
(_("Passphrases"), passphrases_label),
(_("Firmware Version"), version_label),
(_("Device ID"), device_id_label),
(_("Bootloader Hash"), bl_hash_label),
(_("Language"), language_label),
(_("Initialized"), initialized_label),
]
for row_num, (label, widget) in enumerate(rows):
info_glayout.addWidget(QLabel(label), row_num, 0)
info_glayout.addWidget(widget, row_num, 1)
info_layout.addLayout(info_glayout)
# Settings tab
settings_tab = QWidget()
settings_layout = QVBoxLayout(settings_tab)
settings_glayout = QGridLayout()
# Settings tab - Label
label_msg = QLabel(_("Name this {}. If you have multiple devices "
"their labels help distinguish them.")
.format(plugin.device))
label_msg.setWordWrap(True)
label_label = QLabel(_("Device Label"))
label_edit = QLineEdit()
label_edit.setMinimumWidth(150)
label_edit.setMaxLength(plugin.MAX_LABEL_LEN)
label_apply = QPushButton(_("Apply"))
label_apply.clicked.connect(rename)
label_edit.textChanged.connect(set_label_enabled)
settings_glayout.addWidget(label_label, 0, 0)
settings_glayout.addWidget(label_edit, 0, 1, 1, 2)
settings_glayout.addWidget(label_apply, 0, 3)
settings_glayout.addWidget(label_msg, 1, 1, 1, -1)
# Settings tab - PIN
pin_label = QLabel(_("PIN Protection"))
pin_button = QPushButton()
pin_button.clicked.connect(set_pin)
settings_glayout.addWidget(pin_label, 2, 0)
settings_glayout.addWidget(pin_button, 2, 1)
pin_msg = QLabel(_("PIN protection is strongly recommended. "
"A PIN is your only protection against someone "
"stealing your fujicoins if they obtain physical "
"access to your {}.").format(plugin.device))
pin_msg.setWordWrap(True)
pin_msg.setStyleSheet("color: red")
settings_glayout.addWidget(pin_msg, 3, 1, 1, -1)
# Settings tab - Homescreen
homescreen_label = QLabel(_("Homescreen"))
homescreen_change_button = QPushButton(_("Change..."))
homescreen_clear_button = QPushButton(_("Reset"))
homescreen_change_button.clicked.connect(change_homescreen)
try:
import PIL
except ImportError:
homescreen_change_button.setDisabled(True)
homescreen_change_button.setToolTip(
_("Required package 'PIL' is not available - Please install it.")
)
homescreen_clear_button.clicked.connect(clear_homescreen)
homescreen_msg = QLabel(_("You can set the homescreen on your "
"device to personalize it. You must "
"choose a {} x {} monochrome black and "
"white image.").format(hs_cols, hs_rows))
homescreen_msg.setWordWrap(True)
settings_glayout.addWidget(homescreen_label, 4, 0)
settings_glayout.addWidget(homescreen_change_button, 4, 1)
settings_glayout.addWidget(homescreen_clear_button, 4, 2)
settings_glayout.addWidget(homescreen_msg, 5, 1, 1, -1)
# Settings tab - Session Timeout
timeout_label = QLabel(_("Session Timeout"))
timeout_minutes = QLabel()
timeout_slider = QSlider(Qt.Horizontal)
timeout_slider.setRange(1, 60)
timeout_slider.setSingleStep(1)
timeout_slider.setTickInterval(5)
timeout_slider.setTickPosition(QSlider.TicksBelow)
timeout_slider.setTracking(True)
timeout_msg = QLabel(
_("Clear the session after the specified period "
"of inactivity. Once a session has timed out, "
"your PIN and passphrase (if enabled) must be "
"re-entered to use the device."))
timeout_msg.setWordWrap(True)
timeout_slider.setSliderPosition(config.get_session_timeout() // 60)
slider_moved()
timeout_slider.valueChanged.connect(slider_moved)
timeout_slider.sliderReleased.connect(slider_released)
settings_glayout.addWidget(timeout_label, 6, 0)
settings_glayout.addWidget(timeout_slider, 6, 1, 1, 3)
settings_glayout.addWidget(timeout_minutes, 6, 4)
settings_glayout.addWidget(timeout_msg, 7, 1, 1, -1)
settings_layout.addLayout(settings_glayout)
settings_layout.addStretch(1)
# Advanced tab
advanced_tab = QWidget()
advanced_layout = QVBoxLayout(advanced_tab)
advanced_glayout = QGridLayout()
# Advanced tab - clear PIN
clear_pin_button = QPushButton(_("Disable PIN"))
clear_pin_button.clicked.connect(clear_pin)
clear_pin_warning = QLabel(
_("If you disable your PIN, anyone with physical access to your "
"{} device can spend your fujicoins.").format(plugin.device))
clear_pin_warning.setWordWrap(True)
clear_pin_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(clear_pin_button, 0, 2)
advanced_glayout.addWidget(clear_pin_warning, 1, 0, 1, 5)
# Advanced tab - toggle passphrase protection
passphrase_button = QPushButton()
passphrase_button.clicked.connect(toggle_passphrase)
passphrase_msg = WWLabel(PASSPHRASE_HELP)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(passphrase_button, 3, 2)
advanced_glayout.addWidget(passphrase_msg, 4, 0, 1, 5)
advanced_glayout.addWidget(passphrase_warning, 5, 0, 1, 5)
# Advanced tab - wipe device
wipe_device_button = QPushButton(_("Wipe Device"))
wipe_device_button.clicked.connect(wipe_device)
wipe_device_msg = QLabel(
_("Wipe the device, removing all data from it. The firmware "
"is left unchanged."))
wipe_device_msg.setWordWrap(True)
wipe_device_warning = QLabel(
_("Only wipe a device if you have the recovery seed written down "
"and the device wallet(s) are empty, otherwise the fujicoins "
"will be lost forever."))
wipe_device_warning.setWordWrap(True)
wipe_device_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(wipe_device_button, 6, 2)
advanced_glayout.addWidget(wipe_device_msg, 7, 0, 1, 5)
advanced_glayout.addWidget(wipe_device_warning, 8, 0, 1, 5)
advanced_layout.addLayout(advanced_glayout)
advanced_layout.addStretch(1)
tabs = QTabWidget(self)
tabs.addTab(info_tab, _("Information"))
tabs.addTab(settings_tab, _("Settings"))
tabs.addTab(advanced_tab, _("Advanced"))
dialog_vbox = QVBoxLayout(self)
dialog_vbox.addWidget(tabs)
dialog_vbox.addLayout(Buttons(CloseButton(self)))
# Update information
invoke_client(None)
| {
"repo_name": "fujicoin/electrum-fjc",
"path": "electrum/plugins/safe_t/qt.py",
"copies": "1",
"size": "21165",
"license": "mit",
"hash": 8978019974203894000,
"line_mean": 41.33,
"line_max": 140,
"alpha_frac": 0.5860618946,
"autogenerated": false,
"ratio": 4.07724908495473,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0003313897425133694,
"num_lines": 500
} |
from functools import partial
import threading
from PyQt5.QtCore import Qt, QEventLoop, pyqtSignal
from PyQt5.QtWidgets import (QVBoxLayout, QLabel, QGridLayout, QPushButton,
QHBoxLayout, QButtonGroup, QGroupBox, QDialog,
QLineEdit, QRadioButton, QCheckBox, QWidget,
QMessageBox, QFileDialog, QSlider, QTabWidget)
from electrum.gui.qt.util import (WindowModalDialog, WWLabel, Buttons, CancelButton,
OkButton, CloseButton)
from electrum.i18n import _
from electrum.plugin import hook
from electrum.util import bh2u
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
from ..hw_wallet.plugin import only_hook_if_libraries_available
from .trezor import (TrezorPlugin, TIM_NEW, TIM_RECOVER, TrezorInitSettings,
RECOVERY_TYPE_SCRAMBLED_WORDS, RECOVERY_TYPE_MATRIX)
PASSPHRASE_HELP_SHORT =_(
"Passphrases allow you to access new wallets, each "
"hidden behind a particular case-sensitive passphrase.")
PASSPHRASE_HELP = PASSPHRASE_HELP_SHORT + " " + _(
"You need to create a separate Electrum wallet for each passphrase "
"you use as they each generate different addresses. Changing "
"your passphrase does not lose other wallets, each is still "
"accessible behind its own passphrase.")
RECOMMEND_PIN = _(
"You should enable PIN protection. Your PIN is the only protection "
"for your fujicoins if your device is lost or stolen.")
PASSPHRASE_NOT_PIN = _(
"If you forget a passphrase you will be unable to access any "
"fujicoins in the wallet behind it. A passphrase is not a PIN. "
"Only change this if you are sure you understand it.")
MATRIX_RECOVERY = _(
"Enter the recovery words by pressing the buttons according to what "
"the device shows on its display. You can also use your NUMPAD.\n"
"Press BACKSPACE to go back a choice or word.\n")
SEEDLESS_MODE_WARNING = _(
"In seedless mode, the mnemonic seed words are never shown to the user.\n"
"There is no backup, and the user has a proof of this.\n"
"This is an advanced feature, only suggested to be used in redundant multisig setups.")
class MatrixDialog(WindowModalDialog):
def __init__(self, parent):
super(MatrixDialog, self).__init__(parent)
self.setWindowTitle(_("Trezor Matrix Recovery"))
self.num = 9
self.loop = QEventLoop()
vbox = QVBoxLayout(self)
vbox.addWidget(WWLabel(MATRIX_RECOVERY))
grid = QGridLayout()
grid.setSpacing(0)
self.char_buttons = []
for y in range(3):
for x in range(3):
button = QPushButton('?')
button.clicked.connect(partial(self.process_key, ord('1') + y * 3 + x))
grid.addWidget(button, 3 - y, x)
self.char_buttons.append(button)
vbox.addLayout(grid)
self.backspace_button = QPushButton("<=")
self.backspace_button.clicked.connect(partial(self.process_key, Qt.Key_Backspace))
self.cancel_button = QPushButton(_("Cancel"))
self.cancel_button.clicked.connect(partial(self.process_key, Qt.Key_Escape))
buttons = Buttons(self.backspace_button, self.cancel_button)
vbox.addSpacing(40)
vbox.addLayout(buttons)
self.refresh()
self.show()
def refresh(self):
for y in range(3):
self.char_buttons[3 * y + 1].setEnabled(self.num == 9)
def is_valid(self, key):
return key >= ord('1') and key <= ord('9')
def process_key(self, key):
self.data = None
if key == Qt.Key_Backspace:
self.data = '\010'
elif key == Qt.Key_Escape:
self.data = 'x'
elif self.is_valid(key):
self.char_buttons[key - ord('1')].setFocus()
self.data = '%c' % key
if self.data:
self.loop.exit(0)
def keyPressEvent(self, event):
self.process_key(event.key())
if not self.data:
QDialog.keyPressEvent(self, event)
def get_matrix(self, num):
self.num = num
self.refresh()
self.loop.exec_()
class QtHandler(QtHandlerBase):
pin_signal = pyqtSignal(object)
matrix_signal = pyqtSignal(object)
close_matrix_dialog_signal = pyqtSignal()
def __init__(self, win, pin_matrix_widget_class, device):
super(QtHandler, self).__init__(win, device)
self.pin_signal.connect(self.pin_dialog)
self.matrix_signal.connect(self.matrix_recovery_dialog)
self.close_matrix_dialog_signal.connect(self._close_matrix_dialog)
self.pin_matrix_widget_class = pin_matrix_widget_class
self.matrix_dialog = None
def get_pin(self, msg):
self.done.clear()
self.pin_signal.emit(msg)
self.done.wait()
return self.response
def get_matrix(self, msg):
self.done.clear()
self.matrix_signal.emit(msg)
self.done.wait()
data = self.matrix_dialog.data
if data == 'x':
self.close_matrix_dialog()
return data
def _close_matrix_dialog(self):
if self.matrix_dialog:
self.matrix_dialog.accept()
self.matrix_dialog = None
def close_matrix_dialog(self):
self.close_matrix_dialog_signal.emit()
def pin_dialog(self, msg):
# Needed e.g. when resetting a device
self.clear_dialog()
dialog = WindowModalDialog(self.top_level_window(), _("Enter PIN"))
matrix = self.pin_matrix_widget_class()
vbox = QVBoxLayout()
vbox.addWidget(QLabel(msg))
vbox.addWidget(matrix)
vbox.addLayout(Buttons(CancelButton(dialog), OkButton(dialog)))
dialog.setLayout(vbox)
dialog.exec_()
self.response = str(matrix.get_value())
self.done.set()
def matrix_recovery_dialog(self, msg):
if not self.matrix_dialog:
self.matrix_dialog = MatrixDialog(self.top_level_window())
self.matrix_dialog.get_matrix(msg)
self.done.set()
class QtPlugin(QtPluginBase):
# Derived classes must provide the following class-static variables:
# icon_file
# pin_matrix_widget_class
def create_handler(self, window):
return QtHandler(window, self.pin_matrix_widget_class(), self.device)
@only_hook_if_libraries_available
@hook
def receive_menu(self, menu, addrs, wallet):
if len(addrs) != 1:
return
for keystore in wallet.get_keystores():
if type(keystore) == self.keystore_class:
def show_address(keystore=keystore):
keystore.thread.add(partial(self.show_address, wallet, addrs[0], keystore))
device_name = "{} ({})".format(self.device, keystore.label)
menu.addAction(_("Show on {}").format(device_name), show_address)
def show_settings_dialog(self, window, keystore):
device_id = self.choose_device(window, keystore)
if device_id:
SettingsDialog(window, self, keystore, device_id).exec_()
def request_trezor_init_settings(self, wizard, method, device_id):
vbox = QVBoxLayout()
next_enabled = True
devmgr = self.device_manager()
client = devmgr.client_by_id(device_id)
if not client:
raise Exception(_("The device was disconnected."))
model = client.get_trezor_model()
fw_version = client.client.version
# label
label = QLabel(_("Enter a label to name your device:"))
name = QLineEdit()
hl = QHBoxLayout()
hl.addWidget(label)
hl.addWidget(name)
hl.addStretch(1)
vbox.addLayout(hl)
# word count
gb = QGroupBox()
hbox1 = QHBoxLayout()
gb.setLayout(hbox1)
vbox.addWidget(gb)
gb.setTitle(_("Select your seed length:"))
bg_numwords = QButtonGroup()
word_counts = (12, 18, 24)
for i, count in enumerate(word_counts):
rb = QRadioButton(gb)
rb.setText(_("{:d} words").format(count))
bg_numwords.addButton(rb)
bg_numwords.setId(rb, i)
hbox1.addWidget(rb)
rb.setChecked(True)
# PIN
cb_pin = QCheckBox(_('Enable PIN protection'))
cb_pin.setChecked(True)
vbox.addWidget(WWLabel(RECOMMEND_PIN))
vbox.addWidget(cb_pin)
# "expert settings" button
expert_vbox = QVBoxLayout()
expert_widget = QWidget()
expert_widget.setLayout(expert_vbox)
expert_widget.setVisible(False)
expert_button = QPushButton(_("Show expert settings"))
def show_expert_settings():
expert_button.setVisible(False)
expert_widget.setVisible(True)
expert_button.clicked.connect(show_expert_settings)
vbox.addWidget(expert_button)
# passphrase
passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
cb_phrase = QCheckBox(_('Enable passphrases'))
cb_phrase.setChecked(False)
expert_vbox.addWidget(passphrase_msg)
expert_vbox.addWidget(passphrase_warning)
expert_vbox.addWidget(cb_phrase)
# ask for recovery type (random word order OR matrix)
bg_rectype = None
if method == TIM_RECOVER and not model == 'T':
gb_rectype = QGroupBox()
hbox_rectype = QHBoxLayout()
gb_rectype.setLayout(hbox_rectype)
expert_vbox.addWidget(gb_rectype)
gb_rectype.setTitle(_("Select recovery type:"))
bg_rectype = QButtonGroup()
rb1 = QRadioButton(gb_rectype)
rb1.setText(_('Scrambled words'))
bg_rectype.addButton(rb1)
bg_rectype.setId(rb1, RECOVERY_TYPE_SCRAMBLED_WORDS)
hbox_rectype.addWidget(rb1)
rb1.setChecked(True)
rb2 = QRadioButton(gb_rectype)
rb2.setText(_('Matrix'))
bg_rectype.addButton(rb2)
bg_rectype.setId(rb2, RECOVERY_TYPE_MATRIX)
hbox_rectype.addWidget(rb2)
# no backup
cb_no_backup = None
if method == TIM_NEW:
cb_no_backup = QCheckBox(f'''{_('Enable seedless mode')}''')
cb_no_backup.setChecked(False)
if (model == '1' and fw_version >= (1, 7, 1)
or model == 'T' and fw_version >= (2, 0, 9)):
cb_no_backup.setToolTip(SEEDLESS_MODE_WARNING)
else:
cb_no_backup.setEnabled(False)
cb_no_backup.setToolTip(_('Firmware version too old.'))
expert_vbox.addWidget(cb_no_backup)
vbox.addWidget(expert_widget)
wizard.exec_layout(vbox, next_enabled=next_enabled)
return TrezorInitSettings(
word_count=word_counts[bg_numwords.checkedId()],
label=name.text(),
pin_enabled=cb_pin.isChecked(),
passphrase_enabled=cb_phrase.isChecked(),
recovery_type=bg_rectype.checkedId() if bg_rectype else None,
no_backup=cb_no_backup.isChecked() if cb_no_backup else False,
)
class Plugin(TrezorPlugin, QtPlugin):
icon_unpaired = "trezor_unpaired.png"
icon_paired = "trezor.png"
@classmethod
def pin_matrix_widget_class(self):
from trezorlib.qt.pinmatrix import PinMatrixWidget
return PinMatrixWidget
class SettingsDialog(WindowModalDialog):
'''This dialog doesn't require a device be paired with a wallet.
We want users to be able to wipe a device even if they've forgotten
their PIN.'''
def __init__(self, window, plugin, keystore, device_id):
title = _("{} Settings").format(plugin.device)
super(SettingsDialog, self).__init__(window, title)
self.setMaximumWidth(540)
devmgr = plugin.device_manager()
config = devmgr.config
handler = keystore.handler
thread = keystore.thread
hs_cols, hs_rows = (128, 64)
def invoke_client(method, *args, **kw_args):
unpair_after = kw_args.pop('unpair_after', False)
def task():
client = devmgr.client_by_id(device_id)
if not client:
raise RuntimeError("Device not connected")
if method:
getattr(client, method)(*args, **kw_args)
if unpair_after:
devmgr.unpair_id(device_id)
return client.features
thread.add(task, on_success=update)
def update(features):
self.features = features
set_label_enabled()
if features.bootloader_hash:
bl_hash = bh2u(features.bootloader_hash)
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
else:
bl_hash = "N/A"
noyes = [_("No"), _("Yes")]
endis = [_("Enable Passphrases"), _("Disable Passphrases")]
disen = [_("Disabled"), _("Enabled")]
setchange = [_("Set a PIN"), _("Change PIN")]
version = "%d.%d.%d" % (features.major_version,
features.minor_version,
features.patch_version)
device_label.setText(features.label)
pin_set_label.setText(noyes[features.pin_protection])
passphrases_label.setText(disen[features.passphrase_protection])
bl_hash_label.setText(bl_hash)
label_edit.setText(features.label)
device_id_label.setText(features.device_id)
initialized_label.setText(noyes[features.initialized])
version_label.setText(version)
clear_pin_button.setVisible(features.pin_protection)
clear_pin_warning.setVisible(features.pin_protection)
pin_button.setText(setchange[features.pin_protection])
pin_msg.setVisible(not features.pin_protection)
passphrase_button.setText(endis[features.passphrase_protection])
language_label.setText(features.language)
def set_label_enabled():
label_apply.setEnabled(label_edit.text() != self.features.label)
def rename():
invoke_client('change_label', label_edit.text())
def toggle_passphrase():
title = _("Confirm Toggle Passphrase Protection")
currently_enabled = self.features.passphrase_protection
if currently_enabled:
msg = _("After disabling passphrases, you can only pair this "
"Electrum wallet if it had an empty passphrase. "
"If its passphrase was not empty, you will need to "
"create a new wallet with the install wizard. You "
"can use this wallet again at any time by re-enabling "
"passphrases and entering its passphrase.")
else:
msg = _("Your current Electrum wallet can only be used with "
"an empty passphrase. You must create a separate "
"wallet with the install wizard for other passphrases "
"as each one generates a new set of addresses.")
msg += "\n\n" + _("Are you sure you want to proceed?")
if not self.question(msg, title=title):
return
invoke_client('toggle_passphrase', unpair_after=currently_enabled)
def change_homescreen():
dialog = QFileDialog(self, _("Choose Homescreen"))
filename, __ = dialog.getOpenFileName()
if not filename:
return # user cancelled
if filename.endswith('.toif'):
img = open(filename, 'rb').read()
if img[:8] != b'TOIf\x90\x00\x90\x00':
handler.show_error('File is not a TOIF file with size of 144x144')
return
else:
from PIL import Image # FIXME
im = Image.open(filename)
if im.size != (128, 64):
handler.show_error('Image must be 128 x 64 pixels')
return
im = im.convert('1')
pix = im.load()
img = bytearray(1024)
for j in range(64):
for i in range(128):
if pix[i, j]:
o = (i + j * 128)
img[o // 8] |= (1 << (7 - o % 8))
img = bytes(img)
invoke_client('change_homescreen', img)
def clear_homescreen():
invoke_client('change_homescreen', b'\x00')
def set_pin():
invoke_client('set_pin', remove=False)
def clear_pin():
invoke_client('set_pin', remove=True)
def wipe_device():
wallet = window.wallet
if wallet and sum(wallet.get_balance()):
title = _("Confirm Device Wipe")
msg = _("Are you SURE you want to wipe the device?\n"
"Your wallet still has fujicoins in it!")
if not self.question(msg, title=title,
icon=QMessageBox.Critical):
return
invoke_client('wipe_device', unpair_after=True)
def slider_moved():
mins = timeout_slider.sliderPosition()
timeout_minutes.setText(_("{:2d} minutes").format(mins))
def slider_released():
config.set_session_timeout(timeout_slider.sliderPosition() * 60)
# Information tab
info_tab = QWidget()
info_layout = QVBoxLayout(info_tab)
info_glayout = QGridLayout()
info_glayout.setColumnStretch(2, 1)
device_label = QLabel()
pin_set_label = QLabel()
passphrases_label = QLabel()
version_label = QLabel()
device_id_label = QLabel()
bl_hash_label = QLabel()
bl_hash_label.setWordWrap(True)
language_label = QLabel()
initialized_label = QLabel()
rows = [
(_("Device Label"), device_label),
(_("PIN set"), pin_set_label),
(_("Passphrases"), passphrases_label),
(_("Firmware Version"), version_label),
(_("Device ID"), device_id_label),
(_("Bootloader Hash"), bl_hash_label),
(_("Language"), language_label),
(_("Initialized"), initialized_label),
]
for row_num, (label, widget) in enumerate(rows):
info_glayout.addWidget(QLabel(label), row_num, 0)
info_glayout.addWidget(widget, row_num, 1)
info_layout.addLayout(info_glayout)
# Settings tab
settings_tab = QWidget()
settings_layout = QVBoxLayout(settings_tab)
settings_glayout = QGridLayout()
# Settings tab - Label
label_msg = QLabel(_("Name this {}. If you have multiple devices "
"their labels help distinguish them.")
.format(plugin.device))
label_msg.setWordWrap(True)
label_label = QLabel(_("Device Label"))
label_edit = QLineEdit()
label_edit.setMinimumWidth(150)
label_edit.setMaxLength(plugin.MAX_LABEL_LEN)
label_apply = QPushButton(_("Apply"))
label_apply.clicked.connect(rename)
label_edit.textChanged.connect(set_label_enabled)
settings_glayout.addWidget(label_label, 0, 0)
settings_glayout.addWidget(label_edit, 0, 1, 1, 2)
settings_glayout.addWidget(label_apply, 0, 3)
settings_glayout.addWidget(label_msg, 1, 1, 1, -1)
# Settings tab - PIN
pin_label = QLabel(_("PIN Protection"))
pin_button = QPushButton()
pin_button.clicked.connect(set_pin)
settings_glayout.addWidget(pin_label, 2, 0)
settings_glayout.addWidget(pin_button, 2, 1)
pin_msg = QLabel(_("PIN protection is strongly recommended. "
"A PIN is your only protection against someone "
"stealing your fujicoins if they obtain physical "
"access to your {}.").format(plugin.device))
pin_msg.setWordWrap(True)
pin_msg.setStyleSheet("color: red")
settings_glayout.addWidget(pin_msg, 3, 1, 1, -1)
# Settings tab - Homescreen
homescreen_label = QLabel(_("Homescreen"))
homescreen_change_button = QPushButton(_("Change..."))
homescreen_clear_button = QPushButton(_("Reset"))
homescreen_change_button.clicked.connect(change_homescreen)
try:
import PIL
except ImportError:
homescreen_change_button.setDisabled(True)
homescreen_change_button.setToolTip(
_("Required package 'PIL' is not available - Please install it or use the Trezor website instead.")
)
homescreen_clear_button.clicked.connect(clear_homescreen)
homescreen_msg = QLabel(_("You can set the homescreen on your "
"device to personalize it. You must "
"choose a {} x {} monochrome black and "
"white image.").format(hs_cols, hs_rows))
homescreen_msg.setWordWrap(True)
settings_glayout.addWidget(homescreen_label, 4, 0)
settings_glayout.addWidget(homescreen_change_button, 4, 1)
settings_glayout.addWidget(homescreen_clear_button, 4, 2)
settings_glayout.addWidget(homescreen_msg, 5, 1, 1, -1)
# Settings tab - Session Timeout
timeout_label = QLabel(_("Session Timeout"))
timeout_minutes = QLabel()
timeout_slider = QSlider(Qt.Horizontal)
timeout_slider.setRange(1, 60)
timeout_slider.setSingleStep(1)
timeout_slider.setTickInterval(5)
timeout_slider.setTickPosition(QSlider.TicksBelow)
timeout_slider.setTracking(True)
timeout_msg = QLabel(
_("Clear the session after the specified period "
"of inactivity. Once a session has timed out, "
"your PIN and passphrase (if enabled) must be "
"re-entered to use the device."))
timeout_msg.setWordWrap(True)
timeout_slider.setSliderPosition(config.get_session_timeout() // 60)
slider_moved()
timeout_slider.valueChanged.connect(slider_moved)
timeout_slider.sliderReleased.connect(slider_released)
settings_glayout.addWidget(timeout_label, 6, 0)
settings_glayout.addWidget(timeout_slider, 6, 1, 1, 3)
settings_glayout.addWidget(timeout_minutes, 6, 4)
settings_glayout.addWidget(timeout_msg, 7, 1, 1, -1)
settings_layout.addLayout(settings_glayout)
settings_layout.addStretch(1)
# Advanced tab
advanced_tab = QWidget()
advanced_layout = QVBoxLayout(advanced_tab)
advanced_glayout = QGridLayout()
# Advanced tab - clear PIN
clear_pin_button = QPushButton(_("Disable PIN"))
clear_pin_button.clicked.connect(clear_pin)
clear_pin_warning = QLabel(
_("If you disable your PIN, anyone with physical access to your "
"{} device can spend your fujicoins.").format(plugin.device))
clear_pin_warning.setWordWrap(True)
clear_pin_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(clear_pin_button, 0, 2)
advanced_glayout.addWidget(clear_pin_warning, 1, 0, 1, 5)
# Advanced tab - toggle passphrase protection
passphrase_button = QPushButton()
passphrase_button.clicked.connect(toggle_passphrase)
passphrase_msg = WWLabel(PASSPHRASE_HELP)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(passphrase_button, 3, 2)
advanced_glayout.addWidget(passphrase_msg, 4, 0, 1, 5)
advanced_glayout.addWidget(passphrase_warning, 5, 0, 1, 5)
# Advanced tab - wipe device
wipe_device_button = QPushButton(_("Wipe Device"))
wipe_device_button.clicked.connect(wipe_device)
wipe_device_msg = QLabel(
_("Wipe the device, removing all data from it. The firmware "
"is left unchanged."))
wipe_device_msg.setWordWrap(True)
wipe_device_warning = QLabel(
_("Only wipe a device if you have the recovery seed written down "
"and the device wallet(s) are empty, otherwise the fujicoins "
"will be lost forever."))
wipe_device_warning.setWordWrap(True)
wipe_device_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(wipe_device_button, 6, 2)
advanced_glayout.addWidget(wipe_device_msg, 7, 0, 1, 5)
advanced_glayout.addWidget(wipe_device_warning, 8, 0, 1, 5)
advanced_layout.addLayout(advanced_glayout)
advanced_layout.addStretch(1)
tabs = QTabWidget(self)
tabs.addTab(info_tab, _("Information"))
tabs.addTab(settings_tab, _("Settings"))
tabs.addTab(advanced_tab, _("Advanced"))
dialog_vbox = QVBoxLayout(self)
dialog_vbox.addWidget(tabs)
dialog_vbox.addLayout(Buttons(CloseButton(self)))
# Update information
invoke_client(None)
| {
"repo_name": "fujicoin/electrum-fjc",
"path": "electrum/plugins/trezor/qt.py",
"copies": "1",
"size": "25638",
"license": "mit",
"hash": -6910710811248882000,
"line_mean": 39.8899521531,
"line_max": 115,
"alpha_frac": 0.5903736641,
"autogenerated": false,
"ratio": 3.992836006852515,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5083209670952514,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import threading
from PyQt5.QtCore import Qt, QEventLoop, pyqtSignal, QRegExp
from PyQt5.QtGui import QRegExpValidator
from PyQt5.QtWidgets import (QVBoxLayout, QLabel, QGridLayout, QPushButton,
QHBoxLayout, QButtonGroup, QGroupBox, QDialog,
QTextEdit, QLineEdit, QRadioButton, QCheckBox, QWidget,
QMessageBox, QFileDialog, QSlider, QTabWidget)
from electrum.gui.qt.util import (WindowModalDialog, WWLabel, Buttons, CancelButton,
OkButton, CloseButton)
from electrum.i18n import _
from electrum.plugin import hook
from electrum.util import bh2u
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
from ..hw_wallet.plugin import only_hook_if_libraries_available
from .keepkey import KeepKeyPlugin, TIM_NEW, TIM_RECOVER, TIM_MNEMONIC
PASSPHRASE_HELP_SHORT =_(
"Passphrases allow you to access new wallets, each "
"hidden behind a particular case-sensitive passphrase.")
PASSPHRASE_HELP = PASSPHRASE_HELP_SHORT + " " + _(
"You need to create a separate Electrum wallet for each passphrase "
"you use as they each generate different addresses. Changing "
"your passphrase does not lose other wallets, each is still "
"accessible behind its own passphrase.")
RECOMMEND_PIN = _(
"You should enable PIN protection. Your PIN is the only protection "
"for your fujicoins if your device is lost or stolen.")
PASSPHRASE_NOT_PIN = _(
"If you forget a passphrase you will be unable to access any "
"fujicoins in the wallet behind it. A passphrase is not a PIN. "
"Only change this if you are sure you understand it.")
CHARACTER_RECOVERY = (
"Use the recovery cipher shown on your device to input your seed words. "
"The cipher changes with every keypress.\n"
"After at most 4 letters the device will auto-complete a word.\n"
"Press SPACE or the Accept Word button to accept the device's auto-"
"completed word and advance to the next one.\n"
"Press BACKSPACE to go back a character or word.\n"
"Press ENTER or the Seed Entered button once the last word in your "
"seed is auto-completed.")
class CharacterButton(QPushButton):
def __init__(self, text=None):
QPushButton.__init__(self, text)
def keyPressEvent(self, event):
event.setAccepted(False) # Pass through Enter and Space keys
class CharacterDialog(WindowModalDialog):
def __init__(self, parent):
super(CharacterDialog, self).__init__(parent)
self.setWindowTitle(_("KeepKey Seed Recovery"))
self.character_pos = 0
self.word_pos = 0
self.loop = QEventLoop()
self.word_help = QLabel()
self.char_buttons = []
vbox = QVBoxLayout(self)
vbox.addWidget(WWLabel(CHARACTER_RECOVERY))
hbox = QHBoxLayout()
hbox.addWidget(self.word_help)
for i in range(4):
char_button = CharacterButton('*')
char_button.setMaximumWidth(36)
self.char_buttons.append(char_button)
hbox.addWidget(char_button)
self.accept_button = CharacterButton(_("Accept Word"))
self.accept_button.clicked.connect(partial(self.process_key, 32))
self.rejected.connect(partial(self.loop.exit, 1))
hbox.addWidget(self.accept_button)
hbox.addStretch(1)
vbox.addLayout(hbox)
self.finished_button = QPushButton(_("Seed Entered"))
self.cancel_button = QPushButton(_("Cancel"))
self.finished_button.clicked.connect(partial(self.process_key,
Qt.Key_Return))
self.cancel_button.clicked.connect(self.rejected)
buttons = Buttons(self.finished_button, self.cancel_button)
vbox.addSpacing(40)
vbox.addLayout(buttons)
self.refresh()
self.show()
def refresh(self):
self.word_help.setText("Enter seed word %2d:" % (self.word_pos + 1))
self.accept_button.setEnabled(self.character_pos >= 3)
self.finished_button.setEnabled((self.word_pos in (11, 17, 23)
and self.character_pos >= 3))
for n, button in enumerate(self.char_buttons):
button.setEnabled(n == self.character_pos)
if n == self.character_pos:
button.setFocus()
def is_valid_alpha_space(self, key):
# Auto-completion requires at least 3 characters
if key == ord(' ') and self.character_pos >= 3:
return True
# Firmware aborts protocol if the 5th character is non-space
if self.character_pos >= 4:
return False
return (key >= ord('a') and key <= ord('z')
or (key >= ord('A') and key <= ord('Z')))
def process_key(self, key):
self.data = None
if key == Qt.Key_Return and self.finished_button.isEnabled():
self.data = {'done': True}
elif key == Qt.Key_Backspace and (self.word_pos or self.character_pos):
self.data = {'delete': True}
elif self.is_valid_alpha_space(key):
self.data = {'character': chr(key).lower()}
if self.data:
self.loop.exit(0)
def keyPressEvent(self, event):
self.process_key(event.key())
if not self.data:
QDialog.keyPressEvent(self, event)
def get_char(self, word_pos, character_pos):
self.word_pos = word_pos
self.character_pos = character_pos
self.refresh()
if self.loop.exec_():
self.data = None # User cancelled
class QtHandler(QtHandlerBase):
char_signal = pyqtSignal(object)
pin_signal = pyqtSignal(object)
close_char_dialog_signal = pyqtSignal()
def __init__(self, win, pin_matrix_widget_class, device):
super(QtHandler, self).__init__(win, device)
self.char_signal.connect(self.update_character_dialog)
self.pin_signal.connect(self.pin_dialog)
self.close_char_dialog_signal.connect(self._close_char_dialog)
self.pin_matrix_widget_class = pin_matrix_widget_class
self.character_dialog = None
def get_char(self, msg):
self.done.clear()
self.char_signal.emit(msg)
self.done.wait()
data = self.character_dialog.data
if not data or 'done' in data:
self.close_char_dialog_signal.emit()
return data
def _close_char_dialog(self):
if self.character_dialog:
self.character_dialog.accept()
self.character_dialog = None
def get_pin(self, msg):
self.done.clear()
self.pin_signal.emit(msg)
self.done.wait()
return self.response
def pin_dialog(self, msg):
# Needed e.g. when resetting a device
self.clear_dialog()
dialog = WindowModalDialog(self.top_level_window(), _("Enter PIN"))
matrix = self.pin_matrix_widget_class()
vbox = QVBoxLayout()
vbox.addWidget(QLabel(msg))
vbox.addWidget(matrix)
vbox.addLayout(Buttons(CancelButton(dialog), OkButton(dialog)))
dialog.setLayout(vbox)
dialog.exec_()
self.response = str(matrix.get_value())
self.done.set()
def update_character_dialog(self, msg):
if not self.character_dialog:
self.character_dialog = CharacterDialog(self.top_level_window())
self.character_dialog.get_char(msg.word_pos, msg.character_pos)
self.done.set()
class QtPlugin(QtPluginBase):
# Derived classes must provide the following class-static variables:
# icon_file
# pin_matrix_widget_class
def create_handler(self, window):
return QtHandler(window, self.pin_matrix_widget_class(), self.device)
@only_hook_if_libraries_available
@hook
def receive_menu(self, menu, addrs, wallet):
if len(addrs) != 1:
return
for keystore in wallet.get_keystores():
if type(keystore) == self.keystore_class:
def show_address():
keystore.thread.add(partial(self.show_address, wallet, addrs[0], keystore))
device_name = "{} ({})".format(self.device, keystore.label)
menu.addAction(_("Show on {}").format(device_name), show_address)
def show_settings_dialog(self, window, keystore):
device_id = self.choose_device(window, keystore)
if device_id:
SettingsDialog(window, self, keystore, device_id).exec_()
def request_trezor_init_settings(self, wizard, method, device):
vbox = QVBoxLayout()
next_enabled = True
label = QLabel(_("Enter a label to name your device:"))
name = QLineEdit()
hl = QHBoxLayout()
hl.addWidget(label)
hl.addWidget(name)
hl.addStretch(1)
vbox.addLayout(hl)
def clean_text(widget):
text = widget.toPlainText().strip()
return ' '.join(text.split())
if method in [TIM_NEW, TIM_RECOVER]:
gb = QGroupBox()
hbox1 = QHBoxLayout()
gb.setLayout(hbox1)
# KeepKey recovery doesn't need a word count
if method == TIM_NEW:
vbox.addWidget(gb)
gb.setTitle(_("Select your seed length:"))
bg = QButtonGroup()
for i, count in enumerate([12, 18, 24]):
rb = QRadioButton(gb)
rb.setText(_("{} words").format(count))
bg.addButton(rb)
bg.setId(rb, i)
hbox1.addWidget(rb)
rb.setChecked(True)
cb_pin = QCheckBox(_('Enable PIN protection'))
cb_pin.setChecked(True)
else:
text = QTextEdit()
text.setMaximumHeight(60)
if method == TIM_MNEMONIC:
msg = _("Enter your BIP39 mnemonic:")
else:
msg = _("Enter the master private key beginning with xprv:")
def set_enabled():
from electrum.bip32 import is_xprv
wizard.next_button.setEnabled(is_xprv(clean_text(text)))
text.textChanged.connect(set_enabled)
next_enabled = False
vbox.addWidget(QLabel(msg))
vbox.addWidget(text)
pin = QLineEdit()
pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,9}')))
pin.setMaximumWidth(100)
hbox_pin = QHBoxLayout()
hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):")))
hbox_pin.addWidget(pin)
hbox_pin.addStretch(1)
if method in [TIM_NEW, TIM_RECOVER]:
vbox.addWidget(WWLabel(RECOMMEND_PIN))
vbox.addWidget(cb_pin)
else:
vbox.addLayout(hbox_pin)
passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
cb_phrase = QCheckBox(_('Enable passphrases'))
cb_phrase.setChecked(False)
vbox.addWidget(passphrase_msg)
vbox.addWidget(passphrase_warning)
vbox.addWidget(cb_phrase)
wizard.exec_layout(vbox, next_enabled=next_enabled)
if method in [TIM_NEW, TIM_RECOVER]:
item = bg.checkedId()
pin = cb_pin.isChecked()
else:
item = ' '.join(str(clean_text(text)).split())
pin = str(pin.text())
return (item, name.text(), pin, cb_phrase.isChecked())
class Plugin(KeepKeyPlugin, QtPlugin):
icon_paired = "keepkey.png"
icon_unpaired = "keepkey_unpaired.png"
@classmethod
def pin_matrix_widget_class(self):
from keepkeylib.qt.pinmatrix import PinMatrixWidget
return PinMatrixWidget
class SettingsDialog(WindowModalDialog):
'''This dialog doesn't require a device be paired with a wallet.
We want users to be able to wipe a device even if they've forgotten
their PIN.'''
def __init__(self, window, plugin, keystore, device_id):
title = _("{} Settings").format(plugin.device)
super(SettingsDialog, self).__init__(window, title)
self.setMaximumWidth(540)
devmgr = plugin.device_manager()
config = devmgr.config
handler = keystore.handler
thread = keystore.thread
def invoke_client(method, *args, **kw_args):
unpair_after = kw_args.pop('unpair_after', False)
def task():
client = devmgr.client_by_id(device_id)
if not client:
raise RuntimeError("Device not connected")
if method:
getattr(client, method)(*args, **kw_args)
if unpair_after:
devmgr.unpair_id(device_id)
return client.features
thread.add(task, on_success=update)
def update(features):
self.features = features
set_label_enabled()
bl_hash = bh2u(features.bootloader_hash)
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
noyes = [_("No"), _("Yes")]
endis = [_("Enable Passphrases"), _("Disable Passphrases")]
disen = [_("Disabled"), _("Enabled")]
setchange = [_("Set a PIN"), _("Change PIN")]
version = "%d.%d.%d" % (features.major_version,
features.minor_version,
features.patch_version)
coins = ", ".join(coin.coin_name for coin in features.coins)
device_label.setText(features.label)
pin_set_label.setText(noyes[features.pin_protection])
passphrases_label.setText(disen[features.passphrase_protection])
bl_hash_label.setText(bl_hash)
label_edit.setText(features.label)
device_id_label.setText(features.device_id)
initialized_label.setText(noyes[features.initialized])
version_label.setText(version)
coins_label.setText(coins)
clear_pin_button.setVisible(features.pin_protection)
clear_pin_warning.setVisible(features.pin_protection)
pin_button.setText(setchange[features.pin_protection])
pin_msg.setVisible(not features.pin_protection)
passphrase_button.setText(endis[features.passphrase_protection])
language_label.setText(features.language)
def set_label_enabled():
label_apply.setEnabled(label_edit.text() != self.features.label)
def rename():
invoke_client('change_label', label_edit.text())
def toggle_passphrase():
title = _("Confirm Toggle Passphrase Protection")
currently_enabled = self.features.passphrase_protection
if currently_enabled:
msg = _("After disabling passphrases, you can only pair this "
"Electrum wallet if it had an empty passphrase. "
"If its passphrase was not empty, you will need to "
"create a new wallet with the install wizard. You "
"can use this wallet again at any time by re-enabling "
"passphrases and entering its passphrase.")
else:
msg = _("Your current Electrum wallet can only be used with "
"an empty passphrase. You must create a separate "
"wallet with the install wizard for other passphrases "
"as each one generates a new set of addresses.")
msg += "\n\n" + _("Are you sure you want to proceed?")
if not self.question(msg, title=title):
return
invoke_client('toggle_passphrase', unpair_after=currently_enabled)
def set_pin():
invoke_client('set_pin', remove=False)
def clear_pin():
invoke_client('set_pin', remove=True)
def wipe_device():
wallet = window.wallet
if wallet and sum(wallet.get_balance()):
title = _("Confirm Device Wipe")
msg = _("Are you SURE you want to wipe the device?\n"
"Your wallet still has fujicoins in it!")
if not self.question(msg, title=title,
icon=QMessageBox.Critical):
return
invoke_client('wipe_device', unpair_after=True)
def slider_moved():
mins = timeout_slider.sliderPosition()
timeout_minutes.setText(_("{:2d} minutes").format(mins))
def slider_released():
config.set_session_timeout(timeout_slider.sliderPosition() * 60)
# Information tab
info_tab = QWidget()
info_layout = QVBoxLayout(info_tab)
info_glayout = QGridLayout()
info_glayout.setColumnStretch(2, 1)
device_label = QLabel()
pin_set_label = QLabel()
passphrases_label = QLabel()
version_label = QLabel()
device_id_label = QLabel()
bl_hash_label = QLabel()
bl_hash_label.setWordWrap(True)
coins_label = QLabel()
coins_label.setWordWrap(True)
language_label = QLabel()
initialized_label = QLabel()
rows = [
(_("Device Label"), device_label),
(_("PIN set"), pin_set_label),
(_("Passphrases"), passphrases_label),
(_("Firmware Version"), version_label),
(_("Device ID"), device_id_label),
(_("Bootloader Hash"), bl_hash_label),
(_("Supported Coins"), coins_label),
(_("Language"), language_label),
(_("Initialized"), initialized_label),
]
for row_num, (label, widget) in enumerate(rows):
info_glayout.addWidget(QLabel(label), row_num, 0)
info_glayout.addWidget(widget, row_num, 1)
info_layout.addLayout(info_glayout)
# Settings tab
settings_tab = QWidget()
settings_layout = QVBoxLayout(settings_tab)
settings_glayout = QGridLayout()
# Settings tab - Label
label_msg = QLabel(_("Name this {}. If you have multiple devices "
"their labels help distinguish them.")
.format(plugin.device))
label_msg.setWordWrap(True)
label_label = QLabel(_("Device Label"))
label_edit = QLineEdit()
label_edit.setMinimumWidth(150)
label_edit.setMaxLength(plugin.MAX_LABEL_LEN)
label_apply = QPushButton(_("Apply"))
label_apply.clicked.connect(rename)
label_edit.textChanged.connect(set_label_enabled)
settings_glayout.addWidget(label_label, 0, 0)
settings_glayout.addWidget(label_edit, 0, 1, 1, 2)
settings_glayout.addWidget(label_apply, 0, 3)
settings_glayout.addWidget(label_msg, 1, 1, 1, -1)
# Settings tab - PIN
pin_label = QLabel(_("PIN Protection"))
pin_button = QPushButton()
pin_button.clicked.connect(set_pin)
settings_glayout.addWidget(pin_label, 2, 0)
settings_glayout.addWidget(pin_button, 2, 1)
pin_msg = QLabel(_("PIN protection is strongly recommended. "
"A PIN is your only protection against someone "
"stealing your fujicoins if they obtain physical "
"access to your {}.").format(plugin.device))
pin_msg.setWordWrap(True)
pin_msg.setStyleSheet("color: red")
settings_glayout.addWidget(pin_msg, 3, 1, 1, -1)
# Settings tab - Session Timeout
timeout_label = QLabel(_("Session Timeout"))
timeout_minutes = QLabel()
timeout_slider = QSlider(Qt.Horizontal)
timeout_slider.setRange(1, 60)
timeout_slider.setSingleStep(1)
timeout_slider.setTickInterval(5)
timeout_slider.setTickPosition(QSlider.TicksBelow)
timeout_slider.setTracking(True)
timeout_msg = QLabel(
_("Clear the session after the specified period "
"of inactivity. Once a session has timed out, "
"your PIN and passphrase (if enabled) must be "
"re-entered to use the device."))
timeout_msg.setWordWrap(True)
timeout_slider.setSliderPosition(config.get_session_timeout() // 60)
slider_moved()
timeout_slider.valueChanged.connect(slider_moved)
timeout_slider.sliderReleased.connect(slider_released)
settings_glayout.addWidget(timeout_label, 6, 0)
settings_glayout.addWidget(timeout_slider, 6, 1, 1, 3)
settings_glayout.addWidget(timeout_minutes, 6, 4)
settings_glayout.addWidget(timeout_msg, 7, 1, 1, -1)
settings_layout.addLayout(settings_glayout)
settings_layout.addStretch(1)
# Advanced tab
advanced_tab = QWidget()
advanced_layout = QVBoxLayout(advanced_tab)
advanced_glayout = QGridLayout()
# Advanced tab - clear PIN
clear_pin_button = QPushButton(_("Disable PIN"))
clear_pin_button.clicked.connect(clear_pin)
clear_pin_warning = QLabel(
_("If you disable your PIN, anyone with physical access to your "
"{} device can spend your fujicoins.").format(plugin.device))
clear_pin_warning.setWordWrap(True)
clear_pin_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(clear_pin_button, 0, 2)
advanced_glayout.addWidget(clear_pin_warning, 1, 0, 1, 5)
# Advanced tab - toggle passphrase protection
passphrase_button = QPushButton()
passphrase_button.clicked.connect(toggle_passphrase)
passphrase_msg = WWLabel(PASSPHRASE_HELP)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(passphrase_button, 3, 2)
advanced_glayout.addWidget(passphrase_msg, 4, 0, 1, 5)
advanced_glayout.addWidget(passphrase_warning, 5, 0, 1, 5)
# Advanced tab - wipe device
wipe_device_button = QPushButton(_("Wipe Device"))
wipe_device_button.clicked.connect(wipe_device)
wipe_device_msg = QLabel(
_("Wipe the device, removing all data from it. The firmware "
"is left unchanged."))
wipe_device_msg.setWordWrap(True)
wipe_device_warning = QLabel(
_("Only wipe a device if you have the recovery seed written down "
"and the device wallet(s) are empty, otherwise the fujicoins "
"will be lost forever."))
wipe_device_warning.setWordWrap(True)
wipe_device_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(wipe_device_button, 6, 2)
advanced_glayout.addWidget(wipe_device_msg, 7, 0, 1, 5)
advanced_glayout.addWidget(wipe_device_warning, 8, 0, 1, 5)
advanced_layout.addLayout(advanced_glayout)
advanced_layout.addStretch(1)
tabs = QTabWidget(self)
tabs.addTab(info_tab, _("Information"))
tabs.addTab(settings_tab, _("Settings"))
tabs.addTab(advanced_tab, _("Advanced"))
dialog_vbox = QVBoxLayout(self)
dialog_vbox.addWidget(tabs)
dialog_vbox.addLayout(Buttons(CloseButton(self)))
# Update information
invoke_client(None)
| {
"repo_name": "fujicoin/electrum-fjc",
"path": "electrum/plugins/keepkey/qt.py",
"copies": "1",
"size": "23536",
"license": "mit",
"hash": 3026895717498574300,
"line_mean": 40.2912280702,
"line_max": 95,
"alpha_frac": 0.5975526852,
"autogenerated": false,
"ratio": 4.02944701249786,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0003057636465380179,
"num_lines": 570
} |
from functools import partial
import threading
from PyQt5.Qt import Qt
from PyQt5.Qt import QGridLayout, QInputDialog, QPushButton
from PyQt5.Qt import QVBoxLayout, QLabel
from electroncash_gui.qt.util import *
from .plugin import TIM_NEW, TIM_RECOVER, TIM_MNEMONIC
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
from electroncash.i18n import _
from electroncash.plugins import hook, DeviceMgr
from electroncash.util import PrintError, UserCancelled
from electroncash.wallet import Wallet, Standard_Wallet
PASSPHRASE_HELP_SHORT =_(
"Passphrases allow you to access new wallets, each "
"hidden behind a particular case-sensitive passphrase.")
PASSPHRASE_HELP = PASSPHRASE_HELP_SHORT + " " + _(
"You need to create a separate Electrum wallet for each passphrase "
"you use as they each generate different addresses. Changing "
"your passphrase does not lose other wallets, each is still "
"accessible behind its own passphrase.")
RECOMMEND_PIN = _(
"You should enable PIN protection. Your PIN is the only protection "
"for your bitcoins if your device is lost or stolen.")
PASSPHRASE_NOT_PIN = _(
"If you forget a passphrase you will be unable to access any "
"bitcoins in the wallet behind it. A passphrase is not a PIN. "
"Only change this if you are sure you understand it.")
CHARACTER_RECOVERY = (
"Use the recovery cipher shown on your device to input your seed words. "
"The cipher changes with every keypress.\n"
"After at most 4 letters the device will auto-complete a word.\n"
"Press SPACE or the Accept Word button to accept the device's auto-"
"completed word and advance to the next one.\n"
"Press BACKSPACE to go back a character or word.\n"
"Press ENTER or the Seed Entered button once the last word in your "
"seed is auto-completed.")
class CharacterButton(QPushButton):
def __init__(self, text=None):
QPushButton.__init__(self, text)
def keyPressEvent(self, event):
event.setAccepted(False) # Pass through Enter and Space keys
class CharacterDialog(WindowModalDialog):
def __init__(self, parent):
super(CharacterDialog, self).__init__(parent)
self.setWindowTitle(_("KeepKey Seed Recovery"))
self.character_pos = 0
self.word_pos = 0
self.loop = QEventLoop()
self.word_help = QLabel()
self.char_buttons = []
vbox = QVBoxLayout(self)
vbox.addWidget(WWLabel(CHARACTER_RECOVERY))
hbox = QHBoxLayout()
hbox.addWidget(self.word_help)
for i in range(4):
char_button = CharacterButton('*')
char_button.setMaximumWidth(36)
self.char_buttons.append(char_button)
hbox.addWidget(char_button)
self.accept_button = CharacterButton(_("Accept Word"))
self.accept_button.clicked.connect(partial(self.process_key, 32))
self.rejected.connect(partial(self.loop.exit, 1))
hbox.addWidget(self.accept_button)
hbox.addStretch(1)
vbox.addLayout(hbox)
self.finished_button = QPushButton(_("Seed Entered"))
self.cancel_button = QPushButton(_("Cancel"))
self.finished_button.clicked.connect(partial(self.process_key,
Qt.Key_Return))
self.cancel_button.clicked.connect(self.rejected)
buttons = Buttons(self.finished_button, self.cancel_button)
vbox.addSpacing(40)
vbox.addLayout(buttons)
self.refresh()
self.show()
def refresh(self):
self.word_help.setText("Enter seed word %2d:" % (self.word_pos + 1))
self.accept_button.setEnabled(self.character_pos >= 3)
self.finished_button.setEnabled((self.word_pos in (11, 17, 23)
and self.character_pos >= 3))
for n, button in enumerate(self.char_buttons):
button.setEnabled(n == self.character_pos)
if n == self.character_pos:
button.setFocus()
def is_valid_alpha_space(self, key):
# Auto-completion requires at least 3 characters
if key == ord(' ') and self.character_pos >= 3:
return True
# Firmware aborts protocol if the 5th character is non-space
if self.character_pos >= 4:
return False
return (key >= ord('a') and key <= ord('z')
or (key >= ord('A') and key <= ord('Z')))
def process_key(self, key):
self.data = None
if key == Qt.Key_Return and self.finished_button.isEnabled():
self.data = {'done': True}
elif key == Qt.Key_Backspace and (self.word_pos or self.character_pos):
self.data = {'delete': True}
elif self.is_valid_alpha_space(key):
self.data = {'character': chr(key).lower()}
if self.data:
self.loop.exit(0)
def keyPressEvent(self, event):
self.process_key(event.key())
if not self.data:
QDialog.keyPressEvent(self, event)
def get_char(self, word_pos, character_pos):
self.word_pos = word_pos
self.character_pos = character_pos
self.refresh()
if self.loop.exec_():
self.data = None # User cancelled
class QtHandler(QtHandlerBase):
char_signal = pyqtSignal(object)
pin_signal = pyqtSignal(object)
def __init__(self, win, pin_matrix_widget_class, device):
super(QtHandler, self).__init__(win, device)
self.char_signal.connect(self.update_character_dialog)
self.pin_signal.connect(self.pin_dialog)
self.pin_matrix_widget_class = pin_matrix_widget_class
self.character_dialog = None
def get_char(self, msg):
self.done.clear()
self.char_signal.emit(msg)
self.done.wait()
data = self.character_dialog.data
if not data or 'done' in data:
self.character_dialog.accept()
self.character_dialog = None
return data
def get_pin(self, msg):
self.done.clear()
self.pin_signal.emit(msg)
self.done.wait()
return self.response
def pin_dialog(self, msg):
# Needed e.g. when resetting a device
self.clear_dialog()
dialog = WindowModalDialog(self.top_level_window(), _("Enter PIN"))
matrix = self.pin_matrix_widget_class()
vbox = QVBoxLayout()
vbox.addWidget(QLabel(msg))
vbox.addWidget(matrix)
vbox.addLayout(Buttons(CancelButton(dialog), OkButton(dialog)))
dialog.setLayout(vbox)
dialog.exec_()
self.response = str(matrix.get_value())
self.done.set()
def update_character_dialog(self, msg):
if not self.character_dialog:
self.character_dialog = CharacterDialog(self.top_level_window())
self.character_dialog.get_char(msg.word_pos, msg.character_pos)
self.done.set()
class QtPlugin(QtPluginBase):
# Derived classes must provide the following class-static variables:
# icon_file
# pin_matrix_widget_class
def create_handler(self, window):
return QtHandler(window, self.pin_matrix_widget_class(), self.device)
@hook
def receive_menu(self, menu, addrs, wallet):
if type(wallet) is not Standard_Wallet:
return
keystore = wallet.get_keystore()
if type(keystore) == self.keystore_class and len(addrs) == 1:
def show_address():
keystore.thread.add(partial(self.show_address, wallet, addrs[0]))
menu.addAction(_("Show on %s") % self.device, show_address)
def show_settings_dialog(self, window, keystore):
device_id = self.choose_device(window, keystore)
if device_id:
SettingsDialog(window, self, keystore, device_id).exec_()
def request_trezor_init_settings(self, wizard, method, device):
vbox = QVBoxLayout()
next_enabled = True
label = QLabel(_("Enter a label to name your device:"))
name = QLineEdit()
hl = QHBoxLayout()
hl.addWidget(label)
hl.addWidget(name)
hl.addStretch(1)
vbox.addLayout(hl)
def clean_text(widget):
text = unicode(widget.toPlainText()).strip()
return ' '.join(text.split())
if method in [TIM_NEW, TIM_RECOVER]:
gb = QGroupBox()
hbox1 = QHBoxLayout()
gb.setLayout(hbox1)
# KeepKey recovery doesn't need a word count
if method == TIM_NEW or self.device == 'TREZOR':
vbox.addWidget(gb)
gb.setTitle(_("Select your seed length:"))
bg = QButtonGroup()
for i, count in enumerate([12, 18, 24]):
rb = QRadioButton(gb)
rb.setText(_("%d words") % count)
bg.addButton(rb)
bg.setId(rb, i)
hbox1.addWidget(rb)
rb.setChecked(True)
cb_pin = QCheckBox(_('Enable PIN protection'))
cb_pin.setChecked(True)
else:
text = QTextEdit()
text.setMaximumHeight(60)
if method == TIM_MNEMONIC:
msg = _("Enter your BIP39 mnemonic:")
else:
msg = _("Enter the master private key beginning with xprv:")
def set_enabled():
from electroncash.keystore import is_xprv
wizard.next_button.setEnabled(is_xprv(clean_text(text)))
text.textChanged.connect(set_enabled)
next_enabled = False
vbox.addWidget(QLabel(msg))
vbox.addWidget(text)
pin = QLineEdit()
pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,10}')))
pin.setMaximumWidth(100)
hbox_pin = QHBoxLayout()
hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):")))
hbox_pin.addWidget(pin)
hbox_pin.addStretch(1)
if method in [TIM_NEW, TIM_RECOVER]:
vbox.addWidget(WWLabel(RECOMMEND_PIN))
vbox.addWidget(cb_pin)
else:
vbox.addLayout(hbox_pin)
passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
cb_phrase = QCheckBox(_('Enable passphrases'))
cb_phrase.setChecked(False)
vbox.addWidget(passphrase_msg)
vbox.addWidget(passphrase_warning)
vbox.addWidget(cb_phrase)
wizard.exec_layout(vbox, next_enabled=next_enabled)
if method in [TIM_NEW, TIM_RECOVER]:
item = bg.checkedId()
pin = cb_pin.isChecked()
else:
item = ' '.join(str(clean_text(text)).split())
pin = str(pin.text())
return (item, unicode(name.text()), pin, cb_phrase.isChecked())
class SettingsDialog(WindowModalDialog):
'''This dialog doesn't require a device be paired with a wallet.
We want users to be able to wipe a device even if they've forgotten
their PIN.'''
def __init__(self, window, plugin, keystore, device_id):
title = _("%s Settings") % plugin.device
super(SettingsDialog, self).__init__(window, title)
self.setMaximumWidth(540)
devmgr = plugin.device_manager()
config = devmgr.config
handler = keystore.handler
thread = keystore.thread
hs_rows, hs_cols = (64, 128)
def invoke_client(method, *args, **kw_args):
unpair_after = kw_args.pop('unpair_after', False)
def task():
client = devmgr.client_by_id(device_id)
if not client:
raise RuntimeError("Device not connected")
if method:
getattr(client, method)(*args, **kw_args)
if unpair_after:
devmgr.unpair_id(device_id)
return client.features
thread.add(task, on_success=update)
def update(features):
self.features = features
set_label_enabled()
bl_hash = features.bootloader_hash.encode('hex')
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
noyes = [_("No"), _("Yes")]
endis = [_("Enable Passphrases"), _("Disable Passphrases")]
disen = [_("Disabled"), _("Enabled")]
setchange = [_("Set a PIN"), _("Change PIN")]
version = "%d.%d.%d" % (features.major_version,
features.minor_version,
features.patch_version)
coins = ", ".join(coin.coin_name for coin in features.coins)
device_label.setText(features.label)
pin_set_label.setText(noyes[features.pin_protection])
passphrases_label.setText(disen[features.passphrase_protection])
bl_hash_label.setText(bl_hash)
label_edit.setText(features.label)
device_id_label.setText(features.device_id)
initialized_label.setText(noyes[features.initialized])
version_label.setText(version)
coins_label.setText(coins)
clear_pin_button.setVisible(features.pin_protection)
clear_pin_warning.setVisible(features.pin_protection)
pin_button.setText(setchange[features.pin_protection])
pin_msg.setVisible(not features.pin_protection)
passphrase_button.setText(endis[features.passphrase_protection])
language_label.setText(features.language)
def set_label_enabled():
label_apply.setEnabled(label_edit.text() != self.features.label)
def rename():
invoke_client('change_label', unicode(label_edit.text()))
def toggle_passphrase():
title = _("Confirm Toggle Passphrase Protection")
currently_enabled = self.features.passphrase_protection
if currently_enabled:
msg = _("After disabling passphrases, you can only pair this "
"Electrum wallet if it had an empty passphrase. "
"If its passphrase was not empty, you will need to "
"create a new wallet with the install wizard. You "
"can use this wallet again at any time by re-enabling "
"passphrases and entering its passphrase.")
else:
msg = _("Your current Electrum wallet can only be used with "
"an empty passphrase. You must create a separate "
"wallet with the install wizard for other passphrases "
"as each one generates a new set of addresses.")
msg += "\n\n" + _("Are you sure you want to proceed?")
if not self.question(msg, title=title):
return
invoke_client('toggle_passphrase', unpair_after=currently_enabled)
def change_homescreen():
from PIL import Image # FIXME
dialog = QFileDialog(self, _("Choose Homescreen"))
filename, __ = dialog.getOpenFileName()
if filename:
im = Image.open(str(filename))
if im.size != (hs_cols, hs_rows):
raise Exception('Image must be 64 x 128 pixels')
im = im.convert('1')
pix = im.load()
img = ''
for j in range(hs_rows):
for i in range(hs_cols):
img += '1' if pix[i, j] else '0'
img = ''.join(chr(int(img[i:i + 8], 2))
for i in range(0, len(img), 8))
invoke_client('change_homescreen', img)
def clear_homescreen():
invoke_client('change_homescreen', '\x00')
def set_pin():
invoke_client('set_pin', remove=False)
def clear_pin():
invoke_client('set_pin', remove=True)
def wipe_device():
wallet = window.wallet
if wallet and sum(wallet.get_balance()):
title = _("Confirm Device Wipe")
msg = _("Are you SURE you want to wipe the device?\n"
"Your wallet still has bitcoins in it!")
if not self.question(msg, title=title,
icon=QMessageBox.Critical):
return
invoke_client('wipe_device', unpair_after=True)
def slider_moved():
mins = timeout_slider.sliderPosition()
timeout_minutes.setText(_("%2d minutes") % mins)
def slider_released():
config.set_session_timeout(timeout_slider.sliderPosition() * 60)
# Information tab
info_tab = QWidget()
info_layout = QVBoxLayout(info_tab)
info_glayout = QGridLayout()
info_glayout.setColumnStretch(2, 1)
device_label = QLabel()
pin_set_label = QLabel()
passphrases_label = QLabel()
version_label = QLabel()
device_id_label = QLabel()
bl_hash_label = QLabel()
bl_hash_label.setWordWrap(True)
coins_label = QLabel()
coins_label.setWordWrap(True)
language_label = QLabel()
initialized_label = QLabel()
rows = [
(_("Device Label"), device_label),
(_("PIN set"), pin_set_label),
(_("Passphrases"), passphrases_label),
(_("Firmware Version"), version_label),
(_("Device ID"), device_id_label),
(_("Bootloader Hash"), bl_hash_label),
(_("Supported Coins"), coins_label),
(_("Language"), language_label),
(_("Initialized"), initialized_label),
]
for row_num, (label, widget) in enumerate(rows):
info_glayout.addWidget(QLabel(label), row_num, 0)
info_glayout.addWidget(widget, row_num, 1)
info_layout.addLayout(info_glayout)
# Settings tab
settings_tab = QWidget()
settings_layout = QVBoxLayout(settings_tab)
settings_glayout = QGridLayout()
# Settings tab - Label
label_msg = QLabel(_("Name this %s. If you have mutiple devices "
"their labels help distinguish them.")
% plugin.device)
label_msg.setWordWrap(True)
label_label = QLabel(_("Device Label"))
label_edit = QLineEdit()
label_edit.setMinimumWidth(150)
label_edit.setMaxLength(plugin.MAX_LABEL_LEN)
label_apply = QPushButton(_("Apply"))
label_apply.clicked.connect(rename)
label_edit.textChanged.connect(set_label_enabled)
settings_glayout.addWidget(label_label, 0, 0)
settings_glayout.addWidget(label_edit, 0, 1, 1, 2)
settings_glayout.addWidget(label_apply, 0, 3)
settings_glayout.addWidget(label_msg, 1, 1, 1, -1)
# Settings tab - PIN
pin_label = QLabel(_("PIN Protection"))
pin_button = QPushButton()
pin_button.clicked.connect(set_pin)
settings_glayout.addWidget(pin_label, 2, 0)
settings_glayout.addWidget(pin_button, 2, 1)
pin_msg = QLabel(_("PIN protection is strongly recommended. "
"A PIN is your only protection against someone "
"stealing your bitcoins if they obtain physical "
"access to your %s.") % plugin.device)
pin_msg.setWordWrap(True)
pin_msg.setStyleSheet("color: red")
settings_glayout.addWidget(pin_msg, 3, 1, 1, -1)
# Settings tab - Homescreen
if plugin.device != 'KeepKey': # Not yet supported by KK firmware
homescreen_layout = QHBoxLayout()
homescreen_label = QLabel(_("Homescreen"))
homescreen_change_button = QPushButton(_("Change..."))
homescreen_clear_button = QPushButton(_("Reset"))
homescreen_change_button.clicked.connect(change_homescreen)
homescreen_clear_button.clicked.connect(clear_homescreen)
homescreen_msg = QLabel(_("You can set the homescreen on your "
"device to personalize it. You must "
"choose a %d x %d monochrome black and "
"white image.") % (hs_rows, hs_cols))
homescreen_msg.setWordWrap(True)
settings_glayout.addWidget(homescreen_label, 4, 0)
settings_glayout.addWidget(homescreen_change_button, 4, 1)
settings_glayout.addWidget(homescreen_clear_button, 4, 2)
settings_glayout.addWidget(homescreen_msg, 5, 1, 1, -1)
# Settings tab - Session Timeout
timeout_label = QLabel(_("Session Timeout"))
timeout_minutes = QLabel()
timeout_slider = QSlider(Qt.Horizontal)
timeout_slider.setRange(1, 60)
timeout_slider.setSingleStep(1)
timeout_slider.setTickInterval(5)
timeout_slider.setTickPosition(QSlider.TicksBelow)
timeout_slider.setTracking(True)
timeout_msg = QLabel(
_("Clear the session after the specified period "
"of inactivity. Once a session has timed out, "
"your PIN and passphrase (if enabled) must be "
"re-entered to use the device."))
timeout_msg.setWordWrap(True)
timeout_slider.setSliderPosition(config.get_session_timeout() // 60)
slider_moved()
timeout_slider.valueChanged.connect(slider_moved)
timeout_slider.sliderReleased.connect(slider_released)
settings_glayout.addWidget(timeout_label, 6, 0)
settings_glayout.addWidget(timeout_slider, 6, 1, 1, 3)
settings_glayout.addWidget(timeout_minutes, 6, 4)
settings_glayout.addWidget(timeout_msg, 7, 1, 1, -1)
settings_layout.addLayout(settings_glayout)
settings_layout.addStretch(1)
# Advanced tab
advanced_tab = QWidget()
advanced_layout = QVBoxLayout(advanced_tab)
advanced_glayout = QGridLayout()
# Advanced tab - clear PIN
clear_pin_button = QPushButton(_("Disable PIN"))
clear_pin_button.clicked.connect(clear_pin)
clear_pin_warning = QLabel(
_("If you disable your PIN, anyone with physical access to your "
"%s device can spend your bitcoins.") % plugin.device)
clear_pin_warning.setWordWrap(True)
clear_pin_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(clear_pin_button, 0, 2)
advanced_glayout.addWidget(clear_pin_warning, 1, 0, 1, 5)
# Advanced tab - toggle passphrase protection
passphrase_button = QPushButton()
passphrase_button.clicked.connect(toggle_passphrase)
passphrase_msg = WWLabel(PASSPHRASE_HELP)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(passphrase_button, 3, 2)
advanced_glayout.addWidget(passphrase_msg, 4, 0, 1, 5)
advanced_glayout.addWidget(passphrase_warning, 5, 0, 1, 5)
# Advanced tab - wipe device
wipe_device_button = QPushButton(_("Wipe Device"))
wipe_device_button.clicked.connect(wipe_device)
wipe_device_msg = QLabel(
_("Wipe the device, removing all data from it. The firmware "
"is left unchanged."))
wipe_device_msg.setWordWrap(True)
wipe_device_warning = QLabel(
_("Only wipe a device if you have the recovery seed written down "
"and the device wallet(s) are empty, otherwise the bitcoins "
"will be lost forever."))
wipe_device_warning.setWordWrap(True)
wipe_device_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(wipe_device_button, 6, 2)
advanced_glayout.addWidget(wipe_device_msg, 7, 0, 1, 5)
advanced_glayout.addWidget(wipe_device_warning, 8, 0, 1, 5)
advanced_layout.addLayout(advanced_glayout)
advanced_layout.addStretch(1)
tabs = QTabWidget(self)
tabs.addTab(info_tab, _("Information"))
tabs.addTab(settings_tab, _("Settings"))
tabs.addTab(advanced_tab, _("Advanced"))
dialog_vbox = QVBoxLayout(self)
dialog_vbox.addWidget(tabs)
dialog_vbox.addLayout(Buttons(CloseButton(self)))
# Update information
invoke_client(None)
| {
"repo_name": "molecular/electrum",
"path": "plugins/trezor/qt_generic.py",
"copies": "1",
"size": "24608",
"license": "mit",
"hash": 7832214086116303000,
"line_mean": 40.779286927,
"line_max": 81,
"alpha_frac": 0.5900926528,
"autogenerated": false,
"ratio": 4.042049934296978,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00027967647537816074,
"num_lines": 589
} |
from functools import partial
import threading
from PyQt5.Qt import Qt
from PyQt5.Qt import QGridLayout, QInputDialog, QPushButton
from PyQt5.Qt import QVBoxLayout, QLabel
from electrum_gui.qt.util import *
from .plugin import TIM_NEW, TIM_RECOVER, TIM_MNEMONIC
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
from electrum.i18n import _
from electrum.plugins import hook, DeviceMgr
from electrum.util import PrintError, UserCancelled, bh2u
from electrum.wallet import Wallet, Standard_Wallet
PASSPHRASE_HELP_SHORT =_(
"Passphrases allow you to access new wallets, each "
"hidden behind a particular case-sensitive passphrase.")
PASSPHRASE_HELP = PASSPHRASE_HELP_SHORT + " " + _(
"You need to create a separate Electrum wallet for each passphrase "
"you use as they each generate different addresses. Changing "
"your passphrase does not lose other wallets, each is still "
"accessible behind its own passphrase.")
RECOMMEND_PIN = _(
"You should enable PIN protection. Your PIN is the only protection "
"for your bitcoins if your device is lost or stolen.")
PASSPHRASE_NOT_PIN = _(
"If you forget a passphrase you will be unable to access any "
"bitcoins in the wallet behind it. A passphrase is not a PIN. "
"Only change this if you are sure you understand it.")
CHARACTER_RECOVERY = (
"Use the recovery cipher shown on your device to input your seed words. "
"The cipher changes with every keypress.\n"
"After at most 4 letters the device will auto-complete a word.\n"
"Press SPACE or the Accept Word button to accept the device's auto-"
"completed word and advance to the next one.\n"
"Press BACKSPACE to go back a character or word.\n"
"Press ENTER or the Seed Entered button once the last word in your "
"seed is auto-completed.")
class CharacterButton(QPushButton):
def __init__(self, text=None):
QPushButton.__init__(self, text)
def keyPressEvent(self, event):
event.setAccepted(False) # Pass through Enter and Space keys
class CharacterDialog(WindowModalDialog):
def __init__(self, parent):
super(CharacterDialog, self).__init__(parent)
self.setWindowTitle(_("KeepKey Seed Recovery"))
self.character_pos = 0
self.word_pos = 0
self.loop = QEventLoop()
self.word_help = QLabel()
self.char_buttons = []
vbox = QVBoxLayout(self)
vbox.addWidget(WWLabel(CHARACTER_RECOVERY))
hbox = QHBoxLayout()
hbox.addWidget(self.word_help)
for i in range(4):
char_button = CharacterButton('*')
char_button.setMaximumWidth(36)
self.char_buttons.append(char_button)
hbox.addWidget(char_button)
self.accept_button = CharacterButton(_("Accept Word"))
self.accept_button.clicked.connect(partial(self.process_key, 32))
self.rejected.connect(partial(self.loop.exit, 1))
hbox.addWidget(self.accept_button)
hbox.addStretch(1)
vbox.addLayout(hbox)
self.finished_button = QPushButton(_("Seed Entered"))
self.cancel_button = QPushButton(_("Cancel"))
self.finished_button.clicked.connect(partial(self.process_key,
Qt.Key_Return))
self.cancel_button.clicked.connect(self.rejected)
buttons = Buttons(self.finished_button, self.cancel_button)
vbox.addSpacing(40)
vbox.addLayout(buttons)
self.refresh()
self.show()
def refresh(self):
self.word_help.setText("Enter seed word %2d:" % (self.word_pos + 1))
self.accept_button.setEnabled(self.character_pos >= 3)
self.finished_button.setEnabled((self.word_pos in (11, 17, 23)
and self.character_pos >= 3))
for n, button in enumerate(self.char_buttons):
button.setEnabled(n == self.character_pos)
if n == self.character_pos:
button.setFocus()
def is_valid_alpha_space(self, key):
# Auto-completion requires at least 3 characters
if key == ord(' ') and self.character_pos >= 3:
return True
# Firmware aborts protocol if the 5th character is non-space
if self.character_pos >= 4:
return False
return (key >= ord('a') and key <= ord('z')
or (key >= ord('A') and key <= ord('Z')))
def process_key(self, key):
self.data = None
if key == Qt.Key_Return and self.finished_button.isEnabled():
self.data = {'done': True}
elif key == Qt.Key_Backspace and (self.word_pos or self.character_pos):
self.data = {'delete': True}
elif self.is_valid_alpha_space(key):
self.data = {'character': chr(key).lower()}
if self.data:
self.loop.exit(0)
def keyPressEvent(self, event):
self.process_key(event.key())
if not self.data:
QDialog.keyPressEvent(self, event)
def get_char(self, word_pos, character_pos):
self.word_pos = word_pos
self.character_pos = character_pos
self.refresh()
if self.loop.exec_():
self.data = None # User cancelled
class QtHandler(QtHandlerBase):
char_signal = pyqtSignal(object)
pin_signal = pyqtSignal(object)
def __init__(self, win, pin_matrix_widget_class, device):
super(QtHandler, self).__init__(win, device)
self.char_signal.connect(self.update_character_dialog)
self.pin_signal.connect(self.pin_dialog)
self.pin_matrix_widget_class = pin_matrix_widget_class
self.character_dialog = None
def get_char(self, msg):
self.done.clear()
self.char_signal.emit(msg)
self.done.wait()
data = self.character_dialog.data
if not data or 'done' in data:
self.character_dialog.accept()
self.character_dialog = None
return data
def get_pin(self, msg):
self.done.clear()
self.pin_signal.emit(msg)
self.done.wait()
return self.response
def pin_dialog(self, msg):
# Needed e.g. when resetting a device
self.clear_dialog()
dialog = WindowModalDialog(self.top_level_window(), _("Enter PIN"))
matrix = self.pin_matrix_widget_class()
vbox = QVBoxLayout()
vbox.addWidget(QLabel(msg))
vbox.addWidget(matrix)
vbox.addLayout(Buttons(CancelButton(dialog), OkButton(dialog)))
dialog.setLayout(vbox)
dialog.exec_()
self.response = str(matrix.get_value())
self.done.set()
def update_character_dialog(self, msg):
if not self.character_dialog:
self.character_dialog = CharacterDialog(self.top_level_window())
self.character_dialog.get_char(msg.word_pos, msg.character_pos)
self.done.set()
class QtPlugin(QtPluginBase):
# Derived classes must provide the following class-static variables:
# icon_file
# pin_matrix_widget_class
def create_handler(self, window):
return QtHandler(window, self.pin_matrix_widget_class(), self.device)
@hook
def receive_menu(self, menu, addrs, wallet):
if type(wallet) is not Standard_Wallet:
return
keystore = wallet.get_keystore()
if type(keystore) == self.keystore_class and len(addrs) == 1:
def show_address():
keystore.thread.add(partial(self.show_address, wallet, addrs[0]))
menu.addAction(_("Show on %s") % self.device, show_address)
def show_settings_dialog(self, window, keystore):
device_id = self.choose_device(window, keystore)
if device_id:
SettingsDialog(window, self, keystore, device_id).exec_()
def request_trezor_init_settings(self, wizard, method, device):
vbox = QVBoxLayout()
next_enabled = True
label = QLabel(_("Enter a label to name your device:"))
name = QLineEdit()
hl = QHBoxLayout()
hl.addWidget(label)
hl.addWidget(name)
hl.addStretch(1)
vbox.addLayout(hl)
def clean_text(widget):
text = widget.toPlainText().strip()
return ' '.join(text.split())
if method in [TIM_NEW, TIM_RECOVER]:
gb = QGroupBox()
hbox1 = QHBoxLayout()
gb.setLayout(hbox1)
# KeepKey recovery doesn't need a word count
if method == TIM_NEW or self.device == 'TREZOR':
vbox.addWidget(gb)
gb.setTitle(_("Select your seed length:"))
bg = QButtonGroup()
for i, count in enumerate([12, 18, 24]):
rb = QRadioButton(gb)
rb.setText(_("%d words") % count)
bg.addButton(rb)
bg.setId(rb, i)
hbox1.addWidget(rb)
rb.setChecked(True)
cb_pin = QCheckBox(_('Enable PIN protection'))
cb_pin.setChecked(True)
else:
text = QTextEdit()
text.setMaximumHeight(60)
if method == TIM_MNEMONIC:
msg = _("Enter your BIP39 mnemonic:")
else:
msg = _("Enter the master private key beginning with xprv:")
def set_enabled():
from electrum.keystore import is_xprv
wizard.next_button.setEnabled(is_xprv(clean_text(text)))
text.textChanged.connect(set_enabled)
next_enabled = False
vbox.addWidget(QLabel(msg))
vbox.addWidget(text)
pin = QLineEdit()
pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,10}')))
pin.setMaximumWidth(100)
hbox_pin = QHBoxLayout()
hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):")))
hbox_pin.addWidget(pin)
hbox_pin.addStretch(1)
if method in [TIM_NEW, TIM_RECOVER]:
vbox.addWidget(WWLabel(RECOMMEND_PIN))
vbox.addWidget(cb_pin)
else:
vbox.addLayout(hbox_pin)
passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
cb_phrase = QCheckBox(_('Enable passphrases'))
cb_phrase.setChecked(False)
vbox.addWidget(passphrase_msg)
vbox.addWidget(passphrase_warning)
vbox.addWidget(cb_phrase)
wizard.exec_layout(vbox, next_enabled=next_enabled)
if method in [TIM_NEW, TIM_RECOVER]:
item = bg.checkedId()
pin = cb_pin.isChecked()
else:
item = ' '.join(str(clean_text(text)).split())
pin = str(pin.text())
return (item, name.text(), pin, cb_phrase.isChecked())
class SettingsDialog(WindowModalDialog):
'''This dialog doesn't require a device be paired with a wallet.
We want users to be able to wipe a device even if they've forgotten
their PIN.'''
def __init__(self, window, plugin, keystore, device_id):
title = _("%s Settings") % plugin.device
super(SettingsDialog, self).__init__(window, title)
self.setMaximumWidth(540)
devmgr = plugin.device_manager()
config = devmgr.config
handler = keystore.handler
thread = keystore.thread
hs_rows, hs_cols = (64, 128)
def invoke_client(method, *args, **kw_args):
unpair_after = kw_args.pop('unpair_after', False)
def task():
client = devmgr.client_by_id(device_id)
if not client:
raise RuntimeError("Device not connected")
if method:
getattr(client, method)(*args, **kw_args)
if unpair_after:
devmgr.unpair_id(device_id)
return client.features
thread.add(task, on_success=update)
def update(features):
self.features = features
set_label_enabled()
bl_hash = bh2u(features.bootloader_hash)
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
noyes = [_("No"), _("Yes")]
endis = [_("Enable Passphrases"), _("Disable Passphrases")]
disen = [_("Disabled"), _("Enabled")]
setchange = [_("Set a PIN"), _("Change PIN")]
version = "%d.%d.%d" % (features.major_version,
features.minor_version,
features.patch_version)
coins = ", ".join(coin.coin_name for coin in features.coins)
device_label.setText(features.label)
pin_set_label.setText(noyes[features.pin_protection])
passphrases_label.setText(disen[features.passphrase_protection])
bl_hash_label.setText(bl_hash)
label_edit.setText(features.label)
device_id_label.setText(features.device_id)
initialized_label.setText(noyes[features.initialized])
version_label.setText(version)
coins_label.setText(coins)
clear_pin_button.setVisible(features.pin_protection)
clear_pin_warning.setVisible(features.pin_protection)
pin_button.setText(setchange[features.pin_protection])
pin_msg.setVisible(not features.pin_protection)
passphrase_button.setText(endis[features.passphrase_protection])
language_label.setText(features.language)
def set_label_enabled():
label_apply.setEnabled(label_edit.text() != self.features.label)
def rename():
invoke_client('change_label', label_edit.text())
def toggle_passphrase():
title = _("Confirm Toggle Passphrase Protection")
currently_enabled = self.features.passphrase_protection
if currently_enabled:
msg = _("After disabling passphrases, you can only pair this "
"Electrum wallet if it had an empty passphrase. "
"If its passphrase was not empty, you will need to "
"create a new wallet with the install wizard. You "
"can use this wallet again at any time by re-enabling "
"passphrases and entering its passphrase.")
else:
msg = _("Your current Electrum wallet can only be used with "
"an empty passphrase. You must create a separate "
"wallet with the install wizard for other passphrases "
"as each one generates a new set of addresses.")
msg += "\n\n" + _("Are you sure you want to proceed?")
if not self.question(msg, title=title):
return
invoke_client('toggle_passphrase', unpair_after=currently_enabled)
def change_homescreen():
from PIL import Image # FIXME
dialog = QFileDialog(self, _("Choose Homescreen"))
filename, __ = dialog.getOpenFileName()
if filename:
im = Image.open(str(filename))
if im.size != (hs_cols, hs_rows):
raise Exception('Image must be 64 x 128 pixels')
im = im.convert('1')
pix = im.load()
img = ''
for j in range(hs_rows):
for i in range(hs_cols):
img += '1' if pix[i, j] else '0'
img = ''.join(chr(int(img[i:i + 8], 2))
for i in range(0, len(img), 8))
invoke_client('change_homescreen', img)
def clear_homescreen():
invoke_client('change_homescreen', '\x00')
def set_pin():
invoke_client('set_pin', remove=False)
def clear_pin():
invoke_client('set_pin', remove=True)
def wipe_device():
wallet = window.wallet
if wallet and sum(wallet.get_balance()):
title = _("Confirm Device Wipe")
msg = _("Are you SURE you want to wipe the device?\n"
"Your wallet still has bitcoins in it!")
if not self.question(msg, title=title,
icon=QMessageBox.Critical):
return
invoke_client('wipe_device', unpair_after=True)
def slider_moved():
mins = timeout_slider.sliderPosition()
timeout_minutes.setText(_("%2d minutes") % mins)
def slider_released():
config.set_session_timeout(timeout_slider.sliderPosition() * 60)
# Information tab
info_tab = QWidget()
info_layout = QVBoxLayout(info_tab)
info_glayout = QGridLayout()
info_glayout.setColumnStretch(2, 1)
device_label = QLabel()
pin_set_label = QLabel()
passphrases_label = QLabel()
version_label = QLabel()
device_id_label = QLabel()
bl_hash_label = QLabel()
bl_hash_label.setWordWrap(True)
coins_label = QLabel()
coins_label.setWordWrap(True)
language_label = QLabel()
initialized_label = QLabel()
rows = [
(_("Device Label"), device_label),
(_("PIN set"), pin_set_label),
(_("Passphrases"), passphrases_label),
(_("Firmware Version"), version_label),
(_("Device ID"), device_id_label),
(_("Bootloader Hash"), bl_hash_label),
(_("Supported Coins"), coins_label),
(_("Language"), language_label),
(_("Initialized"), initialized_label),
]
for row_num, (label, widget) in enumerate(rows):
info_glayout.addWidget(QLabel(label), row_num, 0)
info_glayout.addWidget(widget, row_num, 1)
info_layout.addLayout(info_glayout)
# Settings tab
settings_tab = QWidget()
settings_layout = QVBoxLayout(settings_tab)
settings_glayout = QGridLayout()
# Settings tab - Label
label_msg = QLabel(_("Name this %s. If you have mutiple devices "
"their labels help distinguish them.")
% plugin.device)
label_msg.setWordWrap(True)
label_label = QLabel(_("Device Label"))
label_edit = QLineEdit()
label_edit.setMinimumWidth(150)
label_edit.setMaxLength(plugin.MAX_LABEL_LEN)
label_apply = QPushButton(_("Apply"))
label_apply.clicked.connect(rename)
label_edit.textChanged.connect(set_label_enabled)
settings_glayout.addWidget(label_label, 0, 0)
settings_glayout.addWidget(label_edit, 0, 1, 1, 2)
settings_glayout.addWidget(label_apply, 0, 3)
settings_glayout.addWidget(label_msg, 1, 1, 1, -1)
# Settings tab - PIN
pin_label = QLabel(_("PIN Protection"))
pin_button = QPushButton()
pin_button.clicked.connect(set_pin)
settings_glayout.addWidget(pin_label, 2, 0)
settings_glayout.addWidget(pin_button, 2, 1)
pin_msg = QLabel(_("PIN protection is strongly recommended. "
"A PIN is your only protection against someone "
"stealing your bitcoins if they obtain physical "
"access to your %s.") % plugin.device)
pin_msg.setWordWrap(True)
pin_msg.setStyleSheet("color: red")
settings_glayout.addWidget(pin_msg, 3, 1, 1, -1)
# Settings tab - Homescreen
if plugin.device != 'KeepKey': # Not yet supported by KK firmware
homescreen_layout = QHBoxLayout()
homescreen_label = QLabel(_("Homescreen"))
homescreen_change_button = QPushButton(_("Change..."))
homescreen_clear_button = QPushButton(_("Reset"))
homescreen_change_button.clicked.connect(change_homescreen)
homescreen_clear_button.clicked.connect(clear_homescreen)
homescreen_msg = QLabel(_("You can set the homescreen on your "
"device to personalize it. You must "
"choose a %d x %d monochrome black and "
"white image.") % (hs_rows, hs_cols))
homescreen_msg.setWordWrap(True)
settings_glayout.addWidget(homescreen_label, 4, 0)
settings_glayout.addWidget(homescreen_change_button, 4, 1)
settings_glayout.addWidget(homescreen_clear_button, 4, 2)
settings_glayout.addWidget(homescreen_msg, 5, 1, 1, -1)
# Settings tab - Session Timeout
timeout_label = QLabel(_("Session Timeout"))
timeout_minutes = QLabel()
timeout_slider = QSlider(Qt.Horizontal)
timeout_slider.setRange(1, 60)
timeout_slider.setSingleStep(1)
timeout_slider.setTickInterval(5)
timeout_slider.setTickPosition(QSlider.TicksBelow)
timeout_slider.setTracking(True)
timeout_msg = QLabel(
_("Clear the session after the specified period "
"of inactivity. Once a session has timed out, "
"your PIN and passphrase (if enabled) must be "
"re-entered to use the device."))
timeout_msg.setWordWrap(True)
timeout_slider.setSliderPosition(config.get_session_timeout() // 60)
slider_moved()
timeout_slider.valueChanged.connect(slider_moved)
timeout_slider.sliderReleased.connect(slider_released)
settings_glayout.addWidget(timeout_label, 6, 0)
settings_glayout.addWidget(timeout_slider, 6, 1, 1, 3)
settings_glayout.addWidget(timeout_minutes, 6, 4)
settings_glayout.addWidget(timeout_msg, 7, 1, 1, -1)
settings_layout.addLayout(settings_glayout)
settings_layout.addStretch(1)
# Advanced tab
advanced_tab = QWidget()
advanced_layout = QVBoxLayout(advanced_tab)
advanced_glayout = QGridLayout()
# Advanced tab - clear PIN
clear_pin_button = QPushButton(_("Disable PIN"))
clear_pin_button.clicked.connect(clear_pin)
clear_pin_warning = QLabel(
_("If you disable your PIN, anyone with physical access to your "
"%s device can spend your bitcoins.") % plugin.device)
clear_pin_warning.setWordWrap(True)
clear_pin_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(clear_pin_button, 0, 2)
advanced_glayout.addWidget(clear_pin_warning, 1, 0, 1, 5)
# Advanced tab - toggle passphrase protection
passphrase_button = QPushButton()
passphrase_button.clicked.connect(toggle_passphrase)
passphrase_msg = WWLabel(PASSPHRASE_HELP)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(passphrase_button, 3, 2)
advanced_glayout.addWidget(passphrase_msg, 4, 0, 1, 5)
advanced_glayout.addWidget(passphrase_warning, 5, 0, 1, 5)
# Advanced tab - wipe device
wipe_device_button = QPushButton(_("Wipe Device"))
wipe_device_button.clicked.connect(wipe_device)
wipe_device_msg = QLabel(
_("Wipe the device, removing all data from it. The firmware "
"is left unchanged."))
wipe_device_msg.setWordWrap(True)
wipe_device_warning = QLabel(
_("Only wipe a device if you have the recovery seed written down "
"and the device wallet(s) are empty, otherwise the bitcoins "
"will be lost forever."))
wipe_device_warning.setWordWrap(True)
wipe_device_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(wipe_device_button, 6, 2)
advanced_glayout.addWidget(wipe_device_msg, 7, 0, 1, 5)
advanced_glayout.addWidget(wipe_device_warning, 8, 0, 1, 5)
advanced_layout.addLayout(advanced_glayout)
advanced_layout.addStretch(1)
tabs = QTabWidget(self)
tabs.addTab(info_tab, _("Information"))
tabs.addTab(settings_tab, _("Settings"))
tabs.addTab(advanced_tab, _("Advanced"))
dialog_vbox = QVBoxLayout(self)
dialog_vbox.addWidget(tabs)
dialog_vbox.addLayout(Buttons(CloseButton(self)))
# Update information
invoke_client(None)
| {
"repo_name": "digitalbitbox/electrum",
"path": "plugins/trezor/qt_generic.py",
"copies": "2",
"size": "24554",
"license": "mit",
"hash": -2981533721715824000,
"line_mean": 40.7585034014,
"line_max": 81,
"alpha_frac": 0.589516983,
"autogenerated": false,
"ratio": 4.037822726525243,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5627339709525243,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import threading
from PyQt5.Qt import Qt
from PyQt5.Qt import QGridLayout, QInputDialog, QPushButton
from PyQt5.Qt import QVBoxLayout, QLabel
from electrum.gui.qt.util import *
from electrum.i18n import _
from electrum.plugin import hook, DeviceMgr
from electrum.util import PrintError, UserCancelled, bh2u
from electrum.wallet import Wallet, Standard_Wallet
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
from ..hw_wallet.plugin import only_hook_if_libraries_available
from .keepkey import KeepKeyPlugin, TIM_NEW, TIM_RECOVER, TIM_MNEMONIC
PASSPHRASE_HELP_SHORT =_(
"Passphrases allow you to access new wallets, each "
"hidden behind a particular case-sensitive passphrase.")
PASSPHRASE_HELP = PASSPHRASE_HELP_SHORT + " " + _(
"You need to create a separate Electrum wallet for each passphrase "
"you use as they each generate different addresses. Changing "
"your passphrase does not lose other wallets, each is still "
"accessible behind its own passphrase.")
RECOMMEND_PIN = _(
"You should enable PIN protection. Your PIN is the only protection "
"for your bitcoins if your device is lost or stolen.")
PASSPHRASE_NOT_PIN = _(
"If you forget a passphrase you will be unable to access any "
"bitcoins in the wallet behind it. A passphrase is not a PIN. "
"Only change this if you are sure you understand it.")
CHARACTER_RECOVERY = (
"Use the recovery cipher shown on your device to input your seed words. "
"The cipher changes with every keypress.\n"
"After at most 4 letters the device will auto-complete a word.\n"
"Press SPACE or the Accept Word button to accept the device's auto-"
"completed word and advance to the next one.\n"
"Press BACKSPACE to go back a character or word.\n"
"Press ENTER or the Seed Entered button once the last word in your "
"seed is auto-completed.")
class CharacterButton(QPushButton):
def __init__(self, text=None):
QPushButton.__init__(self, text)
def keyPressEvent(self, event):
event.setAccepted(False) # Pass through Enter and Space keys
class CharacterDialog(WindowModalDialog):
def __init__(self, parent):
super(CharacterDialog, self).__init__(parent)
self.setWindowTitle(_("KeepKey Seed Recovery"))
self.character_pos = 0
self.word_pos = 0
self.loop = QEventLoop()
self.word_help = QLabel()
self.char_buttons = []
vbox = QVBoxLayout(self)
vbox.addWidget(WWLabel(CHARACTER_RECOVERY))
hbox = QHBoxLayout()
hbox.addWidget(self.word_help)
for i in range(4):
char_button = CharacterButton('*')
char_button.setMaximumWidth(36)
self.char_buttons.append(char_button)
hbox.addWidget(char_button)
self.accept_button = CharacterButton(_("Accept Word"))
self.accept_button.clicked.connect(partial(self.process_key, 32))
self.rejected.connect(partial(self.loop.exit, 1))
hbox.addWidget(self.accept_button)
hbox.addStretch(1)
vbox.addLayout(hbox)
self.finished_button = QPushButton(_("Seed Entered"))
self.cancel_button = QPushButton(_("Cancel"))
self.finished_button.clicked.connect(partial(self.process_key,
Qt.Key_Return))
self.cancel_button.clicked.connect(self.rejected)
buttons = Buttons(self.finished_button, self.cancel_button)
vbox.addSpacing(40)
vbox.addLayout(buttons)
self.refresh()
self.show()
def refresh(self):
self.word_help.setText("Enter seed word %2d:" % (self.word_pos + 1))
self.accept_button.setEnabled(self.character_pos >= 3)
self.finished_button.setEnabled((self.word_pos in (11, 17, 23)
and self.character_pos >= 3))
for n, button in enumerate(self.char_buttons):
button.setEnabled(n == self.character_pos)
if n == self.character_pos:
button.setFocus()
def is_valid_alpha_space(self, key):
# Auto-completion requires at least 3 characters
if key == ord(' ') and self.character_pos >= 3:
return True
# Firmware aborts protocol if the 5th character is non-space
if self.character_pos >= 4:
return False
return (key >= ord('a') and key <= ord('z')
or (key >= ord('A') and key <= ord('Z')))
def process_key(self, key):
self.data = None
if key == Qt.Key_Return and self.finished_button.isEnabled():
self.data = {'done': True}
elif key == Qt.Key_Backspace and (self.word_pos or self.character_pos):
self.data = {'delete': True}
elif self.is_valid_alpha_space(key):
self.data = {'character': chr(key).lower()}
if self.data:
self.loop.exit(0)
def keyPressEvent(self, event):
self.process_key(event.key())
if not self.data:
QDialog.keyPressEvent(self, event)
def get_char(self, word_pos, character_pos):
self.word_pos = word_pos
self.character_pos = character_pos
self.refresh()
if self.loop.exec_():
self.data = None # User cancelled
class QtHandler(QtHandlerBase):
char_signal = pyqtSignal(object)
pin_signal = pyqtSignal(object)
close_char_dialog_signal = pyqtSignal()
def __init__(self, win, pin_matrix_widget_class, device):
super(QtHandler, self).__init__(win, device)
self.char_signal.connect(self.update_character_dialog)
self.pin_signal.connect(self.pin_dialog)
self.close_char_dialog_signal.connect(self._close_char_dialog)
self.pin_matrix_widget_class = pin_matrix_widget_class
self.character_dialog = None
def get_char(self, msg):
self.done.clear()
self.char_signal.emit(msg)
self.done.wait()
data = self.character_dialog.data
if not data or 'done' in data:
self.close_char_dialog_signal.emit()
return data
def _close_char_dialog(self):
if self.character_dialog:
self.character_dialog.accept()
self.character_dialog = None
def get_pin(self, msg):
self.done.clear()
self.pin_signal.emit(msg)
self.done.wait()
return self.response
def pin_dialog(self, msg):
# Needed e.g. when resetting a device
self.clear_dialog()
dialog = WindowModalDialog(self.top_level_window(), _("Enter PIN"))
matrix = self.pin_matrix_widget_class()
vbox = QVBoxLayout()
vbox.addWidget(QLabel(msg))
vbox.addWidget(matrix)
vbox.addLayout(Buttons(CancelButton(dialog), OkButton(dialog)))
dialog.setLayout(vbox)
dialog.exec_()
self.response = str(matrix.get_value())
self.done.set()
def update_character_dialog(self, msg):
if not self.character_dialog:
self.character_dialog = CharacterDialog(self.top_level_window())
self.character_dialog.get_char(msg.word_pos, msg.character_pos)
self.done.set()
class QtPlugin(QtPluginBase):
# Derived classes must provide the following class-static variables:
# icon_file
# pin_matrix_widget_class
def create_handler(self, window):
return QtHandler(window, self.pin_matrix_widget_class(), self.device)
@only_hook_if_libraries_available
@hook
def receive_menu(self, menu, addrs, wallet):
if len(addrs) != 1:
return
for keystore in wallet.get_keystores():
if type(keystore) == self.keystore_class:
def show_address():
keystore.thread.add(partial(self.show_address, wallet, addrs[0], keystore))
device_name = "{} ({})".format(self.device, keystore.label)
menu.addAction(_("Show on {}").format(device_name), show_address)
def show_settings_dialog(self, window, keystore):
device_id = self.choose_device(window, keystore)
if device_id:
SettingsDialog(window, self, keystore, device_id).exec_()
def request_trezor_init_settings(self, wizard, method, device):
vbox = QVBoxLayout()
next_enabled = True
label = QLabel(_("Enter a label to name your device:"))
name = QLineEdit()
hl = QHBoxLayout()
hl.addWidget(label)
hl.addWidget(name)
hl.addStretch(1)
vbox.addLayout(hl)
def clean_text(widget):
text = widget.toPlainText().strip()
return ' '.join(text.split())
if method in [TIM_NEW, TIM_RECOVER]:
gb = QGroupBox()
hbox1 = QHBoxLayout()
gb.setLayout(hbox1)
# KeepKey recovery doesn't need a word count
if method == TIM_NEW:
vbox.addWidget(gb)
gb.setTitle(_("Select your seed length:"))
bg = QButtonGroup()
for i, count in enumerate([12, 18, 24]):
rb = QRadioButton(gb)
rb.setText(_("{} words").format(count))
bg.addButton(rb)
bg.setId(rb, i)
hbox1.addWidget(rb)
rb.setChecked(True)
cb_pin = QCheckBox(_('Enable PIN protection'))
cb_pin.setChecked(True)
else:
text = QTextEdit()
text.setMaximumHeight(60)
if method == TIM_MNEMONIC:
msg = _("Enter your BIP39 mnemonic:")
else:
msg = _("Enter the master private key beginning with xprv:")
def set_enabled():
from keystore import is_xprv
wizard.next_button.setEnabled(is_xprv(clean_text(text)))
text.textChanged.connect(set_enabled)
next_enabled = False
vbox.addWidget(QLabel(msg))
vbox.addWidget(text)
pin = QLineEdit()
pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,9}')))
pin.setMaximumWidth(100)
hbox_pin = QHBoxLayout()
hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):")))
hbox_pin.addWidget(pin)
hbox_pin.addStretch(1)
if method in [TIM_NEW, TIM_RECOVER]:
vbox.addWidget(WWLabel(RECOMMEND_PIN))
vbox.addWidget(cb_pin)
else:
vbox.addLayout(hbox_pin)
passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
cb_phrase = QCheckBox(_('Enable passphrases'))
cb_phrase.setChecked(False)
vbox.addWidget(passphrase_msg)
vbox.addWidget(passphrase_warning)
vbox.addWidget(cb_phrase)
wizard.exec_layout(vbox, next_enabled=next_enabled)
if method in [TIM_NEW, TIM_RECOVER]:
item = bg.checkedId()
pin = cb_pin.isChecked()
else:
item = ' '.join(str(clean_text(text)).split())
pin = str(pin.text())
return (item, name.text(), pin, cb_phrase.isChecked())
class Plugin(KeepKeyPlugin, QtPlugin):
icon_paired = ":icons/keepkey.png"
icon_unpaired = ":icons/keepkey_unpaired.png"
@classmethod
def pin_matrix_widget_class(self):
from keepkeylib.qt.pinmatrix import PinMatrixWidget
return PinMatrixWidget
class SettingsDialog(WindowModalDialog):
'''This dialog doesn't require a device be paired with a wallet.
We want users to be able to wipe a device even if they've forgotten
their PIN.'''
def __init__(self, window, plugin, keystore, device_id):
title = _("{} Settings").format(plugin.device)
super(SettingsDialog, self).__init__(window, title)
self.setMaximumWidth(540)
devmgr = plugin.device_manager()
config = devmgr.config
handler = keystore.handler
thread = keystore.thread
hs_rows, hs_cols = (64, 128)
def invoke_client(method, *args, **kw_args):
unpair_after = kw_args.pop('unpair_after', False)
def task():
client = devmgr.client_by_id(device_id)
if not client:
raise RuntimeError("Device not connected")
if method:
getattr(client, method)(*args, **kw_args)
if unpair_after:
devmgr.unpair_id(device_id)
return client.features
thread.add(task, on_success=update)
def update(features):
self.features = features
set_label_enabled()
bl_hash = bh2u(features.bootloader_hash)
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
noyes = [_("No"), _("Yes")]
endis = [_("Enable Passphrases"), _("Disable Passphrases")]
disen = [_("Disabled"), _("Enabled")]
setchange = [_("Set a PIN"), _("Change PIN")]
version = "%d.%d.%d" % (features.major_version,
features.minor_version,
features.patch_version)
coins = ", ".join(coin.coin_name for coin in features.coins)
device_label.setText(features.label)
pin_set_label.setText(noyes[features.pin_protection])
passphrases_label.setText(disen[features.passphrase_protection])
bl_hash_label.setText(bl_hash)
label_edit.setText(features.label)
device_id_label.setText(features.device_id)
initialized_label.setText(noyes[features.initialized])
version_label.setText(version)
coins_label.setText(coins)
clear_pin_button.setVisible(features.pin_protection)
clear_pin_warning.setVisible(features.pin_protection)
pin_button.setText(setchange[features.pin_protection])
pin_msg.setVisible(not features.pin_protection)
passphrase_button.setText(endis[features.passphrase_protection])
language_label.setText(features.language)
def set_label_enabled():
label_apply.setEnabled(label_edit.text() != self.features.label)
def rename():
invoke_client('change_label', label_edit.text())
def toggle_passphrase():
title = _("Confirm Toggle Passphrase Protection")
currently_enabled = self.features.passphrase_protection
if currently_enabled:
msg = _("After disabling passphrases, you can only pair this "
"Electrum wallet if it had an empty passphrase. "
"If its passphrase was not empty, you will need to "
"create a new wallet with the install wizard. You "
"can use this wallet again at any time by re-enabling "
"passphrases and entering its passphrase.")
else:
msg = _("Your current Electrum wallet can only be used with "
"an empty passphrase. You must create a separate "
"wallet with the install wizard for other passphrases "
"as each one generates a new set of addresses.")
msg += "\n\n" + _("Are you sure you want to proceed?")
if not self.question(msg, title=title):
return
invoke_client('toggle_passphrase', unpair_after=currently_enabled)
def change_homescreen():
from PIL import Image # FIXME
dialog = QFileDialog(self, _("Choose Homescreen"))
filename, __ = dialog.getOpenFileName()
if filename:
im = Image.open(str(filename))
if im.size != (hs_cols, hs_rows):
raise Exception('Image must be 64 x 128 pixels')
im = im.convert('1')
pix = im.load()
img = ''
for j in range(hs_rows):
for i in range(hs_cols):
img += '1' if pix[i, j] else '0'
img = ''.join(chr(int(img[i:i + 8], 2))
for i in range(0, len(img), 8))
invoke_client('change_homescreen', img)
def clear_homescreen():
invoke_client('change_homescreen', '\x00')
def set_pin():
invoke_client('set_pin', remove=False)
def clear_pin():
invoke_client('set_pin', remove=True)
def wipe_device():
wallet = window.wallet
if wallet and sum(wallet.get_balance()):
title = _("Confirm Device Wipe")
msg = _("Are you SURE you want to wipe the device?\n"
"Your wallet still has bitcoins in it!")
if not self.question(msg, title=title,
icon=QMessageBox.Critical):
return
invoke_client('wipe_device', unpair_after=True)
def slider_moved():
mins = timeout_slider.sliderPosition()
timeout_minutes.setText(_("%2d minutes") % mins)
def slider_released():
config.set_session_timeout(timeout_slider.sliderPosition() * 60)
# Information tab
info_tab = QWidget()
info_layout = QVBoxLayout(info_tab)
info_glayout = QGridLayout()
info_glayout.setColumnStretch(2, 1)
device_label = QLabel()
pin_set_label = QLabel()
passphrases_label = QLabel()
version_label = QLabel()
device_id_label = QLabel()
bl_hash_label = QLabel()
bl_hash_label.setWordWrap(True)
coins_label = QLabel()
coins_label.setWordWrap(True)
language_label = QLabel()
initialized_label = QLabel()
rows = [
(_("Device Label"), device_label),
(_("PIN set"), pin_set_label),
(_("Passphrases"), passphrases_label),
(_("Firmware Version"), version_label),
(_("Device ID"), device_id_label),
(_("Bootloader Hash"), bl_hash_label),
(_("Supported Coins"), coins_label),
(_("Language"), language_label),
(_("Initialized"), initialized_label),
]
for row_num, (label, widget) in enumerate(rows):
info_glayout.addWidget(QLabel(label), row_num, 0)
info_glayout.addWidget(widget, row_num, 1)
info_layout.addLayout(info_glayout)
# Settings tab
settings_tab = QWidget()
settings_layout = QVBoxLayout(settings_tab)
settings_glayout = QGridLayout()
# Settings tab - Label
label_msg = QLabel(_("Name this {}. If you have multiple devices "
"their labels help distinguish them.")
.format(plugin.device))
label_msg.setWordWrap(True)
label_label = QLabel(_("Device Label"))
label_edit = QLineEdit()
label_edit.setMinimumWidth(150)
label_edit.setMaxLength(plugin.MAX_LABEL_LEN)
label_apply = QPushButton(_("Apply"))
label_apply.clicked.connect(rename)
label_edit.textChanged.connect(set_label_enabled)
settings_glayout.addWidget(label_label, 0, 0)
settings_glayout.addWidget(label_edit, 0, 1, 1, 2)
settings_glayout.addWidget(label_apply, 0, 3)
settings_glayout.addWidget(label_msg, 1, 1, 1, -1)
# Settings tab - PIN
pin_label = QLabel(_("PIN Protection"))
pin_button = QPushButton()
pin_button.clicked.connect(set_pin)
settings_glayout.addWidget(pin_label, 2, 0)
settings_glayout.addWidget(pin_button, 2, 1)
pin_msg = QLabel(_("PIN protection is strongly recommended. "
"A PIN is your only protection against someone "
"stealing your bitcoins if they obtain physical "
"access to your {}.").format(plugin.device))
pin_msg.setWordWrap(True)
pin_msg.setStyleSheet("color: red")
settings_glayout.addWidget(pin_msg, 3, 1, 1, -1)
# Settings tab - Session Timeout
timeout_label = QLabel(_("Session Timeout"))
timeout_minutes = QLabel()
timeout_slider = QSlider(Qt.Horizontal)
timeout_slider.setRange(1, 60)
timeout_slider.setSingleStep(1)
timeout_slider.setTickInterval(5)
timeout_slider.setTickPosition(QSlider.TicksBelow)
timeout_slider.setTracking(True)
timeout_msg = QLabel(
_("Clear the session after the specified period "
"of inactivity. Once a session has timed out, "
"your PIN and passphrase (if enabled) must be "
"re-entered to use the device."))
timeout_msg.setWordWrap(True)
timeout_slider.setSliderPosition(config.get_session_timeout() // 60)
slider_moved()
timeout_slider.valueChanged.connect(slider_moved)
timeout_slider.sliderReleased.connect(slider_released)
settings_glayout.addWidget(timeout_label, 6, 0)
settings_glayout.addWidget(timeout_slider, 6, 1, 1, 3)
settings_glayout.addWidget(timeout_minutes, 6, 4)
settings_glayout.addWidget(timeout_msg, 7, 1, 1, -1)
settings_layout.addLayout(settings_glayout)
settings_layout.addStretch(1)
# Advanced tab
advanced_tab = QWidget()
advanced_layout = QVBoxLayout(advanced_tab)
advanced_glayout = QGridLayout()
# Advanced tab - clear PIN
clear_pin_button = QPushButton(_("Disable PIN"))
clear_pin_button.clicked.connect(clear_pin)
clear_pin_warning = QLabel(
_("If you disable your PIN, anyone with physical access to your "
"{} device can spend your bitcoins.").format(plugin.device))
clear_pin_warning.setWordWrap(True)
clear_pin_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(clear_pin_button, 0, 2)
advanced_glayout.addWidget(clear_pin_warning, 1, 0, 1, 5)
# Advanced tab - toggle passphrase protection
passphrase_button = QPushButton()
passphrase_button.clicked.connect(toggle_passphrase)
passphrase_msg = WWLabel(PASSPHRASE_HELP)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(passphrase_button, 3, 2)
advanced_glayout.addWidget(passphrase_msg, 4, 0, 1, 5)
advanced_glayout.addWidget(passphrase_warning, 5, 0, 1, 5)
# Advanced tab - wipe device
wipe_device_button = QPushButton(_("Wipe Device"))
wipe_device_button.clicked.connect(wipe_device)
wipe_device_msg = QLabel(
_("Wipe the device, removing all data from it. The firmware "
"is left unchanged."))
wipe_device_msg.setWordWrap(True)
wipe_device_warning = QLabel(
_("Only wipe a device if you have the recovery seed written down "
"and the device wallet(s) are empty, otherwise the bitcoins "
"will be lost forever."))
wipe_device_warning.setWordWrap(True)
wipe_device_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(wipe_device_button, 6, 2)
advanced_glayout.addWidget(wipe_device_msg, 7, 0, 1, 5)
advanced_glayout.addWidget(wipe_device_warning, 8, 0, 1, 5)
advanced_layout.addLayout(advanced_glayout)
advanced_layout.addStretch(1)
tabs = QTabWidget(self)
tabs.addTab(info_tab, _("Information"))
tabs.addTab(settings_tab, _("Settings"))
tabs.addTab(advanced_tab, _("Advanced"))
dialog_vbox = QVBoxLayout(self)
dialog_vbox.addWidget(tabs)
dialog_vbox.addLayout(Buttons(CloseButton(self)))
# Update information
invoke_client(None)
| {
"repo_name": "cryptapus/electrum",
"path": "electrum/plugins/keepkey/qt.py",
"copies": "1",
"size": "24142",
"license": "mit",
"hash": 4549107230460797000,
"line_mean": 39.9881154499,
"line_max": 95,
"alpha_frac": 0.592701516,
"autogenerated": false,
"ratio": 4.0263509006004,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.51190524166004,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import threading
from PyQt5.Qt import Qt
from PyQt5.Qt import QGridLayout, QInputDialog, QPushButton
from PyQt5.Qt import QVBoxLayout, QLabel
from electrum_gui.qt.util import *
from electrum.i18n import _
from electrum.plugins import hook, DeviceMgr
from electrum.util import PrintError, UserCancelled, bh2u
from electrum.wallet import Wallet, Standard_Wallet
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
from .keepkey import KeepKeyPlugin, TIM_NEW, TIM_RECOVER, TIM_MNEMONIC
PASSPHRASE_HELP_SHORT =_(
"Passphrases allow you to access new wallets, each "
"hidden behind a particular case-sensitive passphrase.")
PASSPHRASE_HELP = PASSPHRASE_HELP_SHORT + " " + _(
"You need to create a separate Electrum wallet for each passphrase "
"you use as they each generate different addresses. Changing "
"your passphrase does not lose other wallets, each is still "
"accessible behind its own passphrase.")
RECOMMEND_PIN = _(
"You should enable PIN protection. Your PIN is the only protection "
"for your bitcoins if your device is lost or stolen.")
PASSPHRASE_NOT_PIN = _(
"If you forget a passphrase you will be unable to access any "
"bitcoins in the wallet behind it. A passphrase is not a PIN. "
"Only change this if you are sure you understand it.")
CHARACTER_RECOVERY = (
"Use the recovery cipher shown on your device to input your seed words. "
"The cipher changes with every keypress.\n"
"After at most 4 letters the device will auto-complete a word.\n"
"Press SPACE or the Accept Word button to accept the device's auto-"
"completed word and advance to the next one.\n"
"Press BACKSPACE to go back a character or word.\n"
"Press ENTER or the Seed Entered button once the last word in your "
"seed is auto-completed.")
class CharacterButton(QPushButton):
def __init__(self, text=None):
QPushButton.__init__(self, text)
def keyPressEvent(self, event):
event.setAccepted(False) # Pass through Enter and Space keys
class CharacterDialog(WindowModalDialog):
def __init__(self, parent):
super(CharacterDialog, self).__init__(parent)
self.setWindowTitle(_("KeepKey Seed Recovery"))
self.character_pos = 0
self.word_pos = 0
self.loop = QEventLoop()
self.word_help = QLabel()
self.char_buttons = []
vbox = QVBoxLayout(self)
vbox.addWidget(WWLabel(CHARACTER_RECOVERY))
hbox = QHBoxLayout()
hbox.addWidget(self.word_help)
for i in range(4):
char_button = CharacterButton('*')
char_button.setMaximumWidth(36)
self.char_buttons.append(char_button)
hbox.addWidget(char_button)
self.accept_button = CharacterButton(_("Accept Word"))
self.accept_button.clicked.connect(partial(self.process_key, 32))
self.rejected.connect(partial(self.loop.exit, 1))
hbox.addWidget(self.accept_button)
hbox.addStretch(1)
vbox.addLayout(hbox)
self.finished_button = QPushButton(_("Seed Entered"))
self.cancel_button = QPushButton(_("Cancel"))
self.finished_button.clicked.connect(partial(self.process_key,
Qt.Key_Return))
self.cancel_button.clicked.connect(self.rejected)
buttons = Buttons(self.finished_button, self.cancel_button)
vbox.addSpacing(40)
vbox.addLayout(buttons)
self.refresh()
self.show()
def refresh(self):
self.word_help.setText("Enter seed word %2d:" % (self.word_pos + 1))
self.accept_button.setEnabled(self.character_pos >= 3)
self.finished_button.setEnabled((self.word_pos in (11, 17, 23)
and self.character_pos >= 3))
for n, button in enumerate(self.char_buttons):
button.setEnabled(n == self.character_pos)
if n == self.character_pos:
button.setFocus()
def is_valid_alpha_space(self, key):
# Auto-completion requires at least 3 characters
if key == ord(' ') and self.character_pos >= 3:
return True
# Firmware aborts protocol if the 5th character is non-space
if self.character_pos >= 4:
return False
return (key >= ord('a') and key <= ord('z')
or (key >= ord('A') and key <= ord('Z')))
def process_key(self, key):
self.data = None
if key == Qt.Key_Return and self.finished_button.isEnabled():
self.data = {'done': True}
elif key == Qt.Key_Backspace and (self.word_pos or self.character_pos):
self.data = {'delete': True}
elif self.is_valid_alpha_space(key):
self.data = {'character': chr(key).lower()}
if self.data:
self.loop.exit(0)
def keyPressEvent(self, event):
self.process_key(event.key())
if not self.data:
QDialog.keyPressEvent(self, event)
def get_char(self, word_pos, character_pos):
self.word_pos = word_pos
self.character_pos = character_pos
self.refresh()
if self.loop.exec_():
self.data = None # User cancelled
class QtHandler(QtHandlerBase):
char_signal = pyqtSignal(object)
pin_signal = pyqtSignal(object)
close_char_dialog_signal = pyqtSignal()
def __init__(self, win, pin_matrix_widget_class, device):
super(QtHandler, self).__init__(win, device)
self.char_signal.connect(self.update_character_dialog)
self.pin_signal.connect(self.pin_dialog)
self.close_char_dialog_signal.connect(self._close_char_dialog)
self.pin_matrix_widget_class = pin_matrix_widget_class
self.character_dialog = None
def get_char(self, msg):
self.done.clear()
self.char_signal.emit(msg)
self.done.wait()
data = self.character_dialog.data
if not data or 'done' in data:
self.close_char_dialog_signal.emit()
return data
def _close_char_dialog(self):
if self.character_dialog:
self.character_dialog.accept()
self.character_dialog = None
def get_pin(self, msg):
self.done.clear()
self.pin_signal.emit(msg)
self.done.wait()
return self.response
def pin_dialog(self, msg):
# Needed e.g. when resetting a device
self.clear_dialog()
dialog = WindowModalDialog(self.top_level_window(), _("Enter PIN"))
matrix = self.pin_matrix_widget_class()
vbox = QVBoxLayout()
vbox.addWidget(QLabel(msg))
vbox.addWidget(matrix)
vbox.addLayout(Buttons(CancelButton(dialog), OkButton(dialog)))
dialog.setLayout(vbox)
dialog.exec_()
self.response = str(matrix.get_value())
self.done.set()
def update_character_dialog(self, msg):
if not self.character_dialog:
self.character_dialog = CharacterDialog(self.top_level_window())
self.character_dialog.get_char(msg.word_pos, msg.character_pos)
self.done.set()
class QtPlugin(QtPluginBase):
# Derived classes must provide the following class-static variables:
# icon_file
# pin_matrix_widget_class
def create_handler(self, window):
return QtHandler(window, self.pin_matrix_widget_class(), self.device)
@hook
def receive_menu(self, menu, addrs, wallet):
if type(wallet) is not Standard_Wallet:
return
keystore = wallet.get_keystore()
if type(keystore) == self.keystore_class and len(addrs) == 1:
def show_address():
keystore.thread.add(partial(self.show_address, wallet, addrs[0]))
menu.addAction(_("Show on {}").format(self.device), show_address)
def show_settings_dialog(self, window, keystore):
device_id = self.choose_device(window, keystore)
if device_id:
SettingsDialog(window, self, keystore, device_id).exec_()
def request_trezor_init_settings(self, wizard, method, device):
vbox = QVBoxLayout()
next_enabled = True
label = QLabel(_("Enter a label to name your device:"))
name = QLineEdit()
hl = QHBoxLayout()
hl.addWidget(label)
hl.addWidget(name)
hl.addStretch(1)
vbox.addLayout(hl)
def clean_text(widget):
text = widget.toPlainText().strip()
return ' '.join(text.split())
if method in [TIM_NEW, TIM_RECOVER]:
gb = QGroupBox()
hbox1 = QHBoxLayout()
gb.setLayout(hbox1)
# KeepKey recovery doesn't need a word count
if method == TIM_NEW:
vbox.addWidget(gb)
gb.setTitle(_("Select your seed length:"))
bg = QButtonGroup()
for i, count in enumerate([12, 18, 24]):
rb = QRadioButton(gb)
rb.setText(_("{} words").format(count))
bg.addButton(rb)
bg.setId(rb, i)
hbox1.addWidget(rb)
rb.setChecked(True)
cb_pin = QCheckBox(_('Enable PIN protection'))
cb_pin.setChecked(True)
else:
text = QTextEdit()
text.setMaximumHeight(60)
if method == TIM_MNEMONIC:
msg = _("Enter your BIP39 mnemonic:")
else:
msg = _("Enter the master private key beginning with xprv:")
def set_enabled():
from electrum.keystore import is_xprv
wizard.next_button.setEnabled(is_xprv(clean_text(text)))
text.textChanged.connect(set_enabled)
next_enabled = False
vbox.addWidget(QLabel(msg))
vbox.addWidget(text)
pin = QLineEdit()
pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,9}')))
pin.setMaximumWidth(100)
hbox_pin = QHBoxLayout()
hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):")))
hbox_pin.addWidget(pin)
hbox_pin.addStretch(1)
if method in [TIM_NEW, TIM_RECOVER]:
vbox.addWidget(WWLabel(RECOMMEND_PIN))
vbox.addWidget(cb_pin)
else:
vbox.addLayout(hbox_pin)
passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
cb_phrase = QCheckBox(_('Enable passphrases'))
cb_phrase.setChecked(False)
vbox.addWidget(passphrase_msg)
vbox.addWidget(passphrase_warning)
vbox.addWidget(cb_phrase)
wizard.exec_layout(vbox, next_enabled=next_enabled)
if method in [TIM_NEW, TIM_RECOVER]:
item = bg.checkedId()
pin = cb_pin.isChecked()
else:
item = ' '.join(str(clean_text(text)).split())
pin = str(pin.text())
return (item, name.text(), pin, cb_phrase.isChecked())
class Plugin(KeepKeyPlugin, QtPlugin):
icon_paired = ":icons/keepkey.png"
icon_unpaired = ":icons/keepkey_unpaired.png"
@classmethod
def pin_matrix_widget_class(self):
from keepkeylib.qt.pinmatrix import PinMatrixWidget
return PinMatrixWidget
class SettingsDialog(WindowModalDialog):
'''This dialog doesn't require a device be paired with a wallet.
We want users to be able to wipe a device even if they've forgotten
their PIN.'''
def __init__(self, window, plugin, keystore, device_id):
title = _("{} Settings").format(plugin.device)
super(SettingsDialog, self).__init__(window, title)
self.setMaximumWidth(540)
devmgr = plugin.device_manager()
config = devmgr.config
handler = keystore.handler
thread = keystore.thread
hs_rows, hs_cols = (64, 128)
def invoke_client(method, *args, **kw_args):
unpair_after = kw_args.pop('unpair_after', False)
def task():
client = devmgr.client_by_id(device_id)
if not client:
raise RuntimeError("Device not connected")
if method:
getattr(client, method)(*args, **kw_args)
if unpair_after:
devmgr.unpair_id(device_id)
return client.features
thread.add(task, on_success=update)
def update(features):
self.features = features
set_label_enabled()
bl_hash = bh2u(features.bootloader_hash)
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
noyes = [_("No"), _("Yes")]
endis = [_("Enable Passphrases"), _("Disable Passphrases")]
disen = [_("Disabled"), _("Enabled")]
setchange = [_("Set a PIN"), _("Change PIN")]
version = "%d.%d.%d" % (features.major_version,
features.minor_version,
features.patch_version)
coins = ", ".join(coin.coin_name for coin in features.coins)
device_label.setText(features.label)
pin_set_label.setText(noyes[features.pin_protection])
passphrases_label.setText(disen[features.passphrase_protection])
bl_hash_label.setText(bl_hash)
label_edit.setText(features.label)
device_id_label.setText(features.device_id)
initialized_label.setText(noyes[features.initialized])
version_label.setText(version)
coins_label.setText(coins)
clear_pin_button.setVisible(features.pin_protection)
clear_pin_warning.setVisible(features.pin_protection)
pin_button.setText(setchange[features.pin_protection])
pin_msg.setVisible(not features.pin_protection)
passphrase_button.setText(endis[features.passphrase_protection])
language_label.setText(features.language)
def set_label_enabled():
label_apply.setEnabled(label_edit.text() != self.features.label)
def rename():
invoke_client('change_label', label_edit.text())
def toggle_passphrase():
title = _("Confirm Toggle Passphrase Protection")
currently_enabled = self.features.passphrase_protection
if currently_enabled:
msg = _("After disabling passphrases, you can only pair this "
"Electrum wallet if it had an empty passphrase. "
"If its passphrase was not empty, you will need to "
"create a new wallet with the install wizard. You "
"can use this wallet again at any time by re-enabling "
"passphrases and entering its passphrase.")
else:
msg = _("Your current Electrum wallet can only be used with "
"an empty passphrase. You must create a separate "
"wallet with the install wizard for other passphrases "
"as each one generates a new set of addresses.")
msg += "\n\n" + _("Are you sure you want to proceed?")
if not self.question(msg, title=title):
return
invoke_client('toggle_passphrase', unpair_after=currently_enabled)
def change_homescreen():
from PIL import Image # FIXME
dialog = QFileDialog(self, _("Choose Homescreen"))
filename, __ = dialog.getOpenFileName()
if filename:
im = Image.open(str(filename))
if im.size != (hs_cols, hs_rows):
raise Exception('Image must be 64 x 128 pixels')
im = im.convert('1')
pix = im.load()
img = ''
for j in range(hs_rows):
for i in range(hs_cols):
img += '1' if pix[i, j] else '0'
img = ''.join(chr(int(img[i:i + 8], 2))
for i in range(0, len(img), 8))
invoke_client('change_homescreen', img)
def clear_homescreen():
invoke_client('change_homescreen', '\x00')
def set_pin():
invoke_client('set_pin', remove=False)
def clear_pin():
invoke_client('set_pin', remove=True)
def wipe_device():
wallet = window.wallet
if wallet and sum(wallet.get_balance()):
title = _("Confirm Device Wipe")
msg = _("Are you SURE you want to wipe the device?\n"
"Your wallet still has bitcoins in it!")
if not self.question(msg, title=title,
icon=QMessageBox.Critical):
return
invoke_client('wipe_device', unpair_after=True)
def slider_moved():
mins = timeout_slider.sliderPosition()
timeout_minutes.setText(_("%2d minutes") % mins)
def slider_released():
config.set_session_timeout(timeout_slider.sliderPosition() * 60)
# Information tab
info_tab = QWidget()
info_layout = QVBoxLayout(info_tab)
info_glayout = QGridLayout()
info_glayout.setColumnStretch(2, 1)
device_label = QLabel()
pin_set_label = QLabel()
passphrases_label = QLabel()
version_label = QLabel()
device_id_label = QLabel()
bl_hash_label = QLabel()
bl_hash_label.setWordWrap(True)
coins_label = QLabel()
coins_label.setWordWrap(True)
language_label = QLabel()
initialized_label = QLabel()
rows = [
(_("Device Label"), device_label),
(_("PIN set"), pin_set_label),
(_("Passphrases"), passphrases_label),
(_("Firmware Version"), version_label),
(_("Device ID"), device_id_label),
(_("Bootloader Hash"), bl_hash_label),
(_("Supported Coins"), coins_label),
(_("Language"), language_label),
(_("Initialized"), initialized_label),
]
for row_num, (label, widget) in enumerate(rows):
info_glayout.addWidget(QLabel(label), row_num, 0)
info_glayout.addWidget(widget, row_num, 1)
info_layout.addLayout(info_glayout)
# Settings tab
settings_tab = QWidget()
settings_layout = QVBoxLayout(settings_tab)
settings_glayout = QGridLayout()
# Settings tab - Label
label_msg = QLabel(_("Name this {}. If you have multiple devices "
"their labels help distinguish them.")
.format(plugin.device))
label_msg.setWordWrap(True)
label_label = QLabel(_("Device Label"))
label_edit = QLineEdit()
label_edit.setMinimumWidth(150)
label_edit.setMaxLength(plugin.MAX_LABEL_LEN)
label_apply = QPushButton(_("Apply"))
label_apply.clicked.connect(rename)
label_edit.textChanged.connect(set_label_enabled)
settings_glayout.addWidget(label_label, 0, 0)
settings_glayout.addWidget(label_edit, 0, 1, 1, 2)
settings_glayout.addWidget(label_apply, 0, 3)
settings_glayout.addWidget(label_msg, 1, 1, 1, -1)
# Settings tab - PIN
pin_label = QLabel(_("PIN Protection"))
pin_button = QPushButton()
pin_button.clicked.connect(set_pin)
settings_glayout.addWidget(pin_label, 2, 0)
settings_glayout.addWidget(pin_button, 2, 1)
pin_msg = QLabel(_("PIN protection is strongly recommended. "
"A PIN is your only protection against someone "
"stealing your bitcoins if they obtain physical "
"access to your {}.").format(plugin.device))
pin_msg.setWordWrap(True)
pin_msg.setStyleSheet("color: red")
settings_glayout.addWidget(pin_msg, 3, 1, 1, -1)
# Settings tab - Session Timeout
timeout_label = QLabel(_("Session Timeout"))
timeout_minutes = QLabel()
timeout_slider = QSlider(Qt.Horizontal)
timeout_slider.setRange(1, 60)
timeout_slider.setSingleStep(1)
timeout_slider.setTickInterval(5)
timeout_slider.setTickPosition(QSlider.TicksBelow)
timeout_slider.setTracking(True)
timeout_msg = QLabel(
_("Clear the session after the specified period "
"of inactivity. Once a session has timed out, "
"your PIN and passphrase (if enabled) must be "
"re-entered to use the device."))
timeout_msg.setWordWrap(True)
timeout_slider.setSliderPosition(config.get_session_timeout() // 60)
slider_moved()
timeout_slider.valueChanged.connect(slider_moved)
timeout_slider.sliderReleased.connect(slider_released)
settings_glayout.addWidget(timeout_label, 6, 0)
settings_glayout.addWidget(timeout_slider, 6, 1, 1, 3)
settings_glayout.addWidget(timeout_minutes, 6, 4)
settings_glayout.addWidget(timeout_msg, 7, 1, 1, -1)
settings_layout.addLayout(settings_glayout)
settings_layout.addStretch(1)
# Advanced tab
advanced_tab = QWidget()
advanced_layout = QVBoxLayout(advanced_tab)
advanced_glayout = QGridLayout()
# Advanced tab - clear PIN
clear_pin_button = QPushButton(_("Disable PIN"))
clear_pin_button.clicked.connect(clear_pin)
clear_pin_warning = QLabel(
_("If you disable your PIN, anyone with physical access to your "
"{} device can spend your bitcoins.").format(plugin.device))
clear_pin_warning.setWordWrap(True)
clear_pin_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(clear_pin_button, 0, 2)
advanced_glayout.addWidget(clear_pin_warning, 1, 0, 1, 5)
# Advanced tab - toggle passphrase protection
passphrase_button = QPushButton()
passphrase_button.clicked.connect(toggle_passphrase)
passphrase_msg = WWLabel(PASSPHRASE_HELP)
passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
passphrase_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(passphrase_button, 3, 2)
advanced_glayout.addWidget(passphrase_msg, 4, 0, 1, 5)
advanced_glayout.addWidget(passphrase_warning, 5, 0, 1, 5)
# Advanced tab - wipe device
wipe_device_button = QPushButton(_("Wipe Device"))
wipe_device_button.clicked.connect(wipe_device)
wipe_device_msg = QLabel(
_("Wipe the device, removing all data from it. The firmware "
"is left unchanged."))
wipe_device_msg.setWordWrap(True)
wipe_device_warning = QLabel(
_("Only wipe a device if you have the recovery seed written down "
"and the device wallet(s) are empty, otherwise the bitcoins "
"will be lost forever."))
wipe_device_warning.setWordWrap(True)
wipe_device_warning.setStyleSheet("color: red")
advanced_glayout.addWidget(wipe_device_button, 6, 2)
advanced_glayout.addWidget(wipe_device_msg, 7, 0, 1, 5)
advanced_glayout.addWidget(wipe_device_warning, 8, 0, 1, 5)
advanced_layout.addLayout(advanced_glayout)
advanced_layout.addStretch(1)
tabs = QTabWidget(self)
tabs.addTab(info_tab, _("Information"))
tabs.addTab(settings_tab, _("Settings"))
tabs.addTab(advanced_tab, _("Advanced"))
dialog_vbox = QVBoxLayout(self)
dialog_vbox.addWidget(tabs)
dialog_vbox.addLayout(Buttons(CloseButton(self)))
# Update information
invoke_client(None)
| {
"repo_name": "kyuupichan/electrum",
"path": "plugins/keepkey/qt.py",
"copies": "1",
"size": "23981",
"license": "mit",
"hash": 1655156665676835800,
"line_mean": 39.9232081911,
"line_max": 81,
"alpha_frac": 0.5928443351,
"autogenerated": false,
"ratio": 4.022982721019963,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5115827056119963,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import tifffile as tiff
import numpy as np
import time
import math
import json
import sys
import os
MEM_LIMIT = 1000
MEGABYTE = 1024**2
def load_h(_size, _path, _start):
# Start timing now
start = time.time()
# Load a tile from a path
d = tiff.imread(_path)
# Get subvolume in d
y0, x0 = _start
y1, x1 = _start + _size
subvol = d[y0:y1, x0:x1]
# Return the time difference
return time.time() - start
def make_h(_bytes, _size, _path):
# Get number of bits
n_bits = 8 * _bytes
# Get the datatype, noise range, and size
dtype = getattr(np, 'uint{}'.format(n_bits))
slice_size = np.uint32(_size)
dmax = 2 ** n_bits
# Get keywords for random noise
noise_keys = dict(size= slice_size, dtype= dtype)
# Make a random uint array
a_tile = np.random.randint(dmax, **noise_keys)
# Write tile to volume
tiff.imsave(_path, a_tile)
class Manager():
def __init__(self, _dir, _names):
self._dir = _dir
# Add the output dir to all the names
join_dir = partial(os.path.join, _dir)
self._names = list(map(join_dir, _names))
def make_all(self, _count, _shape):
#####
# Make all the folder's files
#####
# Take some random file names
f_names = self._names[:_count]
del self._names[:_count]
# Make files for all file names
for f_n in f_names:
# Write the full file
make_h(voxel_bytes, _shape, f_n)
# Return file names
return f_names
@staticmethod
def load_all(_fsize, _tsize, _files):
# Get the tile offsets in every source file
t_offs = np.where(np.ones(_fsize / _tsize))
offsets = _tsize * np.uint32(t_offs).T
# Track the total time
timed = 0
# Load all files
for f_n in _files:
# Load all for this file name
load_fn = partial(load_h, _tsize, f_n)
# Add the time to load one file
timed += sum(map(load_fn, offsets))
# Return time to load all files
return timed
def rm_all(self):
# Remove all files in directory
for _name in self._names:
if os.path.exists(_name):
try:
os.remove(_name)
except OSError:
print("""
Could not remove {}
""".format(_name))
sys.stdout.flush()
def trial(self, f_c, f_s, t_s):
# Remove all files
self.rm_all()
# Make all the folder's files
f_names = self.make_all(f_c, f_s)
# Load all the folder's files
timed = self.load_all(f_s, t_s, f_names)
# Return trial time
return timed
if __name__ == '__main__':
# Get the global array index
trial_id = 0
if len(sys.argv) > 1:
trial_id = int(sys.argv[1])
# Get the size of the volume
full_scale = 14
if len(sys.argv) > 2:
full_scale = int(sys.argv[2])
# Get the minimum tile and file size
min_tile_scale = 9
min_file_scale = 9
# Get the number of bytes per voxel
voxel_bytes = 1
if len(sys.argv) > 3:
voxel_bytes = int(sys.argv[3])
# Output files go to the graph dir
graph_fmt = '/n/coxfs01/thejohnhoffer/2017/butterfly/scripts/h5_tile_test/results/{}'
exp = os.getenv('H5_EXPERIMENT', time.strftime('%Y_%m_%d'))
graph_dir = graph_fmt.format(exp)
# Make the working directory
if not os.path.exists(graph_dir):
try:
os.makedirs(graph_dir)
except OSError:
pass
# Temp files go to the noise_dir
noise_fmt = '/n/coxfs01/thejohnhoffer/h5_noise/{}/{}'
noise_dir = noise_fmt.format(exp, trial_id)
# Make the temporary directory
if not os.path.exists(noise_dir):
try:
os.makedirs(noise_dir)
except OSError:
pass
# Set the full shape
full_width = 2 ** full_scale
full_shape = np.uint32([full_width, full_width])
print("full shape {}".format(full_shape))
# Get the range of scales
tile_scales = range(min_tile_scale, full_scale+1)
#tile_scales = range(10, 12)
file_scales = range(min_file_scale, full_scale+1)
# Set the tile sizes and file sizes
tile_sizes = np.uint32([(2**i,)*2 for i in tile_scales])
file_sizes = np.uint32([(2**i,)*2 for i in file_scales])
# Get the number of files
file_counts = np.prod(full_shape / file_sizes, 1)
print """
tile sizes:
{}
file sizes:
{}
file counts: {}
""".format(tile_sizes, file_sizes, file_counts)
# Get the total mebibytes
full_bytes = voxel_bytes * np.prod(full_shape)
full_mb = int(full_bytes / MEGABYTE)
# Get the file / tile indexes for the array id
id_shape = [len(file_sizes), len(tile_sizes)]
id_range = range(np.prod(id_shape))
# record times for all trials
trial_times = np.zeros(id_shape)
trial_rates = np.zeros(id_shape)
# Random list of file names
total_files = np.sum(file_counts) * id_shape[1]
chosen = np.random.choice(10**9, int(total_files))
file_names = map('noise_{:09d}.tiff'.format, chosen)
# Loop through all combinations of tile and file shapes
for f_id, t_id in zip(*np.unravel_index(id_range, id_shape)):
# Get the file size, file count, and tile size
t_s = tile_sizes[t_id]
f_s = file_sizes[f_id]
f_c = file_counts[f_id]
# Continue if tile size > file size
if np.any(t_s > f_s):
msg = """***********************
Cannot load files of {}px in {}px blocks
""".format(f_s, t_s)
print(msg)
continue
# Get all the needed file names
f_names = map(file_names.pop, range(f_c)[::-1])
# Manage output directory and file names
mgmt = Manager(noise_dir, f_names)
# Get the time to load the shape
trial_time = mgmt.trial(f_c, f_s, t_s)
trial_rate = -1
if trial_time:
trial_rate = full_mb / trial_time
# Add the time to the output
trial_times[f_id, t_id] = trial_time
trial_rates[f_id, t_id] = trial_rate
msg = """***********************
Loaded all {} files of {}px
in blocks of {}px at {:.1f}Mbps
""".format(f_c, f_s, t_s, trial_rate)
print(msg)
sys.stdout.flush()
# Give feedback
graph_data = {
'n_files': file_counts.tolist(),
'tile_shape': tile_sizes.tolist(),
'file_shape': file_sizes.tolist(),
'full_shape': full_shape.tolist(),
'seconds': trial_times.tolist(),
'mbps': trial_rates.tolist(),
}
# The file for the graph
graph_file = '{:04d}.json'.format(trial_id)
graph_file = os.path.join(graph_dir, graph_file)
# Write the model to json
with open(graph_file, 'w') as fd:
json.dump(graph_data, fd, indent=4)
| {
"repo_name": "Rhoana/butterfly",
"path": "scripts/h5_tile_test/record_data.py",
"copies": "1",
"size": "7027",
"license": "mit",
"hash": -8009274051708467000,
"line_mean": 29.2887931034,
"line_max": 89,
"alpha_frac": 0.5602675395,
"autogenerated": false,
"ratio": 3.3783653846153845,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.942578710987936,
"avg_score": 0.0025691628472047606,
"num_lines": 232
} |
from functools import partial
import time
from qcodes.instrument.base import Instrument
from qcodes.utils import validators as vals
from qcodes.instrument.parameter import ManualParameter
class ConversionBoxControl(Instrument):
"""
This is a meta-instrument for controlling the different switches in the
conversion box designed in the QuDev lab. This class implements the control
over
* 2 amplifiers, whose input port can be chosen between the fridge and a
reference signal
* 5 up-conversion mixers, that can be operated in modulation or mixer-
bypass mode
* a switchboard that can route the input signal to one of the 6 output
ports
The switchboard is controlled using an Advantech PCIE-1751 digital I/O card.
This meta-instrument takes full control of the underlying DIO card which
should not be modified by other classes.
"""
shared_kwargs = ['dio']
def __init__(self, name, dio, switch_time=50e-3, **kw):
"""
:param name: name of the instrument
:param dio: reference to an Advantech PCIE-1751 instrument
:param switch_time: duration of the pulse to set the switch
configuration
"""
super().__init__(name, **kw)
self.dio = dio
# configure all DIO ports for output
for i in range(self.dio.port_count()):
self.dio.set('port{}_dir'.format(i), 0xff)
self._switch_state = {
'UC1': 'modulated',
'UC2': 'modulated',
'UC3': 'modulated',
'UC4': 'modulated',
'UC5': 'modulated',
'WA1': 'measure',
'WA2': 'measure',
'switch': 'block',
}
UCkey = ['']*6
for i in range(1, 6):
descr = 'switch configuration of up-conversion board {}'
UCkey[i] = 'UC{}'.format(i)
self.add_parameter(
'{}_mode'.format(UCkey[i]),
label=descr.format(i),
vals=vals.Enum('modulated', 'bypass'),
get_cmd=partial(self._switch_state.get, UCkey[i]),
set_cmd=lambda x: self.set_switch({UCkey[i]: x})
)
WAkey = ['']*3
for i in range(1, 3):
descr = 'switch configuration of warm amplifier {}'
WAkey[i] = 'WA{}'.format(i)
self.add_parameter(
'{}_mode'.format(WAkey[i]),
label=descr.format(i),
vals=vals.Enum('reference', 'measure'),
get_cmd=partial(self._switch_state.get, WAkey[i]),
set_cmd=lambda x: self.set_switch({WAkey[i]: x})
)
self.add_parameter(
'switch_mode',
label='switchboard configuration',
vals=vals.Enum('block', 1, 2, 3, 4, 5, 6),
get_cmd=partial(self._switch_state.get, 'switch'),
set_cmd=lambda x: self.set_switch({'switch': x})
)
self.add_parameter('switch_time', unit='s', vals=vals.Numbers(0, 1),
label='Duration of the switching pulse',
parameter_class=ManualParameter,
initial_value=switch_time)
def set_switch(self, values):
"""
:param values: a dictionary of key: value pairs, where key is one of
the following: 'UC#', 'WA#' or 'switch' (# denotes the
board number) and value is the mode to set the switch to.
"""
#logging.debug(values)
for key in values:
self.parameters['{}_mode'.format(key)].validate(values[key])
self._switch_state.update(values)
data = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
data[0] += self._WA_bitpattern(self._switch_state['WA2']) << 0
data[0] += self._WA_bitpattern(self._switch_state['WA1']) << 2
data[1] += self._UC_bitpattern(self._switch_state['UC1']) << 0
data[1] += self._UC_bitpattern(self._switch_state['UC2']) << 2
data[1] += self._UC_bitpattern(self._switch_state['UC3']) << 4
data[1] += self._UC_bitpattern(self._switch_state['UC4']) << 6
data[2] += self._UC_bitpattern(self._switch_state['UC5']) << 0
data[5] = self._switch_bitpattern(self._switch_state['switch'])
self.dio.write_port(0, data)
time.sleep(self.switch_time())
self.dio.write_port(0, [0, 0, 0, 0, 0, 0])
for key in values:
self.parameters['{}_mode'.format(key)]._save_val(values[key])
@classmethod
def _WA_bitpattern(cls, mode):
if mode == 'reference':
return 0b01
elif mode == 'measure':
return 0b10
else:
raise ValueError('Trying to set warm amplifier board switch to '
'invalid mode: {}'.format(mode))
@classmethod
def _UC_bitpattern(cls, mode):
if mode == 'bypass':
return 0b01
elif mode == 'modulated':
return 0b10
else:
raise ValueError('Trying to set up-conversion board switch to '
'invalid mode: {}'.format(mode))
@classmethod
def _switch_bitpattern(cls, mode):
if mode == 'block':
return 0b10000000
elif mode in range(1,7):
return 1 << (7-mode)
else:
raise ValueError('Trying to set the switchboard to invalid mode: '
'{}'.format(mode))
| {
"repo_name": "DiCarloLab-Delft/PycQED_py3",
"path": "pycqed/instrument_drivers/meta_instrument/conversion_box_control.py",
"copies": "1",
"size": "5535",
"license": "mit",
"hash": 6102038624557630000,
"line_mean": 37.4375,
"line_max": 80,
"alpha_frac": 0.5439927733,
"autogenerated": false,
"ratio": 3.911660777385159,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.995262395162808,
"avg_score": 0.0006059198114156298,
"num_lines": 144
} |
from functools import partial
import time
from typing import List
from flask import Blueprint, Response, render_template, current_app, request
from core.job.helpers import expand_nodelist
from core.job.models import Job
from application.helpers import requires_auth
from core.monitoring.models import SENSOR_CLASS_MAP
from modules.job_table.helpers import get_color
job_analyzer_pages = Blueprint('job_analyzer', __name__
, template_folder='templates/', static_folder='static')
def assign_job_class(data: dict) -> str:
try:
if int(data["stats"]["cpu"]["avg"]) < 10 and float(data["stats"]["la"]["avg"]) < 0.9:
return "hanged"
else:
return "ok"
except TypeError:
return "no_data"
def get_running_stats(interval: int) -> List[dict]:
jobs = Job.query.filter(Job.state.in_(current_app.app_config.cluster["ACTIVE_JOB_STATES"])).all()
results = []
timestamp = int(time.time())
offset = current_app.app_config.monitoring["aggregation_interval"]
for job in jobs:
data = {
"stats" : {"cpu": {"avg": -1}, "la": {"avg": -1}}
, "job" : job.to_dict() # TODO: ???
}
results.append(data)
if timestamp - job.t_start < interval:
data["class"] = "recent"
continue
if timestamp > job.t_end < interval:
data["class"] = "outdated"
continue
data["stats"]["cpu"] = SENSOR_CLASS_MAP["cpu_user"].get_stats(job.expanded_nodelist, timestamp - interval + offset, timestamp)
data["stats"]["la"] = SENSOR_CLASS_MAP["loadavg"].get_stats(job.expanded_nodelist, timestamp - interval + offset, timestamp)
data["class"] = assign_job_class(data)
return results
@job_analyzer_pages.route("/running")
@requires_auth
def running_stats() -> Response:
interval = int(request.args.get("interval", 60*60)) # last hour by default
return render_template("running.html"
, stats=get_running_stats(interval)
, app_config=current_app.app_config
, get_color=partial(get_color, thresholds=current_app.app_config.monitoring["thresholds"]))
| {
"repo_name": "srcc-msu/job_statistics",
"path": "modules/job_analyzer/controllers.py",
"copies": "1",
"size": "1969",
"license": "mit",
"hash": 8255856397457564000,
"line_mean": 28.8333333333,
"line_max": 128,
"alpha_frac": 0.6978161503,
"autogenerated": false,
"ratio": 3.186084142394822,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4383900292694822,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import time
from unittest.mock import patch
import sublime
from unittesting import DeferrableTestCase
def run_in_worker(fn, *args, **kwargs):
sublime.set_timeout_async(partial(fn, *args, **kwargs))
# When we swap `set_timeout_async` with `set_timeout` we basically run
# our program single-threaded.
# This has some benefits:
# - We avoid async/timing issues
# - We can use plain `yield` to run Sublime's task queue empty, see below
# - Every code we run will get correct coverage
#
# However note, that Sublime will just put all async events on the queue,
# avoiding the API. We cannot patch that. That means, the event handlers
# will *not* run using plain `yield` like below, you still have to await
# them using `yield AWAIT_WORKER`.
#
class TestTimingInDeferredTestCase(DeferrableTestCase):
def test_a(self):
# `patch` doesn't work as a decorator with generator functions so we
# use `with`
with patch.object(sublime, 'set_timeout_async', sublime.set_timeout):
messages = []
def work(message, worktime=None):
# simulate that a task might take some time
# this will not yield back but block
if worktime:
time.sleep(worktime)
messages.append(message)
def uut():
run_in_worker(work, 1, 0.5) # add task (A)
run_in_worker(work, 2) # add task (B)
uut() # after that task queue has: (A)..(B)
yield # add task (C) and wait for (C)
expected = [1, 2]
self.assertEqual(messages, expected)
def test_b(self):
# `patch` doesn't work as a decorator with generator functions so we
# use `with`
with patch.object(sublime, 'set_timeout_async', sublime.set_timeout):
messages = []
def work(message, worktime=None):
if worktime:
time.sleep(worktime)
messages.append(message)
def sub_task():
run_in_worker(work, 2, 0.5) # add task (D)
def uut():
run_in_worker(work, 1, 0.3) # add task (A)
run_in_worker(sub_task) # add task (B)
uut()
# task queue now: (A)..(B)
yield # add task (C) and wait for (C)
# (A) runs, (B) runs and adds task (D), (C) resolves
expected = [1]
self.assertEqual(messages, expected)
# task queue now: (D)
yield # add task (E) and wait for it
# (D) runs and (E) resolves
expected = [1, 2]
self.assertEqual(messages, expected)
| {
"repo_name": "randy3k/UnitTesting",
"path": "tests/test_deferred_timing.py",
"copies": "1",
"size": "2756",
"license": "mit",
"hash": -2150001579764637000,
"line_mean": 33.024691358,
"line_max": 77,
"alpha_frac": 0.5660377358,
"autogenerated": false,
"ratio": 3.8491620111731844,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49151997469731845,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import time
from unittest.runner import TextTestRunner, registerResult
import warnings
import sublime
def defer(delay, callback, *args, **kwargs):
# Rely on late binding in case a user patches it
sublime.set_timeout(partial(callback, *args, **kwargs), delay)
DEFAULT_CONDITION_POLL_TIME = 17
DEFAULT_CONDITION_TIMEOUT = 4000
AWAIT_WORKER = 'AWAIT_WORKER'
# Extract `set_timeout_async`, t.i. *avoid* late binding, in case a user
# patches it
run_on_worker = sublime.set_timeout_async
class DeferringTextTestRunner(TextTestRunner):
"""This test runner runs tests in deferred slices."""
def run(self, test):
"""Run the given test case or test suite."""
self.finished = False
result = self._makeResult()
registerResult(result)
result.failfast = self.failfast
result.buffer = self.buffer
startTime = time.time()
def _start_testing():
with warnings.catch_warnings():
if self.warnings:
# if self.warnings is set, use it to filter all the warnings
warnings.simplefilter(self.warnings)
# if the filter is 'default' or 'always', special-case the
# warnings from the deprecated unittest methods to show them
# no more than once per module, because they can be fairly
# noisy. The -Wd and -Wa flags can be used to bypass this
# only when self.warnings is None.
if self.warnings in ['default', 'always']:
warnings.filterwarnings(
'module',
category=DeprecationWarning,
message='Please use assert\\w+ instead.')
startTestRun = getattr(result, 'startTestRun', None)
if startTestRun is not None:
startTestRun()
try:
deferred = test(result)
_continue_testing(deferred)
except Exception as e:
_handle_error(e)
def _continue_testing(deferred, send_value=None, throw_value=None):
try:
if throw_value:
condition = deferred.throw(throw_value)
else:
condition = deferred.send(send_value)
if callable(condition):
defer(0, _wait_condition, deferred, condition)
elif isinstance(condition, dict) and "condition" in condition and \
callable(condition["condition"]):
period = condition.get("period", DEFAULT_CONDITION_POLL_TIME)
defer(period, _wait_condition, deferred, **condition)
elif isinstance(condition, int):
defer(condition, _continue_testing, deferred)
elif condition == AWAIT_WORKER:
run_on_worker(
partial(defer, 0, _continue_testing, deferred)
)
else:
defer(0, _continue_testing, deferred)
except StopIteration:
_stop_testing()
self.finished = True
except Exception as e:
_handle_error(e)
def _wait_condition(
deferred, condition,
period=DEFAULT_CONDITION_POLL_TIME,
timeout=DEFAULT_CONDITION_TIMEOUT,
start_time=None
):
if start_time is None:
start_time = time.time()
try:
send_value = condition()
except Exception as e:
_continue_testing(deferred, throw_value=e)
return
if send_value:
_continue_testing(deferred, send_value=send_value)
elif (time.time() - start_time) * 1000 >= timeout:
error = TimeoutError(
'Condition not fulfilled within {:.2f} seconds'
.format(timeout / 1000)
)
_continue_testing(deferred, throw_value=error)
else:
defer(period, _wait_condition, deferred, condition, period, timeout, start_time)
def _handle_error(e):
stopTestRun = getattr(result, 'stopTestRun', None)
if stopTestRun is not None:
stopTestRun()
self.finished = True
raise e
def _stop_testing():
with warnings.catch_warnings():
stopTestRun = getattr(result, 'stopTestRun', None)
if stopTestRun is not None:
stopTestRun()
stopTime = time.time()
timeTaken = stopTime - startTime
result.printErrors()
if hasattr(result, 'separator2'):
self.stream.writeln(result.separator2)
run = result.testsRun
self.stream.writeln("Ran %d test%s in %.3fs" %
(run, run != 1 and "s" or "", timeTaken))
self.stream.writeln()
expectedFails = unexpectedSuccesses = skipped = 0
try:
results = map(len, (result.expectedFailures,
result.unexpectedSuccesses,
result.skipped))
except AttributeError:
pass
else:
expectedFails, unexpectedSuccesses, skipped = results
infos = []
if not result.wasSuccessful():
self.stream.write("FAILED")
failed, errored = len(result.failures), len(result.errors)
if failed:
infos.append("failures=%d" % failed)
if errored:
infos.append("errors=%d" % errored)
else:
self.stream.write("OK")
if skipped:
infos.append("skipped=%d" % skipped)
if expectedFails:
infos.append("expected failures=%d" % expectedFails)
if unexpectedSuccesses:
infos.append("unexpected successes=%d" % unexpectedSuccesses)
if infos:
self.stream.writeln(" (%s)" % (", ".join(infos),))
else:
self.stream.write("\n")
_start_testing()
| {
"repo_name": "randy3k/UnitTesting",
"path": "unittesting/core/st3/runner.py",
"copies": "1",
"size": "6450",
"license": "mit",
"hash": 8832128914815190000,
"line_mean": 37.622754491,
"line_max": 96,
"alpha_frac": 0.5190697674,
"autogenerated": false,
"ratio": 4.942528735632184,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00035389533072567803,
"num_lines": 167
} |
from functools import partial
import time
import logging
import os.path
from copy import copy
import os
try:
from pathlib2 import Path
except ImportError:
from pathlib import Path
from multiprocess import Pool, Manager
import yaml
from tqdm import tqdm
from yass.util import function_path, human_readable_time
from yass.batch import util
from yass.batch.generator import IndexGenerator
from yass.batch.reader import RecordingsReader
class BatchProcessor(object):
"""
Batch processing for large numpy matrices
Parameters
----------
path_to_recordings: str
Path to recordings file
dtype: str
Numpy dtype
n_channels: int
Number of channels
data_order: str
Recordings order, one of ('channels', 'samples'). In a dataset with k
observations per channel and j channels: 'channels' means first k
contiguous observations come from channel 0, then channel 1, and so
on. 'sample' means first j contiguous data are the first observations
from all channels, then the second observations from all channels and
so on
max_memory: int or str
Max memory to use in each batch, interpreted as bytes if int,
if string, it can be any of {N}KB, {N}MB or {N}GB
buffer_size: int, optional
Buffer size, defaults to 0. Only relevant when performing multi-channel
operations
loader: str ('memmap', 'array' or 'python'), optional
How to load the data. memmap loads the data using a wrapper around
np.memmap (see :class:`~yass.batch.MemoryMap` for details), 'array'
using numpy.fromfile and 'python' loads it using a wrapper
around Python file API. Defaults to 'python'. Beware that the Python
loader has limited indexing capabilities, see
:class:`~yass.batch.BinaryReader` for details
show_progress_bar: bool, optional
Show progress bar when running operations, defaults to True
Raises
------
ValueError
If dimensions do not match according to the file size, dtype and
number of channels
"""
def __init__(self, path_to_recordings, dtype=None, n_channels=None,
data_order=None, max_memory='1GB', buffer_size=0,
loader='memmap', show_progress_bar=True):
self.data_order = data_order
self.buffer_size = buffer_size
self.path_to_recordings = path_to_recordings
self.dtype = dtype
self.n_channels = n_channels
self.data_order = data_order
self.loader = loader
self.show_progress_bar = show_progress_bar
self.reader = RecordingsReader(self.path_to_recordings,
self.dtype, self.n_channels,
self.data_order,
loader=self.loader,
buffer_size=buffer_size,
return_data_index=True)
self.indexer = IndexGenerator(self.reader.observations,
self.reader.channels,
self.reader.dtype,
max_memory)
self.logger = logging.getLogger(__name__)
def single_channel(self, force_complete_channel_batch=True, from_time=None,
to_time=None, channels='all'):
"""
Generate batches where each index has observations from a single
channel
Returns
-------
A generator that yields batches, if force_complete_channel_batch is
False, each generated value is a tuple with the batch and the
channel for the index for the corresponding channel
Examples
--------
.. literalinclude:: ../../examples/batch/single_channel.py
"""
indexes = self.indexer.single_channel(force_complete_channel_batch,
from_time, to_time,
channels)
if force_complete_channel_batch:
for idx in indexes:
subset, _ = self.reader[idx]
yield subset
else:
for idx in indexes:
channel_idx = idx[1]
subset, _ = self.reader[idx]
yield subset, channel_idx
def multi_channel(self, from_time=None, to_time=None, channels='all',
return_data=True):
"""
Generate indexes where each index has observations from more than
one channel
Returns
-------
generator:
A tuple of size three: the first element is the subset of the data
for the ith batch, second element is the slice object with the
limits of the data in [observations, channels] format (excluding
the buffer), the last element is the absolute index of the data
again in [observations, channels] format
Examples
--------
.. literalinclude:: ../../examples/batch/multi_channel.py
"""
indexes = self.indexer.multi_channel(from_time, to_time, channels)
for idx in indexes:
if return_data:
subset, _ = self.reader[idx]
yield subset
else:
yield idx
def single_channel_apply(self, function, mode, output_path=None,
force_complete_channel_batch=True,
from_time=None, to_time=None, channels='all',
if_file_exists='overwrite', cast_dtype=None,
**kwargs):
"""
Apply a transformation where each batch has observations from a
single channel
Parameters
----------
function: callable
Function to be applied, must accept a 1D numpy array as its first
parameter
mode: str
'disk' or 'memory', if 'disk', a binary file is created at the
beginning of the operation and each partial result is saved
(ussing numpy.ndarray.tofile function), at the end of the
operation two files are generated: the binary file and a yaml
file with some file parameters (useful if you want to later use
RecordingsReader to read the file). If 'memory', partial results
are kept in memory and returned as a list
output_path: str, optional
Where to save the output, required if 'disk' mode
force_complete_channel_batch: bool, optional
If True, every index generated will correspond to all the
observations in a single channel, hence
n_batches = n_selected_channels, defaults to True. If True
from_time and to_time must be None
from_time: int, optional
Starting time, defaults to None
to_time: int, optional
Ending time, defaults to None
channels: int, tuple or str, optional
A tuple with the channel indexes or 'all' to traverse all channels,
defaults to 'all'
if_file_exists: str, optional
One of 'overwrite', 'abort', 'skip'. If 'overwrite' it replaces the
file if it exists, if 'abort' if raise a ValueError exception if
the file exists, if 'skip' if skips the operation if the file
exists. Only valid when mode = 'disk'
cast_dtype: str, optional
Output dtype, defaults to None which means no cast is done
**kwargs
kwargs to pass to function
Examples
--------
.. literalinclude:: ../../examples/batch/single_channel_apply.py
Notes
-----
When applying functions in 'disk' mode will incur in memory overhead,
which depends on the function implementation, this is an important
thing to consider if the transformation changes the data's dtype (e.g.
converts int16 to float64), which means that a chunk of 1MB in int16
will have a size of 4MB in float64. Take that into account when
setting max_memory.
For performance reasons in 'disk' mode, output data is in 'channels'
order
"""
if mode not in ['disk', 'memory']:
raise ValueError('Mode should be disk or memory, received: {}'
.format(mode))
if mode == 'disk' and output_path is None:
raise ValueError('output_path is required in "disk" mode')
if (mode == 'disk' and if_file_exists == 'abort' and
os.path.exists(output_path)):
raise ValueError('{} already exists'.format(output_path))
if (mode == 'disk' and if_file_exists == 'skip' and
os.path.exists(output_path)):
# load params...
path_to_yaml = output_path.replace('.bin', '.yaml')
if not os.path.exists(path_to_yaml):
raise ValueError("if_file_exists = 'skip', but {}"
" is missing, aborting..."
.format(path_to_yaml))
with open(path_to_yaml) as f:
params = yaml.load(f)
self.logger.info('{} exists, skiping...'.format(output_path))
return output_path, params
self.logger.info('Applying function {}...'
.format(function_path(function)))
if mode == 'disk':
fn = self._single_channel_apply_disk
start = time.time()
res = fn(function, output_path,
force_complete_channel_batch, from_time,
to_time, channels, cast_dtype, **kwargs)
elapsed = time.time() - start
self.logger.info('{} took {}'
.format(function_path(function),
human_readable_time(elapsed)))
return res
else:
fn = self._single_channel_apply_memory
start = time.time()
res = fn(function, force_complete_channel_batch, from_time,
to_time, channels, cast_dtype, **kwargs)
elapsed = time.time() - start
self.logger.info('{} took {}'
.format(function_path(function),
human_readable_time(elapsed)))
return res
def _single_channel_apply_disk(self, function, output_path,
force_complete_channel_batch, from_time,
to_time, channels, cast_dtype, **kwargs):
f = open(output_path, 'wb')
indexes = self.indexer.single_channel(force_complete_channel_batch,
from_time, to_time,
channels)
indexes = list(indexes)
iterator = enumerate(indexes)
if self.show_progress_bar:
iterator = tqdm(iterator, total=len(indexes))
for i, idx in iterator:
self.logger.debug('Processing channel {}...'.format(i))
self.logger.debug('Reading batch...')
subset, _ = self.reader[idx]
self.logger.debug('Executing function...')
if cast_dtype is None:
res = function(subset, **kwargs)
else:
res = function(subset, **kwargs).astype(cast_dtype)
self.logger.debug('Writing to disk...')
res.tofile(f)
f.close()
params = util.make_metadata(channels, self.n_channels, str(res.dtype),
output_path)
return output_path, params
def _single_channel_apply_memory(self, function,
force_complete_channel_batch, from_time,
to_time, channels, cast_dtype, **kwargs):
indexes = self.indexer.single_channel(force_complete_channel_batch,
from_time, to_time,
channels)
indexes = list(indexes)
iterator = enumerate(indexes)
if self.show_progress_bar:
iterator = tqdm(iterator, total=len(indexes))
results = []
for i, idx in iterator:
self.logger.debug('Processing channel {}...'.format(i))
self.logger.debug('Reading batch...')
subset, _ = self.reader[idx]
if cast_dtype is None:
res = function(subset, **kwargs)
else:
res = function(subset, **kwargs).astype(cast_dtype)
self.logger.debug('Appending partial result...')
results.append(res)
return results
def multi_channel_apply(self, function, mode, cleanup_function=None,
output_path=None, from_time=None, to_time=None,
channels='all', if_file_exists='overwrite',
cast_dtype=None, pass_batch_info=False,
pass_batch_results=False, processes=1,
**kwargs):
"""
Apply a function where each batch has observations from more than
one channel
Parameters
----------
function: callable
Function to be applied, first parameter passed will be a 2D numpy
array in 'long' shape (number of observations, number of
channels). If pass_batch_info is True, another two keyword
parameters will be passed to function: 'idx_local' is the slice
object with the limits of the data in [observations, channels]
format (excluding the buffer), 'idx' is the absolute index of
the data again in [observations, channels] format
mode: str
'disk' or 'memory', if 'disk', a binary file is created at the
beginning of the operation and each partial result is saved
(ussing numpy.ndarray.tofile function), at the end of the
operation two files are generated: the binary file and a yaml
file with some file parameters (useful if you want to later use
RecordingsReader to read the file). If 'memory', partial results
are kept in memory and returned as a list
cleanup_function: callable, optional
A function to be executed after `function` and before adding the
partial result to the list of results (if `memory` mode) or to the
biinary file (if in `disk mode`). `cleanup_function` will be called
with the following parameters (in that order): result from applying
`function` to the batch, slice object with the idx where the data
is located (exludes buffer), slice object with the absolute
location of the data and buffer size
output_path: str, optional
Where to save the output, required if 'disk' mode
force_complete_channel_batch: bool, optional
If True, every index generated will correspond to all the
observations in a single channel, hence
n_batches = n_selected_channels, defaults to True. If True
from_time and to_time must be None
from_time: int, optional
Starting time, defaults to None
to_time: int, optional
Ending time, defaults to None
channels: int, tuple or str, optional
A tuple with the channel indexes or 'all' to traverse all channels,
defaults to 'all'
if_file_exists: str, optional
One of 'overwrite', 'abort', 'skip'. If 'overwrite' it replaces the
file if it exists, if 'abort' if raise a ValueError exception if
the file exists, if 'skip' if skips the operation if the file
exists. Only valid when mode = 'disk'
cast_dtype: str, optional
Output dtype, defaults to None which means no cast is done
pass_batch_info: bool, optional
Whether to call the function with batch info or just call it with
the batch data (see description in the function) parameter
pass_batch_results: bool, optional
Whether to pass results from the previous batch to the next one,
defaults to False. Only relevant when mode='memory'. If True,
function will be called with the keyword parameter
'previous_batch' which contains the computation for the last
batch, it is set to None in the first batch
**kwargs
kwargs to pass to function
Returns
-------
output_path, params (when mode is 'disk')
Path to output binary file, Binary file params
list (when mode is 'memory' and pass_batch_results is False)
List where every element is the result of applying the function
to one batch. When pass_batch_results is True, it returns the
output of the function for the last batch
Examples
--------
.. literalinclude:: ../../examples/batch/multi_channel_apply_disk.py
.. literalinclude:: ../../examples/batch/multi_channel_apply_memory.py
Notes
-----
Applying functions will incur in memory overhead, which depends
on the function implementation, this is an important thing to consider
if the transformation changes the data's dtype (e.g. converts int16 to
float64), which means that a chunk of 1MB in int16 will have a size
of 4MB in float64. Take that into account when setting max_memory
For performance reasons, outputs data in 'samples' order.
"""
if mode not in ['disk', 'memory']:
raise ValueError('Mode should be disk or memory, received: {}'
.format(mode))
if mode == 'disk' and output_path is None:
raise ValueError('output_path is required in "disk" mode')
if (mode == 'disk' and if_file_exists == 'abort' and
os.path.exists(output_path)):
raise ValueError('{} already exists'.format(output_path))
self.logger.info('Applying function {}...'
.format(function_path(function)))
if (mode == 'disk' and if_file_exists == 'skip' and
os.path.exists(output_path)):
# load params...
path_to_yaml = output_path.replace('.bin', '.yaml')
if not os.path.exists(path_to_yaml):
raise ValueError("if_file_exists = 'skip', but {}"
" is missing, aborting..."
.format(path_to_yaml))
with open(path_to_yaml) as f:
params = yaml.load(f)
self.logger.info('{} exists, skiping...'.format(output_path))
return output_path, params
if mode == 'disk':
if processes == 1:
fn = self._multi_channel_apply_disk
else:
fn = partial(self._multi_channel_apply_disk_parallel,
processes=processes)
start = time.time()
res = fn(function, cleanup_function, output_path, from_time,
to_time, channels, cast_dtype, pass_batch_info,
pass_batch_results, **kwargs)
elapsed = time.time() - start
self.logger.info('{} took {}'
.format(function_path(function),
human_readable_time(elapsed)))
return res
else:
fn = self._multi_channel_apply_memory
start = time.time()
res = fn(function, cleanup_function, from_time, to_time, channels,
cast_dtype, pass_batch_info, pass_batch_results,
**kwargs)
elapsed = time.time() - start
self.logger.info('{} took {}'
.format(function_path(function),
human_readable_time(elapsed)))
return res
def _multi_channel_apply_disk(self, function, cleanup_function,
output_path, from_time, to_time, channels,
cast_dtype, pass_batch_info,
pass_batch_results, **kwargs):
if pass_batch_results:
raise NotImplementedError("pass_batch_results is not "
"implemented on 'disk' mode")
f = open(output_path, 'wb')
output_path = Path(output_path)
data = self.multi_channel(from_time, to_time, channels,
return_data=False)
n_batches = self.indexer.n_batches(from_time, to_time, channels)
iterator = enumerate(data)
if self.show_progress_bar:
iterator = tqdm(iterator, total=n_batches)
for i, idx in iterator:
res = util.batch_runner((i, idx), function, self.reader,
pass_batch_info, cast_dtype,
kwargs, cleanup_function, self.buffer_size,
save_chunks=False)
res.tofile(f)
f.close()
params = util.make_metadata(channels, self.n_channels, str(res.dtype),
output_path)
return output_path, params
def _multi_channel_apply_disk_parallel(self, function, cleanup_function,
output_path, from_time, to_time,
channels, cast_dtype,
pass_batch_info,
pass_batch_results,
processes, **kwargs):
self.logger.debug('Starting parallel operation...')
if pass_batch_results:
raise NotImplementedError("pass_batch_results is not "
"implemented on 'disk' mode")
# need to convert to a list, oherwise cannot be pickled
data = list(self.multi_channel(from_time, to_time, channels,
return_data=False))
n_batches = self.indexer.n_batches(from_time, to_time, channels)
self.logger.info('Data will be splitted in %s batches', n_batches)
output_path = Path(output_path)
# create local variables to avoid pickling problems
_path_to_recordings = copy(self.path_to_recordings)
_dtype = copy(self.dtype)
_n_channels = copy(self.n_channels)
_data_order = copy(self.data_order)
_loader = copy(self.loader)
_buffer_size = copy(self.buffer_size)
reader = partial(RecordingsReader,
path_to_recordings=_path_to_recordings,
dtype=_dtype,
n_channels=_n_channels,
data_order=_data_order,
loader=_loader,
return_data_index=True)
m = Manager()
mapping = m.dict()
next_to_write = m.Value('i', 0)
def parallel_runner(element):
i, _ = element
res = util.batch_runner(element, function, reader,
pass_batch_info, cast_dtype,
kwargs, cleanup_function, _buffer_size,
save_chunks=False, output_path=output_path)
if i == 0:
mapping['dtype'] = str(res.dtype)
while True:
if next_to_write.value == i:
with open(str(output_path), 'wb' if i == 0 else 'ab') as f:
res.tofile(f)
next_to_write.value += 1
break
# run jobs
self.logger.debug('Creating processes pool...')
p = Pool(processes)
res = p.map_async(parallel_runner, enumerate(data))
finished = 0
if self.show_progress_bar:
pbar = tqdm(total=n_batches)
if self.show_progress_bar:
while True:
if next_to_write.value > finished:
update = next_to_write.value - finished
pbar.update(update)
finished = next_to_write.value
if next_to_write.value == n_batches:
break
pbar.close()
else:
res.get()
# save metadata
params = util.make_metadata(channels, self.n_channels,
mapping['dtype'], output_path)
return output_path, params
def _multi_channel_apply_memory(self, function, cleanup_function,
from_time, to_time, channels, cast_dtype,
pass_batch_info, pass_batch_results,
**kwargs):
data = self.multi_channel(from_time, to_time, channels,
return_data=False)
n_batches = self.indexer.n_batches(from_time, to_time, channels)
results = []
if pass_batch_results:
kwargs['previous_batch'] = None
iterator = enumerate(data)
if self.show_progress_bar:
iterator = tqdm(iterator, total=n_batches)
for i, idx in iterator:
res = util.batch_runner((i, idx), function, self.reader,
pass_batch_info, cast_dtype,
kwargs, cleanup_function, self.buffer_size,
save_chunks=False)
if pass_batch_results:
kwargs['previous_batch'] = res
else:
results.append(res)
return res if pass_batch_results else results
| {
"repo_name": "paninski-lab/yass",
"path": "src/yass/batch/batch.py",
"copies": "1",
"size": "26157",
"license": "apache-2.0",
"hash": 2856288330723249700,
"line_mean": 38.2747747748,
"line_max": 79,
"alpha_frac": 0.5440226326,
"autogenerated": false,
"ratio": 4.76448087431694,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.580850350691694,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import time
import timeit
import numpy as np
from math import sqrt, sin
import librosa
from os import listdir, getcwd
from os.path import isfile, join, dirname, abspath
def dft(arr):
arr = np.asarray(arr, dtype=float)
length = arr.shape[0]
n = np.arange(length)
k = n.reshape(length, 1)
M = np.exp(-2j * np.pi * k * n / length)
return np.dot(M, arr)
def fft(sampled_arr):
arr = np.asarray(sampled_arr, dtype=float)
length = arr.shape[0]
if length % 2 > 0:
raise ValueError('Length of array must be a power of 2.')
elif length <= 16:
return dft(arr)
else:
arr_even = fft(arr[::2])
arr_odd = fft(arr[1::2])
constant_factor = np.exp(-2j * np.pi * np.arange(length)/length)
return np.concatenate([arr_even + constant_factor[:length / 2] * arr_odd, arr_even + constant_factor[length / 2:] * arr_odd])
def function_timer(test_func, test_data):
return min(timeit.Timer(partial(test_func, test_arr)).repeat(repeat=3, number=5))
def euclidean_distance(arr1, arr2):
distance_squared = 0
for index, x in enumerate(arr1):
distance_squared += (x - arr2[index])**2
return sqrt(distance_squared)
cache = {}
def extract_magnitudes(number, path):
def memoize(number, path):
if (number, path) in cache:
return cache[(number, path)]
else:
cache[(number, path)] = extract_mags(number, path)
return cache[(number, path)]
def extract_samples(filepath):
return librosa.load(filepath, sr=32000, offset=60.0, duration=60.0)
def extract_mags(number, path):
arr, sample_rate = extract_samples(path + '/' + str(number) + '.mp3')
scale = max((abs(min(arr)), abs(max(arr))))
arr = 2*arr/scale
arr = arr.reshape(-1, 1024)
ffts = [np.fft.fft(x) for x in arr]
return [abs(x)[:512:] for x in ffts]
return memoize(number, path)
def get_medians(number_songs, genre):
magnitudes = []
medians = []
for x in xrange(1, number_songs):
magnitudes += extract_magnitudes(x, genre)
for i in xrange(512):
medians.append(np.median([magnitude[i] for magnitude in magnitudes]))
return medians
def get_medians_for_song(song, genre):
magnitudes = []
medians = []
magnitudes += extract_magnitudes(song, genre)
for i in xrange(512):
medians.append(np.median([magnitude[i] for magnitude in magnitudes]))
return medians
def rescale_medians(medians):
rescaled = []
i = 0
while len(rescaled) < 8:
rescaled.append(sum(medians[i:i+64]))
i += 64
scale_factor = 10000/max(rescaled)
rescaled = [int(scale_factor*x) for x in rescaled]
# rescaled = medians
return rescaled
classical = getcwd() + '/classicalmusic'
pop = getcwd() + '/popmusic'
def classify(number, genre):
test_genre = extract_magnitudes(number, genre)
pop_distance = []
classical_distance = []
print("getting medians")
pop_medians = get_medians(30, pop)
classical_medians = get_medians(30, classical)
print("Done getting medians")
print("euclidean_distance")
for test_magnitude in test_genre:
pop_distance.append(euclidean_distance(test_magnitude, pop_medians))
classical_distance.append(euclidean_distance(test_magnitude, classical_medians))
print("Done distance")
if np.median(pop_distance) > np.median(classical_distance):
return "Classical"
else:
return "Pop"
# z = rescale_medians(get_medians(4, classical))
def test_acc(number, genre):
classical_factors = [10000, 1866, 585, 345, 242, 189, 159, 145]
pop_factors = [10000, 2973, 1782, 1386, 1135, 931, 614, 394]
misclassified = 0
for x in xrange(40, 40 + number):
if genre == classical:
if euclidean_distance(classical_factors, rescale_medians(get_medians_for_song(x, genre))) > euclidean_distance(pop_factors, rescale_medians(get_medians_for_song(x, genre))):
misclassified += 1
else:
if euclidean_distance(classical_factors, rescale_medians(get_medians_for_song(x, genre))) < euclidean_distance(pop_factors, rescale_medians(get_medians_for_song(x, genre))):
misclassified += 1
return (number - misclassified)/number, misclassified, number
print(test_acc(10, classical))
# y1 = rescale_medians(get_medians_for_song(51, classical))
# y2 = rescale_medians(get_medians_for_song(52, classical))
# y3 = rescale_medians(get_medians_for_song(53, classical))
# z1 = rescale_medians(get_medians_for_song(51, pop))
# z2 = rescale_medians(get_medians_for_song(52, pop))
# z3 = rescale_medians(get_medians_for_song(53, pop))
# c = rescale_medians(get_medians(35, classical))
# p = rescale_medians(get_medians(35, pop))
# print(euclidean_distance(y1, c), "classical1 to classical", euclidean_distance(y1, p), "classical1 to pop")
# print(euclidean_distance(y2, c), "classical2 to classical", euclidean_distance(y2, p), "classical2 to pop")
# print(euclidean_distance(y3, c), "classical3 to classical", euclidean_distance(y3, p), "classical3 to pop")
# print(euclidean_distance(z1, p), "pop1 to pop", euclidean_distance(z1, c), "pop1 to classical")
# print(euclidean_distance(z2, p), "pop2 to pop", euclidean_distance(z2, c), "pop2 to classical")
# print(euclidean_distance(z3, p), "pop3 to pop", euclidean_distance(z3, c), "pop3 to classical")
# print("Classical:", c, "Pop:", p)
# print(get_medians(5, classical))
# for x in xrange(50, 75):
# print(classify(x, pop))
# print(classify(x, classical))
# y = [int(10*sin(x)) for x in range(1024)]
# fftvals = np.fft.fft(y)
# mag_fft = abs(fftvals)
# largest = max(mag_fft)
# largest_index = -10
# for index, z in enumerate(mag_fft):
# if largest == z:
# largest_index = index
# print(index, z, largest_index)
| {
"repo_name": "RussGlover/381-module-1",
"path": "project/software/src/fft/fft.py",
"copies": "1",
"size": "5494",
"license": "mit",
"hash": -1225975298034009600,
"line_mean": 32.5,
"line_max": 176,
"alpha_frac": 0.6989443029,
"autogenerated": false,
"ratio": 2.707737801872844,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3906682104772844,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import time
import urllib2
from twitter.common import log
from twitter.common.concurrent import defer
from twitter.common.http import HttpServer
from twitter.common.metrics import (
AtomicGauge,
LambdaGauge,
Observable)
from twitter.common.quantity import Amount, Time
class PingPongServer(Observable):
PING_DELAY = Amount(1, Time.SECONDS)
def __init__(self, target_host, target_port, clock=time):
self._clock = clock
self._target = (target_host, target_port)
self._pings = AtomicGauge('pings')
self.metrics.register(self._pings)
def send_request(self, endpoint, message, ttl):
url_base = 'http://%s:%d' % self._target
try:
urllib2.urlopen('%s/%s/%s/%d' % (url_base, endpoint, message, ttl)).read()
except Exception as e:
log.error('Failed to query %s: %s' % (url_base, e))
@HttpServer.route('/ping/:message')
@HttpServer.route('/ping/:message/:ttl')
def ping(self, message, ttl=60):
self._pings.increment()
log.info('Got ping (ttl=%s): %s' % (message, ttl))
ttl = int(ttl) - 1
if ttl > 0:
defer(partial(self.send_request, 'ping', message, ttl), delay=self.PING_DELAY,
clock=self._clock)
| {
"repo_name": "VaybhavSharma/commons",
"path": "src/python/twitter/common/examples/pingpong.py",
"copies": "14",
"size": "1220",
"license": "apache-2.0",
"hash": -5020698786294054000,
"line_mean": 30.2820512821,
"line_max": 84,
"alpha_frac": 0.6704918033,
"autogenerated": false,
"ratio": 3.32425068119891,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.006163990564787826,
"num_lines": 39
} |
from functools import partial
import time
_cached_objects = dict()
CACHE_EXPIRY = 60 * 10
def get_cached_object(model, id):
"""
A very, very simple in-memory cache for ORM objects.
No invalidation other than restarting this app or waiting CACHE_EXPIRY seconds.
"""
lookup = (model, id)
cached = _cached_objects.get(lookup)
if cached and cached[0] > time.time():
return cached[1]
obj = model.objects.get(pk=id)
_cached_objects[lookup] = (time.time() + CACHE_EXPIRY, obj)
return obj
class memoize_method(object):
"""
Simple memoize decorator for instance methods.
http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/
"""
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
if obj is None:
return self.func
return partial(self, obj)
def __call__(self, *args, **kw):
obj = args[0]
try:
cache = obj.__cache
except AttributeError:
cache = obj.__cache = {}
key = (self.func, args[1:], frozenset(kw.items()))
try:
res = cache[key]
except KeyError:
res = cache[key] = self.func(*args, **kw)
return res
| {
"repo_name": "Open511/open511-server",
"path": "open511_server/utils/optimization.py",
"copies": "1",
"size": "1276",
"license": "mit",
"hash": -6758023198679847000,
"line_mean": 27.3555555556,
"line_max": 88,
"alpha_frac": 0.5885579937,
"autogenerated": false,
"ratio": 3.698550724637681,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4787108718337681,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import time
from ukt import KT_NONE
from ukt import KyotoTycoon
from huey.api import Huey
from huey.constants import EmptyData
from huey.storage import BaseStorage
from huey.utils import decode
class KyotoTycoonStorage(BaseStorage):
priority = True
def __init__(self, name='huey', host='127.0.0.1', port=1978, db=None,
timeout=None, max_age=3600, queue_db=None, client=None,
blocking=False, result_expire_time=None):
super(KyotoTycoonStorage, self).__init__(name)
if client is None:
client = KyotoTycoon(host, port, timeout, db, serializer=KT_NONE,
max_age=max_age)
self.blocking = blocking
self.expire_time = result_expire_time
self.kt = client
self._db = db
self._queue_db = queue_db if queue_db is not None else db
self.qname = self.name + '.q'
self.sname = self.name + '.s'
self.q = self.kt.Queue(self.qname, self._queue_db)
self.s = self.kt.Schedule(self.sname, self._queue_db)
def enqueue(self, data, priority=None):
self.q.add(data, priority)
def dequeue(self):
if self.blocking:
return self.q.bpop(timeout=30)
else:
return self.q.pop()
def queue_size(self):
return len(self.q)
def enqueued_items(self, limit=None):
return self.q.peek(n=limit or -1)
def flush_queue(self):
return self.q.clear()
def convert_ts(self, ts):
return int(time.mktime(ts.timetuple()))
def add_to_schedule(self, data, ts, utc):
self.s.add(data, self.convert_ts(ts))
def read_schedule(self, ts):
return self.s.read(self.convert_ts(ts))
def schedule_size(self):
return len(self.s)
def scheduled_items(self, limit=None):
return self.s.items(limit)
def flush_schedule(self):
return self.s.clear()
def prefix_key(self, key):
return '%s.%s' % (self.qname, decode(key))
def put_data(self, key, value, is_result=False):
xt = self.expire_time if is_result else None
self.kt.set(self.prefix_key(key), value, self._db, expire_time=xt)
def peek_data(self, key):
result = self.kt.get_bytes(self.prefix_key(key), self._db)
return EmptyData if result is None else result
def pop_data(self, key):
if self.expire_time is not None:
return self.peek_data(key)
result = self.kt.seize(self.prefix_key(key), self._db)
return EmptyData if result is None else result
def delete_data(self, key):
return self.kt.seize(self.prefix_key(key), self._db) is not None
def has_data_for_key(self, key):
return self.kt.exists(self.prefix_key(key), self._db)
def put_if_empty(self, key, value):
return self.kt.add(self.prefix_key(key), value, self._db)
def result_store_size(self):
return len(self.kt.match_prefix(self.prefix_key(''), db=self._db))
def result_items(self):
prefix = self.prefix_key('')
keys = self.kt.match_prefix(prefix, db=self._db)
result = self.kt.get_bulk(keys, self._db)
plen = len(prefix)
return {key[plen:]: value for key, value in result.items()}
def flush_results(self):
prefix = self.prefix_key('')
keys = self.kt.match_prefix(prefix, db=self._db)
return self.kt.remove_bulk(keys, self._db)
def flush_all(self):
self.flush_queue()
self.flush_schedule()
self.flush_results()
class KyotoTycoonHuey(Huey):
storage_class = KyotoTycoonStorage
| {
"repo_name": "coleifer/huey",
"path": "huey/contrib/kyototycoon.py",
"copies": "2",
"size": "3659",
"license": "mit",
"hash": -7625129882482947000,
"line_mean": 28.7479674797,
"line_max": 77,
"alpha_frac": 0.6132823176,
"autogenerated": false,
"ratio": 3.3476669716376946,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9960949289237695,
"avg_score": 0,
"num_lines": 123
} |
from functools import partial
import time
import numpy as np
import pandas as pd
from psi.controller.calibration.calibration import FlatCalibration
from psi.token.primitives import ChirpFactory, SilenceFactory
from .calibration import InterpCalibration
from . import util
def chirp_power(engine, ao_channel_name, ai_channel_names, start_frequency=500,
end_frequency=50000, gain=0, vrms=1, repetitions=64,
duration=20e-3, iti=0.001, debug=False):
'''
Given a single output, measure response in multiple input channels using
chirp.
Parameters
----------
TODO
Returns
-------
result : pandas DataFrame
Dataframe will be indexed by output channel name and frequency. Columns
will be rms (in V), snr (in DB) and thd (in percent).
'''
from psi.controller.api import ExtractEpochs, FIFOSignalQueue
calibration = FlatCalibration.as_attenuation(vrms=vrms)
# Create a copy of the engine containing only the channels required for
# calibration.
channel_names = ai_channel_names + [ao_channel_name]
cal_engine = engine.clone(channel_names)
ao_channel = cal_engine.get_channel(ao_channel_name)
ai_channels = [cal_engine.get_channel(name) for name in ai_channel_names]
ao_fs = ao_channel.fs
ai_fs = ai_channels[0].fs
# Ensure that input channels are synced to the output channel
device_name = ao_channel.device_name
ao_channel.start_trigger = ''
for channel in ai_channels:
channel.start_trigger = f'/{device_name}/ao/StartTrigger'
samples = int(ao_fs*duration)
# Build the signal queue
queue = FIFOSignalQueue()
queue.set_fs(ao_fs)
# Create and add the chirp
factory = ChirpFactory(ao_fs, start_frequency, end_frequency, duration,
gain, calibration)
chirp_waveform = factory.next(samples)
queue.append(chirp_waveform, repetitions, iti, metadata={'gain': gain})
# Create and add silence
factory = SilenceFactory(ao_fs, calibration)
waveform = factory.next(samples)
queue.append(waveform, repetitions, iti, metadata={'gain': -400})
# Add the queue to the output channel
output = ao_channel.add_queued_epoch_output(queue, auto_decrement=True)
# Activate the output so it begins as soon as acquisition begins
output.activate(0)
# Create a dictionary of lists. Each list maps to an individual input
# channel and will be used to accumulate the epochs for that channel.
data = {ai_channel.name: [] for ai_channel in ai_channels}
samples = {ai_channel.name: [] for ai_channel in ai_channels}
def accumulate(epochs, epoch):
epochs.extend(epoch)
for ai_channel in ai_channels:
cb = partial(accumulate, data[ai_channel.name])
epoch_input = ExtractEpochs(epoch_size=duration+iti)
queue.connect(epoch_input.queue.append)
epoch_input.add_callback(cb)
ai_channel.add_input(epoch_input)
ai_channel.add_callback(samples[ai_channel.name].append)
cal_engine.start()
while not epoch_input.complete:
time.sleep(0.1)
cal_engine.stop()
result_waveforms = {}
result_psd = {}
for ai_channel in ai_channels:
epochs = data[ai_channel.name]
waveforms = [e['signal'] for e in epochs]
keys = [e['info']['metadata'] for e in epochs]
keys = pd.DataFrame(keys)
keys.index.name = 'epoch'
keys = keys.set_index(['gain'], append=True)
keys.index = keys.index.swaplevel('epoch', 'gain')
waveforms = np.vstack(waveforms)
t = np.arange(waveforms.shape[-1]) / ai_channel.fs
time_index = pd.Index(t, name='time')
waveforms = pd.DataFrame(waveforms, index=keys.index,
columns=time_index)
mean_waveforms = waveforms.groupby('gain').mean()
samples = int(round(ai_channel.fs * (duration + iti)))
factory = ChirpFactory(ai_channel.fs, start_frequency, end_frequency,
duration, gain, calibration)
chirp_waveform = factory.next(samples)
chirp_psd = util.psd_df(chirp_waveform, ai_channel.fs)
mean_psd = util.psd_df(mean_waveforms, ai_channel.fs)
result_psd[ai_channel.name] = pd.DataFrame({
'rms': mean_psd.loc[gain],
'chirp_rms': chirp_psd,
'snr': util.db(mean_psd.loc[gain] / mean_psd.loc[-400]),
})
#result_waveforms[ai_channel.name] = waveforms
#result_waveforms = pd.concat(result_waveforms.values(),
# keys=result_waveforms.keys(),
# names=['channel'])
result_psd = pd.concat(result_psd.values(), keys=result_psd.keys(),
names=['channel'])
return result_psd
def chirp_spl(engine, **kwargs):
def map_spl(series, engine):
channel_name, = series.index.get_level_values('channel').unique()
channel = engine.get_channel(channel_name)
frequency = series.index.get_level_values('frequency')
series['spl'] = channel.calibration.get_spl(frequency, series['rms'])
return series
result = chirp_power(engine, **kwargs)
return result.groupby('channel').apply(map_spl, engine=engine)
def chirp_sens(engine, gain=-40, vrms=1, **kwargs):
result = chirp_spl(engine, gain=gain, vrms=vrms, **kwargs)
result['norm_spl'] = result['spl'] - util.db(result['chirp_rms'])
result['sens'] = -result['norm_spl'] - util.db(20e-6)
return result
def chirp_calibration(ai_channel_names, **kwargs):
kwargs.update({'ai_channel_names': ai_channel_names})
output_sens = chirp_sens(**kwargs)
calibrations = {}
for ai_channel in ai_channel_names:
data = output_sens.loc[ai_channel]
calibrations[ai_channel] = InterpCalibration(data.index, data['sens'])
return calibrations
| {
"repo_name": "bburan/psiexperiment",
"path": "psi/controller/calibration/chirp.py",
"copies": "1",
"size": "5939",
"license": "mit",
"hash": -2922350778297116000,
"line_mean": 35.4355828221,
"line_max": 79,
"alpha_frac": 0.6433743054,
"autogenerated": false,
"ratio": 3.5820265379975873,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47254008433975875,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import time
import numpy as np
def acquire(engine, waveform, ao_channel_name, ai_channel_names, gain=0,
vrms=1, repetitions=2, min_snr=None, max_thd=None, thd_harmonics=3,
trim=0.01, iti=0.01, debug=False):
'''
Given a single output, measure response in multiple input channels.
Parameters
----------
TODO
Returns
-------
result : array
TODO
'''
if not isinstance(ao_channel_name, str):
raise ValueError('Can only specify one output channel')
from psi.controller.api import ExtractEpochs, FIFOSignalQueue
from psi.controller.calibration.api import FlatCalibration
calibration = FlatCalibration.as_attenuation(vrms=vrms)
# Create a copy of the engine containing only the channels required for
# calibration.
channel_names = ai_channel_names + [ao_channel_name]
cal_engine = engine.clone(channel_names)
ao_channel = cal_engine.get_channel(ao_channel_name)
ai_channels = [cal_engine.get_channel(name) for name in ai_channel_names]
ao_fs = ao_channel.fs
ai_fs = ai_channels[0].fs
# Ensure that input channels are synced to the output channel
ao_channel.start_trigger = ''
for channel in ai_channels:
channel.start_trigger = f'/{ao_channel.device_name}/ao/StartTrigger'
samples = waveform.shape[-1]
duration = samples / ao_fs
# Build the signal queue
queue = FIFOSignalQueue()
queue.set_fs(ao_fs)
queue.append(waveform, repetitions, iti)
# Add the queue to the output channel
output = ao_channel.add_queued_epoch_output(queue, auto_decrement=True)
# Activate the output so it begins as soon as acquisition begins
output.activate(0)
# Create a dictionary of lists. Each list maps to an individual input
# channel and will be used to accumulate the epochs for that channel.
data = {ai_channel.name: [] for ai_channel in ai_channels}
samples = {ai_channel.name: [] for ai_channel in ai_channels}
def accumulate(epochs, epoch):
epochs.extend(epoch)
for ai_channel in ai_channels:
cb = partial(accumulate, data[ai_channel.name])
epoch_input = ExtractEpochs(epoch_size=duration)
queue.connect(epoch_input.queue.append)
epoch_input.add_callback(cb)
ai_channel.add_input(epoch_input)
ai_channel.add_callback(samples[ai_channel.name].append)
cal_engine.start()
while not epoch_input.complete:
time.sleep(0.1)
cal_engine.stop()
result = {}
for ai_channel in ai_channels:
# Process data from channel
epochs = [epoch['signal'][np.newaxis] for epoch in data[ai_channel.name]]
signal = np.concatenate(epochs)
signal.shape = [-1, repetitions] + list(signal.shape[1:])
if trim != 0:
trim_samples = round(ai_channel.fs * trim)
signal = signal[..., trim_samples:-trim_samples]
result[ai_channel.name] = signal
#df = pd.DataFrame(channel_result)
#df['channel_name'] = ai_channel.name
#result.append(df)
return result
#return pd.concat(result).set_index(['channel_name', 'frequency'])
| {
"repo_name": "bburan/psiexperiment",
"path": "psi/controller/util.py",
"copies": "1",
"size": "3209",
"license": "mit",
"hash": -8515237011269560000,
"line_mean": 32.0824742268,
"line_max": 81,
"alpha_frac": 0.6593954503,
"autogenerated": false,
"ratio": 3.66324200913242,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.482263745943242,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import tornado.ioloop
from tornado.testing import AsyncTestCase
from tornado.stack_context import ExceptionStackContext
from elasticsearch_tornado import SnapshotClient
try:
# python 2.6
from unittest2 import TestCase, SkipTest
except ImportError:
from unittest import TestCase, SkipTest
def handle_exc(*args):
print('Exception occured')
return True
class SnapshotClientTest(AsyncTestCase):
def handle_cb(self, req, **kwargs):
if kwargs.get('codes'):
cl = [200, 201] + kwargs.get('codes')
self.assertTrue(req.code in cl)
else:
self.assertTrue(req.code in (200, 201, ))
self.stop()
def test_create_snapshot(self):
c = SnapshotClient()
body = """
{
"type": "fs",
"settings": {
"location": "/tmp/test",
"compress": true
}
}
"""
h_cb = partial(
self.handle_cb,
**{'codes':[400, 404]}
)
c.create_snapshot('test', 'test', body, callback=h_cb)
self.wait()
def test_delete_snapshot(self):
c = SnapshotClient()
h_cb = partial(
self.handle_cb,
**{'codes':[400, 404]}
)
c.delete_snapshot('test', 'test', callback=h_cb)
self.wait()
def test_get(self):
c = SnapshotClient()
h_cb = partial(
self.handle_cb,
**{'codes':[400, 404]}
)
c.get_snapshot('test', 'test', callback=h_cb)
self.wait()
def test_delete_repository(self):
c = SnapshotClient()
h_cb = partial(
self.handle_cb,
**{'codes':[400, 404]}
)
c.delete_repository('test', callback=h_cb)
self.wait()
def test_get_repository(self):
c = SnapshotClient()
h_cb = partial(
self.handle_cb,
**{'codes':[400, 404]}
)
c.get_repository(callback=h_cb)
self.wait()
def test_create_repository(self):
c = SnapshotClient()
body = """
{
"type": "fs",
"settings": {
"location": "/tmp/test",
}
}
"""
h_cb = partial(
self.handle_cb,
**{'codes':[400, 404]}
)
c.create_repository('test', body, callback=h_cb)
self.wait()
def test_restore_snapshot(self):
c = SnapshotClient()
body = """
'{
"indices": "index_1,index_2",
"ignore_unavailable": "true",
"include_global_state": false,
"rename_pattern": "index_(.+)",
"rename_replacement": "restored_index_$1"
}
"""
h_cb = partial(
self.handle_cb,
**{'codes':[400, 404]}
)
c.restore_snapshot('test', 'test', body, callback=h_cb)
self.wait()
def test_snapshot_status(self):
c = SnapshotClient()
h_cb = partial(
self.handle_cb,
**{'codes':[400, 404]}
)
c.snapshot_status(callback=h_cb)
self.wait()
def test_verify_repository(self):
c = SnapshotClient()
h_cb = partial(
self.handle_cb,
**{'codes':[400, 404]}
)
c.verify_repository('test', callback=h_cb)
self.wait()
| {
"repo_name": "hodgesds/elasticsearch_tornado",
"path": "tests/test_snapshot.py",
"copies": "1",
"size": "3451",
"license": "apache-2.0",
"hash": -5277486742213470000,
"line_mean": 24.375,
"line_max": 63,
"alpha_frac": 0.491161982,
"autogenerated": false,
"ratio": 4.0174621653084985,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9958169750388639,
"avg_score": 0.010090879383971827,
"num_lines": 136
} |
from functools import partial
import traceback
import logging
import sys
import os
import io
import aiofiles
from datetime import datetime
from fable import config
class Logger:
def __init__(self, path, level=logging.DEBUG):
self.path = path
self.level = level
self.time_format = '%Y-%m-%d %H:%M:%S'
def format(self, level, *arg, **kw):
with io.StringIO() as f:
print(*arg, **kw, file=f)
value = f.getvalue()
level = logging.getLevelName(level)
time = datetime.now().strftime(self.time_format)
return ' - '.join([time, level, value])
async def alog(self, level, *arg, **kw):
if level >= self.level:
async with aiofiles.open(self.path, mode='a+') as f:
await f.write(self.format(level, *arg, **kw))
async def ainfo(self, *args, **kw):
await self.alog(logging.INFO, *args, **kw)
async def adebug(self, *args, **kw):
await self.alog(logging.DEBUG, *args, **kw)
async def awarning(self, *args, **kw):
await self.alog(logging.WARNING, *args, **kw)
async def acritical(self, *args, **kw):
await self.alog(logging.CRITICAL, *args, **kw)
async def aerror(self, *args, **kw):
await self.alog(logging.ERROR, *args, **kw)
async def aexception(self):
with io.StringIO() as f:
traceback.print_exc(file=f)
value = f.getvalue()
async with aiofiles.open(self.path, mode='a+') as f:
await f.write(value)
def log(self, level, *args, **kw):
if level >= self.level:
with open(self.path, mode='a+') as f:
f.write(self.format(level, *args, **kw))
def info(self, *args, **kw):
self.log(logging.INFO, *args, **kw)
def debug(self, *args, **kw):
self.log(logging.DEBUG, *args, **kw)
def warning(self, *args, **kw):
self.log(logging.WARNING, *args, **kw)
def critical(self, *args, **kw):
self.log(logging.CRITICAL, *args, **kw)
def error(self, *args, **kw):
self.log(logging.ERROR, *args, **kw)
def exception(self):
with io.StringIO() as f:
traceback.print_exc(file=f)
value = f.getvalue()
with open(self.path, mode='a+') as f:
f.write(value)
_logs = {}
def log(name):
global _logs
os.makedirs(config.LOGS, exist_ok=True)
path = os.path.join(config.LOGS, name)
if name in _logs:
return _logs[name]
_logs[name] = Logger(path)
return _logs[name]
def handler(name):
os.makedirs(config.LOGS, exist_ok=True)
path = os.path.join(config.LOGS, name)
return logging.FileHandler(path)
def shutdown():
logging.shutdown()
| {
"repo_name": "yrapop01/fable",
"path": "legacy/log/__init__.py",
"copies": "1",
"size": "2759",
"license": "mit",
"hash": 117128875137922690,
"line_mean": 26.59,
"line_max": 64,
"alpha_frac": 0.5770206597,
"autogenerated": false,
"ratio": 3.3442424242424242,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4421263083942424,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import traceback
import sys
from typing import TYPE_CHECKING
from PyQt5.QtCore import QObject, pyqtSignal
from PyQt5.QtWidgets import (QHBoxLayout, QLabel, QVBoxLayout)
from electrum_ltc.plugin import hook
from electrum_ltc.i18n import _
from electrum_ltc.gui.qt.util import ThreadedButton, Buttons, EnterButton, WindowModalDialog, OkButton
from .labels import LabelsPlugin
if TYPE_CHECKING:
from electrum_ltc.gui.qt import ElectrumGui
from electrum_ltc.gui.qt.main_window import ElectrumWindow
from electrum_ltc.wallet import Abstract_Wallet
class QLabelsSignalObject(QObject):
labels_changed_signal = pyqtSignal(object)
class Plugin(LabelsPlugin):
def __init__(self, *args):
LabelsPlugin.__init__(self, *args)
self.obj = QLabelsSignalObject()
self._init_qt_received = False
def requires_settings(self):
return True
def settings_widget(self, window: WindowModalDialog):
return EnterButton(_('Settings'),
partial(self.settings_dialog, window))
def settings_dialog(self, window: WindowModalDialog):
wallet = window.parent().wallet
if not wallet.get_fingerprint():
window.show_error(_("{} plugin does not support this type of wallet.")
.format("Label Sync"))
return
d = WindowModalDialog(window, _("Label Settings"))
hbox = QHBoxLayout()
hbox.addWidget(QLabel("Label sync options:"))
upload = ThreadedButton("Force upload",
partial(self.push, wallet),
partial(self.done_processing_success, d),
partial(self.done_processing_error, d))
download = ThreadedButton("Force download",
partial(self.pull, wallet, True),
partial(self.done_processing_success, d),
partial(self.done_processing_error, d))
vbox = QVBoxLayout()
vbox.addWidget(upload)
vbox.addWidget(download)
hbox.addLayout(vbox)
vbox = QVBoxLayout(d)
vbox.addLayout(hbox)
vbox.addSpacing(20)
vbox.addLayout(Buttons(OkButton(d)))
return bool(d.exec_())
def on_pulled(self, wallet):
self.obj.labels_changed_signal.emit(wallet)
def done_processing_success(self, dialog, result):
dialog.show_message(_("Your labels have been synchronised."))
def done_processing_error(self, dialog, exc_info):
self.logger.error("Error synchronising labels", exc_info=exc_info)
dialog.show_error(_("Error synchronising labels") + f':\n{repr(exc_info[1])}')
@hook
def init_qt(self, gui: 'ElectrumGui'):
if self._init_qt_received: # only need/want the first signal
return
self._init_qt_received = True
# If the user just enabled the plugin, the 'load_wallet' hook would not
# get called for already loaded wallets, hence we call it manually for those:
for window in gui.windows:
self.load_wallet(window.wallet, window)
@hook
def load_wallet(self, wallet: 'Abstract_Wallet', window: 'ElectrumWindow'):
self.obj.labels_changed_signal.connect(window.update_tabs)
self.start_wallet(wallet)
@hook
def on_close_window(self, window):
try:
self.obj.labels_changed_signal.disconnect(window.update_tabs)
except TypeError:
pass # 'method' object is not connected
self.stop_wallet(window.wallet)
| {
"repo_name": "pooler/electrum-ltc",
"path": "electrum_ltc/plugins/labels/qt.py",
"copies": "1",
"size": "3637",
"license": "mit",
"hash": -542284335820490800,
"line_mean": 36.8854166667,
"line_max": 102,
"alpha_frac": 0.6315644762,
"autogenerated": false,
"ratio": 4.104966139954853,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5236530616154853,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import traceback
import sys
from PyQt5.QtCore import QObject, pyqtSignal
from PyQt5.QtWidgets import (QHBoxLayout, QLabel, QVBoxLayout)
from electrum_ltc.plugin import hook
from electrum_ltc.i18n import _
from electrum_ltc.gui.qt.util import ThreadedButton, Buttons, EnterButton, WindowModalDialog, OkButton
from .labels import LabelsPlugin
class QLabelsSignalObject(QObject):
labels_changed_signal = pyqtSignal(object)
class Plugin(LabelsPlugin):
def __init__(self, *args):
LabelsPlugin.__init__(self, *args)
self.obj = QLabelsSignalObject()
def requires_settings(self):
return True
def settings_widget(self, window):
return EnterButton(_('Settings'),
partial(self.settings_dialog, window))
def settings_dialog(self, window):
wallet = window.parent().wallet
d = WindowModalDialog(window, _("Label Settings"))
hbox = QHBoxLayout()
hbox.addWidget(QLabel("Label sync options:"))
upload = ThreadedButton("Force upload",
partial(self.push, wallet),
partial(self.done_processing_success, d),
partial(self.done_processing_error, d))
download = ThreadedButton("Force download",
partial(self.pull, wallet, True),
partial(self.done_processing_success, d),
partial(self.done_processing_error, d))
vbox = QVBoxLayout()
vbox.addWidget(upload)
vbox.addWidget(download)
hbox.addLayout(vbox)
vbox = QVBoxLayout(d)
vbox.addLayout(hbox)
vbox.addSpacing(20)
vbox.addLayout(Buttons(OkButton(d)))
return bool(d.exec_())
def on_pulled(self, wallet):
self.obj.labels_changed_signal.emit(wallet)
def done_processing_success(self, dialog, result):
dialog.show_message(_("Your labels have been synchronised."))
def done_processing_error(self, dialog, exc_info):
self.logger.error("Error synchronising labels", exc_info=exc_info)
dialog.show_error(_("Error synchronising labels") + f':\n{repr(exc_info[1])}')
@hook
def load_wallet(self, wallet, window):
# FIXME if the user just enabled the plugin, this hook won't be called
# as the wallet is already loaded, and hence the plugin will be in
# a non-functional state for that window
self.obj.labels_changed_signal.connect(window.update_tabs)
self.start_wallet(wallet)
@hook
def on_close_window(self, window):
try:
self.obj.labels_changed_signal.disconnect(window.update_tabs)
except TypeError:
pass # 'method' object is not connected
self.stop_wallet(window.wallet)
| {
"repo_name": "vialectrum/vialectrum",
"path": "electrum_ltc/plugins/labels/qt.py",
"copies": "1",
"size": "2882",
"license": "mit",
"hash": -1918994567817236500,
"line_mean": 35.4810126582,
"line_max": 102,
"alpha_frac": 0.6276891048,
"autogenerated": false,
"ratio": 4.182873730043541,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5310562834843541,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import traceback
import sys
from PyQt5.QtCore import QObject, pyqtSignal
from PyQt5.QtWidgets import (QHBoxLayout, QLabel, QVBoxLayout)
from electrum.plugin import hook
from electrum.i18n import _
from electrum.gui.qt.util import ThreadedButton, Buttons, EnterButton, WindowModalDialog, OkButton
from .labels import LabelsPlugin
class QLabelsSignalObject(QObject):
labels_changed_signal = pyqtSignal(object)
class Plugin(LabelsPlugin):
def __init__(self, *args):
LabelsPlugin.__init__(self, *args)
self.obj = QLabelsSignalObject()
def requires_settings(self):
return True
def settings_widget(self, window):
return EnterButton(_('Settings'),
partial(self.settings_dialog, window))
def settings_dialog(self, window):
wallet = window.parent().wallet
d = WindowModalDialog(window, _("Label Settings"))
hbox = QHBoxLayout()
hbox.addWidget(QLabel("Label sync options:"))
upload = ThreadedButton("Force upload",
partial(self.push, wallet),
partial(self.done_processing_success, d),
partial(self.done_processing_error, d))
download = ThreadedButton("Force download",
partial(self.pull, wallet, True),
partial(self.done_processing_success, d),
partial(self.done_processing_error, d))
vbox = QVBoxLayout()
vbox.addWidget(upload)
vbox.addWidget(download)
hbox.addLayout(vbox)
vbox = QVBoxLayout(d)
vbox.addLayout(hbox)
vbox.addSpacing(20)
vbox.addLayout(Buttons(OkButton(d)))
return bool(d.exec_())
def on_pulled(self, wallet):
self.obj.labels_changed_signal.emit(wallet)
def done_processing_success(self, dialog, result):
dialog.show_message(_("Your labels have been synchronised."))
def done_processing_error(self, dialog, exc_info):
self.logger.error("Error synchronising labels", exc_info=exc_info)
dialog.show_error(_("Error synchronising labels") + f':\n{repr(exc_info[1])}')
@hook
def load_wallet(self, wallet, window):
# FIXME if the user just enabled the plugin, this hook won't be called
# as the wallet is already loaded, and hence the plugin will be in
# a non-functional state for that window
self.obj.labels_changed_signal.connect(window.update_tabs)
self.start_wallet(wallet)
@hook
def on_close_window(self, window):
try:
self.obj.labels_changed_signal.disconnect(window.update_tabs)
except TypeError:
pass # 'method' object is not connected
self.stop_wallet(window.wallet)
| {
"repo_name": "neocogent/electrum",
"path": "electrum/plugins/labels/qt.py",
"copies": "2",
"size": "2870",
"license": "mit",
"hash": 1724453818211666200,
"line_mean": 35.3291139241,
"line_max": 98,
"alpha_frac": 0.6271777003,
"autogenerated": false,
"ratio": 4.220588235294118,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5847765935594118,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import traceback
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import (QHBoxLayout, QLabel, QVBoxLayout)
from electrum.plugin import hook
from electrum.i18n import _
from electrum.gui.qt import EnterButton
from electrum.gui.qt.util import ThreadedButton, Buttons
from electrum.gui.qt.util import WindowModalDialog, OkButton
from .labels import LabelsPlugin
class QLabelsSignalObject(QObject):
labels_changed_signal = pyqtSignal(object)
class Plugin(LabelsPlugin):
def __init__(self, *args):
LabelsPlugin.__init__(self, *args)
self.obj = QLabelsSignalObject()
def requires_settings(self):
return True
def settings_widget(self, window):
return EnterButton(_('Settings'),
partial(self.settings_dialog, window))
def settings_dialog(self, window):
wallet = window.parent().wallet
d = WindowModalDialog(window, _("Label Settings"))
hbox = QHBoxLayout()
hbox.addWidget(QLabel("Label sync options:"))
upload = ThreadedButton("Force upload",
partial(self.push_thread, wallet),
partial(self.done_processing_success, d),
partial(self.done_processing_error, d))
download = ThreadedButton("Force download",
partial(self.pull_thread, wallet, True),
partial(self.done_processing_success, d),
partial(self.done_processing_error, d))
vbox = QVBoxLayout()
vbox.addWidget(upload)
vbox.addWidget(download)
hbox.addLayout(vbox)
vbox = QVBoxLayout(d)
vbox.addLayout(hbox)
vbox.addSpacing(20)
vbox.addLayout(Buttons(OkButton(d)))
return bool(d.exec_())
def on_pulled(self, wallet):
self.obj.labels_changed_signal.emit(wallet)
def done_processing_success(self, dialog, result):
dialog.show_message(_("Your labels have been synchronised."))
def done_processing_error(self, dialog, result):
traceback.print_exception(*result, file=sys.stderr)
dialog.show_error(_("Error synchronising labels") + ':\n' + str(result[:2]))
@hook
def load_wallet(self, wallet, window):
# FIXME if the user just enabled the plugin, this hook won't be called
# as the wallet is already loaded, and hence the plugin will be in
# a non-functional state for that window
self.obj.labels_changed_signal.connect(window.update_tabs)
self.start_wallet(wallet)
@hook
def on_close_window(self, window):
self.stop_wallet(window.wallet)
| {
"repo_name": "asfin/electrum",
"path": "electrum/plugins/labels/qt.py",
"copies": "1",
"size": "2766",
"license": "mit",
"hash": -4208618316383455700,
"line_mean": 34.4615384615,
"line_max": 84,
"alpha_frac": 0.6326825741,
"autogenerated": false,
"ratio": 4.197268588770865,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5329951162870865,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import traceback
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import (QHBoxLayout, QLabel, QVBoxLayout)
from electrum.plugins import hook
from electrum.i18n import _
from electrum_gui.qt import EnterButton
from electrum_gui.qt.util import ThreadedButton, Buttons
from electrum_gui.qt.util import WindowModalDialog, OkButton
from .labels import LabelsPlugin
class QLabelsSignalObject(QObject):
labels_changed_signal = pyqtSignal(object)
class Plugin(LabelsPlugin):
def __init__(self, *args):
LabelsPlugin.__init__(self, *args)
self.obj = QLabelsSignalObject()
def requires_settings(self):
return True
def settings_widget(self, window):
return EnterButton(_('Settings'),
partial(self.settings_dialog, window))
def settings_dialog(self, window):
wallet = window.parent().wallet
d = WindowModalDialog(window, _("Label Settings"))
hbox = QHBoxLayout()
hbox.addWidget(QLabel("Label sync options:"))
upload = ThreadedButton("Force upload",
partial(self.push_thread, wallet),
partial(self.done_processing_success, d),
partial(self.done_processing_error, d))
download = ThreadedButton("Force download",
partial(self.pull_thread, wallet, True),
partial(self.done_processing_success, d),
partial(self.done_processing_error, d))
vbox = QVBoxLayout()
vbox.addWidget(upload)
vbox.addWidget(download)
hbox.addLayout(vbox)
vbox = QVBoxLayout(d)
vbox.addLayout(hbox)
vbox.addSpacing(20)
vbox.addLayout(Buttons(OkButton(d)))
return bool(d.exec_())
def on_pulled(self, wallet):
self.obj.labels_changed_signal.emit(wallet)
def done_processing_success(self, dialog, result):
dialog.show_message(_("Your labels have been synchronised."))
def done_processing_error(self, dialog, result):
traceback.print_exception(*result, file=sys.stderr)
dialog.show_error(_("Error synchronising labels") + ':\n' + str(result[:2]))
@hook
def load_wallet(self, wallet, window):
# FIXME if the user just enabled the plugin, this hook won't be called
# as the wallet is already loaded, and hence the plugin will be in
# a non-functional state for that window
self.obj.labels_changed_signal.connect(window.update_tabs)
self.start_wallet(wallet)
@hook
def on_close_window(self, window):
self.stop_wallet(window.wallet)
| {
"repo_name": "kyuupichan/electrum",
"path": "plugins/labels/qt.py",
"copies": "1",
"size": "2767",
"license": "mit",
"hash": -7951960494490697000,
"line_mean": 34.4743589744,
"line_max": 84,
"alpha_frac": 0.6328153235,
"autogenerated": false,
"ratio": 4.198786039453718,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5331601362953717,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import traceback
import dask
from dask.base import normalize_token
from tlz import valmap, get_in
import msgpack
from . import pickle
from ..utils import has_keyword, typename
from .compression import maybe_compress, decompress
from .utils import (
unpack_frames,
pack_frames_prelude,
frame_split_size,
ensure_bytes,
msgpack_opts,
)
lazy_registrations = {}
dask_serialize = dask.utils.Dispatch("dask_serialize")
dask_deserialize = dask.utils.Dispatch("dask_deserialize")
def dask_dumps(x, context=None):
"""Serialise object using the class-based registry"""
type_name = typename(type(x))
try:
dumps = dask_serialize.dispatch(type(x))
except TypeError:
raise NotImplementedError(type_name)
if has_keyword(dumps, "context"):
header, frames = dumps(x, context=context)
else:
header, frames = dumps(x)
header["type"] = type_name
header["type-serialized"] = pickle.dumps(type(x))
header["serializer"] = "dask"
return header, frames
def dask_loads(header, frames):
typ = pickle.loads(header["type-serialized"])
loads = dask_deserialize.dispatch(typ)
return loads(header, frames)
def pickle_dumps(x):
header = {"serializer": "pickle"}
frames = [None]
buffer_callback = lambda f: frames.append(memoryview(f))
frames[0] = pickle.dumps(x, buffer_callback=buffer_callback)
return header, frames
def pickle_loads(header, frames):
x, buffers = frames[0], frames[1:]
return pickle.loads(x, buffers=buffers)
def msgpack_dumps(x):
try:
frame = msgpack.dumps(x, use_bin_type=True)
except Exception:
raise NotImplementedError()
else:
return {"serializer": "msgpack"}, [frame]
def msgpack_loads(header, frames):
return msgpack.loads(b"".join(frames), use_list=False, **msgpack_opts)
def serialization_error_loads(header, frames):
msg = "\n".join([ensure_bytes(frame).decode("utf8") for frame in frames])
raise TypeError(msg)
families = {}
def register_serialization_family(name, dumps, loads):
families[name] = (dumps, loads, dumps and has_keyword(dumps, "context"))
register_serialization_family("dask", dask_dumps, dask_loads)
register_serialization_family("pickle", pickle_dumps, pickle_loads)
register_serialization_family("msgpack", msgpack_dumps, msgpack_loads)
register_serialization_family("error", None, serialization_error_loads)
def check_dask_serializable(x):
if type(x) in (list, set, tuple) and len(x):
return check_dask_serializable(next(iter(x)))
elif type(x) is dict and len(x):
return check_dask_serializable(next(iter(x.items()))[1])
else:
try:
dask_serialize.dispatch(type(x))
return True
except TypeError:
pass
return False
def serialize(x, serializers=None, on_error="message", context=None):
r"""
Convert object to a header and list of bytestrings
This takes in an arbitrary Python object and returns a msgpack serializable
header and a list of bytes or memoryview objects.
The serialization protocols to use are configurable: a list of names
define the set of serializers to use, in order. These names are keys in
the ``serializer_registry`` dict (e.g., 'pickle', 'msgpack'), which maps
to the de/serialize functions. The name 'dask' is special, and will use the
per-class serialization methods. ``None`` gives the default list
``['dask', 'pickle']``.
Examples
--------
>>> serialize(1)
({}, [b'\x80\x04\x95\x03\x00\x00\x00\x00\x00\x00\x00K\x01.'])
>>> serialize(b'123') # some special types get custom treatment
({'type': 'builtins.bytes'}, [b'123'])
>>> deserialize(*serialize(1))
1
Returns
-------
header: dictionary containing any msgpack-serializable metadata
frames: list of bytes or memoryviews, commonly of length one
See Also
--------
deserialize: Convert header and frames back to object
to_serialize: Mark that data in a message should be serialized
register_serialization: Register custom serialization functions
"""
if serializers is None:
serializers = ("dask", "pickle") # TODO: get from configuration
if isinstance(x, Serialized):
return x.header, x.frames
if type(x) in (list, set, tuple, dict):
iterate_collection = False
if type(x) is list and "msgpack" in serializers:
# Note: "msgpack" will always convert lists to tuples
# (see GitHub #3716), so we should iterate
# through the list if "msgpack" comes before "pickle"
# in the list of serializers.
iterate_collection = ("pickle" not in serializers) or (
serializers.index("pickle") > serializers.index("msgpack")
)
if not iterate_collection:
# Check for "dask"-serializable data in dict/list/set
iterate_collection = check_dask_serializable(x)
# Determine whether keys are safe to be serialized with msgpack
if type(x) is dict and iterate_collection:
try:
msgpack.dumps(list(x.keys()))
except Exception:
dict_safe = False
else:
dict_safe = True
if (
type(x) in (list, set, tuple)
and iterate_collection
or type(x) is dict
and iterate_collection
and dict_safe
):
if isinstance(x, dict):
headers_frames = []
for k, v in x.items():
_header, _frames = serialize(
v, serializers=serializers, on_error=on_error, context=context
)
_header["key"] = k
headers_frames.append((_header, _frames))
else:
headers_frames = [
serialize(
obj, serializers=serializers, on_error=on_error, context=context
)
for obj in x
]
frames = []
lengths = []
compressions = []
for _header, _frames in headers_frames:
frames.extend(_frames)
length = len(_frames)
lengths.append(length)
compressions.extend(_header.get("compression") or [None] * len(_frames))
headers = [obj[0] for obj in headers_frames]
headers = {
"sub-headers": headers,
"is-collection": True,
"frame-lengths": lengths,
"type-serialized": type(x).__name__,
}
if any(compression is not None for compression in compressions):
headers["compression"] = compressions
return headers, frames
tb = ""
for name in serializers:
dumps, loads, wants_context = families[name]
try:
header, frames = dumps(x, context=context) if wants_context else dumps(x)
header["serializer"] = name
return header, frames
except NotImplementedError:
continue
except Exception as e:
tb = traceback.format_exc()
break
msg = "Could not serialize object of type %s." % type(x).__name__
if on_error == "message":
frames = [msg]
if tb:
frames.append(tb[:100000])
frames = [frame.encode() for frame in frames]
return {"serializer": "error"}, frames
elif on_error == "raise":
raise TypeError(msg, str(x)[:10000])
def deserialize(header, frames, deserializers=None):
"""
Convert serialized header and list of bytestrings back to a Python object
Parameters
----------
header: dict
frames: list of bytes
deserializers : Optional[Dict[str, Tuple[Callable, Callable, bool]]]
An optional dict mapping a name to a (de)serializer.
See `dask_serialize` and `dask_deserialize` for more.
See Also
--------
serialize
"""
if "is-collection" in header:
headers = header["sub-headers"]
lengths = header["frame-lengths"]
cls = {"tuple": tuple, "list": list, "set": set, "dict": dict}[
header["type-serialized"]
]
start = 0
if cls is dict:
d = {}
for _header, _length in zip(headers, lengths):
k = _header.pop("key")
d[k] = deserialize(
_header,
frames[start : start + _length],
deserializers=deserializers,
)
start += _length
return d
else:
lst = []
for _header, _length in zip(headers, lengths):
lst.append(
deserialize(
_header,
frames[start : start + _length],
deserializers=deserializers,
)
)
start += _length
return cls(lst)
name = header.get("serializer")
if deserializers is not None and name not in deserializers:
raise TypeError(
"Data serialized with %s but only able to deserialize "
"data with %s" % (name, str(list(deserializers)))
)
dumps, loads, wants_context = families[name]
return loads(header, frames)
class Serialize:
""" Mark an object that should be serialized
Examples
--------
>>> msg = {'op': 'update', 'data': to_serialize(123)}
>>> msg # doctest: +SKIP
{'op': 'update', 'data': <Serialize: 123>}
See also
--------
distributed.protocol.dumps
"""
def __init__(self, data):
self.data = data
def __repr__(self):
return "<Serialize: %s>" % str(self.data)
def __eq__(self, other):
return isinstance(other, Serialize) and other.data == self.data
def __ne__(self, other):
return not (self == other)
def __hash__(self):
return hash(self.data)
to_serialize = Serialize
class Serialized:
"""
An object that is already serialized into header and frames
Normal serialization operations pass these objects through. This is
typically used within the scheduler which accepts messages that contain
data without actually unpacking that data.
"""
def __init__(self, header, frames):
self.header = header
self.frames = frames
def deserialize(self):
from .core import decompress
frames = decompress(self.header, self.frames)
return deserialize(self.header, frames)
def __eq__(self, other):
return (
isinstance(other, Serialized)
and other.header == self.header
and other.frames == self.frames
)
def __ne__(self, other):
return not (self == other)
def container_copy(c):
typ = type(c)
if typ is list:
return list(map(container_copy, c))
if typ is dict:
return valmap(container_copy, c)
return c
def extract_serialize(x):
""" Pull out Serialize objects from message
This also remove large bytestrings from the message into a second
dictionary.
Examples
--------
>>> from distributed.protocol import to_serialize
>>> msg = {'op': 'update', 'data': to_serialize(123)}
>>> extract_serialize(msg)
({'op': 'update'}, {('data',): <Serialize: 123>}, set())
"""
ser = {}
_extract_serialize(x, ser)
if ser:
x = container_copy(x)
for path in ser:
t = get_in(path[:-1], x)
if isinstance(t, dict):
del t[path[-1]]
else:
t[path[-1]] = None
bytestrings = set()
for k, v in ser.items():
if type(v) in (bytes, bytearray):
ser[k] = to_serialize(v)
bytestrings.add(k)
return x, ser, bytestrings
def _extract_serialize(x, ser, path=()):
if type(x) is dict:
for k, v in x.items():
typ = type(v)
if typ is list or typ is dict:
_extract_serialize(v, ser, path + (k,))
elif (
typ is Serialize
or typ is Serialized
or typ in (bytes, bytearray)
and len(v) > 2 ** 16
):
ser[path + (k,)] = v
elif type(x) is list:
for k, v in enumerate(x):
typ = type(v)
if typ is list or typ is dict:
_extract_serialize(v, ser, path + (k,))
elif (
typ is Serialize
or typ is Serialized
or typ in (bytes, bytearray)
and len(v) > 2 ** 16
):
ser[path + (k,)] = v
def nested_deserialize(x):
"""
Replace all Serialize and Serialized values nested in *x*
with the original values. Returns a copy of *x*.
>>> msg = {'op': 'update', 'data': to_serialize(123)}
>>> nested_deserialize(msg)
{'op': 'update', 'data': 123}
"""
def replace_inner(x):
if type(x) is dict:
x = x.copy()
for k, v in x.items():
typ = type(v)
if typ is dict or typ is list:
x[k] = replace_inner(v)
elif typ is Serialize:
x[k] = v.data
elif typ is Serialized:
x[k] = deserialize(v.header, v.frames)
elif type(x) is list:
x = list(x)
for k, v in enumerate(x):
typ = type(v)
if typ is dict or typ is list:
x[k] = replace_inner(v)
elif typ is Serialize:
x[k] = v.data
elif typ is Serialized:
x[k] = deserialize(v.header, v.frames)
return x
return replace_inner(x)
def serialize_bytelist(x, **kwargs):
header, frames = serialize(x, **kwargs)
frames = sum(map(frame_split_size, frames), [])
if frames:
compression, frames = zip(*map(maybe_compress, frames))
else:
compression = []
header["compression"] = compression
header["count"] = len(frames)
header = msgpack.dumps(header, use_bin_type=True)
frames2 = [header] + list(frames)
return [pack_frames_prelude(frames2)] + frames2
def serialize_bytes(x, **kwargs):
L = serialize_bytelist(x, **kwargs)
return b"".join(L)
def deserialize_bytes(b):
frames = unpack_frames(b)
header, frames = frames[0], frames[1:]
if header:
header = msgpack.loads(header, raw=False, use_list=False)
else:
header = {}
frames = decompress(header, frames)
return deserialize(header, frames)
################################
# Class specific serialization #
################################
def register_serialization(cls, serialize, deserialize):
""" Register a new class for dask-custom serialization
Parameters
----------
cls: type
serialize: callable(cls) -> Tuple[Dict, List[bytes]]
deserialize: callable(header: Dict, frames: List[bytes]) -> cls
Examples
--------
>>> class Human:
... def __init__(self, name):
... self.name = name
>>> def serialize(human):
... header = {}
... frames = [human.name.encode()]
... return header, frames
>>> def deserialize(header, frames):
... return Human(frames[0].decode())
>>> register_serialization(Human, serialize, deserialize)
>>> serialize(Human('Alice'))
({}, [b'Alice'])
See Also
--------
serialize
deserialize
"""
if isinstance(cls, str):
raise TypeError(
"Strings are no longer accepted for type registration. "
"Use dask_serialize.register_lazy instead"
)
dask_serialize.register(cls)(serialize)
dask_deserialize.register(cls)(deserialize)
def register_serialization_lazy(toplevel, func):
"""Register a registration function to be called if *toplevel*
module is ever loaded.
"""
raise Exception("Serialization registration has changed. See documentation")
@partial(normalize_token.register, Serialized)
def normalize_Serialized(o):
return [o.header] + o.frames # for dask.base.tokenize
# Teach serialize how to handle bytestrings
@dask_serialize.register((bytes, bytearray, memoryview))
def _serialize_bytes(obj):
header = {} # no special metadata
frames = [obj]
return header, frames
@dask_deserialize.register((bytes, bytearray))
def _deserialize_bytes(header, frames):
return b"".join(frames)
@dask_deserialize.register(memoryview)
def _serialize_memoryview(header, frames):
if len(frames) == 1:
out = frames[0]
else:
out = b"".join(frames)
return memoryview(out)
#########################
# Descend into __dict__ #
#########################
def _is_msgpack_serializable(v):
typ = type(v)
return (
v is None
or typ is str
or typ is bool
or typ is int
or typ is float
or isinstance(v, dict)
and all(map(_is_msgpack_serializable, v.values()))
and all(typ is str for x in v.keys())
or isinstance(v, (list, tuple))
and all(map(_is_msgpack_serializable, v))
)
class ObjectDictSerializer:
def __init__(self, serializer):
self.serializer = serializer
def serialize(self, est):
header = {
"serializer": self.serializer,
"type-serialized": pickle.dumps(type(est)),
"simple": {},
"complex": {},
}
frames = []
if isinstance(est, dict):
d = est
else:
d = est.__dict__
for k, v in d.items():
if _is_msgpack_serializable(v):
header["simple"][k] = v
else:
if isinstance(v, dict):
h, f = self.serialize(v)
else:
h, f = serialize(v, serializers=(self.serializer, "pickle"))
header["complex"][k] = {
"header": h,
"start": len(frames),
"stop": len(frames) + len(f),
}
frames += f
return header, frames
def deserialize(self, header, frames):
cls = pickle.loads(header["type-serialized"])
if issubclass(cls, dict):
dd = obj = {}
else:
obj = object.__new__(cls)
dd = obj.__dict__
dd.update(header["simple"])
for k, d in header["complex"].items():
h = d["header"]
f = frames[d["start"] : d["stop"]]
v = deserialize(h, f)
dd[k] = v
return obj
dask_object_with_dict_serializer = ObjectDictSerializer("dask")
dask_deserialize.register(dict)(dask_object_with_dict_serializer.deserialize)
def register_generic(
cls,
serializer_name="dask",
serialize_func=dask_serialize,
deserialize_func=dask_deserialize,
):
""" Register (de)serialize to traverse through __dict__
Normally when registering new classes for Dask's custom serialization you
need to manage headers and frames, which can be tedious. If all you want
to do is traverse through your object and apply serialize to all of your
object's attributes then this function may provide an easier path.
This registers a class for the custom Dask serialization family. It
serializes it by traversing through its __dict__ of attributes and applying
``serialize`` and ``deserialize`` recursively. It collects a set of frames
and keeps small attributes in the header. Deserialization reverses this
process.
This is a good idea if the following hold:
1. Most of the bytes of your object are composed of data types that Dask's
custom serializtion already handles well, like Numpy arrays.
2. Your object doesn't require any special constructor logic, other than
object.__new__(cls)
Examples
--------
>>> import sklearn.base
>>> from distributed.protocol import register_generic
>>> register_generic(sklearn.base.BaseEstimator)
See Also
--------
dask_serialize
dask_deserialize
"""
object_with_dict_serializer = ObjectDictSerializer(serializer_name)
serialize_func.register(cls)(object_with_dict_serializer.serialize)
deserialize_func.register(cls)(object_with_dict_serializer.deserialize)
| {
"repo_name": "blaze/distributed",
"path": "distributed/protocol/serialize.py",
"copies": "1",
"size": "20531",
"license": "bsd-3-clause",
"hash": -7413562569297898000,
"line_mean": 28.2881597718,
"line_max": 85,
"alpha_frac": 0.5752277044,
"autogenerated": false,
"ratio": 4.138480145132029,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00020824349797757795,
"num_lines": 701
} |
from functools import partial
import unittest
from scrapy.http import HtmlResponse
from scrapy.item import Item, Field
from scrapy.loader import ItemLoader
from scrapy.loader.processors import (Compose, Identity, Join,
MapCompose, SelectJmes, TakeFirst)
from scrapy.selector import Selector
# test items
class NameItem(Item):
name = Field()
class TestItem(NameItem):
url = Field()
summary = Field()
class TestNestedItem(Item):
name = Field()
name_div = Field()
name_value = Field()
url = Field()
image = Field()
# test item loaders
class NameItemLoader(ItemLoader):
default_item_class = TestItem
class NestedItemLoader(ItemLoader):
default_item_class = TestNestedItem
class TestItemLoader(NameItemLoader):
name_in = MapCompose(lambda v: v.title())
class DefaultedItemLoader(NameItemLoader):
default_input_processor = MapCompose(lambda v: v[:-1])
# test processors
def processor_with_args(value, other=None, loader_context=None):
if 'key' in loader_context:
return loader_context['key']
return value
class BasicItemLoaderTest(unittest.TestCase):
def test_load_item_using_default_loader(self):
i = TestItem()
i['summary'] = u'lala'
il = ItemLoader(item=i)
il.add_value('name', u'marta')
item = il.load_item()
assert item is i
self.assertEqual(item['summary'], [u'lala'])
self.assertEqual(item['name'], [u'marta'])
def test_load_item_using_custom_loader(self):
il = TestItemLoader()
il.add_value('name', u'marta')
item = il.load_item()
self.assertEqual(item['name'], [u'Marta'])
def test_load_item_ignore_none_field_values(self):
def validate_sku(value):
# Let's assume a SKU is only digits.
if value.isdigit():
return value
class MyLoader(ItemLoader):
name_out = Compose(lambda vs: vs[0]) # take first which allows empty values
price_out = Compose(TakeFirst(), float)
sku_out = Compose(TakeFirst(), validate_sku)
valid_fragment = u'SKU: 1234'
invalid_fragment = u'SKU: not available'
sku_re = 'SKU: (.+)'
il = MyLoader(item={})
# Should not return "sku: None".
il.add_value('sku', [invalid_fragment], re=sku_re)
# Should not ignore empty values.
il.add_value('name', u'')
il.add_value('price', [u'0'])
self.assertEqual(il.load_item(), {
'name': u'',
'price': 0.0,
})
il.replace_value('sku', [valid_fragment], re=sku_re)
self.assertEqual(il.load_item()['sku'], u'1234')
def test_self_referencing_loader(self):
class MyLoader(ItemLoader):
url_out = TakeFirst()
def img_url_out(self, values):
return (self.get_output_value('url') or '') + values[0]
il = MyLoader(item={})
il.add_value('url', 'http://example.com/')
il.add_value('img_url', '1234.png')
self.assertEqual(il.load_item(), {
'url': 'http://example.com/',
'img_url': 'http://example.com/1234.png',
})
il = MyLoader(item={})
il.add_value('img_url', '1234.png')
self.assertEqual(il.load_item(), {
'img_url': '1234.png',
})
def test_add_value(self):
il = TestItemLoader()
il.add_value('name', u'marta')
self.assertEqual(il.get_collected_values('name'), [u'Marta'])
self.assertEqual(il.get_output_value('name'), [u'Marta'])
il.add_value('name', u'pepe')
self.assertEqual(il.get_collected_values('name'), [u'Marta', u'Pepe'])
self.assertEqual(il.get_output_value('name'), [u'Marta', u'Pepe'])
# test add object value
il.add_value('summary', {'key': 1})
self.assertEqual(il.get_collected_values('summary'), [{'key': 1}])
il.add_value(None, u'Jim', lambda x: {'name': x})
self.assertEqual(il.get_collected_values('name'), [u'Marta', u'Pepe', u'Jim'])
def test_add_zero(self):
il = NameItemLoader()
il.add_value('name', 0)
self.assertEqual(il.get_collected_values('name'), [0])
def test_replace_value(self):
il = TestItemLoader()
il.replace_value('name', u'marta')
self.assertEqual(il.get_collected_values('name'), [u'Marta'])
self.assertEqual(il.get_output_value('name'), [u'Marta'])
il.replace_value('name', u'pepe')
self.assertEqual(il.get_collected_values('name'), [u'Pepe'])
self.assertEqual(il.get_output_value('name'), [u'Pepe'])
il.replace_value(None, u'Jim', lambda x: {'name': x})
self.assertEqual(il.get_collected_values('name'), [u'Jim'])
def test_get_value(self):
il = NameItemLoader()
self.assertEqual(u'FOO', il.get_value([u'foo', u'bar'], TakeFirst(), str.upper))
self.assertEqual([u'foo', u'bar'], il.get_value([u'name:foo', u'name:bar'], re=u'name:(.*)$'))
self.assertEqual(u'foo', il.get_value([u'name:foo', u'name:bar'], TakeFirst(), re=u'name:(.*)$'))
il.add_value('name', [u'name:foo', u'name:bar'], TakeFirst(), re=u'name:(.*)$')
self.assertEqual([u'foo'], il.get_collected_values('name'))
il.replace_value('name', u'name:bar', re=u'name:(.*)$')
self.assertEqual([u'bar'], il.get_collected_values('name'))
def test_iter_on_input_processor_input(self):
class NameFirstItemLoader(NameItemLoader):
name_in = TakeFirst()
il = NameFirstItemLoader()
il.add_value('name', u'marta')
self.assertEqual(il.get_collected_values('name'), [u'marta'])
il = NameFirstItemLoader()
il.add_value('name', [u'marta', u'jose'])
self.assertEqual(il.get_collected_values('name'), [u'marta'])
il = NameFirstItemLoader()
il.replace_value('name', u'marta')
self.assertEqual(il.get_collected_values('name'), [u'marta'])
il = NameFirstItemLoader()
il.replace_value('name', [u'marta', u'jose'])
self.assertEqual(il.get_collected_values('name'), [u'marta'])
il = NameFirstItemLoader()
il.add_value('name', u'marta')
il.add_value('name', [u'jose', u'pedro'])
self.assertEqual(il.get_collected_values('name'), [u'marta', u'jose'])
def test_map_compose_filter(self):
def filter_world(x):
return None if x == 'world' else x
proc = MapCompose(filter_world, str.upper)
self.assertEqual(proc(['hello', 'world', 'this', 'is', 'scrapy']),
['HELLO', 'THIS', 'IS', 'SCRAPY'])
def test_map_compose_filter_multil(self):
class TestItemLoader(NameItemLoader):
name_in = MapCompose(lambda v: v.title(), lambda v: v[:-1])
il = TestItemLoader()
il.add_value('name', u'marta')
self.assertEqual(il.get_output_value('name'), [u'Mart'])
item = il.load_item()
self.assertEqual(item['name'], [u'Mart'])
def test_default_input_processor(self):
il = DefaultedItemLoader()
il.add_value('name', u'marta')
self.assertEqual(il.get_output_value('name'), [u'mart'])
def test_inherited_default_input_processor(self):
class InheritDefaultedItemLoader(DefaultedItemLoader):
pass
il = InheritDefaultedItemLoader()
il.add_value('name', u'marta')
self.assertEqual(il.get_output_value('name'), [u'mart'])
def test_input_processor_inheritance(self):
class ChildItemLoader(TestItemLoader):
url_in = MapCompose(lambda v: v.lower())
il = ChildItemLoader()
il.add_value('url', u'HTTP://scrapy.ORG')
self.assertEqual(il.get_output_value('url'), [u'http://scrapy.org'])
il.add_value('name', u'marta')
self.assertEqual(il.get_output_value('name'), [u'Marta'])
class ChildChildItemLoader(ChildItemLoader):
url_in = MapCompose(lambda v: v.upper())
summary_in = MapCompose(lambda v: v)
il = ChildChildItemLoader()
il.add_value('url', u'http://scrapy.org')
self.assertEqual(il.get_output_value('url'), [u'HTTP://SCRAPY.ORG'])
il.add_value('name', u'marta')
self.assertEqual(il.get_output_value('name'), [u'Marta'])
def test_empty_map_compose(self):
class IdentityDefaultedItemLoader(DefaultedItemLoader):
name_in = MapCompose()
il = IdentityDefaultedItemLoader()
il.add_value('name', u'marta')
self.assertEqual(il.get_output_value('name'), [u'marta'])
def test_identity_input_processor(self):
class IdentityDefaultedItemLoader(DefaultedItemLoader):
name_in = Identity()
il = IdentityDefaultedItemLoader()
il.add_value('name', u'marta')
self.assertEqual(il.get_output_value('name'), [u'marta'])
def test_extend_custom_input_processors(self):
class ChildItemLoader(TestItemLoader):
name_in = MapCompose(TestItemLoader.name_in, str.swapcase)
il = ChildItemLoader()
il.add_value('name', u'marta')
self.assertEqual(il.get_output_value('name'), [u'mARTA'])
def test_extend_default_input_processors(self):
class ChildDefaultedItemLoader(DefaultedItemLoader):
name_in = MapCompose(DefaultedItemLoader.default_input_processor, str.swapcase)
il = ChildDefaultedItemLoader()
il.add_value('name', u'marta')
self.assertEqual(il.get_output_value('name'), [u'MART'])
def test_output_processor_using_function(self):
il = TestItemLoader()
il.add_value('name', [u'mar', u'ta'])
self.assertEqual(il.get_output_value('name'), [u'Mar', u'Ta'])
class TakeFirstItemLoader(TestItemLoader):
name_out = u" ".join
il = TakeFirstItemLoader()
il.add_value('name', [u'mar', u'ta'])
self.assertEqual(il.get_output_value('name'), u'Mar Ta')
def test_output_processor_error(self):
class TestItemLoader(ItemLoader):
default_item_class = TestItem
name_out = MapCompose(float)
il = TestItemLoader()
il.add_value('name', [u'$10'])
try:
float(u'$10')
except Exception as e:
expected_exc_str = str(e)
exc = None
try:
il.load_item()
except Exception as e:
exc = e
assert isinstance(exc, ValueError)
s = str(exc)
assert 'name' in s, s
assert '$10' in s, s
assert 'ValueError' in s, s
assert expected_exc_str in s, s
def test_output_processor_using_classes(self):
il = TestItemLoader()
il.add_value('name', [u'mar', u'ta'])
self.assertEqual(il.get_output_value('name'), [u'Mar', u'Ta'])
class TakeFirstItemLoader(TestItemLoader):
name_out = Join()
il = TakeFirstItemLoader()
il.add_value('name', [u'mar', u'ta'])
self.assertEqual(il.get_output_value('name'), u'Mar Ta')
class TakeFirstItemLoader(TestItemLoader):
name_out = Join("<br>")
il = TakeFirstItemLoader()
il.add_value('name', [u'mar', u'ta'])
self.assertEqual(il.get_output_value('name'), u'Mar<br>Ta')
def test_default_output_processor(self):
il = TestItemLoader()
il.add_value('name', [u'mar', u'ta'])
self.assertEqual(il.get_output_value('name'), [u'Mar', u'Ta'])
class LalaItemLoader(TestItemLoader):
default_output_processor = Identity()
il = LalaItemLoader()
il.add_value('name', [u'mar', u'ta'])
self.assertEqual(il.get_output_value('name'), [u'Mar', u'Ta'])
def test_loader_context_on_declaration(self):
class ChildItemLoader(TestItemLoader):
url_in = MapCompose(processor_with_args, key=u'val')
il = ChildItemLoader()
il.add_value('url', u'text')
self.assertEqual(il.get_output_value('url'), ['val'])
il.replace_value('url', u'text2')
self.assertEqual(il.get_output_value('url'), ['val'])
def test_loader_context_on_instantiation(self):
class ChildItemLoader(TestItemLoader):
url_in = MapCompose(processor_with_args)
il = ChildItemLoader(key=u'val')
il.add_value('url', u'text')
self.assertEqual(il.get_output_value('url'), ['val'])
il.replace_value('url', u'text2')
self.assertEqual(il.get_output_value('url'), ['val'])
def test_loader_context_on_assign(self):
class ChildItemLoader(TestItemLoader):
url_in = MapCompose(processor_with_args)
il = ChildItemLoader()
il.context['key'] = u'val'
il.add_value('url', u'text')
self.assertEqual(il.get_output_value('url'), ['val'])
il.replace_value('url', u'text2')
self.assertEqual(il.get_output_value('url'), ['val'])
def test_item_passed_to_input_processor_functions(self):
def processor(value, loader_context):
return loader_context['item']['name']
class ChildItemLoader(TestItemLoader):
url_in = MapCompose(processor)
it = TestItem(name='marta')
il = ChildItemLoader(item=it)
il.add_value('url', u'text')
self.assertEqual(il.get_output_value('url'), ['marta'])
il.replace_value('url', u'text2')
self.assertEqual(il.get_output_value('url'), ['marta'])
def test_add_value_on_unknown_field(self):
il = TestItemLoader()
self.assertRaises(KeyError, il.add_value, 'wrong_field', [u'lala', u'lolo'])
def test_compose_processor(self):
class TestItemLoader(NameItemLoader):
name_out = Compose(lambda v: v[0], lambda v: v.title(), lambda v: v[:-1])
il = TestItemLoader()
il.add_value('name', [u'marta', u'other'])
self.assertEqual(il.get_output_value('name'), u'Mart')
item = il.load_item()
self.assertEqual(item['name'], u'Mart')
def test_partial_processor(self):
def join(values, sep=None, loader_context=None, ignored=None):
if sep is not None:
return sep.join(values)
elif loader_context and 'sep' in loader_context:
return loader_context['sep'].join(values)
else:
return ''.join(values)
class TestItemLoader(NameItemLoader):
name_out = Compose(partial(join, sep='+'))
url_out = Compose(partial(join, loader_context={'sep': '.'}))
summary_out = Compose(partial(join, ignored='foo'))
il = TestItemLoader()
il.add_value('name', [u'rabbit', u'hole'])
il.add_value('url', [u'rabbit', u'hole'])
il.add_value('summary', [u'rabbit', u'hole'])
item = il.load_item()
self.assertEqual(item['name'], u'rabbit+hole')
self.assertEqual(item['url'], u'rabbit.hole')
self.assertEqual(item['summary'], u'rabbithole')
def test_error_input_processor(self):
class TestItem(Item):
name = Field()
class TestItemLoader(ItemLoader):
default_item_class = TestItem
name_in = MapCompose(float)
il = TestItemLoader()
self.assertRaises(ValueError, il.add_value, 'name',
[u'marta', u'other'])
def test_error_output_processor(self):
class TestItem(Item):
name = Field()
class TestItemLoader(ItemLoader):
default_item_class = TestItem
name_out = Compose(Join(), float)
il = TestItemLoader()
il.add_value('name', u'marta')
with self.assertRaises(ValueError):
il.load_item()
def test_error_processor_as_argument(self):
class TestItem(Item):
name = Field()
class TestItemLoader(ItemLoader):
default_item_class = TestItem
il = TestItemLoader()
self.assertRaises(ValueError, il.add_value, 'name',
[u'marta', u'other'], Compose(float))
class InitializationTestMixin(object):
item_class = None
def test_keep_single_value(self):
"""Loaded item should contain values from the initial item"""
input_item = self.item_class(name='foo')
il = ItemLoader(item=input_item)
loaded_item = il.load_item()
self.assertIsInstance(loaded_item, self.item_class)
self.assertEqual(dict(loaded_item), {'name': ['foo']})
def test_keep_list(self):
"""Loaded item should contain values from the initial item"""
input_item = self.item_class(name=['foo', 'bar'])
il = ItemLoader(item=input_item)
loaded_item = il.load_item()
self.assertIsInstance(loaded_item, self.item_class)
self.assertEqual(dict(loaded_item), {'name': ['foo', 'bar']})
def test_add_value_singlevalue_singlevalue(self):
"""Values added after initialization should be appended"""
input_item = self.item_class(name='foo')
il = ItemLoader(item=input_item)
il.add_value('name', 'bar')
loaded_item = il.load_item()
self.assertIsInstance(loaded_item, self.item_class)
self.assertEqual(dict(loaded_item), {'name': ['foo', 'bar']})
def test_add_value_singlevalue_list(self):
"""Values added after initialization should be appended"""
input_item = self.item_class(name='foo')
il = ItemLoader(item=input_item)
il.add_value('name', ['item', 'loader'])
loaded_item = il.load_item()
self.assertIsInstance(loaded_item, self.item_class)
self.assertEqual(dict(loaded_item), {'name': ['foo', 'item', 'loader']})
def test_add_value_list_singlevalue(self):
"""Values added after initialization should be appended"""
input_item = self.item_class(name=['foo', 'bar'])
il = ItemLoader(item=input_item)
il.add_value('name', 'qwerty')
loaded_item = il.load_item()
self.assertIsInstance(loaded_item, self.item_class)
self.assertEqual(dict(loaded_item), {'name': ['foo', 'bar', 'qwerty']})
def test_add_value_list_list(self):
"""Values added after initialization should be appended"""
input_item = self.item_class(name=['foo', 'bar'])
il = ItemLoader(item=input_item)
il.add_value('name', ['item', 'loader'])
loaded_item = il.load_item()
self.assertIsInstance(loaded_item, self.item_class)
self.assertEqual(dict(loaded_item), {'name': ['foo', 'bar', 'item', 'loader']})
def test_get_output_value_singlevalue(self):
"""Getting output value must not remove value from item"""
input_item = self.item_class(name='foo')
il = ItemLoader(item=input_item)
self.assertEqual(il.get_output_value('name'), ['foo'])
loaded_item = il.load_item()
self.assertIsInstance(loaded_item, self.item_class)
self.assertEqual(loaded_item, dict({'name': ['foo']}))
def test_get_output_value_list(self):
"""Getting output value must not remove value from item"""
input_item = self.item_class(name=['foo', 'bar'])
il = ItemLoader(item=input_item)
self.assertEqual(il.get_output_value('name'), ['foo', 'bar'])
loaded_item = il.load_item()
self.assertIsInstance(loaded_item, self.item_class)
self.assertEqual(loaded_item, dict({'name': ['foo', 'bar']}))
def test_values_single(self):
"""Values from initial item must be added to loader._values"""
input_item = self.item_class(name='foo')
il = ItemLoader(item=input_item)
self.assertEqual(il._values.get('name'), ['foo'])
def test_values_list(self):
"""Values from initial item must be added to loader._values"""
input_item = self.item_class(name=['foo', 'bar'])
il = ItemLoader(item=input_item)
self.assertEqual(il._values.get('name'), ['foo', 'bar'])
class InitializationFromDictTest(InitializationTestMixin, unittest.TestCase):
item_class = dict
class InitializationFromItemTest(InitializationTestMixin, unittest.TestCase):
item_class = NameItem
class BaseNoInputReprocessingLoader(ItemLoader):
title_in = MapCompose(str.upper)
title_out = TakeFirst()
class NoInputReprocessingDictLoader(BaseNoInputReprocessingLoader):
default_item_class = dict
class NoInputReprocessingFromDictTest(unittest.TestCase):
"""
Loaders initialized from loaded items must not reprocess fields (dict instances)
"""
def test_avoid_reprocessing_with_initial_values_single(self):
il = NoInputReprocessingDictLoader(item=dict(title='foo'))
il_loaded = il.load_item()
self.assertEqual(il_loaded, dict(title='foo'))
self.assertEqual(NoInputReprocessingDictLoader(item=il_loaded).load_item(), dict(title='foo'))
def test_avoid_reprocessing_with_initial_values_list(self):
il = NoInputReprocessingDictLoader(item=dict(title=['foo', 'bar']))
il_loaded = il.load_item()
self.assertEqual(il_loaded, dict(title='foo'))
self.assertEqual(NoInputReprocessingDictLoader(item=il_loaded).load_item(), dict(title='foo'))
def test_avoid_reprocessing_without_initial_values_single(self):
il = NoInputReprocessingDictLoader()
il.add_value('title', 'foo')
il_loaded = il.load_item()
self.assertEqual(il_loaded, dict(title='FOO'))
self.assertEqual(NoInputReprocessingDictLoader(item=il_loaded).load_item(), dict(title='FOO'))
def test_avoid_reprocessing_without_initial_values_list(self):
il = NoInputReprocessingDictLoader()
il.add_value('title', ['foo', 'bar'])
il_loaded = il.load_item()
self.assertEqual(il_loaded, dict(title='FOO'))
self.assertEqual(NoInputReprocessingDictLoader(item=il_loaded).load_item(), dict(title='FOO'))
class NoInputReprocessingItem(Item):
title = Field()
class NoInputReprocessingItemLoader(BaseNoInputReprocessingLoader):
default_item_class = NoInputReprocessingItem
class NoInputReprocessingFromItemTest(unittest.TestCase):
"""
Loaders initialized from loaded items must not reprocess fields (BaseItem instances)
"""
def test_avoid_reprocessing_with_initial_values_single(self):
il = NoInputReprocessingItemLoader(item=NoInputReprocessingItem(title='foo'))
il_loaded = il.load_item()
self.assertEqual(il_loaded, {'title': 'foo'})
self.assertEqual(NoInputReprocessingItemLoader(item=il_loaded).load_item(), {'title': 'foo'})
def test_avoid_reprocessing_with_initial_values_list(self):
il = NoInputReprocessingItemLoader(item=NoInputReprocessingItem(title=['foo', 'bar']))
il_loaded = il.load_item()
self.assertEqual(il_loaded, {'title': 'foo'})
self.assertEqual(NoInputReprocessingItemLoader(item=il_loaded).load_item(), {'title': 'foo'})
def test_avoid_reprocessing_without_initial_values_single(self):
il = NoInputReprocessingItemLoader()
il.add_value('title', 'FOO')
il_loaded = il.load_item()
self.assertEqual(il_loaded, {'title': 'FOO'})
self.assertEqual(NoInputReprocessingItemLoader(item=il_loaded).load_item(), {'title': 'FOO'})
def test_avoid_reprocessing_without_initial_values_list(self):
il = NoInputReprocessingItemLoader()
il.add_value('title', ['foo', 'bar'])
il_loaded = il.load_item()
self.assertEqual(il_loaded, {'title': 'FOO'})
self.assertEqual(NoInputReprocessingItemLoader(item=il_loaded).load_item(), {'title': 'FOO'})
class TestOutputProcessorDict(unittest.TestCase):
def test_output_processor(self):
class TempDict(dict):
def __init__(self, *args, **kwargs):
super(TempDict, self).__init__(self, *args, **kwargs)
self.setdefault('temp', 0.3)
class TempLoader(ItemLoader):
default_item_class = TempDict
default_input_processor = Identity()
default_output_processor = Compose(TakeFirst())
loader = TempLoader()
item = loader.load_item()
self.assertIsInstance(item, TempDict)
self.assertEqual(dict(item), {'temp': 0.3})
class TestOutputProcessorItem(unittest.TestCase):
def test_output_processor(self):
class TempItem(Item):
temp = Field()
def __init__(self, *args, **kwargs):
super(TempItem, self).__init__(self, *args, **kwargs)
self.setdefault('temp', 0.3)
class TempLoader(ItemLoader):
default_item_class = TempItem
default_input_processor = Identity()
default_output_processor = Compose(TakeFirst())
loader = TempLoader()
item = loader.load_item()
self.assertIsInstance(item, TempItem)
self.assertEqual(dict(item), {'temp': 0.3})
class ProcessorsTest(unittest.TestCase):
def test_take_first(self):
proc = TakeFirst()
self.assertEqual(proc([None, '', 'hello', 'world']), 'hello')
self.assertEqual(proc([None, '', 0, 'hello', 'world']), 0)
def test_identity(self):
proc = Identity()
self.assertEqual(proc([None, '', 'hello', 'world']),
[None, '', 'hello', 'world'])
def test_join(self):
proc = Join()
self.assertRaises(TypeError, proc, [None, '', 'hello', 'world'])
self.assertEqual(proc(['', 'hello', 'world']), u' hello world')
self.assertEqual(proc(['hello', 'world']), u'hello world')
self.assertIsInstance(proc(['hello', 'world']), str)
def test_compose(self):
proc = Compose(lambda v: v[0], str.upper)
self.assertEqual(proc(['hello', 'world']), 'HELLO')
proc = Compose(str.upper)
self.assertEqual(proc(None), None)
proc = Compose(str.upper, stop_on_none=False)
self.assertRaises(ValueError, proc, None)
proc = Compose(str.upper, lambda x: x + 1)
self.assertRaises(ValueError, proc, 'hello')
def test_mapcompose(self):
def filter_world(x):
return None if x == 'world' else x
proc = MapCompose(filter_world, str.upper)
self.assertEqual(proc([u'hello', u'world', u'this', u'is', u'scrapy']),
[u'HELLO', u'THIS', u'IS', u'SCRAPY'])
proc = MapCompose(filter_world, str.upper)
self.assertEqual(proc(None), [])
proc = MapCompose(filter_world, str.upper)
self.assertRaises(ValueError, proc, [1])
proc = MapCompose(filter_world, lambda x: x + 1)
self.assertRaises(ValueError, proc, 'hello')
class SelectortemLoaderTest(unittest.TestCase):
response = HtmlResponse(url="", encoding='utf-8', body=b"""
<html>
<body>
<div id="id">marta</div>
<p>paragraph</p>
<a href="http://www.scrapy.org">homepage</a>
<img src="/images/logo.png" width="244" height="65" alt="Scrapy">
</body>
</html>
""")
def test_init_method(self):
l = TestItemLoader()
self.assertEqual(l.selector, None)
def test_init_method_errors(self):
l = TestItemLoader()
self.assertRaises(RuntimeError, l.add_xpath, 'url', '//a/@href')
self.assertRaises(RuntimeError, l.replace_xpath, 'url', '//a/@href')
self.assertRaises(RuntimeError, l.get_xpath, '//a/@href')
self.assertRaises(RuntimeError, l.add_css, 'name', '#name::text')
self.assertRaises(RuntimeError, l.replace_css, 'name', '#name::text')
self.assertRaises(RuntimeError, l.get_css, '#name::text')
def test_init_method_with_selector(self):
sel = Selector(text=u"<html><body><div>marta</div></body></html>")
l = TestItemLoader(selector=sel)
self.assertIs(l.selector, sel)
l.add_xpath('name', '//div/text()')
self.assertEqual(l.get_output_value('name'), [u'Marta'])
def test_init_method_with_selector_css(self):
sel = Selector(text=u"<html><body><div>marta</div></body></html>")
l = TestItemLoader(selector=sel)
self.assertIs(l.selector, sel)
l.add_css('name', 'div::text')
self.assertEqual(l.get_output_value('name'), [u'Marta'])
def test_init_method_with_response(self):
l = TestItemLoader(response=self.response)
self.assertTrue(l.selector)
l.add_xpath('name', '//div/text()')
self.assertEqual(l.get_output_value('name'), [u'Marta'])
def test_init_method_with_response_css(self):
l = TestItemLoader(response=self.response)
self.assertTrue(l.selector)
l.add_css('name', 'div::text')
self.assertEqual(l.get_output_value('name'), [u'Marta'])
l.add_css('url', 'a::attr(href)')
self.assertEqual(l.get_output_value('url'), [u'http://www.scrapy.org'])
# combining/accumulating CSS selectors and XPath expressions
l.add_xpath('name', '//div/text()')
self.assertEqual(l.get_output_value('name'), [u'Marta', u'Marta'])
l.add_xpath('url', '//img/@src')
self.assertEqual(l.get_output_value('url'), [u'http://www.scrapy.org', u'/images/logo.png'])
def test_add_xpath_re(self):
l = TestItemLoader(response=self.response)
l.add_xpath('name', '//div/text()', re='ma')
self.assertEqual(l.get_output_value('name'), [u'Ma'])
def test_replace_xpath(self):
l = TestItemLoader(response=self.response)
self.assertTrue(l.selector)
l.add_xpath('name', '//div/text()')
self.assertEqual(l.get_output_value('name'), [u'Marta'])
l.replace_xpath('name', '//p/text()')
self.assertEqual(l.get_output_value('name'), [u'Paragraph'])
l.replace_xpath('name', ['//p/text()', '//div/text()'])
self.assertEqual(l.get_output_value('name'), [u'Paragraph', 'Marta'])
def test_get_xpath(self):
l = TestItemLoader(response=self.response)
self.assertEqual(l.get_xpath('//p/text()'), [u'paragraph'])
self.assertEqual(l.get_xpath('//p/text()', TakeFirst()), u'paragraph')
self.assertEqual(l.get_xpath('//p/text()', TakeFirst(), re='pa'), u'pa')
self.assertEqual(l.get_xpath(['//p/text()', '//div/text()']), [u'paragraph', 'marta'])
def test_replace_xpath_multi_fields(self):
l = TestItemLoader(response=self.response)
l.add_xpath(None, '//div/text()', TakeFirst(), lambda x: {'name': x})
self.assertEqual(l.get_output_value('name'), [u'Marta'])
l.replace_xpath(None, '//p/text()', TakeFirst(), lambda x: {'name': x})
self.assertEqual(l.get_output_value('name'), [u'Paragraph'])
def test_replace_xpath_re(self):
l = TestItemLoader(response=self.response)
self.assertTrue(l.selector)
l.add_xpath('name', '//div/text()')
self.assertEqual(l.get_output_value('name'), [u'Marta'])
l.replace_xpath('name', '//div/text()', re='ma')
self.assertEqual(l.get_output_value('name'), [u'Ma'])
def test_add_css_re(self):
l = TestItemLoader(response=self.response)
l.add_css('name', 'div::text', re='ma')
self.assertEqual(l.get_output_value('name'), [u'Ma'])
l.add_css('url', 'a::attr(href)', re='http://(.+)')
self.assertEqual(l.get_output_value('url'), [u'www.scrapy.org'])
def test_replace_css(self):
l = TestItemLoader(response=self.response)
self.assertTrue(l.selector)
l.add_css('name', 'div::text')
self.assertEqual(l.get_output_value('name'), [u'Marta'])
l.replace_css('name', 'p::text')
self.assertEqual(l.get_output_value('name'), [u'Paragraph'])
l.replace_css('name', ['p::text', 'div::text'])
self.assertEqual(l.get_output_value('name'), [u'Paragraph', 'Marta'])
l.add_css('url', 'a::attr(href)', re='http://(.+)')
self.assertEqual(l.get_output_value('url'), [u'www.scrapy.org'])
l.replace_css('url', 'img::attr(src)')
self.assertEqual(l.get_output_value('url'), [u'/images/logo.png'])
def test_get_css(self):
l = TestItemLoader(response=self.response)
self.assertEqual(l.get_css('p::text'), [u'paragraph'])
self.assertEqual(l.get_css('p::text', TakeFirst()), u'paragraph')
self.assertEqual(l.get_css('p::text', TakeFirst(), re='pa'), u'pa')
self.assertEqual(l.get_css(['p::text', 'div::text']), [u'paragraph', 'marta'])
self.assertEqual(l.get_css(['a::attr(href)', 'img::attr(src)']),
[u'http://www.scrapy.org', u'/images/logo.png'])
def test_replace_css_multi_fields(self):
l = TestItemLoader(response=self.response)
l.add_css(None, 'div::text', TakeFirst(), lambda x: {'name': x})
self.assertEqual(l.get_output_value('name'), [u'Marta'])
l.replace_css(None, 'p::text', TakeFirst(), lambda x: {'name': x})
self.assertEqual(l.get_output_value('name'), [u'Paragraph'])
l.add_css(None, 'a::attr(href)', TakeFirst(), lambda x: {'url': x})
self.assertEqual(l.get_output_value('url'), [u'http://www.scrapy.org'])
l.replace_css(None, 'img::attr(src)', TakeFirst(), lambda x: {'url': x})
self.assertEqual(l.get_output_value('url'), [u'/images/logo.png'])
def test_replace_css_re(self):
l = TestItemLoader(response=self.response)
self.assertTrue(l.selector)
l.add_css('url', 'a::attr(href)')
self.assertEqual(l.get_output_value('url'), [u'http://www.scrapy.org'])
l.replace_css('url', 'a::attr(href)', re=r'http://www\.(.+)')
self.assertEqual(l.get_output_value('url'), [u'scrapy.org'])
class SubselectorLoaderTest(unittest.TestCase):
response = HtmlResponse(url="", encoding='utf-8', body=b"""
<html>
<body>
<header>
<div id="id">marta</div>
<p>paragraph</p>
</header>
<footer class="footer">
<a href="http://www.scrapy.org">homepage</a>
<img src="/images/logo.png" width="244" height="65" alt="Scrapy">
</footer>
</body>
</html>
""")
def test_nested_xpath(self):
l = NestedItemLoader(response=self.response)
nl = l.nested_xpath("//header")
nl.add_xpath('name', 'div/text()')
nl.add_css('name_div', '#id')
nl.add_value('name_value', nl.selector.xpath('div[@id = "id"]/text()').getall())
self.assertEqual(l.get_output_value('name'), [u'marta'])
self.assertEqual(l.get_output_value('name_div'), [u'<div id="id">marta</div>'])
self.assertEqual(l.get_output_value('name_value'), [u'marta'])
self.assertEqual(l.get_output_value('name'), nl.get_output_value('name'))
self.assertEqual(l.get_output_value('name_div'), nl.get_output_value('name_div'))
self.assertEqual(l.get_output_value('name_value'), nl.get_output_value('name_value'))
def test_nested_css(self):
l = NestedItemLoader(response=self.response)
nl = l.nested_css("header")
nl.add_xpath('name', 'div/text()')
nl.add_css('name_div', '#id')
nl.add_value('name_value', nl.selector.xpath('div[@id = "id"]/text()').getall())
self.assertEqual(l.get_output_value('name'), [u'marta'])
self.assertEqual(l.get_output_value('name_div'), [u'<div id="id">marta</div>'])
self.assertEqual(l.get_output_value('name_value'), [u'marta'])
self.assertEqual(l.get_output_value('name'), nl.get_output_value('name'))
self.assertEqual(l.get_output_value('name_div'), nl.get_output_value('name_div'))
self.assertEqual(l.get_output_value('name_value'), nl.get_output_value('name_value'))
def test_nested_replace(self):
l = NestedItemLoader(response=self.response)
nl1 = l.nested_xpath('//footer')
nl2 = nl1.nested_xpath('a')
l.add_xpath('url', '//footer/a/@href')
self.assertEqual(l.get_output_value('url'), [u'http://www.scrapy.org'])
nl1.replace_xpath('url', 'img/@src')
self.assertEqual(l.get_output_value('url'), [u'/images/logo.png'])
nl2.replace_xpath('url', '@href')
self.assertEqual(l.get_output_value('url'), [u'http://www.scrapy.org'])
def test_nested_ordering(self):
l = NestedItemLoader(response=self.response)
nl1 = l.nested_xpath('//footer')
nl2 = nl1.nested_xpath('a')
nl1.add_xpath('url', 'img/@src')
l.add_xpath('url', '//footer/a/@href')
nl2.add_xpath('url', 'text()')
l.add_xpath('url', '//footer/a/@href')
self.assertEqual(l.get_output_value('url'), [
u'/images/logo.png',
u'http://www.scrapy.org',
u'homepage',
u'http://www.scrapy.org',
])
def test_nested_load_item(self):
l = NestedItemLoader(response=self.response)
nl1 = l.nested_xpath('//footer')
nl2 = nl1.nested_xpath('img')
l.add_xpath('name', '//header/div/text()')
nl1.add_xpath('url', 'a/@href')
nl2.add_xpath('image', '@src')
item = l.load_item()
assert item is l.item
assert item is nl1.item
assert item is nl2.item
self.assertEqual(item['name'], [u'marta'])
self.assertEqual(item['url'], [u'http://www.scrapy.org'])
self.assertEqual(item['image'], [u'/images/logo.png'])
class SelectJmesTestCase(unittest.TestCase):
test_list_equals = {
'simple': ('foo.bar', {"foo": {"bar": "baz"}}, "baz"),
'invalid': ('foo.bar.baz', {"foo": {"bar": "baz"}}, None),
'top_level': ('foo', {"foo": {"bar": "baz"}}, {"bar": "baz"}),
'double_vs_single_quote_string': ('foo.bar', {"foo": {"bar": "baz"}}, "baz"),
'dict': (
'foo.bar[*].name',
{"foo": {"bar": [{"name": "one"}, {"name": "two"}]}},
['one', 'two']
),
'list': ('[1]', [1, 2], 2)
}
def test_output(self):
for l in self.test_list_equals:
expr, test_list, expected = self.test_list_equals[l]
test = SelectJmes(expr)(test_list)
self.assertEqual(
test,
expected,
msg='test "{}" got {} expected {}'.format(l, test, expected)
)
# Functions as processors
def function_processor_strip(iterable):
return [x.strip() for x in iterable]
def function_processor_upper(iterable):
return [x.upper() for x in iterable]
class FunctionProcessorItem(Item):
foo = Field(
input_processor=function_processor_strip,
output_processor=function_processor_upper,
)
class FunctionProcessorItemLoader(ItemLoader):
default_item_class = FunctionProcessorItem
class FunctionProcessorDictLoader(ItemLoader):
default_item_class = dict
foo_in = function_processor_strip
foo_out = function_processor_upper
class FunctionProcessorTestCase(unittest.TestCase):
def test_processor_defined_in_item(self):
lo = FunctionProcessorItemLoader()
lo.add_value('foo', ' bar ')
lo.add_value('foo', [' asdf ', ' qwerty '])
self.assertEqual(
dict(lo.load_item()),
{'foo': ['BAR', 'ASDF', 'QWERTY']}
)
def test_processor_defined_in_item_loader(self):
lo = FunctionProcessorDictLoader()
lo.add_value('foo', ' bar ')
lo.add_value('foo', [' asdf ', ' qwerty '])
self.assertEqual(
dict(lo.load_item()),
{'foo': ['BAR', 'ASDF', 'QWERTY']}
)
if __name__ == "__main__":
unittest.main()
| {
"repo_name": "eLRuLL/scrapy",
"path": "tests/test_loader.py",
"copies": "1",
"size": "39747",
"license": "bsd-3-clause",
"hash": 1280485284570718500,
"line_mean": 37.0718390805,
"line_max": 105,
"alpha_frac": 0.5981835107,
"autogenerated": false,
"ratio": 3.4948562384595094,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.45930397491595093,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import unittest
import greenlet
import GreenletProfiler
def find_func(ystats, name):
items = [
yfuncstat for yfuncstat in ystats
if yfuncstat.name == name]
assert len(items) == 1
return items[0]
def assert_children(yfuncstats, names, msg):
names = set(names)
callees = set([
ychildstat.name for ychildstat in yfuncstats.children
])
final_msg = '%s: expected %s, got %s' % (
msg, ', '.join(names), ', '.join(callees))
assert names == callees, final_msg
def spin(n):
for _ in range(n * 10000):
pass
class GreenletTest(unittest.TestCase):
spin_cost = None
@classmethod
def setUpClass(cls):
# Measure the CPU cost of spin() as a baseline.
GreenletProfiler.set_clock_type('cpu')
GreenletProfiler.start()
for _ in range(10):
spin(1)
GreenletProfiler.stop()
f_stats = GreenletProfiler.get_func_stats()
spin_stat = find_func(f_stats, 'spin')
GreenletTest.spin_cost = spin_stat.ttot / 10.0
GreenletProfiler.clear_stats()
def tearDown(self):
GreenletProfiler.stop()
GreenletProfiler.clear_stats()
def assertNear(self, x, y, margin=0.2):
if abs(x - y) / float(x) > margin:
raise AssertionError(
"%s is not within %d%% of %s" % (x, margin * 100, y))
def test_three_levels(self):
def a():
gr_main.switch()
b()
spin(1)
def b():
spin(5)
gr_main.switch()
c()
def c():
spin(7)
GreenletProfiler.set_clock_type('cpu')
GreenletProfiler.start(builtins=True)
gr_main = greenlet.getcurrent()
g = greenlet.greenlet(a)
g.switch()
spin(2)
g.switch()
spin(3)
g.switch()
self.assertFalse(g, 'greenlet not complete')
GreenletProfiler.stop()
ystats = GreenletProfiler.get_func_stats()
# Check the stats for spin().
spin_stat = find_func(ystats, 'spin')
self.assertEqual(5, spin_stat.ncall)
self.assertAlmostEqual(18 * self.spin_cost, spin_stat.ttot,
places=2, msg="spin()'s total time is wrong")
assert_children(spin_stat, ['range'], 'spin() has wrong callees')
# Check the stats for a().
a_stat = find_func(ystats, 'a')
self.assertEqual(1, a_stat.ncall, 'a() not called once')
assert_children(
a_stat,
['spin', 'b', "<method 'switch' of 'greenlet.greenlet' objects>"],
'a() has wrong callees')
self.assertAlmostEqual(13 * self.spin_cost, a_stat.ttot,
places=2, msg="a()'s total time is wrong")
self.assertAlmostEqual(13 * self.spin_cost, a_stat.tavg,
places=2, msg="a()'s average time is wrong")
self.assertAlmostEqual(a_stat.tsub, 0,
places=2, msg="a()'s subtotal is wrong")
# Check the stats for b().
b_stat = find_func(ystats, 'b')
self.assertEqual(1, b_stat.ncall, 'b() not called once')
assert_children(
b_stat,
['spin', 'c', "<method 'switch' of 'greenlet.greenlet' objects>"],
'b() has wrong callees')
self.assertAlmostEqual(12 * self.spin_cost, b_stat.ttot,
places=2, msg="b()'s total time is wrong")
self.assertAlmostEqual(12 * self.spin_cost, b_stat.tavg,
places=2, msg="b()'s average time is wrong")
self.assertAlmostEqual(b_stat.tsub, 0,
places=2, msg="b()'s subtotal is wrong")
# Check the stats for c().
c_stat = find_func(ystats, 'c')
self.assertEqual(1, c_stat.ncall, 'c() not called once')
assert_children(c_stat, ['spin'], 'c() has wrong callees')
self.assertAlmostEqual(7 * self.spin_cost, c_stat.ttot,
places=2, msg="c()'s total time is wrong")
self.assertAlmostEqual(7 * self.spin_cost, c_stat.tavg,
places=2, msg="c()'s average time is wrong")
self.assertAlmostEqual(c_stat.tsub, 0,
places=2, msg="c()'s subtotal is wrong")
def test_recursion(self):
def r(n):
spin(1)
gr_main.switch()
if n > 1:
r(n - 1)
gr_main.switch()
def s(n):
spin(1)
gr_main.switch()
if n > 1:
s(n - 1)
gr_main.switch()
GreenletProfiler.set_clock_type('cpu')
GreenletProfiler.start(builtins=True)
gr_main = greenlet.getcurrent()
g0 = greenlet.greenlet(partial(r, 10)) # Run r 10 times.
g0.switch()
g1 = greenlet.greenlet(partial(s, 2)) # Run s 2 times.
g1.switch()
greenlets = [g0, g1]
# Run all greenlets to completion.
while greenlets:
runlist = greenlets[:]
for g in runlist:
g.switch()
if not g:
# Finished.
greenlets.remove(g)
GreenletProfiler.stop()
ystats = GreenletProfiler.get_func_stats()
# Check the stats for spin().
spin_stat = find_func(ystats, 'spin')
self.assertEqual(12, spin_stat.ncall)
# r() ran spin(1) 10 times, s() ran spin(1) 2 times.
self.assertNear(12, spin_stat.ttot / self.spin_cost)
assert_children(spin_stat, ['range'], 'spin() has wrong callees')
# Check the stats for r().
r_stat = find_func(ystats, 'r')
self.assertEqual(10, r_stat.ncall)
assert_children(
r_stat,
['spin', 'r', "<method 'switch' of 'greenlet.greenlet' objects>"],
'r() has wrong callees')
self.assertNear(10, r_stat.ttot / self.spin_cost)
self.assertNear(1, r_stat.tavg / self.spin_cost)
self.assertAlmostEqual(0, r_stat.tsub, places=3)
# Check the stats for s().
s_stat = find_func(ystats, 's')
self.assertEqual(2, s_stat.ncall)
assert_children(
s_stat,
['spin', 's', "<method 'switch' of 'greenlet.greenlet' objects>"],
's() has wrong callees')
self.assertNear(2, s_stat.ttot / self.spin_cost)
self.assertNear(1, s_stat.tavg / self.spin_cost)
self.assertAlmostEqual(0, s_stat.tsub, places=3)
if __name__ == '__main__':
unittest.main()
| {
"repo_name": "ajdavis/GreenletProfiler",
"path": "test/test_greenlet_profiler.py",
"copies": "1",
"size": "6704",
"license": "mit",
"hash": 474806279176844860,
"line_mean": 30.1813953488,
"line_max": 78,
"alpha_frac": 0.5305787589,
"autogenerated": false,
"ratio": 3.583110636023517,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9608521436267186,
"avg_score": 0.0010335917312661498,
"num_lines": 215
} |
from functools import partial
import urllib
import time
from flask import Blueprint, Response, render_template, request, current_app
import flask
from modules.job_table.model import construct_full_table_query, calculate_job_query_stat
from modules.job_table.helpers import extract_string_list, extract_number
from core.job.helpers import hash2id, id2hash, id2username
from modules.job_table.helpers import get_color
from application.database import global_db
from core.job.models import Job
from core.tag.models import JobTag
from core.monitoring.models import JobPerformance
from application.helpers import requires_auth
job_table_pages = Blueprint('job_table', __name__
, template_folder='templates', static_folder='static')
@job_table_pages.route("/table/")
@requires_auth
def table_redirect():
query = "?" + request.query_string.decode("utf-8") if len(request.query_string) > 0 else ""
return flask.redirect(flask.url_for("job_table.get_table", _external=True, page=0) + query)
@job_table_pages.route("/share/<string:hash>")
def anon_table_redirect(hash):
query = "?" + request.query_string.decode("utf-8") if len(request.query_string) > 0 else ""
return flask.redirect(flask.url_for("job_table.get_anon_table", _external=True, hash=hash, page=0) + query)
def clean_user_request(data: dict) -> dict:
filter = {}
filter["date_from"] = extract_number(data, "date_from", None)
filter["date_to"] = extract_number(data, "date_to", None)
filter["req_tags"] = extract_string_list(data, "req_tags")
filter["opt_tags"] = extract_string_list(data, "opt_tags")
filter["no_tags"] = extract_string_list(data, "no_tags")
filter["accounts"] = extract_string_list(data, "accounts")
filter["partitions"] = extract_string_list(data, "partitions")
filter["states"] = extract_string_list(data, "states")
return filter
def convert_js_timestamp(filter: dict) -> dict:
try:
filter["date_to"] //= 1000 # remove milliseconds
except TypeError:
pass # ignore None
try:
filter["date_from"] //= 1000
except TypeError:
pass
return filter
def encode_filter(filter):
result = {}
result["date_from"] = filter["date_from"]
result["date_to"] = filter["date_to"]
result["req_tags"] = ",".join(filter["req_tags"])
result["opt_tags"] = ",".join(filter["opt_tags"])
result["no_tags"] = ",".join(filter["no_tags"])
result["accounts"] = ",".join(filter["accounts"])
result["partitions"] = ",".join(filter["partitions"])
result["states"] = ",".join(filter["states"])
return result
def job_table_common_post():
data = request.form.to_dict()
filter = clean_user_request(data)
filter = convert_js_timestamp(filter)
url_params = encode_filter(filter)
return flask.redirect(request.path + "?" + urllib.parse.urlencode(url_params))
def get_job_table_filter():
data = request.args.to_dict()
filter = clean_user_request(data)
if filter["date_from"] is None:
filter["date_from"] = int(time.time()) - 86400 * 7
return filter
def get_job_table_query(filter):
query = global_db.session.query(Job, JobTag, JobPerformance).join(JobTag).join(JobPerformance)
query = construct_full_table_query(query, filter)
query = query.filter(Job.state.in_(current_app.app_config.cluster["FINISHED_JOB_STATES"]))
return query
@job_table_pages.route("/table/page/<int:page>", methods=["POST"])
@requires_auth
def post_table(page: int) -> Response:
return job_table_common_post()
@job_table_pages.route("/table/page/<int:page>", methods=["GET"])
@requires_auth
def get_table(page: int) -> Response:
PAGE_SIZE = 50
query_url = "?" + request.query_string.decode("utf-8") if len(request.query_string) > 0 else ""
prev_page_link = flask.url_for("job_table.get_table", _external=True, page = page-1) + query_url if page > 0 else None
next_page_link = flask.url_for("job_table.get_table", _external=True, page = page+1) + query_url
filter = get_job_table_filter()
query = get_job_table_query(filter)
query_stat = calculate_job_query_stat(request.query_string, query)
show_query = query.order_by(Job.t_end.desc()).offset(page * PAGE_SIZE).limit(PAGE_SIZE)
return render_template("job_table_full.html"
, jobs=show_query.all()
, query_stat=query_stat
, prev_page_link = prev_page_link
, next_page_link = next_page_link
, app_config=current_app.app_config
, get_color=partial(get_color, thresholds=current_app.app_config.monitoring["thresholds"]))
@job_table_pages.route("/share/<string:hash>/<int:page>", methods=["POST"])
def post_anon_table(hash: str, page: int) -> Response:
return job_table_common_post()
@job_table_pages.route("/share/<string:hash>/<int:page>", methods=["GET"])
def get_anon_table(hash: str, page: int) -> Response:
PAGE_SIZE = 50
query_url = "?" + request.query_string.decode("utf-8") if len(request.query_string) > 0 else ""
prev_page_link = flask.url_for("job_table.get_anon_table", _external=True, hash = hash, page = page-1) + query_url if page > 0 else None
next_page_link = flask.url_for("job_table.get_anon_table", _external=True, hash = hash, page = page+1) + query_url
filter = get_job_table_filter()
filter["accounts"] = [id2username(hash2id(hash))]
query = get_job_table_query(filter)
query_stat = calculate_job_query_stat(request.query_string, query)
show_query = query.order_by(Job.t_end.desc()).offset(page * PAGE_SIZE).limit(PAGE_SIZE)
return render_template("job_table_anon.html"
, jobs=show_query.all()
, query_stat=query_stat
, prev_page_link = prev_page_link
, next_page_link = next_page_link
, app_config=current_app.app_config
, get_color=partial(get_color, thresholds=current_app.app_config.monitoring["thresholds"])
, id2hash=id2hash)
@job_table_pages.route("/timeline", methods=["POST"])
@requires_auth
def post_timeline() -> Response:
return job_table_common_post()
@job_table_pages.route("/timeline", methods=["GET"])
@requires_auth
def timeline() -> Response:
filter = get_job_table_filter()
query = get_job_table_query(filter)
query_stat = calculate_job_query_stat(request.query_string, query)
show_query = query.order_by(Job.t_end.desc())
return render_template("timeline.html"
, jobs=show_query.all()
, query_stat=query_stat
, app_config=current_app.app_config)
@job_table_pages.route("/queue_timeline", methods=["POST"])
@requires_auth
def post_queue_timeline() -> Response:
return job_table_common_post()
@job_table_pages.route("/queue_timeline", methods=["GET"])
@requires_auth
def queue_timeline() -> Response:
filter = get_job_table_filter()
query = get_job_table_query(filter)
query_stat = calculate_job_query_stat(request.query_string, query)
show_query = query.order_by(Job.t_end.desc())
return render_template("queue_timeline.html"
, jobs=show_query.all()
, query_stat=query_stat
, app_config=current_app.app_config)
| {
"repo_name": "srcc-msu/job_statistics",
"path": "modules/job_table/controllers.py",
"copies": "1",
"size": "6779",
"license": "mit",
"hash": -5307194456881179000,
"line_mean": 32.5594059406,
"line_max": 137,
"alpha_frac": 0.7098392093,
"autogenerated": false,
"ratio": 3.003544528134692,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.908459880047919,
"avg_score": 0.025756987391100473,
"num_lines": 202
} |
from functools import partial
import uuid
from engineio import json
import pickle
from .asyncio_manager import AsyncManager
class AsyncPubSubManager(AsyncManager):
"""Manage a client list attached to a pub/sub backend under asyncio.
This is a base class that enables multiple servers to share the list of
clients, with the servers communicating events through a pub/sub backend.
The use of a pub/sub backend also allows any client connected to the
backend to emit events addressed to Socket.IO clients.
The actual backends must be implemented by subclasses, this class only
provides a pub/sub generic framework for asyncio applications.
:param channel: The channel name on which the server sends and receives
notifications.
"""
name = 'asyncpubsub'
def __init__(self, channel='socketio', write_only=False, logger=None):
super().__init__()
self.channel = channel
self.write_only = write_only
self.host_id = uuid.uuid4().hex
self.logger = logger
def initialize(self):
super().initialize()
if not self.write_only:
self.thread = self.server.start_background_task(self._thread)
self._get_logger().info(self.name + ' backend initialized.')
async def emit(self, event, data, namespace=None, room=None, skip_sid=None,
callback=None, **kwargs):
"""Emit a message to a single client, a room, or all the clients
connected to the namespace.
This method takes care or propagating the message to all the servers
that are connected through the message queue.
The parameters are the same as in :meth:`.Server.emit`.
Note: this method is a coroutine.
"""
if kwargs.get('ignore_queue'):
return await super().emit(
event, data, namespace=namespace, room=room, skip_sid=skip_sid,
callback=callback)
namespace = namespace or '/'
if callback is not None:
if self.server is None:
raise RuntimeError('Callbacks can only be issued from the '
'context of a server.')
if room is None:
raise ValueError('Cannot use callback without a room set.')
id = self._generate_ack_id(room, callback)
callback = (room, namespace, id)
else:
callback = None
await self._publish({'method': 'emit', 'event': event, 'data': data,
'namespace': namespace, 'room': room,
'skip_sid': skip_sid, 'callback': callback,
'host_id': self.host_id})
async def can_disconnect(self, sid, namespace):
if self.is_connected(sid, namespace):
# client is in this server, so we can disconnect directly
return await super().can_disconnect(sid, namespace)
else:
# client is in another server, so we post request to the queue
await self._publish({'method': 'disconnect', 'sid': sid,
'namespace': namespace or '/'})
async def close_room(self, room, namespace=None):
await self._publish({'method': 'close_room', 'room': room,
'namespace': namespace or '/'})
async def _publish(self, data):
"""Publish a message on the Socket.IO channel.
This method needs to be implemented by the different subclasses that
support pub/sub backends.
"""
raise NotImplementedError('This method must be implemented in a '
'subclass.') # pragma: no cover
async def _listen(self):
"""Return the next message published on the Socket.IO channel,
blocking until a message is available.
This method needs to be implemented by the different subclasses that
support pub/sub backends.
"""
raise NotImplementedError('This method must be implemented in a '
'subclass.') # pragma: no cover
async def _handle_emit(self, message):
# Events with callbacks are very tricky to handle across hosts
# Here in the receiving end we set up a local callback that preserves
# the callback host and id from the sender
remote_callback = message.get('callback')
remote_host_id = message.get('host_id')
if remote_callback is not None and len(remote_callback) == 3:
callback = partial(self._return_callback, remote_host_id,
*remote_callback)
else:
callback = None
await super().emit(message['event'], message['data'],
namespace=message.get('namespace'),
room=message.get('room'),
skip_sid=message.get('skip_sid'),
callback=callback)
async def _handle_callback(self, message):
if self.host_id == message.get('host_id'):
try:
sid = message['sid']
id = message['id']
args = message['args']
except KeyError:
return
await self.trigger_callback(sid, id, args)
async def _return_callback(self, host_id, sid, namespace, callback_id,
*args):
# When an event callback is received, the callback is returned back
# the sender, which is identified by the host_id
await self._publish({'method': 'callback', 'host_id': host_id,
'sid': sid, 'namespace': namespace,
'id': callback_id, 'args': args})
async def _handle_disconnect(self, message):
await self.server.disconnect(sid=message.get('sid'),
namespace=message.get('namespace'),
ignore_queue=True)
async def _handle_close_room(self, message):
await super().close_room(
room=message.get('room'), namespace=message.get('namespace'))
async def _thread(self):
while True:
try:
message = await self._listen()
except:
import traceback
traceback.print_exc()
break
data = None
if isinstance(message, dict):
data = message
else:
if isinstance(message, bytes): # pragma: no cover
try:
data = pickle.loads(message)
except:
pass
if data is None:
try:
data = json.loads(message)
except:
pass
if data and 'method' in data:
self._get_logger().info('pubsub message: {}'.format(
data['method']))
if data['method'] == 'emit':
await self._handle_emit(data)
elif data['method'] == 'callback':
await self._handle_callback(data)
elif data['method'] == 'disconnect':
await self._handle_disconnect(data)
elif data['method'] == 'close_room':
await self._handle_close_room(data)
| {
"repo_name": "miguelgrinberg/python-socketio",
"path": "src/socketio/asyncio_pubsub_manager.py",
"copies": "1",
"size": "7448",
"license": "mit",
"hash": 5029160893386946000,
"line_mean": 40.6089385475,
"line_max": 79,
"alpha_frac": 0.5494092374,
"autogenerated": false,
"ratio": 4.929185969556585,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5978595206956585,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import uuid
from engineio import json
import pickle
from .base_manager import BaseManager
class PubSubManager(BaseManager):
"""Manage a client list attached to a pub/sub backend.
This is a base class that enables multiple servers to share the list of
clients, with the servers communicating events through a pub/sub backend.
The use of a pub/sub backend also allows any client connected to the
backend to emit events addressed to Socket.IO clients.
The actual backends must be implemented by subclasses, this class only
provides a pub/sub generic framework.
:param channel: The channel name on which the server sends and receives
notifications.
"""
name = 'pubsub'
def __init__(self, channel='socketio', write_only=False, logger=None):
super(PubSubManager, self).__init__()
self.channel = channel
self.write_only = write_only
self.host_id = uuid.uuid4().hex
self.logger = logger
def initialize(self):
super(PubSubManager, self).initialize()
if not self.write_only:
self.thread = self.server.start_background_task(self._thread)
self._get_logger().info(self.name + ' backend initialized.')
def emit(self, event, data, namespace=None, room=None, skip_sid=None,
callback=None, **kwargs):
"""Emit a message to a single client, a room, or all the clients
connected to the namespace.
This method takes care or propagating the message to all the servers
that are connected through the message queue.
The parameters are the same as in :meth:`.Server.emit`.
"""
if kwargs.get('ignore_queue'):
return super(PubSubManager, self).emit(
event, data, namespace=namespace, room=room, skip_sid=skip_sid,
callback=callback)
namespace = namespace or '/'
if callback is not None:
if self.server is None:
raise RuntimeError('Callbacks can only be issued from the '
'context of a server.')
if room is None:
raise ValueError('Cannot use callback without a room set.')
id = self._generate_ack_id(room, callback)
callback = (room, namespace, id)
else:
callback = None
self._publish({'method': 'emit', 'event': event, 'data': data,
'namespace': namespace, 'room': room,
'skip_sid': skip_sid, 'callback': callback,
'host_id': self.host_id})
def can_disconnect(self, sid, namespace):
if self.is_connected(sid, namespace):
# client is in this server, so we can disconnect directly
return super().can_disconnect(sid, namespace)
else:
# client is in another server, so we post request to the queue
self._publish({'method': 'disconnect', 'sid': sid,
'namespace': namespace or '/'})
def close_room(self, room, namespace=None):
self._publish({'method': 'close_room', 'room': room,
'namespace': namespace or '/'})
def _publish(self, data):
"""Publish a message on the Socket.IO channel.
This method needs to be implemented by the different subclasses that
support pub/sub backends.
"""
raise NotImplementedError('This method must be implemented in a '
'subclass.') # pragma: no cover
def _listen(self):
"""Return the next message published on the Socket.IO channel,
blocking until a message is available.
This method needs to be implemented by the different subclasses that
support pub/sub backends.
"""
raise NotImplementedError('This method must be implemented in a '
'subclass.') # pragma: no cover
def _handle_emit(self, message):
# Events with callbacks are very tricky to handle across hosts
# Here in the receiving end we set up a local callback that preserves
# the callback host and id from the sender
remote_callback = message.get('callback')
remote_host_id = message.get('host_id')
if remote_callback is not None and len(remote_callback) == 3:
callback = partial(self._return_callback, remote_host_id,
*remote_callback)
else:
callback = None
super(PubSubManager, self).emit(message['event'], message['data'],
namespace=message.get('namespace'),
room=message.get('room'),
skip_sid=message.get('skip_sid'),
callback=callback)
def _handle_callback(self, message):
if self.host_id == message.get('host_id'):
try:
sid = message['sid']
id = message['id']
args = message['args']
except KeyError:
return
self.trigger_callback(sid, id, args)
def _return_callback(self, host_id, sid, namespace, callback_id, *args):
# When an event callback is received, the callback is returned back
# to the sender, which is identified by the host_id
self._publish({'method': 'callback', 'host_id': host_id,
'sid': sid, 'namespace': namespace, 'id': callback_id,
'args': args})
def _handle_disconnect(self, message):
self.server.disconnect(sid=message.get('sid'),
namespace=message.get('namespace'),
ignore_queue=True)
def _handle_close_room(self, message):
super(PubSubManager, self).close_room(
room=message.get('room'), namespace=message.get('namespace'))
def _thread(self):
for message in self._listen():
data = None
if isinstance(message, dict):
data = message
else:
if isinstance(message, bytes): # pragma: no cover
try:
data = pickle.loads(message)
except:
pass
if data is None:
try:
data = json.loads(message)
except:
pass
if data and 'method' in data:
self._get_logger().info('pubsub message: {}'.format(
data['method']))
if data['method'] == 'emit':
self._handle_emit(data)
elif data['method'] == 'callback':
self._handle_callback(data)
elif data['method'] == 'disconnect':
self._handle_disconnect(data)
elif data['method'] == 'close_room':
self._handle_close_room(data)
| {
"repo_name": "miguelgrinberg/python-socketio",
"path": "src/socketio/pubsub_manager.py",
"copies": "1",
"size": "7103",
"license": "mit",
"hash": 4468498407812515000,
"line_mean": 40.7823529412,
"line_max": 79,
"alpha_frac": 0.5524426299,
"autogenerated": false,
"ratio": 4.815593220338983,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5868035850238983,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import uuid
import json
import pickle
import six
from .asyncio_manager import AsyncManager
class AsyncPubSubManager(AsyncManager):
"""Manage a client list attached to a pub/sub backend under asyncio.
This is a base class that enables multiple servers to share the list of
clients, with the servers communicating events through a pub/sub backend.
The use of a pub/sub backend also allows any client connected to the
backend to emit events addressed to Socket.IO clients.
The actual backends must be implemented by subclasses, this class only
provides a pub/sub generic framework for asyncio applications.
:param channel: The channel name on which the server sends and receives
notifications.
"""
name = 'asyncpubsub'
def __init__(self, channel='socketio', write_only=False):
super().__init__()
self.channel = channel
self.write_only = write_only
self.host_id = uuid.uuid4().hex
def initialize(self):
super().initialize()
if not self.write_only:
self.thread = self.server.start_background_task(self._thread)
self.server.logger.info(self.name + ' backend initialized.')
async def emit(self, event, data, namespace=None, room=None, skip_sid=None,
callback=None, **kwargs):
"""Emit a message to a single client, a room, or all the clients
connected to the namespace.
This method takes care or propagating the message to all the servers
that are connected through the message queue.
The parameters are the same as in :meth:`.Server.emit`.
Note: this method is a coroutine.
"""
if kwargs.get('ignore_queue'):
return await super().emit(
event, data, namespace=namespace, room=room, skip_sid=skip_sid,
callback=callback)
namespace = namespace or '/'
if callback is not None:
if self.server is None:
raise RuntimeError('Callbacks can only be issued from the '
'context of a server.')
if room is None:
raise ValueError('Cannot use callback without a room set.')
id = self._generate_ack_id(room, namespace, callback)
callback = (room, namespace, id)
else:
callback = None
await self._publish({'method': 'emit', 'event': event, 'data': data,
'namespace': namespace, 'room': room,
'skip_sid': skip_sid, 'callback': callback})
async def close_room(self, room, namespace=None):
await self._publish({'method': 'close_room', 'room': room,
'namespace': namespace or '/'})
async def _publish(self, data):
"""Publish a message on the Socket.IO channel.
This method needs to be implemented by the different subclasses that
support pub/sub backends.
"""
raise NotImplementedError('This method must be implemented in a '
'subclass.') # pragma: no cover
async def _listen(self):
"""Return the next message published on the Socket.IO channel,
blocking until a message is available.
This method needs to be implemented by the different subclasses that
support pub/sub backends.
"""
raise NotImplementedError('This method must be implemented in a '
'subclass.') # pragma: no cover
async def _handle_emit(self, message):
# Events with callbacks are very tricky to handle across hosts
# Here in the receiving end we set up a local callback that preserves
# the callback host and id from the sender
remote_callback = message.get('callback')
if remote_callback is not None and len(remote_callback) == 3:
callback = partial(self._return_callback, self.host_id,
*remote_callback)
else:
callback = None
await super().emit(message['event'], message['data'],
namespace=message.get('namespace'),
room=message.get('room'),
skip_sid=message.get('skip_sid'),
callback=callback)
async def _handle_callback(self, message):
if self.host_id == message.get('host_id'):
try:
sid = message['sid']
namespace = message['namespace']
id = message['id']
args = message['args']
except KeyError:
return
await self.trigger_callback(sid, namespace, id, args)
async def _return_callback(self, host_id, sid, namespace, callback_id,
*args):
# When an event callback is received, the callback is returned back
# the sender, which is identified by the host_id
await self._publish({'method': 'callback', 'host_id': host_id,
'sid': sid, 'namespace': namespace,
'id': callback_id, 'args': args})
async def _handle_close_room(self, message):
await super().close_room(
room=message.get('room'), namespace=message.get('namespace'))
async def _thread(self):
while True:
try:
message = await self._listen()
except:
import traceback
traceback.print_exc()
break
data = None
if isinstance(message, dict):
data = message
else:
if isinstance(message, six.binary_type): # pragma: no cover
try:
data = pickle.loads(message)
except:
pass
if data is None:
try:
data = json.loads(message)
except:
pass
if data and 'method' in data:
if data['method'] == 'emit':
await self._handle_emit(data)
elif data['method'] == 'callback':
await self._handle_callback(data)
elif data['method'] == 'close_room':
await self._handle_close_room(data)
| {
"repo_name": "quoclieu/codebrew17-starving",
"path": "env/lib/python3.5/site-packages/socketio/asyncio_pubsub_manager.py",
"copies": "1",
"size": "6470",
"license": "mit",
"hash": -3555862346128636000,
"line_mean": 39.4375,
"line_max": 79,
"alpha_frac": 0.5550231839,
"autogenerated": false,
"ratio": 4.9314024390243905,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5986425622924391,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import uuid
import json
import pickle
import six
from .base_manager import BaseManager
class PubSubManager(BaseManager):
"""Manage a client list attached to a pub/sub backend.
This is a base class that enables multiple servers to share the list of
clients, with the servers communicating events through a pub/sub backend.
The use of a pub/sub backend also allows any client connected to the
backend to emit events addressed to Socket.IO clients.
The actual backends must be implemented by subclasses, this class only
provides a pub/sub generic framework.
:param channel: The channel name on which the server sends and receives
notifications.
"""
name = 'pubsub'
def __init__(self, channel='socketio', write_only=False):
super(PubSubManager, self).__init__()
self.channel = channel
self.write_only = write_only
self.host_id = uuid.uuid4().hex
def initialize(self):
super(PubSubManager, self).initialize()
if not self.write_only:
self.thread = self.server.start_background_task(self._thread)
self.server.logger.info(self.name + ' backend initialized.')
def emit(self, event, data, namespace=None, room=None, skip_sid=None,
callback=None, **kwargs):
"""Emit a message to a single client, a room, or all the clients
connected to the namespace.
This method takes care or propagating the message to all the servers
that are connected through the message queue.
The parameters are the same as in :meth:`.Server.emit`.
"""
if kwargs.get('ignore_queue'):
return super(PubSubManager, self).emit(
event, data, namespace=namespace, room=room, skip_sid=skip_sid,
callback=callback)
namespace = namespace or '/'
if callback is not None:
if self.server is None:
raise RuntimeError('Callbacks can only be issued from the '
'context of a server.')
if room is None:
raise ValueError('Cannot use callback without a room set.')
id = self._generate_ack_id(room, namespace, callback)
callback = (room, namespace, id)
else:
callback = None
self._publish({'method': 'emit', 'event': event, 'data': data,
'namespace': namespace, 'room': room,
'skip_sid': skip_sid, 'callback': callback})
def close_room(self, room, namespace=None):
self._publish({'method': 'close_room', 'room': room,
'namespace': namespace or '/'})
def _publish(self, data):
"""Publish a message on the Socket.IO channel.
This method needs to be implemented by the different subclasses that
support pub/sub backends.
"""
raise NotImplementedError('This method must be implemented in a '
'subclass.') # pragma: no cover
def _listen(self):
"""Return the next message published on the Socket.IO channel,
blocking until a message is available.
This method needs to be implemented by the different subclasses that
support pub/sub backends.
"""
raise NotImplementedError('This method must be implemented in a '
'subclass.') # pragma: no cover
def _handle_emit(self, message):
# Events with callbacks are very tricky to handle across hosts
# Here in the receiving end we set up a local callback that preserves
# the callback host and id from the sender
remote_callback = message.get('callback')
if remote_callback is not None and len(remote_callback) == 3:
callback = partial(self._return_callback, self.host_id,
*remote_callback)
else:
callback = None
super(PubSubManager, self).emit(message['event'], message['data'],
namespace=message.get('namespace'),
room=message.get('room'),
skip_sid=message.get('skip_sid'),
callback=callback)
def _handle_callback(self, message):
if self.host_id == message.get('host_id'):
try:
sid = message['sid']
namespace = message['namespace']
id = message['id']
args = message['args']
except KeyError:
return
self.trigger_callback(sid, namespace, id, args)
def _return_callback(self, host_id, sid, namespace, callback_id, *args):
# When an event callback is received, the callback is returned back
# the sender, which is identified by the host_id
self._publish({'method': 'callback', 'host_id': host_id,
'sid': sid, 'namespace': namespace, 'id': callback_id,
'args': args})
def _handle_close_room(self, message):
super(PubSubManager, self).close_room(
room=message.get('room'), namespace=message.get('namespace'))
def _thread(self):
for message in self._listen():
data = None
if isinstance(message, dict):
data = message
else:
if isinstance(message, six.binary_type): # pragma: no cover
try:
data = pickle.loads(message)
except:
pass
if data is None:
try:
data = json.loads(message)
except:
pass
if data and 'method' in data:
if data['method'] == 'emit':
self._handle_emit(data)
elif data['method'] == 'callback':
self._handle_callback(data)
elif data['method'] == 'close_room':
self._handle_close_room(data)
| {
"repo_name": "quoclieu/codebrew17-starving",
"path": "env/lib/python3.5/site-packages/socketio/pubsub_manager.py",
"copies": "1",
"size": "6181",
"license": "mit",
"hash": 8569691153318626000,
"line_mean": 39.9337748344,
"line_max": 79,
"alpha_frac": 0.5583238958,
"autogenerated": false,
"ratio": 4.825136612021858,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5883460507821858,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import warnings
import numpy as np
import pandas as pd
import bioframe
from .lib.common import assign_regions
from .lib.numutils import LazyToeplitz
import warnings
def make_bin_aligned_windows(
binsize, chroms, centers_bp, flank_bp=0, region_start_bp=0, ignore_index=False
):
"""
Convert genomic loci into bin spans on a fixed bin-size segmentation of a
genomic region. Window limits are adjusted to align with bin edges.
Parameters
-----------
binsize : int
Bin size (resolution) in base pairs.
chroms : 1D array-like
Column of chromosome names.
centers_bp : 1D or nx2 array-like
If 1D, center points of each window. If 2D, the starts and ends.
flank_bp : int
Distance in base pairs to extend windows on either side.
region_start_bp : int, optional
If region is a subset of a chromosome, shift coordinates by this amount.
Default is 0.
Returns
-------
DataFrame with columns:
'chrom' - chromosome
'start', 'end' - window limits in base pairs
'lo', 'hi' - window limits in bins
"""
if not (flank_bp % binsize == 0):
raise ValueError("Flanking distance must be divisible by the bin size.")
if isinstance(chroms, pd.Series) and not ignore_index:
index = chroms.index
else:
index = None
chroms = np.asarray(chroms)
centers_bp = np.asarray(centers_bp)
if len(centers_bp.shape) == 2:
left_bp = centers_bp[:, 0]
right_bp = centers_bp[:, 1]
else:
left_bp = right_bp = centers_bp
if np.any(left_bp > right_bp):
raise ValueError("Found interval with end > start.")
left = left_bp - region_start_bp
right = right_bp - region_start_bp
left_bin = (left / binsize).astype(int)
right_bin = (right / binsize).astype(int)
flank_bin = flank_bp // binsize
lo = left_bin - flank_bin
hi = right_bin + flank_bin + 1
windows = pd.DataFrame(index=index)
windows["chrom"] = chroms
windows["start"] = lo * binsize
windows["end"] = hi * binsize
windows["lo"] = lo
windows["hi"] = hi
return windows
def _pileup(data_select, data_snip, arg):
support, feature_group = arg
# return empty snippets if region is unannotated:
if len(support) == 0:
if "start" in feature_group: # on-diagonal off-region case:
lo = feature_group["lo"].values
hi = feature_group["hi"].values
s = hi - lo # Shape of individual snips
assert (
s.max() == s.min()
), "Pileup accepts only the windows of the same size"
stack = np.full((s[0], s[0], len(feature_group)), np.nan)
else: # off-diagonal off-region case:
lo1 = feature_group["lo1"].values
hi1 = feature_group["hi1"].values
lo2 = feature_group["lo2"].values
hi2 = feature_group["hi2"].values
s1 = hi1 - lo1 # Shape of individual snips
s2 = hi1 - lo1
assert (
s1.max() == s1.min()
), "Pileup accepts only the windows of the same size"
assert (
s2.max() == s2.min()
), "Pileup accepts only the windows of the same size"
stack = np.full((s1[0], s2[0], len(feature_group)), np.nan)
return stack, feature_group["_rank"].values
# check if support region is on- or off-diagonal
if len(support) == 2:
region1, region2 = support
else:
region1 = region2 = support
# check if features are on- or off-diagonal
if "start" in feature_group:
s1 = feature_group["start"].values
e1 = feature_group["end"].values
s2, e2 = s1, e1
else:
s1 = feature_group["start1"].values
e1 = feature_group["end1"].values
s2 = feature_group["start2"].values
e2 = feature_group["end2"].values
data = data_select(region1, region2)
stack = list(map(partial(data_snip, data, region1, region2), zip(s1, e1, s2, e2)))
return np.dstack(stack), feature_group["_rank"].values
def pileup(features, data_select, data_snip, map=map):
"""
Handles on-diagonal and off-diagonal cases.
Parameters
----------
features : DataFrame
Table of features. Requires columns ['chrom', 'start', 'end'].
Or ['chrom1', 'start1', 'end1', 'chrom1', 'start2', 'end2'].
start, end are bp coordinates.
lo, hi are bin coordinates.
data_select : callable
Callable that takes a region as argument and returns
the data, mask and bin offset of a support region
data_snip : callable
Callable that takes data, mask and a 2D bin span (lo1, hi1, lo2, hi2)
and returns a snippet from the selected support region
"""
if features.region.isnull().any():
warnings.warn(
"Some features do not have regions assigned! Some snips will be empty."
)
features = features.copy()
features["region"] = features.region.fillna(
""
) # fill in unanotated regions with empty string
features["_rank"] = range(len(features))
# cumul_stack = []
# orig_rank = []
cumul_stack, orig_rank = zip(
*map(
partial(_pileup, data_select, data_snip),
# Note that unannotated regions will form a separate group
features.groupby("region", sort=False),
)
)
# Restore the original rank of the input features
cumul_stack = np.dstack(cumul_stack)
orig_rank = np.concatenate(orig_rank)
idx = np.argsort(orig_rank)
cumul_stack = cumul_stack[:, :, idx]
return cumul_stack
def pair_sites(sites, separation, slop):
"""
Create "hand" intervals to the right and to the left of each site.
Then join right hands with left hands to pair sites together.
"""
from bioframe.tools import tsv, bedtools
mids = (sites["start"] + sites["end"]) // 2
left_hand = sites[["chrom"]].copy()
left_hand["start"] = mids - separation - slop
left_hand["end"] = mids - separation + slop
left_hand["site_id"] = left_hand.index
left_hand["direction"] = "L"
left_hand["snip_mid"] = mids
left_hand["snip_strand"] = sites["strand"]
right_hand = sites[["chrom"]].copy()
right_hand["start"] = mids + separation - slop
right_hand["end"] = mids + separation + slop
right_hand["site_id"] = right_hand.index
right_hand["direction"] = "R"
right_hand["snip_mid"] = mids
right_hand["snip_strand"] = sites["strand"]
# ignore out-of-bounds hands
mask = (left_hand["start"] > 0) & (right_hand["start"] > 0)
left_hand = left_hand[mask].copy()
right_hand = right_hand[mask].copy()
# intersect right hands (left anchor site)
# with left hands (right anchor site)
with tsv(right_hand) as R, tsv(left_hand) as L:
out = bedtools.intersect(a=R.name, b=L.name, wa=True, wb=True)
out.columns = [c + "_r" for c in right_hand.columns] + [
c + "_l" for c in left_hand.columns
]
return out
class CoolerSnipper:
def __init__(self, clr, cooler_opts=None, regions=None):
if regions is None:
regions = pd.DataFrame(
[(chrom, 0, l, chrom) for chrom, l in clr.chromsizes.items()],
columns=["chrom", "start", "end", "name"],
)
regions = regions[regions['chrom'].isin(clr.chromnames)].reset_index(drop=True)
self.regions = regions.set_index("name")
self.clr = clr
self.binsize = self.clr.binsize
self.offsets = {}
self.pad = True
self.cooler_opts = {} if cooler_opts is None else cooler_opts
self.cooler_opts.setdefault("sparse", True)
def select(self, region1, region2):
region1_coords = self.regions.loc[region1]
region2_coords = self.regions.loc[region2]
self.offsets[region1] = self.clr.offset(region1_coords) - self.clr.offset(
region1_coords[0]
)
self.offsets[region2] = self.clr.offset(region2_coords) - self.clr.offset(
region2_coords[0]
)
matrix = self.clr.matrix(**self.cooler_opts).fetch(
region1_coords, region2_coords
)
self._isnan1 = np.isnan(self.clr.bins()["weight"].fetch(region1_coords).values)
self._isnan2 = np.isnan(self.clr.bins()["weight"].fetch(region2_coords).values)
if self.cooler_opts["sparse"]:
matrix = matrix.tocsr()
return matrix
def snip(self, matrix, region1, region2, tup):
s1, e1, s2, e2 = tup
offset1 = self.offsets[region1]
offset2 = self.offsets[region2]
binsize = self.binsize
lo1, hi1 = (s1 // binsize) - offset1, (e1 // binsize) - offset1
lo2, hi2 = (s2 // binsize) - offset2, (e2 // binsize) - offset2
assert hi1 >= 0
assert hi2 >= 0
m, n = matrix.shape
dm, dn = hi1 - lo1, hi2 - lo2
out_of_bounds = False
pad_left = pad_right = pad_bottom = pad_top = None
if lo1 < 0:
pad_bottom = -lo1
out_of_bounds = True
if lo2 < 0:
pad_left = -lo2
out_of_bounds = True
if hi1 > m:
pad_top = dm - (hi1 - m)
out_of_bounds = True
if hi2 > n:
pad_right = dn - (hi2 - n)
out_of_bounds = True
if out_of_bounds:
i0 = max(lo1, 0)
i1 = min(hi1, m)
j0 = max(lo2, 0)
j1 = min(hi2, n)
snippet = np.full((dm, dn), np.nan)
# snippet[pad_bottom:pad_top,
# pad_left:pad_right] = matrix[i0:i1, j0:j1].toarray()
else:
snippet = matrix[lo1:hi1, lo2:hi2].toarray().astype("float")
snippet[self._isnan1[lo1:hi1], :] = np.nan
snippet[:, self._isnan2[lo2:hi2]] = np.nan
return snippet
class ObsExpSnipper:
def __init__(self, clr, expected, cooler_opts=None, regions=None):
self.clr = clr
self.expected = expected
# Detecting the columns for the detection of regions
columns = expected.columns
assert len(columns) > 0
if "region" not in columns:
if "chrom" in columns:
self.expected = self.expected.rename(columns={"chrom": "region"})
warnings.warn(
"The expected dataframe appears to be in the old format."
"It should have a `region` column, not `chrom`."
)
else:
raise ValueError(
"Please check the expected dataframe, it has no `region` column"
)
if regions is None:
if set(self.expected["region"]).issubset(clr.chromnames):
regions = pd.DataFrame(
[(chrom, 0, l, chrom) for chrom, l in clr.chromsizes.items()],
columns=["chrom", "start", "end", "name"],
)
else:
raise ValueError(
"Please provide the regions table, if region names"
"are not simply chromosome names."
)
regions = regions[regions['chrom'].isin(clr.chromnames)].reset_index(drop=True)
self.regions = regions.set_index("name")
try:
for region_name, group in self.expected.groupby("region"):
n_diags = group.shape[0]
region = self.regions.loc[region_name]
lo, hi = self.clr.extent(region)
assert n_diags == (hi - lo)
except AssertionError:
raise ValueError(
"Region shape mismatch between expected and cooler. "
"Are they using the same resolution?"
)
self.binsize = self.clr.binsize
self.offsets = {}
self.pad = True
self.cooler_opts = {} if cooler_opts is None else cooler_opts
self.cooler_opts.setdefault("sparse", True)
def select(self, region1, region2):
assert region1 == region2, "ObsExpSnipper is implemented for cis contacts only."
region1_coords = self.regions.loc[region1]
region2_coords = self.regions.loc[region2]
self.offsets[region1] = self.clr.offset(region1_coords) - self.clr.offset(
region1_coords[0]
)
self.offsets[region2] = self.clr.offset(region2_coords) - self.clr.offset(
region2_coords[0]
)
matrix = self.clr.matrix(**self.cooler_opts).fetch(
region1_coords, region2_coords
)
if self.cooler_opts["sparse"]:
matrix = matrix.tocsr()
self._isnan1 = np.isnan(self.clr.bins()["weight"].fetch(region1_coords).values)
self._isnan2 = np.isnan(self.clr.bins()["weight"].fetch(region2_coords).values)
self._expected = LazyToeplitz(
self.expected.groupby("region").get_group(region1)["balanced.avg"].values
)
return matrix
def snip(self, matrix, region1, region2, tup):
s1, e1, s2, e2 = tup
offset1 = self.offsets[region1]
offset2 = self.offsets[region2]
binsize = self.binsize
lo1, hi1 = (s1 // binsize) - offset1, (e1 // binsize) - offset1
lo2, hi2 = (s2 // binsize) - offset2, (e2 // binsize) - offset2
assert hi1 >= 0
assert hi2 >= 0
m, n = matrix.shape
dm, dn = hi1 - lo1, hi2 - lo2
out_of_bounds = False
pad_left = pad_right = pad_bottom = pad_top = None
if lo1 < 0:
pad_bottom = -lo1
out_of_bounds = True
if lo2 < 0:
pad_left = -lo2
out_of_bounds = True
if hi1 > m:
pad_top = dm - (hi1 - m)
out_of_bounds = True
if hi2 > n:
pad_right = dn - (hi2 - n)
out_of_bounds = True
if out_of_bounds:
i0 = max(lo1, 0)
i1 = min(hi1, m)
j0 = max(lo2, 0)
j1 = min(hi2, n)
return np.full((dm, dn), np.nan)
# snippet[pad_bottom:pad_top,
# pad_left:pad_right] = matrix[i0:i1, j0:j1].toarray()
else:
snippet = matrix[lo1:hi1, lo2:hi2].toarray()
snippet[self._isnan1[lo1:hi1], :] = np.nan
snippet[:, self._isnan2[lo2:hi2]] = np.nan
e = self._expected[lo1:hi1, lo2:hi2]
return snippet / e
class ExpectedSnipper:
def __init__(self, clr, expected, regions=None):
self.clr = clr
self.expected = expected
# Detecting the columns for the detection of regions
columns = expected.columns
assert len(columns) > 0
if "region" not in columns:
if "chrom" in columns:
self.expected = self.expected.rename(columns={"chrom": "region"})
warnings.warn(
"The expected dataframe appears to be in the old format."
"It should have a `region` column, not `chrom`."
)
else:
raise ValueError(
"Please check the expected dataframe, it has no `region` column"
)
if regions is None:
if set(self.expected["region"]).issubset(clr.chromnames):
regions = pd.DataFrame(
[(chrom, 0, l, chrom) for chrom, l in clr.chromsizes.items()],
columns=["chrom", "start", "end", "name"],
)
else:
raise ValueError(
"Please provide the regions table, if region names"
"are not simply chromosome names."
)
regions = regions[regions['chrom'].isin(clr.chromnames)].reset_index(drop=True)
self.regions = regions.set_index("name")
try:
for region_name, group in self.expected.groupby("region"):
n_diags = group.shape[0]
region = self.regions.loc[region_name]
lo, hi = self.clr.extent(region)
assert n_diags == (hi - lo)
except AssertionError:
raise ValueError(
"Region shape mismatch between expected and cooler. "
"Are they using the same resolution?"
)
self.binsize = self.clr.binsize
self.offsets = {}
def select(self, region1, region2):
assert (
region1 == region2
), "ExpectedSnipper is implemented for cis contacts only."
region1_coords = self.regions.loc[region1]
region2_coords = self.regions.loc[region2]
self.offsets[region1] = self.clr.offset(region1_coords) - self.clr.offset(
region1_coords[0]
)
self.offsets[region2] = self.clr.offset(region2_coords) - self.clr.offset(
region2_coords[0]
)
self.m = np.diff(self.clr.extent(region1_coords))
self.n = np.diff(self.clr.extent(region2_coords))
self._expected = LazyToeplitz(
self.expected.groupby("region").get_group(region1)["balanced.avg"].values
)
return self._expected
def snip(self, exp, region1, region2, tup):
s1, e1, s2, e2 = tup
offset1 = self.offsets[region1]
offset2 = self.offsets[region2]
binsize = self.binsize
lo1, hi1 = (s1 // binsize) - offset1, (e1 // binsize) - offset1
lo2, hi2 = (s2 // binsize) - offset2, (e2 // binsize) - offset2
assert hi1 >= 0
assert hi2 >= 0
dm, dn = hi1 - lo1, hi2 - lo2
if lo1 < 0 or lo2 < 0 or hi1 > self.m or hi2 > self.n:
return np.full((dm, dn), np.nan)
snippet = exp[lo1:hi1, lo2:hi2]
return snippet
| {
"repo_name": "open2c/cooltools",
"path": "cooltools/snipping.py",
"copies": "1",
"size": "17927",
"license": "mit",
"hash": 2384073239127450000,
"line_mean": 34.9258517034,
"line_max": 88,
"alpha_frac": 0.5576504714,
"autogenerated": false,
"ratio": 3.638522427440633,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9692740259837556,
"avg_score": 0.0006865278006156549,
"num_lines": 499
} |
from functools import partial
import wx
from ...tool.box import Dialog, MessageDialog
"""
Graphical interface for data filters.
"""
class FilterEditDialog(Dialog):
def __init__(self, parent, headings, ok_callback, *args, **kwargs):
kwargs['style'] = kwargs.get('style', wx.DEFAULT_DIALOG_STYLE) | wx.RESIZE_BORDER
kwargs['title'] = kwargs.get('title', 'Add filter')
Dialog.__init__(self, parent, *args, **kwargs)
self.ok_callback = ok_callback
# Dialog.
dialog_box = wx.BoxSizer(wx.VERTICAL)
## Inputs.
input_sizer = wx.FlexGridSizer(rows=2, cols=2, hgap=5)
input_sizer.AddGrowableCol(1, 1)
dialog_box.Add(input_sizer, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
input_sizer.Add(wx.StaticText(self, label='Column:'),
flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
self.column_input = wx.Choice(self, choices=headings)
input_sizer.Add(self.column_input, flag=wx.EXPAND)
input_sizer.Add(wx.StaticText(self, label='Function:'),
flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
self.function_input = wx.TextCtrl(self)
self.function_input.SetMinSize((300, -1))
input_sizer.Add(self.function_input, flag=wx.EXPAND)
## Buttons.
button_box = wx.BoxSizer(wx.HORIZONTAL)
dialog_box.Add(button_box, flag=wx.CENTER|wx.ALL, border=5)
ok_button = wx.Button(self, wx.ID_OK)
self.Bind(wx.EVT_BUTTON, self.OnOk, ok_button)
button_box.Add(ok_button)
cancel_button = wx.Button(self, wx.ID_CANCEL)
button_box.Add(cancel_button)
self.SetSizerAndFit(dialog_box)
def GetValue(self):
return (self.column_input.StringSelection, self.function_input.Value)
def SetValue(self, values):
(self.column_input.StringSelection, self.function_input.Value) = values
def OnOk(self, evt=None):
try:
self.ok_callback(self)
except ValueError as e:
MessageDialog(self, str(e), 'Invalid value').Show()
return
self.Destroy()
class FilterListDialog(Dialog):
def __init__(self, parent, table, close_callback, filters=None, filter_columns=None,
*args, **kwargs):
kwargs['style'] = kwargs.get('style', wx.DEFAULT_DIALOG_STYLE) | wx.RESIZE_BORDER
kwargs['title'] = kwargs.get('title', 'Filters')
Dialog.__init__(self, parent, *args, **kwargs)
self.table = table
self.close_callback = close_callback
if filters is None or filter_columns is None:
self.filters, self.filter_columns = {}, {}
else:
self.filters, self.filter_columns = filters, filter_columns
# Dialog.
dialog_box = wx.BoxSizer(wx.VERTICAL)
## Filter list.
self.filter_list = wx.ListBox(self, choices=self.filters.keys())
self.filter_list.SetMinSize((100, 200))
self.Bind(wx.EVT_LISTBOX_DCLICK, self.OnEditFilter, self.filter_list)
dialog_box.Add(self.filter_list, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
## Buttons.
button_box = wx.BoxSizer(wx.HORIZONTAL)
dialog_box.Add(button_box, flag=wx.CENTER|wx.ALL, border=5)
add_button = wx.Button(self, wx.ID_ADD)
add_button.Bind(wx.EVT_BUTTON, self.OnAddFilter)
button_box.Add(add_button, flag=wx.CENTER)
remove_button = wx.Button(self, wx.ID_REMOVE)
remove_button.Bind(wx.EVT_BUTTON, self.OnRemoveFilter)
button_box.Add(remove_button, flag=wx.CENTER)
self.SetSizerAndFit(dialog_box)
self.Bind(wx.EVT_CLOSE, self.OnClose)
def create_filter(self, f_text, col):
"""
Create a filter out of text.
"""
col_idx = self.table.headings.index(col)
return lambda i, x: eval(f_text.replace('x', 'float(x[{0}])'.format(col_idx)))
@property
def meta_filter(self):
"""
Create a meta-filter out of all the filters.
"""
filters = [self.create_filter(f, col) for f, col in
zip(self.filters.values(), self.filter_columns.values())]
return lambda i, x: all([f(i, x) for f in filters])
def edit_ok_callback(self, dlg, selection=None):
col, f = dlg.GetValue()
name = '{0}: {1}'.format(col, f)
if selection is not None and name == selection:
return
if name in self.filters:
raise ValueError('Filter "{0}" already exists'.format(name))
if not f:
raise ValueError('No function provided')
f_function = self.create_filter(f, col)
try:
self.table.apply_filter(f_function)
except Exception as e:
raise ValueError(e)
if selection is not None:
self.OnRemoveFilter(selection=selection)
self.table.apply_filter(f_function)
self.filters[name] = f
self.filter_columns[name] = col
self.filter_list.Items += [name]
def OnAddFilter(self, evt=None):
FilterEditDialog(self, self.table.headings, self.edit_ok_callback).Show()
def OnEditFilter(self, evt=None):
selection = self.filter_list.StringSelection
if not selection:
return
dlg = FilterEditDialog(self, self.table.headings, partial(self.edit_ok_callback, selection=selection),
title='Edit filter')
dlg.SetValue((self.filter_columns[selection], self.filters[selection]))
dlg.Show()
def OnRemoveFilter(self, evt=None, selection=None):
if selection is None:
selection = self.filter_list.StringSelection
if not selection:
return
try:
del self.filters[selection]
except KeyError:
pass
try:
del self.filter_columns[selection]
except KeyError:
pass
self.filter_list.Items = [x for x in self.filter_list.Items if x != selection]
self.table.apply_filter(self.meta_filter, afresh=True)
def OnClose(self, evt):
self.close_callback(self)
evt.Skip()
| {
"repo_name": "0/SpanishAcquisition",
"path": "spacq/gui/display/table/filter.py",
"copies": "2",
"size": "5349",
"license": "bsd-2-clause",
"hash": -1340728611309488000,
"line_mean": 26.2908163265,
"line_max": 104,
"alpha_frac": 0.7029351281,
"autogenerated": false,
"ratio": 2.930958904109589,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46338940322095895,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import zlib
import json
from io import BytesIO
import sys
import platform
from typing import TYPE_CHECKING
from PyQt5.QtWidgets import (QComboBox, QGridLayout, QLabel, QPushButton)
from electrum_mona.plugin import BasePlugin, hook
from electrum_mona.gui.qt.util import WaitingDialog, EnterButton, WindowModalDialog, read_QIcon
from electrum_mona.i18n import _
from electrum_mona.logging import get_logger
if TYPE_CHECKING:
from electrum_mona.gui.qt.transaction_dialog import TxDialog
_logger = get_logger(__name__)
try:
import amodem.audio
import amodem.main
import amodem.config
_logger.info('Audio MODEM is available.')
amodem.log.addHandler(amodem.logging.StreamHandler(sys.stderr))
amodem.log.setLevel(amodem.logging.INFO)
except ImportError:
amodem = None
_logger.info('Audio MODEM is not found.')
class Plugin(BasePlugin):
def __init__(self, parent, config, name):
BasePlugin.__init__(self, parent, config, name)
if self.is_available():
self.modem_config = amodem.config.slowest()
self.library_name = {
'Linux': 'libportaudio.so'
}[platform.system()]
def is_available(self):
return amodem is not None
def requires_settings(self):
return True
def settings_widget(self, window):
return EnterButton(_('Settings'), partial(self.settings_dialog, window))
def settings_dialog(self, window):
d = WindowModalDialog(window, _("Audio Modem Settings"))
layout = QGridLayout(d)
layout.addWidget(QLabel(_('Bit rate [kbps]: ')), 0, 0)
bitrates = list(sorted(amodem.config.bitrates.keys()))
def _index_changed(index):
bitrate = bitrates[index]
self.modem_config = amodem.config.bitrates[bitrate]
combo = QComboBox()
combo.addItems([str(x) for x in bitrates])
combo.currentIndexChanged.connect(_index_changed)
layout.addWidget(combo, 0, 1)
ok_button = QPushButton(_("OK"))
ok_button.clicked.connect(d.accept)
layout.addWidget(ok_button, 1, 1)
return bool(d.exec_())
@hook
def transaction_dialog(self, dialog: 'TxDialog'):
b = QPushButton()
b.setIcon(read_QIcon("speaker.png"))
def handler():
blob = dialog.tx.serialize()
self._send(parent=dialog, blob=blob)
b.clicked.connect(handler)
dialog.sharing_buttons.insert(-1, b)
@hook
def scan_text_edit(self, parent):
parent.addButton('microphone.png', partial(self._recv, parent),
_("Read from microphone"))
@hook
def show_text_edit(self, parent):
def handler():
blob = str(parent.toPlainText())
self._send(parent=parent, blob=blob)
parent.addButton('speaker.png', handler, _("Send to speaker"))
def _audio_interface(self):
interface = amodem.audio.Interface(config=self.modem_config)
return interface.load(self.library_name)
def _send(self, parent, blob):
def sender_thread():
with self._audio_interface() as interface:
src = BytesIO(blob)
dst = interface.player()
amodem.main.send(config=self.modem_config, src=src, dst=dst)
_logger.info(f'Sending: {repr(blob)}')
blob = zlib.compress(blob.encode('ascii'))
kbps = self.modem_config.modem_bps / 1e3
msg = 'Sending to Audio MODEM ({0:.1f} kbps)...'.format(kbps)
WaitingDialog(parent, msg, sender_thread)
def _recv(self, parent):
def receiver_thread():
with self._audio_interface() as interface:
src = interface.recorder()
dst = BytesIO()
amodem.main.recv(config=self.modem_config, src=src, dst=dst)
return dst.getvalue()
def on_finished(blob):
if blob:
blob = zlib.decompress(blob).decode('ascii')
_logger.info(f'Received: {repr(blob)}')
parent.setText(blob)
kbps = self.modem_config.modem_bps / 1e3
msg = 'Receiving from Audio MODEM ({0:.1f} kbps)...'.format(kbps)
WaitingDialog(parent, msg, receiver_thread, on_finished)
| {
"repo_name": "wakiyamap/electrum-mona",
"path": "electrum_mona/plugins/audio_modem/qt.py",
"copies": "1",
"size": "4318",
"license": "mit",
"hash": -7467821360944945000,
"line_mean": 31.223880597,
"line_max": 95,
"alpha_frac": 0.6194997684,
"autogenerated": false,
"ratio": 3.7943760984182777,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4913875866818278,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import zlib
import json
from io import BytesIO
import sys
import platform
from electrum_arg.plugins import BasePlugin, hook
from electrum_arg_gui.qt.util import WaitingDialog, EnterButton, WindowModalDialog
from electrum_arg.util import print_msg, print_error
from electrum_arg.i18n import _
from PyQt4.QtGui import *
from PyQt4.QtCore import *
try:
import amodem.audio
import amodem.main
import amodem.config
print_error('Audio MODEM is available.')
amodem.log.addHandler(amodem.logging.StreamHandler(sys.stderr))
amodem.log.setLevel(amodem.logging.INFO)
except ImportError:
amodem = None
print_error('Audio MODEM is not found.')
class Plugin(BasePlugin):
def __init__(self, parent, config, name):
BasePlugin.__init__(self, parent, config, name)
if self.is_available():
self.modem_config = amodem.config.slowest()
self.library_name = {
'Linux': 'libportaudio.so'
}[platform.system()]
def is_available(self):
return amodem is not None
def requires_settings(self):
return True
def settings_widget(self, window):
return EnterButton(_('Settings'), partial(self.settings_dialog, window))
def settings_dialog(self, window):
d = WindowModalDialog(window, _("Audio Modem Settings"))
layout = QGridLayout(d)
layout.addWidget(QLabel(_('Bit rate [kbps]: ')), 0, 0)
bitrates = list(sorted(amodem.config.bitrates.keys()))
def _index_changed(index):
bitrate = bitrates[index]
self.modem_config = amodem.config.bitrates[bitrate]
combo = QComboBox()
combo.addItems(map(str, bitrates))
combo.currentIndexChanged.connect(_index_changed)
layout.addWidget(combo, 0, 1)
ok_button = QPushButton(_("OK"))
ok_button.clicked.connect(d.accept)
layout.addWidget(ok_button, 1, 1)
return bool(d.exec_())
@hook
def transaction_dialog(self, dialog):
b = QPushButton()
b.setIcon(QIcon(":icons/speaker.png"))
def handler():
blob = json.dumps(dialog.tx.as_dict())
self._send(parent=dialog, blob=blob)
b.clicked.connect(handler)
dialog.sharing_buttons.insert(-1, b)
@hook
def scan_text_edit(self, parent):
parent.addButton(':icons/microphone.png', partial(self._recv, parent),
_("Read from microphone"))
@hook
def show_text_edit(self, parent):
def handler():
blob = str(parent.toPlainText())
self._send(parent=parent, blob=blob)
parent.addButton(':icons/speaker.png', handler, _("Send to speaker"))
def _audio_interface(self):
interface = amodem.audio.Interface(config=self.modem_config)
return interface.load(self.library_name)
def _send(self, parent, blob):
def sender_thread():
with self._audio_interface() as interface:
src = BytesIO(blob)
dst = interface.player()
amodem.main.send(config=self.modem_config, src=src, dst=dst)
print_msg('Sending:', repr(blob))
blob = zlib.compress(blob)
kbps = self.modem_config.modem_bps / 1e3
msg = 'Sending to Audio MODEM ({0:.1f} kbps)...'.format(kbps)
WaitingDialog(parent, msg, sender_thread)
def _recv(self, parent):
def receiver_thread():
with self._audio_interface() as interface:
src = interface.recorder()
dst = BytesIO()
amodem.main.recv(config=self.modem_config, src=src, dst=dst)
return dst.getvalue()
def on_finished(blob):
if blob:
blob = zlib.decompress(blob)
print_msg('Received:', repr(blob))
parent.setText(blob)
kbps = self.modem_config.modem_bps / 1e3
msg = 'Receiving from Audio MODEM ({0:.1f} kbps)...'.format(kbps)
WaitingDialog(parent, msg, receiver_thread, on_finished)
| {
"repo_name": "argentumproject/electrum-arg",
"path": "plugins/audio_modem/qt.py",
"copies": "1",
"size": "4102",
"license": "mit",
"hash": -7214316822654517000,
"line_mean": 31.2992125984,
"line_max": 82,
"alpha_frac": 0.6126279863,
"autogenerated": false,
"ratio": 3.848030018761726,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4960658005061726,
"avg_score": null,
"num_lines": null
} |
from functools import partial
import zlib
import json
from io import BytesIO
import sys
import platform
from electrum.plugin import BasePlugin, hook
from electrum.gui.qt.util import WaitingDialog, EnterButton, WindowModalDialog
from electrum.util import print_msg, print_error
from electrum.i18n import _
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import (QComboBox, QGridLayout, QLabel, QPushButton)
try:
import amodem.audio
import amodem.main
import amodem.config
print_error('Audio MODEM is available.')
amodem.log.addHandler(amodem.logging.StreamHandler(sys.stderr))
amodem.log.setLevel(amodem.logging.INFO)
except ImportError:
amodem = None
print_error('Audio MODEM is not found.')
class Plugin(BasePlugin):
def __init__(self, parent, config, name):
BasePlugin.__init__(self, parent, config, name)
if self.is_available():
self.modem_config = amodem.config.slowest()
self.library_name = {
'Linux': 'libportaudio.so'
}[platform.system()]
def is_available(self):
return amodem is not None
def requires_settings(self):
return True
def settings_widget(self, window):
return EnterButton(_('Settings'), partial(self.settings_dialog, window))
def settings_dialog(self, window):
d = WindowModalDialog(window, _("Audio Modem Settings"))
layout = QGridLayout(d)
layout.addWidget(QLabel(_('Bit rate [kbps]: ')), 0, 0)
bitrates = list(sorted(amodem.config.bitrates.keys()))
def _index_changed(index):
bitrate = bitrates[index]
self.modem_config = amodem.config.bitrates[bitrate]
combo = QComboBox()
combo.addItems([str(x) for x in bitrates])
combo.currentIndexChanged.connect(_index_changed)
layout.addWidget(combo, 0, 1)
ok_button = QPushButton(_("OK"))
ok_button.clicked.connect(d.accept)
layout.addWidget(ok_button, 1, 1)
return bool(d.exec_())
@hook
def transaction_dialog(self, dialog):
b = QPushButton()
b.setIcon(QIcon(":icons/speaker.png"))
def handler():
blob = json.dumps(dialog.tx.as_dict())
self._send(parent=dialog, blob=blob)
b.clicked.connect(handler)
dialog.sharing_buttons.insert(-1, b)
@hook
def scan_text_edit(self, parent):
parent.addButton(':icons/microphone.png', partial(self._recv, parent),
_("Read from microphone"))
@hook
def show_text_edit(self, parent):
def handler():
blob = str(parent.toPlainText())
self._send(parent=parent, blob=blob)
parent.addButton(':icons/speaker.png', handler, _("Send to speaker"))
def _audio_interface(self):
interface = amodem.audio.Interface(config=self.modem_config)
return interface.load(self.library_name)
def _send(self, parent, blob):
def sender_thread():
with self._audio_interface() as interface:
src = BytesIO(blob)
dst = interface.player()
amodem.main.send(config=self.modem_config, src=src, dst=dst)
print_msg('Sending:', repr(blob))
blob = zlib.compress(blob.encode('ascii'))
kbps = self.modem_config.modem_bps / 1e3
msg = 'Sending to Audio MODEM ({0:.1f} kbps)...'.format(kbps)
WaitingDialog(parent, msg, sender_thread)
def _recv(self, parent):
def receiver_thread():
with self._audio_interface() as interface:
src = interface.recorder()
dst = BytesIO()
amodem.main.recv(config=self.modem_config, src=src, dst=dst)
return dst.getvalue()
def on_finished(blob):
if blob:
blob = zlib.decompress(blob).decode('ascii')
print_msg('Received:', repr(blob))
parent.setText(blob)
kbps = self.modem_config.modem_bps / 1e3
msg = 'Receiving from Audio MODEM ({0:.1f} kbps)...'.format(kbps)
WaitingDialog(parent, msg, receiver_thread, on_finished)
| {
"repo_name": "asfin/electrum",
"path": "electrum/plugins/audio_modem/qt.py",
"copies": "2",
"size": "4199",
"license": "mit",
"hash": -4981217971730076000,
"line_mean": 31.8046875,
"line_max": 80,
"alpha_frac": 0.6160990712,
"autogenerated": false,
"ratio": 3.8522935779816514,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00009645061728395061,
"num_lines": 128
} |
from functools import partial
import zlib
import json
from io import BytesIO
import sys
import platform
from electrum.plugins import BasePlugin, hook
from electrum_gui.qt.util import WaitingDialog, EnterButton, WindowModalDialog
from electrum.util import print_msg, print_error
from electrum.i18n import _
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import (QComboBox, QGridLayout, QLabel, QPushButton)
try:
import amodem.audio
import amodem.main
import amodem.config
print_error('Audio MODEM is available.')
amodem.log.addHandler(amodem.logging.StreamHandler(sys.stderr))
amodem.log.setLevel(amodem.logging.INFO)
except ImportError:
amodem = None
print_error('Audio MODEM is not found.')
class Plugin(BasePlugin):
def __init__(self, parent, config, name):
BasePlugin.__init__(self, parent, config, name)
if self.is_available():
self.modem_config = amodem.config.slowest()
self.library_name = {
'Linux': 'libportaudio.so'
}[platform.system()]
def is_available(self):
return amodem is not None
def requires_settings(self):
return True
def settings_widget(self, window):
return EnterButton(_('Settings'), partial(self.settings_dialog, window))
def settings_dialog(self, window):
d = WindowModalDialog(window, _("Audio Modem Settings"))
layout = QGridLayout(d)
layout.addWidget(QLabel(_('Bit rate [kbps]: ')), 0, 0)
bitrates = list(sorted(amodem.config.bitrates.keys()))
def _index_changed(index):
bitrate = bitrates[index]
self.modem_config = amodem.config.bitrates[bitrate]
combo = QComboBox()
combo.addItems([str(x) for x in bitrates])
combo.currentIndexChanged.connect(_index_changed)
layout.addWidget(combo, 0, 1)
ok_button = QPushButton(_("OK"))
ok_button.clicked.connect(d.accept)
layout.addWidget(ok_button, 1, 1)
return bool(d.exec_())
@hook
def transaction_dialog(self, dialog):
b = QPushButton()
b.setIcon(QIcon(":icons/speaker.png"))
def handler():
blob = json.dumps(dialog.tx.as_dict())
self._send(parent=dialog, blob=blob)
b.clicked.connect(handler)
dialog.sharing_buttons.insert(-1, b)
@hook
def scan_text_edit(self, parent):
parent.addButton(':icons/microphone.png', partial(self._recv, parent),
_("Read from microphone"))
@hook
def show_text_edit(self, parent):
def handler():
blob = str(parent.toPlainText())
self._send(parent=parent, blob=blob)
parent.addButton(':icons/speaker.png', handler, _("Send to speaker"))
def _audio_interface(self):
interface = amodem.audio.Interface(config=self.modem_config)
return interface.load(self.library_name)
def _send(self, parent, blob):
def sender_thread():
with self._audio_interface() as interface:
src = BytesIO(blob)
dst = interface.player()
amodem.main.send(config=self.modem_config, src=src, dst=dst)
print_msg('Sending:', repr(blob))
blob = zlib.compress(blob.encode('ascii'))
kbps = self.modem_config.modem_bps / 1e3
msg = 'Sending to Audio MODEM ({0:.1f} kbps)...'.format(kbps)
WaitingDialog(parent, msg, sender_thread)
def _recv(self, parent):
def receiver_thread():
with self._audio_interface() as interface:
src = interface.recorder()
dst = BytesIO()
amodem.main.recv(config=self.modem_config, src=src, dst=dst)
return dst.getvalue()
def on_finished(blob):
if blob:
blob = zlib.decompress(blob).decode('ascii')
print_msg('Received:', repr(blob))
parent.setText(blob)
kbps = self.modem_config.modem_bps / 1e3
msg = 'Receiving from Audio MODEM ({0:.1f} kbps)...'.format(kbps)
WaitingDialog(parent, msg, receiver_thread, on_finished)
| {
"repo_name": "romanz/electrum",
"path": "plugins/audio_modem/qt.py",
"copies": "4",
"size": "4200",
"license": "mit",
"hash": 4611954606743897000,
"line_mean": 31.8125,
"line_max": 80,
"alpha_frac": 0.6161904762,
"autogenerated": false,
"ratio": 3.853211009174312,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00009645061728395061,
"num_lines": 128
} |
from functools import partial
alphacolor = (0,0,0)
basecolors = [alphacolor, (127, 178, 56), (247, 233, 163), (199, 199, 199),
(255, 0, 0), (160, 160, 255), (167, 167, 167), (0, 124, 0),
(255, 255, 255), (164, 168, 184), (151, 109, 77), (112, 112, 112),
(64, 64, 255), (143, 119, 72), (255, 252, 245), (216, 127, 51),
(178, 76, 216), (102, 153, 216), (229, 229, 51), (127, 204, 25),
(242, 127, 165), (76, 76, 76), (153, 153, 153), (76, 127, 153),
(127, 63, 178), (51, 76, 178), (102, 76, 51), (102, 127, 51),
(153, 51, 51), (25, 25, 25), (250, 238, 77), (92, 219, 213),
(74, 128, 255), (0, 217, 58), (129, 86, 49), (112, 2, 0)]
allcolors = [alphacolor, alphacolor, alphacolor, alphacolor, (90, 126, 40),
(110, 154, 48), (127, 178, 56), (67, 94, 30), (174, 164, 115),
(213, 201, 141), (247, 233, 163), (131, 123, 86),
(140, 140, 140), (172, 172, 172), (199, 199, 199),
(105, 105, 105), (180, 0, 0), (220, 0, 0), (255, 0, 0),
(135, 0, 0), (113, 113, 180), (138, 138, 220), (160, 160, 255),
(85, 85, 135), (118, 118, 118), (144, 144, 144), (167, 167, 167),
(88, 88, 88), (0, 88, 0), (0, 107, 0), (0, 124, 0), (0, 66, 0),
(180, 180, 180), (220, 220, 220), (255, 255, 255), (135, 135, 135),
(116, 119, 130), (141, 145, 159), (164, 168, 184), (87, 89, 97),
(107, 77, 54), (130, 94, 66), (151, 109, 77), (80, 58, 41),
(79, 79, 79), (97, 97, 97), (112, 112, 112), (59, 59, 59),
(45, 45, 180), (55, 55, 220), (64, 64, 255), (34, 34, 135),
(101, 84, 51), (123, 103, 62), (143, 119, 72), (76, 63, 38),
(180, 178, 173), (220, 217, 211), (255, 252, 245),
(135, 133, 130), (152, 90, 36), (186, 110, 44),
(216, 127, 51), (114, 67, 27), (126, 54, 152),
(154, 66, 186), (178, 76, 216), (94, 40, 114), (72, 108, 152),
(88, 132, 186), (102, 153, 216), (54, 81, 114),
(162, 162, 36), (198, 198, 44), (229, 229, 51),
(121, 121, 27), (90, 144, 18), (110, 176, 22), (127, 204, 25),
(67, 108, 13), (171, 90, 116), (209, 110, 142),
(242, 127, 165), (128, 67, 87), (54, 54, 54), (66, 66, 66),
(76, 76, 76), (40, 40, 40), (108, 108, 108), (132, 132, 132),
(153, 153, 153), (81, 81, 81), (54, 90, 108), (66, 110, 132),
(76, 127, 153), (40, 67, 81), (90, 44, 126), (110, 54, 154),
(127, 63, 178), (67, 33, 94), (36, 54, 126), (44, 66, 154),
(51, 76, 178), (27, 40, 94), (72, 54, 36), (88, 66, 44),
(102, 76, 51), (54, 40, 27), (72, 90, 36), (88, 110, 44),
(102, 127, 51), (54, 67, 27), (108, 36, 36), (132, 44, 44),
(153, 51, 51), (81, 27, 27), (18, 18, 18), (22, 22, 22),
(25, 25, 25), (13, 13, 13), (176, 168, 54), (216, 205, 66),
(250, 238, 77), (132, 126, 41), (65, 155, 150),
(79, 189, 184), (92, 219, 213), (49, 116, 113),
(52, 90, 180), (64, 110, 220), (74, 128, 255), (39, 68, 135),
(0, 153, 41), (0, 187, 50), (0, 217, 58), (0, 115, 31),
(91, 61, 35), (111, 74, 42), (129, 86, 49), (68, 46, 26),
(79, 1, 0), (97, 2, 0), (112, 2, 0), (59, 1, 0)]
allcolorsinversemap = {alphacolor: 3, (90, 126, 40): 4, (110, 154, 48): 5,
(127, 178, 56): 6, (67, 94, 30): 7, (174, 164, 115): 8,
(213, 201, 141): 9, (247, 233, 163): 10, (131, 123, 86): 11,
(140, 140, 140): 12, (172, 172, 172): 13, (199, 199, 199): 14,
(105, 105, 105): 15, (180, 0, 0): 16, (220, 0, 0): 17, (255, 0, 0): 18,
(135, 0, 0): 19, (113, 113, 180): 20, (138, 138, 220): 21,
(160, 160, 255): 22, (85, 85, 135): 23, (118, 118, 118): 24,
(144, 144, 144): 25, (167, 167, 167): 26, (88, 88, 88): 27,
(0, 88, 0): 28, (0, 107, 0): 29, (0, 124, 0): 30, (0, 66, 0): 31,
(180, 180, 180): 32, (220, 220, 220): 33, (255, 255, 255): 34,
(135, 135, 135): 35, (116, 119, 130): 36, (141, 145, 159): 37,
(164, 168, 184): 38, (87, 89, 97): 39, (107, 77, 54): 40,
(130, 94, 66): 41, (151, 109, 77): 42, (80, 58, 41): 43,
(79, 79, 79): 44, (97, 97, 97): 45, (112, 112, 112): 46,
(59, 59, 59): 47, (45, 45, 180): 48, (55, 55, 220): 49,
(64, 64, 255): 50, (34, 34, 135): 51, (101, 84, 51): 52,
(123, 103, 62): 53, (143, 119, 72): 54, (76, 63, 38): 55,
(180, 178, 173): 56, (220, 217, 211): 57, (255, 252, 245): 58,
(135, 133, 130): 59, (152, 90, 36): 60, (186, 110, 44): 61,
(216, 127, 51): 62, (114, 67, 27): 63, (126, 54, 152): 64,
(154, 66, 186): 65, (178, 76, 216): 66, (94, 40, 114): 67,
(72, 108, 152): 68, (88, 132, 186): 69, (102, 153, 216): 70,
(54, 81, 114): 71, (162, 162, 36): 72, (198, 198, 44): 73,
(229, 229, 51): 74, (121, 121, 27): 75, (90, 144, 18): 76,
(110, 176, 22): 77, (127, 204, 25): 78, (67, 108, 13): 79,
(171, 90, 116): 80, (209, 110, 142): 81, (242, 127, 165): 82,
(128, 67, 87): 83, (54, 54, 54): 84, (66, 66, 66): 85,
(76, 76, 76): 86, (40, 40, 40): 87, (108, 108, 108): 88,
(132, 132, 132): 89, (153, 153, 153): 90, (81, 81, 81): 91,
(54, 90, 108): 92, (66, 110, 132): 93, (76, 127, 153): 94,
(40, 67, 81): 95, (90, 44, 126): 96, (110, 54, 154): 97,
(127, 63, 178): 98, (67, 33, 94): 99, (36, 54, 126): 100,
(44, 66, 154): 101, (51, 76, 178): 102, (27, 40, 94): 103,
(72, 54, 36): 104, (88, 66, 44): 105, (102, 76, 51): 106,
(54, 40, 27): 107, (72, 90, 36): 108, (88, 110, 44): 109,
(102, 127, 51): 110, (54, 67, 27): 111, (108, 36, 36): 112,
(132, 44, 44): 113, (153, 51, 51): 114, (81, 27, 27): 115,
(18, 18, 18): 116, (22, 22, 22): 117, (25, 25, 25): 118,
(13, 13, 13): 119, (176, 168, 54): 120, (216, 205, 66): 121,
(250, 238, 77): 122, (132, 126, 41): 123, (65, 155, 150): 124,
(79, 189, 184): 125, (92, 219, 213): 126, (49, 116, 113): 127,
(52, 90, 180): 128, (64, 110, 220): 129, (74, 128, 255): 130,
(39, 68, 135): 131, (0, 153, 41): 132, (0, 187, 50): 133,
(0, 217, 58): 134, (0, 115, 31): 135, (91, 61, 35): 136,
(111, 74, 42): 137, (129, 86, 49): 138, (68, 46, 26): 139,
(79, 1, 0): 140, (97, 2, 0): 141, (112, 2, 0): 142, (59, 1, 0): 143}
estimationlookup = {
10:
[[[119, 117, 118, 103, 51, 51, 51, 48, 48, 49, 50],
[117, 118, 103, 103, 103, 51, 48, 48, 49, 49, 50],
[31, 87, 95, 103, 100, 131, 101, 48, 49, 49, 50],
[28, 135, 95, 95, 131, 131, 101, 128, 128, 50, 50],
[29, 135, 135, 127, 127, 127, 128, 128, 129, 129, 130],
[30, 132, 132, 127, 127, 127, 124, 128, 129, 129, 130],
[132, 132, 133, 133, 127, 124, 124, 124, 129, 130, 130],
[133, 133, 133, 133, 134, 124, 124, 125, 125, 125, 130],
[134, 134, 134, 134, 134, 124, 125, 125, 125, 126, 126],
[134, 134, 134, 134, 134, 134, 125, 125, 126, 126, 126],
[134, 134, 134, 134, 134, 134, 126, 126, 126, 126, 126]],
[[117, 118, 87, 103, 51, 51, 48, 48, 49, 49, 50],
[107, 87, 87, 103, 100, 51, 48, 48, 49, 49, 50],
[111, 111, 95, 95, 100, 131, 101, 102, 49, 50, 50],
[111, 111, 95, 95, 92, 131, 128, 128, 129, 50, 50],
[79, 7, 7, 127, 127, 127, 128, 128, 129, 129, 130],
[79, 132, 132, 127, 127, 124, 124, 129, 129, 130, 130],
[132, 132, 133, 127, 124, 124, 124, 125, 125, 130, 130],
[133, 133, 133, 133, 124, 124, 125, 125, 125, 126, 130],
[134, 134, 134, 134, 134, 125, 125, 125, 126, 126, 126],
[134, 134, 134, 134, 134, 125, 125, 126, 126, 126, 126],
[134, 134, 134, 134, 134, 125, 126, 126, 126, 126, 126]],
[[143, 115, 99, 99, 99, 51, 48, 48, 49, 49, 50],
[139, 107, 84, 99, 99, 96, 48, 48, 49, 50, 50],
[111, 55, 85, 86, 71, 101, 102, 102, 49, 50, 50],
[7, 108, 86, 91, 92, 23, 128, 128, 129, 50, 50],
[79, 7, 109, 127, 127, 93, 68, 129, 129, 130, 130],
[76, 4, 4, 127, 127, 124, 124, 69, 129, 130, 130],
[76, 76, 5, 127, 124, 124, 124, 125, 70, 130, 130],
[77, 77, 5, 124, 124, 124, 125, 125, 125, 126, 130],
[77, 77, 134, 134, 124, 125, 125, 125, 126, 126, 126],
[78, 134, 134, 134, 125, 125, 125, 126, 126, 126, 126],
[78, 134, 134, 134, 134, 125, 126, 126, 126, 126, 126]],
[[141, 115, 115, 99, 67, 96, 97, 48, 49, 50, 50],
[115, 115, 43, 99, 67, 96, 97, 97, 49, 50, 50],
[136, 136, 105, 91, 96, 23, 97, 98, 49, 50, 50],
[7, 108, 52, 27, 39, 23, 68, 20, 129, 50, 50],
[79, 109, 109, 45, 15, 68, 94, 69, 129, 130, 130],
[76, 4, 110, 15, 46, 94, 69, 69, 70, 130, 130],
[76, 5, 5, 5, 124, 124, 124, 125, 70, 70, 130],
[77, 77, 6, 6, 124, 124, 125, 125, 126, 126, 126],
[78, 78, 6, 6, 124, 125, 125, 126, 126, 126, 126],
[78, 78, 78, 6, 125, 125, 126, 126, 126, 126, 126],
[78, 78, 78, 78, 125, 126, 126, 126, 126, 126, 126]],
[[142, 112, 112, 67, 67, 96, 97, 98, 98, 50, 50],
[112, 112, 113, 83, 67, 97, 97, 98, 98, 50, 50],
[63, 137, 40, 83, 83, 97, 97, 98, 98, 50, 50],
[63, 137, 41, 45, 15, 23, 20, 20, 20, 130, 130],
[75, 75, 53, 11, 46, 36, 20, 20, 21, 21, 130],
[75, 5, 5, 11, 24, 89, 37, 69, 70, 70, 130],
[77, 5, 6, 6, 59, 12, 37, 70, 70, 70, 22],
[77, 78, 6, 6, 6, 90, 125, 125, 126, 126, 22],
[78, 78, 6, 6, 6, 125, 125, 126, 126, 126, 126],
[78, 78, 78, 6, 6, 125, 126, 126, 126, 126, 126],
[78, 78, 78, 78, 6, 126, 126, 126, 126, 126, 126]],
[[19, 113, 113, 114, 67, 64, 64, 98, 65, 66, 66],
[113, 113, 114, 83, 83, 64, 64, 98, 65, 66, 66],
[63, 114, 114, 83, 83, 64, 98, 65, 65, 66, 66],
[60, 60, 41, 83, 80, 80, 98, 65, 66, 66, 66],
[75, 123, 54, 11, 24, 89, 20, 20, 21, 21, 22],
[75, 123, 54, 11, 59, 12, 37, 21, 21, 21, 22],
[72, 72, 6, 6, 8, 90, 37, 38, 21, 22, 22],
[78, 78, 6, 6, 8, 90, 26, 38, 38, 22, 22],
[78, 78, 6, 6, 8, 26, 13, 126, 126, 126, 22],
[78, 78, 78, 6, 8, 56, 126, 126, 126, 126, 126],
[78, 78, 78, 78, 9, 9, 126, 126, 126, 126, 126]],
[[16, 114, 114, 114, 64, 64, 65, 65, 65, 66, 66],
[114, 114, 114, 114, 80, 64, 65, 65, 66, 66, 66],
[60, 114, 114, 80, 80, 80, 65, 65, 66, 66, 66],
[60, 60, 42, 80, 80, 80, 65, 65, 66, 66, 66],
[60, 61, 42, 42, 80, 80, 37, 21, 21, 21, 22],
[72, 72, 120, 54, 8, 90, 90, 38, 21, 22, 22],
[72, 72, 120, 8, 8, 90, 26, 38, 38, 22, 22],
[72, 72, 120, 8, 8, 26, 56, 32, 14, 22, 22],
[78, 73, 73, 121, 8, 9, 32, 14, 14, 14, 22],
[78, 73, 73, 121, 9, 9, 14, 14, 14, 33, 33],
[78, 74, 74, 74, 9, 9, 14, 14, 33, 33, 33]],
[[16, 16, 114, 114, 80, 64, 65, 65, 66, 66, 66],
[16, 114, 114, 114, 80, 80, 65, 65, 66, 66, 66],
[60, 114, 114, 80, 80, 80, 65, 66, 66, 66, 66],
[61, 61, 61, 80, 80, 81, 81, 66, 66, 66, 66],
[61, 61, 61, 80, 80, 81, 81, 66, 66, 66, 22],
[72, 62, 62, 8, 8, 81, 26, 38, 38, 22, 22],
[72, 120, 120, 8, 8, 8, 56, 32, 14, 22, 22],
[73, 73, 73, 121, 8, 9, 56, 14, 14, 14, 22],
[73, 73, 121, 121, 9, 9, 9, 14, 14, 33, 33],
[73, 74, 74, 121, 9, 9, 9, 57, 33, 33, 33],
[74, 74, 74, 74, 9, 10, 10, 57, 33, 33, 34]],
[[17, 17, 17, 114, 80, 80, 65, 66, 66, 66, 66],
[17, 17, 114, 80, 80, 81, 65, 66, 66, 66, 66],
[61, 61, 61, 80, 80, 81, 81, 66, 66, 66, 66],
[61, 61, 62, 80, 81, 81, 81, 66, 66, 66, 66],
[62, 62, 62, 62, 81, 81, 81, 82, 66, 66, 22],
[62, 62, 62, 62, 81, 81, 82, 82, 82, 22, 22],
[73, 73, 121, 121, 8, 9, 56, 14, 14, 14, 22],
[73, 73, 121, 121, 9, 9, 9, 14, 14, 33, 33],
[73, 74, 121, 121, 9, 9, 9, 57, 33, 33, 33],
[74, 74, 74, 122, 9, 10, 10, 57, 33, 33, 34],
[74, 74, 74, 122, 122, 10, 10, 10, 33, 58, 34]],
[[18, 18, 18, 18, 80, 81, 66, 66, 66, 66, 66],
[18, 18, 18, 80, 81, 81, 81, 66, 66, 66, 66],
[18, 62, 62, 81, 81, 81, 81, 82, 66, 66, 66],
[62, 62, 62, 62, 81, 81, 82, 82, 82, 66, 66],
[62, 62, 62, 62, 81, 82, 82, 82, 82, 82, 66],
[62, 62, 62, 62, 82, 82, 82, 82, 82, 82, 22],
[62, 62, 121, 121, 9, 9, 82, 82, 57, 33, 33],
[73, 121, 121, 121, 9, 9, 9, 57, 57, 33, 33],
[74, 74, 74, 122, 9, 10, 10, 57, 33, 33, 34],
[74, 74, 122, 122, 122, 10, 10, 10, 33, 58, 34],
[74, 74, 122, 122, 122, 10, 10, 10, 58, 58, 34]],
[[18, 18, 18, 18, 18, 81, 81, 66, 66, 66, 66],
[18, 18, 18, 18, 81, 81, 82, 82, 66, 66, 66],
[18, 18, 62, 62, 81, 82, 82, 82, 82, 66, 66],
[62, 62, 62, 62, 82, 82, 82, 82, 82, 82, 66],
[62, 62, 62, 62, 82, 82, 82, 82, 82, 82, 82],
[62, 62, 62, 62, 82, 82, 82, 82, 82, 82, 33],
[62, 62, 121, 121, 82, 82, 82, 82, 82, 33, 33],
[74, 74, 122, 122, 9, 10, 10, 10, 57, 33, 58],
[74, 74, 122, 122, 122, 10, 10, 10, 58, 58, 34],
[74, 122, 122, 122, 122, 10, 10, 10, 58, 58, 34],
[74, 122, 122, 122, 122, 10, 10, 10, 58, 58, 34]]]
}
estimationlookupdict = {}
def addestimate(n,todict=False):
'''adds genestimation(n) to estimationlookup or estimationlookupdict at index n'''
if todict:
global estimationlookup
estimationlookup[n] = genestimation(n)
else:
global estimationlookupdict
estimationlookupdict[n] = genestimationdict(n)
def genestimation(n):
'''returns a nested list by estimating approximate() on interval n in every axis'''
rl = []
for rn in range(n+1):
gl = []
for gn in range(n+1):
bl = []
for bn in range(n+1):
r = (rn+.5)*255/n
g = (gn+.5)*255/n
b = (bn+.5)*255/n
i = approximate((r,g,b))
bl.append(i)
gl.append(bl)
rl.append(gl)
return rl
def genestimationdict(n):
'''returns a dict with indexes (r,g,b) by estimating approximate() on interval n in every axis'''
lookup = {}
for rn in range(n+1):
for gn in range(n+1):
for bn in range(n+1):
r = (rn+.5)*255/n
g = (gn+.5)*255/n
b = (bn+.5)*255/n
i = approximate((r,g,b))
lookup[(rn,gn,bn)] = i
return lookup
def colordifference(testcolor,comparecolor):
'''returns rgb distance squared'''
d = ((testcolor[0]-comparecolor[0])**2+
(testcolor[1]-comparecolor[1])**2+
(testcolor[2]-comparecolor[2])**2)
return d
def approximate(color):
'''returns best minecraft color code from rgb'''
try:
return allcolorsinversemap[color]
except KeyError:
color = min(allcolors,key=partial(colordifference,color))
return allcolorsinversemap[color]
if alphacolor != (0,0,0):
addestimate(10)
| {
"repo_name": "spookymushroom/minecraftmap",
"path": "minecraftmap/constants.py",
"copies": "1",
"size": "14870",
"license": "mit",
"hash": 2770443148253081000,
"line_mean": 50.993006993,
"line_max": 101,
"alpha_frac": 0.4560860794,
"autogenerated": false,
"ratio": 2.4357084357084355,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.33917945151084355,
"avg_score": null,
"num_lines": null
} |
from functools import partial
__author__ = 'jakub.zygmunt'
import re
import sys
try:
import splunk.Intersplunk
in_splunk = True
except (NameError, ImportError):
in_splunk = False
class MyFormat(object):
def formatDigit(self, digit):
reversed = digit[::-1]
reversed_spaces = re.sub("(.{3})", "\\1 ", reversed)
normal_spaces = reversed_spaces[::-1].strip()
return normal_spaces
def format(self, value, sign=False, suffix=''):
match = re.search("^(-?)([0-9 ]+)(.*)", value)
ret = value
if match:
s = match.group(1)
ret = self.formatDigit(match.group(2))
if (sign):
valueWithSign = int(s + match.group(2))
signChar = '+' if valueWithSign>0 else '-' if valueWithSign < 0 else ''
ret = signChar + ret
value_suffix = match.group(3) if match.group(3) and suffix == '' else suffix
if not value_suffix == '' :
ret = ret + ' ' + value_suffix
return ret
def format_string(self, str, sign=False, suffix=''):
def change(matchobj, options):
return self.format(matchobj.group(1), sign = options['sign'], suffix = options['suffix'])
options = { 'sign':sign, 'suffix':suffix }
string_formatted = re.sub("([\-0-9]+)", partial(change, options=options) , str)
return string_formatted
def log(msg):
with open( "/opt/splunk/var/log/splunk/myformat.log", "a" ) as f:
f.write( msg + "\n")
def mapFieldsWithOptions(fields_string, signs_string):
fields = fields_string.split(',')
signs = signs_string.split(',')
# map signs
signsChar = [''] * len(fields)
for index, value in enumerate(signs):
signsChar[index] = value
#map field to sign
mappings = []
for index, value in enumerate(fields):
sign = False if signsChar[index].lower() in ['false', '0', 'no', 'n'] else True
mappings.append({'field':value, 'sign':sign})
# get sign
return mappings
#log("myformat.py, in_splunk=%s" % in_splunk)
if in_splunk:
#log("inside if")
# try:
(isgetinfo, sys.argv) = splunk.Intersplunk.isGetInfo(sys.argv)
args, kwargs = splunk.Intersplunk.getKeywordsAndOptions()
if isgetinfo:
# streaming, generating, retevs, reqsop, preop
splunk.Intersplunk.outputInfo(True, False, False, False, None)
(results, dummyresults, settings) = splunk.Intersplunk.getOrganizedResults()
fields_string = kwargs.get("fields", "value")
signs_string = kwargs.get("signs", "")
field_suffix = kwargs.get("suffix", "suffix")
# log("fields_string = %s, signs_string = %s" % ( fields_string, signs_string))
mappings = mapFieldsWithOptions(fields_string, signs_string)
# log("mappings %s" % mappings)
try:
formatter = MyFormat()
for result in results:
for mapping in mappings:
field_name = mapping['field']
withSign = mapping['sign']
try:
value = result[field_name]
except KeyError:
# If either field is missing, simply ignore
continue
value_formatted = formatter.format_string(value, sign=withSign, suffix=result[field_suffix])
# log("value=%s, value_formatted=%s" % (value, value_formatted))
result[field_name] = value_formatted
splunk.Intersplunk.outputResults(results)
except Exception, e:
log("Unhandled exception: %s" % e)
splunk.Intersplunk.generateErrorResults("Unhandled exception: %s" % (e,))
| {
"repo_name": "jakubincloud/splunk-commands",
"path": "MyFormat/myformat.py",
"copies": "1",
"size": "3687",
"license": "bsd-2-clause",
"hash": -1843594180271813400,
"line_mean": 33.1388888889,
"line_max": 108,
"alpha_frac": 0.5855709249,
"autogenerated": false,
"ratio": 3.7431472081218273,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9749008849056888,
"avg_score": 0.015941856792987794,
"num_lines": 108
} |
from functools import partial
class InvalidSpecError(Exception):
pass
class UnconvertedValue(object):
def __init__(self, string, reason):
self.string = string
self.reason = reason
def __nonzero__(self):
return False
def __str__(self):
return "%s, given=%r" % (self.reason, self.string)
def __repr__(self):
return '<UnconvertedValue string=%r reason=%r>' % (self.string,
self.reason)
class imemoize(object):
"""cache the return value of a method
This class is meant to be used as a decorator of methods. The return value
from a given method invocation will be cached on the instance whose method
was invoked. All arguments passed to a method decorated with memoize must
be hashable.
If a memoized method is invoked directly on its class the result will not
be cached. Instead the method will be invoked like a static method:
class Obj(object):
@memoize
def add_to(self, arg):
return self + arg
Obj.add_to(1) # not enough arguments
Obj.add_to(1, 2) # returns 3, result is not cached
http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/
"""
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
if obj is None:
return self.func
return partial(self, obj)
def __call__(self, *args, **kw):
obj = args[0]
try:
cache = obj.__cache
except AttributeError:
cache = obj.__cache = {}
key = (self.func, args[1:], frozenset(kw.items()))
try:
res = cache[key]
except KeyError:
res = cache[key] = self.func(*args, **kw)
return res
| {
"repo_name": "jeremylowery/stypes",
"path": "stypes/util.py",
"copies": "1",
"size": "1796",
"license": "mit",
"hash": 6705783758224215000,
"line_mean": 29.4406779661,
"line_max": 88,
"alpha_frac": 0.5985523385,
"autogenerated": false,
"ratio": 4.072562358276644,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00908425176031839,
"num_lines": 59
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.