nwo
stringlengths
6
76
sha
stringlengths
40
40
path
stringlengths
5
118
language
stringclasses
1 value
identifier
stringlengths
1
89
parameters
stringlengths
2
5.4k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
51.1k
docstring
stringlengths
1
17.6k
docstring_summary
stringlengths
0
7.02k
docstring_tokens
sequence
function
stringlengths
30
51.1k
function_tokens
sequence
url
stringlengths
85
218
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
svm.py
python
toPyModel
(model_ptr)
return m
toPyModel(model_ptr) -> svm_model Convert a ctypes POINTER(svm_model) to a Python svm_model
toPyModel(model_ptr) -> svm_model
[ "toPyModel", "(", "model_ptr", ")", "-", ">", "svm_model" ]
def toPyModel(model_ptr): """ toPyModel(model_ptr) -> svm_model Convert a ctypes POINTER(svm_model) to a Python svm_model """ if bool(model_ptr) == False: raise ValueError("Null pointer") m = model_ptr.contents m.__createfrom__ = 'C' return m
[ "def", "toPyModel", "(", "model_ptr", ")", ":", "if", "bool", "(", "model_ptr", ")", "==", "False", ":", "raise", "ValueError", "(", "\"Null pointer\"", ")", "m", "=", "model_ptr", ".", "contents", "m", ".", "__createfrom__", "=", "'C'", "return", "m" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/svm.py#L293-L303
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
svmutil.py
python
svm_read_problem
(data_file_name)
return (prob_y, prob_x)
svm_read_problem(data_file_name) -> [y, x] Read LIBSVM-format data from data_file_name and return labels y and data instances x.
svm_read_problem(data_file_name) -> [y, x]
[ "svm_read_problem", "(", "data_file_name", ")", "-", ">", "[", "y", "x", "]" ]
def svm_read_problem(data_file_name): """ svm_read_problem(data_file_name) -> [y, x] Read LIBSVM-format data from data_file_name and return labels y and data instances x. """ prob_y = [] prob_x = [] for line in open(data_file_name): line = line.split(None, 1) # In case an instance with all zero features if len(line) == 1: line += [''] label, features = line xi = {} for e in features.split(): ind, val = e.split(":") xi[int(ind)] = float(val) prob_y += [float(label)] prob_x += [xi] return (prob_y, prob_x)
[ "def", "svm_read_problem", "(", "data_file_name", ")", ":", "prob_y", "=", "[", "]", "prob_x", "=", "[", "]", "for", "line", "in", "open", "(", "data_file_name", ")", ":", "line", "=", "line", ".", "split", "(", "None", ",", "1", ")", "# In case an instance with all zero features", "if", "len", "(", "line", ")", "==", "1", ":", "line", "+=", "[", "''", "]", "label", ",", "features", "=", "line", "xi", "=", "{", "}", "for", "e", "in", "features", ".", "split", "(", ")", ":", "ind", ",", "val", "=", "e", ".", "split", "(", "\":\"", ")", "xi", "[", "int", "(", "ind", ")", "]", "=", "float", "(", "val", ")", "prob_y", "+=", "[", "float", "(", "label", ")", "]", "prob_x", "+=", "[", "xi", "]", "return", "(", "prob_y", ",", "prob_x", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/svmutil.py#L14-L34
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
svmutil.py
python
svm_load_model
(model_file_name)
return model
svm_load_model(model_file_name) -> model Load a LIBSVM model from model_file_name and return.
svm_load_model(model_file_name) -> model
[ "svm_load_model", "(", "model_file_name", ")", "-", ">", "model" ]
def svm_load_model(model_file_name): """ svm_load_model(model_file_name) -> model Load a LIBSVM model from model_file_name and return. """ model = libsvm.svm_load_model(model_file_name.encode()) if not model: print("can't open model file %s" % model_file_name) return None model = toPyModel(model) return model
[ "def", "svm_load_model", "(", "model_file_name", ")", ":", "model", "=", "libsvm", ".", "svm_load_model", "(", "model_file_name", ".", "encode", "(", ")", ")", "if", "not", "model", ":", "print", "(", "\"can't open model file %s\"", "%", "model_file_name", ")", "return", "None", "model", "=", "toPyModel", "(", "model", ")", "return", "model" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/svmutil.py#L36-L47
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
svmutil.py
python
svm_save_model
(model_file_name, model)
svm_save_model(model_file_name, model) -> None Save a LIBSVM model to the file model_file_name.
svm_save_model(model_file_name, model) -> None
[ "svm_save_model", "(", "model_file_name", "model", ")", "-", ">", "None" ]
def svm_save_model(model_file_name, model): """ svm_save_model(model_file_name, model) -> None Save a LIBSVM model to the file model_file_name. """ libsvm.svm_save_model(model_file_name.encode(), model)
[ "def", "svm_save_model", "(", "model_file_name", ",", "model", ")", ":", "libsvm", ".", "svm_save_model", "(", "model_file_name", ".", "encode", "(", ")", ",", "model", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/svmutil.py#L49-L55
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
svmutil.py
python
evaluations
(ty, pv)
return (ACC, MSE, SCC)
evaluations(ty, pv) -> (ACC, MSE, SCC) Calculate accuracy, mean squared error and squared correlation coefficient using the true values (ty) and predicted values (pv).
evaluations(ty, pv) -> (ACC, MSE, SCC)
[ "evaluations", "(", "ty", "pv", ")", "-", ">", "(", "ACC", "MSE", "SCC", ")" ]
def evaluations(ty, pv): """ evaluations(ty, pv) -> (ACC, MSE, SCC) Calculate accuracy, mean squared error and squared correlation coefficient using the true values (ty) and predicted values (pv). """ if len(ty) != len(pv): raise ValueError("len(ty) must equal to len(pv)") total_correct = total_error = 0 sumv = sumy = sumvv = sumyy = sumvy = 0 for v, y in zip(pv, ty): if y == v: total_correct += 1 total_error += (v-y)*(v-y) sumv += v sumy += y sumvv += v*v sumyy += y*y sumvy += v*y l = len(ty) ACC = 100.0*total_correct/l MSE = total_error/l try: SCC = ((l*sumvy-sumv*sumy)*(l*sumvy-sumv*sumy))/((l*sumvv-sumv*sumv)*(l*sumyy-sumy*sumy)) except: SCC = float('nan') return (ACC, MSE, SCC)
[ "def", "evaluations", "(", "ty", ",", "pv", ")", ":", "if", "len", "(", "ty", ")", "!=", "len", "(", "pv", ")", ":", "raise", "ValueError", "(", "\"len(ty) must equal to len(pv)\"", ")", "total_correct", "=", "total_error", "=", "0", "sumv", "=", "sumy", "=", "sumvv", "=", "sumyy", "=", "sumvy", "=", "0", "for", "v", ",", "y", "in", "zip", "(", "pv", ",", "ty", ")", ":", "if", "y", "==", "v", ":", "total_correct", "+=", "1", "total_error", "+=", "(", "v", "-", "y", ")", "*", "(", "v", "-", "y", ")", "sumv", "+=", "v", "sumy", "+=", "y", "sumvv", "+=", "v", "*", "v", "sumyy", "+=", "y", "*", "y", "sumvy", "+=", "v", "*", "y", "l", "=", "len", "(", "ty", ")", "ACC", "=", "100.0", "*", "total_correct", "/", "l", "MSE", "=", "total_error", "/", "l", "try", ":", "SCC", "=", "(", "(", "l", "*", "sumvy", "-", "sumv", "*", "sumy", ")", "*", "(", "l", "*", "sumvy", "-", "sumv", "*", "sumy", ")", ")", "/", "(", "(", "l", "*", "sumvv", "-", "sumv", "*", "sumv", ")", "*", "(", "l", "*", "sumyy", "-", "sumy", "*", "sumy", ")", ")", "except", ":", "SCC", "=", "float", "(", "'nan'", ")", "return", "(", "ACC", ",", "MSE", ",", "SCC", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/svmutil.py#L57-L84
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
svmutil.py
python
svm_train
(arg1, arg2=None, arg3=None)
svm_train(y, x [, options]) -> model | ACC | MSE svm_train(prob [, options]) -> model | ACC | MSE svm_train(prob, param) -> model | ACC| MSE Train an SVM model from data (y, x) or an svm_problem prob using 'options' or an svm_parameter param. If '-v' is specified in 'options' (i.e., cross validation) either accuracy (ACC) or mean-squared error (MSE) is returned. options: -s svm_type : set type of SVM (default 0) 0 -- C-SVC (multi-class classification) 1 -- nu-SVC (multi-class classification) 2 -- one-class SVM 3 -- epsilon-SVR (regression) 4 -- nu-SVR (regression) -t kernel_type : set type of kernel function (default 2) 0 -- linear: u'*v 1 -- polynomial: (gamma*u'*v + coef0)^degree 2 -- radial basis function: exp(-gamma*|u-v|^2) 3 -- sigmoid: tanh(gamma*u'*v + coef0) 4 -- precomputed kernel (kernel values in training_set_file) -d degree : set degree in kernel function (default 3) -g gamma : set gamma in kernel function (default 1/num_features) -r coef0 : set coef0 in kernel function (default 0) -c cost : set the parameter C of C-SVC, epsilon-SVR, and nu-SVR (default 1) -n nu : set the parameter nu of nu-SVC, one-class SVM, and nu-SVR (default 0.5) -p epsilon : set the epsilon in loss function of epsilon-SVR (default 0.1) -m cachesize : set cache memory size in MB (default 100) -e epsilon : set tolerance of termination criterion (default 0.001) -h shrinking : whether to use the shrinking heuristics, 0 or 1 (default 1) -b probability_estimates : whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0) -wi weight : set the parameter C of class i to weight*C, for C-SVC (default 1) -v n: n-fold cross validation mode -q : quiet mode (no outputs)
svm_train(y, x [, options]) -> model | ACC | MSE svm_train(prob [, options]) -> model | ACC | MSE svm_train(prob, param) -> model | ACC| MSE
[ "svm_train", "(", "y", "x", "[", "options", "]", ")", "-", ">", "model", "|", "ACC", "|", "MSE", "svm_train", "(", "prob", "[", "options", "]", ")", "-", ">", "model", "|", "ACC", "|", "MSE", "svm_train", "(", "prob", "param", ")", "-", ">", "model", "|", "ACC|", "MSE" ]
def svm_train(arg1, arg2=None, arg3=None): """ svm_train(y, x [, options]) -> model | ACC | MSE svm_train(prob [, options]) -> model | ACC | MSE svm_train(prob, param) -> model | ACC| MSE Train an SVM model from data (y, x) or an svm_problem prob using 'options' or an svm_parameter param. If '-v' is specified in 'options' (i.e., cross validation) either accuracy (ACC) or mean-squared error (MSE) is returned. options: -s svm_type : set type of SVM (default 0) 0 -- C-SVC (multi-class classification) 1 -- nu-SVC (multi-class classification) 2 -- one-class SVM 3 -- epsilon-SVR (regression) 4 -- nu-SVR (regression) -t kernel_type : set type of kernel function (default 2) 0 -- linear: u'*v 1 -- polynomial: (gamma*u'*v + coef0)^degree 2 -- radial basis function: exp(-gamma*|u-v|^2) 3 -- sigmoid: tanh(gamma*u'*v + coef0) 4 -- precomputed kernel (kernel values in training_set_file) -d degree : set degree in kernel function (default 3) -g gamma : set gamma in kernel function (default 1/num_features) -r coef0 : set coef0 in kernel function (default 0) -c cost : set the parameter C of C-SVC, epsilon-SVR, and nu-SVR (default 1) -n nu : set the parameter nu of nu-SVC, one-class SVM, and nu-SVR (default 0.5) -p epsilon : set the epsilon in loss function of epsilon-SVR (default 0.1) -m cachesize : set cache memory size in MB (default 100) -e epsilon : set tolerance of termination criterion (default 0.001) -h shrinking : whether to use the shrinking heuristics, 0 or 1 (default 1) -b probability_estimates : whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0) -wi weight : set the parameter C of class i to weight*C, for C-SVC (default 1) -v n: n-fold cross validation mode -q : quiet mode (no outputs) """ prob, param = None, None if isinstance(arg1, (list, tuple)): assert isinstance(arg2, (list, tuple)) y, x, options = arg1, arg2, arg3 param = svm_parameter(options) prob = svm_problem(y, x, isKernel=(param.kernel_type == PRECOMPUTED)) elif isinstance(arg1, svm_problem): prob = arg1 if isinstance(arg2, svm_parameter): param = arg2 else: param = svm_parameter(arg2) if prob == None or param == None: raise TypeError("Wrong types for the arguments") if param.kernel_type == PRECOMPUTED: for xi in prob.x_space: idx, val = xi[0].index, xi[0].value if xi[0].index != 0: raise ValueError('Wrong input format: first column must be 0:sample_serial_number') if val <= 0 or val > prob.n: raise ValueError('Wrong input format: sample_serial_number out of range') if param.gamma == 0 and prob.n > 0: param.gamma = 1.0 / prob.n libsvm.svm_set_print_string_function(param.print_func) err_msg = libsvm.svm_check_parameter(prob, param) if err_msg: raise ValueError('Error: %s' % err_msg) if param.cross_validation: l, nr_fold = prob.l, param.nr_fold target = (c_double * l)() libsvm.svm_cross_validation(prob, param, nr_fold, target) ACC, MSE, SCC = evaluations(prob.y[:l], target[:l]) if param.svm_type in [EPSILON_SVR, NU_SVR]: print("Cross Validation Mean squared error = %g" % MSE) print("Cross Validation Squared correlation coefficient = %g" % SCC) return MSE else: print("Cross Validation Accuracy = %g%%" % ACC) return ACC else: m = libsvm.svm_train(prob, param) m = toPyModel(m) # If prob is destroyed, data including SVs pointed by m can remain. m.x_space = prob.x_space return m
[ "def", "svm_train", "(", "arg1", ",", "arg2", "=", "None", ",", "arg3", "=", "None", ")", ":", "prob", ",", "param", "=", "None", ",", "None", "if", "isinstance", "(", "arg1", ",", "(", "list", ",", "tuple", ")", ")", ":", "assert", "isinstance", "(", "arg2", ",", "(", "list", ",", "tuple", ")", ")", "y", ",", "x", ",", "options", "=", "arg1", ",", "arg2", ",", "arg3", "param", "=", "svm_parameter", "(", "options", ")", "prob", "=", "svm_problem", "(", "y", ",", "x", ",", "isKernel", "=", "(", "param", ".", "kernel_type", "==", "PRECOMPUTED", ")", ")", "elif", "isinstance", "(", "arg1", ",", "svm_problem", ")", ":", "prob", "=", "arg1", "if", "isinstance", "(", "arg2", ",", "svm_parameter", ")", ":", "param", "=", "arg2", "else", ":", "param", "=", "svm_parameter", "(", "arg2", ")", "if", "prob", "==", "None", "or", "param", "==", "None", ":", "raise", "TypeError", "(", "\"Wrong types for the arguments\"", ")", "if", "param", ".", "kernel_type", "==", "PRECOMPUTED", ":", "for", "xi", "in", "prob", ".", "x_space", ":", "idx", ",", "val", "=", "xi", "[", "0", "]", ".", "index", ",", "xi", "[", "0", "]", ".", "value", "if", "xi", "[", "0", "]", ".", "index", "!=", "0", ":", "raise", "ValueError", "(", "'Wrong input format: first column must be 0:sample_serial_number'", ")", "if", "val", "<=", "0", "or", "val", ">", "prob", ".", "n", ":", "raise", "ValueError", "(", "'Wrong input format: sample_serial_number out of range'", ")", "if", "param", ".", "gamma", "==", "0", "and", "prob", ".", "n", ">", "0", ":", "param", ".", "gamma", "=", "1.0", "/", "prob", ".", "n", "libsvm", ".", "svm_set_print_string_function", "(", "param", ".", "print_func", ")", "err_msg", "=", "libsvm", ".", "svm_check_parameter", "(", "prob", ",", "param", ")", "if", "err_msg", ":", "raise", "ValueError", "(", "'Error: %s'", "%", "err_msg", ")", "if", "param", ".", "cross_validation", ":", "l", ",", "nr_fold", "=", "prob", ".", "l", ",", "param", ".", "nr_fold", "target", "=", "(", "c_double", "*", "l", ")", "(", ")", "libsvm", ".", "svm_cross_validation", "(", "prob", ",", "param", ",", "nr_fold", ",", "target", ")", "ACC", ",", "MSE", ",", "SCC", "=", "evaluations", "(", "prob", ".", "y", "[", ":", "l", "]", ",", "target", "[", ":", "l", "]", ")", "if", "param", ".", "svm_type", "in", "[", "EPSILON_SVR", ",", "NU_SVR", "]", ":", "print", "(", "\"Cross Validation Mean squared error = %g\"", "%", "MSE", ")", "print", "(", "\"Cross Validation Squared correlation coefficient = %g\"", "%", "SCC", ")", "return", "MSE", "else", ":", "print", "(", "\"Cross Validation Accuracy = %g%%\"", "%", "ACC", ")", "return", "ACC", "else", ":", "m", "=", "libsvm", ".", "svm_train", "(", "prob", ",", "param", ")", "m", "=", "toPyModel", "(", "m", ")", "# If prob is destroyed, data including SVs pointed by m can remain.", "m", ".", "x_space", "=", "prob", ".", "x_space", "return", "m" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/svmutil.py#L86-L171
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
svmutil.py
python
svm_predict
(y, x, m, options="")
return pred_labels, (ACC, MSE, SCC), pred_values
svm_predict(y, x, m [, options]) -> (p_labels, p_acc, p_vals) Predict data (y, x) with the SVM model m. options: -b probability_estimates: whether to predict probability estimates, 0 or 1 (default 0); for one-class SVM only 0 is supported. -q : quiet mode (no outputs). The return tuple contains p_labels: a list of predicted labels p_acc: a tuple including accuracy (for classification), mean-squared error, and squared correlation coefficient (for regression). p_vals: a list of decision values or probability estimates (if '-b 1' is specified). If k is the number of classes, for decision values, each element includes results of predicting k(k-1)/2 binary-class SVMs. For probabilities, each element contains k values indicating the probability that the testing instance is in each class. Note that the order of classes here is the same as 'model.label' field in the model structure.
svm_predict(y, x, m [, options]) -> (p_labels, p_acc, p_vals)
[ "svm_predict", "(", "y", "x", "m", "[", "options", "]", ")", "-", ">", "(", "p_labels", "p_acc", "p_vals", ")" ]
def svm_predict(y, x, m, options=""): """ svm_predict(y, x, m [, options]) -> (p_labels, p_acc, p_vals) Predict data (y, x) with the SVM model m. options: -b probability_estimates: whether to predict probability estimates, 0 or 1 (default 0); for one-class SVM only 0 is supported. -q : quiet mode (no outputs). The return tuple contains p_labels: a list of predicted labels p_acc: a tuple including accuracy (for classification), mean-squared error, and squared correlation coefficient (for regression). p_vals: a list of decision values or probability estimates (if '-b 1' is specified). If k is the number of classes, for decision values, each element includes results of predicting k(k-1)/2 binary-class SVMs. For probabilities, each element contains k values indicating the probability that the testing instance is in each class. Note that the order of classes here is the same as 'model.label' field in the model structure. """ def info(s): print(s) predict_probability = 0 argv = options.split() i = 0 while i < len(argv): if argv[i] == '-b': i += 1 predict_probability = int(argv[i]) elif argv[i] == '-q': info = print_null else: raise ValueError("Wrong options") i+=1 svm_type = m.get_svm_type() is_prob_model = m.is_probability_model() nr_class = m.get_nr_class() pred_labels = [] pred_values = [] if predict_probability: if not is_prob_model: raise ValueError("Model does not support probabiliy estimates") if svm_type in [NU_SVR, EPSILON_SVR]: info("Prob. model for test data: target value = predicted value + z,\n" "z: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=%g" % m.get_svr_probability()); nr_class = 0 prob_estimates = (c_double * nr_class)() for xi in x: xi, idx = gen_svm_nodearray(xi, isKernel=(m.param.kernel_type == PRECOMPUTED)) label = libsvm.svm_predict_probability(m, xi, prob_estimates) values = prob_estimates[:nr_class] pred_labels += [label] pred_values += [values] else: if is_prob_model: info("Model supports probability estimates, but disabled in predicton.") if svm_type in (ONE_CLASS, EPSILON_SVR, NU_SVC): nr_classifier = 1 else: nr_classifier = nr_class*(nr_class-1)//2 dec_values = (c_double * nr_classifier)() for xi in x: xi, idx = gen_svm_nodearray(xi, isKernel=(m.param.kernel_type == PRECOMPUTED)) label = libsvm.svm_predict_values(m, xi, dec_values) if(nr_class == 1): values = [1] else: values = dec_values[:nr_classifier] pred_labels += [label] pred_values += [values] ACC, MSE, SCC = evaluations(y, pred_labels) l = len(y) if svm_type in [EPSILON_SVR, NU_SVR]: info("Mean squared error = %g (regression)" % MSE) info("Squared correlation coefficient = %g (regression)" % SCC) else: info("Accuracy = %g%% (%d/%d) (classification)" % (ACC, int(l*ACC/100), l)) return pred_labels, (ACC, MSE, SCC), pred_values
[ "def", "svm_predict", "(", "y", ",", "x", ",", "m", ",", "options", "=", "\"\"", ")", ":", "def", "info", "(", "s", ")", ":", "print", "(", "s", ")", "predict_probability", "=", "0", "argv", "=", "options", ".", "split", "(", ")", "i", "=", "0", "while", "i", "<", "len", "(", "argv", ")", ":", "if", "argv", "[", "i", "]", "==", "'-b'", ":", "i", "+=", "1", "predict_probability", "=", "int", "(", "argv", "[", "i", "]", ")", "elif", "argv", "[", "i", "]", "==", "'-q'", ":", "info", "=", "print_null", "else", ":", "raise", "ValueError", "(", "\"Wrong options\"", ")", "i", "+=", "1", "svm_type", "=", "m", ".", "get_svm_type", "(", ")", "is_prob_model", "=", "m", ".", "is_probability_model", "(", ")", "nr_class", "=", "m", ".", "get_nr_class", "(", ")", "pred_labels", "=", "[", "]", "pred_values", "=", "[", "]", "if", "predict_probability", ":", "if", "not", "is_prob_model", ":", "raise", "ValueError", "(", "\"Model does not support probabiliy estimates\"", ")", "if", "svm_type", "in", "[", "NU_SVR", ",", "EPSILON_SVR", "]", ":", "info", "(", "\"Prob. model for test data: target value = predicted value + z,\\n\"", "\"z: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=%g\"", "%", "m", ".", "get_svr_probability", "(", ")", ")", "nr_class", "=", "0", "prob_estimates", "=", "(", "c_double", "*", "nr_class", ")", "(", ")", "for", "xi", "in", "x", ":", "xi", ",", "idx", "=", "gen_svm_nodearray", "(", "xi", ",", "isKernel", "=", "(", "m", ".", "param", ".", "kernel_type", "==", "PRECOMPUTED", ")", ")", "label", "=", "libsvm", ".", "svm_predict_probability", "(", "m", ",", "xi", ",", "prob_estimates", ")", "values", "=", "prob_estimates", "[", ":", "nr_class", "]", "pred_labels", "+=", "[", "label", "]", "pred_values", "+=", "[", "values", "]", "else", ":", "if", "is_prob_model", ":", "info", "(", "\"Model supports probability estimates, but disabled in predicton.\"", ")", "if", "svm_type", "in", "(", "ONE_CLASS", ",", "EPSILON_SVR", ",", "NU_SVC", ")", ":", "nr_classifier", "=", "1", "else", ":", "nr_classifier", "=", "nr_class", "*", "(", "nr_class", "-", "1", ")", "//", "2", "dec_values", "=", "(", "c_double", "*", "nr_classifier", ")", "(", ")", "for", "xi", "in", "x", ":", "xi", ",", "idx", "=", "gen_svm_nodearray", "(", "xi", ",", "isKernel", "=", "(", "m", ".", "param", ".", "kernel_type", "==", "PRECOMPUTED", ")", ")", "label", "=", "libsvm", ".", "svm_predict_values", "(", "m", ",", "xi", ",", "dec_values", ")", "if", "(", "nr_class", "==", "1", ")", ":", "values", "=", "[", "1", "]", "else", ":", "values", "=", "dec_values", "[", ":", "nr_classifier", "]", "pred_labels", "+=", "[", "label", "]", "pred_values", "+=", "[", "values", "]", "ACC", ",", "MSE", ",", "SCC", "=", "evaluations", "(", "y", ",", "pred_labels", ")", "l", "=", "len", "(", "y", ")", "if", "svm_type", "in", "[", "EPSILON_SVR", ",", "NU_SVR", "]", ":", "info", "(", "\"Mean squared error = %g (regression)\"", "%", "MSE", ")", "info", "(", "\"Squared correlation coefficient = %g (regression)\"", "%", "SCC", ")", "else", ":", "info", "(", "\"Accuracy = %g%% (%d/%d) (classification)\"", "%", "(", "ACC", ",", "int", "(", "l", "*", "ACC", "/", "100", ")", ",", "l", ")", ")", "return", "pred_labels", ",", "(", "ACC", ",", "MSE", ",", "SCC", ")", ",", "pred_values" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/svmutil.py#L173-L260
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/modpython_example.py
python
test
(req, name=Tests.__all__[0])
return """<html> <head> <title>PyCAPTCHA Example</title> </head> <body> <h1>PyCAPTCHA Example (for mod_python)</h1> <p> <b>%s</b>: %s </p> <p><img src="image?id=%s"/></p> <p> <form action="solution" method="get"> Enter the word shown: <input type="text" name="word"/> <input type="hidden" name="id" value="%s"/> </form> </p> <p> Or try... <ul> %s </ul> </p> </body> </html> """ % (test.__class__.__name__, test.__doc__, test.id, test.id, others)
Show a newly generated CAPTCHA of the given class. Default is the first class name given in Tests.__all__
Show a newly generated CAPTCHA of the given class. Default is the first class name given in Tests.__all__
[ "Show", "a", "newly", "generated", "CAPTCHA", "of", "the", "given", "class", ".", "Default", "is", "the", "first", "class", "name", "given", "in", "Tests", ".", "__all__" ]
def test(req, name=Tests.__all__[0]): """Show a newly generated CAPTCHA of the given class. Default is the first class name given in Tests.__all__ """ test = _getFactory(req).new(getattr(Tests, name)) # Make a list of tests other than the one we're using others = [] for t in Tests.__all__: if t != name: others.append('<li><a href="?name=%s">%s</a></li>' % (t,t)) others = "\n".join(others) return """<html> <head> <title>PyCAPTCHA Example</title> </head> <body> <h1>PyCAPTCHA Example (for mod_python)</h1> <p> <b>%s</b>: %s </p> <p><img src="image?id=%s"/></p> <p> <form action="solution" method="get"> Enter the word shown: <input type="text" name="word"/> <input type="hidden" name="id" value="%s"/> </form> </p> <p> Or try... <ul> %s </ul> </p> </body> </html> """ % (test.__class__.__name__, test.__doc__, test.id, test.id, others)
[ "def", "test", "(", "req", ",", "name", "=", "Tests", ".", "__all__", "[", "0", "]", ")", ":", "test", "=", "_getFactory", "(", "req", ")", ".", "new", "(", "getattr", "(", "Tests", ",", "name", ")", ")", "# Make a list of tests other than the one we're using", "others", "=", "[", "]", "for", "t", "in", "Tests", ".", "__all__", ":", "if", "t", "!=", "name", ":", "others", ".", "append", "(", "'<li><a href=\"?name=%s\">%s</a></li>'", "%", "(", "t", ",", "t", ")", ")", "others", "=", "\"\\n\"", ".", "join", "(", "others", ")", "return", "\"\"\"<html>\n<head>\n<title>PyCAPTCHA Example</title>\n</head>\n<body>\n<h1>PyCAPTCHA Example (for mod_python)</h1>\n<p>\n <b>%s</b>:\n %s\n</p>\n\n<p><img src=\"image?id=%s\"/></p>\n<p>\n <form action=\"solution\" method=\"get\">\n Enter the word shown:\n <input type=\"text\" name=\"word\"/>\n <input type=\"hidden\" name=\"id\" value=\"%s\"/>\n </form>\n</p>\n\n<p>\nOr try...\n<ul>\n%s\n</ul>\n</p>\n\n</body>\n</html>\n\"\"\"", "%", "(", "test", ".", "__class__", ".", "__name__", ",", "test", ".", "__doc__", ",", "test", ".", "id", ",", "test", ".", "id", ",", "others", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/modpython_example.py#L27-L69
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/modpython_example.py
python
image
(req, id)
return apache.OK
Generate an image for the CAPTCHA with the given ID string
Generate an image for the CAPTCHA with the given ID string
[ "Generate", "an", "image", "for", "the", "CAPTCHA", "with", "the", "given", "ID", "string" ]
def image(req, id): """Generate an image for the CAPTCHA with the given ID string""" test = _getFactory(req).get(id) if not test: raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND req.content_type = "image/jpeg" test.render().save(req, "JPEG") return apache.OK
[ "def", "image", "(", "req", ",", "id", ")", ":", "test", "=", "_getFactory", "(", "req", ")", ".", "get", "(", "id", ")", "if", "not", "test", ":", "raise", "apache", ".", "SERVER_RETURN", ",", "apache", ".", "HTTP_NOT_FOUND", "req", ".", "content_type", "=", "\"image/jpeg\"", "test", ".", "render", "(", ")", ".", "save", "(", "req", ",", "\"JPEG\"", ")", "return", "apache", ".", "OK" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/modpython_example.py#L72-L79
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/modpython_example.py
python
solution
(req, id, word)
return """<html> <head> <title>PyCAPTCHA Example</title> </head> <body> <h1>PyCAPTCHA Example</h1> <h2>%s</h2> <p><img src="image?id=%s"/></p> <p><b>%s</b></p> <p>You guessed: %s</p> <p>Possible solutions: %s</p> <p><a href="test">Try again</a></p> </body> </html> """ % (test.__class__.__name__, test.id, result, word, ", ".join(test.solutions))
Grade a CAPTCHA given a solution word
Grade a CAPTCHA given a solution word
[ "Grade", "a", "CAPTCHA", "given", "a", "solution", "word" ]
def solution(req, id, word): """Grade a CAPTCHA given a solution word""" test = _getFactory(req).get(id) if not test: raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND if not test.valid: # Invalid tests will always return False, to prevent # random trial-and-error attacks. This could be confusing to a user... result = "Test invalidated, try another test" elif test.testSolutions([word]): result = "Correct" else: result = "Incorrect" return """<html> <head> <title>PyCAPTCHA Example</title> </head> <body> <h1>PyCAPTCHA Example</h1> <h2>%s</h2> <p><img src="image?id=%s"/></p> <p><b>%s</b></p> <p>You guessed: %s</p> <p>Possible solutions: %s</p> <p><a href="test">Try again</a></p> </body> </html> """ % (test.__class__.__name__, test.id, result, word, ", ".join(test.solutions))
[ "def", "solution", "(", "req", ",", "id", ",", "word", ")", ":", "test", "=", "_getFactory", "(", "req", ")", ".", "get", "(", "id", ")", "if", "not", "test", ":", "raise", "apache", ".", "SERVER_RETURN", ",", "apache", ".", "HTTP_NOT_FOUND", "if", "not", "test", ".", "valid", ":", "# Invalid tests will always return False, to prevent", "# random trial-and-error attacks. This could be confusing to a user...", "result", "=", "\"Test invalidated, try another test\"", "elif", "test", ".", "testSolutions", "(", "[", "word", "]", ")", ":", "result", "=", "\"Correct\"", "else", ":", "result", "=", "\"Incorrect\"", "return", "\"\"\"<html>\n<head>\n<title>PyCAPTCHA Example</title>\n</head>\n<body>\n<h1>PyCAPTCHA Example</h1>\n<h2>%s</h2>\n<p><img src=\"image?id=%s\"/></p>\n<p><b>%s</b></p>\n<p>You guessed: %s</p>\n<p>Possible solutions: %s</p>\n<p><a href=\"test\">Try again</a></p>\n</body>\n</html>\n\"\"\"", "%", "(", "test", ".", "__class__", ".", "__name__", ",", "test", ".", "id", ",", "result", ",", "word", ",", "\", \"", ".", "join", "(", "test", ".", "solutions", ")", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/modpython_example.py#L82-L111
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/Captcha/Words.py
python
WordList.read
(self)
Read words from disk
Read words from disk
[ "Read", "words", "from", "disk" ]
def read(self): """Read words from disk""" f = open(os.path.join(File.dataDir, "words", self.fileName)) self.words = [] for line in f.xreadlines(): line = line.strip() if not line: continue if line[0] == '#': continue for word in line.split(): if self.minLength is not None and len(word) < self.minLength: continue if self.maxLength is not None and len(word) > self.maxLength: continue self.words.append(word)
[ "def", "read", "(", "self", ")", ":", "f", "=", "open", "(", "os", ".", "path", ".", "join", "(", "File", ".", "dataDir", ",", "\"words\"", ",", "self", ".", "fileName", ")", ")", "self", ".", "words", "=", "[", "]", "for", "line", "in", "f", ".", "xreadlines", "(", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "not", "line", ":", "continue", "if", "line", "[", "0", "]", "==", "'#'", ":", "continue", "for", "word", "in", "line", ".", "split", "(", ")", ":", "if", "self", ".", "minLength", "is", "not", "None", "and", "len", "(", "word", ")", "<", "self", ".", "minLength", ":", "continue", "if", "self", ".", "maxLength", "is", "not", "None", "and", "len", "(", "word", ")", ">", "self", ".", "maxLength", ":", "continue", "self", ".", "words", ".", "append", "(", "word", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/Captcha/Words.py#L26-L42
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/Captcha/Words.py
python
WordList.pick
(self)
return random.choice(self.words)
Pick a random word from the list, reading it in if necessary
Pick a random word from the list, reading it in if necessary
[ "Pick", "a", "random", "word", "from", "the", "list", "reading", "it", "in", "if", "necessary" ]
def pick(self): """Pick a random word from the list, reading it in if necessary""" if self.words is None: self.read() return random.choice(self.words)
[ "def", "pick", "(", "self", ")", ":", "if", "self", ".", "words", "is", "None", ":", "self", ".", "read", "(", ")", "return", "random", ".", "choice", "(", "self", ".", "words", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/Captcha/Words.py#L44-L48
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/Captcha/Base.py
python
BaseCaptcha.testSolutions
(self, solutions)
return numCorrect >= self.minCorrectSolutions and \ numIncorrect <= self.maxIncorrectSolutions
Test whether the given solutions are sufficient for this CAPTCHA. A given CAPTCHA can only be tested once, after that it is invalid and always returns False. This makes random guessing much less effective.
Test whether the given solutions are sufficient for this CAPTCHA. A given CAPTCHA can only be tested once, after that it is invalid and always returns False. This makes random guessing much less effective.
[ "Test", "whether", "the", "given", "solutions", "are", "sufficient", "for", "this", "CAPTCHA", ".", "A", "given", "CAPTCHA", "can", "only", "be", "tested", "once", "after", "that", "it", "is", "invalid", "and", "always", "returns", "False", ".", "This", "makes", "random", "guessing", "much", "less", "effective", "." ]
def testSolutions(self, solutions): """Test whether the given solutions are sufficient for this CAPTCHA. A given CAPTCHA can only be tested once, after that it is invalid and always returns False. This makes random guessing much less effective. """ if not self.valid: return False self.valid = False numCorrect = 0 numIncorrect = 0 for solution in solutions: if solution in self.solutions: numCorrect += 1 else: numIncorrect += 1 return numCorrect >= self.minCorrectSolutions and \ numIncorrect <= self.maxIncorrectSolutions
[ "def", "testSolutions", "(", "self", ",", "solutions", ")", ":", "if", "not", "self", ".", "valid", ":", "return", "False", "self", ".", "valid", "=", "False", "numCorrect", "=", "0", "numIncorrect", "=", "0", "for", "solution", "in", "solutions", ":", "if", "solution", "in", "self", ".", "solutions", ":", "numCorrect", "+=", "1", "else", ":", "numIncorrect", "+=", "1", "return", "numCorrect", ">=", "self", ".", "minCorrectSolutions", "and", "numIncorrect", "<=", "self", ".", "maxIncorrectSolutions" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/Captcha/Base.py#L45-L64
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/Captcha/Base.py
python
Factory.new
(self, cls, *args, **kwargs)
return inst
Create a new instance of our assigned BaseCaptcha subclass, passing it any extra arguments we're given. This stores the result for later testing.
Create a new instance of our assigned BaseCaptcha subclass, passing it any extra arguments we're given. This stores the result for later testing.
[ "Create", "a", "new", "instance", "of", "our", "assigned", "BaseCaptcha", "subclass", "passing", "it", "any", "extra", "arguments", "we", "re", "given", ".", "This", "stores", "the", "result", "for", "later", "testing", "." ]
def new(self, cls, *args, **kwargs): """Create a new instance of our assigned BaseCaptcha subclass, passing it any extra arguments we're given. This stores the result for later testing. """ self.clean() inst = cls(*args, **kwargs) self.storedInstances[inst.id] = inst return inst
[ "def", "new", "(", "self", ",", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "clean", "(", ")", "inst", "=", "cls", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "storedInstances", "[", "inst", ".", "id", "]", "=", "inst", "return", "inst" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/Captcha/Base.py#L76-L84
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/Captcha/Base.py
python
Factory.get
(self, id)
return self.storedInstances.get(id)
Retrieve the CAPTCHA with the given ID. If it's expired already, this will return None. A typical web application will need to new() a CAPTCHA when generating an html page, then get() it later when its images or sounds must be rendered.
Retrieve the CAPTCHA with the given ID. If it's expired already, this will return None. A typical web application will need to new() a CAPTCHA when generating an html page, then get() it later when its images or sounds must be rendered.
[ "Retrieve", "the", "CAPTCHA", "with", "the", "given", "ID", ".", "If", "it", "s", "expired", "already", "this", "will", "return", "None", ".", "A", "typical", "web", "application", "will", "need", "to", "new", "()", "a", "CAPTCHA", "when", "generating", "an", "html", "page", "then", "get", "()", "it", "later", "when", "its", "images", "or", "sounds", "must", "be", "rendered", "." ]
def get(self, id): """Retrieve the CAPTCHA with the given ID. If it's expired already, this will return None. A typical web application will need to new() a CAPTCHA when generating an html page, then get() it later when its images or sounds must be rendered. """ return self.storedInstances.get(id)
[ "def", "get", "(", "self", ",", "id", ")", ":", "return", "self", ".", "storedInstances", ".", "get", "(", "id", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/Captcha/Base.py#L86-L92
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/Captcha/Base.py
python
Factory.clean
(self)
Removed expired tests
Removed expired tests
[ "Removed", "expired", "tests" ]
def clean(self): """Removed expired tests""" expiredIds = [] now = time.time() for inst in self.storedInstances.itervalues(): if inst.creationTime + self.lifetime < now: expiredIds.append(inst.id) for id in expiredIds: del self.storedInstances[id]
[ "def", "clean", "(", "self", ")", ":", "expiredIds", "=", "[", "]", "now", "=", "time", ".", "time", "(", ")", "for", "inst", "in", "self", ".", "storedInstances", ".", "itervalues", "(", ")", ":", "if", "inst", ".", "creationTime", "+", "self", ".", "lifetime", "<", "now", ":", "expiredIds", ".", "append", "(", "inst", ".", "id", ")", "for", "id", "in", "expiredIds", ":", "del", "self", ".", "storedInstances", "[", "id", "]" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/Captcha/Base.py#L94-L102
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/Captcha/Base.py
python
Factory.test
(self, id, solutions)
return result
Test the given list of solutions against the BaseCaptcha instance created earlier with the given id. Returns True if the test passed, False on failure. In either case, the test is invalidated. Returns False in the case of an invalid id.
Test the given list of solutions against the BaseCaptcha instance created earlier with the given id. Returns True if the test passed, False on failure. In either case, the test is invalidated. Returns False in the case of an invalid id.
[ "Test", "the", "given", "list", "of", "solutions", "against", "the", "BaseCaptcha", "instance", "created", "earlier", "with", "the", "given", "id", ".", "Returns", "True", "if", "the", "test", "passed", "False", "on", "failure", ".", "In", "either", "case", "the", "test", "is", "invalidated", ".", "Returns", "False", "in", "the", "case", "of", "an", "invalid", "id", "." ]
def test(self, id, solutions): """Test the given list of solutions against the BaseCaptcha instance created earlier with the given id. Returns True if the test passed, False on failure. In either case, the test is invalidated. Returns False in the case of an invalid id. """ self.clean() inst = self.storedInstances.get(id) if not inst: return False result = inst.testSolutions(solutions) return result
[ "def", "test", "(", "self", ",", "id", ",", "solutions", ")", ":", "self", ".", "clean", "(", ")", "inst", "=", "self", ".", "storedInstances", ".", "get", "(", "id", ")", "if", "not", "inst", ":", "return", "False", "result", "=", "inst", ".", "testSolutions", "(", "solutions", ")", "return", "result" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/Captcha/Base.py#L104-L115
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/Captcha/File.py
python
RandomFileFactory._checkExtension
(self, name)
return False
Check the file against our given list of extensions
Check the file against our given list of extensions
[ "Check", "the", "file", "against", "our", "given", "list", "of", "extensions" ]
def _checkExtension(self, name): """Check the file against our given list of extensions""" for ext in self.extensions: if name.endswith(ext): return True return False
[ "def", "_checkExtension", "(", "self", ",", "name", ")", ":", "for", "ext", "in", "self", ".", "extensions", ":", "if", "name", ".", "endswith", "(", "ext", ")", ":", "return", "True", "return", "False" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/Captcha/File.py#L28-L33
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/Captcha/File.py
python
RandomFileFactory._findFullPaths
(self)
return paths
From our given file list, find a list of full paths to files
From our given file list, find a list of full paths to files
[ "From", "our", "given", "file", "list", "find", "a", "list", "of", "full", "paths", "to", "files" ]
def _findFullPaths(self): """From our given file list, find a list of full paths to files""" paths = [] for name in self.fileList: path = os.path.join(dataDir, self.basePath, name) if os.path.isdir(path): for content in os.listdir(path): if self._checkExtension(content): paths.append(os.path.join(path, content)) else: paths.append(path) return paths
[ "def", "_findFullPaths", "(", "self", ")", ":", "paths", "=", "[", "]", "for", "name", "in", "self", ".", "fileList", ":", "path", "=", "os", ".", "path", ".", "join", "(", "dataDir", ",", "self", ".", "basePath", ",", "name", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "for", "content", "in", "os", ".", "listdir", "(", "path", ")", ":", "if", "self", ".", "_checkExtension", "(", "content", ")", ":", "paths", ".", "append", "(", "os", ".", "path", ".", "join", "(", "path", ",", "content", ")", ")", "else", ":", "paths", ".", "append", "(", "path", ")", "return", "paths" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/Captcha/File.py#L35-L46
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/Captcha/Visual/Base.py
python
ImageCaptcha.getImage
(self)
return self._image
Get a PIL image representing this CAPTCHA test, creating it if necessary
Get a PIL image representing this CAPTCHA test, creating it if necessary
[ "Get", "a", "PIL", "image", "representing", "this", "CAPTCHA", "test", "creating", "it", "if", "necessary" ]
def getImage(self): """Get a PIL image representing this CAPTCHA test, creating it if necessary""" if not self._image: self._image = self.render() return self._image
[ "def", "getImage", "(", "self", ")", ":", "if", "not", "self", ".", "_image", ":", "self", ".", "_image", "=", "self", ".", "render", "(", ")", "return", "self", ".", "_image" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/Captcha/Visual/Base.py#L29-L33
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/Captcha/Visual/Base.py
python
ImageCaptcha.getLayers
(self)
return []
Subclasses must override this to return a list of Layer instances to render. Lists within the list of layers are recursively rendered.
Subclasses must override this to return a list of Layer instances to render. Lists within the list of layers are recursively rendered.
[ "Subclasses", "must", "override", "this", "to", "return", "a", "list", "of", "Layer", "instances", "to", "render", ".", "Lists", "within", "the", "list", "of", "layers", "are", "recursively", "rendered", "." ]
def getLayers(self): """Subclasses must override this to return a list of Layer instances to render. Lists within the list of layers are recursively rendered. """ return []
[ "def", "getLayers", "(", "self", ")", ":", "return", "[", "]" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/Captcha/Visual/Base.py#L35-L39
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/Captcha/Visual/Base.py
python
ImageCaptcha.render
(self, size=None)
return self._renderList(self._layers, Image.new("RGB", size))
Render this CAPTCHA, returning a PIL image
Render this CAPTCHA, returning a PIL image
[ "Render", "this", "CAPTCHA", "returning", "a", "PIL", "image" ]
def render(self, size=None): """Render this CAPTCHA, returning a PIL image""" if size is None: size = self.defaultSize img = Image.new("RGB", size) return self._renderList(self._layers, Image.new("RGB", size))
[ "def", "render", "(", "self", ",", "size", "=", "None", ")", ":", "if", "size", "is", "None", ":", "size", "=", "self", ".", "defaultSize", "img", "=", "Image", ".", "new", "(", "\"RGB\"", ",", "size", ")", "return", "self", ".", "_renderList", "(", "self", ".", "_layers", ",", "Image", ".", "new", "(", "\"RGB\"", ",", "size", ")", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/Captcha/Visual/Base.py#L41-L46
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/Captcha/Visual/Text.py
python
FontFactory.pick
(self)
return (fileName, size)
Returns a (fileName, size) tuple that can be passed to ImageFont.truetype()
Returns a (fileName, size) tuple that can be passed to ImageFont.truetype()
[ "Returns", "a", "(", "fileName", "size", ")", "tuple", "that", "can", "be", "passed", "to", "ImageFont", ".", "truetype", "()" ]
def pick(self): """Returns a (fileName, size) tuple that can be passed to ImageFont.truetype()""" fileName = File.RandomFileFactory.pick(self) size = int(random.uniform(self.minSize, self.maxSize) + 0.5) return (fileName, size)
[ "def", "pick", "(", "self", ")", ":", "fileName", "=", "File", ".", "RandomFileFactory", ".", "pick", "(", "self", ")", "size", "=", "int", "(", "random", ".", "uniform", "(", "self", ".", "minSize", ",", "self", ".", "maxSize", ")", "+", "0.5", ")", "return", "(", "fileName", ",", "size", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/Captcha/Visual/Text.py#L34-L38
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/Captcha/Visual/Distortions.py
python
WarpBase.getTransform
(self, image)
return lambda x, y: (x, y)
Return a transformation function, subclasses should override this
Return a transformation function, subclasses should override this
[ "Return", "a", "transformation", "function", "subclasses", "should", "override", "this" ]
def getTransform(self, image): """Return a transformation function, subclasses should override this""" return lambda x, y: (x, y)
[ "def", "getTransform", "(", "self", ",", "image", ")", ":", "return", "lambda", "x", ",", "y", ":", "(", "x", ",", "y", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/Captcha/Visual/Distortions.py#L50-L52
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/setup/my_install_data.py
python
Data_Files.debug_print
(self, msg)
Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true.
Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true.
[ "Print", "msg", "to", "stdout", "if", "the", "global", "DEBUG", "(", "taken", "from", "the", "DISTUTILS_DEBUG", "environment", "variable", ")", "flag", "is", "true", "." ]
def debug_print (self, msg): """Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true. """ from distutils.core import DEBUG if DEBUG: print msg
[ "def", "debug_print", "(", "self", ",", "msg", ")", ":", "from", "distutils", ".", "core", "import", "DEBUG", "if", "DEBUG", ":", "print", "msg" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/setup/my_install_data.py#L72-L78
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/setup/my_install_data.py
python
Data_Files.finalize
(self)
complete the files list by processing the given template
complete the files list by processing the given template
[ "complete", "the", "files", "list", "by", "processing", "the", "given", "template" ]
def finalize(self): """ complete the files list by processing the given template """ if self.finalized: return if self.files == None: self.files = [] if self.template != None: if type(self.template) == StringType: self.template = string.split(self.template,";") filelist = FileList(self.warn,self.debug_print) for line in self.template: filelist.process_template_line(string.strip(line)) filelist.sort() filelist.remove_duplicates() self.files.extend(filelist.files) self.finalized = 1
[ "def", "finalize", "(", "self", ")", ":", "if", "self", ".", "finalized", ":", "return", "if", "self", ".", "files", "==", "None", ":", "self", ".", "files", "=", "[", "]", "if", "self", ".", "template", "!=", "None", ":", "if", "type", "(", "self", ".", "template", ")", "==", "StringType", ":", "self", ".", "template", "=", "string", ".", "split", "(", "self", ".", "template", ",", "\";\"", ")", "filelist", "=", "FileList", "(", "self", ".", "warn", ",", "self", ".", "debug_print", ")", "for", "line", "in", "self", ".", "template", ":", "filelist", ".", "process_template_line", "(", "string", ".", "strip", "(", "line", ")", ")", "filelist", ".", "sort", "(", ")", "filelist", ".", "remove_duplicates", "(", ")", "self", ".", "files", ".", "extend", "(", "filelist", ".", "files", ")", "self", ".", "finalized", "=", "1" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/setup/my_install_data.py#L81-L96
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/setup/my_install_data.py
python
my_install_data.check_data
(self,d)
return d
check if data are in new format, if not create a suitable object. returns finalized data object
check if data are in new format, if not create a suitable object. returns finalized data object
[ "check", "if", "data", "are", "in", "new", "format", "if", "not", "create", "a", "suitable", "object", ".", "returns", "finalized", "data", "object" ]
def check_data(self,d): """ check if data are in new format, if not create a suitable object. returns finalized data object """ if not isinstance(d, Data_Files): self.warn(("old-style data files list found " "-- please convert to Data_Files instance")) if type(d) is TupleType: if len(d) != 2 or not (type(d[1]) is ListType): raise DistutilsSetupError, \ ("each element of 'data_files' option must be an " "Data File instance, a string or 2-tuple (string,[strings])") d = Data_Files(copy_to=d[0],files=d[1]) else: if not (type(d) is StringType): raise DistutilsSetupError, \ ("each element of 'data_files' option must be an " "Data File instance, a string or 2-tuple (string,[strings])") d = Data_Files(files=[d]) d.finalize() return d
[ "def", "check_data", "(", "self", ",", "d", ")", ":", "if", "not", "isinstance", "(", "d", ",", "Data_Files", ")", ":", "self", ".", "warn", "(", "(", "\"old-style data files list found \"", "\"-- please convert to Data_Files instance\"", ")", ")", "if", "type", "(", "d", ")", "is", "TupleType", ":", "if", "len", "(", "d", ")", "!=", "2", "or", "not", "(", "type", "(", "d", "[", "1", "]", ")", "is", "ListType", ")", ":", "raise", "DistutilsSetupError", ",", "(", "\"each element of 'data_files' option must be an \"", "\"Data File instance, a string or 2-tuple (string,[strings])\"", ")", "d", "=", "Data_Files", "(", "copy_to", "=", "d", "[", "0", "]", ",", "files", "=", "d", "[", "1", "]", ")", "else", ":", "if", "not", "(", "type", "(", "d", ")", "is", "StringType", ")", ":", "raise", "DistutilsSetupError", ",", "(", "\"each element of 'data_files' option must be an \"", "\"Data File instance, a string or 2-tuple (string,[strings])\"", ")", "d", "=", "Data_Files", "(", "files", "=", "[", "d", "]", ")", "d", ".", "finalize", "(", ")", "return", "d" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/setup/my_install_data.py#L105-L125
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/contrib/ezcaptcha.py
python
getChallenge
()
return key
Returns a string, which should be placed as a hidden field on a web form. This string identifies a particular challenge, and is needed later for: - retrieving the image file for viewing the challenge, via call to getImageData() - testing a response to the challenge, via call to testSolution() The format of the string is:: base64(id+":"+expirytime+":"+sha1(id, answer, expirytime, secret)) Where: - id is a pseudo-random id identifying this challenge instance, and used to locate the temporary file under which the image is stored - expirytime is unixtime in hex - answer is the plaintext string of the word on the challenge picture - secret is the secret signing key 'captchaSecretKey
Returns a string, which should be placed as a hidden field on a web form. This string identifies a particular challenge, and is needed later for: - retrieving the image file for viewing the challenge, via call to getImageData() - testing a response to the challenge, via call to testSolution()
[ "Returns", "a", "string", "which", "should", "be", "placed", "as", "a", "hidden", "field", "on", "a", "web", "form", ".", "This", "string", "identifies", "a", "particular", "challenge", "and", "is", "needed", "later", "for", ":", "-", "retrieving", "the", "image", "file", "for", "viewing", "the", "challenge", "via", "call", "to", "getImageData", "()", "-", "testing", "a", "response", "to", "the", "challenge", "via", "call", "to", "testSolution", "()" ]
def getChallenge(): """ Returns a string, which should be placed as a hidden field on a web form. This string identifies a particular challenge, and is needed later for: - retrieving the image file for viewing the challenge, via call to getImageData() - testing a response to the challenge, via call to testSolution() The format of the string is:: base64(id+":"+expirytime+":"+sha1(id, answer, expirytime, secret)) Where: - id is a pseudo-random id identifying this challenge instance, and used to locate the temporary file under which the image is stored - expirytime is unixtime in hex - answer is the plaintext string of the word on the challenge picture - secret is the secret signing key 'captchaSecretKey """ # get a CAPTCHA object g = PseudoGimpy() # retrieve text solution answer = g.solutions[0] # generate a unique id under which to save it id = _generateId(answer) # save the image to disk, so it can be delivered from the # browser's next request i = g.render() path = _getImagePath(id) f = file(path, "wb") i.save(f, "jpeg") f.close() # compute 'key' key = _encodeKey(id, answer) return key
[ "def", "getChallenge", "(", ")", ":", "# get a CAPTCHA object", "g", "=", "PseudoGimpy", "(", ")", "# retrieve text solution", "answer", "=", "g", ".", "solutions", "[", "0", "]", "# generate a unique id under which to save it", "id", "=", "_generateId", "(", "answer", ")", "# save the image to disk, so it can be delivered from the", "# browser's next request", "i", "=", "g", ".", "render", "(", ")", "path", "=", "_getImagePath", "(", "id", ")", "f", "=", "file", "(", "path", ",", "\"wb\"", ")", "i", ".", "save", "(", "f", ",", "\"jpeg\"", ")", "f", ".", "close", "(", ")", "# compute 'key'", "key", "=", "_encodeKey", "(", "id", ",", "answer", ")", "return", "key" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/contrib/ezcaptcha.py#L81-L120
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/contrib/ezcaptcha.py
python
testSolution
(key, guess)
Tests if guess is a correct solution
Tests if guess is a correct solution
[ "Tests", "if", "guess", "is", "a", "correct", "solution" ]
def testSolution(key, guess): """ Tests if guess is a correct solution """ try: id, expiry, sig = _decodeKey(key) # test for timeout if time.time() > expiry: # sorry, timed out, too late _delImage(id) return False # test for past usage of this key path = _getImagePath(id) if not os.path.isfile(path): # no such key, fail out return False # test for correct word if _signChallenge(id, guess, expiry) != sig: # sorry, wrong word return False # successful _delImage(id) # image no longer needed return True except: #traceback.print_exc() return False
[ "def", "testSolution", "(", "key", ",", "guess", ")", ":", "try", ":", "id", ",", "expiry", ",", "sig", "=", "_decodeKey", "(", "key", ")", "# test for timeout", "if", "time", ".", "time", "(", ")", ">", "expiry", ":", "# sorry, timed out, too late", "_delImage", "(", "id", ")", "return", "False", "# test for past usage of this key", "path", "=", "_getImagePath", "(", "id", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "# no such key, fail out", "return", "False", "# test for correct word", "if", "_signChallenge", "(", "id", ",", "guess", ",", "expiry", ")", "!=", "sig", ":", "# sorry, wrong word", "return", "False", "# successful", "_delImage", "(", "id", ")", "# image no longer needed", "return", "True", "except", ":", "#traceback.print_exc()", "return", "False" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/contrib/ezcaptcha.py#L126-L156
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/contrib/ezcaptcha.py
python
_encodeKey
(id, answer)
return key
Encodes the challenge ID and the answer into a string which is safe to give to a potentially hostile client The key is base64-encoding of 'id:expirytime:answer'
Encodes the challenge ID and the answer into a string which is safe to give to a potentially hostile client
[ "Encodes", "the", "challenge", "ID", "and", "the", "answer", "into", "a", "string", "which", "is", "safe", "to", "give", "to", "a", "potentially", "hostile", "client" ]
def _encodeKey(id, answer): """ Encodes the challenge ID and the answer into a string which is safe to give to a potentially hostile client The key is base64-encoding of 'id:expirytime:answer' """ expiryTime = int(time.time() + captchaTimeout) sig = _signChallenge(id, answer, expiryTime) raw = "%s:%x:%s" % (id, expiryTime, sig) key = base64.encodestring(raw).replace("\n", "") return key
[ "def", "_encodeKey", "(", "id", ",", "answer", ")", ":", "expiryTime", "=", "int", "(", "time", ".", "time", "(", ")", "+", "captchaTimeout", ")", "sig", "=", "_signChallenge", "(", "id", ",", "answer", ",", "expiryTime", ")", "raw", "=", "\"%s:%x:%s\"", "%", "(", "id", ",", "expiryTime", ",", "sig", ")", "key", "=", "base64", ".", "encodestring", "(", "raw", ")", ".", "replace", "(", "\"\\n\"", ",", "\"\"", ")", "return", "key" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/contrib/ezcaptcha.py#L161-L172
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/contrib/ezcaptcha.py
python
_decodeKey
(key)
return id, expiry, sig
decodes a given key, returns id, expiry time and signature
decodes a given key, returns id, expiry time and signature
[ "decodes", "a", "given", "key", "returns", "id", "expiry", "time", "and", "signature" ]
def _decodeKey(key): """ decodes a given key, returns id, expiry time and signature """ raw = base64.decodestring(key) id, expiry, sig = raw.split(":", 2) expiry = int(expiry, 16) return id, expiry, sig
[ "def", "_decodeKey", "(", "key", ")", ":", "raw", "=", "base64", ".", "decodestring", "(", "key", ")", "id", ",", "expiry", ",", "sig", "=", "raw", ".", "split", "(", "\":\"", ",", "2", ")", "expiry", "=", "int", "(", "expiry", ",", "16", ")", "return", "id", ",", "expiry", ",", "sig" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/contrib/ezcaptcha.py#L174-L181
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/contrib/ezcaptcha.py
python
_generateId
(solution)
return sha.new( "%s%s%s" % ( captchaSecretKey, solution, random.random())).hexdigest()[:10]
returns a pseudo-random id under which picture gets stored
returns a pseudo-random id under which picture gets stored
[ "returns", "a", "pseudo", "-", "random", "id", "under", "which", "picture", "gets", "stored" ]
def _generateId(solution): """ returns a pseudo-random id under which picture gets stored """ return sha.new( "%s%s%s" % ( captchaSecretKey, solution, random.random())).hexdigest()[:10]
[ "def", "_generateId", "(", "solution", ")", ":", "return", "sha", ".", "new", "(", "\"%s%s%s\"", "%", "(", "captchaSecretKey", ",", "solution", ",", "random", ".", "random", "(", ")", ")", ")", ".", "hexdigest", "(", ")", "[", ":", "10", "]" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/contrib/ezcaptcha.py#L187-L194
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/contrib/ezcaptcha.py
python
_delImage
(id)
deletes image from tmp dir, no longer wanted
deletes image from tmp dir, no longer wanted
[ "deletes", "image", "from", "tmp", "dir", "no", "longer", "wanted" ]
def _delImage(id): """ deletes image from tmp dir, no longer wanted """ try: imgPath = _getImagePath(id) if os.path.isfile(imgPath): os.unlink(imgPath) except: traceback.print_exc() pass
[ "def", "_delImage", "(", "id", ")", ":", "try", ":", "imgPath", "=", "_getImagePath", "(", "id", ")", "if", "os", ".", "path", ".", "isfile", "(", "imgPath", ")", ":", "os", ".", "unlink", "(", "imgPath", ")", "except", ":", "traceback", ".", "print_exc", "(", ")", "pass" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/contrib/ezcaptcha.py#L199-L209
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/contrib/ezcaptcha.py
python
_demo
()
Presents a demo of this captcha module. If you run this file as a CGI in your web server, you'll see the demo in action
Presents a demo of this captcha module. If you run this file as a CGI in your web server, you'll see the demo in action
[ "Presents", "a", "demo", "of", "this", "captcha", "module", ".", "If", "you", "run", "this", "file", "as", "a", "CGI", "in", "your", "web", "server", "you", "ll", "see", "the", "demo", "in", "action" ]
def _demo(): """ Presents a demo of this captcha module. If you run this file as a CGI in your web server, you'll see the demo in action """ import cgi fields = cgi.FieldStorage() cmd = fields.getvalue("cmd", "") if not cmd: # first view key = getChallenge() print """Content-Type: text/html <html> <head> <title>ezcaptcha demo</title> <head> <body> <h1>ezcaptcha demo</h1> <form method="POST"> <input type="hidden" name="cmd" value="answerCaptcha"> <input type="hidden" name="captchaKey" value="%s"> <img src="?cmd=showCaptchaImg&captchaKey=%s"> <br> Please type in the word you see in the image above:<br> <input type="text" name="captchaAnswer"><br> <input type="submit" value="Submit"> </form> </body> </html> """ % (key, key) elif cmd == 'showCaptchaImg': # answer browser request for the CAPTCHA challenge image key = fields.getvalue("captchaKey") bindata = getImageData(key) print "Content-Type: image/jpeg" print print bindata elif cmd == 'answerCaptcha': # user has posted in an answer key = fields.getvalue("captchaKey") guess = fields.getvalue("captchaAnswer") # test user's answer if testSolution(key, guess) == True: # successful print """Content-Type: text/html <html> <head> <title>ezcaptcha demo</title> </head> <body> <h1>ezcaptcha demo</h1> Successful!<br> <br> <a href="">Click here</a> for another demo </body> </html> """ else: # failed print """Content-Type: text/html <html> <head> <title>ezcaptcha demo</title> <head> <body> <h1>ezcaptcha demo</h1> Sorry - that was wrong! <form method="POST"> <input type="hidden" name="cmd" value="answerCaptcha"> <input type="hidden" name="captchaKey" value="%s"> <img src="?cmd=showCaptchaImg&captchaKey=%s"> <br> Please type in the word you see in the image above:<br> <input type="text" name="captchaAnswer"><br> <input type="submit" value="Submit"> </form> </body> </html> """ % (key, key)
[ "def", "_demo", "(", ")", ":", "import", "cgi", "fields", "=", "cgi", ".", "FieldStorage", "(", ")", "cmd", "=", "fields", ".", "getvalue", "(", "\"cmd\"", ",", "\"\"", ")", "if", "not", "cmd", ":", "# first view", "key", "=", "getChallenge", "(", ")", "print", "\"\"\"Content-Type: text/html\n\n<html>\n <head>\n <title>ezcaptcha demo</title>\n <head>\n <body>\n <h1>ezcaptcha demo</h1>\n <form method=\"POST\">\n <input type=\"hidden\" name=\"cmd\" value=\"answerCaptcha\">\n <input type=\"hidden\" name=\"captchaKey\" value=\"%s\">\n <img src=\"?cmd=showCaptchaImg&captchaKey=%s\">\n <br>\n Please type in the word you see in the image above:<br>\n <input type=\"text\" name=\"captchaAnswer\"><br>\n <input type=\"submit\" value=\"Submit\">\n </form>\n </body>\n</html>\n\"\"\"", "%", "(", "key", ",", "key", ")", "elif", "cmd", "==", "'showCaptchaImg'", ":", "# answer browser request for the CAPTCHA challenge image", "key", "=", "fields", ".", "getvalue", "(", "\"captchaKey\"", ")", "bindata", "=", "getImageData", "(", "key", ")", "print", "\"Content-Type: image/jpeg\"", "print", "print", "bindata", "elif", "cmd", "==", "'answerCaptcha'", ":", "# user has posted in an answer", "key", "=", "fields", ".", "getvalue", "(", "\"captchaKey\"", ")", "guess", "=", "fields", ".", "getvalue", "(", "\"captchaAnswer\"", ")", "# test user's answer", "if", "testSolution", "(", "key", ",", "guess", ")", "==", "True", ":", "# successful", "print", "\"\"\"Content-Type: text/html\n\n<html>\n <head>\n <title>ezcaptcha demo</title>\n </head>\n <body>\n <h1>ezcaptcha demo</h1>\n Successful!<br>\n <br>\n <a href=\"\">Click here</a> for another demo\n </body>\n</html>\n\"\"\"", "else", ":", "# failed", "print", "\"\"\"Content-Type: text/html\n\n<html>\n <head>\n <title>ezcaptcha demo</title>\n <head>\n <body>\n <h1>ezcaptcha demo</h1>\n Sorry - that was wrong!\n <form method=\"POST\">\n <input type=\"hidden\" name=\"cmd\" value=\"answerCaptcha\">\n <input type=\"hidden\" name=\"captchaKey\" value=\"%s\">\n <img src=\"?cmd=showCaptchaImg&captchaKey=%s\">\n <br>\n Please type in the word you see in the image above:<br>\n <input type=\"text\" name=\"captchaAnswer\"><br>\n <input type=\"submit\" value=\"Submit\">\n </form>\n </body>\n</html>\n\"\"\"", "%", "(", "key", ",", "key", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/contrib/ezcaptcha.py#L213-L301
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib/Captcha/Words.py
python
WordList.read
(self)
Read words from disk
Read words from disk
[ "Read", "words", "from", "disk" ]
def read(self): """Read words from disk""" f = open(os.path.join(File.dataDir, "words", self.fileName)) self.words = [] for line in f.xreadlines(): line = line.strip() if not line: continue if line[0] == '#': continue for word in line.split(): if self.minLength is not None and len(word) < self.minLength: continue if self.maxLength is not None and len(word) > self.maxLength: continue self.words.append(word)
[ "def", "read", "(", "self", ")", ":", "f", "=", "open", "(", "os", ".", "path", ".", "join", "(", "File", ".", "dataDir", ",", "\"words\"", ",", "self", ".", "fileName", ")", ")", "self", ".", "words", "=", "[", "]", "for", "line", "in", "f", ".", "xreadlines", "(", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "not", "line", ":", "continue", "if", "line", "[", "0", "]", "==", "'#'", ":", "continue", "for", "word", "in", "line", ".", "split", "(", ")", ":", "if", "self", ".", "minLength", "is", "not", "None", "and", "len", "(", "word", ")", "<", "self", ".", "minLength", ":", "continue", "if", "self", ".", "maxLength", "is", "not", "None", "and", "len", "(", "word", ")", ">", "self", ".", "maxLength", ":", "continue", "self", ".", "words", ".", "append", "(", "word", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib/Captcha/Words.py#L26-L42
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib/Captcha/Words.py
python
WordList.pick
(self)
return random.choice(self.words)
Pick a random word from the list, reading it in if necessary
Pick a random word from the list, reading it in if necessary
[ "Pick", "a", "random", "word", "from", "the", "list", "reading", "it", "in", "if", "necessary" ]
def pick(self): """Pick a random word from the list, reading it in if necessary""" if self.words is None: self.read() return random.choice(self.words)
[ "def", "pick", "(", "self", ")", ":", "if", "self", ".", "words", "is", "None", ":", "self", ".", "read", "(", ")", "return", "random", ".", "choice", "(", "self", ".", "words", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib/Captcha/Words.py#L44-L48
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib/Captcha/Base.py
python
BaseCaptcha.testSolutions
(self, solutions)
return numCorrect >= self.minCorrectSolutions and \ numIncorrect <= self.maxIncorrectSolutions
Test whether the given solutions are sufficient for this CAPTCHA. A given CAPTCHA can only be tested once, after that it is invalid and always returns False. This makes random guessing much less effective.
Test whether the given solutions are sufficient for this CAPTCHA. A given CAPTCHA can only be tested once, after that it is invalid and always returns False. This makes random guessing much less effective.
[ "Test", "whether", "the", "given", "solutions", "are", "sufficient", "for", "this", "CAPTCHA", ".", "A", "given", "CAPTCHA", "can", "only", "be", "tested", "once", "after", "that", "it", "is", "invalid", "and", "always", "returns", "False", ".", "This", "makes", "random", "guessing", "much", "less", "effective", "." ]
def testSolutions(self, solutions): """Test whether the given solutions are sufficient for this CAPTCHA. A given CAPTCHA can only be tested once, after that it is invalid and always returns False. This makes random guessing much less effective. """ if not self.valid: return False self.valid = False numCorrect = 0 numIncorrect = 0 for solution in solutions: if solution in self.solutions: numCorrect += 1 else: numIncorrect += 1 return numCorrect >= self.minCorrectSolutions and \ numIncorrect <= self.maxIncorrectSolutions
[ "def", "testSolutions", "(", "self", ",", "solutions", ")", ":", "if", "not", "self", ".", "valid", ":", "return", "False", "self", ".", "valid", "=", "False", "numCorrect", "=", "0", "numIncorrect", "=", "0", "for", "solution", "in", "solutions", ":", "if", "solution", "in", "self", ".", "solutions", ":", "numCorrect", "+=", "1", "else", ":", "numIncorrect", "+=", "1", "return", "numCorrect", ">=", "self", ".", "minCorrectSolutions", "and", "numIncorrect", "<=", "self", ".", "maxIncorrectSolutions" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib/Captcha/Base.py#L45-L64
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib/Captcha/Base.py
python
Factory.new
(self, cls, *args, **kwargs)
return inst
Create a new instance of our assigned BaseCaptcha subclass, passing it any extra arguments we're given. This stores the result for later testing.
Create a new instance of our assigned BaseCaptcha subclass, passing it any extra arguments we're given. This stores the result for later testing.
[ "Create", "a", "new", "instance", "of", "our", "assigned", "BaseCaptcha", "subclass", "passing", "it", "any", "extra", "arguments", "we", "re", "given", ".", "This", "stores", "the", "result", "for", "later", "testing", "." ]
def new(self, cls, *args, **kwargs): """Create a new instance of our assigned BaseCaptcha subclass, passing it any extra arguments we're given. This stores the result for later testing. """ self.clean() inst = cls(*args, **kwargs) self.storedInstances[inst.id] = inst return inst
[ "def", "new", "(", "self", ",", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "clean", "(", ")", "inst", "=", "cls", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "storedInstances", "[", "inst", ".", "id", "]", "=", "inst", "return", "inst" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib/Captcha/Base.py#L76-L84
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib/Captcha/Base.py
python
Factory.get
(self, id)
return self.storedInstances.get(id)
Retrieve the CAPTCHA with the given ID. If it's expired already, this will return None. A typical web application will need to new() a CAPTCHA when generating an html page, then get() it later when its images or sounds must be rendered.
Retrieve the CAPTCHA with the given ID. If it's expired already, this will return None. A typical web application will need to new() a CAPTCHA when generating an html page, then get() it later when its images or sounds must be rendered.
[ "Retrieve", "the", "CAPTCHA", "with", "the", "given", "ID", ".", "If", "it", "s", "expired", "already", "this", "will", "return", "None", ".", "A", "typical", "web", "application", "will", "need", "to", "new", "()", "a", "CAPTCHA", "when", "generating", "an", "html", "page", "then", "get", "()", "it", "later", "when", "its", "images", "or", "sounds", "must", "be", "rendered", "." ]
def get(self, id): """Retrieve the CAPTCHA with the given ID. If it's expired already, this will return None. A typical web application will need to new() a CAPTCHA when generating an html page, then get() it later when its images or sounds must be rendered. """ return self.storedInstances.get(id)
[ "def", "get", "(", "self", ",", "id", ")", ":", "return", "self", ".", "storedInstances", ".", "get", "(", "id", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib/Captcha/Base.py#L86-L92
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib/Captcha/Base.py
python
Factory.clean
(self)
Removed expired tests
Removed expired tests
[ "Removed", "expired", "tests" ]
def clean(self): """Removed expired tests""" expiredIds = [] now = time.time() for inst in self.storedInstances.itervalues(): if inst.creationTime + self.lifetime < now: expiredIds.append(inst.id) for id in expiredIds: del self.storedInstances[id]
[ "def", "clean", "(", "self", ")", ":", "expiredIds", "=", "[", "]", "now", "=", "time", ".", "time", "(", ")", "for", "inst", "in", "self", ".", "storedInstances", ".", "itervalues", "(", ")", ":", "if", "inst", ".", "creationTime", "+", "self", ".", "lifetime", "<", "now", ":", "expiredIds", ".", "append", "(", "inst", ".", "id", ")", "for", "id", "in", "expiredIds", ":", "del", "self", ".", "storedInstances", "[", "id", "]" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib/Captcha/Base.py#L94-L102
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib/Captcha/Base.py
python
Factory.test
(self, id, solutions)
return result
Test the given list of solutions against the BaseCaptcha instance created earlier with the given id. Returns True if the test passed, False on failure. In either case, the test is invalidated. Returns False in the case of an invalid id.
Test the given list of solutions against the BaseCaptcha instance created earlier with the given id. Returns True if the test passed, False on failure. In either case, the test is invalidated. Returns False in the case of an invalid id.
[ "Test", "the", "given", "list", "of", "solutions", "against", "the", "BaseCaptcha", "instance", "created", "earlier", "with", "the", "given", "id", ".", "Returns", "True", "if", "the", "test", "passed", "False", "on", "failure", ".", "In", "either", "case", "the", "test", "is", "invalidated", ".", "Returns", "False", "in", "the", "case", "of", "an", "invalid", "id", "." ]
def test(self, id, solutions): """Test the given list of solutions against the BaseCaptcha instance created earlier with the given id. Returns True if the test passed, False on failure. In either case, the test is invalidated. Returns False in the case of an invalid id. """ self.clean() inst = self.storedInstances.get(id) if not inst: return False result = inst.testSolutions(solutions) return result
[ "def", "test", "(", "self", ",", "id", ",", "solutions", ")", ":", "self", ".", "clean", "(", ")", "inst", "=", "self", ".", "storedInstances", ".", "get", "(", "id", ")", "if", "not", "inst", ":", "return", "False", "result", "=", "inst", ".", "testSolutions", "(", "solutions", ")", "return", "result" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib/Captcha/Base.py#L104-L115
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib/Captcha/File.py
python
RandomFileFactory._checkExtension
(self, name)
return False
Check the file against our given list of extensions
Check the file against our given list of extensions
[ "Check", "the", "file", "against", "our", "given", "list", "of", "extensions" ]
def _checkExtension(self, name): """Check the file against our given list of extensions""" for ext in self.extensions: if name.endswith(ext): return True return False
[ "def", "_checkExtension", "(", "self", ",", "name", ")", ":", "for", "ext", "in", "self", ".", "extensions", ":", "if", "name", ".", "endswith", "(", "ext", ")", ":", "return", "True", "return", "False" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib/Captcha/File.py#L28-L33
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib/Captcha/File.py
python
RandomFileFactory._findFullPaths
(self)
return paths
From our given file list, find a list of full paths to files
From our given file list, find a list of full paths to files
[ "From", "our", "given", "file", "list", "find", "a", "list", "of", "full", "paths", "to", "files" ]
def _findFullPaths(self): """From our given file list, find a list of full paths to files""" paths = [] for name in self.fileList: path = os.path.join(dataDir, self.basePath, name) if os.path.isdir(path): for content in os.listdir(path): if self._checkExtension(content): paths.append(os.path.join(path, content)) else: paths.append(path) return paths
[ "def", "_findFullPaths", "(", "self", ")", ":", "paths", "=", "[", "]", "for", "name", "in", "self", ".", "fileList", ":", "path", "=", "os", ".", "path", ".", "join", "(", "dataDir", ",", "self", ".", "basePath", ",", "name", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "for", "content", "in", "os", ".", "listdir", "(", "path", ")", ":", "if", "self", ".", "_checkExtension", "(", "content", ")", ":", "paths", ".", "append", "(", "os", ".", "path", ".", "join", "(", "path", ",", "content", ")", ")", "else", ":", "paths", ".", "append", "(", "path", ")", "return", "paths" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib/Captcha/File.py#L35-L46
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib/Captcha/Visual/Base.py
python
ImageCaptcha.getImage
(self)
return self._image
Get a PIL image representing this CAPTCHA test, creating it if necessary
Get a PIL image representing this CAPTCHA test, creating it if necessary
[ "Get", "a", "PIL", "image", "representing", "this", "CAPTCHA", "test", "creating", "it", "if", "necessary" ]
def getImage(self): """Get a PIL image representing this CAPTCHA test, creating it if necessary""" if not self._image: self._image = self.render() return self._image
[ "def", "getImage", "(", "self", ")", ":", "if", "not", "self", ".", "_image", ":", "self", ".", "_image", "=", "self", ".", "render", "(", ")", "return", "self", ".", "_image" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib/Captcha/Visual/Base.py#L29-L33
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib/Captcha/Visual/Base.py
python
ImageCaptcha.getLayers
(self)
return []
Subclasses must override this to return a list of Layer instances to render. Lists within the list of layers are recursively rendered.
Subclasses must override this to return a list of Layer instances to render. Lists within the list of layers are recursively rendered.
[ "Subclasses", "must", "override", "this", "to", "return", "a", "list", "of", "Layer", "instances", "to", "render", ".", "Lists", "within", "the", "list", "of", "layers", "are", "recursively", "rendered", "." ]
def getLayers(self): """Subclasses must override this to return a list of Layer instances to render. Lists within the list of layers are recursively rendered. """ return []
[ "def", "getLayers", "(", "self", ")", ":", "return", "[", "]" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib/Captcha/Visual/Base.py#L35-L39
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib/Captcha/Visual/Base.py
python
ImageCaptcha.render
(self, size=None)
return self._renderList(self._layers, Image.new("RGB", size))
Render this CAPTCHA, returning a PIL image
Render this CAPTCHA, returning a PIL image
[ "Render", "this", "CAPTCHA", "returning", "a", "PIL", "image" ]
def render(self, size=None): """Render this CAPTCHA, returning a PIL image""" if size is None: size = self.defaultSize img = Image.new("RGB", size) return self._renderList(self._layers, Image.new("RGB", size))
[ "def", "render", "(", "self", ",", "size", "=", "None", ")", ":", "if", "size", "is", "None", ":", "size", "=", "self", ".", "defaultSize", "img", "=", "Image", ".", "new", "(", "\"RGB\"", ",", "size", ")", "return", "self", ".", "_renderList", "(", "self", ".", "_layers", ",", "Image", ".", "new", "(", "\"RGB\"", ",", "size", ")", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib/Captcha/Visual/Base.py#L41-L46
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib/Captcha/Visual/Text.py
python
FontFactory.pick
(self)
return (fileName, size)
Returns a (fileName, size) tuple that can be passed to ImageFont.truetype()
Returns a (fileName, size) tuple that can be passed to ImageFont.truetype()
[ "Returns", "a", "(", "fileName", "size", ")", "tuple", "that", "can", "be", "passed", "to", "ImageFont", ".", "truetype", "()" ]
def pick(self): """Returns a (fileName, size) tuple that can be passed to ImageFont.truetype()""" fileName = File.RandomFileFactory.pick(self) size = int(random.uniform(self.minSize, self.maxSize) + 0.5) return (fileName, size)
[ "def", "pick", "(", "self", ")", ":", "fileName", "=", "File", ".", "RandomFileFactory", ".", "pick", "(", "self", ")", "size", "=", "int", "(", "random", ".", "uniform", "(", "self", ".", "minSize", ",", "self", ".", "maxSize", ")", "+", "0.5", ")", "return", "(", "fileName", ",", "size", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib/Captcha/Visual/Text.py#L34-L38
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib/Captcha/Visual/Distortions.py
python
WarpBase.getTransform
(self, image)
return lambda x, y: (x, y)
Return a transformation function, subclasses should override this
Return a transformation function, subclasses should override this
[ "Return", "a", "transformation", "function", "subclasses", "should", "override", "this" ]
def getTransform(self, image): """Return a transformation function, subclasses should override this""" return lambda x, y: (x, y)
[ "def", "getTransform", "(", "self", ",", "image", ")", ":", "return", "lambda", "x", ",", "y", ":", "(", "x", ",", "y", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib/Captcha/Visual/Distortions.py#L50-L52
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Words.py
python
WordList.read
(self)
Read words from disk
Read words from disk
[ "Read", "words", "from", "disk" ]
def read(self): """Read words from disk""" f = open(os.path.join(File.dataDir, "words", self.fileName)) self.words = [] for line in f.xreadlines(): line = line.strip() if not line: continue if line[0] == '#': continue for word in line.split(): if self.minLength is not None and len(word) < self.minLength: continue if self.maxLength is not None and len(word) > self.maxLength: continue self.words.append(word)
[ "def", "read", "(", "self", ")", ":", "f", "=", "open", "(", "os", ".", "path", ".", "join", "(", "File", ".", "dataDir", ",", "\"words\"", ",", "self", ".", "fileName", ")", ")", "self", ".", "words", "=", "[", "]", "for", "line", "in", "f", ".", "xreadlines", "(", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "not", "line", ":", "continue", "if", "line", "[", "0", "]", "==", "'#'", ":", "continue", "for", "word", "in", "line", ".", "split", "(", ")", ":", "if", "self", ".", "minLength", "is", "not", "None", "and", "len", "(", "word", ")", "<", "self", ".", "minLength", ":", "continue", "if", "self", ".", "maxLength", "is", "not", "None", "and", "len", "(", "word", ")", ">", "self", ".", "maxLength", ":", "continue", "self", ".", "words", ".", "append", "(", "word", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Words.py#L26-L42
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Words.py
python
WordList.pick
(self)
return random.choice(self.words)
Pick a random word from the list, reading it in if necessary
Pick a random word from the list, reading it in if necessary
[ "Pick", "a", "random", "word", "from", "the", "list", "reading", "it", "in", "if", "necessary" ]
def pick(self): """Pick a random word from the list, reading it in if necessary""" if self.words is None: self.read() return random.choice(self.words)
[ "def", "pick", "(", "self", ")", ":", "if", "self", ".", "words", "is", "None", ":", "self", ".", "read", "(", ")", "return", "random", ".", "choice", "(", "self", ".", "words", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Words.py#L44-L48
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Base.py
python
BaseCaptcha.testSolutions
(self, solutions)
return numCorrect >= self.minCorrectSolutions and \ numIncorrect <= self.maxIncorrectSolutions
Test whether the given solutions are sufficient for this CAPTCHA. A given CAPTCHA can only be tested once, after that it is invalid and always returns False. This makes random guessing much less effective.
Test whether the given solutions are sufficient for this CAPTCHA. A given CAPTCHA can only be tested once, after that it is invalid and always returns False. This makes random guessing much less effective.
[ "Test", "whether", "the", "given", "solutions", "are", "sufficient", "for", "this", "CAPTCHA", ".", "A", "given", "CAPTCHA", "can", "only", "be", "tested", "once", "after", "that", "it", "is", "invalid", "and", "always", "returns", "False", ".", "This", "makes", "random", "guessing", "much", "less", "effective", "." ]
def testSolutions(self, solutions): """Test whether the given solutions are sufficient for this CAPTCHA. A given CAPTCHA can only be tested once, after that it is invalid and always returns False. This makes random guessing much less effective. """ if not self.valid: return False self.valid = False numCorrect = 0 numIncorrect = 0 for solution in solutions: if solution in self.solutions: numCorrect += 1 else: numIncorrect += 1 return numCorrect >= self.minCorrectSolutions and \ numIncorrect <= self.maxIncorrectSolutions
[ "def", "testSolutions", "(", "self", ",", "solutions", ")", ":", "if", "not", "self", ".", "valid", ":", "return", "False", "self", ".", "valid", "=", "False", "numCorrect", "=", "0", "numIncorrect", "=", "0", "for", "solution", "in", "solutions", ":", "if", "solution", "in", "self", ".", "solutions", ":", "numCorrect", "+=", "1", "else", ":", "numIncorrect", "+=", "1", "return", "numCorrect", ">=", "self", ".", "minCorrectSolutions", "and", "numIncorrect", "<=", "self", ".", "maxIncorrectSolutions" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Base.py#L45-L64
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Base.py
python
Factory.new
(self, cls, *args, **kwargs)
return inst
Create a new instance of our assigned BaseCaptcha subclass, passing it any extra arguments we're given. This stores the result for later testing.
Create a new instance of our assigned BaseCaptcha subclass, passing it any extra arguments we're given. This stores the result for later testing.
[ "Create", "a", "new", "instance", "of", "our", "assigned", "BaseCaptcha", "subclass", "passing", "it", "any", "extra", "arguments", "we", "re", "given", ".", "This", "stores", "the", "result", "for", "later", "testing", "." ]
def new(self, cls, *args, **kwargs): """Create a new instance of our assigned BaseCaptcha subclass, passing it any extra arguments we're given. This stores the result for later testing. """ self.clean() inst = cls(*args, **kwargs) self.storedInstances[inst.id] = inst return inst
[ "def", "new", "(", "self", ",", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "clean", "(", ")", "inst", "=", "cls", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "storedInstances", "[", "inst", ".", "id", "]", "=", "inst", "return", "inst" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Base.py#L76-L84
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Base.py
python
Factory.get
(self, id)
return self.storedInstances.get(id)
Retrieve the CAPTCHA with the given ID. If it's expired already, this will return None. A typical web application will need to new() a CAPTCHA when generating an html page, then get() it later when its images or sounds must be rendered.
Retrieve the CAPTCHA with the given ID. If it's expired already, this will return None. A typical web application will need to new() a CAPTCHA when generating an html page, then get() it later when its images or sounds must be rendered.
[ "Retrieve", "the", "CAPTCHA", "with", "the", "given", "ID", ".", "If", "it", "s", "expired", "already", "this", "will", "return", "None", ".", "A", "typical", "web", "application", "will", "need", "to", "new", "()", "a", "CAPTCHA", "when", "generating", "an", "html", "page", "then", "get", "()", "it", "later", "when", "its", "images", "or", "sounds", "must", "be", "rendered", "." ]
def get(self, id): """Retrieve the CAPTCHA with the given ID. If it's expired already, this will return None. A typical web application will need to new() a CAPTCHA when generating an html page, then get() it later when its images or sounds must be rendered. """ return self.storedInstances.get(id)
[ "def", "get", "(", "self", ",", "id", ")", ":", "return", "self", ".", "storedInstances", ".", "get", "(", "id", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Base.py#L86-L92
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Base.py
python
Factory.clean
(self)
Removed expired tests
Removed expired tests
[ "Removed", "expired", "tests" ]
def clean(self): """Removed expired tests""" expiredIds = [] now = time.time() for inst in self.storedInstances.itervalues(): if inst.creationTime + self.lifetime < now: expiredIds.append(inst.id) for id in expiredIds: del self.storedInstances[id]
[ "def", "clean", "(", "self", ")", ":", "expiredIds", "=", "[", "]", "now", "=", "time", ".", "time", "(", ")", "for", "inst", "in", "self", ".", "storedInstances", ".", "itervalues", "(", ")", ":", "if", "inst", ".", "creationTime", "+", "self", ".", "lifetime", "<", "now", ":", "expiredIds", ".", "append", "(", "inst", ".", "id", ")", "for", "id", "in", "expiredIds", ":", "del", "self", ".", "storedInstances", "[", "id", "]" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Base.py#L94-L102
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Base.py
python
Factory.test
(self, id, solutions)
return result
Test the given list of solutions against the BaseCaptcha instance created earlier with the given id. Returns True if the test passed, False on failure. In either case, the test is invalidated. Returns False in the case of an invalid id.
Test the given list of solutions against the BaseCaptcha instance created earlier with the given id. Returns True if the test passed, False on failure. In either case, the test is invalidated. Returns False in the case of an invalid id.
[ "Test", "the", "given", "list", "of", "solutions", "against", "the", "BaseCaptcha", "instance", "created", "earlier", "with", "the", "given", "id", ".", "Returns", "True", "if", "the", "test", "passed", "False", "on", "failure", ".", "In", "either", "case", "the", "test", "is", "invalidated", ".", "Returns", "False", "in", "the", "case", "of", "an", "invalid", "id", "." ]
def test(self, id, solutions): """Test the given list of solutions against the BaseCaptcha instance created earlier with the given id. Returns True if the test passed, False on failure. In either case, the test is invalidated. Returns False in the case of an invalid id. """ self.clean() inst = self.storedInstances.get(id) if not inst: return False result = inst.testSolutions(solutions) return result
[ "def", "test", "(", "self", ",", "id", ",", "solutions", ")", ":", "self", ".", "clean", "(", ")", "inst", "=", "self", ".", "storedInstances", ".", "get", "(", "id", ")", "if", "not", "inst", ":", "return", "False", "result", "=", "inst", ".", "testSolutions", "(", "solutions", ")", "return", "result" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Base.py#L104-L115
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib.linux-x86_64-2.7/Captcha/File.py
python
RandomFileFactory._checkExtension
(self, name)
return False
Check the file against our given list of extensions
Check the file against our given list of extensions
[ "Check", "the", "file", "against", "our", "given", "list", "of", "extensions" ]
def _checkExtension(self, name): """Check the file against our given list of extensions""" for ext in self.extensions: if name.endswith(ext): return True return False
[ "def", "_checkExtension", "(", "self", ",", "name", ")", ":", "for", "ext", "in", "self", ".", "extensions", ":", "if", "name", ".", "endswith", "(", "ext", ")", ":", "return", "True", "return", "False" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib.linux-x86_64-2.7/Captcha/File.py#L28-L33
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib.linux-x86_64-2.7/Captcha/File.py
python
RandomFileFactory._findFullPaths
(self)
return paths
From our given file list, find a list of full paths to files
From our given file list, find a list of full paths to files
[ "From", "our", "given", "file", "list", "find", "a", "list", "of", "full", "paths", "to", "files" ]
def _findFullPaths(self): """From our given file list, find a list of full paths to files""" paths = [] for name in self.fileList: path = os.path.join(dataDir, self.basePath, name) if os.path.isdir(path): for content in os.listdir(path): if self._checkExtension(content): paths.append(os.path.join(path, content)) else: paths.append(path) return paths
[ "def", "_findFullPaths", "(", "self", ")", ":", "paths", "=", "[", "]", "for", "name", "in", "self", ".", "fileList", ":", "path", "=", "os", ".", "path", ".", "join", "(", "dataDir", ",", "self", ".", "basePath", ",", "name", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "for", "content", "in", "os", ".", "listdir", "(", "path", ")", ":", "if", "self", ".", "_checkExtension", "(", "content", ")", ":", "paths", ".", "append", "(", "os", ".", "path", ".", "join", "(", "path", ",", "content", ")", ")", "else", ":", "paths", ".", "append", "(", "path", ")", "return", "paths" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib.linux-x86_64-2.7/Captcha/File.py#L35-L46
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Visual/Base.py
python
ImageCaptcha.getImage
(self)
return self._image
Get a PIL image representing this CAPTCHA test, creating it if necessary
Get a PIL image representing this CAPTCHA test, creating it if necessary
[ "Get", "a", "PIL", "image", "representing", "this", "CAPTCHA", "test", "creating", "it", "if", "necessary" ]
def getImage(self): """Get a PIL image representing this CAPTCHA test, creating it if necessary""" if not self._image: self._image = self.render() return self._image
[ "def", "getImage", "(", "self", ")", ":", "if", "not", "self", ".", "_image", ":", "self", ".", "_image", "=", "self", ".", "render", "(", ")", "return", "self", ".", "_image" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Visual/Base.py#L29-L33
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Visual/Base.py
python
ImageCaptcha.getLayers
(self)
return []
Subclasses must override this to return a list of Layer instances to render. Lists within the list of layers are recursively rendered.
Subclasses must override this to return a list of Layer instances to render. Lists within the list of layers are recursively rendered.
[ "Subclasses", "must", "override", "this", "to", "return", "a", "list", "of", "Layer", "instances", "to", "render", ".", "Lists", "within", "the", "list", "of", "layers", "are", "recursively", "rendered", "." ]
def getLayers(self): """Subclasses must override this to return a list of Layer instances to render. Lists within the list of layers are recursively rendered. """ return []
[ "def", "getLayers", "(", "self", ")", ":", "return", "[", "]" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Visual/Base.py#L35-L39
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Visual/Base.py
python
ImageCaptcha.render
(self, size=None)
return self._renderList(self._layers, Image.new("RGB", size))
Render this CAPTCHA, returning a PIL image
Render this CAPTCHA, returning a PIL image
[ "Render", "this", "CAPTCHA", "returning", "a", "PIL", "image" ]
def render(self, size=None): """Render this CAPTCHA, returning a PIL image""" if size is None: size = self.defaultSize img = Image.new("RGB", size) return self._renderList(self._layers, Image.new("RGB", size))
[ "def", "render", "(", "self", ",", "size", "=", "None", ")", ":", "if", "size", "is", "None", ":", "size", "=", "self", ".", "defaultSize", "img", "=", "Image", ".", "new", "(", "\"RGB\"", ",", "size", ")", "return", "self", ".", "_renderList", "(", "self", ".", "_layers", ",", "Image", ".", "new", "(", "\"RGB\"", ",", "size", ")", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Visual/Base.py#L41-L46
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Visual/Text.py
python
FontFactory.pick
(self)
return (fileName, size)
Returns a (fileName, size) tuple that can be passed to ImageFont.truetype()
Returns a (fileName, size) tuple that can be passed to ImageFont.truetype()
[ "Returns", "a", "(", "fileName", "size", ")", "tuple", "that", "can", "be", "passed", "to", "ImageFont", ".", "truetype", "()" ]
def pick(self): """Returns a (fileName, size) tuple that can be passed to ImageFont.truetype()""" fileName = File.RandomFileFactory.pick(self) size = int(random.uniform(self.minSize, self.maxSize) + 0.5) return (fileName, size)
[ "def", "pick", "(", "self", ")", ":", "fileName", "=", "File", ".", "RandomFileFactory", ".", "pick", "(", "self", ")", "size", "=", "int", "(", "random", ".", "uniform", "(", "self", ".", "minSize", ",", "self", ".", "maxSize", ")", "+", "0.5", ")", "return", "(", "fileName", ",", "size", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Visual/Text.py#L34-L38
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Visual/Distortions.py
python
WarpBase.getTransform
(self, image)
return lambda x, y: (x, y)
Return a transformation function, subclasses should override this
Return a transformation function, subclasses should override this
[ "Return", "a", "transformation", "function", "subclasses", "should", "override", "this" ]
def getTransform(self, image): """Return a transformation function, subclasses should override this""" return lambda x, y: (x, y)
[ "def", "getTransform", "(", "self", ",", "image", ")", ":", "return", "lambda", "x", ",", "y", ":", "(", "x", ",", "y", ")" ]
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/pycaptcha/build/lib.linux-x86_64-2.7/Captcha/Visual/Distortions.py#L50-L52
12dmodel/deep_motion_mag
485243bd7428d08059c313321b5e6ebfd7f61991
preprocessor.py
python
get_possion_noise
(image)
return tf.multiply(n, n_str)
Add poisson noise. This function approximate posson noise upto 2nd order. Assume images were in 0-255, and converted to the range of -1 to 1.
Add poisson noise.
[ "Add", "poisson", "noise", "." ]
def get_possion_noise(image): """Add poisson noise. This function approximate posson noise upto 2nd order. Assume images were in 0-255, and converted to the range of -1 to 1. """ n = tf.random_normal(shape=tf.shape(image), mean=0.0, stddev=1.0) # strength ~ sqrt image value in 255, divided by 127.5 to convert # back to -1, 1 range. n_str = tf.sqrt(image + 1.0) / np.sqrt(127.5) return tf.multiply(n, n_str)
[ "def", "get_possion_noise", "(", "image", ")", ":", "n", "=", "tf", ".", "random_normal", "(", "shape", "=", "tf", ".", "shape", "(", "image", ")", ",", "mean", "=", "0.0", ",", "stddev", "=", "1.0", ")", "# strength ~ sqrt image value in 255, divided by 127.5 to convert", "# back to -1, 1 range.", "n_str", "=", "tf", ".", "sqrt", "(", "image", "+", "1.0", ")", "/", "np", ".", "sqrt", "(", "127.5", ")", "return", "tf", ".", "multiply", "(", "n", ",", "n_str", ")" ]
https://github.com/12dmodel/deep_motion_mag/blob/485243bd7428d08059c313321b5e6ebfd7f61991/preprocessor.py#L16-L26
12dmodel/deep_motion_mag
485243bd7428d08059c313321b5e6ebfd7f61991
ops.py
python
expand_dims_1_to_4
(tensor, dims=None)
return tf.expand_dims( tf.expand_dims( tf.expand_dims(tensor, dims[0]), dims[1]), dims[2])
Expand dimension from 1 to 4. Useful for multiplying amplification factor.
Expand dimension from 1 to 4.
[ "Expand", "dimension", "from", "1", "to", "4", "." ]
def expand_dims_1_to_4(tensor, dims=None): """Expand dimension from 1 to 4. Useful for multiplying amplification factor. """ if not dims: dims = [-1, -1, -1] return tf.expand_dims( tf.expand_dims( tf.expand_dims(tensor, dims[0]), dims[1]), dims[2])
[ "def", "expand_dims_1_to_4", "(", "tensor", ",", "dims", "=", "None", ")", ":", "if", "not", "dims", ":", "dims", "=", "[", "-", "1", ",", "-", "1", ",", "-", "1", "]", "return", "tf", ".", "expand_dims", "(", "tf", ".", "expand_dims", "(", "tf", ".", "expand_dims", "(", "tensor", ",", "dims", "[", "0", "]", ")", ",", "dims", "[", "1", "]", ")", ",", "dims", "[", "2", "]", ")" ]
https://github.com/12dmodel/deep_motion_mag/blob/485243bd7428d08059c313321b5e6ebfd7f61991/ops.py#L77-L88
12dmodel/deep_motion_mag
485243bd7428d08059c313321b5e6ebfd7f61991
magnet.py
python
MagNet3Frames.setup_for_inference
(self, checkpoint_dir, image_width, image_height)
Setup model for inference. Build computation graph, initialize variables, and load checkpoint.
Setup model for inference.
[ "Setup", "model", "for", "inference", "." ]
def setup_for_inference(self, checkpoint_dir, image_width, image_height): """Setup model for inference. Build computation graph, initialize variables, and load checkpoint. """ self.image_width = image_width self.image_height = image_height # Figure out image dimension self._build_feed_model() ginit_op = tf.global_variables_initializer() linit_op = tf.local_variables_initializer() self.sess.run([ginit_op, linit_op]) if self.load(checkpoint_dir): print("[*] Load Success") else: raise RuntimeError('MagNet: Failed to load checkpoint file.') self.is_graph_built = True
[ "def", "setup_for_inference", "(", "self", ",", "checkpoint_dir", ",", "image_width", ",", "image_height", ")", ":", "self", ".", "image_width", "=", "image_width", "self", ".", "image_height", "=", "image_height", "# Figure out image dimension", "self", ".", "_build_feed_model", "(", ")", "ginit_op", "=", "tf", ".", "global_variables_initializer", "(", ")", "linit_op", "=", "tf", ".", "local_variables_initializer", "(", ")", "self", ".", "sess", ".", "run", "(", "[", "ginit_op", ",", "linit_op", "]", ")", "if", "self", ".", "load", "(", "checkpoint_dir", ")", ":", "print", "(", "\"[*] Load Success\"", ")", "else", ":", "raise", "RuntimeError", "(", "'MagNet: Failed to load checkpoint file.'", ")", "self", ".", "is_graph_built", "=", "True" ]
https://github.com/12dmodel/deep_motion_mag/blob/485243bd7428d08059c313321b5e6ebfd7f61991/magnet.py#L198-L215
12dmodel/deep_motion_mag
485243bd7428d08059c313321b5e6ebfd7f61991
magnet.py
python
MagNet3Frames.inference
(self, frameA, frameB, amplification_factor)
return out_amp
Run Magnification on two frames. Args: frameA: path to first frame frameB: path to second frame amplification_factor: float for amplification factor
Run Magnification on two frames.
[ "Run", "Magnification", "on", "two", "frames", "." ]
def inference(self, frameA, frameB, amplification_factor): """Run Magnification on two frames. Args: frameA: path to first frame frameB: path to second frame amplification_factor: float for amplification factor """ in_frames = [load_train_data([frameA, frameB, frameB], gray_scale=self.n_channels==1, is_testing=True)] in_frames = np.array(in_frames).astype(np.float32) out_amp = self.sess.run(self.test_output, feed_dict={self.test_input: in_frames, self.test_amplification_factor: [amplification_factor]}) return out_amp
[ "def", "inference", "(", "self", ",", "frameA", ",", "frameB", ",", "amplification_factor", ")", ":", "in_frames", "=", "[", "load_train_data", "(", "[", "frameA", ",", "frameB", ",", "frameB", "]", ",", "gray_scale", "=", "self", ".", "n_channels", "==", "1", ",", "is_testing", "=", "True", ")", "]", "in_frames", "=", "np", ".", "array", "(", "in_frames", ")", ".", "astype", "(", "np", ".", "float32", ")", "out_amp", "=", "self", ".", "sess", ".", "run", "(", "self", ".", "test_output", ",", "feed_dict", "=", "{", "self", ".", "test_input", ":", "in_frames", ",", "self", ".", "test_amplification_factor", ":", "[", "amplification_factor", "]", "}", ")", "return", "out_amp" ]
https://github.com/12dmodel/deep_motion_mag/blob/485243bd7428d08059c313321b5e6ebfd7f61991/magnet.py#L217-L233
12dmodel/deep_motion_mag
485243bd7428d08059c313321b5e6ebfd7f61991
magnet.py
python
MagNet3Frames.run
(self, checkpoint_dir, vid_dir, frame_ext, out_dir, amplification_factor, velocity_mag=False)
Magnify a video in the two-frames mode. Args: checkpoint_dir: checkpoint directory. vid_dir: directory containing video frames videos are processed in sorted order. out_dir: directory to place output frames and resulting video. amplification_factor: the amplification factor, with 0 being no change. velocity_mag: if True, process video in Dynamic mode.
Magnify a video in the two-frames mode.
[ "Magnify", "a", "video", "in", "the", "two", "-", "frames", "mode", "." ]
def run(self, checkpoint_dir, vid_dir, frame_ext, out_dir, amplification_factor, velocity_mag=False): """Magnify a video in the two-frames mode. Args: checkpoint_dir: checkpoint directory. vid_dir: directory containing video frames videos are processed in sorted order. out_dir: directory to place output frames and resulting video. amplification_factor: the amplification factor, with 0 being no change. velocity_mag: if True, process video in Dynamic mode. """ vid_name = os.path.basename(out_dir) # make folder mkdir(out_dir) vid_frames = sorted(glob(os.path.join(vid_dir, '*.' + frame_ext))) first_frame = vid_frames[0] im = imread(first_frame) image_height, image_width = im.shape if not self.is_graph_built: self.setup_for_inference(checkpoint_dir, image_width, image_height) try: i = int(self.ckpt_name.split('-')[-1]) print("Iteration number is {:d}".format(i)) vid_name = vid_name + '_' + str(i) except: print("Cannot get iteration number") if velocity_mag: print("Running in Dynamic mode") prev_frame = first_frame desc = vid_name if len(vid_name) < 10 else vid_name[:10] for frame in tqdm(vid_frames, desc=desc): file_name = os.path.basename(frame) out_amp = self.inference(prev_frame, frame, amplification_factor) im_path = os.path.join(out_dir, file_name) save_images(out_amp, [1, 1], im_path) if velocity_mag: prev_frame = frame # Try to combine it into a video call([DEFAULT_VIDEO_CONVERTER, '-y', '-f', 'image2', '-r', '30', '-i', os.path.join(out_dir, '%06d.png'), '-c:v', 'libx264', os.path.join(out_dir, vid_name + '.mp4')] )
[ "def", "run", "(", "self", ",", "checkpoint_dir", ",", "vid_dir", ",", "frame_ext", ",", "out_dir", ",", "amplification_factor", ",", "velocity_mag", "=", "False", ")", ":", "vid_name", "=", "os", ".", "path", ".", "basename", "(", "out_dir", ")", "# make folder", "mkdir", "(", "out_dir", ")", "vid_frames", "=", "sorted", "(", "glob", "(", "os", ".", "path", ".", "join", "(", "vid_dir", ",", "'*.'", "+", "frame_ext", ")", ")", ")", "first_frame", "=", "vid_frames", "[", "0", "]", "im", "=", "imread", "(", "first_frame", ")", "image_height", ",", "image_width", "=", "im", ".", "shape", "if", "not", "self", ".", "is_graph_built", ":", "self", ".", "setup_for_inference", "(", "checkpoint_dir", ",", "image_width", ",", "image_height", ")", "try", ":", "i", "=", "int", "(", "self", ".", "ckpt_name", ".", "split", "(", "'-'", ")", "[", "-", "1", "]", ")", "print", "(", "\"Iteration number is {:d}\"", ".", "format", "(", "i", ")", ")", "vid_name", "=", "vid_name", "+", "'_'", "+", "str", "(", "i", ")", "except", ":", "print", "(", "\"Cannot get iteration number\"", ")", "if", "velocity_mag", ":", "print", "(", "\"Running in Dynamic mode\"", ")", "prev_frame", "=", "first_frame", "desc", "=", "vid_name", "if", "len", "(", "vid_name", ")", "<", "10", "else", "vid_name", "[", ":", "10", "]", "for", "frame", "in", "tqdm", "(", "vid_frames", ",", "desc", "=", "desc", ")", ":", "file_name", "=", "os", ".", "path", ".", "basename", "(", "frame", ")", "out_amp", "=", "self", ".", "inference", "(", "prev_frame", ",", "frame", ",", "amplification_factor", ")", "im_path", "=", "os", ".", "path", ".", "join", "(", "out_dir", ",", "file_name", ")", "save_images", "(", "out_amp", ",", "[", "1", ",", "1", "]", ",", "im_path", ")", "if", "velocity_mag", ":", "prev_frame", "=", "frame", "# Try to combine it into a video", "call", "(", "[", "DEFAULT_VIDEO_CONVERTER", ",", "'-y'", ",", "'-f'", ",", "'image2'", ",", "'-r'", ",", "'30'", ",", "'-i'", ",", "os", ".", "path", ".", "join", "(", "out_dir", ",", "'%06d.png'", ")", ",", "'-c:v'", ",", "'libx264'", ",", "os", ".", "path", ".", "join", "(", "out_dir", ",", "vid_name", "+", "'.mp4'", ")", "]", ")" ]
https://github.com/12dmodel/deep_motion_mag/blob/485243bd7428d08059c313321b5e6ebfd7f61991/magnet.py#L235-L286
12dmodel/deep_motion_mag
485243bd7428d08059c313321b5e6ebfd7f61991
magnet.py
python
MagNet3Frames._build_IIR_filtering_graphs
(self)
Assume a_0 = 1
Assume a_0 = 1
[ "Assume", "a_0", "=", "1" ]
def _build_IIR_filtering_graphs(self): """ Assume a_0 = 1 """ self.input_image = tf.placeholder(tf.float32, [1, self.image_height, self.image_width, self.n_channels], name='input_image') self.filtered_enc = tf.placeholder(tf.float32, [1, None, None, self.shape_dims], name='filtered_enc') self.out_texture_enc = tf.placeholder(tf.float32, [1, None, None, self.texture_dims], name='out_texture_enc') self.ref_shape_enc = tf.placeholder(tf.float32, [1, None, None, self.shape_dims], name='ref_shape_enc') self.amplification_factor = tf.placeholder(tf.float32, [None], name='amplification_factor') with tf.variable_scope('ynet_3frames'): with tf.variable_scope('encoder'): self.texture_enc, self.shape_rep = \ self._encoder(self.input_image) with tf.variable_scope('manipulator'): # set encoder a to zero because we do temporal filtering # instead of taking the difference. self.out_shape_enc = self.manipulator(0.0, self.filtered_enc, self.amplification_factor) self.out_shape_enc += self.ref_shape_enc - self.filtered_enc with tf.variable_scope('decoder'): self.output_image = tf.clip_by_value( self._decoder(self.out_texture_enc, self.out_shape_enc), -1.0, 1.0) self.saver = tf.train.Saver()
[ "def", "_build_IIR_filtering_graphs", "(", "self", ")", ":", "self", ".", "input_image", "=", "tf", ".", "placeholder", "(", "tf", ".", "float32", ",", "[", "1", ",", "self", ".", "image_height", ",", "self", ".", "image_width", ",", "self", ".", "n_channels", "]", ",", "name", "=", "'input_image'", ")", "self", ".", "filtered_enc", "=", "tf", ".", "placeholder", "(", "tf", ".", "float32", ",", "[", "1", ",", "None", ",", "None", ",", "self", ".", "shape_dims", "]", ",", "name", "=", "'filtered_enc'", ")", "self", ".", "out_texture_enc", "=", "tf", ".", "placeholder", "(", "tf", ".", "float32", ",", "[", "1", ",", "None", ",", "None", ",", "self", ".", "texture_dims", "]", ",", "name", "=", "'out_texture_enc'", ")", "self", ".", "ref_shape_enc", "=", "tf", ".", "placeholder", "(", "tf", ".", "float32", ",", "[", "1", ",", "None", ",", "None", ",", "self", ".", "shape_dims", "]", ",", "name", "=", "'ref_shape_enc'", ")", "self", ".", "amplification_factor", "=", "tf", ".", "placeholder", "(", "tf", ".", "float32", ",", "[", "None", "]", ",", "name", "=", "'amplification_factor'", ")", "with", "tf", ".", "variable_scope", "(", "'ynet_3frames'", ")", ":", "with", "tf", ".", "variable_scope", "(", "'encoder'", ")", ":", "self", ".", "texture_enc", ",", "self", ".", "shape_rep", "=", "self", ".", "_encoder", "(", "self", ".", "input_image", ")", "with", "tf", ".", "variable_scope", "(", "'manipulator'", ")", ":", "# set encoder a to zero because we do temporal filtering", "# instead of taking the difference.", "self", ".", "out_shape_enc", "=", "self", ".", "manipulator", "(", "0.0", ",", "self", ".", "filtered_enc", ",", "self", ".", "amplification_factor", ")", "self", ".", "out_shape_enc", "+=", "self", ".", "ref_shape_enc", "-", "self", ".", "filtered_enc", "with", "tf", ".", "variable_scope", "(", "'decoder'", ")", ":", "self", ".", "output_image", "=", "tf", ".", "clip_by_value", "(", "self", ".", "_decoder", "(", "self", ".", "out_texture_enc", ",", "self", ".", "out_shape_enc", ")", ",", "-", "1.0", ",", "1.0", ")", "self", ".", "saver", "=", "tf", ".", "train", ".", "Saver", "(", ")" ]
https://github.com/12dmodel/deep_motion_mag/blob/485243bd7428d08059c313321b5e6ebfd7f61991/magnet.py#L289-L329
12dmodel/deep_motion_mag
485243bd7428d08059c313321b5e6ebfd7f61991
magnet.py
python
MagNet3Frames.run_temporal
(self, checkpoint_dir, vid_dir, frame_ext, out_dir, amplification_factor, fl, fh, fs, n_filter_tap, filter_type)
Magnify video with a temporal filter. Args: checkpoint_dir: checkpoint directory. vid_dir: directory containing video frames videos are processed in sorted order. out_dir: directory to place output frames and resulting video. amplification_factor: the amplification factor, with 0 being no change. fl: low cutoff frequency. fh: high cutoff frequency. fs: sampling rate of the video. n_filter_tap: number of filter tap to use. filter_type: Type of filter to use. Can be one of "fir", "butter", or "differenceOfIIR". For "differenceOfIIR", fl and fh specifies rl and rh coefficients as in Wadhwa et al.
Magnify video with a temporal filter.
[ "Magnify", "video", "with", "a", "temporal", "filter", "." ]
def run_temporal(self, checkpoint_dir, vid_dir, frame_ext, out_dir, amplification_factor, fl, fh, fs, n_filter_tap, filter_type): """Magnify video with a temporal filter. Args: checkpoint_dir: checkpoint directory. vid_dir: directory containing video frames videos are processed in sorted order. out_dir: directory to place output frames and resulting video. amplification_factor: the amplification factor, with 0 being no change. fl: low cutoff frequency. fh: high cutoff frequency. fs: sampling rate of the video. n_filter_tap: number of filter tap to use. filter_type: Type of filter to use. Can be one of "fir", "butter", or "differenceOfIIR". For "differenceOfIIR", fl and fh specifies rl and rh coefficients as in Wadhwa et al. """ nyq = fs / 2.0 if filter_type == 'fir': filter_b = firwin(n_filter_tap, [fl, fh], nyq=nyq, pass_zero=False) filter_a = [] elif filter_type == 'butter': filter_b, filter_a = butter(n_filter_tap, [fl/nyq, fh/nyq], btype='bandpass') filter_a = filter_a[1:] elif filter_type == 'differenceOfIIR': # This is a copy of what Neal did. Number of taps are ignored. # Treat fl and fh as rl and rh as in Wadhwa's code. # Write down the difference of difference equation in Fourier # domain to proof this: filter_b = [fh - fl, fl - fh] filter_a = [-1.0*(2.0 - fh - fl), (1.0 - fl) * (1.0 - fh)] else: raise ValueError('Filter type must be either ' '["fir", "butter", "differenceOfIIR"] got ' + \ filter_type) head, tail = os.path.split(out_dir) tail = tail + '_fl{}_fh{}_fs{}_n{}_{}'.format(fl, fh, fs, n_filter_tap, filter_type) out_dir = os.path.join(head, tail) vid_name = os.path.basename(out_dir) # make folder mkdir(out_dir) vid_frames = sorted(glob(os.path.join(vid_dir, '*.' + frame_ext))) first_frame = vid_frames[0] im = imread(first_frame) image_height, image_width = im.shape if not self.is_graph_built: self.image_width = image_width self.image_height = image_height # Figure out image dimension self._build_IIR_filtering_graphs() ginit_op = tf.global_variables_initializer() linit_op = tf.local_variables_initializer() self.sess.run([ginit_op, linit_op]) if self.load(checkpoint_dir): print("[*] Load Success") else: raise RuntimeError('MagNet: Failed to load checkpoint file.') self.is_graph_built = True try: i = int(self.ckpt_name.split('-')[-1]) print("Iteration number is {:d}".format(i)) vid_name = vid_name + '_' + str(i) except: print("Cannot get iteration number") if len(filter_a) is not 0: x_state = [] y_state = [] for frame in tqdm(vid_frames, desc='Applying IIR'): file_name = os.path.basename(frame) frame_no, _ = os.path.splitext(file_name) frame_no = int(frame_no) in_frames = [load_train_data([frame, frame, frame], gray_scale=self.n_channels==1, is_testing=True)] in_frames = np.array(in_frames).astype(np.float32) texture_enc, x = self.sess.run([self.texture_enc, self.shape_rep], feed_dict={ self.input_image: in_frames[:, :, :, :3],}) x_state.insert(0, x) # set up initial condition. while len(x_state) < len(filter_b): x_state.insert(0, x) if len(x_state) > len(filter_b): x_state = x_state[:len(filter_b)] y = np.zeros_like(x) for i in range(len(x_state)): y += x_state[i] * filter_b[i] for i in range(len(y_state)): y -= y_state[i] * filter_a[i] # update y state y_state.insert(0, y) if len(y_state) > len(filter_a): y_state = y_state[:len(filter_a)] out_amp = self.sess.run(self.output_image, feed_dict={self.out_texture_enc: texture_enc, self.filtered_enc: y, self.ref_shape_enc: x, self.amplification_factor: [amplification_factor]}) im_path = os.path.join(out_dir, file_name) out_amp = np.squeeze(out_amp) out_amp = (127.5*(out_amp+1)).astype('uint8') cv2.imwrite(im_path, cv2.cvtColor(out_amp, code=cv2.COLOR_RGB2BGR)) else: # This does FIR in fourier domain. Equivalent to cyclic # convolution. x_state = None for i, frame in tqdm(enumerate(vid_frames), desc='Getting encoding'): file_name = os.path.basename(frame) in_frames = [load_train_data([frame, frame, frame], gray_scale=self.n_channels==1, is_testing=True)] in_frames = np.array(in_frames).astype(np.float32) texture_enc, x = self.sess.run([self.texture_enc, self.shape_rep], feed_dict={ self.input_image: in_frames[:, :, :, :3],}) if x_state is None: x_state = np.zeros(x.shape + (len(vid_frames),), dtype='float32') x_state[:, :, :, :, i] = x filter_fft = np.fft.fft(np.fft.ifftshift(filter_b), n=x_state.shape[-1]) # Filtering for i in trange(x_state.shape[1], desc="Applying FIR filter"): x_fft = np.fft.fft(x_state[:, i, :, :], axis=-1) x_fft *= filter_fft[np.newaxis, np.newaxis, np.newaxis, :] x_state[:, i, :, :] = np.fft.ifft(x_fft) for i, frame in tqdm(enumerate(vid_frames), desc='Decoding'): file_name = os.path.basename(frame) frame_no, _ = os.path.splitext(file_name) frame_no = int(frame_no) in_frames = [load_train_data([frame, frame, frame], gray_scale=self.n_channels==1, is_testing=True)] in_frames = np.array(in_frames).astype(np.float32) texture_enc, _ = self.sess.run([self.texture_enc, self.shape_rep], feed_dict={ self.input_image: in_frames[:, :, :, :3], }) out_amp = self.sess.run(self.output_image, feed_dict={self.out_texture_enc: texture_enc, self.filtered_enc: x_state[:, :, :, :, i], self.ref_shape_enc: x, self.amplification_factor: [amplification_factor]}) im_path = os.path.join(out_dir, file_name) out_amp = np.squeeze(out_amp) out_amp = (127.5*(out_amp+1)).astype('uint8') cv2.imwrite(im_path, cv2.cvtColor(out_amp, code=cv2.COLOR_RGB2BGR)) del x_state # Try to combine it into a video call([DEFAULT_VIDEO_CONVERTER, '-y', '-f', 'image2', '-r', '30', '-i', os.path.join(out_dir, '%06d.png'), '-c:v', 'libx264', os.path.join(out_dir, vid_name + '.mp4')] )
[ "def", "run_temporal", "(", "self", ",", "checkpoint_dir", ",", "vid_dir", ",", "frame_ext", ",", "out_dir", ",", "amplification_factor", ",", "fl", ",", "fh", ",", "fs", ",", "n_filter_tap", ",", "filter_type", ")", ":", "nyq", "=", "fs", "/", "2.0", "if", "filter_type", "==", "'fir'", ":", "filter_b", "=", "firwin", "(", "n_filter_tap", ",", "[", "fl", ",", "fh", "]", ",", "nyq", "=", "nyq", ",", "pass_zero", "=", "False", ")", "filter_a", "=", "[", "]", "elif", "filter_type", "==", "'butter'", ":", "filter_b", ",", "filter_a", "=", "butter", "(", "n_filter_tap", ",", "[", "fl", "/", "nyq", ",", "fh", "/", "nyq", "]", ",", "btype", "=", "'bandpass'", ")", "filter_a", "=", "filter_a", "[", "1", ":", "]", "elif", "filter_type", "==", "'differenceOfIIR'", ":", "# This is a copy of what Neal did. Number of taps are ignored.", "# Treat fl and fh as rl and rh as in Wadhwa's code.", "# Write down the difference of difference equation in Fourier", "# domain to proof this:", "filter_b", "=", "[", "fh", "-", "fl", ",", "fl", "-", "fh", "]", "filter_a", "=", "[", "-", "1.0", "*", "(", "2.0", "-", "fh", "-", "fl", ")", ",", "(", "1.0", "-", "fl", ")", "*", "(", "1.0", "-", "fh", ")", "]", "else", ":", "raise", "ValueError", "(", "'Filter type must be either '", "'[\"fir\", \"butter\", \"differenceOfIIR\"] got '", "+", "filter_type", ")", "head", ",", "tail", "=", "os", ".", "path", ".", "split", "(", "out_dir", ")", "tail", "=", "tail", "+", "'_fl{}_fh{}_fs{}_n{}_{}'", ".", "format", "(", "fl", ",", "fh", ",", "fs", ",", "n_filter_tap", ",", "filter_type", ")", "out_dir", "=", "os", ".", "path", ".", "join", "(", "head", ",", "tail", ")", "vid_name", "=", "os", ".", "path", ".", "basename", "(", "out_dir", ")", "# make folder", "mkdir", "(", "out_dir", ")", "vid_frames", "=", "sorted", "(", "glob", "(", "os", ".", "path", ".", "join", "(", "vid_dir", ",", "'*.'", "+", "frame_ext", ")", ")", ")", "first_frame", "=", "vid_frames", "[", "0", "]", "im", "=", "imread", "(", "first_frame", ")", "image_height", ",", "image_width", "=", "im", ".", "shape", "if", "not", "self", ".", "is_graph_built", ":", "self", ".", "image_width", "=", "image_width", "self", ".", "image_height", "=", "image_height", "# Figure out image dimension", "self", ".", "_build_IIR_filtering_graphs", "(", ")", "ginit_op", "=", "tf", ".", "global_variables_initializer", "(", ")", "linit_op", "=", "tf", ".", "local_variables_initializer", "(", ")", "self", ".", "sess", ".", "run", "(", "[", "ginit_op", ",", "linit_op", "]", ")", "if", "self", ".", "load", "(", "checkpoint_dir", ")", ":", "print", "(", "\"[*] Load Success\"", ")", "else", ":", "raise", "RuntimeError", "(", "'MagNet: Failed to load checkpoint file.'", ")", "self", ".", "is_graph_built", "=", "True", "try", ":", "i", "=", "int", "(", "self", ".", "ckpt_name", ".", "split", "(", "'-'", ")", "[", "-", "1", "]", ")", "print", "(", "\"Iteration number is {:d}\"", ".", "format", "(", "i", ")", ")", "vid_name", "=", "vid_name", "+", "'_'", "+", "str", "(", "i", ")", "except", ":", "print", "(", "\"Cannot get iteration number\"", ")", "if", "len", "(", "filter_a", ")", "is", "not", "0", ":", "x_state", "=", "[", "]", "y_state", "=", "[", "]", "for", "frame", "in", "tqdm", "(", "vid_frames", ",", "desc", "=", "'Applying IIR'", ")", ":", "file_name", "=", "os", ".", "path", ".", "basename", "(", "frame", ")", "frame_no", ",", "_", "=", "os", ".", "path", ".", "splitext", "(", "file_name", ")", "frame_no", "=", "int", "(", "frame_no", ")", "in_frames", "=", "[", "load_train_data", "(", "[", "frame", ",", "frame", ",", "frame", "]", ",", "gray_scale", "=", "self", ".", "n_channels", "==", "1", ",", "is_testing", "=", "True", ")", "]", "in_frames", "=", "np", ".", "array", "(", "in_frames", ")", ".", "astype", "(", "np", ".", "float32", ")", "texture_enc", ",", "x", "=", "self", ".", "sess", ".", "run", "(", "[", "self", ".", "texture_enc", ",", "self", ".", "shape_rep", "]", ",", "feed_dict", "=", "{", "self", ".", "input_image", ":", "in_frames", "[", ":", ",", ":", ",", ":", ",", ":", "3", "]", ",", "}", ")", "x_state", ".", "insert", "(", "0", ",", "x", ")", "# set up initial condition.", "while", "len", "(", "x_state", ")", "<", "len", "(", "filter_b", ")", ":", "x_state", ".", "insert", "(", "0", ",", "x", ")", "if", "len", "(", "x_state", ")", ">", "len", "(", "filter_b", ")", ":", "x_state", "=", "x_state", "[", ":", "len", "(", "filter_b", ")", "]", "y", "=", "np", ".", "zeros_like", "(", "x", ")", "for", "i", "in", "range", "(", "len", "(", "x_state", ")", ")", ":", "y", "+=", "x_state", "[", "i", "]", "*", "filter_b", "[", "i", "]", "for", "i", "in", "range", "(", "len", "(", "y_state", ")", ")", ":", "y", "-=", "y_state", "[", "i", "]", "*", "filter_a", "[", "i", "]", "# update y state", "y_state", ".", "insert", "(", "0", ",", "y", ")", "if", "len", "(", "y_state", ")", ">", "len", "(", "filter_a", ")", ":", "y_state", "=", "y_state", "[", ":", "len", "(", "filter_a", ")", "]", "out_amp", "=", "self", ".", "sess", ".", "run", "(", "self", ".", "output_image", ",", "feed_dict", "=", "{", "self", ".", "out_texture_enc", ":", "texture_enc", ",", "self", ".", "filtered_enc", ":", "y", ",", "self", ".", "ref_shape_enc", ":", "x", ",", "self", ".", "amplification_factor", ":", "[", "amplification_factor", "]", "}", ")", "im_path", "=", "os", ".", "path", ".", "join", "(", "out_dir", ",", "file_name", ")", "out_amp", "=", "np", ".", "squeeze", "(", "out_amp", ")", "out_amp", "=", "(", "127.5", "*", "(", "out_amp", "+", "1", ")", ")", ".", "astype", "(", "'uint8'", ")", "cv2", ".", "imwrite", "(", "im_path", ",", "cv2", ".", "cvtColor", "(", "out_amp", ",", "code", "=", "cv2", ".", "COLOR_RGB2BGR", ")", ")", "else", ":", "# This does FIR in fourier domain. Equivalent to cyclic", "# convolution.", "x_state", "=", "None", "for", "i", ",", "frame", "in", "tqdm", "(", "enumerate", "(", "vid_frames", ")", ",", "desc", "=", "'Getting encoding'", ")", ":", "file_name", "=", "os", ".", "path", ".", "basename", "(", "frame", ")", "in_frames", "=", "[", "load_train_data", "(", "[", "frame", ",", "frame", ",", "frame", "]", ",", "gray_scale", "=", "self", ".", "n_channels", "==", "1", ",", "is_testing", "=", "True", ")", "]", "in_frames", "=", "np", ".", "array", "(", "in_frames", ")", ".", "astype", "(", "np", ".", "float32", ")", "texture_enc", ",", "x", "=", "self", ".", "sess", ".", "run", "(", "[", "self", ".", "texture_enc", ",", "self", ".", "shape_rep", "]", ",", "feed_dict", "=", "{", "self", ".", "input_image", ":", "in_frames", "[", ":", ",", ":", ",", ":", ",", ":", "3", "]", ",", "}", ")", "if", "x_state", "is", "None", ":", "x_state", "=", "np", ".", "zeros", "(", "x", ".", "shape", "+", "(", "len", "(", "vid_frames", ")", ",", ")", ",", "dtype", "=", "'float32'", ")", "x_state", "[", ":", ",", ":", ",", ":", ",", ":", ",", "i", "]", "=", "x", "filter_fft", "=", "np", ".", "fft", ".", "fft", "(", "np", ".", "fft", ".", "ifftshift", "(", "filter_b", ")", ",", "n", "=", "x_state", ".", "shape", "[", "-", "1", "]", ")", "# Filtering", "for", "i", "in", "trange", "(", "x_state", ".", "shape", "[", "1", "]", ",", "desc", "=", "\"Applying FIR filter\"", ")", ":", "x_fft", "=", "np", ".", "fft", ".", "fft", "(", "x_state", "[", ":", ",", "i", ",", ":", ",", ":", "]", ",", "axis", "=", "-", "1", ")", "x_fft", "*=", "filter_fft", "[", "np", ".", "newaxis", ",", "np", ".", "newaxis", ",", "np", ".", "newaxis", ",", ":", "]", "x_state", "[", ":", ",", "i", ",", ":", ",", ":", "]", "=", "np", ".", "fft", ".", "ifft", "(", "x_fft", ")", "for", "i", ",", "frame", "in", "tqdm", "(", "enumerate", "(", "vid_frames", ")", ",", "desc", "=", "'Decoding'", ")", ":", "file_name", "=", "os", ".", "path", ".", "basename", "(", "frame", ")", "frame_no", ",", "_", "=", "os", ".", "path", ".", "splitext", "(", "file_name", ")", "frame_no", "=", "int", "(", "frame_no", ")", "in_frames", "=", "[", "load_train_data", "(", "[", "frame", ",", "frame", ",", "frame", "]", ",", "gray_scale", "=", "self", ".", "n_channels", "==", "1", ",", "is_testing", "=", "True", ")", "]", "in_frames", "=", "np", ".", "array", "(", "in_frames", ")", ".", "astype", "(", "np", ".", "float32", ")", "texture_enc", ",", "_", "=", "self", ".", "sess", ".", "run", "(", "[", "self", ".", "texture_enc", ",", "self", ".", "shape_rep", "]", ",", "feed_dict", "=", "{", "self", ".", "input_image", ":", "in_frames", "[", ":", ",", ":", ",", ":", ",", ":", "3", "]", ",", "}", ")", "out_amp", "=", "self", ".", "sess", ".", "run", "(", "self", ".", "output_image", ",", "feed_dict", "=", "{", "self", ".", "out_texture_enc", ":", "texture_enc", ",", "self", ".", "filtered_enc", ":", "x_state", "[", ":", ",", ":", ",", ":", ",", ":", ",", "i", "]", ",", "self", ".", "ref_shape_enc", ":", "x", ",", "self", ".", "amplification_factor", ":", "[", "amplification_factor", "]", "}", ")", "im_path", "=", "os", ".", "path", ".", "join", "(", "out_dir", ",", "file_name", ")", "out_amp", "=", "np", ".", "squeeze", "(", "out_amp", ")", "out_amp", "=", "(", "127.5", "*", "(", "out_amp", "+", "1", ")", ")", ".", "astype", "(", "'uint8'", ")", "cv2", ".", "imwrite", "(", "im_path", ",", "cv2", ".", "cvtColor", "(", "out_amp", ",", "code", "=", "cv2", ".", "COLOR_RGB2BGR", ")", ")", "del", "x_state", "# Try to combine it into a video", "call", "(", "[", "DEFAULT_VIDEO_CONVERTER", ",", "'-y'", ",", "'-f'", ",", "'image2'", ",", "'-r'", ",", "'30'", ",", "'-i'", ",", "os", ".", "path", ".", "join", "(", "out_dir", ",", "'%06d.png'", ")", ",", "'-c:v'", ",", "'libx264'", ",", "os", ".", "path", ".", "join", "(", "out_dir", ",", "vid_name", "+", "'.mp4'", ")", "]", ")" ]
https://github.com/12dmodel/deep_motion_mag/blob/485243bd7428d08059c313321b5e6ebfd7f61991/magnet.py#L331-L512
1aN0rmus/TekDefense-Automater
42548cf454e862669c0a482955358fe27f7150e8
siteinfo.py
python
SiteFacade.__init__
(self, verbose)
Class constructor. Simply creates a blank list and assigns it to instance variable _sites that will be filled with retrieved info from sites defined in the xml configuration file. Argument(s): No arguments are required. Return value(s): Nothing is returned from this Method.
Class constructor. Simply creates a blank list and assigns it to instance variable _sites that will be filled with retrieved info from sites defined in the xml configuration file.
[ "Class", "constructor", ".", "Simply", "creates", "a", "blank", "list", "and", "assigns", "it", "to", "instance", "variable", "_sites", "that", "will", "be", "filled", "with", "retrieved", "info", "from", "sites", "defined", "in", "the", "xml", "configuration", "file", "." ]
def __init__(self, verbose): """ Class constructor. Simply creates a blank list and assigns it to instance variable _sites that will be filled with retrieved info from sites defined in the xml configuration file. Argument(s): No arguments are required. Return value(s): Nothing is returned from this Method. """ self._sites = [] self._verbose = verbose
[ "def", "__init__", "(", "self", ",", "verbose", ")", ":", "self", ".", "_sites", "=", "[", "]", "self", ".", "_verbose", "=", "verbose" ]
https://github.com/1aN0rmus/TekDefense-Automater/blob/42548cf454e862669c0a482955358fe27f7150e8/siteinfo.py#L57-L71
1aN0rmus/TekDefense-Automater
42548cf454e862669c0a482955358fe27f7150e8
siteinfo.py
python
SiteFacade.runSiteAutomation
(self, webretrievedelay, proxy, targetlist, sourcelist, useragent, botoutputrequested, refreshremotexml, versionlocation)
Builds site objects representative of each site listed in the xml config file. Appends a Site object or one of it's subordinate objects to the _sites instance variable so retrieved information can be used. Returns nothing. Argument(s): webretrievedelay -- The amount of seconds to wait between site retrieve calls. Default delay is 2 seconds. proxy -- proxy server address as server:port_number targetlist -- list of strings representing targets to be investigated. Targets can be IP Addresses, MD5 hashes, or hostnames. sourcelist -- list of strings representing a specific site that should only be used for investigation purposes instead of all sites listed in the xml config file. useragent -- String representing user-agent that will be utilized when requesting or submitting data to or from a web site. botoutputrequested -- true or false representing if a minimalized output will be required for the site. refreshremotexml -- true or false representing if Automater will refresh the tekdefense.xml file on each run. Return value(s): Nothing is returned from this Method. Restriction(s): The Method has no restrictions.
Builds site objects representative of each site listed in the xml config file. Appends a Site object or one of it's subordinate objects to the _sites instance variable so retrieved information can be used. Returns nothing.
[ "Builds", "site", "objects", "representative", "of", "each", "site", "listed", "in", "the", "xml", "config", "file", ".", "Appends", "a", "Site", "object", "or", "one", "of", "it", "s", "subordinate", "objects", "to", "the", "_sites", "instance", "variable", "so", "retrieved", "information", "can", "be", "used", ".", "Returns", "nothing", "." ]
def runSiteAutomation(self, webretrievedelay, proxy, targetlist, sourcelist, useragent, botoutputrequested, refreshremotexml, versionlocation): """ Builds site objects representative of each site listed in the xml config file. Appends a Site object or one of it's subordinate objects to the _sites instance variable so retrieved information can be used. Returns nothing. Argument(s): webretrievedelay -- The amount of seconds to wait between site retrieve calls. Default delay is 2 seconds. proxy -- proxy server address as server:port_number targetlist -- list of strings representing targets to be investigated. Targets can be IP Addresses, MD5 hashes, or hostnames. sourcelist -- list of strings representing a specific site that should only be used for investigation purposes instead of all sites listed in the xml config file. useragent -- String representing user-agent that will be utilized when requesting or submitting data to or from a web site. botoutputrequested -- true or false representing if a minimalized output will be required for the site. refreshremotexml -- true or false representing if Automater will refresh the tekdefense.xml file on each run. Return value(s): Nothing is returned from this Method. Restriction(s): The Method has no restrictions. """ if refreshremotexml: SitesFile.updateTekDefenseXMLTree(proxy, self._verbose) remotesitetree = SitesFile.getXMLTree(__TEKDEFENSEXML__, self._verbose) localsitetree = SitesFile.getXMLTree(__SITESXML__, self._verbose) if not localsitetree and not remotesitetree: print 'Unfortunately there is neither a {tekd} file nor a {sites} file that can be utilized for proper' \ ' parsing.\nAt least one configuration XML file must be available for Automater to work properly.\n' \ 'Please see {url} for further instructions.'\ .format(tekd=__TEKDEFENSEXML__, sites=__SITESXML__, url=versionlocation) else: if localsitetree: for siteelement in localsitetree.iter(tag="site"): if self.siteEntryIsValid(siteelement): for targ in targetlist: for source in sourcelist: sitetypematch, targettype, target = self.getSiteInfoIfSiteTypesMatch(source, targ, siteelement) if sitetypematch: self.buildSiteList(siteelement, webretrievedelay, proxy, targettype, target, useragent, botoutputrequested) else: print 'A problem was found in the {sites} file. There appears to be a site entry with ' \ 'unequal numbers of regexs and reporting requirements'.format(sites=__SITESXML__) if remotesitetree: for siteelement in remotesitetree.iter(tag="site"): if self.siteEntryIsValid(siteelement): for targ in targetlist: for source in sourcelist: sitetypematch, targettype, target = self.getSiteInfoIfSiteTypesMatch(source, targ, siteelement) if sitetypematch: self.buildSiteList(siteelement, webretrievedelay, proxy, targettype, target, useragent, botoutputrequested) else: print 'A problem was found in the {sites} file. There appears to be a site entry with ' \ 'unequal numbers of regexs and reporting requirements'.format(sites=__SITESXML__)
[ "def", "runSiteAutomation", "(", "self", ",", "webretrievedelay", ",", "proxy", ",", "targetlist", ",", "sourcelist", ",", "useragent", ",", "botoutputrequested", ",", "refreshremotexml", ",", "versionlocation", ")", ":", "if", "refreshremotexml", ":", "SitesFile", ".", "updateTekDefenseXMLTree", "(", "proxy", ",", "self", ".", "_verbose", ")", "remotesitetree", "=", "SitesFile", ".", "getXMLTree", "(", "__TEKDEFENSEXML__", ",", "self", ".", "_verbose", ")", "localsitetree", "=", "SitesFile", ".", "getXMLTree", "(", "__SITESXML__", ",", "self", ".", "_verbose", ")", "if", "not", "localsitetree", "and", "not", "remotesitetree", ":", "print", "'Unfortunately there is neither a {tekd} file nor a {sites} file that can be utilized for proper'", "' parsing.\\nAt least one configuration XML file must be available for Automater to work properly.\\n'", "'Please see {url} for further instructions.'", ".", "format", "(", "tekd", "=", "__TEKDEFENSEXML__", ",", "sites", "=", "__SITESXML__", ",", "url", "=", "versionlocation", ")", "else", ":", "if", "localsitetree", ":", "for", "siteelement", "in", "localsitetree", ".", "iter", "(", "tag", "=", "\"site\"", ")", ":", "if", "self", ".", "siteEntryIsValid", "(", "siteelement", ")", ":", "for", "targ", "in", "targetlist", ":", "for", "source", "in", "sourcelist", ":", "sitetypematch", ",", "targettype", ",", "target", "=", "self", ".", "getSiteInfoIfSiteTypesMatch", "(", "source", ",", "targ", ",", "siteelement", ")", "if", "sitetypematch", ":", "self", ".", "buildSiteList", "(", "siteelement", ",", "webretrievedelay", ",", "proxy", ",", "targettype", ",", "target", ",", "useragent", ",", "botoutputrequested", ")", "else", ":", "print", "'A problem was found in the {sites} file. There appears to be a site entry with '", "'unequal numbers of regexs and reporting requirements'", ".", "format", "(", "sites", "=", "__SITESXML__", ")", "if", "remotesitetree", ":", "for", "siteelement", "in", "remotesitetree", ".", "iter", "(", "tag", "=", "\"site\"", ")", ":", "if", "self", ".", "siteEntryIsValid", "(", "siteelement", ")", ":", "for", "targ", "in", "targetlist", ":", "for", "source", "in", "sourcelist", ":", "sitetypematch", ",", "targettype", ",", "target", "=", "self", ".", "getSiteInfoIfSiteTypesMatch", "(", "source", ",", "targ", ",", "siteelement", ")", "if", "sitetypematch", ":", "self", ".", "buildSiteList", "(", "siteelement", ",", "webretrievedelay", ",", "proxy", ",", "targettype", ",", "target", ",", "useragent", ",", "botoutputrequested", ")", "else", ":", "print", "'A problem was found in the {sites} file. There appears to be a site entry with '", "'unequal numbers of regexs and reporting requirements'", ".", "format", "(", "sites", "=", "__SITESXML__", ")" ]
https://github.com/1aN0rmus/TekDefense-Automater/blob/42548cf454e862669c0a482955358fe27f7150e8/siteinfo.py#L73-L140
1aN0rmus/TekDefense-Automater
42548cf454e862669c0a482955358fe27f7150e8
siteinfo.py
python
SiteFacade.Sites
(self)
return self._sites
Checks the instance variable _sites is empty or None. Returns _sites (the site list) or None if it is empty. Argument(s): No arguments are required. Return value(s): list -- of Site objects or its subordinates. None -- if _sites is empty or None. Restriction(s): This Method is tagged as a Property.
Checks the instance variable _sites is empty or None. Returns _sites (the site list) or None if it is empty.
[ "Checks", "the", "instance", "variable", "_sites", "is", "empty", "or", "None", ".", "Returns", "_sites", "(", "the", "site", "list", ")", "or", "None", "if", "it", "is", "empty", "." ]
def Sites(self): """ Checks the instance variable _sites is empty or None. Returns _sites (the site list) or None if it is empty. Argument(s): No arguments are required. Return value(s): list -- of Site objects or its subordinates. None -- if _sites is empty or None. Restriction(s): This Method is tagged as a Property. """ if self._sites is None or len(self._sites) == 0: return None return self._sites
[ "def", "Sites", "(", "self", ")", ":", "if", "self", ".", "_sites", "is", "None", "or", "len", "(", "self", ".", "_sites", ")", "==", "0", ":", "return", "None", "return", "self", ".", "_sites" ]
https://github.com/1aN0rmus/TekDefense-Automater/blob/42548cf454e862669c0a482955358fe27f7150e8/siteinfo.py#L172-L189
1aN0rmus/TekDefense-Automater
42548cf454e862669c0a482955358fe27f7150e8
siteinfo.py
python
SiteFacade.identifyTargetType
(self, target)
return "hostname"
Checks the target information provided to determine if it is a(n) IP Address in standard; CIDR or dash notation, or an MD5 hash, or a string hostname. Returns a string md5 if MD5 hash is identified. Returns the string ip if any IP Address format is found. Returns the string hostname if neither of those two are found. Argument(s): target -- string representing the target provided as the first argument to the program when Automater is run. Return value(s): string. Restriction(s): The Method has no restrictions.
Checks the target information provided to determine if it is a(n) IP Address in standard; CIDR or dash notation, or an MD5 hash, or a string hostname. Returns a string md5 if MD5 hash is identified. Returns the string ip if any IP Address format is found. Returns the string hostname if neither of those two are found.
[ "Checks", "the", "target", "information", "provided", "to", "determine", "if", "it", "is", "a", "(", "n", ")", "IP", "Address", "in", "standard", ";", "CIDR", "or", "dash", "notation", "or", "an", "MD5", "hash", "or", "a", "string", "hostname", ".", "Returns", "a", "string", "md5", "if", "MD5", "hash", "is", "identified", ".", "Returns", "the", "string", "ip", "if", "any", "IP", "Address", "format", "is", "found", ".", "Returns", "the", "string", "hostname", "if", "neither", "of", "those", "two", "are", "found", "." ]
def identifyTargetType(self, target): """ Checks the target information provided to determine if it is a(n) IP Address in standard; CIDR or dash notation, or an MD5 hash, or a string hostname. Returns a string md5 if MD5 hash is identified. Returns the string ip if any IP Address format is found. Returns the string hostname if neither of those two are found. Argument(s): target -- string representing the target provided as the first argument to the program when Automater is run. Return value(s): string. Restriction(s): The Method has no restrictions. """ ipAddress = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}') ipFind = re.findall(ipAddress, target) if ipFind is not None and len(ipFind) > 0: return "ip" md5 = re.compile('[a-fA-F0-9]{32}', re.IGNORECASE) md5Find = re.findall(md5,target) if md5Find is not None and len(md5Find) > 0: return "md5" return "hostname"
[ "def", "identifyTargetType", "(", "self", ",", "target", ")", ":", "ipAddress", "=", "re", ".", "compile", "(", "'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'", ")", "ipFind", "=", "re", ".", "findall", "(", "ipAddress", ",", "target", ")", "if", "ipFind", "is", "not", "None", "and", "len", "(", "ipFind", ")", ">", "0", ":", "return", "\"ip\"", "md5", "=", "re", ".", "compile", "(", "'[a-fA-F0-9]{32}'", ",", "re", ".", "IGNORECASE", ")", "md5Find", "=", "re", ".", "findall", "(", "md5", ",", "target", ")", "if", "md5Find", "is", "not", "None", "and", "len", "(", "md5Find", ")", ">", "0", ":", "return", "\"md5\"", "return", "\"hostname\"" ]
https://github.com/1aN0rmus/TekDefense-Automater/blob/42548cf454e862669c0a482955358fe27f7150e8/siteinfo.py#L191-L220
1aN0rmus/TekDefense-Automater
42548cf454e862669c0a482955358fe27f7150e8
siteinfo.py
python
Site.__init__
(self, domainurl, webretrievedelay, proxy, targettype, reportstringforresult, target, useragent, friendlyname, regex, fullurl, boutoutputrequested, importantproperty, params, headers, method, postdata, verbose)
Class constructor. Sets the instance variables based on input from the arguments supplied when Automater is run and what the xml config file stores. Argument(s): domainurl -- string defined in xml in the domainurl XML tag. webretrievedelay -- the amount of seconds to wait between site retrieve calls. Default delay is 2 seconds. proxy -- will set a proxy to use (eg. proxy.example.com:8080). targettype -- the targettype as defined. Either ip, md5, or hostname. reportstringforresult -- string or list of strings that are entered in the entry XML tag within the reportstringforresult XML tag in the xml configuration file. target -- the target that will be used to gather information on. useragent -- the user-agent string that will be utilized when submitting information to or requesting information from a website friendlyname -- string or list of strings that are entered in the entry XML tag within the sitefriendlyname XML tag in the xml configuration file. regex -- the regexs defined in the entry XML tag within the regex XML tag in the xml configuration file. fullurl -- string representation of fullurl pulled from the xml file in the fullurl XML tag. boutoutputrequested -- true or false representation of whether the -b option was used when running the program. If true, it slims the output so a bot can be used and the output is minimalized. importantproperty -- string defined in the the xml config file in the importantproperty XML tag. params -- string or list provided in the entry XML tags within the params XML tag in the xml configuration file. headers -- string or list provided in the entry XML tags within the headers XML tag in the xml configuration file. method -- holds whether this is a GET or POST required site. by default = GET postdata -- dict holding data required for posting values to a site. by default = None verbose -- boolean representing whether text will be printed to stdout Return value(s): Nothing is returned from this Method.
Class constructor. Sets the instance variables based on input from the arguments supplied when Automater is run and what the xml config file stores.
[ "Class", "constructor", ".", "Sets", "the", "instance", "variables", "based", "on", "input", "from", "the", "arguments", "supplied", "when", "Automater", "is", "run", "and", "what", "the", "xml", "config", "file", "stores", "." ]
def __init__(self, domainurl, webretrievedelay, proxy, targettype, reportstringforresult, target, useragent, friendlyname, regex, fullurl, boutoutputrequested, importantproperty, params, headers, method, postdata, verbose): """ Class constructor. Sets the instance variables based on input from the arguments supplied when Automater is run and what the xml config file stores. Argument(s): domainurl -- string defined in xml in the domainurl XML tag. webretrievedelay -- the amount of seconds to wait between site retrieve calls. Default delay is 2 seconds. proxy -- will set a proxy to use (eg. proxy.example.com:8080). targettype -- the targettype as defined. Either ip, md5, or hostname. reportstringforresult -- string or list of strings that are entered in the entry XML tag within the reportstringforresult XML tag in the xml configuration file. target -- the target that will be used to gather information on. useragent -- the user-agent string that will be utilized when submitting information to or requesting information from a website friendlyname -- string or list of strings that are entered in the entry XML tag within the sitefriendlyname XML tag in the xml configuration file. regex -- the regexs defined in the entry XML tag within the regex XML tag in the xml configuration file. fullurl -- string representation of fullurl pulled from the xml file in the fullurl XML tag. boutoutputrequested -- true or false representation of whether the -b option was used when running the program. If true, it slims the output so a bot can be used and the output is minimalized. importantproperty -- string defined in the the xml config file in the importantproperty XML tag. params -- string or list provided in the entry XML tags within the params XML tag in the xml configuration file. headers -- string or list provided in the entry XML tags within the headers XML tag in the xml configuration file. method -- holds whether this is a GET or POST required site. by default = GET postdata -- dict holding data required for posting values to a site. by default = None verbose -- boolean representing whether text will be printed to stdout Return value(s): Nothing is returned from this Method. """ self._sourceurl = domainurl self._webretrievedelay = webretrievedelay self._proxy = proxy self._targetType = targettype self._reportstringforresult = reportstringforresult self._errormessage = "[-] Cannot scrape" self._usermessage = "[*] Checking" self._target = target self._userAgent = useragent self._friendlyName = friendlyname self._regex = "" self.RegEx = regex # call the helper method to clean %TARGET% from regex string self._fullURL = "" self.FullURL = fullurl # call the helper method to clean %TARGET% from fullurl string self._botOutputRequested = boutoutputrequested self._importantProperty = importantproperty self._params = None if params is not None: self.Params = params # call the helper method to clean %TARGET% from params string self._headers = None if headers is not None: self.Headers = headers # call the helper method to clean %TARGET% from params string self._postdata = None if postdata: self.PostData = postdata self._method = None self.Method = method # call the helper method to ensure result is either GET or POST self._results = [] self._verbose = verbose
[ "def", "__init__", "(", "self", ",", "domainurl", ",", "webretrievedelay", ",", "proxy", ",", "targettype", ",", "reportstringforresult", ",", "target", ",", "useragent", ",", "friendlyname", ",", "regex", ",", "fullurl", ",", "boutoutputrequested", ",", "importantproperty", ",", "params", ",", "headers", ",", "method", ",", "postdata", ",", "verbose", ")", ":", "self", ".", "_sourceurl", "=", "domainurl", "self", ".", "_webretrievedelay", "=", "webretrievedelay", "self", ".", "_proxy", "=", "proxy", "self", ".", "_targetType", "=", "targettype", "self", ".", "_reportstringforresult", "=", "reportstringforresult", "self", ".", "_errormessage", "=", "\"[-] Cannot scrape\"", "self", ".", "_usermessage", "=", "\"[*] Checking\"", "self", ".", "_target", "=", "target", "self", ".", "_userAgent", "=", "useragent", "self", ".", "_friendlyName", "=", "friendlyname", "self", ".", "_regex", "=", "\"\"", "self", ".", "RegEx", "=", "regex", "# call the helper method to clean %TARGET% from regex string", "self", ".", "_fullURL", "=", "\"\"", "self", ".", "FullURL", "=", "fullurl", "# call the helper method to clean %TARGET% from fullurl string", "self", ".", "_botOutputRequested", "=", "boutoutputrequested", "self", ".", "_importantProperty", "=", "importantproperty", "self", ".", "_params", "=", "None", "if", "params", "is", "not", "None", ":", "self", ".", "Params", "=", "params", "# call the helper method to clean %TARGET% from params string", "self", ".", "_headers", "=", "None", "if", "headers", "is", "not", "None", ":", "self", ".", "Headers", "=", "headers", "# call the helper method to clean %TARGET% from params string", "self", ".", "_postdata", "=", "None", "if", "postdata", ":", "self", ".", "PostData", "=", "postdata", "self", ".", "_method", "=", "None", "self", ".", "Method", "=", "method", "# call the helper method to ensure result is either GET or POST", "self", ".", "_results", "=", "[", "]", "self", ".", "_verbose", "=", "verbose" ]
https://github.com/1aN0rmus/TekDefense-Automater/blob/42548cf454e862669c0a482955358fe27f7150e8/siteinfo.py#L282-L353
1aN0rmus/TekDefense-Automater
42548cf454e862669c0a482955358fe27f7150e8
siteinfo.py
python
Site.buildSiteFromXML
(self, siteelement, webretrievedelay, proxy, targettype, target, useragent, botoutputrequested, verbose)
return Site(domainurl, webretrievedelay, proxy, targettype, reportstringforresult, target, useragent, sitefriendlyname, regex, fullurl, botoutputrequested, importantproperty, params, headers, method.upper(), postdata, verbose)
Utilizes the Class Methods within this Class to build the Site object. Returns a Site object that defines results returned during the web retrieval investigations. Argument(s): siteelement -- the siteelement object that will be used as the start element. webretrievedelay -- the amount of seconds to wait between site retrieve calls. Default delay is 2 seconds. proxy -- sets a proxy to use in the form of proxy.example.com:8080. targettype -- the targettype as defined. Either ip, md5, or hostname. target -- the target that will be used to gather information on. useragent -- the string utilized to represent the user-agent when web requests or submissions are made. botoutputrequested -- true or false representing if a minimalized output will be required for the site. Return value(s): Site object. Restriction(s): This Method is tagged as a Class Method
Utilizes the Class Methods within this Class to build the Site object. Returns a Site object that defines results returned during the web retrieval investigations.
[ "Utilizes", "the", "Class", "Methods", "within", "this", "Class", "to", "build", "the", "Site", "object", ".", "Returns", "a", "Site", "object", "that", "defines", "results", "returned", "during", "the", "web", "retrieval", "investigations", "." ]
def buildSiteFromXML(self, siteelement, webretrievedelay, proxy, targettype, target, useragent, botoutputrequested, verbose): """ Utilizes the Class Methods within this Class to build the Site object. Returns a Site object that defines results returned during the web retrieval investigations. Argument(s): siteelement -- the siteelement object that will be used as the start element. webretrievedelay -- the amount of seconds to wait between site retrieve calls. Default delay is 2 seconds. proxy -- sets a proxy to use in the form of proxy.example.com:8080. targettype -- the targettype as defined. Either ip, md5, or hostname. target -- the target that will be used to gather information on. useragent -- the string utilized to represent the user-agent when web requests or submissions are made. botoutputrequested -- true or false representing if a minimalized output will be required for the site. Return value(s): Site object. Restriction(s): This Method is tagged as a Class Method """ domainurl = siteelement.find("domainurl").text try: method = siteelement.find("method").text if method.upper() != "GET" and method.upper() != "POST": method = "GET" except: method = "GET" postdata = Site.buildDictionaryFromXML(siteelement, "postdata") reportstringforresult = Site.buildStringOrListfromXML(siteelement, "reportstringforresult") sitefriendlyname = Site.buildStringOrListfromXML(siteelement, "sitefriendlyname") regex = Site.buildStringOrListfromXML(siteelement, "regex") fullurl = siteelement.find("fullurl").text importantproperty = Site.buildStringOrListfromXML(siteelement, "importantproperty") params = Site.buildDictionaryFromXML(siteelement, "params") headers = Site.buildDictionaryFromXML(siteelement, "headers") return Site(domainurl, webretrievedelay, proxy, targettype, reportstringforresult, target, useragent, sitefriendlyname, regex, fullurl, botoutputrequested, importantproperty, params, headers, method.upper(), postdata, verbose)
[ "def", "buildSiteFromXML", "(", "self", ",", "siteelement", ",", "webretrievedelay", ",", "proxy", ",", "targettype", ",", "target", ",", "useragent", ",", "botoutputrequested", ",", "verbose", ")", ":", "domainurl", "=", "siteelement", ".", "find", "(", "\"domainurl\"", ")", ".", "text", "try", ":", "method", "=", "siteelement", ".", "find", "(", "\"method\"", ")", ".", "text", "if", "method", ".", "upper", "(", ")", "!=", "\"GET\"", "and", "method", ".", "upper", "(", ")", "!=", "\"POST\"", ":", "method", "=", "\"GET\"", "except", ":", "method", "=", "\"GET\"", "postdata", "=", "Site", ".", "buildDictionaryFromXML", "(", "siteelement", ",", "\"postdata\"", ")", "reportstringforresult", "=", "Site", ".", "buildStringOrListfromXML", "(", "siteelement", ",", "\"reportstringforresult\"", ")", "sitefriendlyname", "=", "Site", ".", "buildStringOrListfromXML", "(", "siteelement", ",", "\"sitefriendlyname\"", ")", "regex", "=", "Site", ".", "buildStringOrListfromXML", "(", "siteelement", ",", "\"regex\"", ")", "fullurl", "=", "siteelement", ".", "find", "(", "\"fullurl\"", ")", ".", "text", "importantproperty", "=", "Site", ".", "buildStringOrListfromXML", "(", "siteelement", ",", "\"importantproperty\"", ")", "params", "=", "Site", ".", "buildDictionaryFromXML", "(", "siteelement", ",", "\"params\"", ")", "headers", "=", "Site", ".", "buildDictionaryFromXML", "(", "siteelement", ",", "\"headers\"", ")", "return", "Site", "(", "domainurl", ",", "webretrievedelay", ",", "proxy", ",", "targettype", ",", "reportstringforresult", ",", "target", ",", "useragent", ",", "sitefriendlyname", ",", "regex", ",", "fullurl", ",", "botoutputrequested", ",", "importantproperty", ",", "params", ",", "headers", ",", "method", ".", "upper", "(", ")", ",", "postdata", ",", "verbose", ")" ]
https://github.com/1aN0rmus/TekDefense-Automater/blob/42548cf454e862669c0a482955358fe27f7150e8/siteinfo.py#L367-L411
1aN0rmus/TekDefense-Automater
42548cf454e862669c0a482955358fe27f7150e8
siteinfo.py
python
Site.buildStringOrListfromXML
(self, siteelement, elementstring)
return variablename
Takes in a siteelement and then elementstring and builds a string or list from multiple entry XML tags defined in the xml config file. Returns None if there are no entry XML tags for this specific elementstring. Returns a list of those entries if entry XML tags are found or a string of that entry if only one entry XML tag is found. Argument(s): siteelement -- the siteelement object that will be used as the start element. elementstring -- the string representation within the siteelement that will be utilized to get to the single or multiple entry XML tags. Return value(s): None if no entry XML tags are found. List representing all entry keys found within the elementstring. string representing an entry key if only one is found within the elementstring. Restriction(s): This Method is tagged as a Class Method
Takes in a siteelement and then elementstring and builds a string or list from multiple entry XML tags defined in the xml config file. Returns None if there are no entry XML tags for this specific elementstring. Returns a list of those entries if entry XML tags are found or a string of that entry if only one entry XML tag is found.
[ "Takes", "in", "a", "siteelement", "and", "then", "elementstring", "and", "builds", "a", "string", "or", "list", "from", "multiple", "entry", "XML", "tags", "defined", "in", "the", "xml", "config", "file", ".", "Returns", "None", "if", "there", "are", "no", "entry", "XML", "tags", "for", "this", "specific", "elementstring", ".", "Returns", "a", "list", "of", "those", "entries", "if", "entry", "XML", "tags", "are", "found", "or", "a", "string", "of", "that", "entry", "if", "only", "one", "entry", "XML", "tag", "is", "found", "." ]
def buildStringOrListfromXML(self, siteelement, elementstring): """ Takes in a siteelement and then elementstring and builds a string or list from multiple entry XML tags defined in the xml config file. Returns None if there are no entry XML tags for this specific elementstring. Returns a list of those entries if entry XML tags are found or a string of that entry if only one entry XML tag is found. Argument(s): siteelement -- the siteelement object that will be used as the start element. elementstring -- the string representation within the siteelement that will be utilized to get to the single or multiple entry XML tags. Return value(s): None if no entry XML tags are found. List representing all entry keys found within the elementstring. string representing an entry key if only one is found within the elementstring. Restriction(s): This Method is tagged as a Class Method """ variablename = "" if len(siteelement.find(elementstring).findall("entry")) == 0: return None if len(siteelement.find(elementstring).findall("entry")) > 1: variablename = [] for entry in siteelement.find(elementstring).findall("entry"): variablename.append(entry.text) else: variablename = "" variablename = siteelement.find(elementstring).find("entry").text return variablename
[ "def", "buildStringOrListfromXML", "(", "self", ",", "siteelement", ",", "elementstring", ")", ":", "variablename", "=", "\"\"", "if", "len", "(", "siteelement", ".", "find", "(", "elementstring", ")", ".", "findall", "(", "\"entry\"", ")", ")", "==", "0", ":", "return", "None", "if", "len", "(", "siteelement", ".", "find", "(", "elementstring", ")", ".", "findall", "(", "\"entry\"", ")", ")", ">", "1", ":", "variablename", "=", "[", "]", "for", "entry", "in", "siteelement", ".", "find", "(", "elementstring", ")", ".", "findall", "(", "\"entry\"", ")", ":", "variablename", ".", "append", "(", "entry", ".", "text", ")", "else", ":", "variablename", "=", "\"\"", "variablename", "=", "siteelement", ".", "find", "(", "elementstring", ")", ".", "find", "(", "\"entry\"", ")", ".", "text", "return", "variablename" ]
https://github.com/1aN0rmus/TekDefense-Automater/blob/42548cf454e862669c0a482955358fe27f7150e8/siteinfo.py#L414-L450

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
5
Add dataset card