Dataset Viewer
__id__
int64 3.09k
19,722B
| blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
256
| content_id
stringlengths 40
40
| detected_licenses
sequence | license_type
stringclasses 3
values | repo_name
stringlengths 5
109
| repo_url
stringlengths 24
128
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
42
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 6.65k
581M
⌀ | star_events_count
int64 0
1.17k
| fork_events_count
int64 0
154
| gha_license_id
stringclasses 16
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
5.76M
⌀ | gha_stargazers_count
int32 0
407
⌀ | gha_forks_count
int32 0
119
⌀ | gha_open_issues_count
int32 0
640
⌀ | gha_language
stringlengths 1
16
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 9
4.53M
| src_encoding
stringclasses 18
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | year
int64 1.97k
2.01k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
12,369,505,844,840 |
2c34a7d86f4706a06fa24e9415beed8812be3809
|
bd00311326529a54b4ca368717ab2bf622df7df5
|
/static/js/connexps/redis.py
|
2ecd69a59854050544f7015ecbcae426446dab70
|
[] |
no_license
|
glamp/yaksis
|
https://github.com/glamp/yaksis
|
2c0a3b094ecbaefd9ad34aee4a9853134ab43d20
|
bcff3f8d2b1ee2a656e81a09febcdcf1c5b5aa41
|
refs/heads/master
| 2020-12-25T08:42:15.532000 | 2014-06-26T14:36:35 | 2014-06-26T14:36:35 | 7,233,969 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import redis
r = redis.StrictRedis(host='localhost', port=6379, password='password1234')
|
UTF-8
|
Python
| false | false | 2,014 |
4,355,096,865,416 |
ee7e621b1a3d72b73f920339a713cf12b1b537ec
|
61b9e597f0bd27ee7ec86188b7e10518ee30425c
|
/learners/cn2sd/evaluator.py
|
45ffbed3216d9daaf452c2582683876caba413f4
|
[] |
no_license
|
sirrice/dbwipes_src
|
https://github.com/sirrice/dbwipes_src
|
eeb369d09ba28cb1ab3ffa70551c2b253dd39cb3
|
4d42b7d51af190b21679f38150f85dec1496d78c
|
refs/heads/master
| 2021-01-21T12:36:22.888000 | 2014-04-23T20:53:16 | 2014-04-23T20:53:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import orange, Orange
import sys, math, heapq
from rule import *
from refiner import *
from collections import Counter
from util import ids_filter, get_logger, max_prob
import numpy as np
import pdb
_logger = get_logger()
class RuleEvaluator_WRAccAdd(orange.RuleEvaluator):
def __init__(self, *args, **kwargs):
self.cost = 0.
def clear_cache(self):
pass
def __call__(self, newRule, examples, rank_id, weightID, targetClass, prior):
"""compute: prob(class,condition) - p(cond)*p(class)
or: p(cond) * ( p(class|cond) - p(class) )
"""
ncond = N = nclasscond = nclass = 0.0
np_rank_all = examples.to_numpyMA('w', rank_id)[0].reshape(len(examples))
np_weight_all = examples.to_numpyMA('w', weightID)[0].reshape(len(examples))
np_rank_new = newRule.examples.to_numpyMA('w', rank_id)[0].reshape(len(newRule.examples))
np_weight_new = newRule.examples.to_numpyMA('w', weightID)[0].reshape(len(newRule.examples))
start = time.time()
N = np_weight_all.sum()
nclass = np.dot(np_rank_all, np_weight_all)
ncond = np_weight_new.sum()
nclasscond = np.dot(np_rank_new, np_weight_new)
wracc = nclasscond / N - (ncond * nclass) / (N * N)
self.cost += time.time()-start
if wracc > 0:
_logger.debug( 'wracc\t%.5f\t%s', wracc, newRule.ruleToString())
if N == 0:
wracc = -1
if math.isnan(wracc):
wracc = -1
newRule.quality = wracc
newRule.score = wracc
newRule.stats_mean = 0.
newRule.stats_nmean = 0.
return wracc
class RuleEvaluator_WRAccMult(orange.RuleEvaluator):
def __init__(self, alpha):
self.alpha = alpha
def __call__(self, newRule, examples, weightID, targetClass, prior):
raise
#####################################################
#
# The following evaluators are all for combined rule learning
#
#
#####################################################
class ErrorRunner(object):
def __init__(self, err_func):
self.err_func = err_func
self.cache = {}
def __call__(self, rule):
rulehash = hash(rule)
if rulehash in self.cache:
return self.cache[rulehash]
if not len(rule.examples):
return 0.
if True:
data = rule.examples
else:
rule.filter(t, negate=negate)
score = self.err_func( data.to_numpyMA('a')[0] )
score /= (1 + len(rule.examples))
if math.isinf(score):
pdb.set_trace()
self.err_func(data.to_numpyMA('a')[0])
if math.isnan(score):
return 0.
self.cache[rulehash] = score
return score
class ErrorRunnerNegated(object):
def __init__(self, err_func):
self.err_func = err_func
self.cache = {}
def __call__(self, rule):
rulehash = hash(rule)
if rulehash in self.cache:
return self.cache[rulehash]
if not len(rule.examples):
return 0.
rows = rule.filter(self.err_func.table)
if not len(rows):
score = 0.
else:
score = np.mean([ row['temp'].value for row in rows ]) - self.err_func.mean
self.cache[rulehash] = score
return score
class ConfidenceRefiner(object):
def __init__(self, nsamples=10, get_error=None, refiner=None, good_dist=None, **kwargs):
self.good_dist = good_dist
self.nsamples = 10
self.refiner = refiner or BeamRefiner()
self.get_error = get_error
self.cache = {}
self.ncalls = 0
def clear_cache(self):
self.cache = {}
def __call__(self, rule, negate=False):
rulehash = hash('%s\t[%s]' % (rule, negate))
if rulehash in self.cache:
return self.cache[rulehash]
if negate:
res = self.run_negated(rule)
else:
res = self.run(rule)
self.cache[rulehash] = res
return res
def run_negated(self, rule):
base_data = rule.data
err_func = self.get_error.err_func
examples = rule.examples
# sample values in base_data that are not in examples
sampsize = max(1, int(0.05 * len(base_data)))
sampler = Orange.data.sample.SubsetIndices2(p0=sampsize)
sampler.random_generator = Orange.misc.Random(len(examples))
scores = []
for new_rule in self.refiner(rule, negate=True):
sample = base_data.select_ref(sampler(base_data), negate=True) # select 0.05%
new_rule.filter.negate=not new_rule.filter.negate
sample = sample.filter_ref(rule.filter)
n = len(sample)
if n == 0:
continue
score = err_func(sample.to_numpyMA('a')[0])
self.ncalls += 1
if not math.isnan(score):
score /= n
scores.append( score )
if not len(scores):
return 0., 0.,
mean, std = np.mean(scores), np.std(scores)
std = math.sqrt( sum( (mean - score)**2 for score in scores ) / (len(scores) - 1.5) )
if self.good_dist:
mean -= self.good_dist[0]
return mean, std
def run(self, rule):
base_data = rule.data
examples = rule.examples
err_func = self.get_error.err_func
scores = []
for new_rule in self.refiner(rule):
if not len(new_rule.examples):
continue
#return new_rule.filter(t, negate=negate)
data = new_rule.examples
score = self.err_func(data.to_numpyMA('a')[0]) / len(new_rule.examples)
self.ncalls += 1
if not math.isnan(score):
scores.append(score)
if not len(scores):
return 0., 0.
mean, std = np.mean(scores), np.std(scores)
# unbiased std estimator
std = math.sqrt( sum( (mean - score)**2 for score in scores ) / (len(scores) - 1.5) )
if self.good_dist:
mean -= self.good_dist[0]
return mean, std
class ConfidenceSample(object):
def __init__(self, nsamples=10, get_error=None, good_dist=None, **kwargs):
self.good_dist = good_dist
self.nsamples = 50
self.get_error = get_error
self.cache = {}
self.ncalls = 0
def clear_cache(self):
self.cache = {}
def __call__(self, rule, negate=False):
"""
run error function on samples of the rule to compute a confidence score
"""
rulehash = hash('%s\t[%s]' % (rule,negate))
if rulehash in self.cache:
return self.cache[rulehash]
if negate:
res = self.run_negated(rule)
else:
res = self.run(rule)
self.cache[rulehash] = res
return res
def run_negated(self, rule):
base_data = rule.data
err_func = self.get_error.err_func
examples = rule.examples
if len(examples) == len(base_data):
return self.good_dist[0], self.good_dist[1], 0., 0.
# sample values in base_data that are not in examples
sampsize = max(1, int(0.1 * len(base_data)))
sampler = Orange.data.sample.SubsetIndices2(p0=sampsize)
sampler.random_generator = Orange.misc.Random(len(examples))
scores = []
tries = 0
while len(scores) < min(self.nsamples, len(base_data)-len(examples)):
# XXX: doesn't work for the slow error functions
sample = base_data.select_ref(sampler(base_data), negate=True)
rule.filter.negate=not rule.filter.negate
sample = sample.filter_ref(rule.filter)
rule.filter.negate=not rule.filter.negate
n = len(sample)
tries += 1
if n == 0:
continue
data = sample.to_numpyMA('a')[0]
score = err_func(data)
self.ncalls += 1
if not math.isnan(score):
score /= n
scores.append( score )
else:
pdb.set_trace()
score = err_func(data)
if not len(scores):
return 0., 0., 0., 0.
mean, std, minv, maxv = np.mean(scores), np.std(scores), min(scores), max(scores)
std = math.sqrt( sum( (mean - score)**2 for score in scores ) / (len(scores) - 1.5) )
if self.good_dist:
mean -= self.good_dist[0]
return mean, std, minv, maxv
def run(self, rule):
err_func = self.get_error.err_func
examples = rule.examples
sampsize = max(2, int(0.1 * len(examples)))
if len(examples) < 2:
sampler = lambda table: [0]*len(table)
else:
sampler = Orange.data.sample.SubsetIndices2(p0=sampsize)
sampler.random_generator = Orange.misc.Random(len(examples))
scores = []
for i in xrange(self.nsamples):
idxs = sampler(examples)
n = (len(idxs) - sum(idxs))
if n == 0:
continue
if True:
data = examples.select_ref(idxs, negate=True)
else:
data = examples.select_ref(idxs, negate=False)
score = err_func(data.to_numpyMA('a')[0]) / n
self.ncalls += 1
if not math.isnan(score):
scores.append( score )
if not len(scores):
return 0., 0., 0., 0.
mean, std, minv, maxv = np.mean(scores), np.std(scores), min(scores), max(scores)
std = math.sqrt( sum( (mean - score)**2 for score in scores ) / (len(scores) - 1.5) )
if self.good_dist:
mean -= self.good_dist[0]
return mean, std, minv, maxv
class RuleEvaluator_RunErr(orange.RuleEvaluator):
def __init__(self, good_dist, get_error, confidence, **kwargs):
self.good_dist = good_dist
self.get_error = get_error
self.confidence = confidence
self.cost = 0.
self.n_sample_calls = 0
self.beta = kwargs.get('beta', .1) # beta. weight of precision vs recall
def clear_cache(self):
self.confidence.clear_cache()
def get_weights(self, newRule, examples, weightID):
N = len(examples)
ncond = len(newRule.examples)
if weightID is None:
return 1., 1.,
weight_all = examples.to_numpyMA('w', weightID)[0].reshape(N)
weight_cond = newRule.examples.to_numpyMA('w', weightID)[0].reshape(ncond)
allweights = np.mean(weight_all)
condweights = np.mean(weight_cond) if ncond else 0.
return condweights, allweights
def __call__(self, newRule, examples, rank_id, weightID, targetClass, prior):
condweights, allweights = self.get_weights(newRule, examples, weightID)
weight = condweights / allweights
score = self.get_error( newRule )
if (not allweights or
not len(newRule.examples)):
newRule.score = None
return 0.
mean,std,minv, maxv = self.confidence(newRule)
negmean, negstd,nminv,nmaxv = self.confidence(newRule, negate=True)
ret = 0
stats = (weight, score, minv * 100, maxv * 100, std, negmean, len(newRule.examples))
stats = ('\t%.4f' * len(stats)) % stats
_logger.debug( 'wracc samp:%s\t%s' % (stats, newRule) )
newRule.score = score
newRule.weight = condweights / allweights
newRule.stats_mean, newRule.stats_std = mean, std
newRule.stats_minv, newRule.stats_maxv = minv, maxv
newRule.stats_nmean, newRule.stats_nstd = negmean, negstd
newRule.stats_nminv, newRule.stats_nmaxv = nminv, nmaxv
self.n_sample_calls += self.confidence.nsamples
return ret
class RuleEvaluator_RunErr_Next(RuleEvaluator_RunErr):
"""
Uses leave-predicate-out based scoring
"""
def __init__(self, good_dist, err_func, **kwargs):
get_error = ErrorRunner(err_func)
confidence = kwargs.get('confidence',
ConfidenceRefiner(get_error=get_error,
good_dist=good_dist,
**kwargs))
RuleEvaluator_RunErr.__init__(self, good_dist, get_error, confidence, **kwargs)
class RuleEvaluator_RunErr_Sample(RuleEvaluator_RunErr):
def __init__(self, good_dist, err_func, **kwargs):
get_error = ErrorRunner(err_func)
confidence = kwargs.get('confidence', ConfidenceSample(get_error=get_error,
good_dist=good_dist,
**kwargs))
RuleEvaluator_RunErr.__init__(self, good_dist, get_error, confidence, **kwargs)
class RuleEvaluator_RunErr_Negated(RuleEvaluator_RunErr):
"""
Uses error(predicate) scoring
"""
def __init__(self, good_dist, err_func, **kwargs):
get_error = ErrorRunnerNegated(err_func)
confidence = kwargs.get('confidence', ConfidenceSample(get_error=get_error))
RuleEvaluator_RunErr.__init__(self, good_dist, get_error, confidence, **kwargs)
def __call__(self, newRule, examples, rank_id, weightID, targetClass, prior):
if not len(newRule.examples):
return 0.
condweights, allweights = self.get_weights(newRule, examples, weightID)
score = self.get_error( newRule )
if score > 0:
_logger.debug( 'wracc samp:\t%.4f\t%d\t%.4f\t%s',
score, len(newRule.examples), condweights, newRule.ruleToString())
return score / len(newRule.examples)
|
UTF-8
|
Python
| false | false | 2,014 |
8,383,776,200,130 |
9dec44284cee45efee401004a1ec84b8e5c20f1f
|
391198cf74330569cf669f88ecbf83a41c8633dc
|
/src/playercontext.py
|
52eb8912ed678bf8b94ad2d8f5a22f4407da3d02
|
[
"BSD-3-Clause"
] |
permissive
|
Sophie-Williams/Athena-SCG-Bot
|
https://github.com/Sophie-Williams/Athena-SCG-Bot
|
8e18daa149f0134d2ab3d3ce1033cd0adc2dce9f
|
788b0e276a46028fc1107797fb807414131f685a
|
refs/heads/master
| 2020-05-19T15:33:34.552000 | 2009-12-13T04:07:31 | 2009-12-13T04:07:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
"""Game context and configuration classes."""
import offer
import cspparser
import problem
class Config(object):
"""Represents a CSP configuration object."""
def __init__(self, gamekind=None, turnduration=None, mindecrement=None,
initacc=None, maxProposals=0, minProposals=0,
minPropositions=0, objective=None, predicate=None,
numrounds=None, profitfactor=None, otrounds=None,
maxClauses=0, hasSecrets=False, secretRatio=0):
"""A Config object with type enforcement."""
self.gamekind = gamekind
self.turnduration = int(turnduration)
self.mindecrement = float(mindecrement)
self.initacc = float(initacc)
self.maxoffers = self.maxproposals = int(maxProposals)
self.minproposals = int(minProposals)
self.minpropositions = int(minPropositions)
self.maxclauses = int(maxClauses)
self.objective = objective
self.predicate = predicate
self.numrounds = int(numrounds)
self.profitfactor = float(profitfactor)
self.otrounds = int(otrounds)
if hasSecrets == 'true':
self.hassecrets = True
else:
self.hassecrets = False
self.secretratio = float(secretRatio)
@classmethod
def FromString(cls, input):
"""Get a config object from an input string."""
ps = cspparser.Config.searchString(input)
if ps:
return cls.FromParsed(ps[0])
else:
raise Exception('Configuration not found in input string')
@classmethod
def FromParsed(cls, parse_obj):
"""Get a config object from the parser output."""
return cls(**parse_obj.asDict())
class PlayerContext(object):
"""Represent a CSP PlayerContext object from the administrator."""
def __init__(self, config=None, their_offered=None,
our_offered=None, accepted=None,
provided=None, playerid=None, currentround=None,
balance=None):
self.their_offered = offer.Offer.GetOfferList(their_offered)
self.their_offered.sort()
self.our_offered = offer.Offer.GetOfferList(our_offered)
self.accepted = offer.AcceptedChallenge.GetAcceptedChallengeList(accepted)
self.provided = problem.Problem.GetProblemList(provided)
self.config = config
self.playerid = int(playerid)
self.currentround = int(currentround)
self.balance = float(balance)
self.endbalance = float(self.balance)
@classmethod
def FromString(cls, input):
"""Get a playercontext from the inputstring."""
ps = cspparser.PlayerContext.searchString(input)
if ps:
return cls.FromParsed(ps[0])
else:
raise Exception('PlayerContext not found in input string')
@classmethod
def FromParsed(cls, parsed):
"""Get a playercontext from the parser."""
return cls(config=Config.FromParsed(parsed.config),
their_offered=parsed.their_offered,
our_offered=parsed.our_offered,
accepted=parsed.accepted, provided=parsed.provided,
playerid=parsed.playerid, currentround=parsed.currentround,
balance=parsed.balance)
|
UTF-8
|
Python
| false | false | 2,009 |
8,744,553,444,465 |
7e2d946cf1bfc269fb0a8beabef7a7d0cb9136e9
|
f3db511130a20ac1af0719a97d65e7d18fae5c9b
|
/UAVSAR_Bulk_Data_extract_T3.py
|
f0a6b51d2b1828aec8db07be48918f355fb8b8c5
|
[
"GPL-2.0-only"
] |
non_permissive
|
googlecorporation/UAVSAR-Tinklets
|
https://github.com/googlecorporation/UAVSAR-Tinklets
|
f1c498f9619f821380b2cbe03fb86dadbdc4d1bd
|
0726b1f4560ea0f35cc0f27dd157e4f3e2a327da
|
refs/heads/master
| 2018-03-23T13:49:49.123000 | 2014-10-08T11:19:33 | 2014-10-08T11:19:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 6 13:44:34 2014
Takes multiple scenes from an "INPUT" (input_dir) directory and produces
Seperate extracted outputs in an "OUTPUT" (output_path) directory.
!! OUTPUT CANT BE A SUBDIRECTORY OF INPUT !!
@author: SHAUNAK
"""
import os.path
import subprocess
# Read all the files in a given folder
input_dir = "F:\\Work_IITB\\multidate\\" #Working Directory
program_root = "C:\\Program Files (x86)\\PolSARpro_v4.2.0\\" #PolSAR installation
output_dir = "F:\\Work_IITB\\output"
# Make sure that the output directory exists
if ( os.path.isdir(output_dir) == False ):
os.mkdir(output_dir)
# Soft/data_import/airsar_header.exe
# Arguments:
# "E:/Data/UAVSAR/Haywrd_multiangle/Haywrd_05501_10080_007_101110_L090_CX_01.dat"
# "C:/Users/SHAUNAK/AppData/Local/Temp/PolSARpro_4.2.0/Tmp/2014_10_06_12_05_59_airsar_config.txt"
# "C:/Users/SHAUNAK/AppData/Local/Temp/PolSARpro_4.2.0/Tmp/2014_10_06_12_05_59_airsar_fst_header_config.txt"
# "C:/Users/SHAUNAK/AppData/Local/Temp/PolSARpro_4.2.0/Tmp/2014_10_06_12_05_59_airsar_par_header_config.txt"
# "C:/Users/SHAUNAK/AppData/Local/Temp/PolSARpro_4.2.0/Tmp/2014_10_06_12_05_59_airsar_cal_header_config.txt"
# "C:/Users/SHAUNAK/AppData/Local/Temp/PolSARpro_4.2.0/Tmp/2014_10_06_12_05_59_airsar_dem_header_config.txt"
# old MLC
for root, dirs, files in os.walk(input_dir):
#pick up each file and run the extraction steps
for file in files:
## first gather metadata
program_path = os.path.join(program_root, "Soft\\data_import\\airsar_header.exe")
scene_name = file.split(".")[0]
scene_path = os.path.join(output_dir,scene_name)
print(scene_name) # Print the current file under consideration
# Make a new directory for each scene
if ( os.path.isdir(os.path.join(output_dir,scene_name)) == False ):
os.mkdir(os.path.join(output_dir,scene_name))
# Extract the metadata
subprocess.call([program_path, os.path.join(root,file),
os.path.join(scene_path,scene_name)+"_config.txt",
os.path.join(scene_path,scene_name)+"_fst.txt",
os.path.join(scene_path,scene_name)+"_par.txt",
os.path.join(scene_path,scene_name)+"_cal.txt",
os.path.join(scene_path,scene_name)+"_dem.txt","old","MLC"], shell=True)
# Read the files to figure out the parameters for the second call!
config_file_f = open(os.path.join(scene_path,scene_name)+"_config.txt")
configuration = config_file_f.readlines()
config_file_f.close()
num_lines = int(configuration[2].split()[0])
num_cols = int(configuration[5].split()[0])
# Process The Function Soft/data_import/airsar_convert_T3.exe
# Arguments: "E:/Data/UAVSAR/Haywrd_multiangle/Haywrd_05501_10080_007_101110_L090_CX_01.dat" "E:/Data/UAVSAR/Haywrd_multiangle/T3" 3300 0 0 18672 3300 "C:/Users/SHAUNAK/AppData/Local/Temp/PolSARpro_4.2.0/Tmp/2014_10_06_12_05_59_airsar_config.txt" 1 1
# airsar_convert_T3 stk_file_name out_dir Ncol offset_lig offset_col sub_nlig sub_ncol HeaderFile SubSampRG SubSampAZ
#Update the program path
program_path = os.path.join(program_root, "Soft\\data_import\\airsar_convert_T3.exe")
#CHECK / Make the T3 directory
T3_Path = os.path.join(os.path.join(scene_path,"T3"))
if( os.path.isdir(T3_Path) == False):
os.mkdir(T3_Path)
mlAz = "1"
mlRg = "1"
subprocess.call([program_path,
os.path.join(root,file), T3_Path,
str(num_cols), "0", "0", str(num_lines), str(num_cols), os.path.join(scene_path,scene_name)+"_config.txt", mlAz, mlRg])
#Make the pauli RGB
program_path = os.path.join(program_root, "Soft\\bmp_process\\create_pauli_rgb_file_T3.exe")
subprocess.call([program_path,
T3_Path, os.path.join(T3_Path,"PauliRGB.BMP"), str(num_cols),
"0", "0", str(num_lines), str(num_cols)])
|
UTF-8
|
Python
| false | false | 2,014 |
19,121,194,439,456 |
3c0f062734673323781a3e5ec5caad0f7db2ae25
|
29f329bee4c54d2d71fc76874e6ffccc2b56e890
|
/viterbi.py
|
dc38f8578b92acbc35f49853dde80cffb477483c
|
[] |
no_license
|
Peaker/tau
|
https://github.com/Peaker/tau
|
f712213963ad8cb2e135ca34fcc9984673c52d51
|
06b381055ed478eeb45cdaa1b9e584bc2d3c1014
|
refs/heads/master
| 2020-12-25T13:12:48.100000 | 2013-05-18T23:25:58 | 2013-05-18T23:25:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class State(object):
def __init__(self, name):
self.name = name
self.a_table = {}
self.b_table = {}
def __repr__(self):
return self.name
def connect(self, state, prob):
self.a_table[state] = prob
def get_a(self, state):
return self.a_table.get(state, 0.0)
def get_b(self, ch):
return self.b_table.get(ch, 0.0)
def set_b(self, ch, prob):
self.b_table[ch] = prob
class HMM(object):
def __init__(self, num_of_internal_states):
self.num_of_internal_states = num_of_internal_states
self.q0 = State("q0")
self.qF = State("qF")
self.states = {"q0" : self.q0, 0 : self.q0,
"qF" : self.qF, num_of_internal_states + 1 : self.qF}
for i in range(1, num_of_internal_states + 1):
self.states["q%d" % (i,)] = self.states[i] = State("q%d" % (i,))
def __getitem__(self, key):
return self.states[key]
def internal_states(self):
return (self.states[k] for k in range(1, self.num_of_internal_states+1))
def all_states(self):
return (self.states[k] for k in range(0, self.num_of_internal_states+2))
class TableCell(object):
def __init__(self):
self.value = 0.0
self.back = None
def __repr__(self):
return "(%r, %r)" % (self.value, self.back)
class Table(object):
def __init__(self, hmm, observations):
self.hmm = hmm
self.cells = {s : [TableCell() for i in range(len(observations))]
for s in hmm.all_states()}
def __str__(self):
lines = []
for s in self.hmm.all_states():
row = self.cells[s]
line = " | ".join("%.5f %04s" % (cell.value, cell.back) for cell in row)
lines.append(repr(s) + " | " + line)
return "\n".join(lines)
def __getitem__(self, ind):
s, t = ind
return self.cells[s][t]
def viterbi(hmm, observations):
table = Table(hmm, observations)
for s in hmm.internal_states():
table[s, 0].value = hmm.q0.get_a(s) * s.get_b(observations[0])
table[s, 0].back = hmm.q0
for t, ch in enumerate(observations[1:]):
for s in hmm.internal_states():
maxv2 = -1
for q in hmm.internal_states():
v1 = table[q, t].value * q.get_a(s) * s.get_b(ch)
v2 = table[q, t].value * q.get_a(s)
if v1 > table[s, t+1].value:
table[s, t+1].value = v1
if v2 > maxv2:
maxv2 = v2
table[s, t+1].back = q
t = len(observations) - 1
for q in hmm.internal_states():
v = table[q, t].value * q.get_a(hmm.qF)
if v > table[hmm.qF, t].value:
table[hmm.qF, t].value = v
table[hmm.qF, t].back = q
print table
s = hmm.qF
path = []
#t -= 1
while t >= 0:
path.append(s)
s = table[s, t].back
t -= 1
path.append(s)
path.append(hmm.q0)
return path[::-1]
if __name__ == "__main__":
h = HMM(2)
# q0
h["q0"].connect(h["q1"], 0.7)
h["q0"].connect(h["q2"], 0.3)
# q1
h["q1"].set_b("u", 0.5)
h["q1"].set_b("v", 0.5)
h["q1"].connect(h["q1"], 0.5)
h["q1"].connect(h["q2"], 0.3)
h["q1"].connect(h["qF"], 0.2)
# q2
h["q2"].set_b("u", 0.8)
h["q2"].set_b("v", 0.2)
h["q2"].connect(h["q1"], 0.4)
h["q2"].connect(h["q2"], 0.5)
h["q2"].connect(h["qF"], 0.1)
#print viterbi(h, "vvuvuu")
#print viterbi(h, "uuuvuuv")
print viterbi(h, "u")
|
UTF-8
|
Python
| false | false | 2,013 |
3,745,211,494,568 |
66bf8c6f9d515a6f000023694b5aeaa7e9de32c5
|
093a1dea14a493bf306e67a9cb449150e0194891
|
/matrix_generators/call_vector.py
|
ac2d8b0dc586b716539dfb63edd5228cfbc529d5
|
[] |
no_license
|
syadlowsky/density-estimation
|
https://github.com/syadlowsky/density-estimation
|
5ec52f0eaa47acaa04385624a1f29704a7df67b2
|
b742d70171432d66acf581429836e2a7b034b32d
|
refs/heads/master
| 2016-09-05T10:29:00.013000 | 2014-07-01T22:44:12 | 2014-07-01T22:44:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import os, sys
import numpy as np
import logging
from django.db import connection
def get_counts_in_tower(start_time, interval, use_call_model=False):
c = connection.cursor()
#logging.info("Counting time slices in interval given")
#query = """
#SELECT COUNT(DISTINCT traj.timesta)
#FROM mivehdetailedtrajectory traj
#WHERE traj.timesta >= %s AND traj.timesta <= %s
#"""
#c.execute(query, (start_time, start_time+interval))
#intervals = float(c.fetchone()[0])
logging.info("Getting cars in each cell tower for interval")
query = """
SELECT (SELECT COUNT(traj.*)
FROM mivehdetailedtrajectory traj
WHERE ST_Contains(tower.geom, traj.location)
AND traj.timesta >= %s AND traj.timesta <= %s)
FROM cell_data_tower tower
ORDER BY tower.id
"""
c.execute(query, (start_time, start_time+interval))
#tower_counts = [r[0]/intervals for r in c]
tower_counts = [float(r[0]) for r in c]
logging.info("Computing estimated number of calls made for that number of cars in a cell tower.")
if use_call_model:
return np.array([np.random.poisson(interval*count/396.0) for count in tower_counts]) # off by a factor of 10 in denominator for efficiency
else:
return np.array(tower_counts)
|
UTF-8
|
Python
| false | false | 2,014 |
283,467,862,299 |
414af24791260df25c5bdf3e5af73d65853ce573
|
d145f7383c491ad48b26709d369cd0d6a8542e02
|
/py/pdfto/alltests.py
|
ca9b3a0f3bca24e65b0f214a9cdb9a596df9c71a
|
[] |
no_license
|
d910aa14/hot
|
https://github.com/d910aa14/hot
|
f636268df80f55489bde12386104de5666c7f56d
|
2e0caec912aef3d3c673707eecb1152a198b01f0
|
refs/heads/master
| 2016-09-06T12:37:28.201000 | 2013-11-29T13:43:42 | 2013-11-29T13:43:42 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from os.path import dirname, join, realpath
from sys import path as pythonpath
pythonpath[:0] = join(dirname(realpath(__file__))),
from autotester import autorun_text_test
if __name__ == '__main__':
autorun_text_test(__file__)
|
UTF-8
|
Python
| false | false | 2,013 |
12,987,981,132,949 |
da2c8a88c1a4c07055248851f51e157c7cef612c
|
7b04d5e07a6924502245b501b268e606b5e8229f
|
/MyDB.py
|
cbddb2d399edefea28fb5a12fe7d4da48dad0adb
|
[] |
no_license
|
aq2004723/docwebsite
|
https://github.com/aq2004723/docwebsite
|
c68e52fe5532bc271f357857da0cfa19688a8996
|
7646971d2d5fbddf452d4cf52d3f13e811d3a5d1
|
refs/heads/master
| 2021-01-15T22:29:06.269000 | 2014-11-27T13:34:32 | 2014-11-27T13:34:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#coding=utf-8
import MySQLdb
import sys
import time
from unotest import DocumentConverter,DocumentConversionException
import uuid
import os
from com.sun.star.task import ErrorCodeIOException
import base64
class MyDB(object):
def __init__(self):
self.conn=MySQLdb.connect(host='localhost',user='root',passwd='541788',db='heralddoc',port=3306)
self.cursor=self.conn.cursor()
def __delete__(self):
self.conn.close()
def getRandomCookieSecret(self):
return base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes)
def getDoc(self,docID):
sql=r"SELECT docID,docname,cover,pdflocation,docdescribe,downloadcount FROM document WHERE docID = "+ str(docID)
rs = {}
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
for row in results:
rs['docID'] = row[0]
rs['docname'] = row[1]
rs['cover'] = row[2]
rs['pdflocation'] = row[3]
rs['docdescribe'] = row[4]
rs['downloadcount'] = row[5]
except:
s=sys.exc_info()
print "Error '%s' happened on line %d" % (s[1],s[2].tb_lineno)
"""
for i in rs:
print "rs[%s]=" % i,rs[i]
"""
return rs
def news20doc(self):
sql= "SELECT document.docid, document.docname, document.cover, \
userupload.uploaddate,document.docdescribe FROM document \
LEFT JOIN userupload ON document.docID=userupload.docID \
ORDER BY userupload.uploaddate LIMIT 0,20;"
rs = []
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
for row in results:
pdf_temp = {}
pdf_temp['id'] = row[0]
pdf_temp['name']= row[1]
pdf_temp['cover'] = row[2]
pdf_temp['time']= row[3]
pdf_temp['desc']= row[4]
rs.append(pdf_temp)
except:
s=sys.exc_info()
print "Error '%s' happened on line %d" % (s[1],s[2].tb_lineno)
return rs
def upload(self,userID,filename,description,myfile):
#check the file is right
#make a dict for the file
day = time.strftime('%Y/%m/%d',time.localtime(time.time()))
source_path = os.path.join(os.getcwd()+ '/static/file/source', day)
if not os.path.isdir(source_path):
os.makedirs(source_path)
#make the pdf dict
pdf_path = os.path.join(os.getcwd()+ '/static/file/pdf', day)
if not os.path.isdir(pdf_path):
os.makedirs(pdf_path)
#generate the only filename
onlyname = uuid.uuid4().hex
typename = myfile['filename']
typename = typename[typename.find('.'):]
source_path = os.path.join(source_path,onlyname + typename)
pdf_path = os.path.join(pdf_path,onlyname + ".pdf")
#save the file into source_patf
with open(source_path,'wb') as up:
up.write(myfile['body'])
#if not pdf ,call DocumentConverter to translate the doc to pdf
if not typename ==".pdf":
try:
converter = DocumentConverter()
converter.convert(source_path, pdf_path)
except DocumentConversionException, exception:
print "ERROR! " + str(exception)
return False
except ErrorCodeIOException, exception:
print "ERROR! ErrorCodeIOException %d" % exception.ErrCode
try:
source_path = source_path[source_path.find('file/'):]
if typename ==".pdf":
pdf_path= source_path
else:
pdf_path[pdf_path.find('file/'):]
sql = "insert into document(docname,cover,sourcelocation,pdflocation,docdescribe,downloadcount)\
value('%s','%s','%s','%s','%s','%d')"%(filename,"",source_path,pdf_path,description,0)
self.cursor.execute(sql)
self.conn.commit()
sql ="select max(docID) from document"
self.cursor.execute(sql)
results = self.cursor.fetchall()
docID = 0
for row in results:
docID = row[0]
sql = "insert into userupload(docID,uploaddate,userID) \
value(%d,'%s',%d)"%(docID,time.strftime('%Y-%m-%d %H:%M:%S'),long(userID))
self.cursor.execute(sql)
self.conn.commit()
except:
s=sys.exc_info()
print "Error '%s' happened on line %d" % (s[1],s[2].tb_lineno)
def checkuser(self,username,password):
sql = "select userID from user where username = '%s' and password = '%s'"%(username,password)
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
for row in results:
if not row:
return 0
else:
return row[0]
except:
s=sys.exc_info()
print "Error '%s' happened on line %d" % (s[1],s[2].tb_lineno)
def get_doc_cover(self,docID):
sql = "select docuname,cover,uploaddate,pdflocation from document left join userupload \
on userupload.docID = document.docID where document.docID = '%d'"%(docID)
rs = {}
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
for row in results:
rs['docuname'] = row[0]
rs['cover'] = row[1]
rs['time'] = row[2]
rs['pdflocation'] = row[3]
except:
s=sys.exc_info()
print "Error '%s' happened on line %d" % (s[1],s[2].tb_lineno)
return rs
def getdoc(self,docID):
sql = "select docuname,sourcelocation,pdflocation, \
docdescribe,downloadcount from document where docID = '%d'"%(docID)
rs = {}
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
for row in results:
rs['docuname'] = row[0]
rs['sourcelocation'] = row[1]
rs['pdflocation'] = row[2]
rs['docdescribe'] = row[3]
rs['downloadcount'] = row[4]
except:
s=sys.exc_info()
print "Error '%s' happened on line %d" % (s[1],s[2].tb_lineno)
return rs
if __name__ == "__main__":
t = MyDB()
s= t.checkuser('coco','541788')
print s
|
UTF-8
|
Python
| false | false | 2,014 |
14,663,018,399,115 |
edf3210901c2864551b44e7c0837652e595be846
|
c1f1ec2adf2c7a547743357323e4a142426a773c
|
/ex01_guess1.py
|
f542f30ca3b1f55ae6c6e99f7be0557500cc3936
|
[] |
no_license
|
yazzzz/homework
|
https://github.com/yazzzz/homework
|
044d9cc28f23724712e4a72b6faedf48a2d47b87
|
de674acf4694bcca8fd351ba67f82285837c9396
|
refs/heads/master
| 2020-07-05T06:27:32.301000 | 2014-02-19T04:47:40 | 2014-02-19T04:47:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
import random
import re
"""
input cases to handle:
q should quit
check spaces
check letters
check valid number from 1-100
check floats
"""
secret_num = random.randint(1,100)
print secret_num
keepPlaying = True
guess = -1
name = raw_input("what is your name? ")
print "hi %s, i'm thinking of a number between 1 and 100, try and guess it!" % name
while keepPlaying == True:
guess = raw_input("your guess? " )
# we need to check for valid input
# if we find a . in the number, split it to make an int
guess = guess.split(".")[0]
if re.findall("\.",guess):
print "FYI, converting your guess to ", guess
if guess.isdigit():
guess = int(guess)
if guess > 100 or guess < 1:
print "woah, that number is out of the 1-100 range!"
elif guess > secret_num:
print "too high! try again."
elif guess < secret_num:
print "too low! try again."
elif guess == secret_num:
print "WINNER WINNER CHICKEN DINNER!"
answer = raw_input("play again? ")
if answer.lower() in ["y", "yes"]:
keepPlaying = True
secret_num = random.randint(1,100)
print secret_num
elif answer.lower() in ["n", "no", "q","quit"]:
keepPlaying = False
else:
print "please enter a valid number!"
|
UTF-8
|
Python
| false | false | 2,014 |
16,484,084,515,179 |
97b83148dd6f96c4bf18b0c21b657a6fb7c86f05
|
be3b7b8bfa899a3617a79fc9a5effae4b9598be3
|
/electrode/models.py
|
c7b50fc630b7a896e011d3cb2051ebe4dc597b88
|
[] |
no_license
|
neuromusic/sturnus
|
https://github.com/neuromusic/sturnus
|
1032102ed248b5756461737af20f7a25244b1611
|
5b60c7c1eba814828834976c17a8c5b730254382
|
refs/heads/master
| 2021-01-18T15:22:54.885000 | 2014-10-09T23:06:34 | 2014-10-09T23:06:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django.db import models
# from broab.models import RecordingChannel
# class ElectrodeBatch(models.Model):
# """ a batch of electrodes """
# order_id = models.CharField(max_length=255)
# arrival = models.DateField(null=True)
# def __unicode__(self):
# return self.order_id
# class ElectrodeModel(models.Model):
# """ an electrode model
# consider this a platonic electrode. it only exists in the pages of the neuronexus catalog
# """
# manufacturer = models.CharField(max_length=255)
# model_number = models.CharField(max_length=255)
# def __unicode__(self):
# return self.model_number
# class RecordingSiteModel(models.Model):
# """ an electrode site model
# x & y & z coords are in microns when facing the electrode laying flat, from the lower left
# this contains data common to every one of these pads across multiple electrodes
# """
# electrode_model = models.ForeignKey(ElectrodeModel)
# connector_chan = models.PositiveIntegerField(null=True)
# size = models.FloatField(null=True)
# size_units = models.CharField(max_length=255)
# x_coord = models.IntegerField(null=True)
# y_coord = models.IntegerField(null=True)
# z_coord = models.IntegerField(null=True)
# def __unicode__(self):
# return "{a:%s,x:%s,y:%s}" % (self.size, self.x_coord, self.y_coord)
class Electrode(models.Model):
""" a single physical electrode
electrodes have real life analogs, with quirks and defects
"""
serial_number = models.CharField(max_length=255)
notes = models.TextField(blank=True)
status = models.CharField(max_length=255,blank=True)
uses = models.PositiveIntegerField(default=0)
# electrode_model = models.ForeignKey(ElectrodeModel)
# batch = models.ForeignKey(ElectrodeBatch,null=True)
def __unicode__(self):
return self.serial_number
# class RecordingSite(models.Model):
# """ a single physical electrode site
# one recording site on a real electrode
# """
# impedance = models.FloatField(null=True,blank=True)
# electrode = models.ForeignKey(Electrode)
# electrode_pad_model = models.ForeignKey(RecordingSiteModel)
# notes = models.TextField(blank=True)
# def __unicode__(self):
# return "%s:%s" % (self.electrode,self.electrode_pad_model.chan)
# class ExtendedRecordingChannel(RecordingChannel):
# ''' a recording channel '''
# chan = models.PositiveIntegerField()
# gain = models.FloatField(null=True,blank=True)
# filter_high = models.FloatField(null=True,blank=True)
# filter_low = models.FloatField(null=True,blank=True)
# site = models.ForeignKey(RecordingSite)
# def __unicode__(self):
# return "%s" % (self.chan)
|
UTF-8
|
Python
| false | false | 2,014 |
12,678,743,460,789 |
d13ed1e585c33d6c7434badb8e3e676c86ee5257
|
1b23af97877b52f3d25853920a4a0face5ebdc45
|
/cookbook/templatetags/cooktags.py
|
cd1819dc097a688ef036d66cabf161c777dc448d
|
[] |
no_license
|
hcsturix74/django_cuisine
|
https://github.com/hcsturix74/django_cuisine
|
3c19df3936c1608866d855cc51aced1dc8d74aee
|
2a7d8e0f3de56296adb7be5783e3b76ef6bd1196
|
refs/heads/master
| 2016-09-05T21:20:57.094000 | 2012-12-04T00:38:36 | 2012-12-04T00:38:36 | 6,828,909 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
__author__ = 'luca'
from cookbook.models import Recipe, Category
from django import template
import settings
from django.utils.safestring import mark_safe
register = template.Library()
@register.inclusion_tag('')
def show_recipes_by_category(category_id):
"""visualize example charts"""
rec_list = Recipe.objects.filter(category=category_id)
cat = Category.objects.get(id=category_id)
return {'recipe_list':rec_list ,
'category' : cat,
}
@register.inclusion_tag('tt_veg_friendly.html')
def show_vegetarian_recipes():
"""
This tag shows the list of vegetarian recipes
"""
rec_list = Recipe.veg_objects.vegetarian_friendly()
return {'recipe_list':rec_list ,
}
@register.inclusion_tag('tt_veg_friendly.html')
def show_vegan_recipes():
"""
This tag shows the list of vegan recipes
"""
rec_list = Recipe.veg_objects.vegan_friendly()
return {'recipe_list':rec_list ,
}
@register.simple_tag(name='get_forks_count')
def show_forks_count(value):
"""
This tag shows the number of fork for a given one
"""
return Recipe.objects.filter(fork_origin=value).count()
@register.simple_tag(name='get_recipes_count_per_user')
def show_recipes_count_per_user(value):
"""
This tags shows the number of recipes for a given user
"""
return Recipe.objects.filter(author=value).count()
|
UTF-8
|
Python
| false | false | 2,012 |
19,533,511,281,317 |
8c9758acd5d1de3f5c09dfa0b14e9989cb1bf690
|
f5b79e3e72c5caf031806776b23bf89672244483
|
/common_hulpje.py
|
588b134f4cb43bc00c1c1c92b1a81c048a9b81f1
|
[] |
no_license
|
gnur/hulpje
|
https://github.com/gnur/hulpje
|
4b3194bd6680413cd2b847412e57be2094a7e054
|
3e10f91b44327497967d54e384a8475f4a8ca175
|
refs/heads/master
| 2016-05-31T20:52:55.312000 | 2011-11-04T11:39:09 | 2011-11-04T11:39:09 | 1,664,785 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
#file is only used for config values that are the same across files
import re, os, sys
from urllib2 import Request, urlopen, URLError, HTTPError
try:
import feedparser
except ImportError:
print 'Feedparser was not found.'
print 'get it from http://www.feedparser.org'
sys.exit()
try:
import sqlite3 as sqlite
except ImportError:
print 'sqlite was not found'
print 'hulpje.py needs the sqlite3 module to function'
sys.exit()
reg_episode = re.compile('.*([0-9]+)[xE]([0-9]+).*', re.I)
reg_dmy = re.compile('.*2011\.?\s?(\d\d)\.?\s?(\d\d).*', re.I)
reg_torrent = re.compile('.*\/(.*\.torrent)', re.I)
database_location = '/home/gnur/hulpje/gnur_shows_database.db'
torrent_dir = '/home/gnur/'
debug = False
#takes a cursor object and returns a boolean when all tables that are needed are present
def checkDB(cursor):
cursor.execute("""SELECT count(*) from sqlite_master WHERE type='table' AND (
name = 'shows'
OR
name = 'urls'
OR
name = 'show_downloads')""")
return cursor.fetchone() == (3,)
#takes a cursor object and returns a list containing name / regular expression combos
def getShows(cursor):
cursor.execute ("SELECT show,regu FROM shows WHERE active=1")
return [row for row in cursor]
#takes a cursor object and returns a list of urls
def getFeeds(cursor):
cursor.execute ("SELECT id,url FROM urls ORDER BY colum ASC")
return [row for row in cursor]
|
UTF-8
|
Python
| false | false | 2,011 |
10,118,942,953,313 |
6d5df533928167a7643da83a6fedc405a3eaef3c
|
3447a1b3fa6206e06499b4b9f84f5067682a86e6
|
/lib/cortex/services/terminal/terminal.py
|
0207efe2cb21f83d5c1af55ef7d117ae59a2d070
|
[] |
no_license
|
mattvonrocketstein/cortex
|
https://github.com/mattvonrocketstein/cortex
|
5d7af5ca867cd4833cbb2d5dc349085a3a92e5b3
|
324b5c057a2570f84cde95ff4831e59b839858a1
|
refs/heads/master
| 2016-09-05T09:10:58.932000 | 2013-02-04T10:17:36 | 2013-02-04T10:17:36 | 1,063,869 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
""" cortex.services.terminal.terminal
Adapted from: http://code.activestate.com/recipes/410670-integrating-twisted-reactor-with-ipython/
TODO: this appears to be in twshell in ipython 0.10.1 .. extend that?
see also: http://ipython.scipy.org/moin/Cookbook/JobControl
import sys
from IPython.Debugger import Pdb
from IPython.Shell import IPShell
from IPython import ipapi
shell = IPShell(argv=[''])
def set_trace():
ip = ipapi.get()
def_colors = ip.options.colors
Pdb(def_colors).set_trace(sys._getframe().f_back)
"""
import threading
from IPython.Shell import MTInteractiveShell
from IPython.ipmaker import make_IPython
from cortex.core.data import IPY_ARGS
def hijack_reactor():
"""Modifies Twisted's reactor with a dummy so user code does
not block IPython. This function returns the original
'twisted.internet.reactor' that has been hijacked.
NOTE: Make sure you call this *AFTER* you've installed
the reactor of your choice.
"""
from twisted import internet
orig_reactor = internet.reactor
class DummyReactor(object):
def run(self):
pass
def __getattr__(self, name):
return getattr(orig_reactor, name)
def __setattr__(self, name, value):
return setattr(orig_reactor, name, value)
internet.reactor = DummyReactor()
return orig_reactor
class IPShellTwisted(threading.Thread):
"""Run a Twisted reactor while in an IPython session.
Python commands can be passed to the thread where they will be
executed. This is implemented by periodically checking for
passed code using a Twisted reactor callback.
"""
TIMEOUT = 0.03 # Millisecond interval between reactor runs.
def __init__(self, argv=None, user_ns=None, controller=None,debug=1,
shell_class=MTInteractiveShell):
self.controller=controller
from twisted.internet import reactor
self.reactor = hijack_reactor()
self.mainquit = self.reactor.stop
# Make sure IPython keeps going after reactor stop.
def reactorstop():
pass
self.reactor.stop = reactorstop
reactorrun_orig = self.reactor.run
self.quitting = False
def reactorrun():
while True and not self.quitting:
reactorrun_orig()
self.reactor.run = reactorrun
# either the universe stopped the terminal or the
# the terminal stopped the universe.. need to think
# more about this case. the shell can be exited with
# control-d, but you have to hit 'return' to make it final.
# suspect this is related to on_timer() / runcode(), but
# this code is really fragile and changing it can make the
# situation even worse.
on_kill = [ self.mainquit,
self.controller.universe.stop ]
self.IP = make_IPython(argv, user_ns=user_ns, debug=debug,
shell_class=shell_class, on_kill=on_kill)
threading.Thread.__init__(self)
def run(self):
self.IP.mainloop()
self.quitting = True
self.IP.kill()
def on_timer(self):
self.IP.runcode()
self.reactor.callLater(self.TIMEOUT, self.on_timer)
|
UTF-8
|
Python
| false | false | 2,013 |
4,114,578,678,417 |
53decce76d8be2b1d17406019fd6249e801438ea
|
c0431dfc3c025f9b3cb949a931895ef4bf354e26
|
/products/curtius/skins/curtius_scripts/isSiteAnonymous.py
|
a68556cc5185e47a173f6ffcd4725e5345f7a2ca
|
[
"GPL-2.0-or-later"
] |
non_permissive
|
IMIO/buildout.liege
|
https://github.com/IMIO/buildout.liege
|
d8b68b7d7e002e6c08c0f3533335cb501b26b3d9
|
09474772daaf1d11313b38cc9d85799b0508bb19
|
refs/heads/master
| 2018-01-07T15:26:04.010000 | 2014-07-22T11:48:38 | 2014-07-22T11:48:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
## Script (Python) "isSiteAnonymous"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##title=verifie si on est connecte au site ou pas
from Products.CMFCore.utils import getToolByName
mt = getToolByName(context, 'portal_membership')
if mt.isAnonymousUser():
return True
return False
|
UTF-8
|
Python
| false | false | 2,014 |
17,712,445,166,331 |
9d01ad67e35f051d25a33b29fbc39f427b8b7afd
|
62d719c3cb79361c8499087170eff2d6936cf4c7
|
/casir_messenger/models.py
|
dba89a3b600a4f79a375794c26efe0f3cef735e1
|
[] |
no_license
|
CASIRIUTGR1/casir-messenger
|
https://github.com/CASIRIUTGR1/casir-messenger
|
392f22dbc66f9d8b8e11d93f424c8f30c1fbee48
|
8559c4d87a57cb4617a065750504abf75bbddb85
|
refs/heads/master
| 2020-12-28T00:03:28.072000 | 2014-04-17T14:28:04 | 2014-04-17T14:28:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django.db import models
from friends.models import Friendship, FriendshipManager, FriendshipRequest
class message(models.Model):
Auteur = models.ForeignKey('Friend')
|
UTF-8
|
Python
| false | false | 2,014 |
19,138,374,287,014 |
a09e3d85e3d857bdbcc182fb49bb931f84704918
|
e9c5263cec921d49968154467d03fe1b389e3659
|
/neato_mudd/src/neato_mudd/srv/__init__.py
|
c00252c74f76c0ba1e8d664403c8e4697ce99f4a
|
[] |
no_license
|
cyrushx/hmc-robot-drivers
|
https://github.com/cyrushx/hmc-robot-drivers
|
85981ef4e4c0ab1e65975ff9cedc0026415aac0b
|
c5594c4323dff2c25082bc624c1b206f4bb40482
|
refs/heads/master
| 2021-01-16T22:32:36.853000 | 2013-07-25T17:59:54 | 2013-07-25T17:59:54 | 11,671,957 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from ._GetCharger import *
from ._GetButtons import *
from ._Tank import *
from ._Stop import *
from ._Start import *
from ._Exit import *
from ._PlaySound import *
from ._GetSensors import *
|
UTF-8
|
Python
| false | false | 2,013 |
6,064,493,844,178 |
f6b040e65f73d336b809b4e66c5f5ffe8d939790
|
477ea40c430e43412a96095606f5ea602d6ff0f0
|
/src/forms/mainwindow_ui.py
|
83428084bc6b1e1197a872b239872c4b83722987
|
[
"LGPL-3.0-only"
] |
non_permissive
|
DinoZAR/CentralAccessReader
|
https://github.com/DinoZAR/CentralAccessReader
|
83783ea8dbd99a3b8a99a8cf37dd76a9fe32f8ef
|
b2c0f317601252aee9e339de3cc328aec32f2db7
|
refs/heads/master
| 2020-03-19T02:21:20.503000 | 2014-01-09T16:56:24 | 2014-01-09T16:56:24 | 75,678,627 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'W:\Nifty Prose Articulator\workspace\nifty-prose-articulator\src\forms/mainwindow.ui'
#
# Created: Mon Oct 07 13:25:28 2013
# by: PyQt4 UI code generator 4.10
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(1032, 633)
font = QtGui.QFont()
font.setPointSize(12)
MainWindow.setFont(font)
MainWindow.setAcceptDrops(False)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/CAR_Logo.ico")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
MainWindow.setWindowIcon(icon)
MainWindow.setAutoFillBackground(False)
MainWindow.setIconSize(QtCore.QSize(24, 24))
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.horizontalLayout_4 = QtGui.QHBoxLayout(self.centralwidget)
self.horizontalLayout_4.setSpacing(0)
self.horizontalLayout_4.setMargin(0)
self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4"))
self.splitter = QtGui.QSplitter(self.centralwidget)
self.splitter.setOrientation(QtCore.Qt.Horizontal)
self.splitter.setHandleWidth(20)
self.splitter.setObjectName(_fromUtf8("splitter"))
self.layoutWidget = QtGui.QWidget(self.splitter)
self.layoutWidget.setObjectName(_fromUtf8("layoutWidget"))
self.verticalLayout_4 = QtGui.QVBoxLayout(self.layoutWidget)
self.verticalLayout_4.setSpacing(0)
self.verticalLayout_4.setMargin(0)
self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4"))
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setSpacing(0)
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem)
self.bookmarkZoomInButton = QtGui.QPushButton(self.layoutWidget)
self.bookmarkZoomInButton.setMaximumSize(QtCore.QSize(32, 32))
self.bookmarkZoomInButton.setText(_fromUtf8(""))
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/zoom_in_small.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.bookmarkZoomInButton.setIcon(icon1)
self.bookmarkZoomInButton.setIconSize(QtCore.QSize(32, 32))
self.bookmarkZoomInButton.setFlat(True)
self.bookmarkZoomInButton.setObjectName(_fromUtf8("bookmarkZoomInButton"))
self.horizontalLayout_2.addWidget(self.bookmarkZoomInButton)
self.bookmarkZoomOutButton = QtGui.QPushButton(self.layoutWidget)
self.bookmarkZoomOutButton.setMaximumSize(QtCore.QSize(32, 32))
self.bookmarkZoomOutButton.setText(_fromUtf8(""))
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/zoom_out_small.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.bookmarkZoomOutButton.setIcon(icon2)
self.bookmarkZoomOutButton.setIconSize(QtCore.QSize(32, 32))
self.bookmarkZoomOutButton.setFlat(True)
self.bookmarkZoomOutButton.setObjectName(_fromUtf8("bookmarkZoomOutButton"))
self.horizontalLayout_2.addWidget(self.bookmarkZoomOutButton)
spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem1)
self.verticalLayout_4.addLayout(self.horizontalLayout_2)
self.tabWidget = QtGui.QTabWidget(self.layoutWidget)
self.tabWidget.setObjectName(_fromUtf8("tabWidget"))
self.bookmarksTab = QtGui.QWidget()
self.bookmarksTab.setObjectName(_fromUtf8("bookmarksTab"))
self.verticalLayout = QtGui.QVBoxLayout(self.bookmarksTab)
self.verticalLayout.setSpacing(0)
self.verticalLayout.setMargin(0)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.bookmarksTreeView = QtGui.QTreeView(self.bookmarksTab)
font = QtGui.QFont()
font.setPointSize(14)
self.bookmarksTreeView.setFont(font)
self.bookmarksTreeView.setHeaderHidden(True)
self.bookmarksTreeView.setObjectName(_fromUtf8("bookmarksTreeView"))
self.verticalLayout.addWidget(self.bookmarksTreeView)
self.tabWidget.addTab(self.bookmarksTab, _fromUtf8(""))
self.pagesTab = QtGui.QWidget()
self.pagesTab.setObjectName(_fromUtf8("pagesTab"))
self.verticalLayout_2 = QtGui.QVBoxLayout(self.pagesTab)
self.verticalLayout_2.setSpacing(0)
self.verticalLayout_2.setMargin(0)
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.pagesTreeView = QtGui.QTreeView(self.pagesTab)
font = QtGui.QFont()
font.setPointSize(14)
self.pagesTreeView.setFont(font)
self.pagesTreeView.setHeaderHidden(True)
self.pagesTreeView.setObjectName(_fromUtf8("pagesTreeView"))
self.verticalLayout_2.addWidget(self.pagesTreeView)
self.tabWidget.addTab(self.pagesTab, _fromUtf8(""))
self.verticalLayout_4.addWidget(self.tabWidget)
self.layoutWidget1 = QtGui.QWidget(self.splitter)
self.layoutWidget1.setObjectName(_fromUtf8("layoutWidget1"))
self.webViewLayout = QtGui.QVBoxLayout(self.layoutWidget1)
self.webViewLayout.setSpacing(0)
self.webViewLayout.setMargin(0)
self.webViewLayout.setObjectName(_fromUtf8("webViewLayout"))
self.scrollArea = QtGui.QScrollArea(self.layoutWidget1)
self.scrollArea.setFrameShape(QtGui.QFrame.NoFrame)
self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.scrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName(_fromUtf8("scrollArea"))
self.scrollAreaWidgetContents = QtGui.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 931, 69))
self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents"))
self.horizontalLayout = QtGui.QHBoxLayout(self.scrollAreaWidgetContents)
self.horizontalLayout.setSpacing(0)
self.horizontalLayout.setMargin(0)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.playButton = QtGui.QPushButton(self.scrollAreaWidgetContents)
self.playButton.setMaximumSize(QtCore.QSize(60, 50))
self.playButton.setText(_fromUtf8(""))
icon3 = QtGui.QIcon()
icon3.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/play.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.playButton.setIcon(icon3)
self.playButton.setIconSize(QtCore.QSize(50, 50))
self.playButton.setFlat(True)
self.playButton.setObjectName(_fromUtf8("playButton"))
self.horizontalLayout.addWidget(self.playButton)
self.pauseButton = QtGui.QPushButton(self.scrollAreaWidgetContents)
self.pauseButton.setMaximumSize(QtCore.QSize(60, 50))
self.pauseButton.setText(_fromUtf8(""))
icon4 = QtGui.QIcon()
icon4.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/stop.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pauseButton.setIcon(icon4)
self.pauseButton.setIconSize(QtCore.QSize(50, 50))
self.pauseButton.setFlat(True)
self.pauseButton.setObjectName(_fromUtf8("pauseButton"))
self.horizontalLayout.addWidget(self.pauseButton)
self.speechSettingsButton = QtGui.QPushButton(self.scrollAreaWidgetContents)
self.speechSettingsButton.setMaximumSize(QtCore.QSize(60, 50))
self.speechSettingsButton.setText(_fromUtf8(""))
icon5 = QtGui.QIcon()
icon5.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/system_config_services.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.speechSettingsButton.setIcon(icon5)
self.speechSettingsButton.setIconSize(QtCore.QSize(50, 50))
self.speechSettingsButton.setFlat(True)
self.speechSettingsButton.setObjectName(_fromUtf8("speechSettingsButton"))
self.horizontalLayout.addWidget(self.speechSettingsButton)
self.colorSettingsButton = QtGui.QPushButton(self.scrollAreaWidgetContents)
self.colorSettingsButton.setMaximumSize(QtCore.QSize(60, 50))
self.colorSettingsButton.setText(_fromUtf8(""))
icon6 = QtGui.QIcon()
icon6.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/color_settings.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.colorSettingsButton.setIcon(icon6)
self.colorSettingsButton.setIconSize(QtCore.QSize(50, 50))
self.colorSettingsButton.setFlat(True)
self.colorSettingsButton.setObjectName(_fromUtf8("colorSettingsButton"))
self.horizontalLayout.addWidget(self.colorSettingsButton)
self.saveToMP3Button = QtGui.QPushButton(self.scrollAreaWidgetContents)
self.saveToMP3Button.setMaximumSize(QtCore.QSize(60, 50))
self.saveToMP3Button.setText(_fromUtf8(""))
icon7 = QtGui.QIcon()
icon7.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/text_speak.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.saveToMP3Button.setIcon(icon7)
self.saveToMP3Button.setIconSize(QtCore.QSize(50, 50))
self.saveToMP3Button.setFlat(True)
self.saveToMP3Button.setObjectName(_fromUtf8("saveToMP3Button"))
self.horizontalLayout.addWidget(self.saveToMP3Button)
self.zoomInButton = QtGui.QPushButton(self.scrollAreaWidgetContents)
self.zoomInButton.setMaximumSize(QtCore.QSize(60, 50))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Times New Roman"))
font.setItalic(False)
self.zoomInButton.setFont(font)
self.zoomInButton.setText(_fromUtf8(""))
icon8 = QtGui.QIcon()
icon8.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/zoom_in.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.zoomInButton.setIcon(icon8)
self.zoomInButton.setIconSize(QtCore.QSize(50, 50))
self.zoomInButton.setFlat(True)
self.zoomInButton.setObjectName(_fromUtf8("zoomInButton"))
self.horizontalLayout.addWidget(self.zoomInButton)
self.zoomOutButton = QtGui.QPushButton(self.scrollAreaWidgetContents)
self.zoomOutButton.setMaximumSize(QtCore.QSize(60, 50))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Times New Roman"))
font.setItalic(False)
self.zoomOutButton.setFont(font)
self.zoomOutButton.setText(_fromUtf8(""))
icon9 = QtGui.QIcon()
icon9.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/zoom_out.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.zoomOutButton.setIcon(icon9)
self.zoomOutButton.setIconSize(QtCore.QSize(50, 50))
self.zoomOutButton.setFlat(True)
self.zoomOutButton.setObjectName(_fromUtf8("zoomOutButton"))
self.horizontalLayout.addWidget(self.zoomOutButton)
self.zoomResetButton = QtGui.QPushButton(self.scrollAreaWidgetContents)
self.zoomResetButton.setMaximumSize(QtCore.QSize(60, 50))
self.zoomResetButton.setText(_fromUtf8(""))
icon10 = QtGui.QIcon()
icon10.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/zoom_fit_best.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.zoomResetButton.setIcon(icon10)
self.zoomResetButton.setIconSize(QtCore.QSize(50, 50))
self.zoomResetButton.setFlat(True)
self.zoomResetButton.setObjectName(_fromUtf8("zoomResetButton"))
self.horizontalLayout.addWidget(self.zoomResetButton)
self.sliderGridLayout = QtGui.QGridLayout()
self.sliderGridLayout.setContentsMargins(6, -1, 6, -1)
self.sliderGridLayout.setHorizontalSpacing(12)
self.sliderGridLayout.setObjectName(_fromUtf8("sliderGridLayout"))
self.volumeLabel = QtGui.QLabel(self.scrollAreaWidgetContents)
self.volumeLabel.setObjectName(_fromUtf8("volumeLabel"))
self.sliderGridLayout.addWidget(self.volumeLabel, 1, 0, 1, 1)
self.rateLabel = QtGui.QLabel(self.scrollAreaWidgetContents)
self.rateLabel.setObjectName(_fromUtf8("rateLabel"))
self.sliderGridLayout.addWidget(self.rateLabel, 0, 0, 1, 1)
self.rateSlider = QtGui.QSlider(self.scrollAreaWidgetContents)
self.rateSlider.setMinimumSize(QtCore.QSize(201, 0))
self.rateSlider.setMinimum(0)
self.rateSlider.setMaximum(100)
self.rateSlider.setProperty("value", 50)
self.rateSlider.setOrientation(QtCore.Qt.Horizontal)
self.rateSlider.setTickPosition(QtGui.QSlider.TicksAbove)
self.rateSlider.setTickInterval(10)
self.rateSlider.setObjectName(_fromUtf8("rateSlider"))
self.sliderGridLayout.addWidget(self.rateSlider, 0, 1, 1, 1)
self.volumeSlider = QtGui.QSlider(self.scrollAreaWidgetContents)
self.volumeSlider.setMinimumSize(QtCore.QSize(201, 0))
self.volumeSlider.setMaximum(100)
self.volumeSlider.setProperty("value", 100)
self.volumeSlider.setOrientation(QtCore.Qt.Horizontal)
self.volumeSlider.setTickPosition(QtGui.QSlider.TicksAbove)
self.volumeSlider.setTickInterval(10)
self.volumeSlider.setObjectName(_fromUtf8("volumeSlider"))
self.sliderGridLayout.addWidget(self.volumeSlider, 1, 1, 1, 1)
self.horizontalLayout.addLayout(self.sliderGridLayout)
spacerItem2 = QtGui.QSpacerItem(5, 5, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem2)
self.getUpdateButton = QtGui.QPushButton(self.scrollAreaWidgetContents)
icon11 = QtGui.QIcon()
icon11.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/update_down_arrow.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.getUpdateButton.setIcon(icon11)
self.getUpdateButton.setIconSize(QtCore.QSize(32, 32))
self.getUpdateButton.setCheckable(False)
self.getUpdateButton.setFlat(True)
self.getUpdateButton.setObjectName(_fromUtf8("getUpdateButton"))
self.horizontalLayout.addWidget(self.getUpdateButton)
self.horizontalLayout.setStretch(9, 1)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.webViewLayout.addWidget(self.scrollArea)
self.horizontalLayout_3 = QtGui.QHBoxLayout()
self.horizontalLayout_3.setSpacing(0)
self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
self.searchLabel = QtGui.QLabel(self.layoutWidget1)
self.searchLabel.setObjectName(_fromUtf8("searchLabel"))
self.horizontalLayout_3.addWidget(self.searchLabel)
self.searchUpButton = QtGui.QPushButton(self.layoutWidget1)
self.searchUpButton.setMaximumSize(QtCore.QSize(45, 32))
self.searchUpButton.setText(_fromUtf8(""))
icon12 = QtGui.QIcon()
icon12.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/up.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.searchUpButton.setIcon(icon12)
self.searchUpButton.setIconSize(QtCore.QSize(32, 32))
self.searchUpButton.setFlat(True)
self.searchUpButton.setObjectName(_fromUtf8("searchUpButton"))
self.horizontalLayout_3.addWidget(self.searchUpButton)
self.searchDownButton = QtGui.QPushButton(self.layoutWidget1)
self.searchDownButton.setMaximumSize(QtCore.QSize(45, 32))
self.searchDownButton.setText(_fromUtf8(""))
icon13 = QtGui.QIcon()
icon13.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/down.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.searchDownButton.setIcon(icon13)
self.searchDownButton.setIconSize(QtCore.QSize(32, 32))
self.searchDownButton.setFlat(True)
self.searchDownButton.setObjectName(_fromUtf8("searchDownButton"))
self.horizontalLayout_3.addWidget(self.searchDownButton)
self.searchTextBox = QtGui.QLineEdit(self.layoutWidget1)
self.searchTextBox.setObjectName(_fromUtf8("searchTextBox"))
self.horizontalLayout_3.addWidget(self.searchTextBox)
self.searchSettingsButton = QtGui.QPushButton(self.layoutWidget1)
self.searchSettingsButton.setMaximumSize(QtCore.QSize(45, 32))
self.searchSettingsButton.setText(_fromUtf8(""))
icon14 = QtGui.QIcon()
icon14.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/gear.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.searchSettingsButton.setIcon(icon14)
self.searchSettingsButton.setIconSize(QtCore.QSize(32, 32))
self.searchSettingsButton.setFlat(True)
self.searchSettingsButton.setObjectName(_fromUtf8("searchSettingsButton"))
self.horizontalLayout_3.addWidget(self.searchSettingsButton)
self.closeSearchButton = QtGui.QPushButton(self.layoutWidget1)
self.closeSearchButton.setMaximumSize(QtCore.QSize(45, 32))
self.closeSearchButton.setText(_fromUtf8(""))
icon15 = QtGui.QIcon()
icon15.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/dialog_close.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.closeSearchButton.setIcon(icon15)
self.closeSearchButton.setIconSize(QtCore.QSize(32, 32))
self.closeSearchButton.setFlat(True)
self.closeSearchButton.setObjectName(_fromUtf8("closeSearchButton"))
self.horizontalLayout_3.addWidget(self.closeSearchButton)
self.webViewLayout.addLayout(self.horizontalLayout_3)
self.webView = QtWebKit.QWebView(self.layoutWidget1)
self.webView.setSizeIncrement(QtCore.QSize(1, 1))
self.webView.setUrl(QtCore.QUrl(_fromUtf8("about:blank")))
self.webView.setObjectName(_fromUtf8("webView"))
self.webViewLayout.addWidget(self.webView)
self.webViewLayout.setStretch(2, 1)
self.horizontalLayout_4.addWidget(self.splitter)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1032, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
self.menuFile = QtGui.QMenu(self.menubar)
self.menuFile.setObjectName(_fromUtf8("menuFile"))
self.menuMathML = QtGui.QMenu(self.menubar)
self.menuMathML.setObjectName(_fromUtf8("menuMathML"))
self.menuHelp = QtGui.QMenu(self.menubar)
self.menuHelp.setObjectName(_fromUtf8("menuHelp"))
self.menuFunctions = QtGui.QMenu(self.menubar)
self.menuFunctions.setObjectName(_fromUtf8("menuFunctions"))
self.menuSettings = QtGui.QMenu(self.menubar)
self.menuSettings.setObjectName(_fromUtf8("menuSettings"))
self.menuMP3 = QtGui.QMenu(self.menubar)
self.menuMP3.setObjectName(_fromUtf8("menuMP3"))
MainWindow.setMenuBar(self.menubar)
self.actionOpen_Docx = QtGui.QAction(MainWindow)
self.actionOpen_Docx.setObjectName(_fromUtf8("actionOpen_Docx"))
self.actionOpen_Pattern_Editor = QtGui.QAction(MainWindow)
self.actionOpen_Pattern_Editor.setObjectName(_fromUtf8("actionOpen_Pattern_Editor"))
self.actionShow_All_MathML = QtGui.QAction(MainWindow)
self.actionShow_All_MathML.setObjectName(_fromUtf8("actionShow_All_MathML"))
self.actionQuit = QtGui.QAction(MainWindow)
icon16 = QtGui.QIcon()
icon16.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/application_exit.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionQuit.setIcon(icon16)
self.actionQuit.setObjectName(_fromUtf8("actionQuit"))
self.actionTutorial = QtGui.QAction(MainWindow)
icon17 = QtGui.QIcon()
icon17.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/help_contents.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionTutorial.setIcon(icon17)
self.actionTutorial.setObjectName(_fromUtf8("actionTutorial"))
self.actionAbout = QtGui.QAction(MainWindow)
icon18 = QtGui.QIcon()
icon18.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/help_about.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionAbout.setIcon(icon18)
self.actionAbout.setObjectName(_fromUtf8("actionAbout"))
self.actionReport_a_Bug = QtGui.QAction(MainWindow)
icon19 = QtGui.QIcon()
icon19.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/report_bug.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionReport_a_Bug.setIcon(icon19)
self.actionReport_a_Bug.setObjectName(_fromUtf8("actionReport_a_Bug"))
self.actionTake_A_Survey = QtGui.QAction(MainWindow)
icon20 = QtGui.QIcon()
icon20.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/spread.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionTake_A_Survey.setIcon(icon20)
self.actionTake_A_Survey.setObjectName(_fromUtf8("actionTake_A_Survey"))
self.actionSearch = QtGui.QAction(MainWindow)
self.actionSearch.setObjectName(_fromUtf8("actionSearch"))
self.actionPlay = QtGui.QAction(MainWindow)
self.actionPlay.setIcon(icon3)
self.actionPlay.setObjectName(_fromUtf8("actionPlay"))
self.actionStop = QtGui.QAction(MainWindow)
self.actionStop.setIcon(icon4)
self.actionStop.setObjectName(_fromUtf8("actionStop"))
self.actionSave_Selection_to_MP3 = QtGui.QAction(MainWindow)
self.actionSave_Selection_to_MP3.setIcon(icon7)
self.actionSave_Selection_to_MP3.setObjectName(_fromUtf8("actionSave_Selection_to_MP3"))
self.actionSave_All_to_MP3 = QtGui.QAction(MainWindow)
self.actionSave_All_to_MP3.setIcon(icon7)
self.actionSave_All_to_MP3.setObjectName(_fromUtf8("actionSave_All_to_MP3"))
self.actionHighlights_Colors_and_Fonts = QtGui.QAction(MainWindow)
self.actionHighlights_Colors_and_Fonts.setIcon(icon6)
self.actionHighlights_Colors_and_Fonts.setObjectName(_fromUtf8("actionHighlights_Colors_and_Fonts"))
self.actionSpeech = QtGui.QAction(MainWindow)
self.actionSpeech.setIcon(icon5)
self.actionSpeech.setObjectName(_fromUtf8("actionSpeech"))
self.actionZoom_In = QtGui.QAction(MainWindow)
self.actionZoom_In.setIcon(icon1)
self.actionZoom_In.setObjectName(_fromUtf8("actionZoom_In"))
self.actionZoom_Out = QtGui.QAction(MainWindow)
self.actionZoom_Out.setIcon(icon2)
self.actionZoom_Out.setObjectName(_fromUtf8("actionZoom_Out"))
self.actionReset_Zoom = QtGui.QAction(MainWindow)
icon21 = QtGui.QIcon()
icon21.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/icons/zoom_fit_best_small.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionReset_Zoom.setIcon(icon21)
self.actionReset_Zoom.setObjectName(_fromUtf8("actionReset_Zoom"))
self.actionIncrease_Volume = QtGui.QAction(MainWindow)
self.actionIncrease_Volume.setObjectName(_fromUtf8("actionIncrease_Volume"))
self.actionDecrease_Volume = QtGui.QAction(MainWindow)
self.actionDecrease_Volume.setObjectName(_fromUtf8("actionDecrease_Volume"))
self.actionIncrease_Rate = QtGui.QAction(MainWindow)
self.actionIncrease_Rate.setObjectName(_fromUtf8("actionIncrease_Rate"))
self.actionDecrease_Rate = QtGui.QAction(MainWindow)
self.actionDecrease_Rate.setObjectName(_fromUtf8("actionDecrease_Rate"))
self.actionEntire_Document = QtGui.QAction(MainWindow)
self.actionEntire_Document.setIcon(icon7)
self.actionEntire_Document.setObjectName(_fromUtf8("actionEntire_Document"))
self.actionCurrent_Selection = QtGui.QAction(MainWindow)
self.actionCurrent_Selection.setIcon(icon7)
self.actionCurrent_Selection.setObjectName(_fromUtf8("actionCurrent_Selection"))
self.actionBy_Page = QtGui.QAction(MainWindow)
self.actionBy_Page.setIcon(icon7)
self.actionBy_Page.setObjectName(_fromUtf8("actionBy_Page"))
self.actionExport_to_HTML = QtGui.QAction(MainWindow)
self.actionExport_to_HTML.setObjectName(_fromUtf8("actionExport_to_HTML"))
self.menuFile.addAction(self.actionOpen_Docx)
self.menuFile.addSeparator()
self.menuFile.addAction(self.actionSave_All_to_MP3)
self.menuFile.addAction(self.actionSave_Selection_to_MP3)
self.menuFile.addSeparator()
self.menuFile.addAction(self.actionExport_to_HTML)
self.menuFile.addSeparator()
self.menuFile.addAction(self.actionQuit)
self.menuMathML.addAction(self.actionOpen_Pattern_Editor)
self.menuMathML.addAction(self.actionShow_All_MathML)
self.menuHelp.addAction(self.actionTutorial)
self.menuHelp.addAction(self.actionAbout)
self.menuHelp.addSeparator()
self.menuHelp.addAction(self.actionReport_a_Bug)
self.menuHelp.addAction(self.actionTake_A_Survey)
self.menuFunctions.addAction(self.actionPlay)
self.menuFunctions.addAction(self.actionStop)
self.menuFunctions.addSeparator()
self.menuFunctions.addAction(self.actionZoom_In)
self.menuFunctions.addAction(self.actionZoom_Out)
self.menuFunctions.addAction(self.actionReset_Zoom)
self.menuFunctions.addSeparator()
self.menuFunctions.addAction(self.actionIncrease_Volume)
self.menuFunctions.addAction(self.actionDecrease_Volume)
self.menuFunctions.addAction(self.actionIncrease_Rate)
self.menuFunctions.addAction(self.actionDecrease_Rate)
self.menuFunctions.addSeparator()
self.menuFunctions.addAction(self.actionSearch)
self.menuSettings.addAction(self.actionSpeech)
self.menuSettings.addAction(self.actionHighlights_Colors_and_Fonts)
self.menuMP3.addAction(self.actionEntire_Document)
self.menuMP3.addAction(self.actionCurrent_Selection)
self.menuMP3.addSeparator()
self.menuMP3.addAction(self.actionBy_Page)
self.menubar.addAction(self.menuFile.menuAction())
self.menubar.addAction(self.menuFunctions.menuAction())
self.menubar.addAction(self.menuMP3.menuAction())
self.menubar.addAction(self.menuSettings.menuAction())
self.menubar.addAction(self.menuMathML.menuAction())
self.menubar.addAction(self.menuHelp.menuAction())
self.retranslateUi(MainWindow)
self.tabWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "Central Access Reader", None))
self.bookmarkZoomInButton.setToolTip(_translate("MainWindow", "Zoom In", None))
self.bookmarkZoomOutButton.setToolTip(_translate("MainWindow", "Zoom Out", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.bookmarksTab), _translate("MainWindow", "Headings", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.pagesTab), _translate("MainWindow", "Pages", None))
self.playButton.setToolTip(_translate("MainWindow", "Read", None))
self.pauseButton.setToolTip(_translate("MainWindow", "Stop", None))
self.speechSettingsButton.setToolTip(_translate("MainWindow", "Speech Settings", None))
self.colorSettingsButton.setToolTip(_translate("MainWindow", "Highlighting, Colors, and Fonts Settings", None))
self.saveToMP3Button.setToolTip(_translate("MainWindow", "Save All To MP3", None))
self.zoomInButton.setToolTip(_translate("MainWindow", "Zoom In", None))
self.zoomOutButton.setToolTip(_translate("MainWindow", "Zoom Out", None))
self.zoomResetButton.setToolTip(_translate("MainWindow", "Reset Zoom", None))
self.volumeLabel.setText(_translate("MainWindow", "Volume:", None))
self.rateLabel.setText(_translate("MainWindow", "Rate:", None))
self.rateSlider.setToolTip(_translate("MainWindow", "Rate", None))
self.volumeSlider.setToolTip(_translate("MainWindow", "Volume", None))
self.getUpdateButton.setToolTip(_translate("MainWindow", "Update Available!", None))
self.getUpdateButton.setText(_translate("MainWindow", "Update Available!", None))
self.searchLabel.setText(_translate("MainWindow", "Search", None))
self.searchUpButton.setToolTip(_translate("MainWindow", "Previous Occurrence", None))
self.searchDownButton.setToolTip(_translate("MainWindow", "Next Occurrence", None))
self.searchSettingsButton.setToolTip(_translate("MainWindow", "Search Settings", None))
self.closeSearchButton.setToolTip(_translate("MainWindow", "Close Search", None))
self.menuFile.setTitle(_translate("MainWindow", "&File", None))
self.menuMathML.setTitle(_translate("MainWindow", "&MathML", None))
self.menuHelp.setTitle(_translate("MainWindow", "&Help", None))
self.menuFunctions.setTitle(_translate("MainWindow", "F&unctions", None))
self.menuSettings.setTitle(_translate("MainWindow", "&Settings", None))
self.menuMP3.setTitle(_translate("MainWindow", "MP3", None))
self.actionOpen_Docx.setText(_translate("MainWindow", "&Open Word Document", None))
self.actionOpen_Docx.setShortcut(_translate("MainWindow", "Ctrl+O", None))
self.actionOpen_Pattern_Editor.setText(_translate("MainWindow", "&Open Pattern Editor...", None))
self.actionShow_All_MathML.setText(_translate("MainWindow", "&Show All MathML...", None))
self.actionQuit.setText(_translate("MainWindow", "&Quit", None))
self.actionQuit.setShortcut(_translate("MainWindow", "Ctrl+Q", None))
self.actionTutorial.setText(_translate("MainWindow", "&Tutorial", None))
self.actionTutorial.setShortcut(_translate("MainWindow", "Ctrl+H", None))
self.actionAbout.setText(_translate("MainWindow", "&About", None))
self.actionAbout.setShortcut(_translate("MainWindow", "Ctrl+Shift+H", None))
self.actionReport_a_Bug.setText(_translate("MainWindow", "Report a &Bug", None))
self.actionTake_A_Survey.setText(_translate("MainWindow", "Take A &Survey", None))
self.actionSearch.setText(_translate("MainWindow", "S&earch", None))
self.actionSearch.setToolTip(_translate("MainWindow", "Toggles the search bar on and off.", None))
self.actionSearch.setShortcut(_translate("MainWindow", "Ctrl+F", None))
self.actionPlay.setText(_translate("MainWindow", "&Read", None))
self.actionPlay.setShortcut(_translate("MainWindow", "Ctrl+R", None))
self.actionStop.setText(_translate("MainWindow", "&Stop", None))
self.actionStop.setShortcut(_translate("MainWindow", "Ctrl+S", None))
self.actionSave_Selection_to_MP3.setText(_translate("MainWindow", "Save &Selection to MP3", None))
self.actionSave_Selection_to_MP3.setShortcut(_translate("MainWindow", "Ctrl+Shift+M", None))
self.actionSave_All_to_MP3.setText(_translate("MainWindow", "Save &All to MP3", None))
self.actionSave_All_to_MP3.setShortcut(_translate("MainWindow", "Ctrl+M", None))
self.actionHighlights_Colors_and_Fonts.setText(_translate("MainWindow", "&Highlights, Colors, and Fonts", None))
self.actionHighlights_Colors_and_Fonts.setShortcut(_translate("MainWindow", "F2", None))
self.actionSpeech.setText(_translate("MainWindow", "&Speech", None))
self.actionSpeech.setShortcut(_translate("MainWindow", "F1", None))
self.actionZoom_In.setText(_translate("MainWindow", "Zoom In", None))
self.actionZoom_In.setShortcut(_translate("MainWindow", "Ctrl+=", None))
self.actionZoom_Out.setText(_translate("MainWindow", "Zoom Out", None))
self.actionZoom_Out.setShortcut(_translate("MainWindow", "Ctrl+-", None))
self.actionReset_Zoom.setText(_translate("MainWindow", "Reset Zoom", None))
self.actionReset_Zoom.setShortcut(_translate("MainWindow", "Ctrl+Backspace", None))
self.actionIncrease_Volume.setText(_translate("MainWindow", "Increase Volume", None))
self.actionIncrease_Volume.setToolTip(_translate("MainWindow", "Increase Volume", None))
self.actionIncrease_Volume.setShortcut(_translate("MainWindow", "Ctrl+Up", None))
self.actionDecrease_Volume.setText(_translate("MainWindow", "Decrease Volume", None))
self.actionDecrease_Volume.setToolTip(_translate("MainWindow", "Decrease Volume", None))
self.actionDecrease_Volume.setShortcut(_translate("MainWindow", "Ctrl+Down", None))
self.actionIncrease_Rate.setText(_translate("MainWindow", "Increase Rate", None))
self.actionIncrease_Rate.setToolTip(_translate("MainWindow", "Increase Rate", None))
self.actionIncrease_Rate.setShortcut(_translate("MainWindow", "Ctrl+Right", None))
self.actionDecrease_Rate.setText(_translate("MainWindow", "Decrease Rate", None))
self.actionDecrease_Rate.setToolTip(_translate("MainWindow", "Decrease Rate", None))
self.actionDecrease_Rate.setShortcut(_translate("MainWindow", "Ctrl+Left", None))
self.actionEntire_Document.setText(_translate("MainWindow", "Entire Document", None))
self.actionCurrent_Selection.setText(_translate("MainWindow", "Current Selection", None))
self.actionBy_Page.setText(_translate("MainWindow", "By Page", None))
self.actionExport_to_HTML.setText(_translate("MainWindow", "&Export to HTML", None))
from PyQt4 import QtWebKit
import resource_rc
|
UTF-8
|
Python
| false | false | 2,014 |
16,157,667,007,666 |
53283ca9847ba2e602ef88f5187bd1985d8d911f
|
316a07bd7ab47d447606d341c5d221d8318f65b9
|
/horizon/horizon/dashboards/nova/loadbalancers/pools/forms.py
|
a8305b246e86338194d16382723077b2acb702a6
|
[] |
no_license
|
kumarcv/openstack-nf
|
https://github.com/kumarcv/openstack-nf
|
791d16a4844df4666fb2b82a548add98f4832628
|
ad2d8c5d49f510292b1fe373c7c10e53be52ba23
|
refs/heads/master
| 2020-05-20T03:10:54.495000 | 2013-06-16T23:44:11 | 2013-06-16T23:44:11 | 7,497,218 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Freescale Semiconductor, Inc.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import api
from horizon import exceptions
from horizon import forms
from horizon import messages
LOG = logging.getLogger(__name__)
class BasePoolForm(forms.SelfHandlingForm):
def __init__(self, request, *args, **kwargs):
super(BasePoolForm, self).__init__(request, *args, **kwargs)
# Populate subnet choices
subnet_choices = [('', _("Select a Subnet"))]
tenant_id = self.request.user.tenant_id
for subnet in api.quantum.subnet_list(request, tenant_id=tenant_id):
subnet_choices.append((subnet.id, subnet.cidr))
self.fields['subnet_id'].choices = subnet_choices
class UpdatePool(BasePoolForm):
PROTOCOL_CHOICES = (
("", _("Select Protocol")),
("HTTP", _("HTTP")),
("HTTPS", _("HTTPS")),
("TCP", _("TCP")),
)
ALGORITHM_CHOICES = (
("", _("Select Algorithm")),
("ROUNDROBIN", _("Round Robin")),
("LEASTCONN", _("Least Connections")),
("STATIC-RR", _("Static Round Robin")),
("SOURCE", _("Source")),
)
pool_id = forms.CharField(label=_("ID"),
widget=forms.TextInput(
attrs={'readonly': 'readonly'}))
name = forms.CharField(label=_("Pool Name"),
required=True,
initial="",
help_text=_("Name of the Pool"))
description = forms.CharField(label=_("Description"),
required=False,
initial="",
help_text=_("Description"))
subnet_id = forms.ChoiceField(label=_("Subnet"), required=True)
protocol = forms.ChoiceField(label=_("Protocol"),
required=True,
choices=PROTOCOL_CHOICES)
lb_method = forms.ChoiceField(label=_("LB Method"),
required=True,
choices=ALGORITHM_CHOICES)
tenant_id = forms.CharField(widget=forms.HiddenInput)
failure_url = 'horizon:nova:loadbalancers:pools'
def handle(self, request, data):
try:
LOG.debug('params = %s' % data)
#params = {'name': data['name']}
#params['gateway_ip'] = data['gateway_ip']
pool = api.quantum.pool_modify(request, data['pool_id'],
name=data['name'],
description=data['description'],
subnet_id=data['subnet_id'],
protocol=data['protocol'],
lb_method=data['lb_method'])
msg = _('Pool %s was successfully updated.') % data['pool_id']
LOG.debug(msg)
messages.success(request, msg)
return pool
except Exception:
msg = _('Failed to update Pool %s') % data['name']
LOG.info(msg)
redirect = reverse(self.failure_url)
exceptions.handle(request, msg, redirect=redirect)
|
UTF-8
|
Python
| false | false | 2,013 |
1,829,656,083,926 |
827cd722eb8888acab1d4bf33fd6611792ec8b5b
|
9e4717822c7798b8bdba587a15b78c071d78299d
|
/pharo
|
cffe76a66c6d7a58bf14e56d3e5cb8e0c313dac1
|
[] |
no_license
|
ngarbezza/pharo-launcher-linux
|
https://github.com/ngarbezza/pharo-launcher-linux
|
04c965829fb57ee050d3a9df1838769f728e92d7
|
48129f10cd82b773c483b5d94e07797fa7e78f1d
|
refs/heads/master
| 2020-04-02T16:26:08.724000 | 2013-04-02T13:20:16 | 2013-04-02T13:20:16 | 3,076,089 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python3
import os, sys
from configparser import RawConfigParser
# ----------------------------- CONSTANTS ----------------------------------- #
CONFIG_FILE = os.path.expanduser('~/.pharo')
IMAGES_SECTION = 'images'
VMS_SECTION = 'vms'
IMG_CMD = 'image'
VM_CMD = 'vm'
# ---------------------------- add COMMAND ---------------------------------- #
def add():
try:
arg = sys.argv[2]
if arg == IMG_CMD: add_entry(IMAGES_SECTION, sys.argv[3], sys.argv[4])
elif arg == VM_CMD: add_entry(VMS_SECTION, sys.argv[3], sys.argv[4])
else: print("Wrong argument. Enter '%s' or '%s'" % (IMG_CMD, VM_CMD))
except IndexError:
print_missing_argument_msg('add')
def add_entry(section, name, path):
check_config_file()
check_sections()
config = create_config()
if config.has_option(section, name):
print("Name %s is already associated with the path '%s'." % \
(name, config.get(section, name)))
choice = input("Do you want to replace it (y)/n: ")
if choice in ['n', 'N', 'No', 'no', 'NO']: exit()
if not os.path.exists(path) or not os.path.isfile(path):
print("The path '%s' does not exist or it isn't a file" % path)
exit()
config.set(section, name, '"%s"' % os.path.abspath(path))
write_config(config)
print("%s added pointing to %s" % (name, path))
# -------------------------- launch COMMAND --------------------------------- #
def launch():
try:
vm = sys.argv[2]
img = sys.argv[3]
args = ' '.join(sys.argv[4:])
config = create_config()
if config.has_option(VMS_SECTION, vm):
vm = config.get(VMS_SECTION, vm)
if config.has_option(IMAGES_SECTION, img):
img = config.get(IMAGES_SECTION, img)
command = "%s %s %s > /dev/null 2>&1 &" % (vm, img, args)
print("Executing '%s'..." % command)
os.system(command)
except IndexError:
print_missing_argument_msg('launch')
# -------------------------- remove COMMAND --------------------------------- #
def remove():
try:
arg = sys.argv[2]
if arg == IMG_CMD: remove_entry(IMAGES_SECTION, sys.argv[3])
elif arg == VM_CMD: remove_entry(VMS_SECTION, sys.argv[3])
else: print("Wrong argument. Enter '%s' or '%s'" % (IMG_CMD, VM_CMD))
except IndexError:
print_missing_argument_msg('remove')
def remove_entry(section, name):
config = create_config()
if config.has_option(section, name):
config.remove_option(section, name)
print("Name %s removed successfully" % name)
else:
print("The name %s does not exist." % name)
write_config(config)
# --------------------------- list COMMAND ---------------------------------- #
def list(): os.system('cat '+ CONFIG_FILE)
# ------------------------------- HELP -------------------------------------- #
def show_help():
print("""Pharo launcher for GNU/Linux.
Usage: pharo <command> <arguments>
Commands:
launch
Launch an image with a vm (path or name).
Examples:
pharo launch cog moose
pharo launch /path/to/your/vm seaside
pharo launch cog /path/to/your.image
add
Register an image or vm with a name.
Examples:
pharo add image seaside /home/user/images/seaside.image
pharo add vm cog /home/user/vms/pharo
remove
Remove a vm or image association. This doesn't delete the
image or vm, only the name associated to it.
Examples:
pharo remove image seaside
list
List all the images and vms registered.
help
Show this screen.
""")
exit()
# ------------------------- OTHER FUNCTIONS --------------------------------- #
def create_config():
config = RawConfigParser()
config.read(CONFIG_FILE)
return config
def write_config(config):
with open(CONFIG_FILE, 'w') as f: config.write(f)
def print_missing_argument_msg(cmd):
print("Missing argument to " + cmd + " command. Type 'pharo help' " \
+ "to see some examples of this command.")
def check_sections():
config = create_config()
for section in [VMS_SECTION, IMAGES_SECTION]:
if not config.has_section(section): config.add_section(section)
write_config(config)
def check_config_file():
if not os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, 'w') as f: pass
# ------------------------------- MAIN -------------------------------------- #
if __name__ == '__main__':
try: cmd = sys.argv[1]
except IndexError: show_help()
if cmd == 'launch': launch()
elif cmd == 'add': add()
elif cmd == 'remove': remove()
elif cmd == 'list': list()
elif cmd == 'help': show_help()
else: print("Unknown command. Type 'pharo help'" \
+ " to get the list of available commands")
exit()
|
UTF-8
|
Python
| false | false | 2,013 |
9,491,877,725,082 |
9413369d1052d4d5125f1267683fb37f87c4e197
|
274f8641e895cd0dbb715c479def11f01e246cd9
|
/clean_scrape.py
|
103a8d51a64e2e4e242fdc569cc72954ef7519f1
|
[] |
no_license
|
evisactor/RoboBuffett
|
https://github.com/evisactor/RoboBuffett
|
41a826d1414447b730c61aa026562020db9e54b6
|
0d415eb8666466b2ed44ed2048cc69c46120d61f
|
refs/heads/master
| 2021-01-18T05:54:25.547000 | 2012-10-04T18:11:40 | 2012-10-04T18:11:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from ftplib import FTP
from tempfile import NamedTemporaryFile
from itertools import *
import sys
import os
import zipfile
import subprocess
hosts = ['altair.cs.uchicago.edu', 'ursa.cs.uchicago.edu',
'ankaa.cs.uchicago.edu', 'antares.cs.uchicago.edu',
'arcturus.cs.uchicago.edu', 'as.cs.uchicago.edu',
'avior.cs.uchicago.edu', 'be.cs.uchicago.edu',
'betelgeuse.cs.uchicago.edu', 'canopus.cs.uchicago.edu',
'capella.cs.uchicago.edu', 'da.cs.uchicago.edu',
'deneb.cs.uchicago.edu', 'dubhe.cs.uchicago.edu',
'gacrux.cs.uchicago.edu', 'hadar.cs.uchicago.edu',
'ki.cs.uchicago.edu', 'mimosa.cs.uchicago.edu',
'naos.cs.uchicago.edu', 'polaris.cs.uchicago.edu',
'procyon.cs.uchicago.edu', 'rastaban.cs.uchicago.edu',
're.cs.uchicago.edu', 'rigel.cs.uchicago.edu',
'saiph.cs.uchicago.edu', 'sh.cs.uchicago.edu',
'sirius.cs.uchicago.edu', 'ul.cs.uchicago.edu']
def connect_to_SEC(max_attempts=50):
""" Connect to the SEC ftp server, timing out after max_attempts
attempts."""
for i in xrange(max_attempts):
try:
return FTP('ftp.sec.gov')
except EOFError:
pass
print "Maximum number of attempts exceeded. Try again later."
def download_file(server_path, local_path):
"""Download a file at server_path on the global ftp server object
to local_path."""
global ftp
with NamedTemporaryFile(delete=False) as out_file:
temp_file_name = out_file.name
ftp.retrbinary('RETR ' + server_path, out_file.write)
os.rename(temp_file_name, local_path)
print "Succesfully downloaded to {0}".format(local_path)
def ensure(dir):
"""Create a directory if it does not exist"""
if not os.path.exists(dir):
os.makedirs(dir)
def extract_and_remove(zip_path, out_dir):
"""Extract the zip file at zip_path to out_dir and then delete it"""
with zipfile.ZipFile(zip_path, 'r') as outzip:
outzip.extractall(out_dir)
os.remove(zip_path)
def download_index_files(out_dir):
"""Download all of the SEC index files, organizing them into a
directory structure rooted at out_dir."""
years = ['1993', '1994', '1995', '1996',
'1997', '1998', '1999', '2000',
'2001', '2002', '2003', '2004',
'2005', '2006', '2007', '2008',
'2009', '2010', '2011', '2012']
quarters = ['QTR1', 'QTR2', 'QTR3', 'QTR4']
# Get the current working directory so that we can change it
# back when we're done
old_cwd = os.getcwd()
ensure(out_dir)
os.chdir(out_dir)
for year in years:
for quarter in quarters:
subdir = year + '/' + quarter
ensure(subdir)
path = subdir + '/form.zip'
download_file(path, path)
extract_and_remove(path, subdir)
os.chdir(old_cwd)
dropuntil = lambda pred, xs: dropwhile(lambda x: not pred(x), xs)
def paths_for_10ks(index_file):
paths = []
# drop the header of the index file, which is seperated from the
# body by a line of all '-'s
lines = dropuntil(lambda a: re.match('-+$', a), index_file)
lines.next()
for line in lines:
if line[:4] == '10-K' or line[:4] == '10-Q':
fields = re.split('\s\s+', line)
company, date, server_path = (fields[1], fields[3], fields[4])
paths.append((server_path, '{0}_{1}_{2}'.format(company.replace('/', '-'), date, fields[0].replace('/','-'))))
return paths
# Actually don't think I need this
def ssh_setup(user, password):
global hosts
command = 'ssh-keygen -t rsa; cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys'
for host in hosts:
subprocess.call(['ssh', '{0}@{1}'.format(user, host), command])
|
UTF-8
|
Python
| false | false | 2,012 |
19,713,899,892,377 |
8a3ede96fa53a57b57b16ac686447300f87e3ad9
|
a90cac2db31d0c4dacda703dbdfad66ae4c1a0ce
|
/mims.bak/instrument/test.py
|
b328d46a712e99edeb5941c24dc0cd588dd3c55a
|
[] |
no_license
|
gongjun0208/some_study
|
https://github.com/gongjun0208/some_study
|
65c3f1e8caa9e0a3b58cc5f027c29fa9b3849966
|
49a1c8d4ee9acc0dedf2e9b8e5eb730577858bae
|
refs/heads/master
| 2016-09-06T20:34:16.429000 | 2014-09-04T05:59:40 | 2014-09-04T05:59:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import csv
lst = []
with open('xiaoque.csv','r') as f:
data = csv.reader(f)
for i in data:
try:
record = [x.decode('gbk') for x in i if i[0] ]
except:
record = [x.decode('utf8') for x in i if i[0] ]
if record:
lst.append(record)
print lst
|
UTF-8
|
Python
| false | false | 2,014 |
18,519,899,005,843 |
f1ae5f6cfa32ec68d5ecc2fd71336161c8962b97
|
1086351810d15a6167194ffe36fd5e452c6ae531
|
/eventex/core/views.py
|
8b6e0350685d8fc06d8379d9e4a628306e9a1b9f
|
[] |
no_license
|
DiegoVallely/django-project
|
https://github.com/DiegoVallely/django-project
|
9c63e7b56cfffb5986d4c2417142002d268a29f4
|
e808c527c99fb1c0b49668f12c964a7252c665b6
|
refs/heads/master
| 2021-01-22T18:10:32.803000 | 2013-04-21T13:29:23 | 2013-04-21T13:29:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.conf import settings
def homepage(request):
context = {'STATIC_URL':settings.STATIC_URL}
return render_to_response('index.html', context)
|
UTF-8
|
Python
| false | false | 2,013 |
1,486,058,707,695 |
805a2665b588d55d3c03b569e5ca8e6e8d64afa8
|
0429ace2f0ea6c8eac9c4b34f12e5f7b4ad4ef0e
|
/Administration/views/rental_inventory.py
|
228a53f62c6ef19601c1b1878e6150239449964e
|
[] |
no_license
|
j1thomas/mystuff
|
https://github.com/j1thomas/mystuff
|
3788413f86543d67531bba4f2d2eed566a186147
|
12d779b208990d7830713146ef0309f2eabf2b6e
|
refs/heads/master
| 2021-01-23T06:54:38.950000 | 2014-02-08T00:13:27 | 2014-02-08T00:13:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django import forms
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, Http404
from Administration import models as imod
from . import templater
def process_request(request):
Rental_Inventory = imod.RentalInventory.objects.exclude(active=False)
template_vars = {
'rental_inventory': Rental_Inventory,
}
return templater.render_to_response(request, 'rental_inventory.html', template_vars)
|
UTF-8
|
Python
| false | false | 2,014 |
1,709,397,020,182 |
a08b014846b20d9e4fb07c7cf79d423c65109bab
|
7ad1516bd86fb15b35ce3076950a1ed42ff97526
|
/robot_server/scripts/scripts/manualControl.py
|
5106930b3e7e51a3b3afcbb837c070782b6fc9c0
|
[] |
no_license
|
AndLydakis/Sek_Slam
|
https://github.com/AndLydakis/Sek_Slam
|
17e61d35230a960b826d91cd3ad20027e2be63f1
|
82937159413ff38ce20c48da5c5c163db891f7ad
|
refs/heads/master
| 2020-05-20T00:51:50.064000 | 2014-12-23T08:50:49 | 2014-12-23T08:50:49 | 13,829,971 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import rospy
import roslib
from std_msgs.msg import Int32
from sensor_msgs.msg import Joy
import threading
from threading import Thread
class py_to_joy(object):
#the publisher
remote=None
key_pub=None
run=False
#constructor
def __init__(self,socket):
#orizetai o subscriber poy akoyei sto topic chatter gia enan Integer
self.chat_sub = rospy.Subscriber('chatter', Int32, self.chatter_cb2,queue_size=10)
#orizetai o publisher poy 8a steilei ena minima Joy sto topic joy
self.joy_pub = rospy.Publisher('joy', Joy)
#orizetai to minima Joy poy 8a gemisoyme me dedomena
self.joy_msg = Joy()
#to minima Joy exei 2 pinakes gia dia8esima plhktra kai axones, to mege8os twn opoion orizoyme
# me to extend edw estw 2 axones X,Y
self.joy_msg.axes.extend([0.0,0.0,0.0,0.0,0.0,0.0,0.0])
self.joy_msg.buttons.extend([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])
self.socket=socket
def chatter_cb2(self,data):
x=data.data
if(x==1):
self.joy_msg.axes[6]=1
elif(x==2):
self.joy_msg.axes[5]=1
elif(x==3):
self.joy_msg.axes[6]=-1
elif(x==4):
self.joy_msg.axes[5]=-1
elif(x==5):
self.joy_msg.axes[5]=0
self.joy_msg.axes[6]=0
elif(x==0):
self.joy_msg.axes[5]=0
self.joy_msg.axes[6]=0
reason="etsi"
self.remote=0
#rospy.signal_shutdown(reason)
else:
pass
self.joy_pub.publish(self.joy_msg)
self.joy_msg.axes[5]=0
self.joy_msg.axes[6]=0
#callback, kaleitai otan er8ei ena minima sto topic chatter
# def publish_key(self,key):
# #while self.run:
# if self.run :
# #Endexomenos na steilei ena parapano
# self.key_pub.publish(key)
def controller(self):
# arxikopoieitai to node
rospy.init_node('python_to_joy')
#orizetai o publisher poy 8a stelnei tis entoles
self.key_pub = rospy.Publisher('chatter', Int32)
self.remote=1
#oso leitoyrgei to node :
while True:
try:
#diabazei thn entolh tou xrhsth apo to socket
print("W8ting...")
key=int(self.socket.recv(32))
#i=threading.activeCount()
#print i
except ValueError:
print("Not an integer")
#an stal8ei h timh 0 termatizetai to module
self.key_pub.publish(key)
print("key ={}".format(key))
if(key==0):
break
return 0
|
UTF-8
|
Python
| false | false | 2,014 |
17,806,934,419,042 |
4bf0ee9155fe67c3b3d9383c98b9ceafdef31086
|
982961e4a1fa45b7edbefd2dd062b3ad71896682
|
/kakuro.py
|
3aaf7fb4cd64939320e0f99c721988da19bffc7c
|
[] |
no_license
|
bigsnarfdude/doodles
|
https://github.com/bigsnarfdude/doodles
|
c1a5ff575441c07186b342962702fb8adfd6db69
|
4ef3df5401b800008db64650c073521431e47ada
|
refs/heads/master
| 2016-05-25T20:13:22.485000 | 2013-01-28T05:22:35 | 2013-01-28T05:22:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import argparse
from itertools import permutations
def find(target, n_terms):
r = set([])
xs = permutations(range(1,10), n_terms)
for x in xs:
if sum(x) == target:
r.add(tuple(sorted(x)))
return r
def find_in(target, n_terms, ys):
r = set([])
xs = find(target, n_terms)
for x in xs:
for y in ys:
if y not in x:
break
else:
r.add(x)
return r
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("target", type=int)
parser.add_argument("n_terms", type=int)
parser.add_argument("-a", "--args", type=int, nargs="+")
args = parser.parse_args()
if args.args:
for match in find_in(args.target, args.n_terms, args.args):
print match
else:
for match in find(args.target, args.n_terms):
print match
|
UTF-8
|
Python
| false | false | 2,013 |
11,536,282,184,744 |
83ffb56cc8a8867b2a091ac4527f0a682f92f4ac
|
b6afd7d7c8ec1adda6b15b02547ba0e7b315afe2
|
/lyrics/views.py
|
ae2d1abbc87f5fc8a491157f5c7662ea803dbb3f
|
[] |
no_license
|
eanikolaev/lyrics
|
https://github.com/eanikolaev/lyrics
|
d3c7b4c3e12c2e4a75cd0e6ce8f631b5e8924223
|
ac1312bcfd30c1c277051398de3af1217e07eb1f
|
refs/heads/master
| 2016-09-06T09:21:47.417000 | 2014-12-22T20:53:50 | 2014-12-22T20:53:50 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from lyrics.models import Song
from search import search
import time
OK = 1
ERROR = 0
def transform_query(query):
if query and not ('and' in query.lower()) and not ('or' in query.lower()):
return query.replace(' ', ' AND ')
return query
def round_time(seconds):
return "%.2f" % seconds
def index(request):
params_dict = {
}
return render(request, 'index.html', params_dict)
def song_detail(request, song_id):
song = get_object_or_404(Song.objects.all(), id=song_id)
params_dict = {
'song': song
}
return render(request, 'song_detail.html', params_dict)
def song_list(request):
start_time = time.time()
query = request.GET.get('query','')
query = transform_query(query)
if query:
status, res = search(query.encode('utf-8'))
if status == OK:
song_list = Song.objects.filter(id__in=res)
count = song_list.count()
else:
return error(request, res)
else:
song_list = []
count = 0
params_dict = {
'song_list': song_list,
'results_count': count,
'elapsed_time': round_time(time.time() - start_time)
}
return render(request, 'song_list.html', params_dict)
def error(request, msg):
params_dict = {
'message': msg
}
return render(request, 'error.html', params_dict)
|
UTF-8
|
Python
| false | false | 2,014 |
19,215,683,702,753 |
6df31fcbbbbc565ac483d8875800f506a6dc7355
|
23eebd728796e1ba57cce28e07cdc74a1669b0be
|
/slicedinvesting/investor/models.py
|
2a2f21badbead04097cff377aff845a9a7cf2d1f
|
[] |
no_license
|
cha63506/django
|
https://github.com/cha63506/django
|
73c0ca6f3ac02ff1b227963d2b3107a6faf49359
|
e5680466bad9c7ad41f8c9776bb8ea0b53be23dc
|
refs/heads/master
| 2017-05-21T15:26:03.537000 | 2014-03-04T03:25:23 | 2014-03-04T03:25:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import Group as DjangoGroup
from django.db.models.signals import post_save
# Create your models here.
class InvestorProfile(models.Model):
username = models.CharField(max_length=50,primary_key=True)
user = models.OneToOneField(User,related_name='profile')
firstName = models.CharField(max_length=50,null=True,blank=True)
lastName = models.CharField(max_length=50,null=True,blank=True)
bio=models.TextField(null=True, blank=True)
percCompleted=models.FloatField(default=0)
pic=models.ImageField(upload_to="images/",blank=True, null=True)
accountValue=models.FloatField(default=0)
portfolioValue=models.FloatField(default=0)
followers=models.IntegerField(default=0) #TBD - should point to other investors
following=models.IntegerField(default=0) #TBD - should point to other investors
syndicates=models.TextField(null=True, blank=True)
statusUpdate=models.TextField(null=True, blank=True)
portfolioReturn=models.FloatField(default=0)
joiningDate=models.DateField(null=True)
@models.permalink
def get_absolute_url(self):
return ('profiles_profile_detail', (), { 'username': self.username })
def __unicode__(self):
return self.pk
def get_fields(self):
return [(field.name, field.value_to_string(self)) for field in InvestorProfile._meta.fields]
def create_investor(sender, **kwargs):
"""When creating a new user, make him an investor and create an empty profile for him or her."""
u = kwargs["instance"]
try:
if not InvestorProfile.objects.filter(username=u.username):
inv = InvestorProfile(username=u.username,user=u)
inv.save()
g = DjangoGroup.objects.get(name='Investors')
g.user_set.add(u)
except Exception as e:
print e
post_save.connect(create_investor, sender=User)
|
UTF-8
|
Python
| false | false | 2,014 |
5,841,155,566,618 |
ef7bb14f55ea92f9ef51aad09d5f9e5efe0f3d85
|
548c26cc8e68c3116cecaf7e5cd9aadca7608318
|
/notifications/notificationmedium.py
|
f3743a4908747748a25f67ebebe5675ccf8e634c
|
[] |
no_license
|
Morphnus-IT-Solutions/riba
|
https://github.com/Morphnus-IT-Solutions/riba
|
b69ecebf110b91b699947b904873e9870385e481
|
90ff42dfe9c693265998d3182b0d672667de5123
|
refs/heads/master
| 2021-01-13T02:18:42.248000 | 2012-09-06T18:20:26 | 2012-09-06T18:20:26 | 4,067,896 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class NotificationMedium:
def send():abstract
|
UTF-8
|
Python
| false | false | 2,012 |
1,486,058,715,940 |
57e7e2890cbac7c7272bfddc4950bd2ed84fd4ca
|
84aa6f90e5cf5f2e49a9488c1768f2794cbd50db
|
/student/100011247/HW1/right_justify.py
|
b4c67eb7198ebe5b370a03b61839868436091150
|
[] |
no_license
|
u101022119/NTHU10220PHYS290000
|
https://github.com/u101022119/NTHU10220PHYS290000
|
c927bf480df468d7d113e00d764089600b30e69f
|
9e0b5d86117666d04e14f29a253f0aeede4a4dbb
|
refs/heads/master
| 2021-01-16T22:07:41.396000 | 2014-06-22T11:43:36 | 2014-06-22T11:43:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
def right_justify(str):
print ' '*(70-len(str)),str
|
UTF-8
|
Python
| false | false | 2,014 |
6,287,832,159,054 |
b300791f14205f61c2e93949f85cabcdb5760994
|
a89f01ea06cd3d11d98ffd3079e3659a162127c8
|
/slither2/wpl/wf/WebForm-orig.py
|
0afbfabb7dba79a48aaa5b9b474c425534277a06
|
[] |
no_license
|
biocode/slither
|
https://github.com/biocode/slither
|
8e5d3b2c139f94d63369b3dcef211e75ddd845bc
|
bdaa204fa4d37957cf5742cdd3aeecad0a0b5553
|
refs/heads/master
| 2021-05-30T23:25:13.977000 | 2007-05-14T17:13:16 | 2007-05-14T17:13:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
"""
<cvs>
<author>
$Author: gkt $
</author>
<date>
$Date: 2005/03/07 23:13:50 $
</date>
<id>
$Id: WebForm-orig.py,v 1.1 2005/03/07 23:13:50 gkt Exp $
</id>
<synopsis>
WebForm is used to do web form processing. It handles much of the setup
typically required and provides a much simpler CGI interface than the Python
"cgi" module. The documentation below explains in greater detail, and a
tutorial is under development.
</synopsis>
</cvs>
"""
"""
<documentation type="module">
<synopis>
The WebForm class library is designed to allow web programs (so-called CGI
scripts) to be developed with a clear separation of concerns. CGI programming
is often characterized by a need to take input from forms, usually authored
in HTML and consisting of a number of 'input' variables (e.g. text fields,
text areas, checkboxes, selection lists, hidden variables), perform some
business logic, and then render HTML.
There are many similar approaches, such as Zope (gaining popularity) and
XML. However, these approaches suffer from much complexity. WebForm is unique
in that code generation is a completely separate concern from the actual
business logic. It is also well integrated with Python in making sure
exceptions are caught and reported (during development) to the web browser
window. This radically reduces cycle time of development, because it is a pain
to mill through those HTTP logs and figure out your errors, especially in a
live environment. (Syntax errors still resulted in the dreaded server error
messages. However, this will also be supported by a future update.)
At the core of WebForm is the WriteProcessor class library (which is part of
WebForm but is separately useful). This library allows you to perform
substitutions with a simple markup. You will want to take a look at that
library's documentation to understand how it works in detail. In summary,
WebForm allows you to process an entire file. Substitutions can be performed
on the various lines of the file against an environment. There are two types
of substitutions, both of which are very easy to understand:
1. once substitutions - the line is processed once, and variables from
the environment are substituted into a line.
2. looping substitutions - the line is processed multiplet times by an
implicit loop over a data structure.
The accompanying examples show how to make use of the looping substitutions,
which simply involve creating a dictionary data structure and creating a
descriptor for how the data in the dictionary is organized.
</synopsis>
</documentation>
"""
import os, string, os.path
import cgi, WriteProcessor, SimpleWriter, Emitter
import ConfigParser
import sys, traceback
import StringIO
import hwStackTrace
import smtplib
from Directory import Directory
from SimpleCookie import SimpleCookie
class WebForm:
"""
<documentation type="class">
<synopsis>
WebForm is intended to be an abstract class. (There isn't much way in
Python to enforce its use per se.) Thus it should not be instantiated
directly. Instead a subclass should be created. Generally, the subclass
only needs to do the following:
1. Delegate initialization to this class from its __init__ method.
This is very easily done as follows:
WebForm.__init__(self, form, defaultVars, searchPath)
2. Override the process() method with your customized business logic.
Your business logic can assume that form data has been posted and
any default bindings are initialized. There are a number of methods
that can be called from within the process() method to do useful
WebForm operations. These are discussed in the tutorial example.
3. Optionally, override the addRules() method to specify looping style
rules. You'll see in the tutorial that looping rules typically are
used to fill in certain types of HTML elements, such as tables,
selection lists, checkboxes, etc.
</synopsis>
<attribute name="formVars">
The variables from 'input' tags defined in the form doing the POST.
</attribute>
<attribute name="fileVars">
The variables that correspond to uploaded files. Everyone will need to
let me know if additional APIs are needed for the purpose of working with
uploaded files. For now, you will be able to get the contents of the file
without trouble, since the <xref module="cgi"/> module already addresses
this consideration.
</attribute>
<attribute name="searchPath">
Where to find any included files.
</attribute>
<attribute name="prefix">
This is only used if you ask WebForm to bind all entries in
formVars as variables. The binding process allows your business logic
to make references such as 'self.[prefix][form-var] = ...' or
'[var] = self.[prefix][form-var]' instead of having to refer to
self.formVars[var] or self.getFormVar(var). Having the prefix makes
it possible to minimize the likelihood of clobbering your object's
namespace when the bindings are actually made. This particular
attribute is initialized to the empty string. To override it, you
can use the setPrefix() method in your overridden process() method.
</attribute>
</documentation>
"""
def __init__(self, form, defaultVars={}, searchPath=["."], autoDispatch=1, **props):
"""
<documentation type="constructor">
<synopsis>
Initialize the instance. As mentioned, you will not be creating
instances of WebForm (nor should you). Instead, make a subclass
and delegate initialization from your subclass' __init__ method.
</synopsis>
<param name="form">
cgi.FieldStorage(), passed down upon initialization by the
WebFormDispatcher class.
</param>
<param name="defaultVars">
a set of variables that represent default values.
These values come from a .conf file that matches the class name
of the WebForm subclass. The WebFormDispatcher reads the .conf
file and creates this for you automagically.
</param>
<param name="searchPath">
list of directories to be searched for HTML (or any
included file being referenced from within your HTML code). This
is used by the WriteProcessor instance when generating code
from the <xref class="WebForm" method="encode"/> method.
</param>
<param name="encodeTarget">
The name of the HTML file to be used when generating code. This
is initialized to None here but actually is initialized by
the WebDispatcher when dynamically creating an instance of any
WebForm subclass.
</param>
</documentation>
"""
if props.has_key('config_dir'):
self.config_dir = props['config_dir']
else:
self.config_dir = '.'
self.form = form
self.argv = sys.argv[:]
confVars = self.parseConfFile()
self.cookies = []
cookie = self.loadCookie()
if cookie != None:
self.cookies.append(cookie)
self.startingCookieCount = 1
else:
self.startingCookieCount = 0
self.formVars = Directory({})
self.formVars.update(defaultVars)
self.formVars.update(confVars)
self.hiddenVars = []
self.fileVars = Directory({})
self.searchPath = searchPath
self.setContentStandard()
self.extractFormVariables(form)
self.encodeTarget = None
self.prefix = ""
self.autoDispatch = autoDispatch
def extractFormVariables(self, form, depth=0):
for var in form.keys():
try:
if type(form[var]) == type([]):
form_var = form[var][0]
else:
form_var = form[var]
if form_var.filename == None:
self.formVars[var] = form_var.value
else:
VAR_DIR = '/%s' % var
self.fileVars[var] = (form_var.filename, form_var.file)
self.fileVars.create(var)
self.fileVars.cd(var)
self.fileVars['filename'] = form_var.filename
self.fileVars['file'] = form_var.file
self.fileVars.cd('/')
if type(form[var]) == type([]):
VAR_DIR = '/%s' % var
self.formVars.create(var)
self.formVars.cd(var)
self.formVars[var] = []
varCount = 0
for form_var in form[var]:
if form_var.filename == None:
self.formVars["%s_%d"%(var,varCount)] = form_var.value
self.formVars[var].append(form_var.value)
varCount = varCount + 1
self.formVars.cd('/')
except:
raise "WebFormException", str(var) + "=" + str(form[var])
def getFieldStorage(self):
return self.form
def parseConfFile(self):
# Now load the configuration file for the form. Every form is required
# to have one--no exceptions. This allows you to supply (for example)
# default values for variables. The WebForm class will actually
# register every variable appearing here as an actual attribute of
# the WebForm subclass instance.
formDefaults = {}
try:
formId = self.__class__.__name__
configFile = self.config_dir + '/' + formId + '.conf'
confParser = ConfigParser.ConfigParser()
confParser.read( configFile )
optionList = confParser.options(formId)
try:
optionList.remove('__name__')
except:
pass
for option in optionList:
optionValue = confParser.get(formId, option)
formDefaults[option] = optionValue
except:
# If any problem occurs in the ConfigParser, we are going to
# return whatever we were able to get.
pass
return formDefaults
# This method (internal) loads a cookie from the environment.
def loadCookie(self):
if os.environ.has_key("HTTP_COOKIE"):
try:
cookie = SimpleCookie()
cookie.load(os.environ["HTTP_COOKIE"])
except CookieError:
server = smtplib.SMTP('localhost')
excf = StringIO.StringIO()
traceback.print_exc(file=excf)
server.sendmail('hwMail@hostway.com',['duffy@hostway.net'],\
"Subject: Cookies choked in WebForm processing!\n\n%s\nHTTP_COOKIE looks like:\n%s\n" % (excf.getvalue(), os.environ["HTTP_COOKIE"]))
server.quit()
return None
if len(cookie.keys()):
return cookie
else:
return None
else:
return None
# This method tells you whether any cookies are present int the form.
def hasCookies(self):
return len(self.cookies) > 0
# This method returns the list of cookies to a client.
def getCookies(self):
return self.cookies
# This method allocates a cookie and links it onto the list of cookies.
# It's basically a factory method.
def getNewCookie(self):
cookie = SimpleCookie()
self.cookies.append(cookie)
return cookie
# This method will tell you whether any cookie can be found that matches
# a list of vars. Matching occurs if all of the vars are found. An empty
# To use this method, simply pass as many vars as you'd like to check.
# e.g. matchCookie('user','key') as in Jason's examples.
def matchOneCookie(self,*vars):
if len(vars) < 1: return None
for cookie in self.cookies:
matched = 1
for var in vars:
if not cookie.has_key(var):
matched = 0
break
if matched:
return cookie
return None
def matchAllCookies(self, *vars):
if len(vars) < 1: return None
L=[]
for cookie in self.cookies:
matched = 1
for var in vars:
if not cookie.has_key(var):
matched = 0
break
if matched:
L.append(cookie)
return L
def setContentType(self,mimeTypeName):
self.contentType = 'Content-type: ' + mimeTypeName + '\n\n'
def setContentStandard(self):
self.setContentType('text/html')
def removeContentHeader(self):
self.contentType = None
def setSearchPath(self, searchPath):
self.searchPath = searchPath
def setPrefix(self,prefix):
if type(prefix) == type(""):
self.prefix = prefix
# This method allows you to bind the form variables BY NAME and spare
# yourself the agony of having to do self.var = form[var].value calls.
# Here we also provide the ability to prepend a prefix to the variable
# name. This method will NOT clobber any pre-existing binding in this
# object (self).
#
# To make sure everyone understands what's going on here:
# Suppose your form has some variables. Variables come from various
# tags, such as <INPUT name="someVar" value="someValue">. After this
# call, your Form instance (or subclass) will have self.someVar
# (or self.<prefix>someVar) as an attribute.
def bindVars(self, prefix=None):
"""
<documentation type="method">
<synopsis>
This method will take all of the entries defined in
<xref class="WebForm" attribute="formVars">formVars</xref> and
make actual instance variables in the current object using
Python's setattr() method. The name of the instance variable
will be whatever is contained in <xref class="WebForm" attribute="prefix"/>
followed by the actual name appearing in the 'input' tag from
the form. As these variables are effectively 'cached' in the current
object, the companion routine <xref class="WebForm" method="flushVars"/>
must be called to ensure the variables are actually written through
for the next form (usually needed for processing hidden variables).
</synopsis>
</documentation>
"""
if not prefix:
prefix = self.prefix
for var in self.formVars.keys():
if not self.__dict__.has_key(prefix + var):
setattr(self,prefix + var,self.formVars[var])
def flushVars(self, prefix=None):
"""
<documentation type="method">
<synopsis>
This method writes all of the instance variables previously bound
to the current object back to <xref class="WebForm" attribute="formVars"/>.
Python's getattr() is used to find all such variables (as well as
any new variables that may have been added by the
<xref class="WebForm" method="addFormVar"/> method.
</synopsis>
</documentation>
"""
if not prefix:
prefix = self.prefix
for var in self.formVars.keys():
if self.__dict__.has_key(prefix + var):
self.formVars[var] = getattr(self,prefix + var)
def addVars(self, env):
"""
<documentation type="method">
<synopsis>
This method allows you to take a dictionary of bindings and add them
to <xref class="WebForm" attribute="formVars"/> This can be particularly
useful for dumping the result of a database selection, a dynamically'
generated list of options, etc.
</synopsis>
<param name="env">
The dictionary of bindings.
</param>
</documentation>
"""
for var in env.keys():
self.formVars[var] = env[var]
def addVar(self, name, value):
"""
<documentation type="method">
<synopsis>
This method allows you to take a dictionary of bindings and add them
to <xref class="WebForm" attribute="formVars"/> This can be particularly
useful for dumping the result of a database selection, a dynamically'
generated list of options, etc.
</synopsis>
<param name="env">
The dictionary of bindings.
</param>
</documentation>
"""
self.formVars[name] = value
def markHidden(self,var):
"""
<documentation type="method">
<synopsis>
This method allows you to take a dictionary of bindings and add them
to <xref class="WebForm" attribute="formVars"/> This can be particularly
useful for dumping the result of a database selection, a dynamically'
generated list of options, etc.
</synopsis>
<param name="env">
The dictionary of bindings.
</param>
</documentation>
"""
if self.formVars.has_key(var):
self.hiddenVars.append(var)
def getFormVar(self, var):
"""
<documentation type="method">
<synopsis>
This method allows you to take a dictionary of bindings and add them
to <xref class="WebForm" attribute="formVars"/> This can be particularly
useful for dumping the result of a database selection, a dynamically'
generated list of options, etc.
</synopsis>
<param name="env">
The dictionary of bindings.
</param>
</documentation>
"""
if self.formVars.has_key(var):
return self.formVars[var]
else:
return None
def getFormVarDirectory(self):
return self.formVars
def getFileVarDirectory(self):
return self.formVars
def getFileName(self, var):
try:
VAR_DIR = '/%s' % var
self.fileVars.cd(var)
fileName = self.fileVars['filename']
self.fileVars.cd('/')
return fileName
except:
return None
def getFileHandle(self, var):
try:
VAR_DIR = '/%s' % var
self.fileVars.cd(var)
fileHandle = self.fileVars['file']
self.fileVars.cd('/')
return fileHandle
except:
return None
def process(self):
"""
<documentation type="method">
<synopsis>
This method is effectively an NOP. Your subclass should override
this method to do some useful business logic, such as querying the
database, defining variables to fill in dynamically generated
elements, etc.
</synopsis>
</documentation>
"""
pass
def setEncodeFileName(self, fileName):
"""
<documentation type="method">
<synopsis>
This allows you to change what web page is going to come up next.
It is usually a reference to an HTML file, although it does not
have to be, since WebForm always makes sure to generate a content
HTML header when doing code generation.
</synopsis>
<param name="fileName">
The top-level file to be used for doing code generation
</param>
</documentation>
"""
self.encodeTarget = fileName
def encode(self, emitStrategy=Emitter.Emitter(), text=None):
"""
<documentation type="method">
<synopsis>
Generate the code after the business logic from your subclass'
<xref class="WebForm" method="process"/> method is executed.
</synopsis>
<param name="additionalVars">
Any last-minute bindings you wish to establish. Generally, you
should use the methods <xref class="WebForm" method="addFormVar"/>
and <xref class="WebForm" method="addFormVars"/> to make additional
bindings from within your subclass'
<xref class="WebForm" method="process"/> method.
</param>
</documentation>
"""
# Check whether the strategy was specified by name
# Construct object of that type if possible.
# If not, use StringEmitter.
if type(emitStrategy) == type(''):
emitStrategy = Emitter.createEmitter(emitStrategy)
# If the emitStarategy is not a proper subclass of Emitter,
# replace with a StringEmitter instance.
if not isinstance(emitStrategy, Emitter.Emitter):
emitStrategy = Emitter.Emitter()
newEnv = self.formVars.copy()
#for var in additionalVars.keys():
# newEnv[var] = additionalVar[var]
if self.encodeTarget != None:
if self.autoDispatch:
# If there were incoming cookies, we only write
# the *new* cookies. self.startingCookieCount can only
# be 0 or 1, based on the condition in __init__().
for cookie in self.cookies[self.startingCookieCount:]:
emitStrategy.emit(`cookie` + '\n')
# Content goes next.
if self.contentType:
emitStrategy.emit(self.contentType)
# Emit any "initial" text (i.e. stuff to be prepended, usually
# from stray print statements in the process() method.
if text:
emitStrategy.emit(text)
# This is the actual content, i.e. rendering of the page.
wp = WriteProcessor.WriteProcessor(self.encodeTarget, \
self.searchPath, newEnv, \
emitStrategy)
self.addRules(wp)
wp.process()
# else:
# should probably encode to standard output by default...
return emitStrategy.getResult()
def addFormVarRule(self,wp):
"""
<documentation type="method">
<synopsis>
This rule allows you to generate a nice looking table of all
variables defined in the WebForm. Should your subclass provide
its own rules, using the <xref class="WebForm" method="addRules"/>
method, it will be necessary to call this method explicitly or
the <xref class="WebForm" method="addDefaultVars"/> method.
</synopsis>
<param name="wp">
The WriteProcessor instance being used for code generation (supplied
by the <xref class="WebForm" method="encode"> method, which is called
immediately after the <xref class="WebForm" method="process"> method.
</param>
</documentation>
"""
env = {}
for var in self.formVars.keys():
varName = cgi.escape(var)
varValue = self.formVars[varName]
varType = type(varValue)
varType = cgi.escape(`varType`)
varValue = cgi.escape(`varValue`)
env[varName] = (varType,varValue)
if len(env) == 0:
env['N/A'] = ('N/A','N/A')
wp.addLoopingRule('WebForm_VarName',\
'(WebForm_VarType, WebForm_VarValue)', env)
def addHiddenVarRule(self,wp):
"""
<documentation type="method">
<synopsis>
This rule allows you to add all hidden variables (easily) to the
next WebForm. Should your subclass provide
its own rules, using the <xref class="WebForm" method="addRules"/>
method, it will be necessary to call this method explicitly or
the <xref class="WebForm" method="addDefaultVars"/> method.
</synopsis>
</documentation>
"""
env = {}
for var in self.hiddenVars:
env[var] = self.formVars[var]
if len(env) == 0:
env['N/A'] = 'N/A'
wp.addLoopingRule('WebForm_HiddenVarName','WebForm_HiddenVarValue',\
env)
def addDefaultRules(self,wp):
"""
<documentation type="method">
<synopsis>
This will add rules for emitting hidden variables easily and
dumping all variables for the purpose of debugging. This is
equivalent to calling both
<xref class="WebForm" method="addHiddenVarRule"/> and
<xref class="WebForm" method="addFormVarRule"/>. The same comments
apply when you override the
<xref class="WebForm" method="addRules"/> method.
</synopsis>
<param name="wp">
The WriteProcessor object being used, which is supplied automatically
for you.
</param>
</documentation>
"""
self.addFormVarRule(wp)
self.addHiddenVarRule(wp)
def addRules(self,wp):
"""
<documentation type="method">
<synopsis>
Subclasses will override this method to supply their own rules.
When overriding this method, the
<xref class="WebForm" method="addDefaultRules"> method should be
called to establish some useful default rules that are designed
to facilitate debugging and propagation of hidden variables.
</synopsis>
<param name="wp">
The WriteProcessor object being used, which is supplied automatically
for you.
</param>
</documentation>
"""
self.addDefaultRules(wp)
errorText = """
<html>
<head>
<title>WebForm Processing Error</title>
</head>
<body>
<h1>WebForm Error in Processing</h1>
<p>An error has been encountered in processing a form.</p>
<p><<WebForm_Error>></p>
</body>
</html>
"""
def error(form, message, emitContentHeader=1):
"""
documentation type="function">
<synopsis>
This is used to guarantee that any error that occurs when dispatching a
form results in valid HTML being generated. It also guarantees that a
meaningful message will also be displayed.
</synopis>
<param name="form">
The cgi.FieldStorage() object containing all form variables.
</param>
<param name="message">
A human-comprehensible message that describes what happened
and (in the future) how to resolve the problem.
</param>
</documentation>
"""
env = {}
env['WebForm_Error'] = message
if emitContentHeader:
print 'Content-type: text/html\n\n'
wp = SimpleWriter.SimpleWriter()
wp.compile(errorText)
print wp.evaluate(env)
def getWebFormDispatcher(args,htmlSearchPath):
"""
<documentation type="function">
<synopsis>
To use the WebForm system, your main method need only contain a call to
skeleton dispatcher with the command line arguments.
</synopsis>
</documentation>
"""
# args[0] always contains the name of the program. This should be
# the name of your form. Basically, each class must be contained in
# a file that matches the class name. So if your WebForm subclass is
# 'class OrderPizza(WebForm)', it should be in a file named OrderPizza*.
#
programName = args[0]
# Allow for the (real) possibility that the program name might be
# invoked as a full path or whatever. This would probably break if
# we ran on Apache Winhose, but since Hostway would never do such
# a cheesy thing on the server side, I am not going to worry about
# this hypothetical possibility that "/" isn't the separator.
pathParts = string.split(programName,"/")
# The last token after "/" is the complete file name.
realName = pathParts[-1]
mainNameParts = string.split(realName,".")
# Get rid of the .py or .whatever.
className = mainNameParts[0]
# Run, Forrest, Run!
WebFormDispatcher(htmlSearchPath, className, className)
class WebFormDispatcher:
"""
<documentation type="class">
<synopsis>
A singleton class (i.e. only one instance should be created) that
is used to dynamically dispatch and execute user defined WebForm
objects. This class dynamically executes code to import a user-defined
class (from a module having the same name). The instance is created and
then processed (using the <xref class="WebForm" method="process"/>) and
encoded (the part that renders the next HTML form, using
the <xref class="WebForm" method="encode"/> method.
</synopsis>
</documentation>
"""
def __init__(self,searchPath,formId=None,contentType="text/html"):
"""
<documentation type="class">
<synopsis>
All of the work is done in the constructor, since this class is
intended for use as a singleton. That is, an instance is created,
it does its thing, and then it is not used further. A CGI script
simply creates this instance in its main method (or as its only
statement) and that is all there is to it. See the examples for
how to automate the setup of this class. It is very slick, and very
easy.
</synopsis>
<param name="searchPath">
where to find included (HTML) files/fragments
</param>
<param name="formId">
the form to be loaded. Typically, this will simply be the 'name'
of the program, which is sys.args[0].
</param>
<param name="contentType">
Generally, leave this alone. We'll need to think a little bit about
how to get out of the box to generate something non-HTML, such as a
ZIP file or whatever. This should not be a problem to extend. It
will probably require us to change some things in the WebForm class.
</param>
</documentation>
"""
# First get all of the data that was defined in the form. The CGI
# module of Python does this, albeit in a crappy way, since it does
# not pass the values of 'inputs' that were left blank, for example.
#
# We need to peek at the variables to determine what form is to
# be loaded. The 'input' named WebForm_FormId is reserved for this
# purpose.
form = cgi.FieldStorage()
try:
if not formId:
formId = form['WebForm_FormId'].value
except:
error(form,"Hidden 'WebForm_FormId' variable not defined")
return
# This could be deleted but some existing apps could break. I have
# decided to put the .conf logic into the WebForm class itself.
formDefaults = {}
# Import the module (form) dynamically. We will swtich to __import__
# soon, since it has the convenient property of giving a namespace
# reference.
__namespace__ = __import__(formId)
# Dynamically create the form instance. At the end of this, __form__
# is a reference to the form object.
statement = '_form_ = __namespace__.' + formId
statement = statement + '(form,formDefaults,searchPath)'
try:
exec statement
except:
error(form,"could not execute " + statement)
print "<pre>"
traceback.print_exc(None,sys.stdout)
print "</pre>"
return
# Set (by default) the template for generating HTML output code to
# be the same name as the form followed by '.html'. This can be
# changed by the form's process() method.
_form_.setEncodeFileName(formId + '.html')
#
# Call the form's business logic (process) method. This method (as
# mentioned in the WebForm documentation) is to be overridden to
# actually get your business logic wired in.
#
#
# If an exception occurs during this process, it is sent to the
# standard output (which, coincidentally is dup'd to the output
# stream associated with the socket held by the HTTP server. This
# means (happily) that any run time error a la Python is going to
# be seen in the browser window
#
# GKT Note: We want to do two things here.
# 1. Provide the option for printing a generic message and showing
# no traceback (useful during deployment--don't want customers
# to see tracebacks for sure!)
# 2. Support integration with the hwMail package and logging server
# that we are (or hope to be) working on. Flat file logging would
# also be VERY nice.
#
try:
stdout = sys.stdout
sys.stdout = out = StringIO.StringIO()
_form_.process()
sys.stdout = stdout
except:
sys.stdout = stdout
error(form,"Exception encountered in business logic [process()]")
outText = out.getvalue()
print "<pre>"
traceback.print_exc(None,sys.stdout)
print "</pre>"
print "<h1> output intercepted from process() method </h1>"
if len(outText) > 0:
print outText
return
#
# Final Code Generation. It is unlikely an exception will be thrown
# in here. If one does happen, it is impossible to guarantee that the
# exception is propagated to the browser. Assuming that the cookies
# being emitted are well formed (a pretty reasonable assumption), the
# exception should be processed normally.
#
try:
outText = out.getvalue()
if len(outText) > 0:
_form_.encode(text=outText)
else:
_form_.encode()
except:
error(form,"Exception encountered in HTML generation [encode()]")
print "<pre>"
traceback.print_exc(None,sys.stdout)
print "<pre>"
return
# And that's all she wrote! :-) Sorry, pun TRULY not intended.
|
UTF-8
|
Python
| false | false | 2,007 |
14,551,349,243,314 |
635893304e72348c6ae39edcc47e100b76b22e0c
|
33dce6e03f5319c5000eb41c9709c63caf5aaab7
|
/IntradayTransactions/Code_Preprocess.py
|
5704fba7d0769736bc6cf619bb7c0688fba545d9
|
[] |
no_license
|
hahahawowowo/CHSW
|
https://github.com/hahahawowowo/CHSW
|
ea01e6a3189369cf7624d380120a7228b4695234
|
f6758b4ec733524328b47ac071e9f3c9c0ffc82d
|
refs/heads/master
| 2021-05-28T06:32:20.014000 | 2013-01-03T09:40:21 | 2013-01-03T09:40:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# read HS300 codes, format in e.g 000001.SZ
file = open("ACodes.txt",'r')
codes = file.readlines()
file.close()
# create a new file to save the sina format
file_sina = open("ACode_Sina.txt",'w+')
for code in codes:
code = code.rstrip('\n')
code_sep_ex = code.partition('.')
code_sina = code_sep_ex[2].lower() + code_sep_ex[0]
file_sina.write(code_sina)
file_sina.write('\n')
file_sina.close()
|
UTF-8
|
Python
| false | false | 2,013 |
10,694,468,613,596 |
5178043bc96f256f527c7bde294763b6ba4e3e53
|
eae7a539eaba7a23dea8007f02967827298a4795
|
/fit/data_Bc.py
|
4d5d361e81c3d95b3c7b2f137763b875c5d88184
|
[] |
no_license
|
bmcharek/Bu2JpsiKKpi
|
https://github.com/bmcharek/Bu2JpsiKKpi
|
7650cc33e10a525842a816510c090cf9567f2c34
|
7a932af5562e446aa42ed3c4b253df0940a7ef3f
|
refs/heads/master
| 2021-01-12T21:52:43.329000 | 2014-03-07T15:21:34 | 2014-03-07T15:21:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import ROOT
import glob
from AnalysisPython.PyRoUts import *
from AnalysisPython.GetLumi import getLumi
import AnalysisPython.ZipShelve as ZipShelve
from AnalysisPython.Logger import getLogger
# =============================================================================
logger = getLogger(__name__)
#
# define the default storage for data set
#
RAD = ROOT.RooAbsData
if RAD.Tree != RAD.getDefaultStorageType():
print 'DEFINE default storage type to be TTree! '
RAD.setDefaultStorageType(RAD.Tree)
def _draw_(self, *args, **kwargs):
t = self.store().tree()
return t.Draw(*args, **kwargs)
ROOT.RooDataSet.Draw = _draw_
#
tSelection5 = ROOT.TChain('JpsiKKpi/t')
tSelection6 = ROOT.TChain('JpsiKKpi/t')
#
tLumi = ROOT.TChain('GetIntegratedLuminosity/LumiTuple')
outputdir = '/afs/cern.ch/user/a/albarano/cmtuser/Bender_v22r8/Scripts/testing/output/'
files = ['B2JpsiKKpi-2011.root', 'B2JpsiKKpi-2012.root']
files_sel6 = ['B2JpsiKKpi-2011-sel6.root', 'B2JpsiKKpi-2012-sel6.root']
nFiles = len(files)
for f in files:
tSelection5.Add(outputdir + f)
for f in files_sel6:
tSelection6.Add(outputdir + f)
# mc_outputdir = '/afs/cern.ch/user/a/albarano/cmtuser/Bender_v22r8/Scripts/testing/MC/output/'
# tBu_mc = ROOT.TChain('Bplus/t')
# mc_files = ['2011-Kpipi-Pythia6.root',
# '2011-Kpipi-Pythia8.root',
# '2012-Kpipi-Pythia6.root',
# '2012-Kpipi-Pythia8.root']
# for f in mc_files:
# tBu_mc.Add(mc_outputdir + f)
# =============================================================================
# get the luminosity
lumi = getLumi(tLumi)
logger.info(" Luminosity: %s #files %d" % (lumi, nFiles))
logger.info(" Entries B+ -> J/psi KK pi+: %s" % len(tSelection5))
from GaudiKernel.SystemOfUnits import second, nanosecond
from GaudiKernel.PhysicalConstants import c_light
ct_Bu_PDG = VE(0.4911, (0.4911 * 0.011 / 1.638) ** 2)
ct_Bu_MC = 0.492
#
# finally make the class
#
# clname = 'BcTChain'
# logger.info ( 'Finally: prepare&load C++ class %s ' % clname )
# tBc1.MakeClass( clname )
# ROOT.gROOT.LoadMacro( clname + '.C+' )
|
UTF-8
|
Python
| false | false | 2,014 |
13,280,038,928,280 |
fa4dd8dd178d24fb601eb69dbca5c71df62202fd
|
fee8fd15497f72c59475f87b3fc7a380a53ae8f9
|
/alembic/versions/2d67c6e370bb_upgrade_for_social_i.py
|
9db835863637005b02fab78a2f5388bcf21628bc
|
[] |
no_license
|
python-hackers/pythonhackers
|
https://github.com/python-hackers/pythonhackers
|
de22f2b43a585c85e3ab80aebee5b4aeb3cae4a0
|
f99af2e9da0b69cbdc6ad01bc24eb240172bbd4e
|
refs/heads/master
| 2020-12-28T03:12:35.959000 | 2014-01-10T00:19:30 | 2014-01-10T00:19:30 | 15,805,827 | 2 | 0 | null | true | 2014-02-09T16:23:52 | 2014-01-10T18:20:43 | 2014-01-10T18:21:41 | 2014-01-10T18:20:57 | 725 | 0 | 0 | 0 |
Python
| null | null |
"""Upgrade for social information
Revision ID: 2d67c6e370bb
Revises: 1f27928bf1a6
Create Date: 2013-08-18 11:37:33.445584
"""
# revision identifiers, used by Alembic.
revision = '2d67c6e370bb'
down_revision = '1f27928bf1a6'
from alembic import op
import sqlalchemy as sa
def upgrade():
"""
"""
op.add_column('user', sa.Column('password', sa.String(120), nullable=True))
op.add_column('user', sa.Column('first_name', sa.String(80), nullable=True))
op.add_column('user', sa.Column('last_name', sa.String(120), nullable=True))
op.add_column('user', sa.Column('loc', sa.String(50), nullable=True))
op.add_column('user', sa.Column('follower_count', sa.Integer, nullable=True))
op.add_column('user', sa.Column('following_count', sa.Integer, nullable=True))
op.add_column('user', sa.Column('lang', sa.String(5), nullable=True))
op.add_column('user', sa.Column('pic_url', sa.String(200), nullable=True))
op.create_table(
'social_user',
sa.Column('id', sa.Integer, primary_key=True, autoincrement=True),
sa.Column('user_id', sa.Integer, primary_key=True, autoincrement=True),
sa.Column('acc_type', sa.String(2), nullable=False),
sa.Column('name', sa.String(100), nullable=False),
sa.Column('email', sa.Unicode(200), index=True),
sa.Column('nick', sa.Unicode(64), index=True,),
sa.Column('follower_count', sa.Integer),
sa.Column('following_count', sa.Integer),
sa.Column('ext_id', sa.String(50)),
sa.Column('access_token', sa.String(100)),
sa.Column('hireable', sa.Boolean),
)
def downgrade():
op.drop_column('user', 'password')
op.drop_column('user', 'first_name')
op.drop_column('user', 'last_name')
op.drop_column('user', 'loc')
op.drop_column('user', 'follower_count')
op.drop_column('user', 'following_count')
op.drop_column('user', 'lang')
op.drop_column('user', 'pic_url')
op.drop_table("social_user")
|
UTF-8
|
Python
| false | false | 2,014 |
2,748,779,088,663 |
642f288ec40cb5becd6649d06a094ecf72474006
|
f5ef563000b537162d3763978c865a049d4f62c0
|
/src/SuperNearService.py
|
599a320d743eda7b16afe8c0e0fe8970db4950a4
|
[] |
no_license
|
gentiliniluca/kazaa
|
https://github.com/gentiliniluca/kazaa
|
f0f7e65165c4222eb9b91741f57d33f631a70a9a
|
bc0f975f31917117ddd9a6719d32192684c40074
|
refs/heads/master
| 2020-05-17T07:13:15.743000 | 2014-05-07T19:28:17 | 2014-05-07T19:28:17 | 18,674,106 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import SuperNear
import DBException
import Util
import sys
class SuperNearService:
#global MAXSUPERNEARS
#MAXSUPERNEARS = 3
@staticmethod
def insertNewSuperNear(database, ipp2p, pp2p):
try:
superNear = SuperNearService.getSuperNear(database, ipp2p, pp2p)
except:
if SuperNearService.getSuperNearsCount(database) < Util.MAXSUPERNEARS:
superNear = SuperNear.SuperNear(None, ipp2p, pp2p)
superNear.insert(database)
else:
raise DBException.DBException("Max nears number reached!")
return superNear
@staticmethod
def getSuperNear(database, ipp2p, pp2p):
#print("entro")
database.execute("""SELECT idsupernear, ipp2p, pp2p
FROM supernear
WHERE ipp2p = %s AND pp2p = %s""",
(ipp2p, pp2p))
idsupernear, ipp2p, pp2p = database.fetchone()
superNear = SuperNear.SuperNear(idsupernear, ipp2p, pp2p)
return superNear
@staticmethod
def getSuperNears(database):
database.execute("""SELECT idsupernear, ipp2p, pp2p
FROM supernear""")
superNears = []
try:
while True:
idsupernear, ipp2p, pp2p = database.fetchone()
superNear = SuperNear.SuperNear(idsupernear, ipp2p, pp2p)
superNears.append(superNear)
except:
pass
#print (sys.exc_info())
return superNears
@staticmethod
def getSuperNearsCount(database):
database.execute("""SELECT count(*)
FROM supernear""")
count, = database.fetchone()
return count
|
UTF-8
|
Python
| false | false | 2,014 |
End of preview. Expand
in Data Studio
- Downloads last month
- 4