__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
list | 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.532130 | 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.888835 | 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.552449 | 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.123936 | 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.100611 | 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.013312 | 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.201664 | 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.269152 | 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.301788 | 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.885687 | 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.094956 | 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.312675 | 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.932529 | 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.010280 | 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.072031 | 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.853296 | 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.503841 | 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.495411 | 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.724700 | 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.547827 | 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.429464 | 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.803808 | 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.950531 | 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.064956 | 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.485630 | 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.417888 | 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.537935 | 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.248642 | 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.396855 | 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.977374 | 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.014137 | 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.329523 | 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.959114 | 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.743334 | 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 |
13,941,463,886,709 |
1c0c249419ef0c0ac852e93550bf48a55043ef53
|
655d62b07a7f703d1cffa87e7b842ea1a7dc2095
|
/matris.py
|
f733a837b458fc60e966a1dbe6239819c6b5c42c
|
[] |
no_license
|
SabriAl-Safi/sabtris
|
https://github.com/SabriAl-Safi/sabtris
|
86d9f20c61e1f3f8200b2ab520bf495a9bfb28bb
|
ac534a67106261e677ea3d2d5ce473f6e7c2dc0c
|
refs/heads/master
| 2020-05-17T19:13:34.533223 | 2014-03-11T19:15:17 | 2014-03-11T19:15:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import random
tetronimo = {
1: [ [0, 0, 0, 0],
[1, 1, 1, 1],
[0, 0, 0, 0],
[0, 0, 0, 0] ],
2: [ [2, 2],
[2, 2] ],
3: [ [3, 3, 0],
[0, 3, 3],
[0, 0, 0] ],
4: [ [0, 4, 4],
[4, 4, 0],
[0, 0, 0] ],
5: [ [5, 0, 0],
[5, 5, 5],
[0, 0, 0] ],
6: [ [0, 0, 6],
[6, 6, 6],
[0, 0, 0] ],
7: [ [0, 7, 0],
[7, 7, 7],
[0, 0, 0] ]
}
numLinesScore = { 1:40, 2:100, 3:300, 4:1200 }
class GameMatrix:
"""
Matrix representing current state of play.
"""
#-------- Initialisation constructor -----------------------------------
def __init__(self, height, width, initLevel):
self.blocks = [ [ 0
for col in range(width) ]
for row in range(height) ]
#Game stats.
self.height = height
self.width = width
self.score = 0
self.totalLinesCleared = 0
self.level = initLevel
#Control of piece currently in play.
self.pieceInPlay = False
self.activeCells = []
self.activeType = 0
self.activeOrientation = 0
self.activeTopLeftCorner = []
self.dropDelay = 300 - (self.level*20)
#Control of piece ready to be spawned.
self.spawn = []
self.spawnType = 0
self.spawnOrientation = 0
self.spawnReady = False
#-------- External functions -------------------------------------------
def generateSpawn(self):
"""
Randomly generate new tetronimo piece to be spawned.
"""
tetNum = random.randint(1,7)
self.spawn = tetronimo[tetNum]
self.spawnType = tetNum
self.spawnReady = True
self.spawnOrientation = 0
def receiveNudge(self, key):
"""
If a piece is in play, move it according to key.
"""
if self.pieceInPlay:
if key == 'V':
while self.pieceInPlay:
self.nudgePlayPiece('v')
else:
self.nudgePlayPiece(key)
def receiveRotation(self,key):
"""
Rotate the spawn piece or the piece in play, accoridng to key.
"""
if self.pieceInPlay:
self.rotatePlayPiece(key)
#-------- Internal Functions--------------------------------------------
def clearLines(self):
"""
Clear any complete lines in the matrix. If there are lines to clear,
return list of row numbers of cleared lines, else return False.
"""
rowsCleared = []
for rowNum, blockRow in enumerate(self.blocks):
if not 0 in blockRow:
self.blocks[rowNum] = [ 0 for col in range(self.width) ]
rowsCleared.append(rowNum)
if len(rowsCleared) > 0:
return rowsCleared
else:
return False
def updateGameStats(self, numRowsCleared):
"""
Update game statistics after some rows have been cleared.
"""
self.score += (self.level+1)*numLinesScore[numRowsCleared]
self.totalLinesCleared += numRowsCleared
if (self.level+1) * 10 < self.totalLinesCleared:
self.level += 1
if self.level <= 10:
self.dropDelay = 300 - 20*(self.level)
def reshiftRows(self, rowsCleared):
"""
Shift rows down after some rows have been cleared.
"""
numShifts = 0
for row in rowsCleared:
#Starting from the top line cleared, proceed up every row and
#shift it down once. Repeat for the next top line cleared.
rowNum = row
while rowNum > 0:
self.blocks[rowNum] = self.blocks[rowNum-1]
rowNum -= 1
self.blocks[0] = [ 0 for col in range(self.width) ]
numShifts += 1
def spawnTetronimo(self):
"""
Send the spawn piece into the fray.
"""
spawnSize = len(self.spawn[0])
insertFrom = int((self.width/2) - ((spawnSize+1)/2))
for row in range(spawnSize):
for col in range(spawnSize):
#Insert spawn shape into matrix.
spawnBlock = self.spawn[row][col]
if not spawnBlock == 0:
if self.blocks[row][insertFrom + col] == 0:
#Okay to spawn this cell.
self.blocks[row][insertFrom + col] = spawnBlock
#Update the list of active cells.
self.activeCells.append([row, insertFrom + col])
else:
#Spawn cell clashes with a settled piece. Game over!
self.blocks[row][insertFrom + col] = -1
#Update control data.
self.pieceInPlay = True
self.activeType = self.spawnType
self.activeOrientation = self.spawnOrientation
self.activeTopLeftCorner = [0, insertFrom]
self.spawn = []
self.spawnReady = False
self.spawnType = 0
self.spawnOrientation = 0
self.generateSpawn()
def rotatePlayPiece(self, direction):
"""
Rotate the active piece once in the given direction, if possible.
"""
#If the play piece is 'O', don't do anything.
if not self.activeType == 2:
#Identify list of future active cells.
newPiece = tetronimo[self.activeType]
newActiveCells = []
if direction == ']':
#Clockwise rotation.
for rotation in range((self.activeOrientation + 1)%4):
newPiece = zip(*newPiece[::-1])
newOrientation = (self.activeOrientation+1)%4
elif direction == '[':
#Counter-clockwise rotation.
for rotation in range((self.activeOrientation - 1)%4):
newPiece = zip(*newPiece[::-1])
newOrientation = (self.activeOrientation-1)%4
for row in range(len(newPiece)):
for col in range(len(newPiece[0])):
if not newPiece[row][col] == 0:
newRow = self.activeTopLeftCorner[0]+row
newCol = self.activeTopLeftCorner[1]+col
newActiveCells.append([newRow, newCol])
#First, figure out the obstructive cells of the original
#tetronimo active area (e.g. 3x3 spawn matrix), assuming
#tetronimo hasn't been rotated.
obstructiveCells = []
rotationObstructed = False
if self.activeType == 1:
if direction == ']':
obstructiveCells = [ [0, 0],
[0, 1],
[2, 3],
[3, 3] ]
elif direction == '[':
obstructiveCells = [ [0, 2],
[0, 3],
[2, 0],
[3, 0] ]
#Rotate the obstructive cells to be in alignment with
#actual play piece.
for rotation in range(self.activeOrientation):
for index, cell in enumerate(obstructiveCells):
obstructiveCells[index] = [cell[1], 3-cell[0]]
else:
if direction == ']':
obstructiveCells = [ [0, 0],
[2, 2] ]
elif direction == '[':
obstructiveCells = [ [0, 2],
[2, 0] ]
#Rotate the obstructive cells to be in alignment with
#actual play piece.
for rotation in range(self.activeOrientation):
for index, cell in enumerate(obstructiveCells):
obstructiveCells[index] = [cell[1], 2-cell[0]]
#Now embed these values into the actual matrix.
TLRow = self.activeTopLeftCorner[0]
TLCol = self.activeTopLeftCorner[1]
for index, cell in enumerate(obstructiveCells):
obstructiveCells[index] = [TLRow + cell[0], TLCol + cell[1]]
#Determine whether the obstructive cells or new active cells
#clash with any settled blocks. If not, proceed with rotation.
if (self.checkMovementPossible(obstructiveCells)
and self.checkMovementPossible(newActiveCells)):
self.movePlayPiece(newActiveCells)
#Update control data.
self.activeOrientation = newOrientation
def nudgePlayPiece(self, direction):
"""
Move the active piece once in the given direction, if possible.
"""
#Determine list of future active cells.
newTopLeftCorner = [self.activeTopLeftCorner[0],
self.activeTopLeftCorner[1]]
if direction == '<':
newActiveCells = [ [cell[0], cell[1]-1]
for cell in self.activeCells ]
newTopLeftCorner[1] -= 1
elif direction == '>':
newActiveCells = [ [cell[0], cell[1]+1]
for cell in self.activeCells ]
newTopLeftCorner[1] += 1
elif direction == 'v':
newActiveCells = [ [cell[0]+1, cell[1]]
for cell in self.activeCells ]
newTopLeftCorner[0] += 1
#Check whether new cells constitute an allowed movement. If so,
#move play piece.
if self.checkMovementPossible(newActiveCells):
self.movePlayPiece(newActiveCells)
#Update control data.
self.activeTopLeftCorner = newTopLeftCorner
elif direction == 'v':
#If the requested move is downwards but not possible, lock the
#piece.
self.lockPlayPiece()
def checkMovementPossible(self, newActiveCells):
"""
Return False if list of new active cells clashes with settled
blocks, or lies outside the matrix. Return True otherwise.
"""
for cell in newActiveCells:
if (cell[1] < 0 or
cell[1] > self.width-1 or
cell[0] > self.height-1):
return False
elif (not cell in self.activeCells and
not self.blocks[cell[0]][cell[1]] == 0):
return False
return True
def movePlayPiece(self, newActiveCells):
"""
Rewrite play piece into the new list of active cells. It is
assumed that the movement is valid.
"""
#Write new active cells to matrix.
for cell in newActiveCells:
self.blocks[cell[0]][cell[1]] = self.activeType
#Kill the cells that need to die.
for cell in self.activeCells:
if cell not in newActiveCells:
self.blocks[cell[0]][cell[1]] = 0
#Re-assign list of active cells.
self.activeCells = newActiveCells
def lockPlayPiece(self):
"""
Reset control data and clear any lines that need to be cleared.
"""
self.pieceInPlay = False
self.activeCells = []
self.activeType = 0
self.activeOrientation = 0
self.activeTopLeftCorner = []
rowsCleared = self.clearLines()
if rowsCleared:
self.updateGameStats(len(rowsCleared))
self.reshiftRows(rowsCleared)
|
UTF-8
|
Python
| false | false | 2,014 |
2,637,109,959,247 |
5e05416639aba29557a647a192e1713752a30317
|
f4e856ce0f66a3a4d91bac22f06172ae18d385ee
|
/midterm1.py
|
5c65f261c3f8ef3709f6bd219de2c5bea2dd0fc3
|
[] |
no_license
|
Kswang2400/TCSS142
|
https://github.com/Kswang2400/TCSS142
|
9d474ee94719a6de6809311c794d7ba3ea7470c0
|
4e84a8d7b3f91c740b750a026e58e321eca649c8
|
refs/heads/master
| 2021-01-19T05:28:53.065728 | 2014-12-08T05:01:10 | 2014-12-08T05:01:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
'''
142 Midterm Study Guide
Kevin Wang
'''
from random import randint
# 3. If statements
ticket = int(input("What is the cost of the ticket? "))
stars = int(input("What is the number of stars? "))
def interest(ticket, stars):
if ticket < 5:
print("very interested")
if ticket >= 12:
if stars == 5:
print("sort-of interested")
else:
print("not interested")
if 5 <= ticket < 12:
if 2 <= stars <= 4:
print("sort-of interested")
else:
print("not=interested")
interest(ticket, stars)
# 4. For loops
count = 0
for x in range(10):
num = 2 ** x
count += num
print(count)
average = count/10
print("Average: ", average)
lowBound = int(input("Where do start? "))
terms = int(input("How many terms? "))
count = 0
for x in range(terms):
num = lowBound * 2 ** x
count += num
print(count)
average = count/terms
print("Average: ", average)
# 5. While loops
x= 1
while x < 100:
print(x)
x += 10 # should print 1, 11, 21, 31 ... 91 (10 times)
y = 10
while y < 10:
print("count down: ", y)
y = y -1 # zero times, y does not start less than 10
z = 250
while z % 3 != 0:
print(z) # infinite times, 250 % 3 != 0, no changes to z are made
break
# Pythonian half-life
def decay(amount, rate):
newAmount = amount * (1 - rate/100)
return newAmount
amount = int(input("How much Pythonian? "))
rate = float(input("Rate of decay? "))
half = amount / 2
print("\nInput original mass:", amount)
print("Year Mass")
year = 0
while amount >= half:
amount = decay(amount, rate)
year += 1
print("{} {}".format(year,amount))
# coin flip, three heads in a row
def flip():
flip = randint(1, 2)
if flip == 1:
coin = "H"
else:
coin = "T"
return coin
def threeInRow():
results = []
counter = 0
while counter < 3:
HT = flip()
results.append(HT)
# print(results)
if HT == "H":
counter += 1
# print("counter", counter)
else:
counter = 0
print(results)
print("Congrats, three H in a row!")
threeInRow()
|
UTF-8
|
Python
| false | false | 2,014 |
16,346,645,548,483 |
82787d49288c7dbbc52ad4e34bddd2ec7e8194a8
|
76b483ef8b16ca8a3f772a108670125dd1c90332
|
/Sphere_Volume.py
|
46128c1b0fdeae6b2bd52115f254367266030ed3
|
[] |
no_license
|
bitcoinsoftware/3D-Scientific-Visualization
|
https://github.com/bitcoinsoftware/3D-Scientific-Visualization
|
e201e2842c4c854dcb0465341f3f817ff0a99f39
|
93a7d5dc930a5a2ab8fab6baff2817e0d37645d7
|
refs/heads/master
| 2021-01-15T22:28:57.738058 | 2013-08-29T08:30:58 | 2013-08-29T08:30:58 | 12,454,956 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import vtk
from Rendered_Object import *
class Sphere_Volume_Actor(Rendered_Object):
name="Sphere_Volume"
def __init__(self,data_reader):
# Create a colorscale lookup table
self.lut=vtk.vtkLookupTable()
self.lut.SetNumberOfColors(256)
self.lut.SetTableRange(data_reader.get_scalar_range())
self.lut.SetHueRange(0,1)
self.lut.SetRange(data_reader.get_scalar_range())
self.lut.Build()
self.arrow=vtk.vtkSphereSource()
#self.arrow.SetTipResolution(6)
self.arrow.SetRadius(0.4)
#self.arrow.SetTipLength(0.35)
#self.arrow.SetShaftResolution(6)
#self.arrow.SetShaftRadius(0.03)
self.glyph=vtk.vtkGlyph3D()
self.glyph.SetInput(data_reader.get_data_set())
self.glyph.SetSource(self.arrow.GetOutput())
self.glyph.SetColorModeToColorByScalar()
self.glyph.SetScaleModeToScaleByScalar()
#self.glyph.OrientOn()
self.glyph.SetScaleFactor(0.006)
mapper=vtk.vtkPolyDataMapper()
mapper.SetInput(self.glyph.GetOutput())
mapper.SetLookupTable(self.lut)
mapper.ScalarVisibilityOn()
mapper.SetScalarRange(data_reader.get_scalar_range())
self.actor=vtk.vtkActor()
self.actor.SetMapper(mapper)
|
UTF-8
|
Python
| false | false | 2,013 |
17,892,833,769,761 |
4fbc5b5dfbd64817d992bac3ecd596d1347df3d4
|
49e388549ec3bdeb1bd5f3c14f70d0bf77b16d20
|
/openmoc/__init__.py
|
152c3688b9b65637c05203f4abd63447c5175759
|
[] |
no_license
|
mjlong/OpenMOC
|
https://github.com/mjlong/OpenMOC
|
e304f6c1a1a87fba32733407d1aaba1f0464cd86
|
085bafdcb10ee21dba79b21977aa02dca5333edc
|
refs/heads/master
| 2020-12-11T03:26:42.954447 | 2014-09-16T15:15:11 | 2014-09-16T15:15:11 | 24,104,654 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import sys, os
import random
import datetime
import signal
# For Python 2.X.X
if (sys.version_info[0] == 2):
from openmoc import *
# For Python 3.X.X
else:
from openmoc.openmoc import *
# Tell Python to recognize CTRL+C and stop the C++ extension module
# when this is passed in from the keyboard
signal.signal(signal.SIGINT, signal.SIG_DFL)
# Set a log file name using a date and time
now = datetime.datetime.now()
current_time = str(now.month) + '-' + str(now.day) + '-' + str(now.year) + '--'
current_time = current_time + str(now.hour) + ':' + str(now.minute)
current_time = current_time + ':' + str(now.second)
set_log_filename('log/openmoc-' + current_time + '.log');
Timer = Timer()
|
UTF-8
|
Python
| false | false | 2,014 |
6,030,134,104,123 |
331983a10de7dcff5ecd7940f6d65b7eb3d6823b
|
823b3f23ae591a16c888da06ad6b7da4c41ff245
|
/concepts/visualize.py
|
3aeb7156e0bff95e975d73ad6a468834b1f45268
|
[
"MIT"
] |
permissive
|
iSTB/concepts
|
https://github.com/iSTB/concepts
|
aa411060ee37ddac924cff374f6e1274d0b1fda4
|
2373a6a07038dffe4154f6ba725309167582a816
|
refs/heads/master
| 2021-01-18T07:23:54.299901 | 2014-05-28T10:10:25 | 2014-05-28T10:10:25 | 20,228,084 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# visualize.py - convert lattice to graphviz dot
import os
import glob
import graphviz
__all__ = ['lattice', 'render_all']
SORTKEYS = [lambda c: c.index]
NAME_GETTERS = [lambda c: 'c%d' % c.index]
def lattice(lattice, filename, directory, render, view):
"""Return graphviz source for visualizing the lattice graph."""
dot = graphviz.Digraph(
name=lattice.__class__.__name__,
comment=repr(lattice),
filename=filename,
directory=directory,
node_attr=dict(shape='circle', width='.25', style='filled', label=''),
edge_attr=dict(dir='none', labeldistance='1.5', minlen='2')
)
sortkey = SORTKEYS[0]
node_name = NAME_GETTERS[0]
for concept in lattice._concepts:
name = node_name(concept)
dot.node(name)
if concept.objects:
dot.edge(name, name,
headlabel=' '.join(concept.objects),
labelangle='270', color='transparent')
if concept.properties:
dot.edge(name, name,
taillabel=' '.join(concept.properties),
labelangle='90', color='transparent')
dot.edges((name, node_name(c))
for c in sorted(concept.lower_neighbors, key=sortkey))
if render or view:
dot.render(view=view) # pragma: no cover
return dot
def render_all(filepattern='*.cxt', frmat=None, directory=None, out_format=None):
from concepts import Context
if directory is not None:
get_name = lambda filename: os.path.basename(filename)
else:
get_name = lambda filename: filename
if frmat is None:
from concepts.formats import Format
get_frmat = Format.by_extension.get
else:
get_frmat = lambda filename: frmat
for cxtfile in glob.glob(filepattern):
name, ext = os.path.splitext(cxtfile)
filename = '%s.gv' % get_name(name)
c = Context.fromfile(cxtfile, get_frmat(ext))
l = c.lattice
dot = l.graphviz(filename, directory)
if out_format is not None:
dot.format = out_format
dot.render()
|
UTF-8
|
Python
| false | false | 2,014 |
10,376,640,993,903 |
00f9f47b5dcb8e6ee7ff76568277520c050bc2c3
|
93f80dc9ff475a1e1b8465205d75e0bf876d3d44
|
/setup.py
|
e56c12807329dce0bb385b905594bd717863d3f4
|
[
"GPL-3.0-only"
] |
non_permissive
|
yuxiaobu/nansat
|
https://github.com/yuxiaobu/nansat
|
99b9095c37f3a994d2bc52dfd073404208cb0b33
|
6f8e32d899bd6222479c8cab7d72cc82e4ad9780
|
refs/heads/master
| 2021-01-15T17:35:56.420004 | 2013-11-22T12:46:30 | 2013-11-22T12:46:30 | 14,798,150 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#-----------------------------------------------------------------------------
# Name: setup.py
# Purpose:
#
# Author: asumak
#
# Created: 17.06.2013
# Copyright: (c) asumak 2012
# Licence: <your licence>
# ========= !! NB !! HOW TO DO FOR MAC USERS?? ==========
#-----------------------------------------------------------------------------
import os
from subprocess import Popen
import subprocess
import sys
NAME = 'nansat'
MAINTAINER = "Nansat Developers"
MAINTAINER_EMAIL = "numpy-discussion@scipy.org"
DESCRIPTION = "***" # DOCLINES[0]
LONG_DESCRIPTION = "***" # "\n".join(DOCLINES[2:])
URL = "http://normap.nersc.no/"
DOWNLOAD_URL = "http://normap.nersc.no/"
LICENSE = '***'
CLASSIFIERS = '***' # filter(None, CLASSIFIERS.split('\n'))
AUTHOR = ("Asuka Yamakawa, Anton Korosov, Morten W. Hansen, Kunt-Frode Dagestad")
AUTHOR_EMAIL = "asuka.yamakawa@nersc.no"
PLATFORMS = ["UNKNOWN"]
MAJOR = 1
MINOR = 0
MICRO = 0
ISRELEASED = True
VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO)
osName = sys.platform
myNansatDir = os.getcwd()
""" !! NB: How to do for Mac ?? """
if not('win' in osName):
myHomeDir = os.environ.get("HOME")
index = myNansatDir.rfind(myHomeDir)
myNansatDir = myNansatDir[index:]
#----------------------------------------------------------------------------#
# Set environment variables
#----------------------------------------------------------------------------#
if 'win' in osName:
dicDir = {'PYTHONPATH': "\\mappers",
'GDAL_DRIVER_PATH': "\\pixelfunctions"}
for iKey in dicDir.keys():
# check if iKey (environment variable) exist
command = ("set %s" % iKey)
val = Popen(command, shell=True, stdout=subprocess.PIPE)
stdout_value = val.communicate()[0]
# if iKey does not exists
if stdout_value == "":
# command to add new environment variable
myNansatDir = myNansatDir.replace("/", "\\")
command = ("setx %s %s%s" % (iKey, myNansatDir, dicDir[iKey]))
# if iKey exist
else:
# if the folder is not registered yet
if stdout_value.find(myNansatDir + dicDir[iKey]) == -1:
oldPath = stdout_value.replace("/", "\\").\
rstrip().split('=')[1]
newPath = (myNansatDir + dicDir[iKey]).replace("/", "\\")
# command to replace oldfolder to (oldfolder+addFolder)
command = ('setx %s %s;%s' % (iKey, oldPath, newPath))
else:
command = ''
if command != '':
process = Popen(command, shell=True, stdout=subprocess.PIPE)
process.stdout.close()
""" !! NB: How to do for Mac ?? """
else:
dicDir = {'PYTHONPATH': "/mappers", 'GDAL_DRIVER_PATH': "/pixelfunctions"}
for iKey in dicDir.keys():
# check if iKey (environment variable) exist
command = ("grep '%s' .bashrc" % iKey)
val = Popen(command, cwd=myHomeDir, shell=True, stdout=subprocess.PIPE)
stdout_value = val.communicate()[0]
# if iKey does not exists
if stdout_value == "":
# command to add new environment variable
command = ("echo 'export %s=%s%s' >> .bashrc" % (iKey,
myNansatDir,
dicDir[iKey]))
# if iKey exist
else:
# if the folder is not registered yet
if stdout_value.find(myNansatDir + dicDir[iKey]) == -1:
command = ('echo "export %s=\$%s:%s" >> .bashrc' %
(iKey, iKey, myNansatDir + dicDir[iKey]))
else:
command = ""
if command != "":
process = Popen(command, cwd=myHomeDir, shell=True,
stdout=subprocess.PIPE)
process.stdout.close()
#----------------------------------------------------------------------------#
# Copy files
#----------------------------------------------------------------------------#
from distutils.core import setup
setup(
name=NAME,
maintainer=MAINTAINER,
maintainer_email=MAINTAINER_EMAIL,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
url=URL,
download_url=DOWNLOAD_URL,
license=LICENSE,
classifiers=CLASSIFIERS,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
platforms=PLATFORMS,
package_dir={NAME: ''},
packages={NAME, NAME + '.mappers'},
package_data={NAME: ['wkv.xml', "fonts/*.ttf", "pixelfunctions/*"]},
)
|
UTF-8
|
Python
| false | false | 2,013 |
17,162,689,329,625 |
a19bf9df8f241ddd18eaf88bacb547b176a0fbe3
|
17dfcbb6f25c101ca16a0cae866b67afaacd36c6
|
/doublelink/double_link.py
|
19e4f0fa983be677b9a9a86f486802c3422937c8
|
[] |
no_license
|
johnshiver/data-structures
|
https://github.com/johnshiver/data-structures
|
aafbc6216f21a6a76222e195a722decb0fa8a72e
|
8e65271e8cca20eb54d5d225a20f8b73d66079d3
|
refs/heads/master
| 2017-12-22T04:35:23.885755 | 2014-07-16T04:53:10 | 2014-07-16T04:53:10 | 20,502,246 | 2 | 3 | null | false | 2014-07-20T05:57:08 | 2014-06-04T21:51:53 | 2014-06-30T19:44:47 | 2014-07-20T05:56:22 | 1,888 | 0 | 0 | 6 |
Python
| null | null |
"""Implements a double-linked list data structure"""
class Node(object):
def __init__(self, node_name, node_next=None, node_prev=None):
self.node_name = node_name
self.node_next = node_next
self.node_prev = node_prev
class Double_list(object):
def __init__(self):
self.list_ptr = None
def pop(self):
return_value = self.list_ptr.node_name
self.list_ptr = self.list_ptr.node_next
self.list_ptr.node_prev = None
return return_value
def shift(self):
temp = self.list_ptr
while temp.node_next:
temp = temp.node_next
return_value = temp.node_name
temp = temp.node_prev
temp.node_next = None
return return_value
def insert(self, node_name):
# the new head should point to the old head
if not self.list_ptr:
self.list_ptr = Node(node_name)
else:
temp = self.list_ptr
self.list_ptr = Node(node_name, temp)
temp.node_prev = self.list_ptr
def append(self, node_name):
temp = self.list_ptr
while temp.node_next:
temp = temp.node_next
temp.node_next = Node(node_name, None, temp)
def remove(self, value):
temp = self.list_ptr
try:
while temp.node_name != value:
temp = temp.node_next
except AttributeError:
raise AttributeError
else:
temp.node_next.node_prev = temp.node_prev
temp.node_prev.node_next = temp.node_next
|
UTF-8
|
Python
| false | false | 2,014 |
11,785,390,274,874 |
a1b37451dabe91635cbd5a58fe5b47f71c607dee
|
9a4786bd0eb31c24441b0d85ad7163fe45a15032
|
/MiniP/motif_finder.py
|
8455ae8e2736efa00bc9c1be9aa690a4edf10149
|
[] |
no_license
|
JBetz/466-Bioinformatics
|
https://github.com/JBetz/466-Bioinformatics
|
96dc58188513cff237bbd074940167d3c14513d9
|
e116a518226f88999333718735ed4b0d6b35029e
|
refs/heads/master
| 2016-08-04T23:12:03.655881 | 2014-05-11T16:39:26 | 2014-05-11T16:39:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# python packages
import random
import datetime
import sys
# original packages
import globals
import directory
import reader
import writer
import profile_matrix
import probability_matrix
import position_weights
def findMotif(sequences, motifLength, iterations):
# initialize global sequence and motif variables
globals.initialize(sequences, motifLength)
# choose a random motif position for each unchosen sequence
positions = chooseMotifPositions()
# initialize iteration variables
currentInformationContent = 0.0
bestInformationContent = 0.0
profileMatrix = []
probabilityMatrix = []
positionWeights = []
normalizedPositionWeights = []
bestPositions = []
bestProfileMatrix = []
for iteration in range(0, iterations):
for unchosenSequenceIndex in range(0, len(sequences)):
# count residue and background occurences for each position for all unchosen sequences
profileMatrix = profile_matrix.createProfileMatrix(positions, unchosenSequenceIndex)
# determine residue and background probabilities
probabilityMatrix = probability_matrix.createProbabilityMatrix(profileMatrix)
# calculate weight for each possible motif position in the chosen sequence
positionWeights = position_weights.calculatePositionWeights(probabilityMatrix)
# normalize position weights
normalizedPositionWeights = position_weights.normalizePositionWeights(positionWeights)
# randomly choose position based on normalized probabilities
positions[unchosenSequenceIndex] = position_weights.choosePosition(normalizedPositionWeights)
# recalculate profile and probability matrix
profileMatrix = profile_matrix.createProfileMatrix(positions, -1)
probabilityMatrix = probability_matrix.createProbabilityMatrix(profileMatrix)
# calculate information content of current sample
currentInformationContent = probability_matrix.calculateInformationContent(probabilityMatrix, positions)
# update best sample if current has greater information content
if currentInformationContent > bestInformationContent:
bestInformationContent = currentInformationContent
bestPositions = list(positions)
bestProfileMatrix = list(profileMatrix)
# update unchosen sequence value for next iteration
if unchosenSequenceIndex < (len(sequences) - 1):
globals.unchosenSequence = sequences[unchosenSequenceIndex + 1]
return [bestPositions, bestProfileMatrix, bestInformationContent]
def chooseMotifPositions():
positions = []
for x in range(0, globals.numberOfSequences):
positions.append(random.randint(0, globals.lengthOfSequences - globals.motifLength))
return positions
if __name__ == "__main__":
print "\nRunning motif finder..."
print "-----------------------" + '\n'
startTime = datetime.datetime.now()
print "start time = " + str(startTime) + '\n'
# create array of motif length text files
motifLengthFiles = directory.getFiles('motiflength.txt')
sequencesFiles = directory.getFiles('sequences.fa')
numberOfFiles = len(motifLengthFiles)
# iterate over arrays
informationContent = 0
for x in range(0, numberOfFiles):
sequencesFile = sequencesFiles[x]
motifLengthFile = motifLengthFiles[x]
sequences = reader.readFastaFile(sequencesFile)
motifLength = reader.readMotifLengthFile(motifLengthFile)
output = findMotif(sequences, motifLength, int(sys.argv[1]))
informationContent += output[2]
writer.writePredictions(output, sequencesFile, motifLength)
print "files written for " + str(sequencesFile)
if (x + 1) % 10 == 0:
print "\naverage information content for this set: " + str(informationContent/10) + '\n'
informationContent = 0
endTime = datetime.datetime.now()
print "\nend time = " + str(endTime)
print "run time = " + str(endTime - startTime)
print "\n---------------------"
print "Motif finder complete" + '\n'
#for each of the 70 subdirectories does the following
#reads in motiflength.txt and sequences.fa
#performs motif finding algorith on input to generate pwm, and find binding site in each sequence
#
#writes predicted location of binding site in each sequence to "predictedsites.txt" (format tbd, same as sites.txt)
#writes pwm to "predictedmotif.txt" refer to instruction doc
|
UTF-8
|
Python
| false | false | 2,014 |
3,289,944,971,843 |
264a8071ee670fee61cd44b77e23c7d1ed3f2eb6
|
af7e4bd5e0f6badf79635ec4b1f58b0e3f33bda6
|
/euler3.py
|
66ecba2a3c84a4e182651080fb53ac36c6a5587d
|
[] |
no_license
|
Shadaez/euler
|
https://github.com/Shadaez/euler
|
49f4f071a5593e1b5f3265b440691a24e8882867
|
b8e2d5395804ed261fcefc5eb8a90eff59f90ac0
|
refs/heads/master
| 2021-01-22T13:46:59.443721 | 2012-11-17T19:36:01 | 2012-11-17T19:36:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
n = 600851475143
factors = []
def poop(p):
y = []
x = 1
while x < p**.5:
if p%x == 0:
y.append(x)
x += 1
return y
def isPrime(o):
x = 2
while x <= o**.5:
if o%x == 0:
return False
x += 1
else:
return True
factors = poop(n)
print factors
print len(factors)
while not isPrime(factors[len(factors)-1]):
print factors[len(factors)-1]
factors.pop(len(factors)-1)
else:
print factors
|
UTF-8
|
Python
| false | false | 2,012 |
10,075,993,299,831 |
f4b93950942ef33456ead39b2b989d5af5562cd5
|
5132523a3d986e7a231e7155ee2aefab15b71672
|
/EtcWatch/Action/example.py
|
08d28f993aaccbdab12c949c2f0abf1278c3de1e
|
[] |
no_license
|
bwillis81/etcwatch
|
https://github.com/bwillis81/etcwatch
|
12139e76b45e0d003df3e92ec223428fe6fca26b
|
05495710e56502fd42959226ce8b48818db88c8a
|
refs/heads/master
| 2019-09-02T07:12:30.197539 | 2014-11-23T16:39:16 | 2014-11-23T16:39:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from EtcWatch.Helper import OK, ERROR
EXAMPLE = """[core]
email = true
# smtp server examples: localhost, or server.tld:587
smtp = localhost
#emailfrom = custom@from.address
[files]
## format: FILE_TO_WATCH = GROUP_TO_EMAIL
# /etc/some/file = sysadmin
# /etc/some/other/file = devs
[perms]
## format: FILE_TO_WATCH = PERMISSIONS
# /etc/some/file_or_dir = 644
[groups]
## format: GROUP_NAME = EMAIL_ADDRESSES
# sysadmin = tim@x
# devs = bob@x, gary@x, will@x
"""
def example(verbose=False):
print EXAMPLE
return OK
|
UTF-8
|
Python
| false | false | 2,014 |
17,566,416,241,398 |
498556985a9750c9c0956a3e5276d5df82dc4812
|
f9e338ac1118ed0989421e2ae306184e33a34a8f
|
/getdata_element.py
|
51121444007c59c5ec93c9d7f8d8aead1eda421b
|
[] |
non_permissive
|
romali/ajax_show_stock
|
https://github.com/romali/ajax_show_stock
|
4863ed6015df7d5d7d1c82104244c23bfc9824ba
|
2d11352aa27601418f1d4c2e7cee9df03a5cbe4c
|
refs/heads/master
| 2020-02-28T11:08:54.572132 | 2013-10-13T06:45:04 | 2013-10-13T06:45:04 | 23,050,845 | 0 | 1 |
NOASSERTION
| false | 2020-11-20T08:40:07 | 2014-08-17T21:24:45 | 2015-10-10T17:00:45 | 2013-10-13T06:45:24 | 424 | 0 | 1 | 1 | null | false | false |
#!/usr/local/bin/python
#coding=utf-8
'''
Element14 SOAP
WebService地址:
https://hk.element14.com/pffind/services/SearchService?wsdl
https://hk.element14.com/pffind/services/SearchService
User name : 24067
Password : HaWkPengsheng72BuLlS
本接口的实现需要 SOAPpy 模块,如果系统没有安装可以运行下面命令来安装。
$ sudo easy_install fpconst
$ sudo easy_install soappy
'''
#import memcache
import SOAPpy11 as SOAPpy
from SOAPpy11 import SOAPProxy
from SOAPpy11 import WSDL
from SOAPpy11 import headerType ,DictType
import hmac
import base64
import datetime
from mouser_settings import keys_mouser_tt
key = 'HaWkPengsheng72BuLlS'
url = 'https://hk.element14.com/pffind/services/SearchService'
namespace = "http://pf.com/soa/services/v1"
soapaction= "https://hk.element14.com/pffind/services/SearchService"
class MsgException(BaseException):
pass
def get_timestamp():
#x = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
now =datetime.datetime.now() - datetime.timedelta(hours= 8)
x = now.strftime("%Y-%m-%dT%H:%M:%S")
return "%s.198" %x
def get_signature(operate_name, timestamp):
"""
获取signature
operate_name: 为操作名,如:searchByKeyword
timestamp: 为时间戳,如:2011-10-13T05:38:18.198
"""
signature_base_string = operate_name + timestamp
try:
import hashlib
hashed = hmac.new(key, signature_base_string, hashlib.sha1)
except:
import sha
hashed = hmac.new(key, signature_base_string, sha)
return base64.b64encode(hashed.digest())#
class GetDataFromElement(object):
def __init__(self, keyword):
'''
港元对美元的汇率 访问这个网址可以查询
http://www.baidu.com/s?ie=utf-8&bs=港元兑美元&f=8&rsv_bp=1&rsv_spt=3&wd=港元兑美元&inputT=0
'''
self.huilv_hk_us = 0.1288#最后更新时间 2013年 04月 26日 星期五 11:14:53 CST
self.keyword = keyword
SOAPpy.Config.buildWithNamespacePrefix = 0
SOAPpy.Config.debug = 0 #0禁止调试信息
SOAPpy.Config.dumpHeadersOut = 0 #调试信息
SOAPpy.Config.dumpSOAPOut = 0
SOAPpy.Config.dumpSOAPIn = 0
self.customerid = 24067
#self.locale = 'en_CN'
self.locale = 'en_HK'
self.server_url="https://hk.element14.com/pffind/services/SearchService"
#soapaction="https://hk.element14.com/pffind/services/SearchService",
timestamp = get_timestamp()
operate_name = 'searchByKeyword'
signature = get_signature(operate_name,timestamp)
data = {'v1:userInfo':{"v1:signature": signature,
"v1:timestamp": timestamp,
"v1:locale": self.locale,
},
'v1:accountInfo':{"v1:customerId": self.customerid,}
}
hd = headerType(data = data)
self.server=SOAPProxy(self.server_url, namespace="http://pf.com/soa/services/v1", \
noroot=1, header=hd)
self.server.soapaction="https://hk.element14.com/pffind/services/SearchService"
def searchByKeyword(self, offset=0, numberOfResults=5):
"""根据型号关键字搜索结果
keyword: 型号关键字
offset: 返回结果集开始索引
numberOfResults: 最多显示条数
返回:data 一个products结果集
"""
'''
<soapenv:Header>
<v1:userInfo>
<v1:signature>lSZqdtXpws6VODO1tCeMToqsPZQ=</v1:signature>
<v1:timestamp>2011-10-13T09:30:18.198</v1:timestamp>
<v1:locale>en_HK</v1:locale>
</v1:userInfo>
<v1:accountInfo>
<!--You have a CHOICE of the next 3 items at this level-->
<v1:customerId>24067</v1:customerId>
<v1:contractId></v1:contractId>
<v1:billingAccountNo></v1:billingAccountNo>
</v1:accountInfo>
</soapenv:Header>
<body>
<v1:keywordParameter>
<v1:keyword>avr</v1:keyword>
<v1:offset>0</v1:offset>
<v1:numberOfResults>25</v1:numberOfResults>
...
</v1:keywordParameter>
</body>
timestamp = get_timestamp()
operate_name = 'searchByKeyword'
signature = get_signature(operate_name,timestamp)
data = {'v1:userInfo':{"v1:signature": signature,
"v1:timestamp": timestamp,
"v1:locale": self.locale,
},
'v1:accountInfo':{"v1:customerId": self.customerid,}
}
hd = headerType(data = data)
self.server=SOAPProxy(self.server_url, namespace="http://pf.com/soa/services/v1", \
noroot=1, header=hd)
self.server.soapaction="https://hk.element14.com/pffind/services/SearchService"
'''
searchdata = {'v1:keywordParameter':{'v1:keyword': self.keyword,
'v1:offset': offset,
'v1:numberOfResults': numberOfResults,
},
}
data = self.server.searchByKeyword(**searchdata)
if data == '0':
return []
data = data.products
if not isinstance(data, list):
data = [data]
return data
def getdatainfo(self):
"""
返回list_finall的三种格式:
1. [None,{'html':html}]
2. ['similar',{'similar partno':[[sp,sp_url],...],'html':html},...]
3. ['exact',{'mp':mp,'price':price,...},...]
4. ['no_result',{'html':html}]
每个字典元素的的键字存在于列表useful_keys_mouser_tt = ['Manufacturer','Description','Lifecycle',
'Stock', 'On Order', 'Factory Lead-Time',
'Minimum','Multiples','Price','Reel','More']
"""
data = self.searchByKeyword()
list_finall = []
if not data:
list_finall = ['no_result', {}]
else:
list_finall.append('exact')
for d in data:
d_dict = self.getdatainfo_one(d)
partno = d_dict['Manufacturer Part']
if self.keyword == partno:
#continue
list_finall.append(d_dict)
if len(list_finall) == 1:
list_finall = ['similar']
for d in data:
d_dict = self.getdatainfo_one(d)
list_finall.append(d_dict)
return list_finall
def getdatainfo_one(self, d):
d_dict = {}
''' 调用keys_mouser_tt变量的内容 避免手动写死 2012年 12月 31日 星期一 13:30:56 CST '''
d_dict[keys_mouser_tt[14][1]] = '%s / package' % d.packSize#添加包装个数 edit by daimingming on 2013年 01月 24日 星期四 17:44:17 CST
#d_dict['Manufacturer Part'] = d.translatedManufacturerPartNumber
d_dict[keys_mouser_tt[1][1]] = d.translatedManufacturerPartNumber
#d_dict['Manufacturer'] = d.brandName
d_dict[keys_mouser_tt[2][1]] = d.brandName
#d_dict['Stock'] = d.inv
d_dict[keys_mouser_tt[5][1]] = d.inv
''' Stock_info 显示效果较乱 并且不被调用 所以可不返回 2012年 12月 31日 星期一 13:34:14 CST '''
#d_dict['Stock_info'] = d.stock.regionalBreakdown
#d_dict['Minimum'] = d.translatedMinimumOrderQuality
d_dict[keys_mouser_tt[8][1]] = d.translatedMinimumOrderQuality
#d_dict['Reel'] = d.reeling
d_dict[keys_mouser_tt[11][1]] = d.reeling
#d_dict['Rohs'] = d.rohsStatusCode
d_dict[keys_mouser_tt[24][1]] = d.rohsStatusCode
#element14_ordercode xf edit this by 2013 05 27
d_dict[keys_mouser_tt[18][1]] = d.sku
#d_dict[keys_mouser_tt[32][1]] = d.sku
#element14_countryOfOrigin xf edit this by 2013 05 27
d_dict[keys_mouser_tt[34][1]] = d.countryOfOrigin
#d_dict[keys_mouser_tt[33][1]] = d.countryOfOrigin
price_str = ''
try:
prices = d.prices
try:
price_str = '%s:$%s' % (prices['from'], float(prices['cost']) * self.huilv_hk_us)
except:
for one in prices:
price_str += '%s:$%s|||' % (one['from'], float(one['cost']) * self.huilv_hk_us)
if price_str and price_str[-3:] == '|||':
price_str = price_str[:-3]
except:
pass
#d_dict['Price'] = price_str
d_dict[keys_mouser_tt[10][1]] = price_str
return d_dict
def parse_msg(self, data):
"""分析searchByKeyword返回的数据"""
attr_list = [u'attributes', u'brandId', u'brandName', u'comingSoon', u'commodityClassCode', u'countryOfOrigin', u'datasheets', u'discountReason', u'displayName', u'id', u'image', u'inv', u'isAwaitingRelease', u'isSpecialOrder', u'packSize', u'prices', u'productStatus', u'publishingModule', u'reeling', u'releaseStatusCode', u'rohsStatusCode', u'sku', u'stock', u'translatedManufacturerPartNumber', u'translatedMinimumOrderQuality', u'translatedPrimaryCatalogPage', u'unitOfMeasure', u'vatHandlingCode', u'vendorId', u'vendorName', u'related']
for d in data:
print '=' * 80
for one in attr_list:
try:
exec('value = d.%s' % one)
print '%s ---- %s' % (one, value)
except:
pass
print '===== prices (from ---- to: cost) ====='
try:
prices = d.prices
try:
print '%s ---- %s: %s' % (prices['from'], prices['to'], prices['cost'])
except:
for one in prices:
print '%s ---- %s: %s' % (one['from'], one['to'], one['cost'])
except:
pass
try:
print '===== stock ====='
stock = d.stock
stock_attr = [u'breakdown', u'leastLeadTime', u'level', u'nominatedWarehouseDetails', u'regionalBreakdown', u'shipsFromMultipleWarehouses', u'status']
for s_one in stock_attr:
exec('value = stock.%s' % s_one)
print '%s ---- %s' % (s_one, value)
except:
pass
try:
print '===== attributes ====='
attributes = d.attributes
for one in attributes:
print '%s ---- %s' % (one.attributeLabel, one.attributeValue)
except:
pass
def searchByManufacturerPartNumber(self, keyword):
"""根据厂商型号关键字搜索结果
keyword: 型号关键字
返回:data 一个products结果集
"""
'''
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope
soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:v1="http://pf.com/soa/services/v1"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/1999/XMLSchema"
>
<soapenv:Header>
<v1:userInfo>
<v1:locale>en_HK</v1:locale>
<v1:timestamp>2011-10-18T08:56:40.198</v1:timestamp>
<v1:signature>UUS1qJ4i1eljxe4aPiIqKhTZXMI=</v1:signature>
</v1:userInfo>
<v1:accountInfo>
<v1:customerId>24067</v1:customerId>
</v1:accountInfo>
</soapenv:Header>
<soapenv:Body>
<v1:manufacturerPartNumber>
<v1:ManufacturerPartNumber>LTC2630AHSC6</v1:ManufacturerPartNumber>
</v1:manufacturerPartNumber>
</soapenv:Body>
</soapenv:Envelope>
'''
timestamp = get_timestamp()
operate_name = 'searchByManufacturerPartNumber'
signature = get_signature(operate_name,timestamp)
data = {'v1:userInfo':{"v1:signature": signature,
"v1:timestamp": timestamp,
"v1:locale": self.locale,
},
'v1:accountInfo':{"v1:customerId": self.customerid,}
}
hd = headerType(data = data)
self.server=SOAPProxy(self.server_url, namespace="http://pf.com/soa/services/v1", \
noroot=1, header=hd)
self.server.soapaction="https://hk.element14.com/pffind/services/SearchService"
searchdata = {'v1:manufacturerPartNumber':{'v1:ManufacturerPartNumber': keyword, }, }
data = self.server.searchByManufacturerPartNumber(**searchdata)
data = data.products
if not isinstance(data, list):
data = [data]
return data
def searchByPremierFarnellPartNumber(self, keyword):
"""根据厂商型号关键字搜索结果
keyword: 型号关键字
返回:data 一个products结果集
"""
'''
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope
soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:v1="http://pf.com/soa/services/v1"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/1999/XMLSchema"
>
<soapenv:Header>
<v1:userInfo>
<v1:locale>en_HK</v1:locale>
<v1:timestamp>2011-10-18T09:15:44.198</v1:timestamp>
<v1:signature>qk3ZOxzi30Qv/Aj/wXTkgH7fLBc=</v1:signature>
</v1:userInfo>
<v1:accountInfo>
<v1:customerId>24067</v1:customerId>
</v1:accountInfo>
</soapenv:Header>
<soapenv:Body>
<v1:premierFarnellPartNumber>
<v1:Sku>LTC2630AHSC6</v1:Sku>
</v1:premierFarnellPartNumber>
</soapenv:Body>
</soapenv:Envelope>
'''
timestamp = get_timestamp()
operate_name = 'searchByPremierFarnellPartNumber'
signature = get_signature(operate_name,timestamp)
data = {'v1:userInfo':{"v1:signature": signature,
"v1:timestamp": timestamp,
"v1:locale": self.locale,
},
'v1:accountInfo':{"v1:customerId": self.customerid,}
}
hd = headerType(data = data)
self.server=SOAPProxy(self.server_url, namespace="http://pf.com/soa/services/v1", \
noroot=1, header=hd)
self.server.soapaction="https://hk.element14.com/pffind/services/SearchService"
searchdata = {'v1:premierFarnellPartNumbers':{'v1:Sku': keyword, }, }
data = self.server.searchByManufacturerPartNumber(**searchdata)
data = data.products
if not isinstance(data, list):
data = [data]
return data
def quick():
## CODE
import SOAPpy
test = 42
server=SOAPProxy(url, namespace="http://pf.com/soa/services/v1", noroot=1, \
soapaction="https://hk.element14.com/pffind/services/SearchService")
server = server._sa ("urn:soapinterop")
hd = server.Header()
hd.InteropTestHeader ='This should fault, as you don\'t understand the header.'
hd._setMustUnderstand ('InteropTestHeader', 0)
hd._setActor ('InteropTestHeader','http://schemas.xmlsoap.org/soap/actor/next')
server = server._hd (hd)
## /CODE
def main():
'''
这个是可以被外部调用的接口
'''
#使用方法有两种 这是其中一种先初始化一个类的方法
print '* '*20
keyword = 'MK10DX256ZVLQ10'
p = GetDataFromElement(keyword)
info = p.getdatainfo()
print info
xz = raw_input(382)
keyword = 'MK10DX256ZVLQ10R'
p = GetDataFromElement(keyword)
info = p.getdatainfo()
print info
#quick()
if __name__ == '__main__':
#main()#ok
s = """
注意 webservice请求的是hk.element14.com;与cn.element14.com查询结果有区别
MK10DX256ZVLQ10 一个精确匹配
MK10DX256ZVLQ10R 一个精确匹配
1V5KE110A 一个精确匹配
1.5KE100A 三个精确匹配
1.5KE110A-E3/23 没有匹配
"""
print s
''' 下面程序只能成功查询一个型号 不知为何 '''
while 1:
while 1:
mmp = raw_input('please enter the element14 part: ')
if len(mmp) >= 4:
break
else:
print 'count of part must >= 4'
t_sta = datetime.datetime.now()
keyword = mmp
chaxun = GetDataFromElement(keyword)
list_finall = chaxun.getdatainfo()
t_end = datetime.datetime.now()
print 'time: ',t_end - t_sta
if not list_finall:
print 'can not get information of cn.element14.com'
else:
print '462 status:',list_finall[0]
for one_info in list_finall[1:]:
print '*' * 20
for k,v in one_info.items():
print k,' ',v
xz = raw_input(440)
|
UTF-8
|
Python
| false | false | 2,013 |
2,379,411,886,346 |
8d9d994cfc5cf5ddbbb9b661de4aba81d3a9ed66
|
350f37337d26ad8d1fc0a31f9e4e50e4a4f63363
|
/carcade/i18n.py
|
e310fd29caef3130afd63001ee613128bb8bdb6f
|
[
"BSD-2-Clause"
] |
permissive
|
aromanovich/carcade
|
https://github.com/aromanovich/carcade
|
d6d0e331dbe7881f88098c16f2913666bf0ebbce
|
35a9e0017177b2300e31b9a2700ac3f13f96bef2
|
refs/heads/master
| 2020-04-26T01:38:28.348268 | 2014-05-19T18:46:13 | 2014-05-19T18:46:13 | 7,487,482 | 3 | 0 | null | false | 2014-01-02T15:31:54 | 2013-01-07T18:31:48 | 2014-01-02T15:31:54 | 2014-01-02T15:31:54 | 360 | 4 | 1 | 0 |
Python
| null | null |
import gettext
import tempfile
from collections import defaultdict
import polib
from carcade.utils import get_template_source
def get_translations(po_file_path):
"""Creates :class:`gettext.GNUTranslations` from PO file `po_file_path`."""
po_file = polib.pofile(po_file_path)
with tempfile.NamedTemporaryFile() as mo_file:
po_file.save_as_mofile(mo_file.name)
return gettext.GNUTranslations(mo_file)
def extract_translations(jinja2_env, target_pot_file):
"""Produces a `target_pot_file` which contains a list of all
the translatable strings extracted from the templates.
"""
po = polib.POFile()
po.metadata = {'Content-Type': 'text/plain; charset=utf-8'}
messages = defaultdict(list)
for template in jinja2_env.list_templates():
template_source = get_template_source(jinja2_env, template)
for (lineno, _, message) in jinja2_env.extract_translations(template_source):
message = unicode(message)
occurence = (template, lineno)
messages[message].append(occurence)
for message, occurrences in messages.iteritems():
entry = polib.POEntry(msgid=message, msgstr=message, occurrences=occurrences)
po.append(entry)
po.save(target_pot_file)
|
UTF-8
|
Python
| false | false | 2,014 |
13,228,499,282,864 |
94fa1835ee4f93c1e3c514d73584d2a383549cda
|
5b8a007f9166473ed163650bc0d2793918a44e7b
|
/asynchronous/506/semantic.py
|
034ccc1e8def9bc70357f6ca9bfd91a20535a14f
|
[] |
no_license
|
neuront/bitgarden
|
https://github.com/neuront/bitgarden
|
ee76592d1373c400c875ce80335dfadd1406afc5
|
0f8671ec127eec741cefd9b9b9a803a37579992b
|
refs/heads/master
| 2021-06-21T05:17:03.936802 | 2013-03-31T16:47:43 | 2013-03-31T16:47:43 | 1,142,495 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import output
class ContextFlow:
def __init__(self):
self.block = output.Block([])
class Expression:
pass
class NumericLiteral(Expression):
def __init__(self, value):
self.value = value
def compile(self, context):
return output.NumericLiteral(self.value)
class StringLiteral(Expression):
def __init__(self, value):
self.value = value
def compile(self, context):
return output.StringLiteral(self.value)
class Reference(Expression):
def __init__(self, name):
self.name = name
def compile(self, context):
return output.Reference(self.name)
class Binary(Expression):
def __init__(self, op, left, right):
self.op = op
self.left = left
self.right = right
def compile(self, context):
return output.Binary(self.op,
self.left.compile(context),
self.right.compile(context))
class Call(Expression):
def __init__(self, callee, arguments):
self.callee = callee
self.arguments = arguments
def compile(self, context):
compl_callee = self.callee.compile(context)
compl_args = [ arg.compile(context) for arg in self.arguments ]
return output.Call(compl_callee, compl_args)
class Lambda(Expression):
def __init__(self, parameters, body):
self.parameters = parameters
self.body = body
def compile(self, context):
body_context = ContextFlow()
body_flow = body_context.block
self.body.compile(body_context)
return output.Lambda(self.parameters, body_flow)
class RegularAsyncCall(Expression):
def __init__(self, callee, arguments):
self.callee = callee
self.arguments = arguments
def compile(self, context):
compl_callee = self.callee.compile(context)
compl_args = [ arg.compile(context) for arg in self.arguments ]
callback_body_context = ContextFlow()
cb_body_flow = callback_body_context.block
compl_args.append(output.Lambda([ 'error', 'result' ], cb_body_flow))
context.block.add(output.Arithmetics(
output.Call(compl_callee, compl_args)))
context.block = cb_body_flow
return output.Reference('result')
class Statement:
pass
class Block(Statement):
def __init__(self, statements):
self.statements = statements
def compile(self, context):
for s in self.statements: s.compile(context)
class Arithmetics(Statement):
def __init__(self, expression):
self.expression = expression
def compile(self, context):
compl_arith = output.Arithmetics(self.expression.compile(context))
context.block.add(compl_arith)
class Branch(Statement):
def __init__(self, predicate, consequence, alternative):
self.predicate = predicate
self.consequence = consequence
self.alternative = alternative
def compile(self, context):
consq_context = ContextFlow()
consq_flow = consq_context.block
self.consequence.compile(consq_context)
alter_context = ContextFlow()
alter_flow = alter_context.block
self.alternative.compile(consq_context)
compl_branch = output.Branch(self.predicate.compile(context),
consq_flow, alter_flow)
context.block.add(compl_branch)
def main():
root_context = ContextFlow()
root_flow = root_context.block
Block([
Arithmetics(NumericLiteral('10.24')),
Arithmetics(Call(Reference('setTimeout'), [
Lambda([], Block([
Branch(Reference('condition'), Block([
Arithmetics(Call(Reference('doSomething'), []))
]), Block([]))
])),
NumericLiteral(1000)
])),
Arithmetics(
Binary(
'=',
Reference('content'),
RegularAsyncCall(
Binary('.', Reference('fs'), Reference('readFile')),
[ StringLiteral('/etc/passwd') ]))),
Arithmetics(Call(Binary('.',
Reference('console'),
Reference('log')),
[ Reference('context') ]))
]).compile(root_context)
print root_flow.str()
if __name__ == '__main__':
main()
|
UTF-8
|
Python
| false | false | 2,013 |
10,299,331,593,579 |
09a661f46a7524579fdcd6bde6d567cf3bf433ee
|
c64f8a403d9ac8e353b4ca1ea7ec10a28c802311
|
/SConscript
|
c32b1d9ce09427ff464328bf5b398e47713af407
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
non_permissive
|
mikeandmore/tube
|
https://github.com/mikeandmore/tube
|
1eb0a650d42519e3b1f02e6d4f0c2f4106c833f5
|
c99b6a309f0ddaa68cb061d64ba726e477c8c4b1
|
refs/heads/master
| 2020-02-28T22:59:06.816797 | 2012-01-29T18:03:56 | 2012-01-29T18:04:10 | 1,603,943 | 15 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- mode: python -*-
from SCons import SConf
import os
source = ['utils/logger.cc',
'utils/misc.cc',
'utils/mempool.cc',
'utils/lock.cc',
'utils/exception.cc',
'core/poller.cc',
'core/timer.cc',
'core/buffer.cc',
'core/pipeline.cc',
'core/inet_address.cc',
'core/stream.cc',
'core/filesender.cc',
'core/server.cc',
'core/stages.cc',
'core/controller.cc',
'core/wrapper.cc']
http_source = ['http/http_parser.c',
'http/connection.cc',
'http/http_wrapper.cc',
'http/interface.cc',
'http/static_handler.cc',
'http/static.mod.c',
'http/configuration.cc',
'http/io_cache.cc',
'http/http_stages.cc',
'http/capi_impl.cc',
'http/module.c']
http_server_source = ['http/server.cc']
epoll_source = ['core/poller_impl/epoll_poller.cc']
kqueue_source = ['core/poller_impl/kqueue_poller.cc']
port_completion_source = ['core/poller_impl/port_completion_poller.cc']
Import('env', 'GetOS')
def LinuxSpecificConf(ctx):
global source
conf = ctx.sconf
if not SConf.CheckCHeader(ctx, 'sys/epoll.h'):
ctx.Message('Failed because kernel doesn\'t suport epoll')
return False
if SConf.CheckCHeader(ctx, 'sys/sendfile.h'):
conf.Define('USE_LINUX_SENDFILE')
if not SConf.CheckLib(ctx, 'dl'):
ctx.Message('Cannot find dl')
return False
conf.Define('USE_EPOLL')
source += epoll_source
ctx.Result(0)
return True
def FreeBSDSpecificConf(ctx):
global source
conf = ctx.sconf
if not SConf.CheckCHeader(ctx, ['sys/types.h', 'sys/event.h']):
ctx.Message('Failed because kernel doesn\'t support kqueue')
return False
if Sconf.CheckFunction(ctx, 'sendfile'):
conf.Define('USE_FREEBSD_SENDFILE')
conf.Define('USE_KQUEUE')
source += kqueue_source
return True
def SolarisSpecificConf(ctx):
global source
conf = ctx.sconf
if not SConf.CheckLib(ctx, 'socket'):
ctx.Message('Socket library not found')
return False
if not SConf.CheckCHeader(ctx, 'port.h'):
ctx.Message('Failed because kernel doesn\'t support port completion framework')
return False
if SConf.CheckLibWithHeader(ctx, 'sendfile', 'sys/sendfile.h', 'c'):
conf.Define('USE_LINUX_SENDFILE')
conf.Define('USE_PORT_COMPLETION')
global source
source += port_completion_source
return True
def CheckRagel(ctx):
ctx.Message('Checking for Ragel... ')
ret = ctx.TryAction('ragel')
ctx.Result(bool(ret))
return ret
if not env.GetOption('clean'):
specific_conf = None;
boost_headers = ['boost/noncopyable.hpp', 'boost/function.hpp', 'boost/bind.hpp', 'boost/shared_ptr.hpp', 'boost/xpressive/xpressive.hpp']
if GetOS() == 'Linux':
specific_conf = LinuxSpecificConf
elif GetOS() == 'FreeBSD':
specific_conf = FreeBSDSpecificConf
elif GetOS() == 'SunOS':
specific_conf = SolarisSpecificConf
else:
print 'Kernel not supported yet'
Exit(1)
conf = env.Configure(config_h='config.h', custom_tests={'SpecificConf': specific_conf, 'CheckRagel': CheckRagel})
if not conf.CheckLib('z') or not conf.CheckLib('rt'):
Exit(1)
if not conf.CheckLibWithHeader('yaml-cpp', 'yaml-cpp/yaml.h', 'cxx'):
Exit(1)
for header in boost_headers:
if not conf.CheckCXXHeader(header):
Exit(1)
if not conf.CheckLib('jemalloc'):
Exit(1)
if not conf.CheckRagel():
Exit(1)
if not conf.SpecificConf():
Exit(1)
env = conf.Finish()
env.Command('http/http_parser.c', 'http/http_parser.rl', 'ragel -s -G2 $SOURCE -o $TARGET')
pch = env.Command('../pch.h.gch', 'pch.h', '$CXX $CXXFLAGS $CCFLAGS -fPIC -x c++-header $SOURCE -o $TARGET')
env.Depends(source, pch)
libtube = env.SharedLibrary('tube', source=source)
libtube_web = env.SharedLibrary('tube-web', source=http_source, LIBS=['$LIBS', 'libtube'])
tube_server = env.Program('tube-server', source=http_server_source, LIBS=['$LIBS', 'libtube', 'libtube-web'])
def GenTestProg(name, src):
env.Program(name, source=src, LIBS=['$LIBS', 'libtube', 'libtube-web'])
if ARGUMENTS.get('testcase') == '1':
GenTestProg('test/hash_server', 'test/hash_server.cc')
GenTestProg('test/pingpong_server', 'test/pingpong_server.cc')
GenTestProg('test/test_buffer', 'test/test_buffer.cc')
GenTestProg('test/file_server', 'test/file_server.cc')
GenTestProg('test/test_http_parser', 'test/test_http_parser.cc')
GenTestProg('test/test_web', 'test/test_web.cc')
# Install
env.Alias('install', [
env.Install('$LIBDIR/', [libtube, libtube_web]),
env.Install('$PREFIX/bin/', tube_server)
])
|
UTF-8
|
Python
| false | false | 2,012 |
12,257,836,706,155 |
d8c943c1822992a0fdf938954ea9c5eef99662bc
|
568dd2c580186deec258151d11f4fd84e5690456
|
/examples/linked_list_add_bol_mol/linked_list_add_eol.py
|
af3ea8894eddbd291a2500573243019ba16aa047
|
[] |
no_license
|
JoaoFelipe/Data-Structures-Drawer
|
https://github.com/JoaoFelipe/Data-Structures-Drawer
|
f53b34844dcaba350975d66838b983a3ec81347e
|
a9192d850ebba3095f5de64e61bde6eaeb9b1e4e
|
refs/heads/master
| 2021-01-15T11:48:28.849314 | 2014-04-10T03:35:27 | 2014-04-10T03:35:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from __future__ import (absolute_import, division,
print_function, unicode_literals)
import sys
import os
sys.path.append(os.path.join("..", ".."))
from ds_drawer.generators.lists import create_linked_list
from ds_drawer.shapes.cross import Cross
from ds_drawer.shapes.arrow import Arrow
from ds_drawer.shapes.pointer import Pointer
from ds_drawer.shapes.linked_list import LinkedList
from ds_drawer.viewer import viewer
RED = (255, 0, 0)
BLUE = (0, 0, 255)
def draw():
l, e2, a24, e4, a4n, n = create_linked_list([None, 2, None, 4])
# Add 0
cl = Cross(l, color=RED)
e0 = LinkedList((e2.x - 40, e2.y + 40, 0), 0, color=RED)
a02 = Arrow(e0.prox_1, e2.start_4, color=RED)
l0 = Pointer(e0, 'l', direction='ul.start_0', color=RED)
# Add 3
ca24 = Cross(a24, color=BLUE)
e3 = LinkedList((e4.x - 60, e4.y + 40, 0), 3, color=BLUE)
a23 = Arrow(e2.prox_3, e3.start_0, color=BLUE)
a34 = Arrow(e3.prox_1, e4.start_4, color=BLUE)
ant = Pointer(e2, 'ant', direction='u.u_2', color=BLUE)
pp = Pointer(e4, 'p', direction='u.u_2', color=BLUE)
novo = Pointer(e3, 'novo', direction='d.d_2', color=BLUE)
return [
l, e2, a24, e4, a4n, n,
cl, e0, a02, l0,
ca24, e3, a23, a34,
ant, pp, novo
]
if __name__ == '__main__':
viewer(draw)
|
UTF-8
|
Python
| false | false | 2,014 |
14,087,492,739,912 |
5a96c8bf682da779c91c123184ada76d8829a5e9
|
7fe6c3f74498219a57e2143320cfa26edbbd61be
|
/Lab06_part3.py
|
6371a27e6498ff85333fa2e32e6588a84fd71994
|
[] |
no_license
|
Mensah/Lab_Python_06
|
https://github.com/Mensah/Lab_Python_06
|
74ffcb1733d3916b09e1c76a70c54f8a2105cace
|
520879b372f15daf428578cc027e28ccdcfe772e
|
refs/heads/master
| 2020-12-25T11:16:17.894540 | 2012-06-28T11:05:18 | 2012-06-28T11:05:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class Team:
def __init__(self,name,league,manager_name,points):
self.name = name
self.league = league
self.manager_name = manager_name
self.points = points
self.players = []
def add_player(self,player):
self.players.append(player)
def __str__(self):
description ='The ' + self.name + ' team currently managed by ' + self.manager_name + ', are at the top of their group table with ' + self.points + 'points in the ' + self.league + ' Cup'
return description
Spain = Team('Espanyol', 'Euro2012','Nii Guardiola','6')
print Spain
|
UTF-8
|
Python
| false | false | 2,012 |
11,605,001,666,393 |
680d8dc7703f7bfce2ffef2552f013589a5d1cf6
|
3ccfdd3f5e9c1137b351349146228d6839a50391
|
/euler/28.py
|
2e5210c47cf44901c2096cc26cf0ce48fc23f33c
|
[] |
no_license
|
ErnestDu/algorithms
|
https://github.com/ErnestDu/algorithms
|
4f4632acef9434fb9774b3bb5ceb38aa12c7e261
|
7c9b40d0bc43c2fde1e982f3b06bfda59266521b
|
refs/heads/master
| 2020-05-30T06:04:59.153700 | 2014-04-11T07:32:40 | 2014-04-11T07:32:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
ss = 1
k = 2
for i in range (3, 1002, 2):
# print(pow(i,2))
m = pow(i, 2)
ss = ss + 4 * m - (k + 2 * k + 3 * k)
k = k + 2
print(ss)
|
UTF-8
|
Python
| false | false | 2,014 |
566,935,687,006 |
ddad2b40e12522406191166941f91ebbe9c7f0da
|
e8643f04132147994f6d15b26c83b7b3320861a3
|
/config.py
|
7eb25087ca490cd6a0e981876a711ab6c9403e3c
|
[] |
no_license
|
Arachnid/cah
|
https://github.com/Arachnid/cah
|
0498c4854ececfba2acc21551bb54273dbb55ac6
|
e95b5eb2ccf476376d124a8b0d8bdb01cfa08f75
|
refs/heads/master
| 2020-03-30T07:30:43.311385 | 2012-01-09T07:26:14 | 2012-01-09T22:24:50 | 2,596,564 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# CAH config settings
# ROUNDS_PER_GAME = 2 # the count starts at 0
ROUNDS_PER_GAME = 5 # the count starts at 0
SIZE_OF_HAND = 5 # the number of cards dealt to each participant per game
|
UTF-8
|
Python
| false | false | 2,012 |
1,271,310,324,421 |
a0573b6422188713ea9055c01ee1ddba7e2387f5
|
017285567f00030d9332972ec7c0f98b3c7b97b9
|
/app.py
|
dc81f24db96fab9049bacb612f63a77d9d024d5d
|
[
"LGPL-3.0-only"
] |
non_permissive
|
theoo/planewhite
|
https://github.com/theoo/planewhite
|
5a25ea9c256933a6d2ad1b5f75658143558757f4
|
32b24102d6eff4f863e138871545782f7e3a1625
|
refs/heads/master
| 2020-08-06T20:07:49.581885 | 2011-07-07T12:04:28 | 2011-07-07T12:04:28 | 1,924,258 | 64 | 21 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# Complex IT sarl, june 2011
# Theo Reichel and David Hodgetts
# See README.txt for more information
from kivy.app import App
from controller import Controller
from lib.commandLineArgumentExtractor import tryToGetIdFromCommandLineArgument
from lib.utils import Cursor
from kivy.logger import Logger
clientId = tryToGetIdFromCommandLineArgument()
class PlaneWhiteApp(App):
def build(self):
self.controller = Controller(cid=clientId)
self.controller.add_widget(Cursor())
return self.controller
def on_stop(self):
self.controller.cleanupOnExit()
print "Closing connections."
PlaneWhiteApp().run()
|
UTF-8
|
Python
| false | false | 2,011 |
15,032,385,580,971 |
4651c41e1c2fc7e9d7d100ed087eb162409c6403
|
9d5722dbe8cc176c8bf48077a2b439940d45eaf9
|
/src/cid/utils/jsOptimizerProcess.py
|
08c9e78be91b9eb38ac933ae9bf2b669d28b0031
|
[
"AGPL-3.0-only"
] |
non_permissive
|
dunkel13/CaliopeServer
|
https://github.com/dunkel13/CaliopeServer
|
4800b719235d8ff334a57684035d1ff7d6334bbd
|
a71f4e6490ddb6b6ec43e3b71df5b0603a632f37
|
refs/heads/master
| 2021-05-27T12:11:36.500244 | 2014-01-08T15:07:03 | 2014-01-08T15:07:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@authors: Andrés Calderón andres.calderon@correlibre.org
@license: GNU AFFERO GENERAL PUBLIC LICENSE
Caliope Server is the web server of Caliope's Framework
Copyright (C) 2013 Infometrika
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import redis
import sys
import getopt
from simplekv.memory.redisstore import RedisStore
from os import path
from pyinotify import (WatchManager, Notifier, ProcessEvent, IN_MOVED_TO, IN_ACCESS, IN_CREATE, IN_MODIFY, IN_DELETE)
from cid.utils.jsOptimizer import *
from cid.utils.fileUtils import loadJSONFromFile
class StaticsChangesProcessor(ProcessEvent):
def __init__(self, jso, store):
self.jso = jso
self.store = store
def process_IN_CREATE(self, event):
print "Create: %s" % path.join(event.path, event.name)
self.jso.js_put_file_cache(path.join(event.path, event.name), self.store)
def process_IN_MODIFY(self, event):
print "Modify: %s" % path.join(event.path, event.name)
self.jso.js_put_file_cache(path.join(event.path, event.name), self.store)
def process_IN_DELETE(self, event):
pass
def process_IN_MOVED_TO(self, event):
print "in moved: %s" % path.join(event.path, event.name)
self.jso.js_put_file_cache(path.join(event.path, event.name), self.store)
def _parseCommandArguments(argv):
print "_parseCommandArguments" + str(argv)
server_config_file = "conf/caliope_server.json"
try:
opts, args = getopt.getopt(argv, "hc:", ["help", "config=", ])
except getopt.GetoptError:
print 'jsOptimizerProcess.py -c <server_configfile>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'jsOptimizerProcess.py -c <server_configfile>'
sys.exit()
elif opt in ("-c", "--config"):
server_config_file = arg
return server_config_file
def configure_server_and_app(server_config_file):
config = loadJSONFromFile(server_config_file, '')
print config['server']
if 'static' in config['server']:
static_path = config['server']['static']
else:
static_path = "."
if 'minify_enabled' in config['server']:
minify_enabled = config['server']['minify_enabled'].lower() == 'true'
else:
minify_enabled = False
return [static_path, minify_enabled]
def main(argv):
server_config_file = _parseCommandArguments(argv)
[static_path, minify_enabled] = configure_server_and_app(server_config_file)
print "server_config_file = " + server_config_file
print "static_path = " + static_path
print "minify_enabled = " + str(minify_enabled)
store = RedisStore(redis.StrictRedis())
jso = jsOptimizer(minify_enabled)
jso.watch(static_path, store, force=True)
try:
wm = WatchManager()
notifier = Notifier(wm, StaticsChangesProcessor(jso, store))
wm.add_watch(static_path, IN_CREATE | IN_MODIFY | IN_DELETE | IN_MOVED_TO, rec=True)
notifier.loop()
finally:
pass
if __name__ == '__main__':
#: Start the application
main(sys.argv[1:])
|
UTF-8
|
Python
| false | false | 2,014 |
13,460,427,548,831 |
d66098b26a33955d6f7daeff07351ced28c0075c
|
98759b1ff9b52a563332a97286a80cdb48388978
|
/scripts/LRC Lyrics/default.py
|
ba87695d1a0e2eb15e77019c92c8cfd558b51747
|
[] |
no_license
|
WilliamRen/xbmc-addons-chinese
|
https://github.com/WilliamRen/xbmc-addons-chinese
|
4413f3499f125217e7b5d500f1499d1bb332491c
|
c9c8249ec25e8514ab11974220dcc5df34ba7d41
|
refs/heads/master
| 2020-06-02T15:15:10.589453 | 2010-05-13T12:30:37 | 2010-05-13T12:30:37 | 1,070,751 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# LRC Lyrics script revision: - built with build.bat version 1.0 #
# main import's
import sys
import os
import xbmc
# Script constants
__newscriptname__ = "LRC Lyrics"
__scriptname__ = "XBMC Lyrics"
__author__ = "XBMC Lyrics Team"
__url__ = "http://code.google.com/p/xbmc-scripting/"
__svn_url__ = "http://xbmc-scripting.googlecode.com/svn/trunk/"
__credits__ = "XBMC TEAM, freenode/#xbmc-scripting"
__version__ = "1.22"
__svn_revision__ = ""
# Shared resources
BASE_RESOURCE_PATH = os.path.join( os.getcwd(), "resources" )
__language__ = xbmc.Language( os.getcwd() ).getLocalizedString
# Main team credits
__credits_l1__ = __language__( 910 )#"Head Developer & Coder"
__credits_r1__ = "Taxigps"
__credits_l2__ = __language__( 911 )#"Original author"
__credits_r2__ = "Nuka1195 & EnderW"
__credits_l3__ = __language__( 912 )#"Original skinning"
__credits_r3__ = "Smuto"
# additional credits
__add_credits_l1__ = __language__( 1 )#"Xbox Media Center"
__add_credits_r1__ = "Team XBMC"
__add_credits_l2__ = __language__( 913 )#"Unicode support"
__add_credits_r2__ = "Spiff"
__add_credits_l3__ = __language__( 914 )#"Language file"
__add_credits_r3__ = __language__( 2 )#"Translators name"
# Start the main gui or settings gui
if ( __name__ == "__main__" ):
if ( xbmc.Player().isPlayingAudio() ):
import resources.lib.gui as gui
window = "main"
else:
import resources.lib.settings as gui
window = "settings"
ui = gui.GUI( "script-%s-%s.xml" % ( __scriptname__.replace( " ", "_" ), window, ), os.getcwd(), "Default" )
ui.doModal()
del ui
sys.modules.clear()
|
UTF-8
|
Python
| false | false | 2,010 |
15,324,443,336,939 |
6e35b1f0f9f5799fcffd435e4cc708b8ad760ff9
|
562c636e1b022634b82e6ee732cb1196c99f8989
|
/events/models.py
|
c316351ff3e5bfdcbaa654dbcf829828c67d6756
|
[] |
no_license
|
MasterEx/letsrpg-social-network
|
https://github.com/MasterEx/letsrpg-social-network
|
50f6c5e15dcaeff69afcc96d75145c39bc5f4588
|
cd4bdb00548b810072bd99c4d15dde5d081f20ef
|
refs/heads/master
| 2020-04-30T01:47:22.479809 | 2011-11-12T12:38:43 | 2011-11-12T12:38:43 | 1,836,625 | 6 | 5 | 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
class Event(models.Model):
# id is auto created
game_master = models.CharField(max_length=10)
user_role = models.CharField(max_length=10)
date = models.DateTimeField(auto_now_add='true')
slots = models.PositiveSmallIntegerField()
slots_taken = models.IntegerField()
location = models.CharField(max_length=20)
def __unicode__(self):
return self.game_master
class EventPlayer(models.Model):
userid = models.ForeignKey(User)
eventid = models.ForeignKey(Event)
TYPE_CHOICES = (
( 'P' , 'Player'),
( 'M' , 'Game Master - Story Tailer'),
)
type = models.CharField(max_length=1,default='P',choices=TYPE_CHOICES)
def __unicode__(self):
return "date: %s - slots: %s - participant: %s" % (self.eventid.date,self.eventid.slots,self.userid.username)
|
UTF-8
|
Python
| false | false | 2,011 |
8,306,466,776,248 |
4f505d65252a6668e84f903d581d13fddd4ce837
|
7c56dbb3ba327d58ad5ff92b60318e26136b1f10
|
/textproc/py-sphinx-theme-cloud/patches/patch-cloud_sptheme.make_helper.py
|
2f0c9f0d062781668c085597be63e8bf18b5f5ae
|
[] |
no_license
|
minix3/pkgsrc
|
https://github.com/minix3/pkgsrc
|
0e81cd20462472607583a16035811f998732f7a6
|
1d67274bb96961b029c9e959252a612e7760a508
|
HEAD
| 2016-07-26T08:51:42.607793 | 2014-04-04T14:17:10 | 2014-04-04T14:17:10 | 2,857,722 | 8 | 5 | null | null | null | null | null | null | null | null | null | null | null | null | null |
$NetBSD$
- Wrap print string in parens to allow compiling by Python 3.x
--- cloud_sptheme/make_helper.py.orig 2012-07-31 18:11:55.000000000 +0000
+++ cloud_sptheme/make_helper.py
@@ -150,16 +150,16 @@ class SphinxMaker(object):
#targets
#===============================================================
def target_help(self):
- print "Please use \`make <target>' where <target> is one of"
- print " clean remove all compiled files"
- print " html to make standalone HTML files"
- print " servehtml to serve standalone HTML files on port 8000"
-# print " pickle to make pickle files"
-# print " json to make JSON files"
- print " htmlhelp to make HTML files and a HTML help project"
-# print " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
-# print " changes to make an overview over all changed/added/deprecated items"
-# print " linkcheck to check all external links for integrity"
+ print ("Please use \`make <target>' where <target> is one of")
+ print (" clean remove all compiled files")
+ print (" html to make standalone HTML files")
+ print (" servehtml to serve standalone HTML files on port 8000")
+# print (" pickle to make pickle files")
+# print (" json to make JSON files")
+ print (" htmlhelp to make HTML files and a HTML help project")
+# print (" latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter")
+# print (" changes to make an overview over all changed/added/deprecated items")
+# print (" linkcheck to check all external links for integrity")
def target_clean(self):
rmpath(self.BUILD)
@@ -182,7 +182,7 @@ class SphinxMaker(object):
# fall back to stdlib server
import SimpleHTTPServer as s
os.chdir(path)
- print "Serving files from %r on port %r" % (path, port)
+ print ("Serving files from %r on port %r" % (path, port))
s.BaseHTTPServer.HTTPServer(('',port), s.SimpleHTTPRequestHandler).serve_forever()
else:
serve(StaticURLParser(path), host="0.0.0.0", port=port)
@@ -191,8 +191,8 @@ class SphinxMaker(object):
##def target_latex(self):
## build("latex")
- ## print "Run \`make all-pdf' or \`make all-ps' in that directory to" \
- ## "run these through (pdf)latex."
+ ## print ("Run \`make all-pdf' or \`make all-ps' in that directory to"
+ ## "run these through (pdf)latex.")
##
##def target_pdf():
## assert os.name == "posix", "pdf build support not automated for your os"
@@ -200,7 +200,7 @@ class SphinxMaker(object):
## target = BUILD / "latex"
## target.chdir()
## subprocess.call(['make', 'all-pdf'])
- ## print "pdf built"
+ ## print ("pdf built")
#===============================================================
#helpers
@@ -217,9 +217,9 @@ class SphinxMaker(object):
rc = subprocess.call([self.SPHINXBUILD, "-b", name] + ALLSPHINXOPTS + [ target ])
if rc:
- print "Sphinx-Build returned error, exiting."
+ print ("Sphinx-Build returned error, exiting.")
sys.exit(rc)
- print "Build finished. The %s pages are in %r." % (name, target,)
+ print ("Build finished. The %s pages are in %r." % (name, target,))
return target
def get_paper_opts(self):
|
UTF-8
|
Python
| false | false | 2,014 |
12,790,412,644,859 |
dccb4a7f827c07b5625e380f8cd24d2dc9cf87ea
|
1b87d5f7cba7e068f7b2ea902bba494599d20a78
|
/tools/license.py
|
d17132b579bae72704abf7d5cc511a651123b3d2
|
[
"BSD-3-Clause"
] |
permissive
|
jpaalasm/pyglet
|
https://github.com/jpaalasm/pyglet
|
906d03fe53160885665beaed20314b5909903cc9
|
bf1d1f209ca3e702fd4b6611377257f0e2767282
|
refs/heads/master
| 2021-01-25T03:27:08.941964 | 2014-01-25T17:50:57 | 2014-01-25T17:50:57 | 16,236,090 | 2 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
# $Id:$
'''Rewrite the license header of source files.
Usage:
license.py file.py file.py dir/ dir/ ...
'''
import optparse
import os
import sys
license = '''# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.'''
marker = '# ' + '-' * 76
license_lines = [marker] + license.split('\n') + [marker]
def update_license(filename):
'''Open a Python source file and update the license header, writing
it back in place.'''
lines = [l.strip('\r\n') for l in open(filename).readlines()]
if marker in lines:
# Update existing license
try:
marker1 = lines.index(marker)
marker2 = lines.index(marker, marker1 + 1)
if marker in lines[marker2 + 1:]:
raise ValueError() # too many markers
lines = (lines[:marker1] +
license_lines +
lines[marker2 + 1:])
except ValueError:
print >> sys.stderr, "Can't update license in %s" % filename
else:
# Add license to unmarked file
# Skip over #! if present
if not lines:
pass # Skip empty files
elif lines[0].startswith('#!'):
lines = lines[:1] + license_lines + lines[1:]
else:
lines = license_lines + lines
open(filename, 'wb').write('\n'.join(lines) + '\n')
if __name__ == '__main__':
op = optparse.OptionParser()
op.add_option('--exclude', action='append', default=[])
options, args = op.parse_args()
if len(args) < 1:
print >> sys.stderr, __doc__
sys.exit(0)
for path in args:
if os.path.isdir(path):
for root, dirnames, filenames in os.walk(path):
for dirname in dirnames:
if dirname in options.exclude:
dirnames.remove(dirname)
for filename in filenames:
if (filename.endswith('.py') and
filename not in options.exclude):
update_license(os.path.join(root, filename))
else:
update_license(path)
|
UTF-8
|
Python
| false | false | 2,014 |
5,325,759,478,618 |
aaffa4977a330e4444318ac96996de55e26b7ca5
|
e0098089e09e957443f51d17c151a510a959c91e
|
/src/scenarios/ingest/ingest.py
|
67b49ef7bbeba54910db38772211b9c38bdddf37
|
[
"Apache-2.0"
] |
permissive
|
fcrepo4-archive/fcrepo-test-grinder
|
https://github.com/fcrepo4-archive/fcrepo-test-grinder
|
21cf4be457727f588149c3d068499d9b08b080c4
|
0a84334c5e2d29d218e103d5072e6a1e4b8221ff
|
refs/heads/master
| 2020-04-10T00:23:37.756612 | 2014-11-07T16:27:40 | 2014-11-07T16:27:40 | 20,292,248 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# Copyright 2014 DuraSpace, Inc.
#
# 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 string
import os
import uuid
import mimetypes
import httplib, urllib
from threading import Lock
import java.io as io
import org.python.util as util
from urlparse import urljoin
from net.grinder.script.Grinder import grinder
from net.grinder.script import Test
from net.grinder.plugin.http import HTTPRequest
from HTTPClient import NVPair
# Ingest scenario options (single, multiple, mix) with files placed in each folder
option = os.environ.get('INGEST_OPTION', 'single')
# Fedora repository Url, default http://localhost:8080/rest/
fullBaseURL = os.environ.get('FCREPO_URL', 'http://localhost:8080/rest/')
# Test file(s) location
filesDir = 'files/' + option + '/'
test1 = Test(1, "File Ingest Test")
request1 = test1.wrap(HTTPRequest())
# Instrument the request with Test
test1.record(request1)
#
# TestRunner test ingest files in directory /files with scenario/
# options for single file, multiple files, and mix files.
#
# @author lsitu
# @since 11/06/2014
#
class TestRunner:
# Identify the running thread for logging
THREAD_NUM = 0
LOCK = Lock()
requestUrl = ''
threadNum = 0
# The __init__ method is called once for each thread.
# Put any test thread initializations here
def __init__(self):
# Assigning the thread ID
TestRunner.LOCK.acquire()
try:
TestRunner.THREAD_NUM += 1
self.threadNum = TestRunner.THREAD_NUM
finally:
TestRunner.LOCK.release()
# Create object resource to hole the test files.
#
# Grinder HTTPRequest will always POST multipart/form requests, with
# which the fcrepo will create empty binary contents instead of objects.
# Manipulate with httplib to walk aroung it.
#
oid = str(uuid.uuid4())
self.requestUrl = urljoin( fullBaseURL, oid )
paths = self.requestUrl.split( "/", 3 )
conn = httplib.HTTPConnection(paths[2])
conn.request( "PUT", "/" + paths[3] )
response = conn.getresponse()
print "\nThread #" + str(self.threadNum) + " created object: " + self.requestUrl, response.status, response.reason
conn.close()
# The __call__ method is called for each test run performed by
# a worker thread.
def __call__(self):
print "Ingest files directory: " + filesDir
# Don't report to the cosole until we verify the result
grinder.statistics.delayReports = 1
# Ingest all the files one by one in directory $filesDir
for f in os.listdir(filesDir):
# Skit those hidden files like .DS_Store
if ( f.startswith('.') == False ):
cType, encoding = mimetypes.guess_type(f)
if cType is None or encoding is not None:
cType = 'application/octet-stream'
headers = ( NVPair( "Content-Type", cType ), )
inFile = io.FileInputStream(filesDir + f)
# Call the version of POST that takes a byte array.
result = request1.POST( self.requestUrl, inFile, headers )
print "\nThread #" + str(self.threadNum) + " ingested " + f + ": " + self.requestUrl + " " + str(result.statusCode)
inFile.close();
if result.statusCode == 201:
# Report to the console
grinder.statistics.forLastTest.setSuccess(1)
else:
print "\nThread #" + str(self.threadNum) + " error: POST " + self.requestUrl + " " + str(result.statusCode)
# The __del__ method is called at shutdown once for each thread
# It is useful for closing resources (e.g. database connections)
# that were created in __init__.
#def __del__(self):
|
UTF-8
|
Python
| false | false | 2,014 |
13,726,715,489,825 |
ec22911b907242644a989606eaa7381ed2aa574d
|
15d7c13c6c39d9262e959e0c6d226c3ca51fb41e
|
/test.py
|
d3631c47330e9c0f97224b59d32df9815be5a0ec
|
[
"MIT"
] |
permissive
|
metemaddar/persian.py
|
https://github.com/metemaddar/persian.py
|
28a2433236fc511066000f4ef2d3cb565299d811
|
e64017fc3ec6eb90dd70745504419c9c2338c1c4
|
refs/heads/master
| 2021-01-17T08:13:55.940945 | 2013-09-26T10:05:55 | 2013-09-26T10:05:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# encoding: utf-8
from toPersian import *
print enToPersianNumb('شماره کلاس 312')
print enToPersianNumb(3123123.9012)
print enToPersianNumb(123)
print enToPersianchar('sghl ]i ofv')
print arToPersianNumb('٣٤٥٦')
print arToPersianChar(' ك جمهوري اسلامي ايران')
'''
شماره کلاس ۳۱۲
۳۱۲۳۱۲۳.۹۰۱۲
۱۲۳
سلام چه خبر
۳۴۵۶
ک جمهوری اسلامی ایران
'''
|
UTF-8
|
Python
| false | false | 2,013 |
18,966,575,593,622 |
ac8444629b7609628f434314015a3589c5e678fe
|
1382bfb5f1ff2367858f68430cb091e9177ca5d7
|
/GreedMotiffSearch.py
|
abd8b0950cc6e23666dba8ee6bef7cc479e7706f
|
[] |
no_license
|
veranicebad/Stepic
|
https://github.com/veranicebad/Stepic
|
dc8d7efe7bdb11a26e3a35bf03c8e445ced2bf67
|
72df6e2d095aee338d268fed6d2f79fca634ad93
|
refs/heads/master
| 2016-09-06T20:11:51.770584 | 2014-12-08T12:03:45 | 2014-12-08T12:03:45 | 27,712,534 | 1 | 7 | null | null | null | null | null | null | null | null | null | null | null | null | null |
__author__ = 'Vera'
from sets import Set
from copy import deepcopy
import itertools
fin = open('input.txt', 'r')
fout=open('output.txt', 'w')
s0=fin.readline().replace('\n','').split(' ')
k=int(s0[0])
t=int(s0[1])
strings=[]
for line in fin.readlines():
strings.append(line.replace('\n',''))
def Profile(Motifs):
profile=[[0 for x in range(k)] for x in range(255)]
for i in range(len(Motifs[0])):
d={}
for j in range(len(Motifs)):
if Motifs[j][i] in d:
d[Motifs[j][i]]+=1
else:
d[Motifs[j][i]]=1
for key, value in d.items():
profile[ord(key)][i]=float(value)/float(len(Motifs))
return(profile)
def findBestMotiff(s,m):
maxscore=0.0
maxscorepattern=s[:k]
for e in range(len(s)-k+1):
pattern=s[e:e+k]
score=1.0
for i in range(k):
score*=m[ord(pattern[i])][i]
if maxscore<score:
maxscore=score
maxscorepattern=pattern
return(maxscorepattern)
def Score(Motifs):
score=len(Motifs)*len(Motifs[0])
for i in range(len(Motifs[0])):
d={}
for j in range(len(Motifs)):
if Motifs[j][i] in d:
d[Motifs[j][i]]+=1
else:
d[Motifs[j][i]]=1
score-=max(d.values())
return(score)
def GREEDYMOTIFSEARCH(Dna, k,t):
BestMotifs=[]
for i in Dna:
BestMotifs.append(i[:k])
for e in range(len(Dna[0])-k+1):
Motif=(Dna[0][e:e+k])
Motif1 = Motif
Motifs=[]
Motifs.append(Motif1)
for i in range(1,t):
profile=Profile(Motifs)
Motifi=findBestMotiff(Dna[i],profile)
Motifs.append(Motifi)
if Score(Motifs) < Score(BestMotifs):
BestMotifs = Motifs
for bm in BestMotifs:
print(bm)
GREEDYMOTIFSEARCH(strings, k, t)
|
UTF-8
|
Python
| false | false | 2,014 |
6,382,321,425,752 |
f4268a6ac1408ff736fbd77c97e752c4e57ef463
|
680ca1eb9807f4a954c9f93477bc3d262eaa3f18
|
/sdabto.py
|
573e41011da256774474c199c537046e7122f62c
|
[] |
no_license
|
hazel-havard/sdabto
|
https://github.com/hazel-havard/sdabto
|
dd907aaf9b6a17784db8cf2f886671ea5f990035
|
c4cc663e4cc1837a59b0d1b3208efd73d9101010
|
refs/heads/master
| 2021-06-08T00:39:14.592216 | 2014-10-19T22:26:27 | 2014-10-19T22:26:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# Some Days Are Better Than Others
# By Isaac Havard - ihavard@gmail.com
# Copyright 2014
import cmd
from functools import wraps
import random
from weakref import WeakKeyDictionary
import messages
import stages
#globals
#costs in dollars
RENT = 250
GROCERIES = 50
#allowable time between events.
MEAL_INTERVAL = 6 #hours
SLEEP_INTERVAL = 16 #hours
EXERCISE_INTERVAL = 2 #days
SOCIAL_INTERVAL = 2 #days
CLEANING_INTERVAL = 2 #days
#Risks of death while out of control
SPEEDING_RISK = 0.2
ALCOHOL_POISONING_CHANCE = 0.2
#list of people you can call
CALL_DICT = {
"parents": ("mom", "mother", "dad", "father", "parents", "home", "family"),
"friend": ("friend", "friends"),
"hospital": ("hospital", "police", "ambulance", "911"),
"doctor": ("doctor", "psychiatrist"),
"helpline": ("helpline", "suicide helpline", "hotline", "suicide hotline"),
"psychologist": ("therapist", "councellor", "psychologist"),
}
class BoundedField(object):
"""A descriptor for mood and energy fields that supports max values"""
def __init__(self, default=None):
self.default = default
self.data = WeakKeyDictionary()
def __get__(self, instance, owner):
return self.data.get(instance, self.default)
def __set__(self, instance, value):
max = instance.disease_stage["CAP"]
if value < 0:
value = 0
elif value > max:
value = max
self.data[instance] = value
class Character(object):
mood = BoundedField()
energy = BoundedField()
def __init__(self):
self.disease_stage = stages.NORMAL
self.mood = 80
self.energy = 80
#In whole numbers of dollars
self.money = 200
#in hours
self.last_meal = 14
#in hours
self.last_sleep = 0
#in days
self.last_exercise = 1
#in days
self.last_social = 1
#in days
self.last_cleaned = 1
#number of meals
self.groceries = 21
self.hours_played = 8
self.hours_gamed = 0
self.hours_socialized = 0
self.hours_read = 0
self.hours_watched = 0
self.called_parents = False
self.called_friend = False
self.disease_days = 0
self.dead = False
def change_stage(self, stage):
messages = []
if "TIME_WARP" in self.disease_stage and stage == self.disease_stage["NEXT_STAGE"]:
month_str = " months pass "
if self.disease_stage["TIME_WARP"] == 1:
month_str = " month passes "
messages.append(str(self.disease_stage["TIME_WARP"]) + month_str + "this way")
self.last_exercise = 7
self.last_social = 7
self.last_cleaned = 7
self.hours_gamed = 0
self.hours_socialized = 0
self.hours_read = 0
self.hours_watched = 0
self.called_parents = False
self.called_friend = False
self.hours_played += (24 * 30 * self.disease_stage["TIME_WARP"])
if "EXIT_MESSAGE" in self.disease_stage:
messages.append(self.disease_stage["EXIT_MESSAGE"])
self.disease_stage = stage
#reset mood and energy based on new disease caps
self.energy += 0
self.mood += 0
self.disease_days = 0
messages.append(self.disease_stage["INTRO_MESSAGE"])
return messages
def add_hours(self, hours):
messages = []
#if we crossed a day boundary
if (self.hours_played // 24) < ((self.hours_played + hours) // 24):
self.hours_gamed = 0
self.hours_socialized = 0
self.hours_read = 0
self.hours_watched = 0
self.called_parents = False
self.called_friend = False
self.last_exercise += 1
self.last_social += 1
self.last_cleaned += 1
self.disease_days += 1
if self.disease_days >= self.disease_stage["LENGTH"]:
if "NEXT_STAGE" not in self.disease_stage:
self.dead = True
messages.append("You have committed suicide")
return messages
messages.extend(self.change_stage(self.disease_stage["NEXT_STAGE"]))
if ((self.hours_played + hours) // 24) % 7 == 0:
self.money -= RENT
messages.append("Rent and bills due. $" + str(RENT) + " deducted")
self.last_meal += hours
self.last_sleep += hours
self.hours_played += hours
if "EFFECT" in self.disease_stage and random.random() < stages.SIDE_EFFECT_FREQ:
messages.append(self.disease_stage["EFFECT"]["MESSAGE"])
if random.random() < self.disease_stage["THOUGHT_FREQ"] * hours:
messages.append(random.choice(self.disease_stage["THOUGHTS"]))
if self.last_meal > 24 * 7:
messages.append("You have starved to death")
self.dead = True
return messages
def display_mood(self):
mood = self.mood
if self.last_meal > MEAL_INTERVAL:
mood -= min(10 * (self.last_meal - MEAL_INTERVAL), 30)
if self.last_exercise > EXERCISE_INTERVAL:
mood -= min(5 * (self.last_exercise - EXERCISE_INTERVAL), 20)
if self.last_social > SOCIAL_INTERVAL:
mood -= min(5 * (self.last_social - SOCIAL_INTERVAL), 20)
if self.last_cleaned > CLEANING_INTERVAL:
mood -= 5
if mood < 0:
mood = 0
elif mood > self.disease_stage["CAP"]:
mood = self.disease_stage["CAP"]
return mood
def display_energy(self):
energy = self.energy
if self.last_meal > MEAL_INTERVAL:
energy -= min(10 * (self.last_meal - MEAL_INTERVAL), 30)
if self.last_sleep > SLEEP_INTERVAL:
energy -= min(5 * (self.last_sleep - SLEEP_INTERVAL), 20)
if self.last_exercise > EXERCISE_INTERVAL:
energy -= min(5 * (self.last_exercise - EXERCISE_INTERVAL), 20)
if self.disease_stage.get("EFFECT", None) == stages.LOW_ENERGY:
energy -= self.disease_stage["EFFECT"]["PENALTY"]
if energy < 0:
energy = 0
elif energy > self.disease_stage["CAP"]:
energy = self.disease_stage["CAP"]
return energy
def clean(self):
messages = self.add_hours(1)
self.energy -= 5
self.last_cleaned = 0
return messages
def work(self, hours):
messages = self.add_hours(hours)
wages = 10 * hours
if "WAGE_MULTIPLIER" in self.disease_stage:
wages *= self.disease_stage["WAGE_MULTIPLIER"]
self.money += wages
self.energy -= 5 * hours
self.mood -= 5 * hours
return messages
def sleep(self, hours):
messages = self.add_hours(hours)
if hours < 4:
return messages
if hours > 8:
hours = 8
self.last_sleep = 0
if "SLEEP_ENERGY" in self.disease_stage:
self.energy = self.disease_stage["SLEEP_ENERGY"]
return messages
self.energy = (10 * hours)
if hours > 6:
self.energy += 20
return messages
def eat(self):
messages = self.add_hours(1)
self.last_meal = 0
if "FREE_MEALS" not in self.disease_stage:
self.groceries -= 1
return messages
def exercise(self):
messages = self.add_hours(1)
self.last_exercise = 0
self.mood += 5
self.energy -= 5
return messages
def shopping(self):
messages = self.add_hours(1)
self.money -= GROCERIES
self.groceries += 21
if self.groceries > 42:
self.groceries = 42
return messages
def game(self, hours):
messages = self.add_hours(hours)
daily_cap = 4
if "GAMING_CAP" in self.disease_stage:
daily_cap = self.disease_stage["GAMING_CAP"]
hours = max(0, min(hours, daily_cap - self.hours_gamed))
self.hours_gamed += hours
self.mood += 5 * hours
return messages
def socialize(self, hours):
messages = self.add_hours(hours)
self.money -= 10 * hours
self.energy -= 5 * hours
daily_cap = 3
if "SOCIALIZING_CAP" in self.disease_stage:
daily_cap = self.disease_stage["SOCIALIZING_CAP"]
hours = max(0, min(hours, daily_cap - self.hours_socialized))
self.hours_socialized += hours
mood_bonus = 10 * hours
if "SOCIALIZING_MULTIPLIER" in self.disease_stage:
mood_bonus *= self.disease_stage["SOCIALIZING_MULTIPLIER"]
self.mood += mood_bonus
self.last_social = 0
return messages
def call(self, recipient):
messages = self.add_hours(1)
if recipient in CALL_DICT["parents"]:
if not self.called_parents:
self.mood += 5
self.called_parents = True
if self.display_mood() < 20:
messages.append("Your parents notice how rough you're feeling and are worried")
elif self.display_mood() < 50:
messages.append("Your parents notice you're feeling down and try to cheer you up")
elif self.display_mood() > 150:
messages.append("Your parents can barely understand you. They are seriously worried about you")
else:
messages.append("You have a lovely chat with your parents")
if self.money < 0:
self.money = 0
messages.append("Your parents bail you out of your debt. You feel guilty")
elif recipient in CALL_DICT["friend"]:
if not self.called_friend:
self.mood += 5
self.called_friend = True
if self.display_mood() < 20:
messages.append("Your friend notices how rough you're feeling and is worried")
elif self.display_mood() < 50:
messages.append("Your friend notices you're not very happy and tries to cheer you up")
elif self.display_mood() > 150:
messages.append("You seriously freak out your friend, who can barely get a word in edgewise")
else:
messages.append("You have a lovely chat with a friend")
elif recipient in CALL_DICT["hospital"]:
if "HOSPITAL_MESSAGE" in self.disease_stage:
messages.append(self.disease_stage["HOSPTIAL_MESSAGE"])
else:
messages.append("You are turned away. Try 'call doctor'")
if "HOSPTIAL_STAGE" in self.disease_stage:
messages.extend(self.change_stage(self.disease_stage["HOSPTIAL_STAGE"]))
elif recipient in CALL_DICT["doctor"]:
if "DOCTOR_MESSAGE" in self.disease_stage:
messages.append(self.disease_stage["DOCTOR_MESSAGE"])
else:
messages.append("You seem to be in fine health")
if "DOCTOR_STAGE" in self.disease_stage:
messages.extend(self.change_stage(self.disease_stage["DOCTOR_STAGE"]))
elif recipient in CALL_DICT["helpline"]:
messages.append("The helpline details resources available to you. Try 'call psychologist', 'call doctor', or 'call hospital'")
elif recipient in CALL_DICT["psychologist"]:
if "PSYCHOLOGIST_MESSAGE" in self.disease_stage:
messages.append(self.disease_stage["PSYCHOLOGIST_MESSAGE"])
else:
messages.append("They psychologist patiently listens to your problems")
if "PSYCHOLOGIST_STAGE" in self.disease_stage:
messages.extend(self.change_stage(self.disease_stage["PSYCHOLOGIST_STAGE"]))
return messages
def read(self, hours):
messages = self.add_hours(hours)
hours = max(0, min(hours, 4 - self.hours_read))
self.hours_read += hours
self.mood += 5 * hours
return messages
def watch(self, hours):
messages = self.add_hours(hours)
hours = max(0, min(hours, 4 - self.hours_watched))
self.hours_watched += hours
self.mood += 5 * hours
return messages
def get_validate_hour_str(hours):
"""Given an int of hours, create the hour string the validate method needs"""
hour_str = ""
if hours == 1:
hour_str = "after 1 hour "
elif hours > 1:
hour_str = "after " + str(hours) + " hours "
return hour_str
def validate_int_arg(f):
@wraps(f)
def wrapper(self, arg):
try:
hours = int(arg)
except ValueError:
print("\tThis command requires a number of hours, as in 'sleep 8'")
self.bad_command = True
return None
if hours <= 0:
print("\tThis command requires a positive number of hours, as in 'sleep 8'")
self.bad_command = True
return None
if "MEAL_TIMES" in self.character.disease_stage:
if (self.character.hours_played % 24 <= self.character.disease_stage["MEAL_TIMES"][0] and
(self.character.hours_played % 24) + hours > self.character.disease_stage["MEAL_TIMES"][0]):
hours = self.character.disease_stage["MEAL_TIMES"][0] - (self.character.hours_played % 24)
hour_str = get_validate_hour_str(hours)
print("\tA nurse stops you " + hour_str + "to tell you it is breakfast time")
if (self.character.hours_played % 24 <= self.character.disease_stage["MEAL_TIMES"][1] and
(self.character.hours_played % 24) + hours > self.character.disease_stage["MEAL_TIMES"][1]):
hours = self.character.disease_stage["MEAL_TIMES"][1] - (self.character.hours_played % 24)
hour_str = get_validate_hour_str(hours)
print("\tA nurse stops you " + hour_str + "to tell you it is lunch time")
if (self.character.hours_played % 24 <= self.character.disease_stage["MEAL_TIMES"][2] and
(self.character.hours_played % 24) + hours > self.character.disease_stage["MEAL_TIMES"][2]):
hours = self.character.disease_stage["MEAL_TIMES"][2] - (self.character.hours_played % 24)
hour_str = get_validate_hour_str(hours)
print("\tA nurse stops you " + hour_str + "to tell you it is dinner time")
if hours == 0:
self.bad_command = True
return None
return f(self, hours)
return wrapper
class Sdabto_Cmd(cmd.Cmd):
prompt = 'What would you like to do? '
def __init__(self, character):
super(Sdabto_Cmd, self).__init__()
self.character = character
self.bad_command = False
def print_status(self):
messages = []
hunger_time = MEAL_INTERVAL
if "HUNGER_DELAY" in self.character.disease_stage:
hunger_time += self.character.disease_stage["HUNGER_DELAY"]
if self.character.last_meal > hunger_time:
messages.append("You feel hungry")
if self.character.last_sleep > SLEEP_INTERVAL:
messages.append("You feel sleepy")
if self.character.last_exercise > EXERCISE_INTERVAL:
messages.append("You feel lethargic")
if self.character.last_social > SOCIAL_INTERVAL:
messages.append("You feel lonely")
if self.character.last_cleaned > CLEANING_INTERVAL:
messages.append("Your house is a mess")
for message in messages:
print("\t" + message)
print()
mood = self.character.display_mood()
energy = self.character.display_energy()
day = (self.character.hours_played // 24) + 1
hour = self.character.hours_played % 24
print("Day: " + str(day) + " Hour: " + str(hour) + " Mood: " + str(mood) +
" Energy: " + str(energy) + " Money: $" + str(self.character.money) +
" Food: " + str(self.character.groceries) + " meals")
def preloop(self):
print("Welcome to Some Days Are Better Than Others")
print("Trigger Warning: Suicide")
print()
print("You live alone and do freelance work from your computer.")
print("You enjoy gaming, watching movies, and hanging out with friends.")
print("You'd like to save up some money and go to university one day.")
print("Take life one day at a time.")
print()
print("Type 'help' or '?' for some ideas of what to do")
print()
self.print_status()
def postloop(self):
print()
print("This game was based on my own experiences.")
print("All the thoughts are thoughts I've had,")
print("and all the situations are based on things I've experienced.")
print("This may be different from your experiences with mental illness.")
print("I don't mean to imply that this is everyone's reality,")
print("but I wanted to give you a glimpse of mine.")
print("Thanks for playing along.")
print()
print("Goodbye")
def default(self, line):
print("\tSorry, that command is not recognized. Try 'help' or '?' for suggestions")
self.bad_command = True
def precmd(self, line):
if line.startswith("exec"):
return line
return line.lower()
def postcmd(self, stop, line):
if self.character.dead:
print()
print("You have died. Game over")
return True
if not stop and not line.startswith("help") and not line.startswith("?") and not self.bad_command:
if random.random() < self.character.disease_stage.get("LOSS_OF_CONTROL_CHANCE", 0):
print("\tYou lose control for about 8 hours")
messages = self.character.add_hours(8)
activity = random.choice(self.character.disease_stage["ACTIVITIES"])
if activity == "SHOPPING":
messages.append("You go shopping and spend all of your money on home furnishings")
self.character.money -= 500
elif activity == "DRIVING":
messages.append("You rent a car and go for a drive. You find yourself driving much too fast")
if random.random() < SPEEDING_RISK:
messages.append("You get into a terrible car accident. You and the other driver are both killed")
messages.append("Game over")
self.character.dead = True
return True
elif activity == "ART":
messages.append("You start creating a gorgeous calligraphy project")
elif activity == "MUSIC":
messages.append("You find yourself thinking in rhymes and start writing songs")
for message in messages:
print('\t' + message)
self.print_status()
print()
self.bad_command = False
return stop
#def do_exec(self, arg):
# """for debugging only"""
# exec(arg)
def do_exit(self, arg):
"""Exit the program"""
return True
def do_quit(self, arg):
"""Exit the program"""
return True
def do_clean(self, arg):
"""Clean your house"""
if "HOSPITAL_ACTIVITIES" in self.character.disease_stage:
print("\tYou're not at home right now")
return
if random.random() < self.character.disease_stage.get("WORK_FAILURE", 0):
print("\tYou can't be bothered to clean anything right now")
return
if self.character.display_energy() < 20:
print("\tYou're too tired to face cleaning right now")
return
messages = self.character.clean()
messages.append("You clean your house")
for message in messages:
print("\t" + message)
def do_eat(self, arg):
"""Eat a meal"""
if self.character.hours_played % 24 not in self.character.disease_stage.get("MEAL_TIMES", range(24)):
print("\tIt is not meal time yet")
return
if (self.character.last_meal < 4 or
random.random() < self.character.disease_stage.get("EAT_FAILURE", 0)):
print("\tYou don't feel like eating right now")
return
if self.character.groceries < 1:
print("\tYou are out of food. Try 'shop' to get more")
return
messages = self.character.eat()
messages.append("You eat a meal")
for message in messages:
print("\t" + message)
@validate_int_arg
def do_work(self, hours):
"""Work to gain money. Please supply a number of hours, as in 'work 4' """
if "HOSPITAL_ACTIVITIES" in self.character.disease_stage:
print("\tYour doctor doesn't want you to work while you're in the hospital")
return
if random.random() < self.character.disease_stage.get("WORK_FAILURE", 0):
print("\tYou sit down to work but end up playing video games instead")
self.do_game(hours)
return
if self.character.display_energy() < 20:
print("\tYou try to work but your eyes can't focus on the screen.")
return
if hours > 8:
print("\tAfter 8 hours your mind starts to wander...")
hours = 8
elif random.random() < self.character.disease_stage.get("FOCUS_CHANCE", 0):
print("\tYou get in the zone and loose track of time. You work for 8 hours")
hours = 8
messages = self.character.work(hours)
messages.append("You go to your computer and work. You gain $" + str(10 * hours))
for message in messages:
print("\t" + message)
@validate_int_arg
def do_sleep(self, hours):
"""Sleep to get your energy back. Please supply a number of hours, as in 'sleep 8' """
if "SLEEP_CAP" in self.character.disease_stage:
if hours > self.character.disease_stage["SLEEP_CAP"]:
print("\tYou can't sleep. You wake up early feeling fully rested")
hours = self.character.disease_stage["SLEEP_CAP"]
if hours > 12:
print("\tAfter 12 hours you wake up.")
hours = 12
messages = self.character.sleep(hours)
messages.append("You sleep for " + str(hours) + " hours. Your energy is now " + str(self.character.display_energy()))
if "WAKEUP_DELAY" in self.character.disease_stage:
hour_str = " hours"
if self.character.disease_stage["WAKEUP_DELAY"] == 1:
hour_str = " hour"
messages.append("You stay in bed for " + str(self.character.disease_stage["WAKEUP_DELAY"]) + hour_str)
messages.extend(self.character.add_hours(self.character.disease_stage["WAKEUP_DELAY"]))
for message in messages:
print("\t" + message)
def do_exercise(self, arg):
"""Go for a run"""
if "HOSPITAL_ACTIVITIES" in self.character.disease_stage:
print("\tYou're not allowed outside yet")
return
if self.character.hours_played % 24 in self.character.disease_stage.get("MEAL_TIMES", []):
print("\tA nurse stops you to tell you it is meal time")
return
if self.character.display_energy() < 20:
print("\tContemplating a run makes you feel exhausted. Maybe tomorrow...")
return
messages = self.character.exercise()
messages.append("You go for a run")
for message in messages:
print("\t" + message)
def do_shop(self, arg):
"""Buy more groceries"""
if "HOSPITAL_ACTIVITIES" in self.character.disease_stage:
print("\tYou're not allowed outside yet")
return
if self.character.hours_played % 24 in self.character.disease_stage.get("MEAL_TIMES", []):
print("\tA nurse stops you to tell you it is meal time")
return
if self.character.display_energy() < 10:
print("\tYou're too tired to haul home food. There must be something in the fridge...")
return
if self.character.hours_played % 24 < 8 or self.character.hours_played % 24 > 22:
print("\tThe grocery store is closed right now.")
return
if self.character.groceries > 21:
print("\tYour fridge is too full for more groceries")
else:
messages = self.character.shopping()
messages.append("You buy another week of groceries")
for message in messages:
print("\t" + message)
@validate_int_arg
def do_game(self, hours):
"""Play video games. Please supply a number of hours, as in 'game 1' """
if hours > 8:
print("\tAfter 8 hours you lose interest")
hours = 8
elif random.random() < self.character.disease_stage.get("FOCUS_CHANCE", 0):
print("\tYou get in the zone and loose track of time. You game for 8 hours")
hours = 8
messages = self.character.game(hours)
messages.append("You play on your computer. Your mood is now " + str(self.character.display_mood()))
for message in messages:
print("\t" + message)
@validate_int_arg
def do_socialize(self, hours):
"""Go out with friends. Please supply a number of hours, as in 'socialize 2' """
if "HOSPITAL_ACTIVITIES" in self.character.disease_stage:
print("\tYou're not allowed outside yet")
return
if self.character.display_energy() < 20:
print("\tYou can't summon the energy to face people right now. How about a quiet night in?")
return
if random.random() < self.character.disease_stage.get("SOCIALIZE_FAILURE", 0):
print("\tYou get too anxious thinking about people right now. How about a quiet night in?")
return
if hours > 6:
print("\tNone of your friends are free for more than 6 hours")
hours = 6
elif random.random() < self.character.disease_stage.get("FOCUS_CHANCE", 0):
print("\tYou lose track of time and stay out for 6 hours")
hours = 6
effect = random.choice(self.character.disease_stage["SOCIALIZING_EFFECTS"])
if effect == "DRUNK":
print("\tYou have a drink, and then another and another and another. You black out")
if random.random() < ALCOHOL_POISONING_CHANCE:
print("\tYou get severe alcohol poisoning")
self.character.dead = True
return True
print("\tLater your friends, freaked out, tell you you thought you were a character from the last book you read")
elif effect == "INAPPROPRIATE":
print("\tYou start making more and more inappropriate jokes. Some people laugh riotously, but an old friend looks disgusted")
elif effect == "PROMISCUOUS":
print("\tYou hook up with someone you just met")
messages = self.character.socialize(hours)
messages.append("You hang out with friends. You spend $" + str(10 * hours))
for message in messages:
print("\t" + message)
def do_call(self, arg):
"""Call someone on the phone, as in 'call mom' """
if self.character.hours_played % 24 in self.character.disease_stage.get("MEAL_TIMES", []):
print("\tA nurse stops you to tell you it is meal time")
return
caller_known = False
for key, synonym_list in CALL_DICT.items():
if arg in synonym_list:
caller_known = True
break
if not caller_known:
print("\tSorry, recipient unknown")
return
for message in self.character.call(arg):
print("\t" + message)
@validate_int_arg
def do_read(self, hours):
"""Read a book. Please supply a number of hours, as in 'read 4' """
if random.random() < self.character.disease_stage.get("LEISURE_FAILURE", 0):
print("\tYou try to read but the words swim on the page")
return
if hours > 4:
hours = 4
print("\tAfter 4 hours you lose interest")
messages = self.character.read(hours)
messages.append("You read a book")
for message in messages:
print("\t" + message)
@validate_int_arg
def watch(self, hours):
if random.random() < self.character.disease_stage.get("LEISURE_FAILURE", 0):
print("\tYou try to watch something but you can't stay focused on the plot")
return None
if hours > 4:
hours = 4
print("\tAfter 4 hours you lose interest")
messages = self.character.watch(hours)
return messages
def do_watch(self, arg):
"""Watch tv or a movie for a number of hours, as in 'watch movie 4' """
args = arg.split()
if len(args) < 2:
print("\tPlease pick tv or movie and give a number of hours, as in 'watch movie 4'")
return
if args[0] != "tv" and args[0] != "movie":
print("\tYou can watch tv or movies, as in 'watch movie 4'")
return
messages = self.watch(args[1])
if messages is None:
return
article = ""
if args[0] == "movie":
article = "a "
messages.append("You watch " + article + args[0])
for message in messages:
print("\t" + message)
def main():
Sdabto_Cmd(Character()).cmdloop()
if __name__ == '__main__':
main()
|
UTF-8
|
Python
| false | false | 2,014 |
3,083,786,561,910 |
67c994e2cde2c20e9c8074de9e0e80c33c2ef883
|
364e81cb0c01136ac179ff42e33b2449c491b7e5
|
/spell/tags/2.0.9/src/spell/spell/lang/helpers/tmhelper.py
|
cf2db8a95cd2785e9aa7a23a7611818b2d882330
|
[] |
no_license
|
unnch/spell-sat
|
https://github.com/unnch/spell-sat
|
2b06d9ed62b002e02d219bd0784f0a6477e365b4
|
fb11a6800316b93e22ee8c777fe4733032004a4a
|
refs/heads/master
| 2021-01-23T11:49:25.452995 | 2014-10-14T13:04:18 | 2014-10-14T13:04:18 | 42,499,379 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
###################################################################################
## MODULE : spell.lang.helpers.tmhelper
## DATE : Mar 18, 2011
## PROJECT : SPELL
## DESCRIPTION: Helpers for telemetry functions
## --------------------------------------------------------------------------------
##
## Copyright (C) 2008, 2011 SES ENGINEERING, Luxembourg S.A.R.L.
##
## This file is part of SPELL.
##
## This component is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This software is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with SPELL. If not, see <http://www.gnu.org/licenses/>.
##
###################################################################################
from basehelper import WrapperHelper
from spell.lang.constants import *
from spell.lang.modifiers import *
from spell.lib.adapter.constants.notification import *
from spell.lib.exception import SyntaxException
from spell.lang.functions import *
from spell.lib.registry import *
################################################################################
class GetTM_Helper(WrapperHelper):
"""
DESCRIPTION:
Helper for the GetTM wrapper.
"""
# Name of the parameter to be checked
__parameter = None
__extended = False
#===========================================================================
def __init__(self):
WrapperHelper.__init__(self, "TM")
self.__parameter = None
self.__extended = False
self._opName = None
#===========================================================================
def _doPreOperation(self, *args, **kargs):
from spell.lib.adapter.tm_item import TmItemClass
if len(args)==0:
raise SyntaxException("No parameter name given")
# Check correctness
param = args[0]
if type(param) != str:
if not isinstance(param,TmItemClass):
raise SyntaxException("Expected a TM item or name")
# It is a TmItemClass, store it
self.__parameter = param
else:
# Create the parameter and store it
self.__parameter = REGISTRY['TM'][param]
# Store the extended flag if any
self.__extended = (self.getConfig(Extended) == True)
#===========================================================================
def _doOperation(self, *args, **kargs ):
if self.getConfig(ValueFormat)==ENG:
self._write("Retrieving engineering value of " + repr(self.__pname()))
else:
self._write("Retrieving raw value of " + repr(self.__pname()))
value = None
# Refresh the object and return it
REGISTRY['TM'].refresh(self.__parameter, self.getConfig() )
if self.__extended == True:
value = self.__parameter
self._notifyValue( self.__pname(), "<OBJ>", NOTIF_STATUS_OK, "TM item obtained")
else: # Normal behavior
# Get the value in the desired format from the TM interface
value = self.__parameter.value(self.getConfig())
if self.getConfig(Wait)==True:
self._write("Last updated value of " + repr(self.__pname()) + ": " + str(value))
else:
self._write("Last recorded value of " + repr(self.__pname()) + ": " + str(value))
self._notifyValue( self.__pname(), str(value), NOTIF_STATUS_OK, "")
return [False, value,None,None]
#===========================================================================
def _doRepeat(self):
self._notifyValue( self.__pname(), "???", NOTIF_STATUS_PR, " ")
self._write("Retry get parameter " + self.__pname(), {Severity:WARNING} )
return [True, None]
#===========================================================================
def _doSkip(self):
self._notifyValue( self.__pname(), "???", NOTIF_STATUS_SP, " ")
self._write("Skip get parameter " + self.__pname(), {Severity:WARNING} )
return [False, None]
#===========================================================================
def __pname(self):
return self.__parameter.fullName()
################################################################################
class SetGroundParameter_Helper(WrapperHelper):
"""
DESCRIPTION:
Helper for the SetGroundParameter wrapper function.
"""
__toInject = None
__value = None
#===========================================================================
def __init__(self):
WrapperHelper.__init__(self, "TM")
self._opName = "Telemetry injection"
self.__toInject = None
self.__value = None
#===========================================================================
def _doPreOperation(self, *args, **kargs):
if len(args)==0:
raise SyntaxException("No parameters given")
# Since args is a tuple we have to convert it to a list
if len(args)!=1:
# The case of giving a simple inject definition
self.__toInject = args[0]
self.__value = args[1]
# Modifiers will go in useConfig
else:
# Givin an inject list
self.__toInject = args[0]
#===========================================================================
def _doOperation(self, *args, **kargs ):
if type(self.__toInject)==list:
result = REGISTRY['TM'].inject( self.__toInject, self.getConfig() )
if result == True:
self._write("Injected values: ")
for item in self.__toInject:
self._write(" - " + str(item[0]) + " = " + str(item[1]))
else:
self._write("Failed to inject values", {Severity:ERROR})
else:
result = REGISTRY['TM'].inject( self.__toInject, self.__value, self.getConfig() )
if result == True:
self._write("Injected value: " + str(self.__toInject) + " = " + str(self.__value))
else:
self._write("Failed to inject value", {Severity:ERROR})
return [False,result,NOTIF_STATUS_OK,""]
#===========================================================================
def _doRepeat(self):
self._write("Retry inject parameters", {Severity:WARNING} )
return [True, None]
#===========================================================================
def _doSkip(self):
self._write("Skip inject parameters", {Severity:WARNING} )
return [False, None]
################################################################################
class Verify_Helper(WrapperHelper):
"""
DESCRIPTION:
Helper for the Verify wrapper function.
"""
__retryAll = False
__retry = False
__useConfig = {}
__vrfDefinition = None
#===========================================================================
def __init__(self):
WrapperHelper.__init__(self, "TM")
self.__retryAll = False
self.__retry = False
self.__useConfig = {}
self.__vrfDefinition = None
self._opName = "Verification"
#===========================================================================
def _doPreOperation(self, *args, **kargs):
if len(args)==0:
raise SyntaxException("No arguments given")
self.__useConfig = {}
self.__useConfig.update(self.getConfig())
self.__useConfig[Retry] = self.__retry
# Since args is a tuple we have to convert it to a list for TM.verify
if len(args)!=1:
# The case of giving a simple step for verification
self.__vrfDefinition = [ item for item in args ]
else:
# Givin a step or a step list
self.__vrfDefinition = args[0]
#===========================================================================
def _doOperation(self, *args, **kargs ):
self._notifyOpStatus( NOTIF_STATUS_PR, "Verifying..." )
# Wait some time before verifying if requested
if self.__useConfig.has_key(Delay):
delay = self.__useConfig.get(Delay)
if delay:
from spell.lang.functions import WaitFor
self._write("Waiting "+ str(delay) + " seconds before TM verification", {Severity:INFORMATION})
WaitFor(delay)
result = REGISTRY['TM'].verify( self.__vrfDefinition, self.__useConfig )
# If we reach here, result can be true or false, but no exception was raised
# this means that a false verification is considered ok.
return [False,result,NOTIF_STATUS_OK,""]
#===========================================================================
def _doSkip(self):
if self.getConfig(PromptUser)==True:
self._write("Verification skipped", {Severity:WARNING} )
return [False,True]
#===========================================================================
def _doCancel(self):
if self.getConfig(PromptUser)==True:
self._write("Verification cancelled", {Severity:WARNING} )
return [False,False]
#===========================================================================
def _doRecheck(self):
self._write("Retry verification", {Severity:WARNING} )
return [True,False]
################################################################################
class SetLimits_Helper(WrapperHelper):
"""
DESCRIPTION:
Helper for the SetTMparam wrapper function.
"""
__parameter = None
__limits = {}
#===========================================================================
def __init__(self):
WrapperHelper.__init__(self, "TM")
self.__parameter = None
self.__limits = {}
self._opName = ""
#===========================================================================
def _doPreOperation(self, *args, **kargs ):
if len(args)==0:
raise SyntaxException("No parameters given")
self.__parameter = args[0]
self.__limits = {}
if self.hasConfig(Limits):
llist = self.getConfig(Limits)
if type(llist)==list:
if len(llist)==2:
self.__limits[LoRed] = llist[0]
self.__limits[LoYel] = llist[0]
self.__limits[HiRed] = llist[1]
self.__limits[HiYel] = llist[1]
elif len(llist)==4:
self.__limits[LoRed] = llist[0]
self.__limits[LoYel] = llist[1]
self.__limits[HiRed] = llist[2]
self.__limits[HiYel] = llist[3]
else:
raise SyntaxException("Malformed limit definition")
elif type(llist)==dict:
self.__limits = llist
else:
raise SyntaxException("Expected list or dictionary")
else:
if self.hasConfig(LoRed): self.__limits[LoRed] = self.getConfig(LoRed)
if self.hasConfig(LoYel): self.__limits[LoYel] = self.getConfig(LoYel)
if self.hasConfig(HiRed): self.__limits[HiRed] = self.getConfig(HiRed)
if self.hasConfig(HiYel): self.__limits[HiYel] = self.getConfig(HiYel)
if self.hasConfig(LoBoth):
self.__limits[LoYel] = self.getConfig(LoBoth)
self.__limits[LoRed] = self.getConfig(LoBoth)
if self.hasConfig(HiBoth):
self.__limits[HiYel] = self.getConfig(HiBoth)
self.__limits[HiRed] = self.getConfig(HiBoth)
if self.hasConfig(Expected):
self.__limits[Expected] = self.getConfig(Expected)
if len(self.__limits)==0:
raise SyntaxException("No limits given")
#===========================================================================
def _doOperation(self, *args, **kargs ):
result = REGISTRY['TM'].setLimits( self.__parameter, self.__limits, config = self.getConfig() )
return [False,result,NOTIF_STATUS_OK,""]
#===========================================================================
def _doRepeat(self):
self._write("Retry modify parameters", {Severity:WARNING} )
return [True, None]
#===========================================================================
def _doSkip(self):
self._write("Skipped modify parameters", {Severity:WARNING} )
return [False, None]
#===========================================================================
def _doCancel(self):
self._write("Cancel modify parameters", {Severity:WARNING} )
return [False, None]
################################################################################
class GetLimits_Helper(WrapperHelper):
"""
DESCRIPTION:
Helper for the GetTMparam wrapper function.
"""
__parameter = None
__property = None
#===========================================================================
def __init__(self):
WrapperHelper.__init__(self, "TM")
self.__parameter = None
self.__property = None
self._opName = ""
#===========================================================================
def _doPreOperation(self, *args, **kargs ):
if len(args)==0:
raise SyntaxException("No parameters given")
self.__parameter = args[0]
self.__property = args[1]
#===========================================================================
def _doOperation(self, *args, **kargs ):
result = None
limits = REGISTRY['TM'].getLimits( self.__parameter, config = self.getConfig() )
if self.__property == LoRed:
result = limits[0]
elif self.__property == LoYel:
result = limits[1]
elif self.__property == HiYel:
result = limits[2]
elif self.__property == HiRed:
result = limits[3]
else:
raise DriverException("Cannot get property", "Unknown property name: " + repr(self.__property))
return [False,result,NOTIF_STATUS_OK,""]
#===========================================================================
def _doRepeat(self):
self._write("Retry get property", {Severity:WARNING} )
return [True, None]
#===========================================================================
def _doSkip(self):
self._write("Skipped get property", {Severity:WARNING} )
return [False, None]
#===========================================================================
def _doCancel(self):
self._write("Cancel get property", {Severity:WARNING} )
return [False, None]
################################################################################
class LoadLimits_Helper(WrapperHelper):
"""
DESCRIPTION:
Helper for the GetTMparam wrapper function.
"""
__limitsFile = None
__retry = False
__prefix = None
#===========================================================================
def __init__(self):
WrapperHelper.__init__(self, "TM")
self.__limitsFile = None
self.__retry = False
self.__prefix = None
self._opName = ""
#===========================================================================
def _doPreOperation(self, *args, **kargs ):
if len(args)==0:
raise SyntaxException("No limits file URL given")
self.__limitsFile = args[0]
#===========================================================================
def _doOperation(self, *args, **kargs ):
result = None
if not self.__retry:
# Get the database name
self.__limitsFile = args[0]
if type(self.__limitsFile)!=str:
raise SyntaxException("Expected a limits file URL")
if not "://" in self.__limitsFile:
raise SyntaxException("Limits file name must have URI format")
idx = self.__limitsFile.find("://")
self.__prefix = self.__limitsFile[0:idx]
else:
self.__retry = False
idx = self.__limitsFile.find("//")
toShow = self.__limitsFile[idx+2:]
self._notifyValue( "Limits File", repr(toShow), NOTIF_STATUS_PR, "Loading")
self._write("Loading limits file " + repr(toShow))
result = REGISTRY['TM'].loadLimits( self.__limitsFile, config = self.getConfig() )
return [False,result,NOTIF_STATUS_OK,""]
#===========================================================================
def _doRepeat(self):
self._write("Load limits file failed, getting new name", {Severity:WARNING} )
idx = self.__limitsFile.find("//")
toShow = self.__limitsFile[idx+2:]
newName = str(self._prompt("Enter new limits file name (previously " + repr(toShow) + "): ", [], {} ))
if not newName.startswith(self.__prefix):
newName = self.__prefix + "://" + newName
self.__limitsFile = newName
self.__retry = True
return [True, None]
#===========================================================================
def _doSkip(self):
self._write("Skipped load limits file", {Severity:WARNING} )
return [False, None]
#===========================================================================
def _doCancel(self):
self._write("Cancel load limits file", {Severity:WARNING} )
return [False, None]
|
UTF-8
|
Python
| false | false | 2,014 |
14,018,773,264,189 |
be6f610e005c29a4979cf30512acbfa1d25bbda2
|
92e31ccc6f1dae3d62b727b7adaddb894e72b9a1
|
/tags/0.1-alpha/src-0.1-alpha/examples/kusp/subsystems/gsched/tools/groupviewer/gshobjects/__init__.py
|
14e38d2e1779057fd5b38cf3aecada6a7beedf07
|
[] |
no_license
|
dillonhicks/ipymake
|
https://github.com/dillonhicks/ipymake
|
3ae9fe8a976faf8f41b8ee2bf2b8d20eee856000
|
dbd4fc09e468d16a2de8f4be2357e8b4f64a702c
|
refs/heads/master
| 2020-04-13T01:31:36.480051 | 2013-06-20T19:39:27 | 2013-06-20T19:39:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from gshobjects import *
from gshwidgets import *
from gshsdf import *
from gshtoolbar import *
from builtinsdfs import *
|
UTF-8
|
Python
| false | false | 2,013 |
16,578,573,792,915 |
ce183f1439a6495472bb321fc2242523c6dc290e
|
b69d69e346aa49993ca5fff8d35d0f15d564c6d8
|
/~/Downloads/google-cloud-sdk/.install/.backup/lib/googlecloudsdk/calliope/__init__.py
|
1fe8da21a73fef7d0c622986c4d029d074c82503
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
non_permissive
|
squarethecircle/snapBetter
|
https://github.com/squarethecircle/snapBetter
|
07c14f74f147dac3548139263fb1b0942106996f
|
28a12292bc723ee153306294a82b37b27572ebe2
|
refs/heads/master
| 2021-01-19T20:37:16.349189 | 2014-07-28T17:17:28 | 2014-07-28T17:17:28 | 18,232,802 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# Copyright 2013 Google Inc. All Rights Reserved.
"""The calliope CLI/API is a framework for building library interfaces."""
import abc
import argparse
import errno
import imp
import json
import os
import pprint
import re
import sys
import textwrap
import uuid
import argcomplete
from googlecloudsdk.calliope import actions
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.calliope import shell
from googlecloudsdk.calliope import usage_text
from googlecloudsdk.core import log
from googlecloudsdk.core import metrics
from googlecloudsdk.core import properties
class LayoutException(Exception):
"""LayoutException is for problems with module directory structure."""
pass
class ArgumentException(Exception):
"""ArgumentException is for problems with the provided arguments."""
pass
class MissingArgumentException(ArgumentException):
"""An exception for when required arguments are not provided."""
def __init__(self, command_path, missing_arguments):
"""Creates a new MissingArgumentException.
Args:
command_path: A list representing the command or group that had the
required arguments
missing_arguments: A list of the arguments that were not provided
"""
message = ('The following required arguments were not provided for command '
'[{0}]: [{1}]'.format('.'.join(command_path),
', '.join(missing_arguments)))
super(MissingArgumentException, self).__init__(message)
class UnexpectedArgumentException(ArgumentException):
"""An exception for when required arguments are not provided."""
def __init__(self, command_path, unexpected_arguments):
"""Creates a new UnexpectedArgumentException.
Args:
command_path: A list representing the command or group that was given the
unexpected arguments
unexpected_arguments: A list of the arguments that were not valid
"""
message = ('The following arguments were unexpected for command '
'[{0}]: [{1}]'.format('.'.join(command_path),
', '.join(unexpected_arguments)))
super(UnexpectedArgumentException, self).__init__(message)
class _Args(object):
"""A helper class to convert a dictionary into an object with properties."""
def __init__(self, args):
self.__dict__.update(args)
def __str__(self):
return '_Args(%s)' % pprint.pformat(self.__dict__)
def __iter__(self):
for key, value in sorted(self.__dict__.iteritems()):
yield key, value
class _ArgumentInterceptor(object):
"""_ArgumentInterceptor intercepts calls to argparse parsers.
The argparse module provides no public way to access a complete list of
all arguments, and we need to know these so we can do validation of arguments
when this library is used in the python interpreter mode. Argparse itself does
the validation when it is run from the command line.
Attributes:
parser: argparse.Parser, The parser whose methods are being intercepted.
allow_positional: bool, Whether or not to allow positional arguments.
defaults: {str:obj}, A dict of {dest: default} for all the arguments added.
required: [str], A list of the dests for all required arguments.
dests: [str], A list of the dests for all arguments.
positional_args: [argparse.Action], A list of the positional arguments.
flag_args: [argparse.Action], A list of the flag arguments.
Raises:
ArgumentException: if a positional argument is made when allow_positional
is false.
"""
class ParserData(object):
def __init__(self):
self.defaults = {}
self.required = []
self.dests = []
self.mutex_groups = {}
self.positional_args = []
self.flag_args = []
def __init__(self, parser, allow_positional, data=None, mutex_group_id=None):
self.parser = parser
self.allow_positional = allow_positional
self.data = data or _ArgumentInterceptor.ParserData()
self.mutex_group_id = mutex_group_id
@property
def defaults(self):
return self.data.defaults
@property
def required(self):
return self.data.required
@property
def dests(self):
return self.data.dests
@property
def mutex_groups(self):
return self.data.mutex_groups
@property
def positional_args(self):
return self.data.positional_args
@property
def flag_args(self):
return self.data.flag_args
# pylint: disable=g-bad-name
def add_argument(self, *args, **kwargs):
"""add_argument intercepts calls to the parser to track arguments."""
# TODO(user): do not allow short-options without long-options.
# we will choose the first option as the name
name = args[0]
positional = not name.startswith('-')
if positional and not self.allow_positional:
# TODO(user): More informative error message here about which group
# the problem is in.
raise ArgumentException('Illegal positional argument: ' + name)
if positional and '-' in name:
raise ArgumentException(
"Positional arguments cannot contain a '-': " + name)
dest = kwargs.get('dest')
if not dest:
# this is exactly what happens in argparse
dest = name.lstrip(self.parser.prefix_chars).replace('-', '_')
default = kwargs.get('default')
required = kwargs.get('required')
self.defaults[dest] = default
if required:
self.required.append(dest)
self.dests.append(dest)
if self.mutex_group_id:
self.mutex_groups[dest] = self.mutex_group_id
if positional and 'metavar' not in kwargs:
kwargs['metavar'] = name.upper()
added_argument = self.parser.add_argument(*args, **kwargs)
if positional:
self.positional_args.append(added_argument)
else:
self.flag_args.append(added_argument)
return added_argument
# pylint: disable=redefined-builtin
def register(self, registry_name, value, object):
return self.parser.register(registry_name, value, object)
def set_defaults(self, **kwargs):
return self.parser.set_defaults(**kwargs)
def get_default(self, dest):
return self.parser.get_default(dest)
def add_argument_group(self, *args, **kwargs):
new_parser = self.parser.add_argument_group(*args, **kwargs)
return _ArgumentInterceptor(parser=new_parser,
allow_positional=self.allow_positional,
data=self.data)
def add_mutually_exclusive_group(self, **kwargs):
new_parser = self.parser.add_mutually_exclusive_group(**kwargs)
return _ArgumentInterceptor(parser=new_parser,
allow_positional=self.allow_positional,
data=self.data,
mutex_group_id=id(new_parser))
class _ConfigHooks(object):
"""This class holds function hooks for context and config loading/saving."""
def __init__(
self,
load_context=None,
context_filters=None,
group_class=None,
load_config=None,
save_config=None):
"""Create a new object with the given hooks.
Args:
load_context: a function that takes a config object and returns the
context to be sent to commands.
context_filters: a list of functions that take (contex, config, args),
that will be called in order before a command is run. They are
described in the README under the heading GROUP SPECIFICATION.
group_class: base.Group, The class that this config hooks object is for.
load_config: a zero-param function that returns the configuration
dictionary to be sent to commands.
save_config: a one-param function that takes a dictionary object and
serializes it to a JSON file.
"""
self.load_context = load_context if load_context else lambda cfg: {}
self.context_filters = context_filters if context_filters else []
self.group_class = group_class
self.load_config = load_config if load_config else lambda: {}
self.save_config = save_config if save_config else lambda cfg: None
def OverrideWithBase(self, group_base):
"""Get a new _ConfigHooks object with overridden functions based on module.
If module defines any of the function, they will be used instead of what
is in this object. Anything that is not defined will use the existing
behavior.
Args:
group_base: The base.Group class corresponding to the group.
Returns:
A new _ConfigHooks object updated with any newly found hooks
"""
def ContextFilter(context, config, args):
group = group_base(config=config)
group.Filter(context, args)
return group
# We want the new_context_filters to be a completely new list, if there is
# a change.
new_context_filters = self.context_filters + [ContextFilter]
return _ConfigHooks(load_context=self.load_context,
context_filters=new_context_filters,
group_class=group_base,
load_config=self.load_config,
save_config=self.save_config)
class _CommandCommon(object):
"""A base class for _CommandGroup and _Command.
It is responsible for extracting arguments from the modules and does argument
validation, since this is always the same for groups and commands.
"""
def __init__(self, module_dir, module_path, path, construction_id,
config_hooks, help_func, parser_group, allow_positional_args,
loader):
"""Create a new _CommandCommon.
Args:
module_dir: str, The path to the tools directory that this command or
group lives within. Used to find the command or group's source file.
module_path: [str], The command group names that brought us down to this
command group or command from the top module directory.
path: [str], Similar to module_path, but is the path to this command or
group with respect to the CLI itself. This path should be used for
things like error reporting when a specific element in the tree needs
to be referenced.
construction_id: str, A unique identifier for the CommandLoader that is
being constructed.
config_hooks: a _ConfigHooks object to use for loading/saving config.
help_func: func([command path]), A function to call with --help.
parser_group: argparse.Parser, The parser that this command or group will
live in.
allow_positional_args: bool, True if this command can have positional
arguments.
loader: CommandLoader, the CommandLoader hosting this calliope session.
"""
module = self._GetModuleFromPath(module_dir, module_path, path,
construction_id)
self._help_func = help_func
self._config_hooks = config_hooks
self._loader = loader
# pylint:disable=protected-access, The base module is effectively an
# extension of calliope, and we want to leave _Common private so people
# don't extend it directly.
common_type = base._Common.FromModule(module)
self.name = path[-1]
# For the purposes of argparse and the help, we should use dashes.
self.cli_name = self.name.replace('_', '-')
path[-1] = self.cli_name
self._module_path = module_path
self._path = path
self._construction_id = construction_id
self._common_type = common_type
self._common_type.group_class = config_hooks.group_class
if self._common_type.__doc__:
docstring = self._common_type.__doc__
# If there is more than one line, the first line is the short help and
# the rest is the long help.
docitems = docstring.split('\n', 1)
self.short_help = textwrap.dedent(docitems[0]).strip()
if len(docitems) > 1:
self.long_help = textwrap.dedent(docitems[1]).strip()
else:
self.long_help = None
if not self.long_help:
# Odd conditionals here in case an empty string is taken from the
# pydoc.
self.long_help = self.short_help
else:
self.short_help = None
self.long_help = None
self.detailed_help = getattr(self._common_type, 'detailed_help', {})
self._AssignParser(
parser_group=parser_group,
help_func=help_func,
allow_positional_args=allow_positional_args)
def _AssignParser(self, parser_group, help_func, allow_positional_args):
"""Assign a parser group to model this Command or CommandGroup.
Args:
parser_group: argparse._ArgumentGroup, the group that will model this
command or group's arguments.
help_func: func([str]), The long help function that is used for --help.
allow_positional_args: bool, Whether to allow positional args for this
group or not.
"""
if not parser_group:
# This is the root of the command tree, so we create the first parser.
self._parser = argparse.ArgumentParser(description=self.long_help,
add_help=False,
prog='.'.join(self._path))
else:
# This is a normal sub group, so just add a new subparser to the existing
# one.
self._parser = parser_group.add_parser(
self.cli_name,
help=self.short_help,
description=self.long_help,
add_help=False,
prog='.'.join(self._path))
# pylint:disable=protected-access
self._parser._check_value = usage_text.CheckValueAndSuggest
self._parser.error = usage_text.PrintParserError(self._parser)
self._sub_parser = None
self._ai = _ArgumentInterceptor(
parser=self._parser,
allow_positional=allow_positional_args)
self._AcquireArgs()
self._short_help_action = actions.ShortHelpAction(self, self._ai)
if help_func:
self._ai.add_argument(
'-h', action=self._short_help_action,
help='Print a summary help and exit.')
def LongHelp():
help_func(self._path)
self._ai.add_argument(
'--help', action=actions.FunctionExitAction(LongHelp),
help='Display detailed help.')
else:
self._ai.add_argument(
'-h', '--help', action=self._short_help_action,
help='Print a summary help and exit.')
def GetPath(self):
return self._path
def GetDocString(self):
if self.long_help:
return self.long_help
if self.short_help:
return self.short_help
return 'The {name} command.'.format(name=self.name)
def GetSubCommandHelps(self):
return {}
def GetSubGroupHelps(self):
return {}
def _GetModuleFromPath(self, module_dir, module_path, path, construction_id):
"""Import the module and dig into it to return the namespace we are after.
Import the module relative to the top level directory. Then return the
actual module corresponding to the last bit of the path.
Args:
module_dir: str, The path to the tools directory that this command or
group lives within.
module_path: [str], The command group names that brought us down to this
command group or command from the top module directory.
path: [str], The same as module_path but with the groups named as they
will be in the CLI.
construction_id: str, A unique identifier for the CommandLoader that is
being constructed.
Returns:
The imported module.
"""
src_dir = os.path.join(module_dir, *module_path[:-1])
f = None
try:
m = imp.find_module(module_path[-1], [src_dir])
f, file_path, items = m
# Make sure this module name never collides with any real module name.
# Use the CLI naming path, so values are always unique.
name = '__calliope__command__.{construction_id}.{name}'.format(
construction_id=construction_id,
name='.'.join(path).replace('-', '_'))
module = imp.load_module(name, f, file_path, items)
return module
finally:
if f:
f.close()
def _AcquireArgs(self):
"""Call the function to register the arguments for this module."""
args_func = self._common_type.Args
if not args_func:
return
args_func(self._ai)
def _GetSubPathsForNames(self, names):
"""Gets a list of (module path, path) for the given list of sub names.
Args:
names: The names of the sub groups or commands the paths are for
Returns:
A list of tuples of the new (module_path, path) for the given names.
These terms are that as used by the constructor of _CommandGroup and
_Command.
"""
return [(self._module_path + [name], self._path + [name]) for name in names]
def Parser(self):
"""Return the argparse parser this group is using.
Returns:
The argparse parser this group is using
"""
return self._parser
def SubParser(self):
"""Gets or creates the argparse sub parser for this group.
Returns:
The argparse subparser that children of this group should register with.
If a sub parser has not been allocated, it is created now.
"""
if not self._sub_parser:
self._sub_parser = self._parser.add_subparsers()
return self._sub_parser
def CreateNewArgs(self, kwargs, current_args, cli_mode):
"""Make a new argument dictionary from default, existing, and new args.
Args:
kwargs: The keyword args the user provided for this level
current_args: The arguments that have previously been collected at other
levels
cli_mode: True if we are doing arg parsing for cli mode.
Returns:
A new argument dictionary
"""
if cli_mode:
# We are binding one big dictionary of arguments. Filter out all the
# arguments that don't belong to this level.
filtered_kwargs = {}
for key, value in kwargs.iteritems():
if key in self._ai.dests:
filtered_kwargs[key] = value
kwargs = filtered_kwargs
# Make sure the args provided at this level are OK.
self._ValidateArgs(kwargs, cli_mode)
# Start with the defaults arguments for this level.
new_args = dict(self._ai.defaults)
# Add in anything that was already collected above us in the tree.
new_args.update(current_args)
# Add in the args from this invocation.
new_args.update(kwargs)
return new_args
def _ValidateArgs(self, args, cli_mode):
"""Make sure the given arguments are correct for this level.
Ensures that any required args are provided as well as that no unexpected
arguments were provided.
Args:
args: A dictionary of the arguments that were provided
cli_mode: True if we are doing arg parsing for cli mode.
Raises:
ArgumentException: If mutually exclusive arguments were both given.
MissingArgumentException: If there are missing required arguments.
UnexpectedArgumentException: If there are unexpected arguments.
"""
missed_args = []
for required in self._ai.required:
if required not in args:
missed_args.append(required)
if missed_args:
raise MissingArgumentException(self._path, missed_args)
unexpected_args = []
for dest in args:
if dest not in self._ai.dests:
unexpected_args.append(dest)
if unexpected_args:
raise UnexpectedArgumentException(self._path, unexpected_args)
if not cli_mode:
# We only need to do mutex group detections when binding args manually.
# Argparse will take care of this when on the CLI.
found_groups = {}
group_ids = self._ai.mutex_groups
for dest in sorted(args):
group_id = group_ids.get(dest)
if group_id:
found = found_groups.get(group_id)
if found:
raise ArgumentException('Argument {0} is not allowed with {1}'
.format(dest, found))
found_groups[group_id] = dest
class _CommandGroup(_CommandCommon):
"""A class to encapsulate a group of commands."""
def __init__(self, module_dir, module_path, path, construction_id,
parser_group, config_hooks, help_func, loader):
"""Create a new command group.
Args:
module_dir: always the root of the whole command tree
module_path: a list of command group names that brought us down to this
command group from the top module directory
path: similar to module_path, but is the path to this command group
with respect to the CLI itself. This path should be used for things
like error reporting when a specific element in the tree needs to be
referenced
construction_id: str, A unique identifier for the CommandLoader that is
being constructed.
parser_group: the current argparse parser, or None if this is the root
command group. The root command group will allocate the initial
top level argparse parser.
config_hooks: a _ConfigHooks object to use for loading/saving config
help_func: func([command path]), A function to call with --help.
loader: CommandLoader, the CommandLoader hosting this calliope session.
Raises:
LayoutException: if the module has no sub groups or commands
"""
super(_CommandGroup, self).__init__(
module_dir=module_dir,
module_path=module_path,
path=path,
construction_id=construction_id,
config_hooks=config_hooks,
help_func=help_func,
allow_positional_args=False,
parser_group=parser_group,
loader=loader)
self._module_dir = module_dir
self._LoadSubGroups()
self._parser.usage = usage_text.GenerateUsage(self, self._ai)
self._parser.error = usage_text.PrintShortHelpError(self._parser, self)
def _LoadSubGroups(self):
"""Load all of this group's subgroups and commands."""
self._config_hooks = self._config_hooks.OverrideWithBase(self._common_type)
# find sub groups and commands
self.groups = []
self.commands = []
(group_names, command_names) = self._FindSubGroups()
self.all_sub_names = set(group_names + command_names)
if not group_names and not command_names:
raise LayoutException('Group %s has no subgroups or commands'
% '.'.join(self._path))
# recursively create the tree of command groups and commands
sub_parser = self.SubParser()
for (new_module_path, new_path) in self._GetSubPathsForNames(group_names):
self.groups.append(
_CommandGroup(self._module_dir, new_module_path, new_path,
self._construction_id, sub_parser, self._config_hooks,
help_func=self._help_func, loader=self._loader))
for (new_module_path, new_path) in self._GetSubPathsForNames(command_names):
cmd = _Command(self._module_dir, new_module_path, new_path,
self._construction_id, self._config_hooks, sub_parser,
self._help_func, self._loader)
self.commands.append(cmd)
def MakeShellActions(self):
group_names = [group.name for group in self.groups]
command_names = [command.name for command in self.commands]
self._ai.add_argument(
'--shell',
action=shell.ShellAction(group_names + command_names, self._loader),
nargs='?',
help='Launch a subshell for this command or group.')
for group in self.groups:
group.MakeShellActions()
def GetSubCommandHelps(self):
return dict((item.cli_name, item.short_help or '')
for item in self.commands)
def GetSubGroupHelps(self):
return dict((item.cli_name, item.short_help or '')
for item in self.groups)
def GetHelpFunc(self):
return self._help_func
def AddSubGroups(self, groups):
"""Merges other command groups under this one.
If we load command groups for alternate locations, this method is used to
make those extra sub groups fall under this main group in the CLI.
Args:
groups: Any other _CommandGroup objects that should be added to the CLI
"""
self.groups.extend(groups)
for group in groups:
self.all_sub_names.add(group.name)
self._parser.usage = usage_text.GenerateUsage(self, self._ai)
def IsValidSubName(self, name):
"""See if the given name is a name of a registered sub group or command.
Args:
name: The name to check
Returns:
True if the given name is a registered sub group or command of this
command group.
"""
return name in self.all_sub_names
def _FindSubGroups(self):
"""Final all the sub groups and commands under this group.
Returns:
A tuple containing two lists. The first is a list of strings for each
command group, and the second is a list of strings for each command.
Raises:
LayoutException: if there is a command or group with an illegal name.
"""
location = os.path.join(self._module_dir, *self._module_path)
items = os.listdir(location)
groups = []
commands = []
items.sort()
for item in items:
name, ext = os.path.splitext(item)
itempath = os.path.join(location, item)
if ext == '.py':
if name == '__init__':
continue
elif not os.path.isdir(itempath):
continue
if re.search('[A-Z]', name):
raise LayoutException('Commands and groups cannot have capital letters:'
' %s.' % name)
if not os.path.isdir(itempath):
commands.append(name)
else:
init_path = os.path.join(itempath, '__init__.py')
if os.path.exists(init_path):
groups.append(item)
return groups, commands
class _Command(_CommandCommon):
"""A class that encapsulates the configuration for a single command."""
def __init__(self, module_dir, module_path, path, construction_id,
config_hooks, parser_group, help_func, loader):
"""Create a new command.
Args:
module_dir: str, The root of the command tree.
module_path: a list of command group names that brought us down to this
command from the top module directory
path: similar to module_path, but is the path to this command with respect
to the CLI itself. This path should be used for things like error
reporting when a specific element in the tree needs to be referenced
construction_id: str, A unique identifier for the CommandLoader that is
being constructed.
config_hooks: a _ConfigHooks object to use for loading/saving config
parser_group: argparse.Parser, The parser to be used for this command.
help_func: func([str]), Detailed help function.
loader: CommandLoader, the CommandLoader hosting this calliope session.
"""
super(_Command, self).__init__(
module_dir=module_dir,
module_path=module_path,
path=path,
construction_id=construction_id,
config_hooks=config_hooks,
help_func=help_func,
allow_positional_args=True,
parser_group=parser_group,
loader=loader)
self._parser.set_defaults(cmd_func=self.Run, command_path=self._path)
self._parser.usage = usage_text.GenerateUsage(self, self._ai)
def Run(self, args, command=None, cli_mode=False, pre_run_hooks=None,
post_run_hooks=None):
"""Run this command with the given arguments.
Args:
args: The arguments for this command as a namespace.
command: The bound Command object that is used to run this _Command.
cli_mode: If True, catch exceptions.ToolException and call Display().
pre_run_hooks: [_RunHook], Things to run before the command.
post_run_hooks: [_RunHook], Things to run after the command.
Returns:
The object returned by the module's Run() function.
Raises:
exceptions.ToolException: if thrown by the Run() function.
"""
command_path_string = '.'.join(self._path)
properties.VALUES.PushArgs(args)
# Enable user output for CLI mode only if it is not explicitly set in the
# properties (or given in the provided arguments that were just pushed into
# the properties object).
user_output_enabled = properties.VALUES.core.user_output_enabled.GetBool()
set_user_output_property = cli_mode and user_output_enabled is None
if set_user_output_property:
properties.VALUES.core.user_output_enabled.Set(True)
# Now that we have pushed the args, reload the settings so the flags will
# take effect. These will use the values from the properties.
old_user_output_enabled = log.SetUserOutputEnabled(None)
old_verbosity = log.SetVerbosity(None)
try:
if cli_mode and pre_run_hooks:
for hook in pre_run_hooks:
hook.Run(command_path_string)
config = self._config_hooks.load_config()
tool_context = self._config_hooks.load_context(config)
last_group = None
for context_filter in self._config_hooks.context_filters:
last_group = context_filter(tool_context, config, args)
command_instance = self._common_type(
context=tool_context,
config=config,
entry_point=command.EntryPoint(),
command=command,
group=last_group)
log.debug('Running %s with %s.', command_path_string, args)
result = command_instance.Run(args)
self._config_hooks.save_config(config)
command_instance.Display(args, result)
if cli_mode and post_run_hooks:
for hook in post_run_hooks:
hook.Run(command_path_string)
return result
except exceptions.ToolException as exc:
exc.command_name = command_path_string
log.file_only_logger.exception(exc)
if cli_mode:
log.error(exc)
sys.exit(1)
else:
raise
finally:
if set_user_output_property:
properties.VALUES.core.user_output_enabled.Set(None)
log.SetUserOutputEnabled(old_user_output_enabled)
log.SetVerbosity(old_verbosity)
properties.VALUES.PopArgs()
class UnboundCommandGroup(object):
"""A class to represent an unbound command group in the REPL.
Unbound refers to the fact that no arguments have been bound to this command
group yet. This object can be called with a set of arguments to set them.
You can also access any sub group or command of this group as a property if
this group does not require any arguments at this level.
"""
def __init__(self, parent_group, group):
"""Create a new UnboundCommandGroup.
Args:
parent_group: The BoundCommandGroup this is a descendant of or None if
this is the root command.
group: The _CommandGroup that this object is representing
"""
self._parent_group = parent_group
self._group = group
# We change the .__doc__ so that when calliope is used in interpreter mode,
# the user can inspect .__doc__ and get the help messages provided by the
# tool creator.
self.__doc__ = self._group.GetDocString()
def ParentGroup(self):
"""Gives you the bound command group this group is a descendant of.
Returns:
The BoundCommandGroup above this one in the tree or None if we are the top
"""
return self._parent_group
def __call__(self, **kwargs):
return self._BindArgs(kwargs=kwargs, cli_mode=False)
def _BindArgs(self, kwargs, cli_mode):
"""Bind arguments to this command group.
This is called with the kwargs to bind to this command group. It validates
that the group has registered the provided args and that any required args
are provided.
Args:
kwargs: The args to bind to this command group.
cli_mode: True if we are doing arg parsing for cli mode.
Returns:
A new BoundCommandGroup with the given arguments
"""
# pylint: disable=protected-access, We don't want to expose the member or an
# accessor since this is a user facing class. These three classes all work
# as a single unit.
current_args = self._parent_group._args if self._parent_group else {}
# Compute the new argument bindings for what was just provided.
new_args = self._group.CreateNewArgs(
kwargs=kwargs,
current_args=current_args,
cli_mode=cli_mode)
bound_group = BoundCommandGroup(self, self._group, self._parent_group,
new_args, kwargs)
return bound_group
def __getattr__(self, name):
"""Access sub groups or commands without using () notation.
Accessing a sub group or command without using the above call, implicitly
executes the binding with no arguments. If the context has required
arguments, this will fail.
Args:
name: the name of the attribute to get
Returns:
A new UnboundCommandGroup or Command created by binding this command group
with no arguments.
Raises:
AttributeError: if the given name is not a valid sub group or command
"""
# Map dashes in the CLI to underscores in the API.
name = name.replace('-', '_')
if self._group.IsValidSubName(name):
# Bind zero arguments to this group and then get the name we actually
# asked for
return getattr(self._BindArgs(kwargs={}, cli_mode=False), name)
raise AttributeError(name)
def Name(self):
return self._group.name
def HelpFunc(self):
return self._group.GetHelpFunc()
def __repr__(self):
s = ''
if self._parent_group:
s += '%s.' % repr(self._parent_group)
s += self.Name()
return s
class BoundCommandGroup(object):
"""A class to represent a bound command group in the REPL.
Bound refers to the fact that arguments have already been provided for this
command group. You can access sub groups or commands of this group as
properties.
"""
def __init__(self, unbound_group, group, parent_group, args, new_args):
"""Create a new BoundCommandGroup.
Args:
unbound_group: the UnboundCommandGroup that this BoundCommandGroup was
created from.
group: The _CommandGroup equivalent for this group.
parent_group: The BoundCommandGroup this is a descendant of
args: All the default and provided arguments from above and including
this group.
new_args: The args used to bind this command group, not including those
from its parent groups.
"""
self._unbound_group = unbound_group
self._group = group
self._parent_group = parent_group
self._args = args
self._new_args = new_args
# Create attributes for each sub group or command that can come next.
for group in self._group.groups:
setattr(self, group.name, UnboundCommandGroup(self, group))
for command in self._group.commands:
setattr(self, command.name, Command(self, command))
self.__doc__ = self._group.GetDocString()
def __getattr__(self, name):
# Map dashes in the CLI to underscores in the API.
fixed_name = name.replace('-', '_')
if name == fixed_name:
raise AttributeError
return getattr(self, fixed_name)
def UnboundGroup(self):
return self._unbound_group
def ParentGroup(self):
"""Gives you the bound command group this group is a descendant of.
Returns:
The BoundCommandGroup above this one in the tree or None if we are the top
"""
return self._parent_group
def __repr__(self):
s = ''
if self._parent_group:
s += '%s.' % repr(self._parent_group)
s += self._group.name
# There are some things in the args which are set by default, like cmd_func
# and command_path, which should not appear in the repr.
# pylint:disable=protected-access
valid_args = self._group._ai.dests
args = ', '.join(['{0}={1}'.format(arg, repr(val))
for arg, val in self._new_args.iteritems()
if arg in valid_args])
if args:
s += '(%s)' % args
return s
class Command(object):
"""A class representing a command that can be called in the REPL.
At this point, contexts about this command have already been created and bound
to any required arguments for those command groups. This object can be called
to actually invoke the underlying command.
"""
def __init__(self, parent_group, command):
"""Create a new Command.
Args:
parent_group: The BoundCommandGroup this is a descendant of
command: The _Command object to actually invoke
"""
self._parent_group = parent_group
self._command = command
# We change the .__doc__ so that when calliope is used in interpreter mode,
# the user can inspect .__doc__ and get the help messages provided by the
# tool creator.
self.__doc__ = self._command.GetDocString()
def ParentGroup(self):
"""Gives you the bound command group this group is a descendant of.
Returns:
The BoundCommandGroup above this one in the tree or None if we are the top
"""
return self._parent_group
def __call__(self, **kwargs):
return self._Execute(cli_mode=False, pre_run_hooks=None,
post_run_hooks=None, kwargs=kwargs)
def EntryPoint(self):
"""Get the entry point that owns this command."""
cur = self
while cur.ParentGroup():
cur = cur.ParentGroup()
if type(cur) is BoundCommandGroup:
cur = cur.UnboundGroup()
return cur
def _Execute(self, cli_mode, pre_run_hooks, post_run_hooks, kwargs):
"""Invoke the underlying command with the given arguments.
Args:
cli_mode: If true, run in CLI mode without checking kwargs for validity.
pre_run_hooks: [_RunHook], Things to run before the command.
post_run_hooks: [_RunHook], Things to run after the command.
kwargs: The arguments with which to invoke the command.
Returns:
The result of executing the command determined by the command
implementation
"""
# pylint: disable=protected-access, We don't want to expose the member or an
# accessor since this is a user facing class. These three classes all work
# as a single unit.
parent_args = self._parent_group._args if self._parent_group else {}
new_args = self._command.CreateNewArgs(
kwargs=kwargs,
current_args=parent_args,
cli_mode=cli_mode) # we ignore unknown when in cli mode
arg_namespace = _Args(new_args)
return self._command.Run(
args=arg_namespace, command=self, cli_mode=cli_mode,
pre_run_hooks=pre_run_hooks, post_run_hooks=post_run_hooks)
def __repr__(self):
s = ''
if self._parent_group:
s += '%s.' % repr(self._parent_group)
s += self._command.name
return s
class _RunHook(object):
"""Encapsulates a function to be run before or after command execution."""
def __init__(self, func, include_commands=None, exclude_commands=None):
"""Constructs the hook.
Args:
func: function, The no args function to run.
include_commands: str, A regex for the command paths to run. If not
provided, the hook will be run for all commands.
exclude_commands: str, A regex for the command paths to exclude. If not
provided, nothing will be excluded.
"""
self.__func = func
self.__include_commands = include_commands if include_commands else '.*'
self.__exclude_commands = exclude_commands
def Run(self, command_path):
"""Runs this hook if the filters match the given command.
Args:
command_path: str, The calliope command path for the command that was run.
Returns:
bool, True if the hook was run, False if it did not match.
"""
if not re.match(self.__include_commands, command_path):
return False
if self.__exclude_commands and re.match(self.__exclude_commands,
command_path):
return False
self.__func()
return True
class CommandLoader(object):
"""A class to encapsulate loading the CLI and bootstrapping the REPL."""
def __init__(self, name, command_root_directory,
top_level_command=None, module_directories=None,
allow_non_existing_modules=False, load_context=None,
config_file=None, logs_dir=None, version_func=None,
help_func=None):
"""Initialize Calliope.
Args:
name: str, The name of the top level command, used for nice error
reporting.
command_root_directory: str, The path to the directory containing the main
CLI module.
top_level_command: str, If provided, this command within
command_root_directory becomes the entire calliope command. There are
no groups at all, just this command at the top level.
module_directories: An optional dict of additional module directories
that should be loaded as subgroups under the root command. The key is
the name that identifies the command group that will be populated by
the module directory.
allow_non_existing_modules: True to allow extra module directories to not
exist, False to raise an exception if a module does not exist.
load_context: A function that takes the persistent config dict as a
parameter and returns a context dict, or None for a default which
always returns {}.
config_file: str, A path to a config file to use for json config
loading/saving, or None to disable config.
logs_dir: str, The path to the root directory to store logs in, or None
for no log files.
version_func: func, A function to call for a top-level -v and
--version flag. If None, no flags will be available.
help_func: func([command path]), A function to call for in-depth help
messages. It is passed the set of subparsers used (not including the
top-level command). After it is called calliope will exit. This function
will be called when a top-level 'help' command is run, or when the
--help option is added on to any command.
Raises:
LayoutException: If no command root directory is given, or if you provide
a top level command as well as additional module directories.
"""
self.name = name
if not command_root_directory:
raise LayoutException('You must specify a command root directory.')
if module_directories and top_level_command:
raise LayoutException('You may not specify a top level command as well as'
' additional module directories.')
if not module_directories:
module_directories = {}
self.config_file = config_file
self.config_hooks = _ConfigHooks(
load_context=load_context,
load_config=self._CreateLoadConfigFunction(),
save_config=self._CreateSaveConfigFunction())
if top_level_command:
result = self._LoadCLIFromSingleCommand(command_root_directory,
top_level_command,
help_func=help_func)
else:
result = self._LoadCLIFromGroups(command_root_directory,
module_directories,
allow_non_existing_modules,
help_func=help_func)
(self._top_element, self._parser, self._entry_point) = result
self.__pre_run_hooks = []
self.__post_run_hooks = []
if version_func is not None:
self._parser.add_argument(
'-v', '--version',
action=actions.FunctionExitAction(version_func),
help='Print version information.')
# pylint: disable=protected-access
self._top_element._ai.add_argument(
'--verbosity',
choices=log.VALID_VERBOSITY_STRINGS.keys(),
default=None,
help='Override the default verbosity for this command. This must be '
'a standard logging verbosity level: [{values}] (Default: [{default}]).'
.format(values=', '.join(log.VALID_VERBOSITY_STRINGS),
default=log.DEFAULT_VERBOSITY_STRING))
self._top_element._ai.add_argument(
'--user-output-enabled',
default=None,
choices=('true', 'false'),
help='Control whether user intended output is printed to the console. '
'(true/false)')
argcomplete.autocomplete(self._parser, always_complete_options=False)
# Some initialization needs to happen after autocomplete, so that it doesn't
# run each time tab is hit.
log.AddFileLogging(logs_dir)
def _CreateLoadConfigFunction(self):
"""Generates a function that loads config from a file if it is set.
Returns:
The function to load the configuration or None
"""
if not self.config_file:
return None
def _LoadConfig():
if os.path.exists(self.config_file):
with open(self.config_file) as cfile:
cfgdict = json.load(cfile)
if cfgdict:
return cfgdict
return {}
return _LoadConfig
def _CreateSaveConfigFunction(self):
"""Generates a function that saves config from a file if it is set.
Returns:
The function to save the configuration or None
"""
if not self.config_file:
return None
def _SaveConfig(cfg):
"""Save the config to the correct file."""
config_dir, _ = os.path.split(self.config_file)
try:
if not os.path.isdir(config_dir):
os.makedirs(config_dir)
except OSError as e:
if e.errno == errno.EEXIST and os.path.isdir(config_dir):
pass
else: raise
with open(self.config_file, 'w') as cfile:
json.dump(cfg, cfile, indent=2)
cfile.write('\n')
return _SaveConfig
def _LoadCLIFromSingleCommand(self, command_root_directory,
top_level_command, help_func=None):
"""Load the CLI from a single command.
When loaded for a single command, there are no groups and no global
arguments. This is use when a calliope command needs to be made a
standalone command.
Args:
command_root_directory: str, The path to the directory containing the main
CLI module to load.
top_level_command: str, The command name in the root directory that should
be made the entrypoint for the CLI.
help_func: func, If not None, call this function and exit when --help is
provided.
Raises:
LayoutException: If the top level command file does not exist.
Returns:
A tuple of the _Command object loaded from the given command, the argparse
parser for the command tree, and the entry point into the REPL.
"""
file_path = os.path.join(command_root_directory, top_level_command + '.py')
if not os.path.isfile(file_path):
raise LayoutException('The given command does not exist: {}'
.format(file_path))
top_command = _Command(
command_root_directory, [top_level_command], [self.name],
uuid.uuid4().hex, self.config_hooks, parser_group=None,
help_func=help_func, loader=self)
parser = top_command.Parser()
entry_point = Command(None, top_command)
return (top_command, parser, entry_point)
def _LoadCLIFromGroups(self, command_root_directory, module_directories,
allow_non_existing_modules, help_func=None):
"""Load the CLI from a command directory.
Args:
command_root_directory: str, The path to the directory containing the main
CLI module to load.
module_directories: An optional dict of additional module directories
that should be loaded as subgroups under the root command. The key is
the name that identifies the command group that will be populated by
the module directory.
allow_non_existing_modules: True to allow extra module directories to not
exist, False to raise an exception if a module does not exist.
help_func: func(command path), If not None, call this function and exit
when --help is provided with any command or group.
Returns:
A tuple of the _CommandGroup object loaded from the given command groups,
the argparse parser for the command tree, and the entry point into the
REPL.
"""
top_group = self._LoadGroup(self.name, command_root_directory, None,
help_func=help_func)
sub_parser = top_group.SubParser()
sub_groups = []
for module_name, module_directory in module_directories.iteritems():
group = self._LoadGroup(self.name, module_directory, sub_parser,
module_name=module_name,
allow_non_existing=allow_non_existing_modules,
help_func=help_func)
if group:
sub_groups.append(group)
top_group.AddSubGroups(sub_groups)
parser = top_group.Parser()
entry_point = UnboundCommandGroup(None, top_group)
return (top_group, parser, entry_point)
def _LoadGroup(self, command_name, module_directory, parser,
module_name=None, allow_non_existing=False,
help_func=None):
"""Loads a single command group from a directory.
Args:
command_name: The name of the top level command the group is being
registered under. This is used mainly for error reporting to users
when we need to identify the group or command where a problem has
occurred.
module_directory: The path to the location of the module
parser: The argparse parser the module should register itself with or None
if this is the top group.
module_name: An optional name override for the module. If not set, it will
default to using the name of the directory containing the module.
allow_non_existing: True to allow this module to not exist, False to raise
an exception if it does not exist.
help_func: func(command path), If not None, call this function and exit
when --help is provided with any command or group.
Raises:
LayoutException: If the module directory does not exist and
allow_non_existing is False.
Returns:
The _CommandGroup object, or None if the module directory does not exist
and allow_non_existing is True.
"""
if not os.path.isdir(module_directory):
if allow_non_existing:
return None
raise LayoutException('The given module directory does not exist: {}'
.format(module_directory))
module_root, module = os.path.split(module_directory)
if not module_name:
module_name = module
# If this is the top level, don't register the name of the module directory
# itself, it should assume the name of the command. If this is another
# module directory, its name gets explicitly registered under the root
# command.
is_top = not parser # Parser is undefined only for the top level command.
path = [command_name] if is_top else [command_name, module_name]
top_group = _CommandGroup(
module_root, [module], path, uuid.uuid4().hex, parser,
self.config_hooks, help_func=help_func, loader=self)
return top_group
def RegisterPreRunHook(self, func,
include_commands=None, exclude_commands=None):
"""Register a function to be run before command execution.
Args:
func: function, The no args function to run.
include_commands: str, A regex for the command paths to run. If not
provided, the hook will be run for all commands.
exclude_commands: str, A regex for the command paths to exclude. If not
provided, nothing will be excluded.
"""
hook = _RunHook(func, include_commands, exclude_commands)
self.__pre_run_hooks.append(hook)
def RegisterPostRunHook(self, func,
include_commands=None, exclude_commands=None):
"""Register a function to be run after command execution.
Args:
func: function, The no args function to run.
include_commands: str, A regex for the command paths to run. If not
provided, the hook will be run for all commands.
exclude_commands: str, A regex for the command paths to exclude. If not
provided, nothing will be excluded.
"""
hook = _RunHook(func, include_commands, exclude_commands)
self.__post_run_hooks.append(hook)
def Execute(self, args=None):
"""Execute the CLI tool with the given arguments.
Args:
args: The arguments from the command line or None to use sys.argv
"""
self.argv = args or sys.argv[1:]
args = self._parser.parse_args(self.argv)
command_path_string = '.'.join(args.command_path)
# TODO(user): put a real version here
metrics.Commands(command_path_string, None)
path = args.command_path[1:]
kwargs = args.__dict__
# Dig down into the groups and commands, binding the arguments at each step.
# If the path is empty, this means that we have an actual command as the
# entry point and we don't need to dig down, just call it directly.
# The command_path will be, eg, ['top', 'group1', 'group2', 'command'], and
# is set by each _Command when it's loaded from
# 'tools/group1/group2/command.py'. It corresponds also to the python object
# built to mirror the command line, with 'top' corresponding to the
# entry point returned by the EntryPoint() method. Then, in this case, the
# object found with self.EntryPoint().group1.group2.command is the runnable
# command being targetted by this operation. The following code segment
# does this digging and applies the relevant arguments at each step, taken
# from the argparse results.
# pylint: disable=protected-access
cur = self.EntryPoint()
while path:
cur = cur._BindArgs(kwargs=kwargs, cli_mode=True)
cur = getattr(cur, path[0])
path = path[1:]
cur._Execute(cli_mode=True, pre_run_hooks=self.__pre_run_hooks,
post_run_hooks=self.__post_run_hooks, kwargs=kwargs)
def EntryPoint(self):
"""Get the top entry point into the REPL for interactive mode.
Returns:
A REPL command group that allows you to bind args and call commands
interactively in the same way you would from the command line.
"""
return self._entry_point
|
UTF-8
|
Python
| false | false | 2,014 |
16,707,422,820,952 |
6fee7ccc76dccdce530f96c1a61ea383515785da
|
46e68298b98f2d05b9cb4f9cce38d19aef3ac358
|
/python/restore_ip_addresses.py
|
3b7572e7e075e2f6f054c7a5621e6ff2b086f1de
|
[] |
no_license
|
hitigon/leetcode-template
|
https://github.com/hitigon/leetcode-template
|
fe99d5a1c9c5ffbfe0efbd3239ad937719a775f3
|
bcf44642e099763bcd7b7828cd7d9f7b044c52c4
|
refs/heads/master
| 2021-01-22T06:28:10.235865 | 2014-09-21T22:09:32 | 2014-09-21T22:09:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# coding=utf-8
# AC Rate: 20.5%
# https://oj.leetcode.com/problems/restore-ip-addresses/
# Given a string containing only digits, restore it by returning all possible
# For example:
# Given "25525511135",
# return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
class Solution:
# @param s, a string
# @return a list of strings
def restoreIpAddresses(self, s):
|
UTF-8
|
Python
| false | false | 2,014 |
16,320,875,751,109 |
7d38aef21479843ad8d3e1a1caee4fd259725041
|
987a53ed0b5cddde6804f33182741f7d5c0413a3
|
/urls.py
|
e15322f30969f9ae09fc9bb4953bd56e2734be2c
|
[
"Apache-2.0"
] |
permissive
|
caffeinate/blight_blog
|
https://github.com/caffeinate/blight_blog
|
10fe46cfa113d80e211ef5fa6b099429ac648ed1
|
73c51cfd756afbe17258d5d02655ae92abfcde4b
|
refs/heads/master
| 2016-09-06T19:54:35.805983 | 2014-02-18T12:59:34 | 2014-02-18T12:59:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django.conf.urls.defaults import patterns, url
from django.views.generic.simple import direct_to_template
handler500 = 'djangotoolbox.errorviews.server_error'
# system urls (views with a specific controller) should start with an underscore
# so that BlogSurface titles can be slugified and used directly off the root.
# exception is the main_page
urlpatterns = patterns('',
url(r'^$', 'blog.views.main_page', name='main_page'),
url(r'^_add_surface/$', 'blog.views.add_surface', name='add_surface'),
url(r'^_add_post/(?P<surface_id>\d+)$', 'blog.views.add_blog_post', name='add_post'),
url('^_about/$', direct_to_template, {'template': 'about.html'}, name='about'),
url('^(?P<surface_slug>.+)/$', 'blog.views.surface', name='surface_map'),
('^_ah/warmup$', 'djangoappengine.views.warmup'),
)
# really? on GAE?
urlpatterns += patterns('django.contrib.staticfiles.views', url(r'^_static/(?P<path>.*)$', 'serve'),)
|
UTF-8
|
Python
| false | false | 2,014 |
15,204,184,257,023 |
2092b8f3ed9c9ef2bac06f93b163e359aef4e1e7
|
585301e4a13a080eb790cb178d25fe761c147cd7
|
/collective/amberjack/core/registration.py
|
b23b9a2fa509fb957fcc6b73071c044033d347e9
|
[] |
no_license
|
collective/collective.amberjack.core
|
https://github.com/collective/collective.amberjack.core
|
c389d78ca56bc9468389a5fbdb610e31ac58d190
|
08e8fbceac22501eb2f97102b06bdccc6123ad82
|
refs/heads/master
| 2023-06-26T13:39:45.328732 | 2013-12-18T05:46:31 | 2013-12-18T05:46:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from zope.interface import classProvides
from zope.component import provideUtility
from collective.amberjack.core.interfaces import ITourDefinition
from collective.amberjack.core.interfaces import ITourRegistration
from collective.amberjack.core.tour import Tour
from cStringIO import StringIO
from urlparse import urlparse
import zipfile
import tarfile
import urllib2
import os
from translation import utils
class TourRegistration(object):
"""
Generic tour registration class
"""
classProvides(ITourRegistration)
def __init__(self, source, filename=None, request=None):
self.source = source
if request:
filename = self.get_filename(request)
if not filename:
raise AttributeError("Missing filename parameter")
self.filename = filename
def source_packages(self):
raise NotImplemented
def get_filename(self, request):
raise NotImplemented
def translation(self, conf):
utils.registerTranslations(conf)
def register(self):
for conf in self.source_packages():
if self.isProperTour(conf.name):
tour = Tour(conf, self.filename)
provideUtility(component=tour,
provides=ITourDefinition,
name=tour.tourId)
elif conf.name.endswith(".po"):
self.translation(conf)
def isProperTour(self, filename):
return filename.endswith(".cfg")
def archive_handler(filename, source):
""" yield extracted files from a archive """
source.seek(0)
if filename.endswith('.zip'):
#ZIP
_zip = zipfile.ZipFile(source)
for f in _zip.namelist():
yield _zip.open(f,'r')
elif filename.endswith('.tar'):
#TAR
_tar = tarfile.TarFile.open(fileobj=source, mode='r:')
for f in _tar.getmembers():
extract = _tar.extractfile(f)
if extract:
yield extract
elif filename.endswith('.gz'):
#GZ
_tar = tarfile.TarFile.open(fileobj=source, mode='r:gz')
for f in _tar.getmembers():
extract = _tar.extractfile(f)
if extract:
yield extract
class FileArchiveRegistration(TourRegistration):
"""
Zip archive tour registration
"""
classProvides(ITourRegistration)
def source_packages(self):
_zip = StringIO()
_zip.write(self.source)
for archive in archive_handler(self.filename, _zip):
yield archive
def get_filename(self,request):
return request.form['form.zipfile'].filename
class FolderRegistration(TourRegistration):
"""
Folder tour registration
"""
classProvides(ITourRegistration)
def source_packages(self):
for root, dirs, files in os.walk(self.filename):
for name in files:
file = open(os.path.join(root, name),'r')
yield file
class WebRegistration(TourRegistration):
"""
Web tour registration
"""
classProvides(ITourRegistration)
def source_packages(self):
response = urllib2.urlopen(self.source)
_zip = StringIO()
_zip.write(response.read())
for filename, archive in archive_handler(self.filename, _zip):
yield archive
def get_filename(self, request):
return os.path.basename(urlparse(request.form['form.url']).path)
|
UTF-8
|
Python
| false | false | 2,013 |
1,451,698,995,029 |
06ddd8dd51523af61a540ce2f7535b9a6a682f0a
|
d667001344be984f9c552c9bd3e1406610e3b20b
|
/web/dbindexer/middleware.py
|
9c40329f366dbfc1dd9b247b89deb3018359d283
|
[
"MIT"
] |
permissive
|
bdelliott/wordgame
|
https://github.com/bdelliott/wordgame
|
5991e2902202cd135405a96c783e29420222b86c
|
a18cbe0df45408ad3963b3751aebc8e344b74c3d
|
refs/heads/master
| 2021-01-01T06:50:44.253356 | 2012-02-24T02:50:47 | 2012-02-24T02:50:47 | 3,532,130 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from . import models
class DBIndexerMiddleware(object):
"""Empty because the import above already does everything for us"""
pass
|
UTF-8
|
Python
| false | false | 2,012 |
1,709,397,014,726 |
64f706280f912b705070bb306f858959767938fc
|
25f635d2d1ae3880e7fcd85cb639c38001733a8c
|
/test/unit/common/test_fs_utils.py
|
c7f969e52aab16b1da228754d2bb689340d91cff
|
[] |
no_license
|
portante/gluster-swift
|
https://github.com/portante/gluster-swift
|
fbdaf202a54ba220879740cfdb21a89483de0017
|
810b399d243c05343d8fd24b5fb597e2abe4cd61
|
refs/heads/master
| 2021-01-24T06:41:00.005570 | 2013-10-31T11:18:17 | 2013-11-11T01:21:49 | 9,763,643 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# Copyright (c) 2012-2013 Red Hat, Inc.
#
# 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 os
import shutil
import random
import errno
import unittest
import eventlet
from nose import SkipTest
from mock import patch
from tempfile import mkdtemp, mkstemp
from gluster.swift.common import fs_utils as fs
from gluster.swift.common.exceptions import NotDirectoryError, \
FileOrDirNotFoundError, GlusterFileSystemOSError, \
GlusterFileSystemIOError
def mock_os_fsync(fd):
return True
def mock_os_fdatasync(fd):
return True
class TestFsUtils(unittest.TestCase):
""" Tests for common.fs_utils """
def test_do_walk(self):
# create directory structure
tmpparent = mkdtemp()
try:
tmpdirs = []
tmpfiles = []
for i in range(5):
tmpdirs.append(mkdtemp(dir=tmpparent).rsplit(os.path.sep, 1)[1])
tmpfiles.append(mkstemp(dir=tmpparent)[1].rsplit(os.path.sep, \
1)[1])
for path, dirnames, filenames in fs.do_walk(tmpparent):
assert path == tmpparent
assert dirnames.sort() == tmpdirs.sort()
assert filenames.sort() == tmpfiles.sort()
break
finally:
shutil.rmtree(tmpparent)
def test_do_ismount_path_does_not_exist(self):
tmpdir = mkdtemp()
try:
assert False == fs.do_ismount(os.path.join(tmpdir, 'bar'))
finally:
shutil.rmtree(tmpdir)
def test_do_ismount_path_not_mount(self):
tmpdir = mkdtemp()
try:
assert False == fs.do_ismount(tmpdir)
finally:
shutil.rmtree(tmpdir)
def test_do_ismount_path_error(self):
def _mock_os_lstat(path):
raise OSError(13, "foo")
tmpdir = mkdtemp()
try:
with patch("os.lstat", _mock_os_lstat):
try:
fs.do_ismount(tmpdir)
except GlusterFileSystemOSError as err:
pass
else:
self.fail("Expected GlusterFileSystemOSError")
finally:
shutil.rmtree(tmpdir)
def test_do_ismount_path_is_symlink(self):
tmpdir = mkdtemp()
try:
link = os.path.join(tmpdir, "tmp")
os.symlink("/tmp", link)
assert False == fs.do_ismount(link)
finally:
shutil.rmtree(tmpdir)
def test_do_ismount_path_is_root(self):
assert True == fs.do_ismount('/')
def test_do_ismount_parent_path_error(self):
_os_lstat = os.lstat
def _mock_os_lstat(path):
if path.endswith(".."):
raise OSError(13, "foo")
else:
return _os_lstat(path)
tmpdir = mkdtemp()
try:
with patch("os.lstat", _mock_os_lstat):
try:
fs.do_ismount(tmpdir)
except GlusterFileSystemOSError as err:
pass
else:
self.fail("Expected GlusterFileSystemOSError")
finally:
shutil.rmtree(tmpdir)
def test_do_ismount_successes_dev(self):
_os_lstat = os.lstat
class MockStat(object):
def __init__(self, mode, dev, ino):
self.st_mode = mode
self.st_dev = dev
self.st_ino = ino
def _mock_os_lstat(path):
if path.endswith(".."):
parent = _os_lstat(path)
return MockStat(parent.st_mode, parent.st_dev + 1,
parent.st_ino)
else:
return _os_lstat(path)
tmpdir = mkdtemp()
try:
with patch("os.lstat", _mock_os_lstat):
try:
fs.do_ismount(tmpdir)
except GlusterFileSystemOSError as err:
self.fail("Unexpected exception")
else:
pass
finally:
shutil.rmtree(tmpdir)
def test_do_ismount_successes_ino(self):
_os_lstat = os.lstat
class MockStat(object):
def __init__(self, mode, dev, ino):
self.st_mode = mode
self.st_dev = dev
self.st_ino = ino
def _mock_os_lstat(path):
if path.endswith(".."):
return _os_lstat(path)
else:
parent_path = os.path.join(path, "..")
child = _os_lstat(path)
parent = _os_lstat(parent_path)
return MockStat(child.st_mode, parent.st_ino,
child.st_dev)
tmpdir = mkdtemp()
try:
with patch("os.lstat", _mock_os_lstat):
try:
fs.do_ismount(tmpdir)
except GlusterFileSystemOSError as err:
self.fail("Unexpected exception")
else:
pass
finally:
shutil.rmtree(tmpdir)
def test_do_open(self):
_fd, tmpfile = mkstemp()
try:
fd = fs.do_open(tmpfile, os.O_RDONLY)
try:
os.write(fd, 'test')
except OSError as err:
pass
else:
self.fail("OSError expected")
finally:
os.close(fd)
finally:
os.close(_fd)
os.remove(tmpfile)
def test_do_open_err_int_mode(self):
try:
fs.do_open(os.path.join('/tmp', str(random.random())),
os.O_RDONLY)
except GlusterFileSystemOSError:
pass
else:
self.fail("GlusterFileSystemOSError expected")
def test_do_write(self):
fd, tmpfile = mkstemp()
try:
cnt = fs.do_write(fd, "test")
assert cnt == len("test")
finally:
os.close(fd)
os.remove(tmpfile)
def test_do_write_err(self):
fd, tmpfile = mkstemp()
try:
fd1 = os.open(tmpfile, os.O_RDONLY)
try:
fs.do_write(fd1, "test")
except GlusterFileSystemOSError:
pass
else:
self.fail("GlusterFileSystemOSError expected")
finally:
os.close(fd1)
except GlusterFileSystemOSError as ose:
self.fail("Open failed with %s" %ose.strerror)
finally:
os.close(fd)
os.remove(tmpfile)
def test_mkdirs(self):
try:
subdir = os.path.join('/tmp', str(random.random()))
path = os.path.join(subdir, str(random.random()))
fs.mkdirs(path)
assert os.path.exists(path)
assert fs.mkdirs(path)
finally:
shutil.rmtree(subdir)
def test_mkdirs_already_dir(self):
tmpdir = mkdtemp()
try:
fs.mkdirs(tmpdir)
except (GlusterFileSystemOSError, OSError):
self.fail("Unexpected exception")
else:
pass
finally:
shutil.rmtree(tmpdir)
def test_mkdirs(self):
tmpdir = mkdtemp()
try:
fs.mkdirs(os.path.join(tmpdir, "a", "b", "c"))
except OSError:
self.fail("Unexpected exception")
else:
pass
finally:
shutil.rmtree(tmpdir)
def test_mkdirs_existing_file(self):
tmpdir = mkdtemp()
fd, tmpfile = mkstemp(dir=tmpdir)
try:
fs.mkdirs(tmpfile)
except OSError:
pass
else:
self.fail("Expected GlusterFileSystemOSError exception")
finally:
os.close(fd)
shutil.rmtree(tmpdir)
def test_mkdirs_existing_file_on_path(self):
tmpdir = mkdtemp()
fd, tmpfile = mkstemp(dir=tmpdir)
try:
fs.mkdirs(os.path.join(tmpfile, 'b'))
except OSError:
pass
else:
self.fail("Expected GlusterFileSystemOSError exception")
finally:
os.close(fd)
shutil.rmtree(tmpdir)
def test_do_mkdir(self):
try:
path = os.path.join('/tmp', str(random.random()))
fs.do_mkdir(path)
assert os.path.exists(path)
assert fs.do_mkdir(path) is None
finally:
os.rmdir(path)
def test_do_mkdir_err(self):
try:
path = os.path.join('/tmp', str(random.random()), str(random.random()))
fs.do_mkdir(path)
except GlusterFileSystemOSError:
pass
else:
self.fail("GlusterFileSystemOSError expected")
def test_do_listdir(self):
tmpdir = mkdtemp()
try:
subdir = []
for i in range(5):
subdir.append(mkdtemp(dir=tmpdir).rsplit(os.path.sep, 1)[1])
assert subdir.sort() == fs.do_listdir(tmpdir).sort()
finally:
shutil.rmtree(tmpdir)
def test_do_listdir_err(self):
try:
path = os.path.join('/tmp', str(random.random()))
fs.do_listdir(path)
except GlusterFileSystemOSError:
pass
else:
self.fail("GlusterFileSystemOSError expected")
def test_do_fstat(self):
tmpdir = mkdtemp()
try:
fd, tmpfile = mkstemp(dir=tmpdir)
buf1 = os.stat(tmpfile)
buf2 = fs.do_fstat(fd)
assert buf1 == buf2
finally:
os.close(fd)
os.remove(tmpfile)
os.rmdir(tmpdir)
def test_do_fstat_err(self):
try:
fs.do_fstat(1000)
except GlusterFileSystemOSError:
pass
else:
self.fail("Expected GlusterFileSystemOSError")
def test_do_stat(self):
tmpdir = mkdtemp()
try:
fd, tmpfile = mkstemp(dir=tmpdir)
buf1 = os.stat(tmpfile)
buf2 = fs.do_stat(tmpfile)
assert buf1 == buf2
finally:
os.close(fd)
os.remove(tmpfile)
os.rmdir(tmpdir)
def test_do_stat_enoent(self):
res = fs.do_stat(os.path.join('/tmp', str(random.random())))
assert res is None
def test_do_stat_err(self):
def mock_os_stat_eacces(path):
raise OSError(errno.EACCES, os.strerror(errno.EACCES))
try:
with patch('os.stat', mock_os_stat_eacces):
fs.do_stat('/tmp')
except GlusterFileSystemOSError:
pass
else:
self.fail("GlusterFileSystemOSError expected")
def test_do_stat_eio_once(self):
count = [0]
_os_stat = os.stat
def mock_os_stat_eio(path):
count[0] += 1
if count[0] <= 1:
raise OSError(errno.EIO, os.strerror(errno.EIO))
return _os_stat(path)
with patch('os.stat', mock_os_stat_eio):
fs.do_stat('/tmp') is not None
def test_do_stat_eio_twice(self):
count = [0]
_os_stat = os.stat
def mock_os_stat_eio(path):
count[0] += 1
if count[0] <= 2:
raise OSError(errno.EIO, os.strerror(errno.EIO))
return _os_stat(path)
with patch('os.stat', mock_os_stat_eio):
fs.do_stat('/tmp') is not None
def test_do_stat_eio_ten(self):
def mock_os_stat_eio(path):
raise OSError(errno.EIO, os.strerror(errno.EIO))
try:
with patch('os.stat', mock_os_stat_eio):
fs.do_stat('/tmp')
except GlusterFileSystemOSError:
pass
else:
self.fail("GlusterFileSystemOSError expected")
def test_do_close(self):
fd, tmpfile = mkstemp()
try:
fs.do_close(fd)
try:
os.write(fd, "test")
except OSError:
pass
else:
self.fail("OSError expected")
finally:
os.remove(tmpfile)
def test_do_close_err_fd(self):
fd, tmpfile = mkstemp()
try:
fs.do_close(fd)
try:
fs.do_close(fd)
except GlusterFileSystemOSError:
pass
else:
self.fail("GlusterFileSystemOSError expected")
finally:
os.remove(tmpfile)
def test_do_unlink(self):
fd, tmpfile = mkstemp()
try:
assert fs.do_unlink(tmpfile) is None
assert not os.path.exists(tmpfile)
res = fs.do_unlink(os.path.join('/tmp', str(random.random())))
assert res is None
finally:
os.close(fd)
def test_do_unlink_err(self):
tmpdir = mkdtemp()
try:
fs.do_unlink(tmpdir)
except GlusterFileSystemOSError:
pass
else:
self.fail('GlusterFileSystemOSError expected')
finally:
os.rmdir(tmpdir)
def test_do_rename(self):
srcpath = mkdtemp()
try:
destpath = os.path.join('/tmp', str(random.random()))
fs.do_rename(srcpath, destpath)
assert not os.path.exists(srcpath)
assert os.path.exists(destpath)
finally:
os.rmdir(destpath)
def test_do_rename_err(self):
try:
srcpath = os.path.join('/tmp', str(random.random()))
destpath = os.path.join('/tmp', str(random.random()))
fs.do_rename(srcpath, destpath)
except GlusterFileSystemOSError:
pass
else:
self.fail("GlusterFileSystemOSError expected")
def test_dir_empty(self):
tmpdir = mkdtemp()
try:
subdir = mkdtemp(dir=tmpdir)
assert not fs.dir_empty(tmpdir)
assert fs.dir_empty(subdir)
finally:
shutil.rmtree(tmpdir)
def test_dir_empty_err(self):
def _mock_os_listdir(path):
raise OSError(13, "foo")
with patch("os.listdir", _mock_os_listdir):
try:
fs.dir_empty("/tmp")
except GlusterFileSystemOSError:
pass
else:
self.fail("GlusterFileSystemOSError exception expected")
def test_dir_empty_notfound(self):
try:
assert fs.dir_empty(os.path.join('/tmp', str(random.random())))
except FileOrDirNotFoundError:
pass
else:
self.fail("FileOrDirNotFoundError exception expected")
def test_dir_empty_notdir(self):
fd, tmpfile = mkstemp()
try:
try:
fs.dir_empty(tmpfile)
except NotDirectoryError:
pass
else:
self.fail("NotDirectoryError exception expected")
finally:
os.close(fd)
os.unlink(tmpfile)
def test_do_rmdir(self):
tmpdir = mkdtemp()
try:
subdir = mkdtemp(dir=tmpdir)
fd, tmpfile = mkstemp(dir=tmpdir)
try:
fs.do_rmdir(tmpfile)
except GlusterFileSystemOSError:
pass
else:
self.fail("Expected GlusterFileSystemOSError")
assert os.path.exists(subdir)
try:
fs.do_rmdir(tmpdir)
except GlusterFileSystemOSError:
pass
else:
self.fail("Expected GlusterFileSystemOSError")
assert os.path.exists(subdir)
fs.do_rmdir(subdir)
assert not os.path.exists(subdir)
finally:
os.close(fd)
shutil.rmtree(tmpdir)
def test_chown_dir(self):
tmpdir = mkdtemp()
try:
subdir = mkdtemp(dir=tmpdir)
buf = os.stat(subdir)
if buf.st_uid == 0:
raise SkipTest
else:
try:
fs.do_chown(subdir, 20000, 20000)
except GlusterFileSystemOSError as ex:
if ex.errno != errno.EPERM:
self.fail(
"Expected GlusterFileSystemOSError(errno=EPERM)")
else:
self.fail("Expected GlusterFileSystemOSError")
finally:
shutil.rmtree(tmpdir)
def test_chown_file(self):
tmpdir = mkdtemp()
try:
fd, tmpfile = mkstemp(dir=tmpdir)
buf = os.stat(tmpfile)
if buf.st_uid == 0:
raise SkipTest
else:
try:
fs.do_chown(tmpfile, 20000, 20000)
except GlusterFileSystemOSError as ex:
if ex.errno != errno.EPERM:
self.fail(
"Expected GlusterFileSystemOSError(errno=EPERM")
else:
self.fail("Expected GlusterFileSystemOSError")
finally:
os.close(fd)
shutil.rmtree(tmpdir)
def test_chown_file_err(self):
try:
fs.do_chown(os.path.join('/tmp', str(random.random())),
20000, 20000)
except GlusterFileSystemOSError:
pass
else:
self.fail("Expected GlusterFileSystemOSError")
def test_fchown(self):
tmpdir = mkdtemp()
try:
fd, tmpfile = mkstemp(dir=tmpdir)
buf = os.stat(tmpfile)
if buf.st_uid == 0:
raise SkipTest
else:
try:
fs.do_fchown(fd, 20000, 20000)
except GlusterFileSystemOSError as ex:
if ex.errno != errno.EPERM:
self.fail(
"Expected GlusterFileSystemOSError(errno=EPERM)")
else:
self.fail("Expected GlusterFileSystemOSError")
finally:
os.close(fd)
shutil.rmtree(tmpdir)
def test_fchown_err(self):
tmpdir = mkdtemp()
try:
fd, tmpfile = mkstemp(dir=tmpdir)
fd_rd = os.open(tmpfile, os.O_RDONLY)
buf = os.stat(tmpfile)
if buf.st_uid == 0:
raise SkipTest
else:
try:
fs.do_fchown(fd_rd, 20000, 20000)
except GlusterFileSystemOSError as ex:
if ex.errno != errno.EPERM:
self.fail(
"Expected GlusterFileSystemOSError(errno=EPERM)")
else:
self.fail("Expected GlusterFileSystemOSError")
finally:
os.close(fd_rd)
os.close(fd)
shutil.rmtree(tmpdir)
def test_do_fsync(self):
tmpdir = mkdtemp()
try:
fd, tmpfile = mkstemp(dir=tmpdir)
try:
os.write(fd, 'test')
with patch('os.fsync', mock_os_fsync):
assert fs.do_fsync(fd) is None
except GlusterFileSystemOSError as ose:
self.fail('Opening a temporary file failed with %s' %ose.strerror)
else:
os.close(fd)
finally:
shutil.rmtree(tmpdir)
def test_do_fsync_err(self):
tmpdir = mkdtemp()
try:
fd, tmpfile = mkstemp(dir=tmpdir)
os.write(fd, 'test')
with patch('os.fsync', mock_os_fsync):
assert fs.do_fsync(fd) is None
os.close(fd)
try:
fs.do_fsync(fd)
except GlusterFileSystemOSError:
pass
else:
self.fail("Expected GlusterFileSystemOSError")
finally:
shutil.rmtree(tmpdir)
def test_do_fdatasync(self):
tmpdir = mkdtemp()
try:
fd, tmpfile = mkstemp(dir=tmpdir)
try:
os.write(fd, 'test')
with patch('os.fdatasync', mock_os_fdatasync):
assert fs.do_fdatasync(fd) is None
except GlusterFileSystemOSError as ose:
self.fail('Opening a temporary file failed with %s' %ose.strerror)
else:
os.close(fd)
finally:
shutil.rmtree(tmpdir)
def test_do_fdatasync_err(self):
tmpdir = mkdtemp()
try:
fd, tmpfile = mkstemp(dir=tmpdir)
os.write(fd, 'test')
with patch('os.fdatasync', mock_os_fdatasync):
assert fs.do_fdatasync(fd) is None
os.close(fd)
try:
fs.do_fdatasync(fd)
except GlusterFileSystemOSError:
pass
else:
self.fail("Expected GlusterFileSystemOSError")
finally:
shutil.rmtree(tmpdir)
|
UTF-8
|
Python
| false | false | 2,013 |
12,051,678,262,155 |
9bc043dfc4146bf79da46f8d7e785bea2c94515d
|
57a30d5a4f5295cc7bdd700ec142db67e53e2749
|
/tags/pisi/2.4_alpha1/scripts/package-signing/pisign.py
|
286a6a1b1321b70f5c4b2061d37b39049cde3fbb
|
[
"GPL-1.0-or-later",
"GPL-2.0-only"
] |
non_permissive
|
jamiepg1/uludag
|
https://github.com/jamiepg1/uludag
|
3c8dd1c94890617028f253a1875c88c44f8c9874
|
9822e3ff8c9759530606f6afe93bb5a990288553
|
refs/heads/master
| 2017-05-27T09:49:09.757280 | 2014-10-03T08:28:55 | 2014-10-03T08:28:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import base64
import hashlib
import subprocess
import sys
import zipfile
def signData(data, keyfile, passphrase):
"""
Signs data with given key file and passphrase.
Arguments:
data: Data to sign
keyfile: Private key
passphrase: Passphrase
Returns:
Signed data
"""
cmd = '/usr/bin/openssl dgst -sha1 -sign %s -passin pass:%s' % (keyfile, passphrase)
pipe = subprocess.Popen(cmd.split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
pipe.stdin.write(data)
pipe.stdin.close()
return pipe.stdout.read()
def verifyData(data, signature, keyfile=None, certificate=None):
"""
Verifies signature. Keyfile or certificate is required.
Arguments:
data: Original data
signature: Signed data
keyfile: Public keyfile
certificate: Certificate
Returns:
True if valid, False if invalid
"""
if certificate:
cmd = '/usr/bin/openssl x509 -inform pem -in %s -pubkey -noout' % certificate
pipe = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
keyfile = '.tmp_key'
# TODO: This is a workaround, fix ASAP
file(keyfile, 'w').write(pipe.stdout.read())
elif not keyfile:
return False
# TODO: This is a workaround, fix ASAP
file('.tmp_data', 'w').write(data)
file('.tmp_signature', 'w').write(signature)
cmd = '/usr/bin/openssl dgst -sha1 -verify %s -signature .tmp_signature .tmp_data' % keyfile
pipe = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return pipe.wait() == 0
def getZipSums(zip):
"""
Calculates checksums of files in ZIP object.
Arguments:
zip: ZipFile object
Returns:
File names and sums
"""
data = []
for content in zip.infolist():
content_sum = hashlib.sha1(zip.read(content.filename)).hexdigest()
data.append('%s %s' % (content.filename, content_sum))
return '\n'.join(data)
def verifyFile(filename, keyfile=None, certificate=None):
"""
Verifies integrity of a ZIP file. Keyfile or certificate is required.
Arguments:
filename: ZIP filename
keyfile: Public keyfile
certificate: Certificate
Returns:
True if valid, False if invalid
"""
try:
zip = zipfile.ZipFile(filename)
except IOError:
return False
sums = getZipSums(zip)
signature = base64.b64decode(zip.comment)
return verifyData(sums, signature, keyfile, certificate)
def signFile(filename, keyfile, passphrase):
"""
Signs a ZIP file.
Arguments:
filename: ZIP filename
keyfile: Private key
passphrase: Passphrase
"""
zip = zipfile.ZipFile(filename, 'a')
# Sign file checksums
sums = getZipSums(zip)
signature = signData(sums, keyfile, passphrase)
# Write Base64 encoded signature to ZIP file as comment
zip.comment = base64.b64encode(signature)
# Mark file as modified and save it
zip._didModify = True
zip.close()
def printUsage():
"""
Prints usage information of application and exits.
"""
print 'Usage:'
print ' %s sign <path/to/zipfile> <path/to/private_key> <passphrase>' % sys.argv[0]
print ' %s verify <path/to/zipfile> <path/to/certificate>' % sys.argv[0]
sys.exit(1)
if __name__ == '__main__':
try:
operation, filename = sys.argv[1:3]
except ValueError:
printUsage()
if operation == 'sign':
try:
keyfile, passphrase = sys.argv[3:5]
except ValueError:
printUsage()
signFile(filename, keyfile, passphrase)
elif operation == 'verify':
try:
certificate = sys.argv[3]
except ValueError:
printUsage()
if verifyFile(filename, certificate=certificate):
print 'File is OK'
else:
print 'File is corrupt'
else:
printUsage()
|
UTF-8
|
Python
| false | false | 2,014 |
6,863,357,742,885 |
477f2d771394936a78fb3cbf2b907457c8c7d384
|
e8dd52ded9c3ed3f6511e4af6a7538fc8bfe1717
|
/tests/test_transfer.py
|
d35c543eb3d43ba79fc7181799fcf8ec552b5cc3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
non_permissive
|
tbs1980/hmf
|
https://github.com/tbs1980/hmf
|
76aa1e005aeccdba3fa10a2e20ae0b2f75b3c6f3
|
b6a1add9e0e130aea4ec1ac2eea97c3112aa3b54
|
refs/heads/master
| 2021-01-16T21:32:12.254076 | 2014-04-17T06:03:52 | 2014-04-17T06:03:52 | 18,893,663 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import numpy as np
import inspect
import os
LOCATION = "/".join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))).split("/")[:-1])
# from nose.tools import raises
import sys
sys.path.insert(0, LOCATION)
from hmf import Transfer
def check_close(t, t2, fit):
t.update(transfer_fit=fit)
assert np.mean(np.abs((t.power - t2.power) / t.power)) < 1
def test_fits():
t = Transfer(transfer_fit="CAMB")
t2 = Transfer(transfer_fit="CAMB")
for fit in Transfer.fits:
yield check_close, t, t2, fit
def check_update(t, t2, k, v):
t.update(**{k:v})
assert np.mean(np.abs((t.power - t2.power) / t.power)) < 1 and np.mean(np.abs((t.power - t2.power) / t.power)) > 1e-6
def test_updates():
t = Transfer()
t2 = Transfer()
for k, v in {"z":0.1,
"wdm_mass":10.0,
"initial_mode":2,
"lAccuracyBoost":1.5,
"AccuracyBoost":1.5,
"sigma_8":0.82,
"n":0.95,
"H0":68.0}.iteritems():
yield check_update, t, t2, k, v
def test_halofit():
t = Transfer(lnk=np.linspace(-20, 20, 1000), transfer_fit="EH")
assert abs(t.power[0] - t.nonlinear_power[0]) < 1e-5
assert 5 + t.power[-1] < t.nonlinear_power[-1]
|
UTF-8
|
Python
| false | false | 2,014 |
13,013,750,932,399 |
0f64d15a176f57d7544c7dce7bb1869c0ce4df90
|
26eafc2b8ab3eb265f2b01e39d9f3e120d115249
|
/pixmap.py
|
15bf0b550ac80a9ab9d121bb9c2185bd9b89aa86
|
[] |
no_license
|
kragniz/pathfinding-demo
|
https://github.com/kragniz/pathfinding-demo
|
0c334d15463289532a0891aa0f87d6c2a635bdc3
|
2f312c16a8ff977cd6a8242b5c6c11130b782644
|
refs/heads/master
| 2023-08-10T06:20:48.497604 | 2013-04-18T11:58:54 | 2013-04-18T11:58:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
def save(data, filename, maxValue=2**16-1):
width = len(data)
hight = len(data[0])
outFile = open(filename, 'w')
outFile.write('P3\n{hight} {width}\n{max}\n'.format(
width=width,
hight=hight,
max=maxValue)
)
for i in data:
for j in i:
outFile.write('{}\n{}\n{}\n'.format(*j))
|
UTF-8
|
Python
| false | false | 2,013 |
506,806,148,912 |
943224fca14400241562fdbe98dd304d80b9c24d
|
d66b1661110e799995567f20b0091746ed904d47
|
/Contents/Code/__init__.py
|
c6239387ccb24540d784b98c0ccb692324a85b91
|
[] |
no_license
|
IanDBird/Stufftv.bundle
|
https://github.com/IanDBird/Stufftv.bundle
|
557e35f446452a2d7efa37a82af413d087a7c4d8
|
1403fa1bd0877d868155b6c13cc6126ff1a44746
|
refs/heads/master
| 2016-08-01T15:06:13.184039 | 2012-09-25T17:54:01 | 2012-09-25T17:54:01 | 1,789,431 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
####################################################################################################
NAME = L('Title')
ART = 'art-default.jpg'
ICON = 'icon-default.png'
ICON_SEARCH = 'icon-search.png'
BASE_URL = "http://www.stuff.tv"
VIDCASTS_URL = "http://www.stuff.tv/video/vidcasts"
VIDEO_REVIEWS_URL = "http://www.stuff.tv/video/reviews"
SEARCH_URL = "http://www.stuff.tv/search/video?search=%s"
####################################################################################################
# This function is initially called by the PMS framework to initialize the plugin. This includes
# setting up the Plugin static instance along with the displayed artwork.
def Start():
# Initialize the plugin
Plugin.AddViewGroup("List", viewMode = "List", mediaType = "items")
# Set the default ObjectContainer attributes
ObjectContainer.title1 = NAME
ObjectContainer.view_group = 'List'
ObjectContainer.art = R(ICON)
# Default icons for DirectoryObject, VideoClipObject and SearchDirectoryObject in case there isn't an image
DirectoryObject.thumb = R(ICON)
DirectoryObject.art = R(ART)
NextPageObject.thumb = R(ICON)
NextPageObject.art = R(ART)
VideoClipObject.thumb = R(ICON)
VideoClipObject.art = R(ART)
SearchDirectoryObject.thumb = R(ICON)
SearchDirectoryObject.art = R(ART)
# Cache HTTP requests for up to a day
HTTP.CacheTime = CACHE_1DAY
@handler('/video/stufftv', NAME, art = ART, thumb = ICON)
def MainMenu():
oc = ObjectContainer(title1 = L('Title'))
oc.add(DirectoryObject(key = Callback(VidCastMenu), title = L('VidCasts')))
oc.add(DirectoryObject(key = Callback(VideoReviewMenu), title = L('VideoReviews')))
oc.add(SearchDirectoryObject(identifier="com.plexapp.plugins.stufftv", title = L('Search'), prompt = L('SearchPrompt'), thumb = R(ICON)))
return oc
####################################################################################################
# VIDCASTS
####################################################################################################
@route('/video/stufftv/videocasts', allow_sync = True)
def VidCastMenu(url = VIDCASTS_URL):
oc = ObjectContainer(title1 = L('Title'), title2 = L('VidCasts'))
vidcasts_page = HTML.ElementFromURL(url)
vidcasts_initial_node = vidcasts_page.xpath("//div[@class='inner-container']/div/h2[contains(text(), 'Vidcasts')]/..")[0]
vidcasts = vidcasts_initial_node.xpath(".//div[@class='item-list']/ul/li//div[contains(@class,'product')]")
for item in vidcasts:
try:
# Attempt to determine the title
title = item.xpath(".//h4/a/text()")[0]
# Attempt to determine the absolue URL to the page
relative_url = item.xpath(".//div/a")[0].get('href')
url = BASE_URL + String.Quote(relative_url)
# [Optional] - Attempt to determine the date
date = None
try:
date = item.xpath(".//p[@class='meta']/text()")[0]
date = Datetime.ParseDate(date)
except: pass
# [Optional] - Attempt to determine the thumbnail
thumb = None
try:
thumb_url = item.xpath(".//div/a/img")[0].get('src')
thumb = "http:" + String.Quote(thumb_url[5:])
except: pass
oc.add(VideoClipObject(
url = url,
title = title,
thumb = thumb,
originally_available_at = date))
except:
pass
try:
# Attempt to determine if there is more videos available on the next page.
next_relative_url = vidcasts_page.xpath("//div[@class='pagination']/span[@class='next']/a[@class='active']")[0].get('href')
next_url = BASE_URL + next_relative_url
oc.add(NextPageObject(key = Callback(VidCastMenu, url = next_url), title = L('Next')))
except:
pass
return oc
####################################################################################################
# VIDEO REVIEWS
####################################################################################################
@route('/video/stufftv/reviews', allow_sync = True)
def VideoReviewMenu(url = VIDEO_REVIEWS_URL):
oc = ObjectContainer(title1 = L('Title'), title2 = L('VideoReviews'))
video_reviews_page = HTML.ElementFromURL(url)
video_reviews_initial_node = video_reviews_page.xpath("//div[@class='inner-container']/div/h2[contains(text(), 'Video reviews')]/..")[0]
video_reviews = video_reviews_initial_node.xpath(".//div[@class='item-list']/ul/li//div[contains(@class,'product')]")
for item in video_reviews:
try:
# Attempt to determine the title
title = item.xpath(".//h4/a/text()")[0]
# Attempt to determine the absolue URL to the page
relative_url = item.xpath(".//div/a")[0].get('href')
url = BASE_URL + String.Quote(relative_url)
# [Optional] - Attempt to determine the subtitle
date = None
try:
date = item.xpath(".//p[@class='meta']/text()")[0]
date = Datetime.ParseDate(date)
except: pass
# [Optional] - Attempt to determine the thumbnail
thumb = None
try:
thumb_url = item.xpath(".//div/a/img")[0].get('src')
thumb = "http:" + String.Quote(thumb_url[5:])
except: pass
oc.add(VideoClipObject(
url = url,
title = title,
thumb = thumb,
originally_available_at = date))
except:
pass
try:
# Attempt to determine if there is more videos available on the next page.
next_relative_url = video_reviews_page.xpath("//div[@class='pagination']/span[@class='next']/a[@class='active']")[0].get('href')
next_url = BASE_URL + next_relative_url
oc.add(NextPageObject(key = Callback(VideoReviewMenu, url = next_url), title = L('Next')))
except:
pass
return oc
|
UTF-8
|
Python
| false | false | 2,012 |
15,985,868,318,971 |
ef488d5569987388f244aa34defc7215e9634323
|
2feb9a72b5a38eeb5d0362ce2913be85d8025ae0
|
/tink.py
|
732e4c09b7f2f99bdc9ed636ca918b08cf4ed639
|
[] |
no_license
|
JohnJYates/tinkerbell-cros
|
https://github.com/JohnJYates/tinkerbell-cros
|
9093f6c68200bd761f314bc45669ae514ad397dd
|
dc9d4911553c48825293f16c61c234bc32451812
|
refs/heads/master
| 2015-09-24T09:46:25.892504 | 2013-07-08T23:36:00 | 2013-07-08T23:36:00 | 37,266,697 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
import sys
import os
import getopt
import routertable
import eventparser
import analyzer
import platform
# tinkerbell is a tool that parses cros feedback logs into a more
# human readable format.
# the goal is to determine if there are very common wifi issues
# across users.
class Usage(Exception):
def __init__(self, msg):
self.msg = msg
def help():
print >>sys.stderr, "Specify a filename."
def process(filename, header, verbose):
try:
logfile = open(filename, 'r')
except IOError:
print "ERROR: Couldn't open file."
return
board = platform.get_board_name(logfile)
if not board:
board = "BOARD_UNKNOWN"
logfile.seek(0)
table = routertable.get_router_table(logfile)
oui_table = routertable.load_oui_table("oui.table")
routertable.backfill_unknown_models(table, oui_table)
logfile.seek(0)
eventlog = eventparser.get_event_log(logfile)
tracker = analyzer.analyze_log(eventlog)
if verbose:
print "***Router table:"
for key, value in table.iteritems():
print value
print "***Event log:"
for item in eventlog:
print item
print "***Analysis:"
tracker.print_summary()
else:
if header:
print tracker.get_summary_csv_header() + ",Router,Board,File"
for bss in tracker.get_encountered_bss():
router = routertable.lookup_from_table(bss, table, oui_table)
print tracker.get_summary_csv_line() + "," + str(router) + "," + board + "," + str(os.path.basename(filename))
def main(argv=None):
header = False
verbose = False
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "chv", ["csvheader", "help", "verbose"])
except getopt.error, msg:
raise Usage(msg)
for o, a in opts:
if o in ("-c", "--csvheader"):
header = True
if o in ("-v", "--verbose"):
verbose = True
if o in ("-h", "--help"):
help()
sys.exit()
if len(args) != 1:
help()
sys.exit()
process(args[0], header, verbose)
except Usage, err:
print >>sys.stderr, err.msg
print >>sys.stderr, "for help use --help"
return 2
if __name__ == "__main__":
sys.exit(main())
|
UTF-8
|
Python
| false | false | 2,013 |
19,619,410,632,266 |
a3d9ec585011f328cd4bffb8bde1ad9595101233
|
efa10f9e93020b3b12714dba5252f344ad243de6
|
/wedding_site/app/models.py
|
a6624244278b7cd31a7e74f4fbe7e46276ac6c2e
|
[] |
no_license
|
talldave/wedding_website
|
https://github.com/talldave/wedding_website
|
4b9624ce08b08e3ae8ccf654596df47461d265a3
|
440d5a5a1029c8c0e71a608bfe8c36fc587d395f
|
refs/heads/master
| 2020-04-06T05:24:08.006500 | 2014-07-27T19:37:36 | 2014-07-27T19:37:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from flask.ext.sqlalchemy import SQLAlchemy
import logging
logging.basicConfig(filename='~/flask_env/sqldebug.log')
logging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG)
db = SQLAlchemy()
class Guest(db.Model):
__tablename__ = 'GUEST'
id = db.Column(db.Integer, primary_key = True)
track_num = db.Column(db.String(7), nullable=False, unique=True)
first_name = db.Column(db.String(32), nullable=False)
last_name = db.Column(db.String(32), nullable=False)
email_address = db.Column(db.String(64))
salutation = db.Column(db.String(64), nullable=False)
group = db.Column(db.String(64), nullable=False)
def __init__(self, id, track_num, first_name, last_name, email_address, salutation, group):
self.id = id
self.track_num = track_num
self.first_name = first_name.title()
self.last_name = last_name.title()
self.email_address = email_address.lower()
self.salutation = salutation.title()
self.group = group.lower()
class Rsvp(db.Model):
__tablename__ = 'RSVP'
id = db.Column(db.Integer, primary_key = True)
guest_id = db.Column(db.Integer, db.ForeignKey(Guest.id), nullable=False)
response = db.Column(db.Integer, nullable=False, server_default=u"'-1'")
note = db.Column(db.String(4000))
arrival_date = db.Column(db.String(24), nullable=False)
arrival_time = db.Column(db.String(24), nullable=False)
child_care = db.Column(db.Integer, nullable=False, server_default=u"'-1'")
final = db.Column(db.Integer)
def __init__(self, guest_id, response, note, arrival_date, arrival_time, child_care, final ):
self.guest_id = guest_id
self.response = response
self.note = note
self.arrival_date = arrival_date
self.arrival_time = arrival_time
self.child_care = child_care
self.final = final
class GuestRsvp(db.Model):
__tablename__ = 'GUEST_RSVP_V'
id = db.Column(db.Integer, primary_key = True)
first_name = db.Column(db.String(32))
last_name = db.Column(db.String(32))
response = db.Column(db.Integer)
group = db.Column(db.String(64))
child_care = db.Column(db.Integer)
arrival_date = db.Column(db.String(24))
arrival_time = db.Column(db.String(24))
final = db.Column(db.Integer)
note = db.Column(db.String())
rsvp_date = db.Column(db.String(24))
def __init__(self, first_name, last_name, group, response, arrival_date, arrival_time, child_care, final ):
self.first_name = first_name.title()
self.last_name = last_name.title()
self.group = group.lower()
self.response = response
self.child_care = child_care
self.arrival_date = arrival_date.lower()
self.arrival_time = arrival_time.lower()
self.final = final
class Venue(db.Model):
__tablename__ = 'VENUE'
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(), nullable=False)
address_id = db.Column(db.Integer, db.ForeignKey(Address.id), nullable=False)
type = db.Column(db.String(), nullable=False)
phone = db.Column(db.String())
def __init__(self, name, address_id, type, phone):
self.name = name
self.address_id = address_id
self.type = type
self.phone = phone
class LoginTable(db.Model):
__tablename__ = 'LOGIN'
id = db.Column(db.Integer, primary_key = True)
email_not_found = db.Column(db.String(64))
guest_id = db.Column(db.Integer, db.ForeignKey(Guest.id))
ip_addr = db.Column(db.String(16))
def __init__(self, email_not_found, guest_id, ip_addr):
self.email_not_found = email_not_found
self.guest_id = guest_id
self.ip_addr = ip_addr
class Event_V(db.Model):
__tablename__ = 'EVENT_V'
id = db.Column(db.Integer, primary_key = True)
start_date = db.Column(db.DateTime)
end_date = db.Column(db.DateTime)
#venue_id = db.Column(db.Integer)
name = db.Column(db.String(128))
description = db.Column(db.String(4096))
venue_name = db.Column(db.String(64))
venue_phone = db.Column(db.String(16))
addr_street1 = db.Column(db.String(64))
addr_street2 = db.Column(db.String(64))
addr_city = db.Column(db.String(64))
addr_state = db.Column(db.String(2))
addr_zip = db.Column(db.String(10))
streetview_link = db.Column(db.String(256))
def __init__(self, start_date, end_date, venue_id, name, description):
self.start_date = start_date
self.end_date = end_date
self.venue_id = venue_id
self.name = name
self.description = description
class Web_Content(db.Model):
__tablename__ = 'WEB_CONTENT'
id = db.Column(db.Integer, primary_key = True)
page = db.Column(db.String(32), nullable=False)
section = db.Column(db.String(32), nullable=False)
content = db.Column(db.String(4096), nullable=False)
fkey = db.Column(db.Integer)
class Address(db.Model):
__tablename__ = 'ADDRESS'
id = db.Column(db.Integer, primary_key = True)
street1 = db.Column(db.String(64), nullable=False)
city = db.Column(db.String(64), nullable=False)
state = db.Column(db.String(2), nullable=False)
zip = db.Column(db.String(10), nullable=False)
latitude = db.Column(db.Numeric(12,8))
longitude = db.Column(db.Numeric(12,8))
street2 = db.Column(db.String(64))
streetview_link = db.Column(db.String(256))
class Vendor(db.Model):
__tablename__ = 'VENDOR'
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(64), nullable=False)
phone = db.Column(db.String(16))
web = db.Column(db.String(128))
type = db.Column(db.String(32), nullable=False)
class Gift(db.Model):
__tablename__ = 'GIFT'
id = db.Column(db.Integer, primary_key = True)
gift = db.Column(db.String(64), nullable=False)
given_to = db.Column(db.String(128), nullable=False)
given_from = db.Column(db.String(128), nullable=False)
date_recd = db.Column(db.DateTime, nullable=False)
ty_date_sent = db.Column(db.DateTime)
class Billing(db.Model):
__tablename__ = 'BILLING'
id = db.Column(db.Integer, primary_key = True)
amt_est = db.Column(db.Numeric(8,2))
amt_total = db.Column(db.Numeric(8,2), nullable=False)
amt_owe = db.Column(db.Numeric(8,2), nullable=False)
payee = db.Column(db.String(64), nullable=False)
payor = db.Column(db.String(64), nullable=False)
item = db.Column(db.String(128), nullable=False)
|
UTF-8
|
Python
| false | false | 2,014 |
11,347,303,637,233 |
55688c796fa56608ba0682e75c744f60d16f93b2
|
4cb06a6674d1dca463d5d9a5f471655d9b38c0a1
|
/hw1067/assignment1/Problem1.py
|
9143ff79c0ec2dd1df819548fa5acb670fea0dea
|
[] |
no_license
|
nyucusp/gx5003-fall2013
|
https://github.com/nyucusp/gx5003-fall2013
|
1fb98e603d27495704503954f06a800b90303b4b
|
b7c1e2ddb7540a995037db06ce7273bff30a56cd
|
refs/heads/master
| 2021-01-23T07:03:52.834758 | 2013-12-26T23:52:55 | 2013-12-26T23:52:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
# Assignment1, Problem1, Haozhe Wang
# <codecell>
import sys
# <codecell>
import sys
input_Range = map(int,sys.argv[1:])
happy = 0
for x in range(input_Range[0], input_Range[1]+1):
input_num = x
counter = 1
while input_num > 1:
if input_num%2 == 0:
input_num /= 2
else:
input_num *= 3
input_num += 1
counter += 1
if input_num == 1:
if counter > happy:
happy = counter
print input_Range[0], input_Range[1], happy
|
UTF-8
|
Python
| false | false | 2,013 |
2,525,440,791,537 |
ad48117e985f21190e1b01beda6e9d7b2f4c0666
|
d91fe0e972f2befab71987a732111b56245c5efc
|
/example_sm_pkg/scripts/robot_inspection_example.py
|
d927d11d7bf0e7c55d7e1a04516350078b6358fe
|
[] |
no_license
|
karla3jo/robocup2014
|
https://github.com/karla3jo/robocup2014
|
2064e8102d5a3251ae582b7ed37ab80d0398f71c
|
3d8563956fd1276b7e034402a9348dd5cb3dc165
|
refs/heads/master
| 2020-07-26T08:22:13.932741 | 2014-07-14T13:58:48 | 2014-07-14T13:58:48 | 21,850,936 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 22 12:00:00 2013
@author: sampfeiffer
"""
import rospy
import smach
import smach_ros
import actionlib
#from smach_ros import SimpleActionState, ServiceState
from super_state_machine import HelloWorldStateMachine
class DummyStateMachine(smach.State):
def __init__(self):
smach.State.__init__(self, outcomes=['succeeded'], output_keys=[])
def execute(self, userdata):
print "Dummy state to launch real State Machine"
rospy.sleep(1) # in seconds
return 'succeeded'
def main():
rospy.init_node('sm_example_sm_pkg')
sm = smach.StateMachine(outcomes=['succeeded', 'preempted', 'aborted'])
with sm:
# Using this state to wait and to initialize stuff if necessary (fill up input/output keys for example)
smach.StateMachine.add(
'dummy_state',
DummyStateMachine(),
transitions={'succeeded': 'HelloWorldStateMachine'})
smach.StateMachine.add(
'HelloWorldStateMachine',
HelloWorldStateMachine(),
transitions={'succeeded': 'succeeded', 'aborted': 'aborted'})
# This is for the smach_viewer so we can see what is happening, rosrun smach_viewer smach_viewer.py it's cool!
sis = smach_ros.IntrospectionServer(
'sm_example_sm_pkg_introspection', sm, '/SM_ROOT')
sis.start()
sm.execute()
rospy.spin()
sis.stop()
if __name__ == '__main__':
main()
|
UTF-8
|
Python
| false | false | 2,014 |
16,449,724,756,415 |
140d7071f7b028b16531115c6bee3c3df11ebef1
|
2a2697043d28b5e47ae03c79e927903665efde09
|
/Training/workflow.py
|
60948ac66ff20ab879e15d02232adb671426ffd0
|
[] |
no_license
|
sinomiko/advertisingLab
|
https://github.com/sinomiko/advertisingLab
|
13ad3903c8abe58cfac71718852594dc46737860
|
286ff5a49a313f589f3fa4846580434b6f1e655e
|
refs/heads/master
| 2020-03-27T08:21:48.290102 | 2014-04-04T07:43:30 | 2014-04-04T07:43:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import classify
import __init__
from util import TMP_DATA_DIR_PATH
from DataCleaning import userStatusWorkflow
if __name__ == '__main__' :
adset, userset = userStatusWorkflow.getPreSet('')
blacklist = set(['20174985','3834142','3373964','4344041','8350700','2878230','3803920','20174982','4341158','6434934', '3219148','20035409'])
adset = set([line.strip().split()[1] for line in file(TMP_DATA_DIR_PATH+'topAdClickCnt.dict.final')])
for adid in adset :
if adid in blacklist : continue
print adid
classify.workflow(adid ,testing=True)
|
UTF-8
|
Python
| false | false | 2,014 |
13,056,700,584,661 |
ee0fac87030dc272e3bdea0297035912f30a7b97
|
8c32112b0161ae4e504ce55af69d3be9b287313b
|
/lib/attr_update.py
|
497af585ecf4a2930d4d2c9a28bdc092b7b539ce
|
[
"GPL-3.0-only"
] |
non_permissive
|
spiffytech/npcworld
|
https://github.com/spiffytech/npcworld
|
faf78710fd85a4ede2789e2d4be18a4deb7e6ba6
|
8c9b2edf032d9782c8e70777f01d4f31efa1a49c
|
refs/heads/master
| 2020-05-18T16:14:55.782687 | 2014-06-01T20:00:40 | 2014-06-01T20:00:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
def attr_update(obj, child=None, _call=True, **kwargs):
'''Updates attributes on nested namedtuples.
Accepts a namedtuple object, a string denoting the nested namedtuple to update,
and keyword parameters for the new values to assign to its attributes.
You may set _call=False if you wish to assign a callable to a target attribute.
Example: to replace obj.x.y.z, do attr_update(obj, "x.y", z=new_value).
Example: attr_update(obj, "x.y.z", prop1=lambda prop1: prop1*2, prop2='new prop2')
Example: attr_update(obj, "x.y", lambda z: z._replace(prop1=prop1*2, prop2='new prop2'))
Example: attr_update(obj, alpha=lambda alpha: alpha*2, beta='new beta')
'''
def call_val(old, new):
if _call and callable(new):
new_value = new(old)
else:
new_value = new
return new_value
def replace_(to_replace, parts):
parent = reduce(getattr, parts, obj)
new_values = {k: call_val(getattr(parent, k), v) for k,v in to_replace.iteritems()}
new_parent = parent._replace(**new_values)
if len(parts) == 0:
return new_parent
else:
return {parts[-1]: new_parent}
if child in (None, ""):
parts = tuple()
else:
parts = child.split(".")
return reduce(
replace_,
(parts[:i] for i in xrange(len(parts), -1, -1)),
kwargs
)
|
UTF-8
|
Python
| false | false | 2,014 |
16,277,926,094,892 |
6ae7836ad82410430e4679e2bbfdb2b9375ebe6d
|
31afb32154cff65ce5be1cb0e578593af72a3210
|
/toner/controlers/console/controler.py
|
290669eea2efc3b301f4ddc5bc6d1a10cbd0de95
|
[
"GPL-3.0-only"
] |
non_permissive
|
pritam2505/pytoner
|
https://github.com/pritam2505/pytoner
|
3e78a09549d0793061e342f2225ce1a16f192bdb
|
fdb0f9f767f33d0b5bbad0332fffa987c4d9b91b
|
refs/heads/master
| 2021-01-10T04:43:10.039582 | 2007-10-15T17:35:19 | 2007-10-15T17:35:19 | 51,831,822 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#########################################################################
# #
# Copyright 2007 GAUTHIER-LAFAYE Mathieu <mathgl@freesurf.fr> #
# #
# This file is part of PyToner #
# #
# PyToner is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# PyTonner is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
# #
#########################################################################
from toner import core
class Controler:
def __init__(self):
self._logs = core.Logs()
def _input(self, prompt=None):
if prompt is None:
line = raw_input()
else:
line = raw_input(prompt)
if '\n' in line:
line = line[:-1]
return line
def _input_int(self, prompt=None):
try:
num = int(self._input(prompt))
except:
print "Only numeric values are allowed !"
return -1
return num
def _input_num_or_list(self, list, prompt=None):
while True:
line = self._input(prompt)
num = -1
if line == "l":
list()
continue
try:
num = int(line)
except:
print "Need numeric value or 'l' for list"
if num > -1:
break
return num
def _input_with_default(self, default, prompt=None):
line = self._input("%s [%s] " % (prompt, default))
if line == "":
line = default
return line
|
UTF-8
|
Python
| false | false | 2,007 |
2,345,052,181,233 |
cc6eda6624ef92281f4d858f8ef144d9f606d080
|
9e8808b76f437c1dfe5178cff5ff7dae3c2b1a94
|
/gammapy/image/tests/test_profile.py
|
d40208f6b686c4080a29860caefef8b5bfefb80f
|
[] |
no_license
|
ellisowen/gammapy
|
https://github.com/ellisowen/gammapy
|
8b813b73a944a528bcb6be02e9ae8a723622b6d3
|
f30420fbb2bf14d711f79e7af4fc8d71b376e67b
|
refs/heads/master
| 2021-01-17T07:39:10.827691 | 2014-08-07T08:55:06 | 2014-08-07T08:55:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import print_function, division
from numpy.testing import assert_allclose
from astropy.tests.helper import pytest
from .. import profile
try:
import pandas
HAS_PANDAS = True
except ImportError:
HAS_PANDAS = False
@pytest.mark.skipif('not HAS_PANDAS')
def test_compute_binning():
data = [1, 3, 2, 2, 4]
bin_edges = profile.compute_binning(data, n_bins=3, method='equal width')
assert_allclose(bin_edges, [1, 2, 3, 4])
bin_edges = profile.compute_binning(data, n_bins=3, method='equal entries')
# TODO: create test-cases that have been verified by hand here!
assert_allclose(bin_edges, [1, 2, 2.66666667, 4])
|
UTF-8
|
Python
| false | false | 2,014 |
6,597,069,796,277 |
5160fef837973c6bf34b70b0b5b4bcc742647865
|
358fe4332b85cc32c489c05b4967981ad8f05ac0
|
/site/urbanjungle/__init__.py
|
7e676576aacca67ccf3189e6ad0f30c250164eb5
|
[
"GPL-3.0-only"
] |
non_permissive
|
thibault/UrbanJungle
|
https://github.com/thibault/UrbanJungle
|
317c2a48268e281874f18852377df4b4bedc3778
|
7610d8f02f5b591ce603ba522a0c9a3fc5472d82
|
refs/heads/master
| 2020-05-18T15:58:38.864694 | 2011-04-14T12:55:48 | 2011-04-14T12:55:48 | 1,540,558 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import os
from flask import Flask
from flaskext.babel import Babel
app = Flask(__name__)
if os.getenv('DEV') == 'yes':
app.config.from_object('urbanjungle.config.DevelopmentConfig')
elif os.getenv('TEST') == 'yes':
app.config.from_object('urbanjungle.config.TestConfig')
else:
app.config.from_object('urbanjungle.config.ProductionConfig')
babel = Babel(app)
from urbanjungle.controllers.frontend import frontend
app.register_module(frontend)
from urbanjungle.controllers.backend import backend
app.register_module(backend, url_prefix='/admin')
|
UTF-8
|
Python
| false | false | 2,011 |
17,583,596,127,152 |
1f49c9c2224280e77406b12f826099b27bd6c004
|
ca0da0bf29780ee9bd17cfd6efc67386aea68d26
|
/ml/neural_network.py
|
cf8b84afa77ee867a017d01c7abe272040376024
|
[] |
no_license
|
pavelgrib/MachineLearningCourse
|
https://github.com/pavelgrib/MachineLearningCourse
|
3d5afaaef263045f9f2fa49eb570ff720d1f7630
|
ff5a0aab5877d11678a1d4c7b837bfc29a2838e3
|
refs/heads/master
| 2021-05-26T19:51:50.104893 | 2013-07-18T12:10:55 | 2013-07-18T12:10:55 | 6,245,222 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
'''
Created on May 2, 2013
@author: paul
'''
import math, cmath
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(x):
return 1/(1 + math.exp(-x))
def softmax(xs, i):
return math.exp(xs[i]) / sum([math.exp(x) for x in xs])
class NeuralNetwork(object):
def __init__(self):
self.activation = None
self.hidden = None
self.weights = None
def setLayerStructure(self, hiddenLayers):
""" hiddenLayers should look like: [2,3,...] """
self.hidden = hiddenLayers
if not self.activation:
self.activation = [] * len(hiddenLayers)
elif len(self.hidden) > len(self.activation):
self.activation += [0] * (len(self.hidden) - len(self.activation))
elif len(self.hidden) < len(self.activation):
self.activation = self.activation[0:len(self.hidden)]
def setActivation(self, function, forLayer=0):
try:
self.activation[forLayer] = np.vectorize(function)
except IndexError:
print 'activation not set; index ' + str(forLayer) + ' exceeds current number of layers: ' + \
str(len(self.activation)) + '. Call setLayerStructure(anIntList) to change this.'
def learnBP(self, learningData, learningOutputs):
pass
def learnGD(self, learningData, learningOutputs):
pass
def learnSGD(self, learningData, learningOutputs):
pass
def predict(self, testingInputs):
if not (self.hidden and self.activation and self.weights):
raise NetworkNotReadyError(self.hidden, self.activation, self.weights)
elif testingInputs.shape[::-1] == self.weights.shape:
testingInputs = testingInputs.T
else:
pred = np.zeros( (testingInputs.shape[0], self.weights.shape[2]), dtype=float )
for idx, obs in enumerate(np.nditer(testingInputs)):
a = obs
for hiddenLayer in self.hidden:
a = self.activation[hiddenLayer](self.weights[hiddenLayer,:,:] * a)
pred[idx,:] = self.weights[-1,:,:] * a
class NetworkNotReadyError(Exception):
def __init__(self, hidden, activation, weights):
super( NetworkNotReadyError, self).__init__()
self.hidden = hidden
self.activation = activation
self.weights = weights
self.failed = [hidden is None, activation is None, weights is None]
def __str__(self):
return repr(self.failed)
|
UTF-8
|
Python
| false | false | 2,013 |
15,427,522,546,551 |
8a4f4a4c2e26d476069604ea1cfeb020d6a5ed89
|
7c620d87564200b7a0ce74b21ea287ab9ae440a7
|
/Foam/dynamicFvMesh/__init__.py
|
30653d270a43b9d3ca296a427d501a7c2c8442d0
|
[
"GPL-3.0-or-later",
"LicenseRef-scancode-free-unknown",
"GPL-3.0-only"
] |
non_permissive
|
alexey4petrov/pythonFlu
|
https://github.com/alexey4petrov/pythonFlu
|
7732789979d8ed50c1a0bbbb8b79ccf758852323
|
19b0ae8c94e9a406b8cee659ff4dd5fdf68c6b49
|
refs/heads/master
| 2021-01-15T20:57:20.939977 | 2012-10-21T00:05:44 | 2012-10-21T00:05:44 | 1,529,236 | 7 | 3 | null | false | 2012-07-04T13:49:02 | 2011-03-26T13:46:50 | 2012-07-04T08:04:35 | 2012-07-04T08:04:35 | 196 | null | null | null |
C++
| null | null |
## pythonFlu - Python wrapping for OpenFOAM C++ API
## Copyright (C) 2010- Alexey Petrov
## Copyright (C) 2009-2010 Pebble Bed Modular Reactor (Pty) Limited (PBMR)
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## See http://sourceforge.net/projects/pythonflu
##
## Author : Alexey PETROV
##
#---------------------------------------------------------------------------
def createDynamicFvMesh( runTime ):
from Foam import get_proper_function
fun = get_proper_function( "Foam.dynamicFvMesh.createDynamicFvMesh_impl",
"createDynamicFvMesh" )
return fun( runTime )
#------------------------------------------------------------------------------
def meshCourantNo( runTime, mesh, phi ):
meshCoNum = 0.0
meanMeshCoNum = 0.0
if mesh.nInternalFaces():
SfUfbyDelta = mesh.deltaCoeffs() * mesh.phi().mag()
meshCoNum = ( SfUfbyDelta / mesh.magSf() ).ext_max().value() * runTime.deltaT().value()
meanMeshCoNum = ( SfUfbyDelta.sum() / mesh.magSf().sum() ).value() * runTime.deltaT().value()
pass
from Foam.OpenFOAM import ext_Info, nl
ext_Info() << "Mesh Courant Number mean: " << meanMeshCoNum << " max: " << meshCoNum << nl << nl
return meshCoNum, meanMeshCoNum
#----------------------------------------------------------------------------
def createDynamicFvMeshHolder( runTime ):
from Foam import man
autoPtrMesh = createDynamicFvMesh( runTime )
return man( autoPtrMesh.ptr(), man.Deps( runTime ) )
|
UTF-8
|
Python
| false | false | 2,012 |
4,956,392,296,099 |
96aa964a72c0455643c84ceab2652194493de9aa
|
23d99f12ac46f8213e8aba3d237d0ac53745aea6
|
/test.py
|
38cd4a6a4cb6126930e3421afb96938cf3d02c88
|
[] |
no_license
|
linmartinescu/Code
|
https://github.com/linmartinescu/Code
|
95f401bb40a17376828e8df4c8f60c9449e5922e
|
f711a65d9d4441cd79fb0368d3720b568f4eeaf8
|
HEAD
| 2016-08-08T06:30:47.507693 | 2014-12-16T22:28:05 | 2014-12-16T22:28:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
if __name__ == '__main__':
import geometry
v1 = geometry.Vector(4, 3)
print 'v1 =', v1
print 'Type of v1 =', type(v1)
print 'x-component of v1 =', v1.get_x()
print 'y-component of v1 =', v1.get_y()
print 'Magnitude of v1 =', v1.magnitude()
print 'Normalized v1 =', v1.normalize()
v2 = geometry.Vector()
print 'v2 =', v2
v2.set_x(3)
v2.set_y(4)
print 'v2 =', v2
print 'Type of v2 =', type(v2)
print 'x-component of v2 =', v2.get_x()
print 'y-component of v2 =', v2.get_y()
print 'Magnitude of v2 =', v2.magnitude()
print 'Length of v2 =', len(v2)
print '|v1| = ', abs(v1)
print 'Normalized v2 =', v2.normalize()
v3 = geometry.Vector(3.0,4.0)
print 'v3 = ', v3
print 'v1 == v2 =', v1 == v2
print 'v1 == v1 =', v1 == v1
print 'v1 == v3 = ', v1 == v3
print 'v2 == v3 = ', v2 == v3
#test addition
print 'v1 + v2 =', v1 + v2
# test '__mul__'
print 'v1 * 7 =', v1 * 7
print '7 * v1 =', 7 * v1
# test division
print 'v3 / 2.0 = ', v3 / 2.0
listVectors = [v1, v2, v3]
print 'List of vectors [v1, v2, v3] =', listVectors
tupleVectors = (v1, v2, v3)
print 'Tuple of vectors (v1, v2, v3) =', tupleVectors
|
UTF-8
|
Python
| false | false | 2,014 |
17,678,085,402,527 |
88f18965e233fe7de76fda20c90d2bfe57830690
|
d486f9334ed2d9c35a5088710f51632fee46135c
|
/src/util/freespace.py
|
657b0425f1cbc1285e3306a6ccd11e92c0913ead
|
[] |
no_license
|
bluescorpio/PyProjs
|
https://github.com/bluescorpio/PyProjs
|
9ae1451fc6035c70c97015887fe40947fbe0b56d
|
7df126ec7930484b4547aaf15fa8c04f08a5ca7e
|
refs/heads/master
| 2016-08-01T13:36:51.555589 | 2014-05-28T14:00:56 | 2014-05-28T14:00:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
#coding=utf-8
import win32file
sectorsPerCluster, bytesPerSector, numFreeClusters, totalNumClusters \
= win32file.GetDiskFreeSpace("c:\\")
print "FreeSpace: ", (numFreeClusters * sectorsPerCluster * bytesPerSector)/(1024*1024), "MB"
|
UTF-8
|
Python
| false | false | 2,014 |
2,370,821,953,484 |
521cfe337b33f36ddf4c77c41c7cb7467e13c8e5
|
ad3a0791101c73037d8a5c159a67fe672b5807cf
|
/18_long/long.py
|
461c3fa865b7d97973c23b16d885bfa423d5d64d
|
[] |
no_license
|
thunderbump/Rosalind
|
https://github.com/thunderbump/Rosalind
|
eed6593c2e2dd9db28d8b98d435f23694e88c692
|
2f2089e507726c8c094823466d7d4df18d7277d5
|
refs/heads/master
| 2019-01-02T04:59:46.294834 | 2013-04-23T17:12:48 | 2013-04-23T17:12:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
"""Computes the shortest superstring of a series of substrings in a given datafile"""
import sys
argc = len(sys.argv)
data_file_loc = "test_data"
usage = """long.py [data file]
Computes the shortest superstring of a series of substrings in a given datafile"""
if argc > 2:
print(usage)
sys.exit(1)
if argc == 2:
data_file_loc = sys.argv[1]
try:
data_file = open(data_file_loc)
sub_seqs = []
for line in data_file:
if line[-1] == '\n':
line = line[:-1]
if line[-1] == '\r':
line = line[:-1]
sub_seqs.append(line)
data_file.close()
except IOError, error:
print(error)
print(usage)
sys.exit(1)
def check_collision(seqA, seqB):
if seqA in seqB:
return seqB
if seqB in seqA:
return seqA
index = min(len(seqA), len(seqB))
while index > 0:
if seqA[:index] == seqB[len(seqB) - index:]:
return "%s%s" % (seqB[:len(seqB) - index], seqA)
if seqB[:index] == seqA[len(seqA) - index:]:
return "%s%s" % (seqA[:len(seqA) - index], seqB)
index -= 1
def find_collision(sequences):
primary = sequences.pop(0)
min_len_diff = sys.maxint
min_len_index = None
min_len_seq = None
for index, sequence in enumerate(sequences):
candidate = check_collision(primary, sequence)
if candidate == None:
continue
vanilla_len = max(len(sequence), len(primary))
post_len = len(candidate)
if min_len_diff > (post_len - vanilla_len):
min_len_diff = (post_len - vanilla_len)
min_len_index = index
min_len_seq = candidate
if min_len_seq == None:
min_len_sequence = primary
sequences.append("")
min_len_index = -1
sequences.pop(min_len_index)
sequences.append(min_len_seq)
return sequences
while len(sub_seqs) > 1:
sub_seqs = find_collision(sub_seqs)
print sub_seqs[0]
|
UTF-8
|
Python
| false | false | 2,013 |
13,950,053,779,839 |
7affe4987f791b4508f550c2ef87c0d5687a4f10
|
195d979ac1413f56ca4f8b8873f4b4a17807cc51
|
/Data/goodClusters.py
|
30e8d1afed5b363d55b58bf4e82a9f5d65306ac9
|
[] |
no_license
|
saadmahboob/Context-Classifier
|
https://github.com/saadmahboob/Context-Classifier
|
37baecafd9ccc151d715a5f9ff9703afa6fa1b37
|
df73e21093017d3f4193c32b353e57af74397ec8
|
refs/heads/master
| 2021-05-28T03:51:51.583700 | 2014-05-27T02:32:37 | 2014-05-27T02:32:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
'''
Created on Apr 28, 2014
@author: jshor
'''
def get_good_clusters(i):
'''
0 is all place cells
1 is for animal 66, session 60
2 is for animal 70, session 8
Names need to be distinct for caching to work
'''
name = ['All clusters', 'Place Cell clusters (66,60)',
'Place Cell clusters (70,8)'][i]
good = [{i: range(2,100) for
i in range(1,17)},
{1:[2,4,5,6],
2:[5,6],
3:[2,3,4,7,8,10,11],
4:[2,5,6],
5:[2,3,6,7,9],
6:[2],
7:[2,3],
11:[2],
12:[2,3]},
{2:range(2,19),
3:range(2,10),
4:range(2,20),
6:[2,3],
9:[2,3,4,5,6,7,11],
10:[2,3,4],
11:[3,4],
13:[2,3],
15:[2,3],
16:[2,3,4]}][i]
return name, good
|
UTF-8
|
Python
| false | false | 2,014 |
12,515,534,706,919 |
bec7c3571d7a631683f7d5f8f848af6179bb8381
|
ca0d33992a5657c32484fd49ab30f4e0e8e72cba
|
/chapter 1&2/product.py
|
8c0195755214a9e9abe849b228ae5c454db0791f
|
[] |
no_license
|
Haseebvp/Anand-python
|
https://github.com/Haseebvp/Anand-python
|
406ba01d89d0849be9a83ecb342454448267c552
|
d17c692d0aba29e96a3f55177a943c65ab0ec7a6
|
refs/heads/master
| 2020-04-07T13:37:46.590801 | 2013-10-21T07:03:27 | 2013-10-21T07:03:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#Implement a function product, to compute product of a list of numbers.
def prod(a):
t=1
for i in a:
t=t*i
return t
print prod([1,2,3])
|
UTF-8
|
Python
| false | false | 2,013 |
12,515,534,716,023 |
2d4963e4cbf7b48e6db0c83a525a8d7c5c227fdd
|
44ae7979b9706fe94664be6135e299e3abc7302e
|
/utils.py
|
05abf80aac19b536a8ca2a05c77d9114ba785c25
|
[
"MIT"
] |
permissive
|
chairmanK/eulerian-audio-magnification
|
https://github.com/chairmanK/eulerian-audio-magnification
|
122666bd61b7f6f810797b6ef29a316db8cf2def
|
b2ce5bb310be47e6be0873538a23ef381614ec24
|
refs/heads/master
| 2021-01-23T14:56:10.380673 | 2013-02-17T21:54:31 | 2013-02-17T21:54:31 | 8,239,258 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import numpy as np
from scipy.io import wavfile
from scipy.signal import firwin, filtfilt, hamming, resample
default_nyquist = 22050.0
def slurp_wav(path, start=0, end=(44100 * 10)):
"""Read samples from the 0th channel of a WAV file specified by
*path*."""
(fs, signal) = wavfile.read(path)
nyq = fs / 2.0
# For expediency, just pull one channel
if signal.ndim > 1:
signal = signal[:, 0]
signal = signal[start:end]
return (nyq, signal)
def _num_windows(length, window, step):
return max(0, int((length - window + step) / step))
def window_slice_iterator(length, window, step):
"""Generate slices into a 1-dimensional array of specified *length*
with the specified *window* size and *step* size.
Yields slice objects of length *window*. Any remainder at the end is
unceremoniously truncated.
"""
num_windows = _num_windows(length, window, step)
for i in xrange(num_windows):
start = step * i
end = start + window
yield slice(start, end)
def stft(signal, window=1024, step=None, n=None):
"""Compute the short-time Fourier transform on a 1-dimensional array
*signal*, with the specified *window* size, *step* size, and
*n*-resolution FFT.
This function returns a 2-dimensional array of complex floats. The
0th dimension is time (window steps) and the 1th dimension is
frequency.
"""
if step is None:
step = window / 2
if n is None:
n = window
if signal.ndim != 1:
raise ValueError("signal must be a 1-dimensional array")
length = signal.size
num_windows = _num_windows(length, window, step)
out = np.zeros((num_windows, n), dtype=np.complex64)
taper = hamming(window)
for (i, s) in enumerate(window_slice_iterator(length, window, step)):
out[i, :] = np.fft.fft(signal[s] * taper, n)
pyr = stft_laplacian_pyramid(out)
return out
def stft_laplacian_pyramid(spectrogram, levels=None):
"""For each window of the spectrogram, construct laplacian pyramid
on the real and imaginary components of the FFT.
"""
(num_windows, num_freqs) = spectrogram.shape
if levels is None:
levels = int(np.log2(num_freqs))
# (num_windows, num_frequencies, levels)
pyr = np.zeros(spectrogram.shape + (levels,), dtype=np.complex)
for i in xrange(num_windows):
real_pyr = list(laplacian_pyramid(np.real(spectrogram[i, :]), levels=levels))
imag_pyr = list(laplacian_pyramid(np.imag(spectrogram[i, :]), levels=levels))
for j in xrange(levels):
pyr[i, :, j] = real_pyr[j] + 1.0j * imag_pyr[j]
return pyr
def laplacian_pyramid(arr, levels=None):
if arr.ndim != 1:
raise ValueError("arr must be 1-dimensional")
if levels is None:
levels = int(np.log2(arr.size))
tap = np.array([1.0, 4.0, 6.0, 4.0, 1.0]) / 16.0
tap_fft = np.fft.fft(tap, arr.size)
for i in xrange(levels):
smoothed = np.real(np.fft.ifft(np.fft.fft(arr) * tap_fft))
band = arr - smoothed
yield band
arr = smoothed
def amplify_pyramid(pyr, passband, fs, gain=5.0):
tap = firwin(100, passband, nyq=(fs / 2.0), pass_zero=False)
(_, num_freqs, levels) = pyr.shape
amplified_pyr = np.copy(pyr)
for i in xrange(num_freqs):
for j in xrange(levels):
amplitude = gain * filtfilt(tap, [1.0], np.abs(pyr[:, i, j]))
theta = np.angle(pyr[:, i, j])
amplified_pyr[:, i, j] += amplitude * np.exp(1.0j * theta)
return amplified_pyr
def resynthesize(spectrogram, window=1024, step=None, n=None):
"""Compute the short-time Fourier transform on a 1-dimensional array
*signal*, with the specified *window* size, *step* size, and
*n*-resolution FFT.
This function returns a 2-dimensional array of complex floats. The
0th dimension is time (window steps) and the 1th dimension is
frequency.
"""
if step is None:
step = window / 2
if n is None:
n = window
if spectrogram.ndim != 2:
raise ValueError("spectrogram must be a 2-dimensional array")
(num_windows, num_freqs) = spectrogram.shape
length = step * (num_windows - 1) + window
signal = np.zeros((length,))
for i in xrange(num_windows):
snippet = np.real(np.fft.ifft(spectrogram[i, :], window))
signal[(step * i):(step * i + window)] += snippet
signal = signal[window:]
ceiling = np.max(np.abs(signal))
signal = signal / ceiling * 0.9 * 0x8000
signal = signal.astype(np.int16)
return signal
def amplify_modulation(spectrogram, fs, passband=[1.0, 10.0], gain=0.0):
(num_windows, num_freqs) = spectrogram.shape
envelope = np.abs(spectrogram)
amplification = np.ones(envelope.shape)
if gain > 0.0:
taps = firwin(200, passband, nyq=(fs / 2.0), pass_zero=False)
for i in xrange(num_freqs):
#amplification[:, i] = envelope[:, i] + gain * filtfilt(
# taps, [1.0], envelope[:, i])
amplification[:, i] = gain * filtfilt(
taps, [1.0], envelope[:, i])
amplification = np.maximum(0.0, amplification)
amplified_spectrogram = spectrogram * amplification
return amplified_spectrogram
def svd_truncation(spectrogram, k=[0]):
"""Compute SVD of the spectrogram, trunate to *k* components,
reconstitute a new spectrogram."""
# SVD of the spectrogram:
# u.shape == (num_windows, k)
# s.shape == (k, k)
# v.shape == (k, n)
# where
# k == min(num_windows, n)
(left, sv, right) = np.linalg.svd(spectrogram, full_matrices=False)
zero_out = np.array([i for i in xrange(sv.size) if i not in k])
if zero_out.size:
sv[zero_out] = 0.0
truncated = np.dot(left, sv[:, np.newaxis] * right)
return truncated
def total_power(spectrogram):
return np.power(np.abs(spectrogram), 2).sum()
def normalize_total_power(spectrogram, total):
unit_power = spectrogram / np.sqrt(total_power(spectrogram))
return unit_power * np.sqrt(total)
def estimate_spectral_power(spectrogram):
"""Given a spectrogram, compute power for each frequency band."""
# compute mean power at each frequency
power = np.power(np.abs(spectrogram), 2).mean(axis=0)
return power
|
UTF-8
|
Python
| false | false | 2,013 |
9,809,705,322,290 |
da22034d30900327103d9463c9192d8fee115ceb
|
ede7e8184d3b9b36086ea0f1e4f303e2c380fe2b
|
/nilmtk/building.py
|
879f740273df603a1b016656e761fa65ddd62680
|
[
"Apache-2.0"
] |
permissive
|
tonicebrian/nilmtk
|
https://github.com/tonicebrian/nilmtk
|
ec7a1f374f49b17bf92ddb39f54960a7f492c105
|
0c333672b67052d7c32a0d6c31e7c9bec595d759
|
refs/heads/master
| 2021-01-15T11:23:49.996174 | 2013-12-09T12:04:20 | 2013-12-09T12:04:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from nilmtk.sensors.utility import Utility
from nilmtk.sensors.ambient import Ambient
class Building(object):
"""Represent a physical building (e.g. a domestic house).
Attributes
----------
geographic_coordinates : pair of floats, optional
(latitude, longitude)
n_occupants : int, optional
Max number of occupants.
rooms : list of strings, optional
A list of room names. Use standard names for each room
utility : nilmtk Utility object
ambient : nilmtk Ambient object
Stores weather etc.
"""
def __init__(self):
self.geographic_coordinates = None
self.n_occupants = None
self.rooms = []
self.utility = Utility()
self.ambient = Ambient()
def crop(self, start, end):
"""Reduce all timeseries to just these dates"""
raise NotImplementedError
|
UTF-8
|
Python
| false | false | 2,013 |
15,668,040,721,023 |
3f862423f668ef0c0755e752c67b34eb4c1fca97
|
f5f01f9d6c48fa360dfa72b673bd51d4629a1aea
|
/battleShip.py
|
24abb80eb402b145849c43ed50b3bc48764ace39
|
[] |
no_license
|
jackieqif/Python-BattleShip
|
https://github.com/jackieqif/Python-BattleShip
|
37059640c0477eee11c7b47c91836753baf471fd
|
fce7dd973c5b3ef5a2b6579674e1686d43200cc9
|
refs/heads/master
| 2016-09-02T01:13:02.252746 | 2014-01-10T23:33:22 | 2014-01-10T23:33:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
"""BattleShip board Game, by jackieq.
"""
from random import randint
from urllib2 import Request
# from urllib2 import URLError
from urllib2 import urlopen
BOARD = [['O' for a in xrange(5)] for b in xrange(5)]
LEVEL = {
1: 10,
2: 6,
3: 3
}
HIT_MARK = 'X'
class StoryLine(object):
"""Class holding storyline.
Each methords contains dedicate part of the story, i.e. PrintOpening()
"""
def __init__(self, name=None):
self.ascii_url = {
'leg': ['http://www.ascii-art.de/ascii/jkl/leg.txt', (270, 2000)],
'marriage': ['http://www.ascii-art.de/ascii/mno/marriage.txt',
(700, 2500)]
}
self.name = name
def PrintRemote(self, picture, message=None):
url = self.ascii_url[picture][0]
start, end = self.ascii_url[picture][1][0], self.ascii_url[picture][1][1]
request = Request(url)
response = urlopen(request)
content = response.read()[start:end]
print content
print '\n'
if message:
print message
def PrintOpening(self):
"""Print story opening."""
print r"""
,:
,' |
/ :
--' /
\/ />
/ <//
__/ /
)'-. /
./ //
/.' '
'/' ,
+
'
`.
.-"-
( |
. .-' '.
( (. )8:
.' / (_ )
_. :(. )8P `
. ( `-' ( `. .
. : ( .a8a)
/_`( "a `a. )"' '
( (/ . ' )=='') ` a `
( ( ) .8" +)) `) ` `
______ _ _ _ _____ _ _ _____ _____ __ ___
| ___ \ | | | | | | / ___| | (_) / __ \| _ |/ | / |
| |_/ / __ _| |_| |_| | ___ \ `--.| |__ _ _ __ `' / /'| |/' |`| | / /| |
| ___ \/ _` | __| __| |/ _ \ `--. \ '_ \| | '_ \ / / | /| | | |/ /_| |
| |_/ / (_| | |_| |_| | __/ /\__/ / | | | | |_) | ./ /___\ |_/ /_| |\___ |
\____/ \__,_|\__|\__|_|\___| \____/|_| |_|_| .__/ \_____/ \___/ \___/ |_/
| |
|_| jackieq@
"""
Continue()
print '\n' * 5
print r"""
________________________________________________________________________________
, _, ___,'_, ,_, _ , , __ _ ___,___, _, _, , , ___, ,_!
| /_,' | (_, |_)'|\ \_/ '|_)'|\\' | ' | | /_,(_, |_|,' | |_)
'|__'\_ | _) '|'|_|-\ , /` _|_) |-\ | |'|__'\_ _)'| | _|_,'|
' ` ' ' ' ' `(_/ ' ' `' ' ' `' ' ` ' '
________________________________________________________________________________
A invading alian flagship has been detected.
Your goal is to save your nation by sinking the enemy ship as a commander.
"We need to eliminate
all species here, "... people working for Google,
where should we start they are the ones most likely could stop us..."
from?"
\ _.-'~~~~'-._ /
. .-~ \__/ \__/ ~-. .
.-~ (oo) (oo) ~-.
(_____//~~ O//~~ O______)
_.-~` `~-._
/O=O=O=O=O=O=O=O=O=O=O=O=O=O=O=O=O=O\ *
\___________________________________/
\\x x x x x x x/
. * \\x_x_x_x_x_x/
"""
Continue()
print r"""
# # ( )
___#_#___|__
_ |____________| _
_=====| | | | | |==== _
=====| |.---------------------------. | |====
<--------------------' . . . . . . . . '--------------/
\ /
\_______________________________________________WWS_________/
wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
This is your ship, Commander.
It is equipped with advanced shield and guided missle.
"""
def PrintEntering(self):
"""Print ship entering battle field."""
print r"""
_____________________________________________
Entering into battle area...
_____________________________________________
| |
|-|-| |
| |
| {O} |
'--| |
.|]_ |
_.-=.' | |
| | |]_ |
|_.-=' | __|__
_.-=' |\ /|\\
| | |-'-'-'-'-.
|_.-=' '========='
` | |
`. | / \\
|| / \____.
||_.'--==' | // // / /
|| | | |\\ // // / / ___
____ ||__|____|____| \||_/ |_/ |__/ \ __________________/| |
| |______ |===.---. .---.========''=-./// | | | / | |
| || |\| ||| | | | '===' || \|_____|_____|____/__|___|
|-.._||_____|_\___'---' '---'______....---===''======//=//////========|
|--------------\------------------/-----------------//-//////---------/
| \ / // ////// /
| \______________/ // ////// /
| _____===//=//////=========/
|============================================================== /
'----------------------------------------------------------------`
Remember, you just need to provide row and colum number
as coordinate for your missle to hit the hidden alien ship.
"""
Continue()
def PrintRadar1(self):
print r"""
.- _ _ -.
/ / \ .
( ( (` (-o-) `) ) )
\ \_ ` -+- ` _/ /
`- -+- -`
__ _ ___ _|_ ___ __ ___"""
def PrintRadar2(self):
print """
O
|
|
______|
/______ |
| | |
| ===== | |
| ===== | |
| | |
| .-. | | o
| ' . ' | | ~-
..'| '._.' | | o
.' |_______|/ """
def PrintRadar3(self):
print r"""
,-.
/ \ `. __..-,O
: \ --''_..-'.'
| . .-' `. '.
: . .`.'
\ `. / ..
\ `. ' .
`, `. .
,|,`. `-..
|||| ``-...__..-` """
def PrintDefeated(self):
"""print message after being defeated."""
print r"""
You base was destroyed,
and you become homeless...
____
__,-~~/~ `---.
_/_,---( , )
__ / < / ) \___
- ------===;;;'====------------------===;;;===----- - -
\/ ~"~"~"~"~"~\~"~)~"/
(_ ( \ ( > \)
\_( _ < >_>'
~ `-i' ::>|--"
I;|.|.|
<|i::|i|`.
(` ^'"`-' ")
------------------------------------------------------------------
______ _____
/ _____) / ___ \\
| / ___ ____ ____ ____ | | | |_ _ ____ ____
| | (___)/ _ | \ / _ ) | | | | | | / _ )/ ___)
| \____/( ( | | | | ( (/ / | |___| |\ V ( (/ /| |
\_____/ \_||_|_|_|_|\____) \_____/ \_/ \____)_|
"""
Continue()
print r"""
,a_a
{/ ''\_
{\ ,_oo)
{/ (_^_____________________
.=. {/ \___)))*)----------;=====;`
(.=.`\ {/ /=; ~~ |||::::
\ `\{/( \/\ |||::::
\ `. `\ ) ) |||||||
You \ // /_/_ |||||||
'==''---)))) |||||||
You managed to escape though...
\ O,
\___________\/ )_________/
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
def PrintVictory(self):
print r"""
I can\'t believe it, you just sank my ship!
Congratilations, you Win!
|__
|\/
[[ ********* ]] |--
[[ We are proud of you!]]--/ |
[[ ***** ***** ]] | ||
_/| _/|-++'
+ +--| |--|--|_ |-
{ /|__| |/\__| |--- |||__/
+---------------___[}-_===_.'____ /
____`-' ||___-{]_| _[}- | |_[___\==-- \/ _
__..._____--==/___]_|__|_____________________________[___\==--____,------' .7
| You Win /
\_________________________________________________________________________|
wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
""" # end of Story class
def PrintBoard(board):
print r"""
N
W-|-E
S
"""
print ' ' + ' '.join([str(i) for i in xrange(1, 6)])
print ' ' + '-'.join(['-' for i in xrange(5)])
for row in xrange(5):
print str(row + 1) + '| ' + ' '.join(board[row])
def SelectLevel():
while True:
try:
user_input = int(raw_input('Please select game level (1~3): '))
except ValueError:
user_input = ''
if user_input not in [1, 2, 3]:
print 'Please input a number from 1 to 3'
else:
print '\n' * 11
print 'Level ' + str(user_input)
print '__________________________________________________________________'
print 'You have total of % s rounds to sink the alien ship.' % (
LEVEL[user_input])
print '__________________________________________________________________'
print '\n'
print 'Alian Ship detetcted! Missile waiting for target coordinate..'
print '\n' * 11
raw_input('Press Enter to continue...')
return LEVEL[user_input]
def RandomRow(board):
return randint(0, len(board) - 1)
def RandomCol(board):
return randint(0, len(board[0]) - 1)
def RadarOfficior(story, ship_row, ship_col, guess_col, guess_row):
"""print hint base on user input's offset to ship position."""
if ship_row - guess_row < 0:
story.PrintRadar1()
print '((( Radar station1: Commander, enemy is up north )))'
elif ship_row - guess_row > 0:
story.PrintRadar1()
print '((( Radar station1: Commander, enemy is down south )))'
else:
story.PrintRadar2()
print '((( Radar station1: Commander, we are on the right row! )))'
if ship_col - guess_col < 0:
print '((( Radar station2: Commander, enemy is further west )))'
elif ship_col - guess_col > 0:
print '((( Radar station2: Commander, enemy is further east )))'
else:
print '((( Radar station2: Commander, we are on the right column! )))'
if abs(ship_col - guess_col) == 1 and abs(ship_row - guess_row) == 1:
story.PrintRadar3()
print ('((((( Beep... Beep... radar station3 detected that enemy is one '
'coodinate away from your last hit point!!! ))))')
def Guess(story, ship_row, ship_col):
PrintBoard(BOARD)
result = False
try:
guess_row = int(raw_input('Target Row (1~5):')) - 1
guess_col = int(raw_input('Target Col (1_5):')) - 1
except ValueError:
print 'Commander, we can not understand coodinate you\'ve provided...'
return result
if guess_row == ship_row and guess_col == ship_col:
print 'Bang... Bang...'
print 'Bang...'
print 'Target down! Target down!'
result = True
return result
else:
if guess_row < 0 or guess_row > 4 or guess_col < 0 or guess_col > 4:
print 'Oops, that\'s not even in the ocean.'
elif BOARD[guess_row][guess_col] == HIT_MARK:
print 'You guessed that one already.'
else:
print 'You missed the battleship!'
RadarOfficior(story, ship_row, ship_col, guess_col, guess_row)
BOARD[guess_row][guess_col] = HIT_MARK
return result
def StartOver():
while True:
user_input = raw_input('Play again? (y/n): ')
if user_input == 'y':
return True
elif user_input == 'n':
return False
else:
print 'Sorry Commander, I can not understand your instruction... \n'
def Continue():
raw_input('Press Enter to continue...')
def Main():
while True:
story = StoryLine()
story.PrintOpening()
ship_row = RandomRow(BOARD)
ship_col = RandomCol(BOARD)
rounds = SelectLevel()
story.PrintEntering()
for current_round in xrange(rounds):
print 'Round: ' + str(current_round+1)
result = Guess(story, ship_row, ship_col)
if result:
story.PrintVictory()
break
elif current_round == rounds - 1 and not result:
story.PrintDefeated()
if not StartOver():
break
if __name__ == '__main__':
Main()
|
UTF-8
|
Python
| false | false | 2,014 |
14,688,788,153,763 |
8dd998bc5f30b2de692d307c5141fc80e118c948
|
f9b4d4583b7de9ee2458473d05094e4c2cd1bc47
|
/src/linalg/math.py
|
3aa1174808b35e1af99fffca220489bca619e0c0
|
[] |
no_license
|
moshev/mozyka
|
https://github.com/moshev/mozyka
|
2f99627651cc64985f677b2531cee9597d87d2a7
|
4b67c5e6ebdc954f97836b4b7b9c10ab0a9f1df7
|
refs/heads/master
| 2020-06-07T11:47:43.978762 | 2010-11-09T18:31:56 | 2010-11-09T18:31:56 | 187,534 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import numbers
import functools
import copy
import operator
from .ndarray import *
def dot(ndarr, vector):
if not isinstance(ndarr, ndarray) or not isinstance(vector, ndarray):
raise TypeError()
if vector.dimensions != 1:
raise ValueError("Second operand is {0} dimensional - not a vector".format(vector.dimensions))
return sum(ndarr * vector)
class vector:
def __init__(self, size=0, array=None):
'''
Creates a null vector with size coordinates,
or a vector backed by the given array.
'''
if array is not None:
assert(array.dimensions == 1)
assert(array.shape[0] == size or size == 0)
self.array = array
else:
self.array = ndarray((size,))
@functools.wraps(ndarray.__setitem__)
def __setitem__(self, *args):
return self.array.__setitem__(*args)
@functools.wraps(ndarray.__getitem__)
def __getitem__(self, *args):
return self.array.__getitem__(*args)
def __mul__(self, other):
if isinstance(other, vector):
return sum(self.array * other.array)
elif isinstance(other, numbers.Number):
return vector(array=(self.array * other))
else:
raise NotImplementedError()
def __len__(self):
return len(self.array)
class matrix:
def __init__(self, rows=0, columns=0, array=None):
'''
Creates a rows by columns matrix. If columns is 0, creates a square matrix.
The matrix is row-major indexed. You may provide an array to be wrapped, instead of creating a new one.
'''
if array is not None:
assert(array.dimensions == 2)
self.array = array
else:
if columns == 0: columns = rows
self.array = ndarray((columns, rows))
@functools.wraps(ndarray.__setitem__)
def __setitem__(self, *args):
return self.array.__setitem__(*args)
def __getitem__(self, *args):
item = self.array.__getitem__(*args)
if isinstance(item, ndarray):
return vector(array=item)
else:
return item
def __mul__(self, other):
if isinstance(other, matrix):
if self.shape[1] != other.shape[0]:
raise ValueError('Incompatible shapes')
zerovec = array([0] * other.shape[1])
values = array(sum((scalar * row for scalar, row in zip (myrow, other.array)), zerovec) for myrow in self.array)
return matrix(array=values)
elif isinstance(other, vector):
if self.array.shape[0] != len(other):
raise ValueError('Incompatible shapes')
result_array = array(row * other for row in self)
return vector(array=result_array)
else:
raise NotImplementedError()
def __iter__(self):
for i in range(self.shape[0]):
yield self[i]
def __len__(self):
return self.shape[0]
@property
def shape(self):
return self.array.shape
def gaussian_decomposition(square_matrix):
"""
Returns a tuple of matrices (A, B), which have only zeroes above or below the diagonal and
matrix == A * B
The matrix must be square.
"""
if len(square_matrix.shape) != 2 or square_matrix.shape[0] != square_matrix.shape[1]:
raise ValueError('Matrix not square')
size = square_matrix.shape[0]
l = copy.deepcopy(square_matrix.array)
r = identity_matrix(size).array
for i in range(size - 1):
if l[i, i] == 0:
continue
m = l[i, i]
lnorm = l[i] / m
rnorm = array(r[i])
for irow in range(i+1, size):
r[irow] -= l[irow, i] * rnorm
l[irow] -= l[irow, i] * lnorm
return (matrix(array=l), matrix(array=r))
def solve(a, b):
'''
Returns an n-vector x, which is the solution to the linear system
| a * x = b
where a is an n-by-m matrix and b is an m-vector.
a and b can be instances of matrix and vector or ndarray.
returns None if the system doesn't have a solution.
TODO: CURRENTLY DOES NOT SUPPORT THE CASE WHEN n ≠ m
'''
if isinstance(a, matrix):
a = a.array
if isinstance(b, vector):
b = b.array
if len(a.shape) != 2:
raise ValueError('Coefficients argument not two-dimensional.')
if len(b.shape) != 1:
raise ValueError('Result vector argument not one-dimensional.')
if a.shape[0] != b.shape[0]:
raise ValueError('Dimensions mismatch: height of a {0:d} != length of b {1:d}'.format(a.shape[0], b.shape[0]))
if a.shape[0] != a.shape[1]:
raise NotImplementedError()
a = copy.deepcopy(a)
b = copy.deepcopy(b)
for ilead in range(a.shape[1]):
m, im = max((abs(a[i, ilead]), i) for i in range(ilead, a.shape[0]))
m = a[im, ilead]
if im != ilead:
# TODO: Make ndarray act in a way that will make the below easier
tmp = copy.deepcopy(a[im])
a[im] = a[ilead]
a[ilead] = tmp
tmp = copy.deepcopy(b[im])
b[im] = b[ilead]
b[ilead] = tmp
del tmp
if m == 0:
raise NotImplementedError()
a[ilead] /= m
b[ilead] /= m
for irow in range(ilead + 1, a.shape[0]):
if a[irow, ilead] != 0:
b[irow] -= b[ilead] * a[irow, ilead]
a[irow] -= a[ilead] * a[irow, ilead]
x = ndarray(a.shape[1])
for ix in reversed(range(a.shape[0])):
x[ix] = b[ix] - sum(a[ix, i] * x[i] for i in range(ix+1, a.shape[1]))
return x
def determinant(matrix):
"""
Computes the determinant of a matrix.
"""
if len(matrix.shape) != 2 or matrix.shape[0] != matrix.shape[1]:
raise ValueError('Matrix not square')
if matrix.shape[0] == 1:
return matrix[0]
elif matrix.shape[0] == 2:
return matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0]
elif matrix.shape[0] == 3:
return matrix[0, 0] * matrix[1, 1] * matrix[2, 2] +\
matrix[1, 0] * matrix[2, 1] * matrix[0, 2] +\
matrix[2, 0] * matrix[0, 1] * matrix[1, 2] -\
matrix[0, 0] * matrix[2, 1] * matrix[1, 2] -\
matrix[1, 0] * matrix[0, 1] * matrix[2, 2] -\
matrix[2, 0] * matrix[1, 1] * matrix[0, 2]
else:
l, r = gaussian_decomposition(matrix)
return functools.reduce(operator.mul, (l[i, i] * r[i, i] for i in range(matrix.shape[0])))
def identity_matrix(size):
'''
Creates a square identity matrix
'''
m = matrix(size)
for i in range(size):
m[i, i] = 1
return m
|
UTF-8
|
Python
| false | false | 2,010 |
15,693,810,538,689 |
19d372a7d3893688bacfc25985edcb116e4f9d2c
|
f1738cd603e0b2e31143f4ebf7eba403402aecd6
|
/ucs/base/univention-installer/installer/modules/35_dl.py.DISABLED
|
f4e19598a031d214be3f0df0ad982b12f869c6b9
|
[] |
no_license
|
m-narayan/smart
|
https://github.com/m-narayan/smart
|
92f42bf90d7d2b24f61915fac8abab70dd8282bc
|
1a6765deafd8679079b64dcc35f91933d37cf2dd
|
refs/heads/master
| 2016-08-05T17:29:30.847382 | 2013-01-04T04:50:26 | 2013-01-04T04:50:26 | 7,079,786 | 8 | 6 | null | false | 2015-04-29T08:54:12 | 2012-12-09T14:56:27 | 2015-02-22T10:34:03 | 2013-01-04T05:09:25 | 222,839 | 1 | 3 | 32 |
Python
| null | null |
#!/usr/bin/python2.6
# -*- coding: utf-8 -*-
#
# Univention Installer
# installer module: default system language
#
# Copyright 2004-2012 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.
#
# Results of previous modules are placed in self.all_results (dictionary)
# Results of this module need to be stored in the dictionary self.result (variablename:value[,value1,value2])
#
import objects, string, time
from objects import *
from local import _
class object(content):
def checkname(self):
return ['locale_default']
def profile_complete(self):
if self.check('locale_default'):
return False
if self.all_results.has_key('locale_default'):
return True
else:
if self.ignore('locale_default'):
return True
return False
def run_profiled(self):
if self.all_results.has_key('locale_default'):
return {'locale_default': self.all_results['locale_default']}
def __create_selection( self ):
default_value=''
self._locales=self.all_results['locales']
dict={}
if self.all_results.has_key('locale_default'):
default_value=self.all_results['locale_default']
elif hasattr( self, '_locale_default' ):
default_value = self._locale_default
count=0
default_line=0
for i in self._locales.split(" "):
dict[i]=[i, count]
if i == default_value:
default_line = count
count=count+1
self.elements.append(radiobutton(dict,self.minY,self.minX+2,33,10, [default_line])) #3
self.elements[3].current=default_line
def draw( self ):
if hasattr( self, '_locales' ):
self._locale_default = self.elements[ 3 ].result()
del self.elements[ 3 ]
self.__create_selection()
content.draw( self )
def layout(self):
self.elements.append(textline(_('Select your default system language:'),self.minY-1,self.minX+2)) #2
self.__create_selection()
def input(self,key):
if key in [ 10, 32 ] and self.btn_next():
return 'next'
elif key in [ 10, 32 ] and self.btn_back():
return 'prev'
else:
return self.elements[self.current].key_event(key)
def incomplete(self):
if string.join(self.elements[3].result(), ' ').strip(' ') == '':
return _('Please select the default system language')
return 0
def helptext(self):
return _('Default language \n \n Select a default system language.')
def modheader(self):
return _('Default language')
def result(self):
result={}
result['locale_default']=self.elements[3].result()
return result
|
UTF-8
|
Python
| false | false | 2,013 |
15,307,263,454,233 |
450221839f949875cf9912ee79f2f27d3cb99268
|
4824c89fde17b689df24e00c5e553e17dc2e1ae7
|
/main.py
|
39e71c1056b1c1c1245689565060974c7806f14a
|
[] |
no_license
|
h2oboi89/RomanNumerals
|
https://github.com/h2oboi89/RomanNumerals
|
1de6ec344f94ba7f2e5a26fd84735dcdccf2f6b9
|
036f8e42753c42728b3dbff40e71d59f431b65ca
|
refs/heads/master
| 2016-09-01T23:23:48.498050 | 2014-11-23T06:09:04 | 2014-11-23T06:09:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from stack import Stack
from collections import OrderedDict
def main():
print_help()
while True:
raw = input('>')
if raw == QUIT:
break
if raw == HELP:
print_help()
else:
try:
# Decimal -> Roman
print(d_to_r(int(raw)))
except ValueError:
# Roman -> Decimal
val = r_to_d(raw)
if val <= 0:
print('please enter a valid roman numeral')
else:
print(str(val))
QUIT = 'q'
HELP = '?'
NUMERALS = {
'I' : 1,
'V' : 5,
'X' : 10,
'L' : 50,
'C' : 100,
'D' : 500,
'M' : 1000
}
VALUES = OrderedDict(sorted({
1 : 'I',
4 : 'IV',
5 : 'V',
9 : 'IX',
10 : 'X',
40 : 'XL',
50 : 'L',
90 : 'XC',
100 : 'C',
400 : 'CD',
500 : 'D',
900 : 'CM',
1000 : 'M'
}.items()))
def d_to_r(num):
if num <= 0 or num >= 5000:
return ''
out = ''
while num != 0:
d_val = 0
r_val = ''
for k, v in VALUES.items():
if k <= num:
d_val = k
r_val = v
else:
break
num -= d_val
out += r_val
return out
def r_to_d(raw):
# TODO: check for invalid values (IIII, IIX, etc...)
raw = raw.upper()
vals = Stack()
total = 0
for c in raw:
try:
vals.push(NUMERALS[c])
except KeyError:
return -1
if vals.isEmpty():
return 0
val = vals.pop()
total = 0
while not vals.isEmpty():
if val <= vals.peek():
total += val
val = 0
else:
total += (val - vals.pop())
val = 0
if not vals.isEmpty():
val = vals.pop()
total += val
return total
def print_help():
print('Enter roman numeral to convert')
print('Enter \'{0}\' to quit, or \'{1}\' for this help text.'.format(QUIT, HELP))
if __name__ == '__main__':
main()
|
UTF-8
|
Python
| false | false | 2,014 |
10,660,108,847,441 |
055cb2242eb47b898e51273926b412a0db8b5c51
|
676ce7f88c568d411881754fdc94f2d782d617bf
|
/ftw/blog/portlets/archiv.py
|
5b70c098898d8dc47639a93ef9656e645479f6d9
|
[
"GPL-2.0-only"
] |
non_permissive
|
spanish/ftw.blog
|
https://github.com/spanish/ftw.blog
|
668ed4d110da03a2dc3e02c69dc3fc91259f697b
|
6137848a07583e84195e86b22840817d2e2c9ee1
|
refs/heads/master
| 2020-12-01T01:17:10.837164 | 2013-08-22T06:54:22 | 2013-08-22T06:54:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from DateTime import DateTime
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone.utils import base_hasattr
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from ftw.blog.interfaces import IBlogUtils
from plone.app.portlets.portlets import base
from plone.memoize.view import memoize
from plone.portlets.interfaces import IPortletDataProvider
from zope.component import getUtility
from zope.i18n import translate
from zope.interface import implements
from Products.CMFPlone.i18nl10n import monthname_msgid
class IArchivePortlet(IPortletDataProvider):
"""Archive portlet interface.
"""
class Assignment(base.Assignment):
implements(IArchivePortlet)
@property
def title(self):
return "Blog Archive Portlet"
class Renderer(base.Renderer):
def __init__(self, context, request, view, manager, data):
self.context = context
self.data = data
self.request = request
@property
def available(self):
"""Only show the portlet, when the blog isn't empty
"""
if self.archive_summary():
return True
else:
return False
def zLocalizedTime(self, time, long_format=False):
"""Convert time to localized time
"""
month_msgid = monthname_msgid(time.strftime("%m"))
month = translate(month_msgid, domain='plonelocales',
context=self.request)
return u"%s %s" % (month, time.strftime('%Y'))
@memoize
def archive_summary(self):
"""Returns an ordered list of summary infos per month."""
catalog = getToolByName(self.context, 'portal_catalog')
query = {}
blogutils = getUtility(IBlogUtils, name='ftw.blog.utils')
blogroot = blogutils.getBlogRoot(self.context)
if base_hasattr(blogroot, 'getTranslations'):
blogroots = blogroot.getTranslations(review_state=False).values()
root_path = ['/'.join(br.getPhysicalPath()) for br in blogroots]
query['Language'] = 'all'
else:
root_path = '/'.join(blogroot.getPhysicalPath())
query['path'] = root_path
query['portal_type'] = 'BlogEntry'
archive_counts = {}
blog_entries = catalog(**query)
for entry in blog_entries:
year_month = entry.created.strftime('%Y/%m')
if year_month in archive_counts:
archive_counts[year_month] += 1
else:
archive_counts[year_month] = 1
archive_summary = []
ac_keys = archive_counts.keys()
ac_keys.sort(reverse=True)
for year_month in ac_keys:
archive_summary.append(dict(
title=self.zLocalizedTime(DateTime('%s/01' % year_month)),
number=archive_counts[year_month],
url='%s?archiv=%s/01' % (blogroot.absolute_url(), year_month),
))
return archive_summary
render = ViewPageTemplateFile('archiv.pt')
class AddForm(base.NullAddForm):
def create(self):
return Assignment()
|
UTF-8
|
Python
| false | false | 2,013 |
19,095,424,638,021 |
cee75180e728292337d4d65fedac24b419b2a1e3
|
445e45fbe7be35cd510b2c4aca74ca5d5b825453
|
/rango/models.py
|
894ae1192b38476e3591a163def52e76da9523bc
|
[] |
no_license
|
ericjameson/rango-flask
|
https://github.com/ericjameson/rango-flask
|
1d10ab555591dba3af82173e7267060444578a32
|
bab18cb078a3e56c0f2b4a9ec9c21512da53e345
|
refs/heads/master
| 2015-08-09T11:45:26.605873 | 2013-11-13T18:59:01 | 2013-11-13T18:59:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from rango import db
class Category(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128))
views = db.Column(db.Integer)
likes = db.Column(db.Integer)
pages = db.relationship('Page', backref='category',lazy='dynamic')
# def __init__(self, name, views, likes):
# self.name = names
# self.views = views
# self.likes = likes
def __repr__(self):
return self.name
class Page(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(128))
category_name = db.Column(db.Integer, db.ForeignKey('category.name'))
url = db.Column(db.String(128))
views = db.Column(db.Integer)
# def __init__(self, title, category, url, views):
# self.title = title
# self.category = category
# self.url = url
# self.views = views
def __repr__(self):
return self.title
|
UTF-8
|
Python
| false | false | 2,013 |
12,799,002,566,008 |
6dc7d983216e1286abab21376d6704d8b4f1e612
|
59946b9818e259fac60571e3e2204a8ce3b49379
|
/ventilation/views.py
|
0da6029b36b4d6881ef8f6581e518ca7d3a490c4
|
[] |
no_license
|
Se7ge/condition
|
https://github.com/Se7ge/condition
|
dac879a5fa388ecaed4c44805c81622566e99087
|
f9fbd8d120646894d2d77fd6a0e7a18a7bb8288c
|
refs/heads/master
| 2020-05-31T12:39:19.713956 | 2013-11-10T21:38:19 | 2013-11-10T21:38:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
from django.conf import settings
from condition.ventilation.models import Ventilation_Types, Ventilation_Products
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import Template, context, RequestContext
def show_product(request, id):
template_name = 'ventilation/product.html'
return render_to_response(template_name,
{'product': Ventilation_Products.objects.get(pk=int(id)),
},
context_instance=RequestContext(request)
)
def show_type(request, id):
template_name = 'ventilation/type.html'
return render_to_response(template_name,
{'type': Ventilation_Types.objects.get(pk=int(id)),
'products': Ventilation_Products.objects.filter(type_id=int(id)).order_by('-price'),
},
context_instance=RequestContext(request)
)
def search(request):
template_name = 'thermal/search.html'
search = request.POST['search']
type_id = int(request.POST['type_id'])
if type_id:
products = Ventilation_Products.objects.filter(types_id = type_id, name__icontains=search)
else:
products = Ventilation_Products.objects.filter(name__icontains=search)
return render_to_response(template_name,
{'products': products,},
context_instance=RequestContext(request)
)
|
UTF-8
|
Python
| false | false | 2,013 |
2,061,584,317,697 |
65d97f87914231ae564b9d6ebfe3ef90c7901698
|
7e61d51bcb318052a502c02c31fde9763e619455
|
/IPython/nbformat/tests/test_current.py
|
3050e880041aca6f3adef298fc9b095a1cc67379
|
[
"BSD-3-Clause"
] |
permissive
|
pyarnold/ipython
|
https://github.com/pyarnold/ipython
|
e2fbe8592fd37c6f70d895a92e9921e33328d96f
|
c4797f7f069d0a974ddfa1e4251c7550c809dba0
|
refs/heads/master
| 2021-01-21T18:10:36.097876 | 2014-03-19T07:05:50 | 2014-03-19T07:05:50 | 17,895,124 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
"""
Contains tests class for current.py
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from .base import TestsBase
from ..reader import get_version
from ..current import read, current_nbformat
#-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------
class TestCurrent(TestsBase):
def test_read(self):
"""Can older notebooks be opened and automatically converted to the current
nbformat?"""
# Open a version 2 notebook.
with self.fopen(u'test2.ipynb', u'r') as f:
nb = read(f, u'json')
# Check that the notebook was upgraded to the latest version
# automatically.
(major, minor) = get_version(nb)
self.assertEqual(major, current_nbformat)
|
UTF-8
|
Python
| false | false | 2,014 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.