__id__
int64
17.2B
19,722B
blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
133
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
3 values
repo_name
stringlengths
7
73
repo_url
stringlengths
26
92
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
12 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
61.3k
283M
star_events_count
int64
0
47
fork_events_count
int64
0
15
gha_license_id
stringclasses
5 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
82
gha_forks_count
int32
0
25
gha_open_issues_count
int32
0
80
gha_language
stringclasses
5 values
gha_archived
bool
1 class
gha_disabled
bool
1 class
content
stringlengths
19
187k
src_encoding
stringclasses
4 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
year
int64
2k
2.01k
2,594,160,261,700
e1650d8892dc85813a0ba7a1aeab0154aa7cf8b2
64485abd40bfe989aa70d0b1e598fc9160785799
/Final/final_classifier.py
c1fcd5af91aa29634f2c188440c5b3b7c0b6598b
[]
no_license
cassieqiao/text-analytics
https://github.com/cassieqiao/text-analytics
2008e8355d1d277538f414ecceb72c1286bfe098
caf35dee64231ffa7b3d284cea3f04ef4fed758c
refs/heads/master
2021-01-19T09:06:20.043204
2014-12-17T12:23:24
2014-12-17T12:24:32
28,114,238
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on Nov 4, 2014 @author: Cassie ''' from nltk.classify import NaiveBayesClassifier import urllib2 from bs4 import BeautifulSoup import nltk from nltk import ConfusionMatrix from os import listdir def word_feats(words): return dict([(word, True) for word in words.split() ]) clovids = [u'above',u'absorbed',u'act',u'adjusts', u'admiringly',u'age', u'ago', u'alacrity', u'anywhere', u'applies', u'approaches', u'attention', u'bearing', u'beast', u'beauty', u'becomes', u'best', u'between', u'bicycles', u'bled', u'bonnyonce', u'boots', u'briskly', u'burying', u'catheter', u'cell', u'changes', u'christ',u'climbed', u'coffins'] hammids = [u'aah',u'abandon', u'absent', u'absently', u'accepting', u'accursed',u'afraid', u'ages', u'agitated', u'agree', u'air', u'alive',u'alivea', u'alone',u'already', u'among', u'anenometer', u'anger',u'animated', u'anxious', u'ape',u'aperture',u'apologies',u'appalled', u'appears',u'ardour', u'aren', u'armrests', u'arms', u'arses'] monoids = [u'armchair', u'ashbins', u'ashbins.center', u'bare', u'blood', u'covered', u'covering', u'curtains', u'drawn.front', u'draws', u'face.brief', u'hamm.motionless', u'hanging', u'interior.grey', u'large', u'light.left', u'picture.front', u'socks',u'staggering', u'stained', u'tableau.clov', u'thick', u'touching', u'windows',u'arm', u'castors',u'curtain', u'dressing', u'example', u'folds'] naggids= [u'art', u'ballockses', u'balls', u'blowing', u'bluebells', u'breaks',u'buttonholes',u'capable', u'capsized', u'cautiously', u'changed', u'cheer', u'chuckles', u'clasping', u'closing', u'crashed', u'crotch', u'customer', u'dear', u'delight', u'disdainful',u'disgustedly', u'dreadfully', u'drowned', u'earshot', u'englishman',u'excuse', u'fail',u'failed', u'fetches'] nellids = [u'accurate', u'afternoon', u'april', u'ardennes', u'bottom',u'clean', u'como', u'elegiac', u'felt', u'funnier', u'lake',u'most', u'mustn', u'often', u'perished',u'pet',u'quite', u'rowing', u'rub', u'unhappiness', u'warily', u'because', u'beginning',u'comical', u'deep', u'desert', u'engaged', u'farce', u'funny', u'grant'] clov_feats = [(word_feats(f), 'Clov') for f in clovids ] hamm_feats = [(word_feats(f), 'Hamm') for f in hammids ] mono_feats = [(word_feats(f), 'Monologue') for f in monoids ] nagg_feats = [(word_feats(f), 'Nagg') for f in naggids ] nell_feats = [(word_feats(f), 'Nell') for f in nellids ] trainfeats = clov_feats + hamm_feats + mono_feats+nagg_feats+nell_feats classi = NaiveBayesClassifier.train(trainfeats) files = ["Clov","Hamm","Monologue","Nagg","Nell"] ref = "" tagged = "" index = 0 for file in listdir("C:\Users\Cassie\Google Drive\MSiA\Fall 2014\MSiA 490\hw\characters"): path = 'C:\Users\Cassie\Google Drive\MSiA\Fall 2014\MSiA 490\hw\characters' filepath = path + '\\' + file with open (filepath, "r") as myfile: index +=1 for line in myfile: ref = ref + ',' + files[index-1] tag = classi.classify(word_feats(line)) tagged = tagged + ',' + tag print ConfusionMatrix(ref.split(',')[1:], tagged.split(',')[1:]) ''' soup = BeautifulSoup(open("wiki.html")) tables = soup.findAll("table", { "class" : "wikitable sortable" }) ref = "" tagged = "" continents = ["Africa","Asia","Europe","North America","South America","Oceania","Antrctica"] index = 0 for table in tables: index +=1 for row in table.findAll('tr'): cells = row.findAll("td") if len(cells) == 5: if cells[2].find('a',text=True) is not None: b = cells[2].find('a',text=True) cityname = b['title'] citylink = 'http://en.wikipedia.org'+b['href'] try: cityt = wikipedia.page(citylink).content except: cityt = None else: cityname = u"Null" cityt = None if cityt is not None: ref = ref + ',' + continents[index-1] tag = classi.classify(word_feats(cityt)) tagged = tagged + ',' + tag print ConfusionMatrix(ref.split(','), tagged.split(',')) chengdut =wikipedia.page("http://en.wikipedia.org/wiki/Chengdu").content pdist = classi.prob_classify(word_feats(chengdut)) print (pdist.prob('Asia'), pdist.prob("Africa"), pdist.prob("North America"), pdist.prob("South America"), pdist.prob("Europe"),pdist.prob("Oceania"),pdist.prob("Antarctica")) '''
UTF-8
Python
false
false
2,014
18,468,359,390,821
7d976545afc295a0874b9b5b9dfc9d6cf2762fe4
944f5df864a98f2d084ac6162c0dd9ed98078b59
/problem15.py
0c243e399b78b29c0f1dc44f09d21dc8d0a1ccc5
[ "Unlicense" ]
permissive
mohitsoni/python-euler
https://github.com/mohitsoni/python-euler
dd4ab11828536972d5b0812f35c60a036141ea18
8ee0a799bdad4c052d76b1abf1fff8d27177377e
refs/heads/master
2021-01-19T18:02:37.207252
2013-08-14T21:07:13
2013-08-14T21:07:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python ''' For a mxn grid, number of paths equals: (m+n)C(m) ''' m = 2 n = 2 grid = [[0 for j in range(n+1)] for i in range(m+1)] def printGrid(grid): for row in grid: print row print def countPaths(grid, i, j, val): printGrid(grid) grid[i][j] += val # Go right if j+1 < len(grid): countPaths(grid, i, j+1, grid[i][j]) # Go down if i+1 < len(grid): countPaths(grid, i+1, j, grid[i][j]) def countPathsI(grid): i, j = 0, 0 val = 1 while True: grid[i][j] += val # Go right grid[i+1][j] += grid[i][j] # Go down grid[i][j+1] += grid[i][j] i = i+1 j = j+1 printGrid(grid) print countPaths(grid,0,0,1)
UTF-8
Python
false
false
2,013
19,241,453,505,525
c4c9cbd0f65bb7a508552bded7240bf25fc1d6e3
1dcaff791a7dab3a76079b7bd8a19e1bf9f255ba
/betabeard/BetaBeard.py
3e421af24838ddaca7fa83c53e020f951139a8b2
[ "MIT" ]
permissive
TuRz4m/BetaBeard
https://github.com/TuRz4m/BetaBeard
99c56452956231d9aaa41c13c5cca5052713864f
d65ae0f2c39af1b01325fa025207fefc42cf8dc1
refs/heads/master
2020-04-23T08:01:22.347142
2014-01-02T13:45:49
2014-01-02T13:45:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on 10 dec. 2013 @author: TuRz4m ''' import ConfigParser import logging import sys from api.APIUtils import BetaSerieAPI, BadLoginException, SickBeardAPI import os.path logger = logging.getLogger(__name__) logging.getLogger(__name__).setLevel(logging.INFO) logging.getLogger(__name__).addHandler(logging.StreamHandler()) logging.getLogger(__name__).addHandler(logging.FileHandler("logs/BetaBeard.log")) configFile = "BetaBeard.ini" configDbFile = "BetaBeard.db" param = {} paramDb = {} """ Load the config file & fill all the var. """ def checkConfig(config): try: global param param['login'] = config.get("BetaSeries", "login") param['password'] = config.get("BetaSeries", "password") param['sburl'] = config.get("SickBeard", "url") if (config.getboolean("SickBeard", "https")): param['scheme'] = "https" param['apikey'] = config.get("SickBeard", "apikey") param['location'] = config.get("SickBeard", "location") if (param['location'] == ""): param['location'] = None param['lang'] = config.get("SickBeard", "lang") if (param['lang'] == ""): param['lang'] = None param['flatten_folder'] = config.get("SickBeard", "flatten_folder") if (param['flatten_folder'] == ""): param['flatten_folder'] = None param['status'] = config.get("SickBeard", "status") if (param['status'] == ""): param['status'] = None param['initial'] = config.get("SickBeard", "initial") if (param['initial'] == ""): param['initial'] = None param['archive'] = config.get("SickBeard", "archive") if (param['archive'] == ""): param['archive'] = None param['fullUpdate'] = config.getboolean("BetaBeard", "fullUpdate") param['checkTimeLine'] = config.getboolean("BetaBeard", "checkTimeLine") param['demoMode'] = config.getboolean("BetaBeard", "demoMode") except ConfigParser.NoOptionError as ex: logger.error("[BetaBeard] Error in config file : %s", ex) return False except ConfigParser.NoSectionError as ex: logger.error("[BetaBeard] Error in config file : %s", ex) return False return True def loadDb(configToLoad): global paramDb if (os.path.exists(configDbFile)): configToLoad.read(configDbFile) try: paramDb['last_event_id'] = configToLoad.get("BetaBeard", "last_event_id") if (paramDb['last_event_id'] == ""): paramDb['last_event_id'] = None except ConfigParser.NoOptionError: logger.debug("[BetaBeard] Config file Tech not found. Use default.") paramDb['last_event_id'] = None except ConfigParser.NoSectionError: logger.debug("[BetaBeard] Config file Tech not found. Use default.") configToLoad.add_section("BetaBeard") paramDb['last_event_id'] = None """ Update the BetaBeard-tech.ini """ def updateDb(configToSave): logger.debug("[BetaBeard] Update file %s", configDbFile) cfgfile = open(configDbFile,'w') configToSave.write(cfgfile) cfgfile.close() logger.debug("[BetaBeard] File %s updated.", configDbFile) if __name__ == '__main__': # First of all, we need to reed the BetaBeard.ini config file. config = ConfigParser.SafeConfigParser() configDb = ConfigParser.SafeConfigParser() if (os.path.exists(configFile) == False): logger.error("[BetaBeard] Config file %s not found.", configFile) sys.exit(0) config.read(configFile) loadDb(configDb) if checkConfig(config) == False: sys.exit(0) # ----------- Init BetaSeries ----------- # try: beta = BetaSerieAPI(param['login'], param['password']) except BadLoginException as ex: logger.error("[BetaBeard] can't log into BetaSeries.com : %s", ex.value) sys.exit(0) logger.info("[BetaBeard] Login successfull.") # ----------- Init SickBeard ----------- # sickBeard = SickBeardAPI(param['sburl'], param['scheme'], param['apikey']) # ----------- Test SickBeard ----------- # if (sickBeard.ping() == False): logger.error("[BetaBeard] Can't ping SickBeard on url : %s://%s with apikey = %s",param['scheme'], param['sburl'], param['apikey']) sys.exit(0) logger.info("[BetaBeard] Ping SickBeard successfull.") # ----------- If fullUpdate, we retrieve all the current show and add them to sickbear.----------- # if paramDb['last_event_id'] == None: logger.debug("[BetaBeard] last_index_id is None") if param['fullUpdate'] == True: shows = beta.show_list(); logger.debug("[BetaBeard] shows : %s", shows) logger.info("[BetaBeard] Start processing shows.") for show in shows: logger.info("[BetaBeard] Add show in SickBeard : %s (%s)", show[1], show[0]) if (param['demoMode'] == False): success,message = sickBeard.add_show(show[0], param['location'], param['lang'], param['flatten_folder'], param['status'], param['initial'], param['archive']) if (success == False): logger.error("[BetaBeard] Can't add show %s (%s) to sickbeard : %s", show[1], show[0], message) # ----------- retrieve last event processed in betaseries----------- # param['last_event_id'], emptyList = beta.timeline_since(None) elif param['checkTimeLine']: logger.info("[BetaBeard] Start processing timeline.") param['last_event_id'], events = beta.timeline_since(paramDb['last_event_id']) logger.debug("[BetaBeard] Processing timeline : %s", events) if (events != None): for event in events: logger.debug("[BetaBeard] Event : %s", event) # - ADD SERIE - # if (event['type'] == 'add_serie'): betaid = str(event['ref_id']); tvdbid, title = beta.shows_tvdbid(betaid) logger.info("[BetaBeard] Add Show to sickbeard : %s (%s)", title, tvdbid) if (param['demoMode'] == False): success,message = sickBeard.add_show(tvdbid, param['location'], param['lang'], param['flatten_folder'], param['status'], param['initial'], param['archive']) if (success == False): logger.error("[BetaBeard] Can't add show %s (%s) to sickbeard : %s.", title, tvdbid, message) # - DELETE SERIE - # elif (event['type'] == 'del_serie'): betaid = str(event['ref_id']); tvdbid, title = beta.shows_tvdbid(betaid) logger.info("[BetaBeard] Delete Show from sickbeard : %s (%s)", title, tvdbid) if (param['demoMode'] == False): success, message = sickBeard.del_show(tvdbid) if (success == False): logger.error("[BetaBeard] Can't delete show %s (%s) from sickbeard : %s.", title, tvdbid, message) # - PAUSE SERIE - # elif (event['type'] == 'archive'): betaid = str(event['ref_id']); tvdbid, title = beta.shows_tvdbid(betaid) logger.info("[BetaBeard] Archive Show on sickbeard : %s (%s)", title, tvdbid) if (param['demoMode'] == False): success, message = sickBeard.pause_show(tvdbid, 1) if (success == False): logger.error("[BetaBeard] Can't pause show %s (%s) on sickbeard : %s.", title, tvdbid, message) # - UNPAUSE SERIE - # elif (event['type'] == 'unarchive'): betaid = str(event['ref_id']); tvdbid, title = beta.shows_tvdbid(betaid) logger.info("[BetaBeard] UnArchive Show on sickbeard : %s (%s)", title, tvdbid) if (param['demoMode'] == False): success, message = sickBeard.pause_show(tvdbid, 0) if (success == False): logger.error("[BetaBeard] Can't unpause show %s (%s) on sickbeard : %s.", title, tvdbid, message) logger.info("[BetaBeard] Timeline processing done.") # ----------- Update Last_event_id in config file.----------- # if (param['last_event_id'] != None): logger.debug("[BetaBeard] update config with last_event_id=%s", param['last_event_id']) configDb.set("BetaBeard", "last_event_id", str(param['last_event_id'])); updateDb(configDb); else: logger.debug("[BetaBeard] Can't update config file because last_event_id is null")
UTF-8
Python
false
false
2,014
14,877,766,750,569
e8d8f3d33f5515c9d2b54adaee3448390c33a11d
8dedd4614dc0a0a48fad89258efaa7083c2893e7
/admin.py
e47d28cc231ea31e44799ccf2b0a98c86538712e
[]
no_license
abacuspix/rulemaker
https://github.com/abacuspix/rulemaker
1fa6acfc3951a35114b76a0f5d6d7ec072f0bd84
809f25d7585da19ae2094b1da617e6e965a02836
refs/heads/master
2020-08-03T03:43:44.329050
2014-04-04T15:24:51
2014-04-04T15:24:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.contrib import admin from rulemaker.models import * # Register your models here. admin.site.register(Firewall) admin.site.register(Zone) admin.site.register(ExcludeZone) admin.site.register(Policy) admin.site.register(Address) admin.site.register(AddressSet) admin.site.register(Application) admin.site.register(ApplicationPort) admin.site.register(ApplicationSet)
UTF-8
Python
false
false
2,014
687,194,795,934
ca6515c8eb3418681da14e1582632bee7e30c88a
90697e95e7a102f9052370fc8a4fc6cae0be33d7
/parser.py
26650d05e05bd805d1e8bb009939bd89ba100184
[]
no_license
gcali/drisc
https://github.com/gcali/drisc
70af080d803752f0eb2fb5c5c41faa4012ccc21e
50b8adffecfa9167feede75d7b10d18c1c8dfc10
refs/heads/master
2020-03-29T22:46:41.105156
2014-05-09T07:17:38
2014-05-09T07:17:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! /usr/bin/env python3 from lex import Token from transl import Statement, Arg from lex import tokenize from table import SymbolTable from misc import str_list class ParsingError(Exception): pass def _create_parse_error(line_number:int, message:str, token:str)\ -> ParsingError: return ParsingError("(ParseError) l{}: {}\nToken: {}".format( line_number, message, token )) def _create_parse_warning(line_number:int, message:str) -> str: return "(ParseWarning) l{}: {}".format(line_number, message) def parse_tokenlist(token_list:"list(token)")\ -> ("list(statements)","list(str)"): """Parse a list of tokens Returns a tuple: the first element is the list of parsed statements, the second one is a list of warnings found during compilation """ curr_statement = Statement() statement_list = [] warnings_list = [] label_table = dict() is_in_args = False next_is_semicolon = False next_is_colon = False for t in token_list: if next_is_semicolon and t.token_value != ";": raise _create_parse_error(t.line_number, "; expected", t.token_value) elif next_is_colon and t.token_value != ":": raise _create_parse_error(t.line_number, ": expected", t.token_value) elif t.token_name == "label": if not is_in_args and not curr_statement.is_new(): raise _create_parse_error(t.line_number, "Label must be at start of "+ "instruction or in args", t.token_value) elif not is_in_args: curr_statement.label = t.token_value next_is_colon = True else: curr_statement.args.append(Arg(t.token_value, is_register=False, is_label=True)) next_is_semicolon = True elif t.token_name == "operator": if is_in_args: raise _create_parse_error(t.line_number, "operator given when arguments "+ "were expected", t.token_value) else: curr_statement.op = t.token_value is_in_args = True elif t.token_name == "identifier": if not is_in_args: raise _create_parse_error(t.line_number, "identifier not expected", t.token_value) else: curr_statement.args.append(Arg(t.token_value, is_register=True, is_label=False)) elif t.token_name == "constant": if not is_in_args: raise _create_parse_error(t.line_number, "constant not expected", t.token_value) else: curr_statement.args.append(Arg(t.token_value, is_register=False, is_label=False)) elif t.token_name == "keyword" and t.token_value == ":": if not next_is_colon: raise _create_parse_error(t.line_number, "colon expected", t.token_value) else: next_is_colon = False elif t.token_name == "keyword" and t.token_value == ";": curr_statement.line_number = t.line_number statement_list.append(curr_statement) if not curr_statement.op: warnings_list.append(_create_parse_warning( t.line_number, "empty statement" )) curr_statement = Statement() next_is_semicolon = False is_in_args = False if not curr_statement.is_new(): warnings_list.append(_create_parse_warning( -1, "last statement not empty" )) return (statement_list,warnings_list) if __name__ == '__main__': text="LOOP: ADD 12 3 R0;\n" +\ " ADD 5 R0 R1;\n" +\ " GOTO LOOP;;\n" print("Program:") print(text) token_list = tokenize(text, SymbolTable()) s,w = parse_tokenlist(token_list) print("Parsed:") for l in s: print(l) print("Warnings:") for l in w: print(l)
UTF-8
Python
false
false
2,014
16,569,983,868,150
7cf5f88ae7491f020661818a72d918fd1b0141f2
39d063599ea39201ca2ac62c21123c98261544fb
/core/admin.py
460d78ef0dcdb4a7a9a7a81ca802434c21f49bc0
[ "WTFPL" ]
permissive
joaodubas/wttd4
https://github.com/joaodubas/wttd4
477b68fdaff871645888a875e2c499e093e7d616
279a63137506dee5d9f6e1f73af9a57da2fcfbbf
refs/heads/master
2021-01-16T20:34:15.713981
2011-09-13T10:52:40
2011-09-13T10:52:40
2,205,124
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- encoding: utf-8 -*- from django.contrib import admin from django.utils.translation import ugettext as _ from django.core.urlresolvers import reverse from core.models import Speaker, Contact, Talk, Course from multimedia.admin import MediaTabularInline class ContactTabularInline(admin.TabularInline): model = Contact extras = 1 class SpeakerAdmin(admin.ModelAdmin): list_display = ('name', 'url', 'telephone', 'email', 'fax', ) search_fields = ('name', 'contact_set__value', ) prepopulated_fields = {'slug': ('name', )} inlines = (ContactTabularInline, ) def _contact(self, obj, kind): try: return obj.contact_set.filter(kind=kind)[:1][0].value except (Contact.DoesNotExist, IndexError): return '-' def telephone(self, obj): return self._contact(obj, 'P') telephone.short_description = _(u'Telefone') def email(self, obj): return self._contact(obj, 'E') email.short_description = _(u'E-mail') def fax(self, obj): return self._contact(obj, 'F') fax.short_description = _(u'Fax') class TalkAdmin(admin.ModelAdmin): list_display = ('title', 'start_time', 'list_speakers', ) inlines = (MediaTabularInline, ) def list_speakers(self, obj): if not obj.speakers.all().count(): return '<strong>&emdash;</strong>' to_speaker = '<a href="%s">%s</a>' speakers = [to_speaker % (reverse('admin:core_speaker_change', args=[speaker.pk]), speaker.name) for speaker in obj.speakers.all()] return ', '.join(speakers) list_speakers.short_description = _(u'Palestrantes') list_speakers.allow_tags = True class CourseAdmin(TalkAdmin): list_display = TalkAdmin.list_display + ('slots', ) admin.site.register(Speaker, SpeakerAdmin) admin.site.register(Talk, TalkAdmin) admin.site.register(Course, CourseAdmin)
UTF-8
Python
false
false
2,011
8,169,027,807,532
356ef27638147f7e0682958f83037575598114d3
7625367f96e681eb15a5c8d33a679c856765b200
/server_src/modules/corpus.py
618a016d3102acc9b4c11cecc716b49e6ea9a99b
[ "BSD-3-Clause" ]
permissive
jyt109/termite-data-server
https://github.com/jyt109/termite-data-server
2947ce48570226924660cbf9f3f1410e26bed7e8
9cf81b22f13954a0acff2d76ec3096a42d0d2963
refs/heads/master
2021-01-24T04:34:54.427048
2014-02-18T19:48:48
2014-02-18T19:48:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import os import json class Corpus: def __init__( self, request ): self.request = request self.params = self.GetParams() def GetParams( self ): def GetNonNegativeInteger( key, defaultValue ): try: n = int( self.request.vars[ key ] ) if n >= 0: return n else: return 0 except: return defaultValue def GetString( key, defaultValue ): if key in self.request.vars: return self.request.vars[ key ] else: return defaultValue params = { 'searchLimit' : GetNonNegativeInteger( 'searchLimit', 100 ), 'searchOffset' : GetNonNegativeInteger( 'searchOffset', 0 ), 'searchText' : GetString( 'searchText', '' ), 'searchOrdering' : GetString( 'searchOrdering', '' ), 'termLimit' : GetNonNegativeInteger( 'termLimit', 100 ), 'termOffset' : GetNonNegativeInteger( 'termOffset', 0 ) } return params def GetDocMeta( self, params = None ): if params is None: params = self.params searchText = params["searchText"] searchLimit = params["searchLimit"] searchOffset = params["searchOffset"] filename = os.path.join( self.request.folder, 'data/corpus', 'doc-meta.json' ) with open( filename ) as f: content = json.load( f, encoding = 'utf-8' )['data'] results = {} matchCount = 0 keys = sorted(content.keys()) for index in range(len(keys)): obj = content[keys[index]] docContent = obj["DocContent"] if searchText in docContent: matchCount += 1 if len(results) < searchLimit and index >= searchOffset: results[obj["DocID"]] = obj return { "Documents" : results, "docCount" : len(results), "docMaxCount" : matchCount } def GetTermFreqs( self, params = None ): if params is None: params = self.params termLimit = params['termLimit'] termOffset = params['termOffset'] filename = os.path.join( self.request.folder, 'data/corpus', 'term-freqs.json' ) with open( filename ) as f: allTermFreqs = json.load( f, encoding = 'utf-8' ) allTerms = sorted( allTermFreqs.keys(), key = lambda x : -allTermFreqs[x] ) terms = allTerms[termOffset:termOffset+termLimit] termFreqs = { term : allTermFreqs[term] for term in terms if term in allTermFreqs } return termFreqs def GetTermCoFreqs( self, params = None ): if params is None: params = self.params termLimit = params['termLimit'] termOffset = params['termOffset'] filename = os.path.join( self.request.folder, 'data/corpus', 'term-freqs.json' ) with open( filename ) as f: allTermFreqs = json.load( f, encoding = 'utf-8' ) allTerms = sorted( allTermFreqs.keys(), key = lambda x : -allTermFreqs[x] ) terms = allTerms[termOffset:termOffset+termLimit] filename = os.path.join( self.request.folder, 'data/corpus', 'term-co-freqs.json' ) with open( filename ) as f: allTermCoFreqs = json.load( f, encoding = 'utf-8' ) termCoFreqs = { term : allTermCoFreqs[term] for term in terms if term in allTermCoFreqs } for term, termFreqs in termCoFreqs.iteritems(): termCoFreqs[ term ] = { t : termFreqs[t] for t in terms if t in termFreqs } return termCoFreqs
UTF-8
Python
false
false
2,014
9,938,554,368,246
013529288ba1bb07d030adfa990f5c5a2a31c11e
d76e5507194e39fd237e78d19426895e5506f745
/polls/dbindexes.py
85dbb930a03c39a021f28533f00de7c443280b14
[]
no_license
stepturn/stepturn44
https://github.com/stepturn/stepturn44
a87176273ec21f2c61d80409221aecb01428d7c6
c648bbd2b56d4070207e5e436d8cddc87f0ddd28
refs/heads/master
2021-03-12T23:25:57.189245
2011-09-06T23:29:38
2011-09-06T23:29:38
2,338,027
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from .models import Choice from dbindexer.api import register_index register_index(Choice, { 'poll__pub_date': 'year', })
UTF-8
Python
false
false
2,011
4,355,096,851,328
aa45035f36c5d41fce1d7b4c9af55e20048986bd
2f137b21eca9dfca22026e9326b06534b3c5d0e6
/googlesafebrowsing/hashprefix_trie.py
b76340200cc92a3d586febc9c3ac0f9f571650e4
[ "Apache-2.0" ]
permissive
lig/google-safe-browsing
https://github.com/lig/google-safe-browsing
afad6ab509cac9cd4bfacde737d5d9f21139a9dc
fe8b42b3579a9a38c8c19e0295e4e269296e61a8
refs/heads/master
2020-05-29T23:17:34.098193
2010-12-12T17:01:29
2010-12-12T17:01:29
1,160,908
8
1
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # # Copyright 2010 Google 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. """Simple trie implementation that is used by the SB client.""" import itertools class HashprefixTrie(object): """Trie that maps hash prefixes to a list of values.""" # Prefixes shorter than this will not be stored in the HashprefixTrie for # performance reasons. Insertion, Lookup and Deletion will fail on prefixes # shorter than this value. MIN_PREFIX_LEN = 4 class Node(object): """Represents a node in the trie. Holds a list of values and a dict that maps char -> Node. """ __slots__ = ('values', 'children', 'parent') def __init__(self, parent=None): self.values = [] self.children = {} # Maps char -> HashprefixTrie.Node self.parent = parent def __init__(self): self._root = HashprefixTrie.Node() self._size = 0 # Number of hash prefixes in the trie. def _GetPrefixComponents(self, hashprefix): # For performance reasons we will not store any prefixes that are shorter # than 4B. The SafeBrowsing protocol will most probably never serve # prefixes shorter than 4B because it would lead to a high number of # collisions. assert(len(hashprefix) >= HashprefixTrie.MIN_PREFIX_LEN) # Collapse the first 4B together to reduce the number of nodes we have to # store in memory. yield hashprefix[:HashprefixTrie.MIN_PREFIX_LEN] for char in hashprefix[HashprefixTrie.MIN_PREFIX_LEN:]: yield char def _GetNode(self, hashprefix, create_if_necessary=False): """Returns the trie node that will contain hashprefix. If create_if_necessary is True this method will create the necessary trie nodes to store hashprefix in the trie. """ node = self._root for char in self._GetPrefixComponents(hashprefix): if char in node.children: node = node.children[char] elif create_if_necessary: node = node.children.setdefault(char, HashprefixTrie.Node(node)) else: return None return node def Insert(self, hashprefix, entry): """Insert entry with a given hash prefix.""" self._GetNode(hashprefix, True).values.append(entry) self._size += 1 def Delete(self, hashprefix, entry): """Delete a given entry with hash prefix.""" node = self._GetNode(hashprefix) if node and entry in node.values: node.values.remove(entry) self._size -= 1 # recursively delete parent nodes if necessary. while not node.values and not node.children and node.parent: node = node.parent if len(hashprefix) == HashprefixTrie.MIN_PREFIX_LEN: del node.children[hashprefix] break char, hashprefix = hashprefix[-1], hashprefix[:-1] del node.children[char] def Size(self): """Returns the number of values stored in the trie.""" return self._size; def GetPrefixMatches(self, fullhash): """Yields all values that have a prefix of the given fullhash.""" node = self._root for char in self._GetPrefixComponents(fullhash): node = node.children.get(char, None) if not node: break for value in node.values: yield value def PrefixIterator(self): """Iterator over all the hash prefixes that have values.""" stack = [('', self._root)] while stack: hashprefix, node = stack.pop() if node.values: yield hashprefix for char, child in node.children.iteritems(): stack.append((hashprefix + char, child))
UTF-8
Python
false
false
2,010
11,630,771,441,507
1062b64607244d8ff147850aceabab7cf35a22fc
76c10c9895ec0f4ba8463635c4c78edc79e86def
/image_manager/views.py
b7c755f6111af576a7c96fa0a303c60813d966c3
[]
no_license
Garrocho/django-image-manager
https://github.com/Garrocho/django-image-manager
19ee23f54571679433144ad22180b27bb7ca3eac
ca165d215af076bb2085f43a0c15eefd31d31a69
refs/heads/master
2021-01-18T08:43:07.182178
2013-08-26T12:09:05
2013-08-26T12:09:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # @author: Charles Tim Batista Garrocho # @contact: charles.garrocho@gmail.com # @copyright: (C) 2013 Python Software Open Source """ This is the module of the application views. """ from django.http import HttpResponse from django.utils import simplejson from django.conf import settings import manager import mimetypes def add(request): ''' calls the methods of the package manager (records an image) and returns True or False to the end of the process. ''' response, parameters = validate_request(request) if response.status_code == 204: if 'file' in request.FILES: if manager.add(request.FILES['file'], parameters['address'], parameters['name']): response.status_code = 200 return response def load(request): ''' calls the methods of the package manager (loads an image) and returns File or None to the end of the process. ''' response, parameters = validate_request(request) if response.status_code == 204: image = manager.load(parameters['address'], parameters['name']) if image is not None: mimetype, encoding = mimetypes.guess_type(image) response = HttpResponse(mimetype=mimetype) response['Content-Disposition'] = 'attachment; filename=%s' % parameters['name'] response.write(image) response.status_code = 200 return response def list(request): ''' calls the methods of the package manager (several images in the folder list) and returns List Names Images to the end of the process. ''' response, parameters = validate_request(request) if response.status_code == 204: lista_img = manager.list(parameters['address'], parameters['name']) if len(lista_img) > 0: response = HttpResponse(simplejson.dumps({'images': lista_img}), mimetype='application/json') response.encoding = 'utf-8' response.status_code = 200 return response def delete(request): ''' calls the methods of the package manager (delete an image) and returns File or None to the end of the process. ''' response, parameters = validate_request(request) if response.status_code == 204: if manager.delete(parameters['address'], parameters['name']): response.status_code = 200 return response def validate_request(request): ''' validates the parameters passed by post or get method. ''' response = HttpResponse() response.status_code = 204 parameters = None if request.method == settings.MANAGER_IMAGES_METHOD: if request.method == 'POST': if 'address' in request.POST and 'name' in request.POST: parameters = {'address':request.POST['address'], 'name':request.POST['name']} else: response.status_code = 401 else: if 'address' in request.GET and 'name' in request.GET: parameters = {'address':request.GET['address'], 'name':request.GET['name']} else: response.status_code = 401 else: response.status_code = 405 return response, parameters
UTF-8
Python
false
false
2,013
4,904,852,685,732
ed0112b467594725a7dd56ea7cc0c5c368d73237
3d19e1a316de4d6d96471c64332fff7acfaf1308
/Users/S/sensi/german_bundestag_members_plus.py
fe4d0977967730f19241f595474534043b989d36
[]
no_license
BerilBBJ/scraperwiki-scraper-vault
https://github.com/BerilBBJ/scraperwiki-scraper-vault
4e98837ac3b1cc3a3edb01b8954ed00f341c8fcc
65ea6a943cc348a9caf3782b900b36446f7e137d
refs/heads/master
2021-12-02T23:55:58.481210
2013-09-30T17:02:59
2013-09-30T17:02:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import scraperwiki import re from BeautifulSoup import BeautifulSoup html = scraperwiki.scrape('http://www.bundestag.de/bundestag/abgeordnete17/alphabet/index.html') #print html soup = BeautifulSoup(html) # turn our HTML into a BeautifulSoup object rows = soup.findAll(attrs={'class': 'linkIntern'}) #print rows def normalise_party(s): """delete trailing punctuation from party string""" s = re.sub('[\.\*\)\+]+$', '', s) return s for row in rows: person = {} details = row.text spl = details.split(",") lastpart = spl[2] person['LastName'] = spl[0].strip() person['FirstName'] = spl[1].strip() person['Party'] = normalise_party(spl[2].strip()) url = row.a['href'].replace("..", "") person['URL'] = "http://www.bundestag.de/bundestag/abgeordnete17" + url person['Comment'] = '' if re.search('\+', lastpart) is not None: person['Comment'] = 'DECEASED' elif re.search('\*', lastpart) is not None: person['Comment'] = 'RESIGNED' scraperwiki.datastore.save(['URL'], person) import scraperwiki import re from BeautifulSoup import BeautifulSoup html = scraperwiki.scrape('http://www.bundestag.de/bundestag/abgeordnete17/alphabet/index.html') #print html soup = BeautifulSoup(html) # turn our HTML into a BeautifulSoup object rows = soup.findAll(attrs={'class': 'linkIntern'}) #print rows def normalise_party(s): """delete trailing punctuation from party string""" s = re.sub('[\.\*\)\+]+$', '', s) return s for row in rows: person = {} details = row.text spl = details.split(",") lastpart = spl[2] person['LastName'] = spl[0].strip() person['FirstName'] = spl[1].strip() person['Party'] = normalise_party(spl[2].strip()) url = row.a['href'].replace("..", "") person['URL'] = "http://www.bundestag.de/bundestag/abgeordnete17" + url person['Comment'] = '' if re.search('\+', lastpart) is not None: person['Comment'] = 'DECEASED' elif re.search('\*', lastpart) is not None: person['Comment'] = 'RESIGNED' scraperwiki.datastore.save(['URL'], person)
UTF-8
Python
false
false
2,013
17,927,193,528,749
73f746ab2c738bf3ab7058d451db60cca7c64e35
d2903dc7d83c0d2af755721f57d4092d9a10becb
/invitation/management/__init__.py
0b79e03d4c45c54193c0d27cfc1a4b7a4ec4686e
[ "BSD-3-Clause" ]
permissive
devnieL/django-inviting
https://github.com/devnieL/django-inviting
7f9a12535f2433244f4da694af5bc3f50f1fc88a
b29c826bdd34ff4b5c03f927af6239b05821fd4a
refs/heads/master
2020-12-24T22:59:19.902424
2013-08-15T14:01:14
2013-08-15T14:01:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db.models.signals import post_syncdb from invitation.compat import AUTH_USER_MODEL, get_user_model from invitation import models def create_stats_for_existing_users(sender, **kwargs): """ Create `InvitationStats` objects for all users after a `sycndb` """ count = 0 for user in get_user_model().objects.filter(invitation_stats__isnull=True): models.InvitationStats.objects.create(user=user) count += 1 if count > 0: print "Created InvitationStats for %s existing Users" % count post_syncdb.connect(create_stats_for_existing_users, sender=models)
UTF-8
Python
false
false
2,013
1,408,749,298,886
36c868ef5af1d41766a61728990a4a5d2f12dbd4
5edfb5896dbdebf1ccb9bc838e3796cb8c22e8df
/tempest/api/compute/test_auth_token.py
ffeede8afdb6593edfc2dcc950992f387f707f30
[ "Apache-2.0" ]
permissive
arbylee/tempest
https://github.com/arbylee/tempest
a7c2646c5a235d13877df04dc7ff58bf1c577cf4
14b75e861fd7d18aa2f5365e4553393cba93cb3a
refs/heads/master
2021-01-17T15:50:24.708309
2013-10-29T06:02:49
2013-10-29T06:02:49
13,967,090
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright 2013 IBM Corp # # 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 testtools from tempest.api.compute import base import tempest.config as config class AuthTokenTestJSON(base.BaseV2ComputeTest): _interface = 'json' @classmethod def setUpClass(cls): super(AuthTokenTestJSON, cls).setUpClass() cls.servers_v2 = cls.os.servers_client cls.servers_v3 = cls.os.servers_client_v3_auth def test_v2_token(self): # Can get a token using v2 of the identity API and use that to perform # an operation on the compute service. # Doesn't matter which compute API is used, # picking list_servers because it's easy. self.servers_v2.list_servers() @testtools.skipIf(not config.TempestConfig().identity.uri_v3, 'v3 auth client not configured') def test_v3_token(self): # Can get a token using v3 of the identity API and use that to perform # an operation on the compute service. # Doesn't matter which compute API is used, # picking list_servers because it's easy. self.servers_v3.list_servers() class AuthTokenTestXML(AuthTokenTestJSON): _interface = 'xml'
UTF-8
Python
false
false
2,013
438,086,706,036
1125c4ce6f69518ebf531e7d8bb03b26471e1264
e3241c78db850733874973347e38b84fae6476ef
/old/Main.py
cab5744e1868354a09cb46f79dbf20f59d3ca01f
[]
no_license
hathcox/SongBlender
https://github.com/hathcox/SongBlender
daa970f7bd84f87d3bb12bca753fd7087fc9dd16
c3b0064f4dae5f1021f900d8ff1f548512383da5
refs/heads/master
2020-05-29T09:36:30.696964
2012-10-14T21:12:54
2012-10-14T21:12:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import Blender, wave, struct, random blender = Blender.Blender() goodSong = 'goodSongs/popCulture.wav' badSong = 'badSongs/glitchmob.wav' newSong = wave.open('babySongs/new3.wav', 'w') newSong.setparams((2, 2, 44100, 0, 'NONE', 'not compressed')) print "Loaded new Song" if __name__ == '__main__': good_channels, good_sample_rate = blender.pcm_channels(goodSong) good_left_channels = good_channels[0] good_right_channels = good_channels[1] print len(good_left_channels) print "Loaded good song" bad_channels, bad_sample_rate = blender.pcm_channels(badSong) bad_left_channels = bad_channels[0] bad_right_channels = bad_channels[1] print len(bad_left_channels) print "Loaded bad song" finalValues = [] print "Making some shit" bufferSize = 200000 iterations = len(bad_channels[0]) / bufferSize for iteration in range(iterations): for index in range(len(bad_channels[0]) * iteration): average_left = int((good_left_channels[index] + bad_left_channels[index]) / 2) average_right = int((good_right_channels[index] + bad_right_channels[index]) / 2) average_value_packed = struct.pack('h', (average_left + average_right) /2) finalValues.append(average_value_packed) del average_left, average_right, average_value_packed ''' counter = 0 while counter < 3000000: pv = '' if(counter < 1000000): pv = struct.pack('h', counter % 20000) elif(counter < 2000000): pv = struct.pack('h', counter % 15000) else: pv = struct.pack('h', counter % -50) finalValues.append(pv) counter +=1 ''' print "were done!" valueString = ''.join(finalValues) newSong.writeframes(valueString) newSong.close()
UTF-8
Python
false
false
2,012
9,311,489,144,291
ad27da83de7d4ebc445cdb6c0efa6e5d807b092d
417001f185a0234e94402be6bf11b961208307e0
/tests/test_weakref.py
badae7fa2546703ec6a20b95cc69a793bfa6b940
[]
no_license
simplegeo/greenlet
https://github.com/simplegeo/greenlet
671f34b6669e2ae5fa37cb55e91bb18e5c3ad157
eab0f8e760fb07a92e84f55f4ba4c02ae3ec0e00
refs/heads/master
2021-01-01T17:43:05.531441
2010-08-17T00:43:24
2010-08-17T00:43:24
827,374
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import gc import greenlet import weakref import unittest class WeakRefTests(unittest.TestCase): def test_dead_weakref(self): def _dead_greenlet(): g = greenlet.greenlet(lambda:None) g.switch() return g o = weakref.ref(_dead_greenlet()) gc.collect() self.assertEquals(o(), None) def test_inactive_weakref(self): o = weakref.ref(greenlet.greenlet()) gc.collect() self.assertEquals(o(), None)
UTF-8
Python
false
false
2,010
15,891,379,006,860
8b133b1534420d67beb615031fcdcff3f51798f7
ec22b928aea765ef1b3d9786251562e8313de88d
/tests/tests/basic_resource/post_listfield_multiple.py
7a36d69b4b15adf93e6bc5f575042116904c3da7
[ "LGPL-3.0-only" ]
non_permissive
gitaarik/monkful
https://github.com/gitaarik/monkful
ae2f4a47da70ad2c1a1ce3e059f48f3d568e8fc1
27c01e49428dc49e08ba26ff4da652489b406dd9
refs/heads/master
2020-06-01T04:08:08.012106
2014-10-04T17:26:18
2014-10-04T17:26:18
12,561,831
7
3
null
false
2014-04-30T07:53:00
2013-09-03T11:12:37
2014-04-30T07:53:00
2014-04-30T07:53:00
722
2
1
0
Python
null
null
import copy import unittest import json from datetime import datetime from pymongo import MongoClient from apps.basic_resource import server from apps.basic_resource.documents import Article, Comment, Vote class ResourcePostListFieldMultiple(unittest.TestCase): """ Test if a HTTP POST that adds entries to a listfield on a resource gives the right response and adds the data in the database. """ @classmethod def setUpClass(cls): cls.app = server.app.test_client() cls.mongo_client = MongoClient() cls.initial_data = { 'title': "Test title", 'text': "Test text", 'publish': True, 'publish_date': datetime(2013, 10, 9, 8, 7, 8), 'comments': [ Comment( text="Test comment old", email="test@example.com", upvotes=[ Vote(ip_address="1.4.1.2", date=datetime(2012, 5, 2, 9, 1, 3)), Vote(ip_address="2.4.5.2", date=datetime(2012, 8, 2, 8, 2, 1)) ] ), Comment( text="Test comment 2 old", email="test2@example.com", upvotes=[ Vote(ip_address="1.4.1.4", date=datetime(2013, 5, 2, 9, 1, 3)), Vote(ip_address="2.4.9.2", date=datetime(2013, 8, 2, 8, 2, 1)) ] ), ], 'top_comment': Comment( text="Top comment", email="test@example.com", upvotes=[ Vote(ip_address="5.4.1.2", date=datetime(2012, 5, 2, 9, 2, 3)), Vote(ip_address="2.4.1.2", date=datetime(2012, 3, 2, 8, 2, 1)) ] ), 'tags': ["tag1", "tag2", "tag3"] } article = Article(**cls.initial_data).save() cls.add_data = [ { 'text': "Test comment new", 'email': "test-new@example.com", 'upvotes': [ { 'ip_address': "1.2.3.4" }, { 'ip_address': "2.2.3.4" } ] }, { 'text': "Test comment new 2", 'email': "test-new-2@example.com", 'upvotes': [ { 'ip_address': "3.2.3.4" }, { 'ip_address': "2.2.2.4" } ] } ] cls.response = cls.app.post( '/articles/{}/comments/'.format(unicode(article['id'])), headers={'content-type': 'application/json'}, data=json.dumps(cls.add_data) ) @classmethod def tearDownClass(cls): cls.mongo_client.unittest_monkful.article.remove() def test_status_code(self): """ Test if the response status code is 201. """ self.assertEqual(self.response.status_code, 201) def test_content_type(self): """ Test if the content-type header is 'application/json'. """ self.assertEqual( self.response.headers['content-type'], 'application/json' ) def test_json(self): """ Test if the response data is valid JSON. """ try: json.loads(self.response.data) except: self.fail("Response is not valid JSON.") def test_content(self): """ Test if the deserialized response data evaluates back to our data we posted to the resource in `setUpClass`. """ response_data = json.loads(self.response.data) # Remap the response data so that it only has the fields our # orignal data also had. for i, comment in enumerate(response_data): response_data[i] = { 'text': comment['text'], 'upvotes': [ { 'ip_address': comment['upvotes'][0]['ip_address'] }, { 'ip_address': comment['upvotes'][1]['ip_address'] } ] } # Remove the `email` field because it's a writeonly field and # isn't exposed in the resource. original_data = copy.deepcopy(self.add_data) for i, comment in enumerate(original_data): del(original_data[i]['email']) self.assertEqual(response_data, original_data) def test_documents(self): """ Test if the POST-ed data really ended up in the documents, and if the initial data is still there. """ article = Article.objects[0] self.assertEqual(article.title, self.initial_data['title']) self.assertEqual(article.text, self.initial_data['text']) self.assertEqual(article.publish, self.initial_data['publish']) self.assertEqual( article.publish_date, self.initial_data['publish_date'] ) # The initial comments should still be present self.assertEqual( article.comments[0].text, self.initial_data['comments'][0]['text'] ) self.assertEqual( article.comments[0].email, self.initial_data['comments'][0]['email'] ) self.assertEqual( article.comments[1].text, self.initial_data['comments'][1]['text'] ) self.assertEqual( article.comments[1].email, self.initial_data['comments'][1]['email'] ) # The posted comments should be added self.assertEqual( article.comments[2].text, self.add_data[0]['text'] ) self.assertEqual( article.comments[2].email, self.add_data[0]['email'] ) self.assertEqual( article.comments[3].text, self.add_data[1]['text'] ) self.assertEqual( article.comments[3].email, self.add_data[1]['email'] ) self.assertEqual( article.top_comment.text, self.initial_data['top_comment']['text'] ) self.assertEqual( article.top_comment.email, self.initial_data['top_comment']['email'] ) self.assertEqual( article.top_comment.upvotes[0].ip_address, self.initial_data['top_comment']['upvotes'][0]['ip_address'] ) self.assertEqual( article.top_comment.upvotes[1].ip_address, self.initial_data['top_comment']['upvotes'][1]['ip_address'] ) self.assertEqual( article.tags, self.initial_data['tags'] )
UTF-8
Python
false
false
2,014
730,144,453,793
c74959b56cde02727d3e9c2b74272c474473d011
8316e0dc3740ea0c9c9744af56f1584e072146cf
/tests/loganalysis/packetparse.py
f6952557c3a90c0070b3ed422a4818281ddbbcb6
[ "GPL-2.0-or-later", "GPL-2.0-only" ]
non_permissive
xujyan/brunet
https://github.com/xujyan/brunet
b045a5b44c08e6889c814c67a04ed38ad597323d
e371305f347c9e60c264f67160625c255518c897
refs/heads/master
2021-01-16T18:05:10.742131
2009-06-01T15:12:24
2009-06-02T19:14:58
182,706
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # # This takes a Brunet connection log and parses it # The current version takes the whole log. # import sys, time, copy, stats from datetime import timedelta, datetime infilename = sys.argv[1] # bin size (milliseconds) deltatime = timedelta( milliseconds = float(sys.argv[2]) ) direction = "total" #direction = sys.argv[3] # this should be "sent, received, total" ifile = open( infilename, 'r') # r for reading packetstatsname = infilename + "packet_output.txt" packetstatsout = open(packetstatsname, 'w') bytestatsname = infilename + "bytes_stats_output.txt" bytestatsout = open(bytestatsname, 'w') # read the data tmp_address = "" start_time = datetime.today() outputtime = datetime.today() num_packets = 0 num_bytes = 0 deltaincr = copy.deepcopy(deltatime) tmpdeltamultiple = 1 datetime_to_packetlist = {} datetime_to_bytelist = {} count = 0 needs_to_write = False nodes_at_t = 0 for line in ifile: #count = count +1 #print count parsed_line = line.split() if parsed_line[0] == 'Local_node:' : if needs_to_write == True: outputtime = start_time + deltaincr*tmpdeltamultiple #print outputtime.ctime() #print "-----" if outputtime in datetime_to_packetlist: t_list = datetime_to_packetlist[outputtime] t_list.append(num_packets) datetime_to_packetlist[outputtime] = t_list else : datetime_to_packetlist[outputtime] = [num_packets] if outputtime in datetime_to_bytelist: t_list = datetime_to_bytelist[outputtime] t_list.append(num_bytes) datetime_to_bytelist[outputtime] = t_list else : datetime_to_bytelist[outputtime] = [num_bytes] num_packets = 0 num_bytes = 0 tmpdeltamultiple = 1 #print parsed_line[0] , parsed_line[1] , parsed_line[3] ,parsed_line[4] if len( parsed_line) > 1: num_packets = 0 num_bytes = 0 tmp_address = parsed_line[1] tmp_date = parsed_line[3] tmp_time = parsed_line[4] p_d = tmp_date.split('/') p_t = tmp_time.split(':') year = int(p_d[2]) month = int(p_d[0]) day = int(p_d[1]) hour = int(p_t[0]) minute = int(p_t[1]) second = int(p_t[2]) start_time = datetime(year,month,day,hour,minute,second) deltaincr = copy.deepcopy(deltatime) else: c_f = float(parsed_line[0])/1000.0 packetdelta = timedelta( seconds = c_f ) packetbytes = int(parsed_line[1]) needs_to_write = True outputtime = start_time + deltaincr*tmpdeltamultiple #print outputtime.ctime() if deltaincr*tmpdeltamultiple > packetdelta : if direction == 'total' : num_packets = num_packets + 1 num_bytes = num_bytes + packetbytes elif parsed_line[3] == direction: num_packets = num_packets + 1 num_bytes = num_bytes + packetbytes else: print "ERROR in line parsing" else : needs_to_write = False outputtime = start_time + deltaincr*tmpdeltamultiple if outputtime in datetime_to_packetlist: t_list = datetime_to_packetlist[outputtime] t_list.append(num_packets) datetime_to_packetlist[outputtime] = t_list else : datetime_to_packetlist[outputtime] = [num_packets] if outputtime in datetime_to_bytelist: t_list = datetime_to_bytelist[outputtime] t_list.append(num_bytes) datetime_to_bytelist[outputtime] = t_list else : datetime_to_bytelist[outputtime] = [num_bytes] num_packets = 0 num_bytes = 0 tmpdeltamultiple = tmpdeltamultiple + 1 timestamps = datetime_to_packetlist.keys() timestamps.sort() tmp_total = 0 tmp_size = 0 for time_it in timestamps: if len(datetime_to_packetlist[time_it]) > 1: mtmp = stats.mean(datetime_to_packetlist[time_it]) vtmp = stats.var(datetime_to_packetlist[time_it]) tmp_size = len(datetime_to_packetlist[time_it]) tmp_total = tmp_total + tmp_size*mtmp packetstatsout.write( "%s %f %f %i %i\n" % \ (time_it,mtmp,vtmp,tmp_total,tmp_size) ) else : mtmp = stats.mean(datetime_to_packetlist[time_it]) tmp_size = len(datetime_to_packetlist[time_it]) tmp_total = tmp_total + tmp_size*mtmp packetstatsout.write( "%s %f -1 %i %i\n" % \ (time_it,mtmp,tmp_total,tmp_size) ) #datetime_to_packetlist[time_it] timestamps = datetime_to_bytelist.keys() timestamps.sort() tmp_total = 0 tmp_size = 0 for time_it in timestamps: if len(datetime_to_bytelist[time_it]) > 1: mtmp = stats.mean(datetime_to_bytelist[time_it]) vtmp = stats.var(datetime_to_bytelist[time_it]) tmp_size = len(datetime_to_bytelist[time_it]) tmp_total = tmp_total + tmp_size*mtmp bytestatsout.write( "%s %f %f %f %i\n" % (time_it,mtmp,vtmp,tmp_total,tmp_size) ) else : mtmp = stats.mean(datetime_to_bytelist[time_it]) tmp_size = len(datetime_to_bytelist[time_it]) tmp_total = tmp_total + tmp_size*mtmp bytestatsout.write( "%s %f -1 %f %i\n" % ( time_it,mtmp,tmp_total,tmp_size ) )
UTF-8
Python
false
false
2,009
2,095,944,088,559
64f3f740fa01b64d03830d359531f93dcbd5054e
1d82991e029f626abdb35d4e09855265efbcbc23
/Chapter_02/node.py
a0b25b04c05d9dd9b83d9007de94471d230561d8
[]
no_license
jobiaj/Problems-from-Problem-Solving-with-Algorithms-and-Data-Structures-
https://github.com/jobiaj/Problems-from-Problem-Solving-with-Algorithms-and-Data-Structures-
6126395c340c00af21717a3e69a548db6fc71c56
42e518a4af72abf3a8c9455002cf20be369d157b
refs/heads/master
2021-01-18T20:35:12.689684
2014-11-27T07:21:50
2014-11-27T07:21:50
27,213,731
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
class Node: def __init__(self, init__data): self.data = init__data self.next = None def get_data(self): return self.data def get_next(self): return self.next def set_data(self, new_data): self.data = new_data def set_next(self, new_next): self.next = new_next temp = Node(93) print temp.get_data()
UTF-8
Python
false
false
2,014
9,698,036,201,252
7a25b5fde6d689c60eef4c1d84439176c555fe27
fbebbffc47def8a6a7fdc86be16a39f98095237f
/ench.sikuli/ench.py
26647dd61b6851f8e9c79de54c1208674116c1dc
[]
no_license
ion1/minecraft-enchantment-table-grind
https://github.com/ion1/minecraft-enchantment-table-grind
cd756a4973845bc1f133ee54ba9d6c059d9b86d8
6f0c4f806687f1da6279743792b47bb39cb6c36b
refs/heads/master
2021-01-19T06:40:57.926898
2011-12-21T17:18:33
2011-12-21T17:18:33
3,028,286
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
Settings.MoveMouseDelay = 0.05 class Ench: def __init__(self): self.region = Screen(0).selectRegion() def run(self): while True: self.refreshEnchs() try: self.selectEnch() break except FindFailed: pass def refreshEnchs(self): self.selectTitle() doubleClick(self.region.wait(Pattern("Enchant-title.png").exact().targetOffset(2,90), 1)) def selectEnch(self): self.selectTitle() hover(self.region.wait(Pattern("num.png").exact(), 0.1)) def selectTitle(self): click(self.region.wait(Pattern("Enchant-title.png").exact(), FOREVER)) Ench().run()
UTF-8
Python
false
false
2,011
6,442,450,953,147
876fcbfe4cca3bad238eefc267a37044490e6b17
9009f80d5b91cf8da02dd513084ae6b6410afdee
/Algo_Thininking_Module_2.py
f4445e1853d069b9c0d76e6e0d1e6c371cc0b533
[]
no_license
yellowBirdy/Algorithmic_Thinking
https://github.com/yellowBirdy/Algorithmic_Thinking
378a8ca34b948f7685c796e72d9d349b3c5c026f
c76fcfa8c2595a4d7e8214ba4b48cb60eb2743e9
refs/heads/master
2020-05-06T13:35:06.137835
2014-09-19T21:56:44
2014-09-19T21:56:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# coding: utf-8 ## 1. Project # In[42]: """ Project 2 of Algorythmic Thinking implementation: 1. implementing BFS algorithm 2. computing CC of undirected graph using BFS algorithm 3. computing resilence of a network """ #import O(1) queue implementation from collections import deque import random # In[43]: #small fully connected graph EX_UGRAPH0 = {0:set([1,2,3]), 1:set([0,2]), 2:set([0,1]), 3:set([0])} #small graph with 2 CC EX_UGRAPH1 = {0:set([1,2,3]), 1:set([0,2]), 2:set([0,1]), 3:set([0]), 4:set([5]), 5:set([4])} #slightly bigge graph with 4 CC and largest CC size 5 EX_UGRAPH2 = {0:set([1,3,5]), 1:set([0]), 2:set([]), 3:set([0,5]), 4:set([7,8]), 5:set([0,3,9]), 6:set([]), 7:set([4,8]), 8:set([4,7]), 9:set([5]) } ### Task 1: BFS-Visited implementation # In[44]: def bfs_visited(ugraph, start_node): """ Implementation of BFS-visited alogorithm takes 2 args, undirected graph as adjacency list and the start node returns a set of all visited nodes - a connected component of the start node """ queue = deque() visited = set() visited = visited | set([start_node]) queue.append(start_node) while queue: #deque current_node = queue.popleft() for neighbour in ugraph[current_node]: if neighbour not in visited: visited = visited | set([neighbour]) queue.append(neighbour) #end of queue return visited ### Task2: Computing a set of connected components CC using BFS-Visited # In[45]: def cc_visited(ugraph) : """ computes all connected components using BFS-visited algorithm takes 1 arg: undirected graph as adjacency list Returns a list of all connected components of ugraph """ remaining_nodes = set(ugraph.keys()) connected_components = [] while remaining_nodes: start_node = random.sample(remaining_nodes,1)[0] #computes connected component of start_node and adds it to the list of all connected components cc_of_start_node = bfs_visited(ugraph,start_node) connected_components.append(cc_of_start_node) #removes all nodes from computed connected component from remaining nodes remaining_nodes = remaining_nodes - cc_of_start_node return connected_components def largest_cc_size(ugraph): """ Computes the size of largest connected component of a ugraph takes 1 arg: undirected graph as adjacency list returns integer size of largest connected component """ connected_components = cc_visited(ugraph) largest_cc = 0 for component in connected_components: cc_size=len(component) if cc_size > largest_cc: largest_cc = cc_size return largest_cc ### Part3: Resilence test # In[51]: def compute_resilience(ugraph, attack_order): """ Computes the size of largest connected component of a ugraph as a funcion of attacked nodes takes 2 args: undirected graph as adjacency list and a list of attacked nodes returns a list of sizes of largest connected component, first elelment is for full network followed by size after noeds have been attacked """ #copy graph to local variable local_ugraph = {node:graph[node] for node in graph} largest_cc = [] largest_cc.append(largest_cc_size(local_ugraph)) for attacked_node in attack_order: attacked_neighbors = local_ugraph[attacked_node] for neighbor in attacked_neighbors: local_ugraph[neighbor].remove(attacked_node) del local_ugraph[attacked_node] largest_cc.append(largest_cc_size(local_ugraph)) return largest_cc
UTF-8
Python
false
false
2,014
13,924,284,010,745
d6ec0cdf1cd689fb2fa8fb6ef846427920bfa9e8
b45dc9e52246d6ef3a28e2d329f5749aeb442acd
/skinSegmentation/__init__.py
570c6f9f1a954bcb03120e3d458e478fb62aec43
[]
no_license
WillyMaikowski/cc5509
https://github.com/WillyMaikowski/cc5509
32dfb17de97fc03d84840f2cdacb132d9ff2e38b
2764a4d73930b3915873e45cbba6c74f044aec20
refs/heads/master
2016-09-06T19:46:29.094573
2014-10-26T17:19:02
2014-10-26T17:19:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#inicio de la tarea import numpy as np import cv2 import os import utils from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt path = [ "dataSet/train/", "dataSet/test/" ] j=0 totalPixels = 0 totalSkinPixels = 0 totalNonSkinPixels = 0 train = [] train_responses = [] test = [] test_responses = [] skin_freq = {} non_skin_freq = {} skin_points = [] non_skin_points = [] for j in range(2): count = 0 for r, d, f in os.walk(path[j]+"original/"): for imgName in f: #imgName = "img22.jpg" count = count + 1 img = cv2.imread(path[j]+"original/" + imgName, cv2.IMREAD_COLOR) img_skin = img.copy() #img2 = cv2.imread(path[j]+"original/img5.jpg", cv2.IMREAD_COLOR) imgGroundThruth = cv2.imread(path[j]+"groundThruth/" + imgName, 0) #ret, imgGroundThruth = cv2.threshold(imgGroundThruth, 127, 255, cv2.THRESH_BINARY)#todos los grises los tira a blanco ret, imgGroundThruth_inv = cv2.threshold(imgGroundThruth, 127, 1, cv2.THRESH_BINARY)#uno indica no piel, cero indica piel ret, imgGroundThruth = cv2.threshold(imgGroundThruth, 127, 1, cv2.THRESH_BINARY_INV)#uno indica piel, cero indica no piel skin_img = cv2.bitwise_and(img,img,mask = imgGroundThruth) non_skin_img = cv2.bitwise_and(img,img,mask = imgGroundThruth_inv) #print(imgGroundThruth[len(imgGroundThruth[0])/2,]) #hist = cv2.calcHist( [imgGroundThruth], [0], None, [2], [0, 256], False ) hist = cv2.calcHist( [imgGroundThruth], [0], None, [2], [0, 2], False ) #print(hist) totalSkinPixels += hist[0][0] totalNonSkinPixels += hist[1][0] totalPixels += img[:,:,0].size #print(hist) #print( totalPixels) #print( totalNonSkinPixels) #print( totalSkinPixels) #print( totalNonSkinPixels + totalSkinPixels ) #cv2.imshow('',img[:,:,1]); cv2.waitKey(0); cv2.destroyAllWindows(); quit() #cv2.imshow('',skin_img); cv2.waitKey(0); cv2.destroyAllWindows(); quit() #curve = utils.hist_curve(img) #cv2.imshow('histogram',curve) #print(img[0,0]) #img = np.reshape(img, (img[:,:,0].size,3)) #img2 = np.reshape(img2, (img2[:,:,0].size,3)) #print(img) #print(img2) #print(np.vstack((img, img2))) #print(np.reshape(img, (img[:,:,0].size,3))) #print(np.vstack(np.reshape(img, (img[:,:,0].size,3)))) #print(np.reshape(imgGroundThruth, imgGroundThruth.size)) #cv2.imshow('image',img); cv2.waitKey(0); cv2.destroyAllWindows(); quit() #ver http://stackoverflow.com/questions/13254234/train-skin-pixels-using-opencv-cvnormalbayesclassifier # if( j == 0 ): # #generar un histograma de los distintos colores # for k in range(len(imgGroundThruth)): # for l in range(len(imgGroundThruth[0])): # key = tuple(img[k][l]) # if imgGroundThruth[k][l] == 1:#piel # skin_freq[key] = skin_freq.get(key, 0) + 1 # else: # non_skin_freq[key] = non_skin_freq.get(key, 0) + 1 # # np.save('count', count) # np.save('piel_dict',skin_freq) # np.save('no_piel_dict',non_skin_freq) if( j == 0 ): #separar entre piel y no piel skin_img = np.reshape(skin_img, (skin_img[:,:,0].size,3)) #skin_img = skin_img[ ~np.all(skin_img == (0,0,0)) ] non_skin_img = np.reshape(non_skin_img, (non_skin_img[:,:,0].size,3)) #non_skin_img = non_skin_img[ ~(non_skin_img == (0,0,0)) ] if len(skin_points) <= 0: skin_points = skin_img else: skin_points = np.vstack((skin_points, skin_img)) if len( non_skin_points ) <= 0: non_skin_points = non_skin_img else: non_skin_points = np.vstack((non_skin_points, non_skin_img)) img = np.reshape(img, (img[:,:,0].size,3)) imgGroundThruth = np.reshape(imgGroundThruth, imgGroundThruth.size) print( "count",count ) if( j == 0 ): if count == 1: train = img train_responses = imgGroundThruth else: train = np.vstack((train, img)) train_responses = np.hstack((train_responses, imgGroundThruth)) #train.append(img) #train_responses.append(imgGroundThruth) else: if count == 1: test = img test_responses = imgGroundThruth else: test = np.vstack((test, img)) test_responses = np.hstack((test_responses, imgGroundThruth)) #test.append(img) #test_responses.append(imgGroundThruth) # index = 0 # for k in range(len(img_skin)): # for l in range(len(img_skin[0])): # if imgGroundThruth[index] == 1: # img_skin[k,l] = (0,0,0) # index +=1 #cv2.imshow('image',img_skin); cv2.waitKey(0); cv2.destroyAllWindows(); #np.save('piel_dict',skin_freq) #np.save('no_piel_dict',non_skin_freq) skin_freq = np.load('piel_dict.npy').item() non_skin_freq = np.load('no_piel_dict.npy').item() #print(skin_freq) #print(non_skin_freq) #print(non_skin_freq) #print(skin_points) print("imagenes leidas") fig = plt.figure( figsize = (20,20) ) ax = fig.add_subplot(255, projection='3d') max_it = 500 it = 0 for i in skin_points: if ~i.all(): continue it = it + 1 xs = i[0] ys = i[1] zs = i[2] ax.scatter(xs, ys, zs, c='r', marker='o') if it >= max_it: break it = 0 for i in non_skin_points: if ~i.all(): continue it = it + 1 xs = i[0] ys = i[1] zs = i[2] ax.scatter(xs, ys, zs, c='b', marker='^') if it >= max_it: break ax.set_xlabel('Red') ax.set_ylabel('Green') ax.set_zlabel('Blue') plt.tight_layout() plt.show() print("Entrenando") bayes = cv2.NormalBayesClassifier(np.float32(train), np.float32(train_responses)) #cv2.NormalBayesClassifier.predict(samples) #Prediction predictions = [] j=1 #usando clasificador de bayes for r, d, f in os.walk(path[j]+"original/"): for imgName in f: img_original = cv2.imread(path[j]+"original/" + imgName, cv2.IMREAD_COLOR) img = img_original.copy() imgGroundThruth = cv2.imread(path[j]+"groundThruth/" + imgName, 0) ret, imgGroundThruth = cv2.threshold(imgGroundThruth, 128, 1, cv2.THRESH_BINARY_INV)#uno indica piel, cero indica no piel img = np.reshape(img, (img[:,:,0].size,3)) imgGroundThruth = np.reshape(imgGroundThruth, imgGroundThruth.size) retval, results = bayes.predict(np.float32(img)) results = np.hstack(results) matches = results == imgGroundThruth correct = np.count_nonzero( matches ) accuracy = correct * 100.0 / results.size predictions.append( (imgName, accuracy) ) print((imgName, accuracy)) index = 0 img_reconstruct = img_original.copy() cv2.imshow(imgName+"original",img_original); for k in range(len(img_original)): for l in range(len(img_original[0])): img_reconstruct[k,l] = img[index] if results[index] == 1.0:#predijo piel img_original[k,l]=(0,255,0) else: img_original[k,l]=(255,0,0) index+=1 #cv2.imshow(imgName+"_recontru",img_reconstruct); cv2.imshow(imgName,img_original); cv2.waitKey(0); cv2.destroyAllWindows(); print(predictions) retval, results = bayes.predict(np.float32(test)) results = np.hstack(results) matches = results == test_responses correct = np.count_nonzero( matches ) accuracy = correct * 100.0 / results.size print "Total",accuracy #################################################################################### predictions = [] j=1 phi = 1 PC1 = 1.0*totalSkinPixels/totalPixels#probabilidad ser piel PC2 = 1.0*totalNonSkinPixels/totalPixels#probabilidad no ser piel #usando clasificador casero for r, d, f in os.walk(path[j]+"original/"): for imgName in f: #imgName = "img22.jpg" img_original = cv2.imread(path[j]+"original/" + imgName, cv2.IMREAD_COLOR) img = img_original.copy() imgGroundThruth = cv2.imread(path[j]+"groundThruth/" + imgName, 0) ret, imgGroundThruth = cv2.threshold(imgGroundThruth, 128, 1, cv2.THRESH_BINARY_INV)#uno indica piel, cero indica no piel #print(imgGroundThruth[len(imgGroundThruth[0])/2,]) imgGroundThruth = np.reshape(imgGroundThruth, imgGroundThruth.size) results = [] for k in range(len(img_original)): for l in range(len(img_original[0])): key = tuple(img_original[k][l]) PXi_C1 = 1.0*skin_freq.get(key,0)/totalSkinPixels PXi_C2 = 1.0*non_skin_freq.get(key,0)/totalNonSkinPixels PXi = PXi_C1*PC1 + PXi_C2*PC2 PC1_Xi = PXi_C1*PC1/PXi PC2_Xi = PXi_C2*PC2/PXi if PC1_Xi > PC2_Xi*phi:#es piel results.append(1) else: results.append(0) matches = results == imgGroundThruth correct = np.count_nonzero( matches ) accuracy = correct * 100.0 / len(results) predictions.append( (imgName, accuracy) ) print((imgName, accuracy)) index = 0 cv2.imshow(imgName+"original",img_original); for k in range(len(img_original)): for l in range(len(img_original[0])): if results[index] == 1:#predijo piel img_original[k,l]=(0,255,0) #else: # img_original[k,l]=(255,0,0) if imgGroundThruth[index] == 1: img[k,l] = (255,255,255) index+=1 cv2.imshow(imgName+"mascara",img); cv2.imshow(imgName,img_original); cv2.waitKey(0); cv2.destroyAllWindows(); # retval, results = bayes.predict(np.float32(test)) # results = np.hstack(results) # matches = results == test_responses # correct = np.count_nonzero( matches ) # accuracy = correct * 100.0 / results.size # print "Total",accuracy #print( "total pixels = " + str(totalPixels)) #print( "total non skin pixels = " + str(totalNonSkinPixels)) #print( "total skin pixels = " + str(totalSkinPixels) ) #print( "total pixels check = " + str(totalNonSkinPixels + totalSkinPixels ))
UTF-8
Python
false
false
2,014
12,644,383,727,031
9051d9a09faebb96a3263277f072994b920eebbc
4cb06a6674d1dca463d5d9a5f471655d9b38c0a1
/mac1077/Assignment5/Prob2.py
562db0535deaa55b6278b787588bba156e019ce4
[]
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
import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt import matplotlib.dates as dt from matplotlib import ticker from datetime import datetime data = open('actions-fall-2007.dat','r') #open file ddl_date = ['2007-09-18 12:00:00','2007-09-18 12:00:00','2007-10-04 12:00:00', '2007-10-25 12:00:00','2007-11-27 12:00:00','2007-12-11 12:00:00', '2007-12-15 12:00:00'] #deadlines's dates ddl_lst = [] for element in ddl_date: temp = datetime.strptime(element.strip(), '%Y-%m-%d %H:%M:%S') temp2 = dt.date2num(temp) ddl_lst.append(temp2) #assignemnts assignments = [] for line in data: assignments.append(line) del assignments[0] #number & times of assignments num_time = [] for event in assignments: event_date = datetime.strptime(event.strip(),'%Y-%m-%d %H:%M:%S') event_date_num = dt.date2num(event_date) num_time.append(event_date_num) #10 hour period for date1 date1 = dt.date2num(datetime.strptime('2007-09-18 12:00:00','%Y-%m-%d %H:%M:%S')) date2 = dt.date2num(datetime.strptime('2007-09-19 12:00:00','%Y-%m-%d %H:%M:%S')) date_interval = date2 - date1# #bins size divided by 10= number of bins date_range = max(num_time) - min(num_time) num_bins = date_range/date_interval #plot plot_bin_range_min = dt.date2num(datetime.strptime('2007-09-11 12:00:00','%Y-%m-%d %H:%M:%S'))#Limits of minimum date plot_bin_range_max = dt.date2num(datetime.strptime('2007-12-25 12:00:00','%Y-%m-%d %H:%M:%S'))#Limits of maximum date plt.hist(num_time, bins = num_bins, range = (plot_bin_range_min, plot_bin_range_max)) for deadline in ddl_lst: plt.vlines(deadline, 0, 14000, colors = 'y', linestyles = 'solid') plt.vlines(ddl_lst[0], 0, 14000, colors = 'y', linestyles = 'solid', label = 'Due Dates') plt.title('Histogram for Assignments') plt.xlabel('TimeStamp') plt.ylabel('Number of Assignments') plt.xticks(np.arange(plot_bin_range_min, plot_bin_range_max, 10)) plt.gca().xaxis.set_major_formatter(ticker.FuncFormatter(lambda numdate, _: dt.num2date(numdate).strftime('%m/%d/%H:%M:%S'))) plt.gcf().autofmt_xdate() plt.legend(loc='center left') plt.tight_layout() plt.show()
UTF-8
Python
false
false
2,013
12,300,786,372,370
ceea2aa84f7503e907292b3efd2f2e7121673c66
ed0dda37ccdc7354694982ada7a62551d89b8146
/loi/con/00.constitution_du_4_octobre_1958/script
960ccf8d293d00fde3ccd9fae4cb29cb4c8fe842
[]
no_license
techtronics/legit
https://github.com/techtronics/legit
b91e3f7f26225ced58266d1af929cb7e8223bfce
fe741c8b3c7bdd407f95e3cc9915c13e7f0a3644
refs/heads/master
2017-12-04T09:03:21.477372
2012-12-09T23:00:00
2012-12-12T23:00:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python #*-* encoding:utf8 *-* # import urllib2 from bs4 import BeautifulSoup # url1 = "http://www.legifrance.gouv.fr/affichTexte.do?cidTexte=LEGITEXT000006071194" file1 = "/tmp/constitution.html" # #htmlDoc = urllib2.urlopen(url1).read() htmlDoc = open(file1, 'r').read() soup = BeautifulSoup(htmlDoc) listeArticles = soup.find_all("div", {"class" : "article"}) i = -1 for art in listeArticles : i += 1 try: titre=(art.find("div", {"class" : "titreArt"})).contents[0].rstrip().replace(' ', '_') except: print(art) print("") continue try: corps=reduce(lambda x,y: x + "\n" + y, map( lambda x: x.text.rstrip(), art.find_all("p"))) fart = open(str(i).zfill(3) + "." + titre, 'w') fart.write(corps.encode("utf8")) fart.close() except: print(titre.encode("utf8")) print("") continue
UTF-8
Python
false
false
2,012
3,796,751,134,789
a57eda38c7f8937883ce80664631f42521081108
548c26cc8e68c3116cecaf7e5cd9aadca7608318
/fulfillment/manager.py
593ac3ff6d682ba7f8dbf93bc01ea875a7be19ee
[]
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 FulfillmentManager(): def __init__(self): pass def get_order_serviceability(self, order, **kwargs): ''' Checks if an order is serviceable. There are several constraints which define serviceability of the order. The level of checking can be controlled by the flags in kwargs. Available flags are a. stock (always true, not a flag really) b. pincode_covered - check if order can be shipped to pincode c. cod - check if order qualifies for cod Serviceability checks include - 1. SKUs should be in stock/in virutal inventory 2. SKUs should be shippable to given pincode 3. COD should be supported if customer chooses COD The function returns expected stock dates and delivery dates for each of the order items. Delivery dates are computed if pincode is attached to an order and pincode_covered flag is on. ''' pass
UTF-8
Python
false
false
2,012
17,188,459,145,293
05e393bd9b2ed024607b562807861761863e3496
fbe21588ed6792147e291aa223b10b9687aee970
/demo/apps/home/models.py
a2c8423875ff68dd608fb77e88ba3a9ce0ea2d52
[]
no_license
brenotx/demo
https://github.com/brenotx/demo
05a50f1782c6234ac12dcdf9776708c66c74d773
39a39c80d585c606bfa51da3df36f8617d286ede
refs/heads/master
2016-05-27T02:25:19.530193
2013-05-02T04:49:23
2013-05-02T04:49: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 class UserProfile(models.Model): def url(self, filename): route = "MultimediaData/Users/%s/%s" % (self.user.username, filename) return route user = models.OneToOneField(User) photo = models.ImageField(upload_to=url) phone = models.CharField(max_length=30) def __unicode__(self): return self.user.username
UTF-8
Python
false
false
2,013
16,269,336,126,355
5bba121522d2a3b4afcfe619efa3feafc3331194
701ca9dbf892677a47dea38cb246f565e6507c39
/baby/models.py
e21cc64189c07654b3075128466de4b2902ca1b9
[]
no_license
cookie0131/mysite
https://github.com/cookie0131/mysite
19fec1d826032e0e8004b2ba74cf648e71f31316
ef7c3d9baacb735624f8d272fdf0f2d69611dc7d
refs/heads/master
2016-05-27T04:28:21.171138
2014-08-17T11:52:13
2014-08-17T11:52:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding:utf-8 -*- __author__ = 'haocheng' from django.db import models STATUS_CHOICES = ( (1, '开启'), (0, '关闭'), ) TYPE_CHOICES = ( (1, '父节点'), (0, '子节点'), ) TOP_CHOICES = ( (1, '置顶'), (0, '不置顶'), ) SUPPORT_CHOICES = ( (1, '广告'), (0, '内容'), ) PAGE_CHOICES = ( (1, '首页'), (2, '列表页'), (3, '单页右测全部'), (4, '单页其他广告') ) class Channel(models.Model): """ 频道 """ name = models.CharField("频道", max_length=10) code = models.CharField("标识", max_length=15) type = models.SmallIntegerField("类别", max_length=2, choices=TYPE_CHOICES) status = models.SmallIntegerField("状态", max_length=2, choices=STATUS_CHOICES) create_time = models.DateTimeField("创建时间", editable=False, auto_now_add=True) def __unicode__(self): return self.name class SubChannel(Channel): """ 子频道 """ father_node = models.ForeignKey('Channel', related_name='Channel') class Article(models.Model): """文章""" title = models.CharField("标题", max_length=80) introduction = models.CharField("导读", null=True, blank=True, max_length=400) content = models.TextField("内容") pic = models.ImageField("图片", null=True, blank=True, upload_to="baby/article") type = models.ForeignKey('SubChannel') top = models.SmallIntegerField("置顶", max_length=2, choices=TOP_CHOICES) create_time = models.DateTimeField("创建时间", editable=False, auto_now_add=True) def __unicode__(self): return self.title class Support(models.Model): """内容维护块""" code = models.CharField("标识", max_length=20) content = models.TextField("内容") page = models.SmallIntegerField("页面归属", max_length=2, choices=PAGE_CHOICES) type = models.SmallIntegerField("类型", max_length=2, choices=SUPPORT_CHOICES) def __unicode__(self): return self.code
UTF-8
Python
false
false
2,014
18,150,531,807,518
72ee3e9e4d46f14d3856982a7e2155d6a4de5204
07d8c218b8e6facc2c3f3cba29e8949143a11334
/jabba/helpdesk/admin.py
4cdae2c97d0149bfd551958fbab1e6c0f1e22474
[ "BSD-3-Clause" ]
permissive
wiliamsouza/jabba
https://github.com/wiliamsouza/jabba
cacf0587992a1d3f5384d5c315d69b6230df7e8a
6f9453cf906381c0de7664b2717cc94dba4434a5
refs/heads/master
2021-01-20T11:06:23.928684
2012-01-21T00:23:53
2012-01-21T00:23:53
547,237
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.contrib import admin from helpdesk.models import Team, Task, Context, Note, Attachment admin.site.register(Team) admin.site.register(Task) admin.site.register(Context) admin.site.register(Note) admin.site.register(Attachment)
UTF-8
Python
false
false
2,012
17,514,876,650,844
7e2228bf107ba32944ba6e24c2595311ec94bdb1
f2b42062dd2379f90d3ca0ef774e2820d587ea65
/osmosis/model/tests/test_canonical_tensor.py
70b614f2ecbcb86d5cd3e2e2af0ad1f54e99c0db
[ "CC-BY-4.0", "CC-BY-SA-3.0" ]
non_permissive
vistalab/osmosis
https://github.com/vistalab/osmosis
603bf4c48dab369e78100c130dff8f4ed3ef0348
1fbadf936a148d8508ff732d2f8e8edc1e0b95e5
refs/heads/master
2020-03-31T12:39:23.619056
2014-08-26T18:49:05
2014-08-26T18:49:05
7,672,790
1
2
null
true
2014-08-16T00:25:10
2013-01-17T19:37:42
2014-08-14T17:33:41
2014-08-16T00:25:08
91,588
1
2
0
Python
null
null
import os import tempfile import numpy as np import numpy.testing as npt import nibabel as ni import osmosis as oz from osmosis.model.canonical_tensor import (CanonicalTensorModel, CanonicalTensorModelOpt) data_path = os.path.split(oz.__file__)[0] + '/data/' def test_CanonicalTensorModel(): """ Test the simple canonical + sphere model. """ # 1000 'voxels' with constant data in each one in all directions (+b0): data = (np.random.rand(10 * 10 * 10).reshape(10 * 10 * 10, 1) + np.zeros((10 * 10 * 10, 160))).reshape(10,10,10,160) CTM = CanonicalTensorModel(data, data_path + 'dwi.bvecs', data_path + 'dwi.bvals', params_file=tempfile.NamedTemporaryFile().name) # XXX Smoke testing only npt.assert_equal(CTM.fit.shape, CTM.signal.shape) mask_array = np.zeros(ni.load(data_path+'small_dwi.nii.gz').shape[:3]) # Only two voxels: mask_array[1:3, 1:3, 1:3] = 1 # Fit this on some real dwi data for mode in ['signal_attenuation', 'relative_signal', 'normalize', 'log']: for params_file in [None, tempfile.NamedTemporaryFile().name, 'temp']: CTM = CanonicalTensorModel(data_path+'small_dwi.nii.gz', data_path + 'dwi.bvecs', data_path + 'dwi.bvals', mask=mask_array, params_file=params_file, mode=mode) # XXX Smoke testing only: npt.assert_equal(CTM.fit.shape, CTM.signal.shape) npt.assert_equal(CTM.principal_diffusion_direction.shape, CTM.signal.shape[:3] + (3,)) npt.assert_equal(CTM.fractional_anisotropy.shape, CTM.signal.shape[:3]) # Test over-sampling: for over_sample in [362, 246]: # Over-sample from dipy and from # camino-points CTM = CanonicalTensorModel(data_path+'small_dwi.nii.gz', data_path + 'dwi.bvecs', data_path + 'dwi.bvals', mask=mask_array, params_file=tempfile.NamedTemporaryFile().name, over_sample=over_sample, mode=mode) # XXX Smoke testing only: npt.assert_equal(CTM.fit.shape, CTM.signal.shape) # This shouldn't be possible, because we don't have a sphere with 151 # samples handy: npt.assert_raises(ValueError, CanonicalTensorModel, data_path+'small_dwi.nii.gz', data_path + 'dwi.bvecs', data_path + 'dwi.bvals', **dict(mask=mask_array, params_file=tempfile.NamedTemporaryFile().name, over_sample=151)) # If you provide an unrecognized mode, you get an error: npt.assert_raises(ValueError, CanonicalTensorModel, data_path+'small_dwi.nii.gz', data_path + 'dwi.bvecs', data_path + 'dwi.bvals', **dict(mask=mask_array, mode='crazy_mode', params_file=tempfile.NamedTemporaryFile().name)) def test_CanonicalTensorModelOpt(): """ Test fitting of the CanonicalTensorModel by optimization """ mask_array = np.zeros(ni.load(data_path+'small_dwi.nii.gz').shape[:3]) # Only two voxels: mask_array[1:3, 1:3, 1:3] = 1 # Fit this on some real dwi data for model_form in ['flexible', 'constrained', 'ball_and_stick']: for mode in ['relative_signal', 'signal_attenuation']: CTM = CanonicalTensorModelOpt(data_path+'small_dwi.nii.gz', data_path + 'dwi.bvecs', data_path + 'dwi.bvals', model_form = model_form, mode = mode, mask=mask_array, params_file=tempfile.NamedTemporaryFile().name) # XXX Smoke testing for now: npt.assert_equal(CTM.fit.shape, CTM.signal.shape) # Normalize doesn't make sense for the optimization, so we raise an error npt.assert_raises(ValueError, CanonicalTensorModelOpt, data_path+'small_dwi.nii.gz', data_path + 'dwi.bvecs', data_path + 'dwi.bvals', mode='normalize', mask=mask_array, params_file=tempfile.NamedTemporaryFile().name) npt.assert_raises(ValueError, CanonicalTensorModelOpt, data_path+'small_dwi.nii.gz', data_path + 'dwi.bvecs', data_path + 'dwi.bvals', model_form='crazy_model', mode='normalize', mask=mask_array, params_file=tempfile.NamedTemporaryFile().name) def test_predict(): """ Test the CanonicalTensorModel predict method """ # 1000 'voxels' with constant data in each one in all directions (+b0): data = (np.random.rand(10 * 10 * 10).reshape(10 * 10 * 10, 1) + np.zeros((10 * 10 * 10, 160))).reshape(10,10,10,160) CTM = CanonicalTensorModel(data, data_path + 'dwi.bvecs', data_path + 'dwi.bvals', params_file=tempfile.NamedTemporaryFile().name) bvecs = CTM.bvecs[:, CTM.b_idx] new_bvecs = bvecs[:,:4] prediction = CTM.predict(new_bvecs) npt.assert_array_equal(prediction, CTM.fit[...,:4])
UTF-8
Python
false
false
2,014
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
4,741,643,941,490
9012b0babefa46e91358cb8b0313d68aa91b25a8
2ded92a6a17bbdc7b375c429e4732cf9eba95880
/phycas/Phycas/MarkovChain.py
bf95d68a8ccdf011d64e316e884f01918399621e
[ "GPL-2.0-only" ]
non_permissive
danielfan/Phycas
https://github.com/danielfan/Phycas
c540338ac733da235ce6584f436691f36e1b2126
57d69eb19a31a1636bd94281f5bb41a6bd8795fd
refs/heads/master
2021-01-23T06:19:53.486427
2012-03-31T23:53:58
2012-03-31T23:53:58
3,472,421
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os,sys,math from phycas import * import phycas.Phylogeny as Phylogeny import phycas.ProbDist as ProbDist import phycas.Likelihood as Likelihood from LikelihoodCore import LikelihoodCore #from threading import Thread class UnimapSpreadingWrapper(object): def __init__(self, mcmc): self.unimap_ls_move_list = [Likelihood.UnimapLSMove(mcmc.likelihood) for i in range(mcmc.parent.opts.unimap_thread_count)] self.unimap_spreader_move = Likelihood.UnimapTopoMoveSpreader() self.unimap_spreader_move.setName("unimap_topo_move_spreader") self.unimap_spreader_move.setWeight(mcmc.parent.opts.unimap_ls_move_weight) self.unimap_spreader_move.setTree(mcmc.tree) self.unimap_spreader_move.setLot(mcmc.r) for n, m in enumerate(self.unimap_ls_move_list): self.unimap_spreader_move.addTopoMoveToSpreader(m) m.setName("unimap_LS_move %d" % n) m.setWeight(0) m.setTree(mcmc.tree) m.setModel(mcmc.partition_model.getModel(0)) m.setLot(mcmc.r) mcmc.chain_manager.addMove(m) def setSaveDebugInfo(self, f): self.unimap_spreader_move.setSaveDebugInfo(f) for m in self.unimap_ls_move_list: m.setSaveDebugInfo(f) def getName(self): return self.unimap_spreader_move.getName() def getDebugInfo(self): return self.unimap_spreader_move.getDebugInfo() def update(self): #import pdb; pdb.set_trace() self.unimap_spreader_move.update() return True # below here is old code that failed to be truly parallel due to the Python GIL #threads = [Thread(target=i.update) for i in self.unimap_ls_move_list] #for t in threads: # t.start() #for t in threads: # t.join() #print "all threads done!" #return True class MarkovChain(LikelihoodCore): #---+----|----+----|----+----|----+----|----+----|----+----|----+----| """ The MarkovChain class encapsulates the notion of a Markov chain used in Bayesian analyses. The MarkovChain class has the ability to orchestrate a Markov chain Monte Carlo (MCMC) analysis. In Metropolis-coupled MCMC, the cold chain and each of the heated chains are MarkovChain objects. The primary addition MarkovChain adds to the base class LikelihoodCore are prior distributions and the self.heating_power data member. """ def __init__(self, parent, power): #---+----|----+----|----+----|----+----|----+----|----+----|----+----| """ The MarkovChain constructor makes a copy of the supplied parent object, clones all of the prior ProbabilityDistribution objects in the supplied parent object, and sets self.heating_power to the supplied power. """ LikelihoodCore.__init__(self, parent) self.parent = parent # Note: self.parent is the MCMCImpl object self.boldness = 0.0 self.heating_power = power self.chain_manager = None self.tree_scaler_move = None self.subset_relrates_move = None self.edge_move = None self.unimap_fast_nni_move = None self.unimap_sample_ambig_move = None self.unimap_nni_move = None self.unimap_node_slide_move = None self.unimapping_move = None self.unimap_edge_move = None self.larget_simon_move = None # FLEXCAT_MOVE #self.ncat_move = None self.bush_move = None self.topo_prior_calculator = None self.state_freq_moves = [] self.rel_rate_moves = [] self.all_updaters_list = None self.setupChain() def resetNumLikelihoodEvals(self): #---+----|----+----|----+----|----+----|----+----|----+----|----+----| """ Calls the resetNumLikelihoodEvals function of self.likelihood. This resets the number of likelihood evaluations performed to 0. """ # Note: likelihood data member inherited from LikelihoodCore return self.likelihood.resetNumLikelihoodEvals() def getNumLikelihoodEvals(self): #---+----|----+----|----+----|----+----|----+----|----+----|----+----| """ Calls the getNumLikelihoodEvals function of self.likelihood. This returns the number of likelihood evaluations performed since the last call of resetNumLikelihoodEvals. """ # Note: likelihood data member inherited from LikelihoodCore return self.likelihood.getNumLikelihoodEvals() def paramFileHeader(self, paramf): #---+----|----+----|----+----|----+----|----+----|----+----|----+----| """ Writes the header line at the beginning of the parameter file. The parameter paramf should be an (already open for writing) file object. The parameter file corresponds to the *.p file produced by MrBayes. It begins with a line containing the initial random number seed, followed by a line of column titles for the (tab-delimited) sampled parameter information on the subsequent lines. """ # Note: r data member inherited from LikelihoodCore paramf.write('[ID: %d]\n' % self.r.getInitSeed()) if self.parent.opts.doing_steppingstone_sampling: paramf.write('Gen\tbeta\tlnL\tlnPrior') else: paramf.write('Gen\tlnL\tlnPrior') if self.parent.opts.doing_steppingstone_sampling and not self.parent.opts.ssobj.ti: paramf.write('\tlnRefDens') # If the user has defined a reference tree, add a column for the Robinson-Foulds # distance between the sampled tree and the reference tree if self.parent.ref_tree is not None: paramf.write('\tdRF') # If using a model that allows polytomies, include a column indicating the # resolution class of the tree if self.parent.opts.allow_polytomies: paramf.write('\tResClass') paramf.write('\tTL') if self.parent.opts.fix_topology: nbrlens = self.tree.getNNodes() - 1 for i in range(nbrlens): paramf.write('\tbrlen%d' % (i+1)) self.parent.output('\nKey to the edges (preorder traversal):\n%s' % self.tree.keyToEdges()) nmodels = self.partition_model.getNumSubsets() if nmodels > 1: for i in range(nmodels): paramf.write('\tm_%d' % (i+1,)) for i in range(nmodels): m = self.partition_model.getModel(i) paramf.write(m.paramHeader()) def treeFileHeader(self, treef): #---+----|----+----|----+----|----+----|----+----|----+----|----+----| """ Writes the header line at the beginning of the tree file. The parameter treef should be an (already open for writing) file object. The tree file corresponds to the *.t file produced by MrBayes, and is in NEXUS format. This function writes the opening "#NEXUS" line, a comment containing the initial random number seed, and the beginning of a NEXUS TREES block, including the TRANSLATE command. """ treef.write('#NEXUS\n') treef.write('[ID: %d]\n' % self.r.getInitSeed()) treef.write('begin trees;\n') if self.parent.ntax > 0: treef.write('\ttranslate\n') for i in range(self.parent.ntax): if self.parent.taxon_labels[i].find(' ') < 0: # no spaces found in name treef.write('\t\t%d %s%s\n' % (i + 1, self.parent.taxon_labels[i], i == self.parent.ntax - 1 and ';' or ',')) else: # at least one space in taxon name, so enclose name in quotes treef.write("\t\t%d '%s'%s\n" % (i + 1, self.parent.taxon_labels[i], i == self.parent.ntax - 1 and ';' or ',')) def setPower(self, power): #---+----|----+----|----+----|----+----|----+----|----+----|----+----| """ Sets the heating_power data member and calls the setPower method for every updater so that all updaters are immediately informed that the power for this chain has changed. """ self.heating_power = power for updater in self.chain_manager.getAllUpdaters(): updater.setPower(power) def setBoldness(self, boldness): #---+----|----+----|----+----|----+----|----+----|----+----|----+----| """ Sets the boldness data member and calls the setBoldness method for every updater so that all updaters are immediately informed that the boldness for this chain has changed. The boldness is a value from 0 to 100 that specifies the boldness of Metropolis-Hastings moves. Setting the boldness has no effect on slice sampling based updaters. Each move class defines what is meant by boldness. The boldness is changed during an MCMC run in some circumstances, such as during a path sampling analysis where the target distribution changes during the run. """ self.boldness = boldness for updater in self.chain_manager.getAllUpdaters(): updater.setBoldness(boldness) def setupChain(self): #---+----|----+----|----+----|----+----|----+----|----+----|----+----| """ The setupChain method prepares a MarkovChain object before an MCMC analysis is started. This method is called at the end of the MarkovChain constructor. The duties performed include: 1) calling the base class setupCore method; 2) preparing the starting tree by adding data structures needed for computing likelihood (transition matrices and conditional likelihood arrays); 3) setting up prior distributions for model parameters; 4) creating an MCMCManager object and adding all relevant updaters to it; and 5) makes sure each updater knows the type of heating and the power. """ LikelihoodCore.setupCore(self) from phycas import partition,model if self.parent.opts.partition.noData(): self.likelihood.setNoData() LikelihoodCore.prepareForLikelihood(self) self.python_only_moves = [] # add priors to models already added (by LikelihoodCore.setupCore) to partition_model modelspecs = partition.getModels() # partition here refers to the global object (associated with the Phycas partition command) print 'modelspecs has length %d:' % len(modelspecs) nmodels = self.partition_model.getNumSubsets() if nmodels == 1: print 'partition_model contains 1 model (i.e. unpartitioned)' else: print 'partition_model contains %d models' % nmodels self.chain_manager = Likelihood.MCMCChainManager() for i in range(nmodels): # get the Model (as defined in likelihood_models.cpp) associated with partition subset i m = self.partition_model.getModel(i) # get the model specification (defined in Model.py) stored in (Python) partition object mspec = modelspecs[i] #implemented = not (self.parent.opts.fix_topology and mspec.edgelen_hyperprior is not None) #self.parent.phycassert(implemented, 'Cannot currently specify an edge length hyperprior and fix the topology at the same time') # Copy priors related to edge lengths # Note: while these priors are copied for every subset, only those for the # first subset are actually used (at this writing, 31 Jan 2010) because both # tree topology and edge lengths are always (at this writing) linked across subsets # POLPY_NEWWAY // no touch separate_edge_len_dists = mspec.separate_edgelen_hyper # else #separate_edge_len_dists = mspec.internal_edgelen_prior is not mspec.external_edgelen_prior #raw_input('separate_edge_len_dists = %s' % (separate_edge_len_dists and 'yes' or 'no')) m.separateInternalExternalEdgeLenPriors(separate_edge_len_dists) if mspec.external_edgelen_prior is not None: m.setExternalEdgeLenPrior(mspec.external_edgelen_prior.cloneAndSetLot(self.r)) if mspec.internal_edgelen_prior is not None: m.setInternalEdgeLenPrior(mspec.internal_edgelen_prior.cloneAndSetLot(self.r)) if mspec.edgelen_hyperprior is not None: m.setEdgeLenHyperPrior(mspec.edgelen_hyperprior.cloneAndSetLot(self.r)) if mspec.fix_edgelen_hyperparam: m.fixEdgeLenHyperprior() #@POL should be named fixEdgeLenHyperparam else: m.setEdgeLenHyperPrior(None) # Copy priors for this model's parameters if mspec.type == 'codon': m.setKappaPrior(mspec.kappa_prior.cloneAndSetLot(self.r)) m.setOmegaPrior(mspec.omega_prior.cloneAndSetLot(self.r)) if mspec.update_freqs_separately: m.setStateFreqParamPrior(mspec.state_freq_param_prior.cloneAndSetLot(self.r)) else: m.setStateFreqPrior(mspec.state_freq_prior.cloneAndSetLot(self.r)) elif mspec.type == 'gtr': if mspec.update_relrates_separately: m.setRelRateParamPrior(mspec.relrate_param_prior.cloneAndSetLot(self.r)) else: self.parent.phycassert(mspec.relrate_prior.getDistName() == 'Dirichlet', 'mspec.relrate_prior must be of type Dirichlet') m.setRelRatePrior(mspec.relrate_prior) if mspec.update_freqs_separately: m.setStateFreqParamPrior(mspec.state_freq_param_prior.cloneAndSetLot(self.r)) else: self.parent.phycassert(mspec.state_freq_prior.getDistName() == 'Dirichlet', 'mspec.state_freq_prior must be of type Dirichlet') m.setStateFreqPrior(mspec.state_freq_prior.cloneAndSetLot(self.r)) elif mspec.type == 'hky': m.setKappaPrior(mspec.kappa_prior.cloneAndSetLot(self.r)) if mspec.update_freqs_separately: m.setStateFreqParamPrior(mspec.state_freq_param_prior.cloneAndSetLot(self.r)) else: m.setStateFreqPrior(mspec.state_freq_prior.cloneAndSetLot(self.r)) # Copy priors related to among-site rate heterogeneity if mspec.num_rates > 1: m.setDiscreteGammaShapePrior(mspec.gamma_shape_prior.cloneAndSetLot(self.r)) if mspec.pinvar_model: m.setPinvarPrior(mspec.pinvar_prior.cloneAndSetLot(self.r)) # If user specifies fixed tree topology, make each edge length a separate parameter; otherwise, use edge length master parameters if self.parent.opts.fix_topology: m.setEdgeSpecificParams(True) else: m.setEdgeSpecificParams(False) # Add all necessary updaters to the MCMCManager if nmodels == 1: subset_pos = -1 else: subset_pos = i self.chain_manager.addMCMCUpdaters( m, # substitution model self.tree, # tree self.likelihood, # likelihood calculation machinery self.r, # pseudorandom number generator #False, # separate_edgelen_params (separate_edgelen_params is now True only if topology is fixed) self.parent.opts.slice_max_units, # maximum number of slice units allowed self.parent.opts.slice_weight, # weight for each parameter added subset_pos) # i is the subset (needed so that add edge length params will only be added for for first subset) if self.parent.opts.doing_steppingstone_sampling: self.chain_manager.setMinSSWPSampleSize(self.parent.opts.ssobj.minsample) # Add subset-model-specific moves if not mspec.type == 'jc' and not mspec.update_freqs_separately: # Create a StateFreqMove to update entire state frequency vector sfm = Likelihood.StateFreqMove() if mspec.type == 'codon': sfm.setDimension(61) else: sfm.setDimension(4) if nmodels > 1: sfm.setName("state_freqs_%d" % (i+1,)) else: sfm.setName("state_freqs") sfm.setWeight(self.parent.opts.state_freq_weight) sfm.setPosteriorTuningParam(self.parent.opts.state_freq_psi) sfm.setPriorTuningParam(self.parent.opts.state_freq_psi0) sfm.setTree(self.tree) sfm.setModel(m) sfm.setTreeLikelihood(self.likelihood) sfm.setLot(self.r) if m.stateFreqsFixed(): sfm.fixParameter() sfm.setMultivarPrior(mspec.state_freq_prior.cloneAndSetLot(self.r)) self.chain_manager.addMove(sfm) self.state_freq_moves.append(sfm) if mspec.type == 'gtr' and not mspec.update_relrates_separately: # Create a RelRateMove to update entire relative rates vector rrm = Likelihood.RelRatesMove() if nmodels > 1: rrm.setName("relrates_%d" % (i+1,)) else: rrm.setName("relrates") rrm.setWeight(self.parent.opts.rel_rate_weight) rrm.setPosteriorTuningParam(self.parent.opts.rel_rate_psi) rrm.setPriorTuningParam(self.parent.opts.rel_rate_psi0) rrm.setTree(self.tree) rrm.setModel(m) rrm.setTreeLikelihood(self.likelihood) rrm.setLot(self.r) #if self.model.relRatesFixed(): # rrm.fixParameter() rrm.setMultivarPrior(mspec.relrate_prior.cloneAndSetLot(self.r)) self.chain_manager.addMove(rrm) self.rel_rate_moves.append(rrm) self.likelihood.replaceModel(self.partition_model) if self.parent.opts.data_source is None: self.likelihood.setNoData() # user apparently wants to run MCMC with no data model0 = self.partition_model.getModel(0) # Create a TreeScalerMove object to handle scaling the entire tree to allow faster # convergence in edge lengths. This move is unusual in using slice sampling rather # than Metropolis-Hastings updates: most "moves" in parent are Metropolis-Hastings. if self.parent.opts.tree_scaler_weight > 0: self.tree_scaler_move = Likelihood.TreeScalerMove() self.tree_scaler_move.setName("tree_scaler") self.tree_scaler_move.setWeight(self.parent.opts.tree_scaler_weight) self.tree_scaler_move.setPosteriorTuningParam(self.parent.opts.tree_scaler_lambda) self.tree_scaler_move.setPriorTuningParam(self.parent.opts.tree_scaler_lambda0) self.tree_scaler_move.setTree(self.tree) self.tree_scaler_move.setModel(model0) self.tree_scaler_move.setTreeLikelihood(self.likelihood) self.tree_scaler_move.setLot(self.r) if model0.edgeLengthsFixed(): self.tree_scaler_move.fixParameter() self.chain_manager.addMove(self.tree_scaler_move) # If more than one partition subset, add a SubsetRelRate move to modify the # vector of relative substitution rates for each subset if (nmodels > 1): self.subset_relrates_move = Likelihood.SubsetRelRatesMove() self.subset_relrates_move.setDimension(nmodels) self.subset_relrates_move.setName("subset_relrates") self.subset_relrates_move.setWeight(self.parent.opts.subset_relrates_weight) self.subset_relrates_move.setPosteriorTuningParam(self.parent.opts.subset_relrates_psi) self.subset_relrates_move.setPriorTuningParam(self.parent.opts.subset_relrates_psi0) self.subset_relrates_move.setTree(self.tree) self.subset_relrates_move.setModel(None) # the model data member is ignored in this case; instead, the partition model stores the parameters self.subset_relrates_move.setPartitionModel(self.partition_model) self.subset_relrates_move.setTreeLikelihood(self.likelihood) self.subset_relrates_move.setLot(self.r) subset_proportions = partition.getSubsetProportions() self.subset_relrates_move.setSubsetProportions(subset_proportions) if partition.fix_subset_relrates: self.subset_relrates_move.fixParameter() else: self.subset_relrates_move.freeParameter() # only assign a prior distribution if subset relative rates are not fixed if partition.subset_relrates_prior is None: param_list = tuple([1.0]*nmodels) d = ProbDist.RelativeRateDistribution(param_list) d.setCoefficients(subset_proportions) self.subset_relrates_move.setMultivarPrior(d.cloneAndSetLot(self.r)) self.partition_model.setSubsetRelRatePrior(d.cloneAndSetLot(self.r)) else: self.parent.phycassert(partition.subset_relrates_prior.getDistName() == 'RelativeRateDistribution', 'partition.subset_relrates_prior must be of type RelativeRateDistribution') self.parent.phycassert(partition.subset_relrates_prior.getNParams() == nmodels, 'partition.subset_relrates_prior has dimension %d, but there are %d subsets in the partition. Try setting partion.subset_relrates_prior = None to get default flat Dirichlet prior of the appropriate dimension' % (partition.subset_relrates_prior.getNParams(), nmodels)) partition.subset_relrates_prior.setCoefficients(subset_proportions) self.subset_relrates_move.setMultivarPrior(partition.subset_relrates_prior.cloneAndSetLot(self.r)) self.partition_model.setSubsetRelRatePrior(partition.subset_relrates_prior.cloneAndSetLot(self.r)) self.chain_manager.addMove(self.subset_relrates_move) #OLDWAY #if self.parent.opts.fix_topology: # # Create an EdgeMove object to handle Metropolis-Hastings # # updates to the edge lengths only (does not change the topology) # self.edge_move = Likelihood.EdgeMove() # self.edge_move.setName("edge_move") # self.edge_move.setWeight(self.parent.opts.edge_move_weight) # self.edge_move.setPosteriorTuningParam(self.parent.opts.edge_move_lambda) # self.edge_move.setPriorTuningParam(self.parent.opts.edge_move_lambda0) # self.edge_move.setTree(self.tree) # self.edge_move.setModel(model0) # self.edge_move.setTreeLikelihood(self.likelihood) # self.edge_move.setLot(self.r) # self.edge_move.setLambda(self.parent.opts.edge_move_lambda) # if model0.edgeLengthsFixed(): # self.edge_move.fixParameter() # self.chain_manager.addMove(self.edge_move) if self.parent.opts.use_unimap: if False: # Create a UnimapFastNNIMove (replaces LargetSimonMove for unimap analyses) self.unimap_fast_nni_move = Likelihood.UnimapFastNNIMove() self.unimap_fast_nni_move.setName("unimap_fastNNI_move") self.unimap_fast_nni_move.setWeight(self.parent.opts.unimap_fast_nni_move_weight) self.unimap_fast_nni_move.setTree(self.tree) self.unimap_fast_nni_move.setModel(model0) self.unimap_fast_nni_move.setTreeLikelihood(self.likelihood) self.unimap_fast_nni_move.setLot(self.r) self.chain_manager.addMove(self.unimap_fast_nni_move) # Create a UnimapSampleAmbigMove wt = self.parent.opts.unimap_sample_ambig_move_weight self.unimap_sample_ambig_move = Likelihood.UnimapSampleAmbigMove(self.likelihood, self.tree, wt) self.unimap_sample_ambig_move.setName("unimap_sample_ambig_move") num_ambig = self.unimap_sample_ambig_move.getNumAmbigNodes() if num_ambig > 0: if wt > 0.0: self.unimap_sample_ambig_move.setLot(self.r) self.chain_manager.addMove(self.unimap_sample_ambig_move) else: self.parent.phycassert(False, "unimap_sample_ambig_move_weight was set to 0, but %d ambiguous leaves were found" % num_ambig) # Create a UnimapLSMove (replaces LargetSimonMove for unimap analyses) if self.parent.opts.unimap_thread_count > 1 and (self.parent.opts.unimap_ls_move_weight > 0): self.unimap_spreader_move = UnimapSpreadingWrapper(self) self.python_only_moves.append((self.unimap_spreader_move, self.parent.opts.unimap_ls_move_weight)) #self.chain_manager.addMove(self.unimap_spreader_move) else: # Create a UnimapLSMove (replaces LargetSimonMove for unimap analyses) self.unimap_ls_move = Likelihood.UnimapLSMove(self.likelihood) self.unimap_ls_move.setName("unimap_LS_move") self.unimap_ls_move.setWeight(self.parent.opts.unimap_ls_move_weight) self.unimap_ls_move.setTree(self.tree) self.unimap_ls_move.setModel(model0) self.unimap_ls_move.setLot(self.r) self.chain_manager.addMove(self.unimap_ls_move) # Create a UnimapNNIMove (replaces LargetSimonMove for unimap analyses) self.unimap_nni_move = Likelihood.UnimapNNIMove(self.likelihood) self.unimap_nni_move.setName("unimap_NNI_move") self.unimap_nni_move.setWeight(self.parent.opts.unimap_nni_move_weight) self.unimap_nni_move.setTree(self.tree) self.unimap_nni_move.setModel(model0) self.unimap_nni_move.setLot(self.r) self.chain_manager.addMove(self.unimap_nni_move) # Create a UnimapNodeSlideMove (replaces LargetSimonMove for unimap analyses) self.unimap_node_slide_move = Likelihood.UnimapNodeSlideMove(self.likelihood) self.unimap_node_slide_move.setName("unimap_nodeslide_move") self.unimap_node_slide_move.setWeight(self.parent.opts.unimap_node_slide_move_weight) self.unimap_node_slide_move.setTree(self.tree) self.unimap_node_slide_move.setModel(model0) self.unimap_node_slide_move.setLot(self.r) self.chain_manager.addMove(self.unimap_node_slide_move) # Create a MappingMove (to refresh the mapping for all sites) self.unimapping_move = Likelihood.MappingMove() self.unimapping_move.setName("univent_mapping_move") self.unimapping_move.setWeight(self.parent.opts.mapping_move_weight) self.unimapping_move.setTree(self.tree) self.unimapping_move.setModel(model0) self.unimapping_move.setTreeLikelihood(self.likelihood) self.unimapping_move.setLot(self.r) self.chain_manager.addMove(self.unimapping_move) # Create a UnimapEdgeMove object to handle Metropolis-Hastings # updates to the edge lengths only (does not change the topology) self.unimap_edge_move = Likelihood.UnimapEdgeMove() self.unimap_edge_move.setName("unimap_edge_length_move") self.unimap_edge_move.setWeight(self.parent.opts.unimap_edge_move_weight) self.unimap_edge_move.setPosteriorTuningParam(self.parent.opts.unimap_edge_move_lambda) self.unimap_edge_move.setPriorTuningParam(self.parent.opts.unimap_edge_move_lambda0) self.unimap_edge_move.setTree(self.tree) self.unimap_edge_move.setModel(model0) self.unimap_edge_move.setTreeLikelihood(self.likelihood) self.unimap_edge_move.setLot(self.r) self.unimap_edge_move.setLambda(self.parent.opts.unimap_edge_move_lambda) if model0.edgeLengthsFixed(): self.unimap_edge_move.fixParameter() self.chain_manager.addMove(self.unimap_edge_move) elif not self.parent.opts.fix_topology: # Create a LargetSimonMove object to handle Metropolis-Hastings # updates to the tree topology and edge lengths self.larget_simon_move = Likelihood.LargetSimonMove() self.larget_simon_move.setName("larget_simon_local") self.larget_simon_move.setWeight(self.parent.opts.ls_move_weight) self.larget_simon_move.setPosteriorTuningParam(self.parent.opts.ls_move_lambda) self.larget_simon_move.setPriorTuningParam(self.parent.opts.ls_move_lambda0) self.larget_simon_move.setTree(self.tree) self.larget_simon_move.setModel(model0) self.larget_simon_move.setTreeLikelihood(self.likelihood) self.larget_simon_move.setLot(self.r) self.larget_simon_move.setLambda(self.parent.opts.ls_move_lambda) if model0.edgeLengthsFixed(): self.larget_simon_move.fixParameter() self.chain_manager.addMove(self.larget_simon_move) # If requested, create a BushMove object to allow polytomous trees if self.parent.opts.allow_polytomies: # Create a BushMove object self.bush_move = Likelihood.BushMove() # Set up the topology prior self.topo_prior_calculator = self.bush_move.getPolytomyTopoPriorCalculator() self.topo_prior_calculator.chooseUnrooted() self.topo_prior_calculator.setC(self.parent.opts.topo_prior_C) if self.parent.opts.polytomy_prior: self.topo_prior_calculator.choosePolytomyPrior() else: self.topo_prior_calculator.chooseResolutionClassPrior() # Continue setting up BushMove object self.bush_move.setName("bush_move") self.bush_move.setWeight(self.parent.opts.bush_move_weight) self.bush_move.setTree(self.tree) self.bush_move.setModel(model0) self.bush_move.setTreeLikelihood(self.likelihood) self.bush_move.setLot(self.r) self.bush_move.setEdgeLenDistMean(self.parent.opts.bush_move_edgelen_mean) #self.bush_move.viewProposedMove(self.parent.bush_move_debug) if model0.edgeLengthsFixed(): self.bush_move.fixParameter() self.bush_move.finalize() self.chain_manager.addMove(self.bush_move) self.chain_manager.finalize() if self.parent.opts.use_unimap: if num_ambig > 0: self.unimap_sample_ambig_move.sampleTipsAsDisconnected() self.likelihood.fullRemapping(self.tree, self.r, True) # Calculate relative rates if among-site rate heterogeneity is part of the model # Currently, the unnormalized rates are stored in the model; the function call # below normalizes the rate means and probabilities so that they will be accurately # recorded in the first line of the parameter file self.likelihood.recalcRelativeRates() # Make sure each updater knows the heating power and heating type # and set boldness to 0 for each updater (0% boldness is the default, # with more boldness used only in steppingstone sampling where bolder # moves are needed as the influence of the likelihood is progressively # diminished) for updater in self.chain_manager.getAllUpdaters(): updater.setPower(self.heating_power) updater.setBoldness(0.0) if self.parent.opts.ss_heating_likelihood: updater.setLikelihoodHeating() else: updater.setStandardHeating()
UTF-8
Python
false
false
2,012
6,038,724,042,505
401a54e1fa0e3324634513fb77f058341a028ee3
ec54c06d268e7f4fdaac2764136203d924faf25e
/src/stuff/lowT.py
8913aa25df9c2616e755e364110b16ca9da060f5
[ "GPL-2.0-only" ]
non_permissive
gertingold/Casimir
https://github.com/gertingold/Casimir
6f39da282cc0f456b3d76f8ad2fcca9db2a223c7
05ab501a96867ee96600fe87f2a5cbcec31a2fbb
refs/heads/master
2021-01-15T21:45:02.986853
2014-06-30T18:42:11
2014-06-30T18:42:11
14,795,039
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python from __future__ import division import numpy as np from math import * from scipy.special import gamma def lnfac(x): return lgamma(1+x) def Xi(l1, l2, m): return (-1)**l2* exp( (log(2*l1+1)+log(2*l2+1)-lnfac(l1-m)-lnfac(l2-m)-lnfac(l1+m)-lnfac(l2+m)-log(l1)-log(l1+1)-log(l2)-log(l2+1))/2 +lnfac(2*l1)+lnfac(2*l2)+lnfac(l1+l2)-log(4)*(2*l1+l2+1)-lnfac(l1-1)-lnfac(l2-1) ) def logdet1m(M): logdet = 0 w,v = np.linalg.eig(M) for lambda_i in w: lambda_i = complex(lambda_i) logdet += 0.5*log1p( -2*lambda_i.real+lambda_i.real**2 + (lambda_i.imag)**2 ) return logdet def a0(l): return pi*(-1)**l*( 2*gamma(l+1.5)-l*gamma(l+0.5) )/( l*gamma(l+0.5)**2*gamma(l+1.5) ) def b0(l): return pi*(-1)**(l+1)/( gamma(l+0.5)*gamma(l+1.5) ) def Lambda(l1,l2,m): return -sqrt( (2*l1+1)*(2*l2+1)/(l1*l2*(l1+1)*(l2+1)) ) * sqrt( exp(lgamma(l1-m+1)+lgamma(l2-m+1)-lgamma(l1+m+1)-lgamma(l2+m+1)) ) def D(l1,l2,m,nT): return C(l2,l1,m,nT) def C(l1,l2,m,nT): return exp(-2*nT)*m*(-1)**l2*Lambda(l1,l2,m)*( gamma(1+2*l1)*gamma(1+2*l2)*gamma(l1+l2) )/( 2**(l1+l2)*(2*nT)**(l1+l2)*gamma(1+l1)*gamma(l2)*gamma(1+l1-m)*gamma(1+l2-m) ) def B(l1,l2,m,nT): return exp(-2*nT)*(-1)**(l2+1)*Lambda(l1,l2,m)*( gamma(1+2*l1)*gamma(1+2*l2)*gamma(1+l1+l2) )/( 2**(l1+l2)*(2*nT)**(l1+l2+1)*gamma(l1)*gamma(l2)*gamma(1+l1-m)*gamma(1+l2-m) ); def logdetM(n, m, q, T, lmax): minimum = max(m,1) maximum = lmax dim = maximum-minimum+1 if n == 0: EE = np.zeros((dim,dim)) MM = np.zeros((dim,dim)) for l1 in range(minimum, maximum+1): for l2 in range(minimum, maximum+1): XiRL = Xi(l1,l2,m)*q**(2*l1+1) EE[l1-minimum][l2-minimum] = +a0(l1)*XiRL MM[l1-minimum][l2-minimum] = -b0(l1)*XiRL return logdet1m(EE)+logdet1m(MM); else: M = np.zeros((2*dim,2*dim)) for l1 in range(minimum, maximum+1): for l2 in range(minimum, maximum+1): intB = B(l1,l2,m,n*T) intC = C(l1,l2,m,n*T) intD = D(l1,l2,m,n*T) f = (q*n*T/2)**(2*l1+1) M[ l1-minimum][ l2-minimum] = +a0(l1)*f*intB # M_EE M[dim+l1-minimum][dim+l2-minimum] = -b0(l1)*f*intB # M_MM M[dim+l1-minimum][ l2-minimum] = +a0(l1)*f*(intD-intC) # M_EM M[ l1-minimum][dim+l2-minimum] = +b0(l1)*f*(intD-intC) # - M_ME return logdet1m(M) def Fn(n,q,T,lmax): sum_n = 0 for m in range(lmax+1): value = logdetM(n,m,q,T,lmax) if m == 0: value /= 2 sum_n += value if n == 0: sum0 = sum_n sum_n /= 2 return sum_n def F(q,T,lmax): sum = sum0 = Fn(0,q,T,lmax) n = 1 while True: sum_n = Fn(n,q,T,lmax) sum += sum_n n += 1 print n*T if abs(sum_n/sum0) < 1e-6: return T*sum/pi q = 0.5 lmax = 3 T = 1e-3 print T, F(q,T,lmax)
UTF-8
Python
false
false
2,014
18,030,272,711,278
53d8f2a33e9368ba5b709a4b164f7b1664d57400
5a69a1229e4a1ea3f314810c647ab166cf6d721b
/test_bar.py
45e99e49091daef1347ebbd2faed8393d911e327
[]
no_license
DanteYu/learn_python_the_hard_way
https://github.com/DanteYu/learn_python_the_hard_way
ebb6f83643fae134160d220fab5db09957f452e2
2006fa75d9b90f41cbaedd2e4a8d8938695f122f
refs/heads/master
2016-08-04T21:47:05.077207
2014-05-02T12:53:18
2014-05-02T12:53:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! /usr/bin/env python import unittest import bar class BarTestCase(unittest.TestCase): def test_bar_func(self): self.assertTrue(bar.Testfunc(),msg="THEY ARE NOT EUQAL") if __name__ == '__main__': unittest.main()
UTF-8
Python
false
false
2,014
13,340,168,430,447
699c770bf1c6a77db0d88edc1b6f6366411658a7
3bb7b4264de76e0164e00986604125cdf79b223a
/jugades.py
a48c83a5846fb0f03179ad53ed9d84e97731cb86
[]
no_license
beldar/scrabblebabel
https://github.com/beldar/scrabblebabel
0cb4c9edc13d569ea2262554fe3a37ae0702304a
69199ad5e06b9072affa066b549ece4d0c4dab26
refs/heads/master
2021-01-17T22:20:48.909641
2012-03-30T15:45:09
2012-03-30T15:45:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import board b = board.Board() b.play("atras",(7,4),(7,8)) b.play("sara",(7,8),(10,8)) b
UTF-8
Python
false
false
2,012
10,849,087,404,942
1fa1c2aec0eebb6b6fc959a7b5ffe065ed2db723
580824fec14e621d40a03ffc282bc3ca924a55f5
/satchless/__init__.py
94fdc749782984230c55fbe2344783d30c5f5124
[ "BSD-2-Clause" ]
permissive
jackscott/satchless
https://github.com/jackscott/satchless
7249df217c4255a66d33855e8ee1a0455e3fa4b9
991221e3696ca9a574f78424a780e90d8903660b
refs/heads/master
2021-01-16T18:32:43.979234
2014-03-20T07:45:07
2014-03-20T07:48:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Satchless An e-commerce framework for Python """ import logging from . import process from . import item from . import cart __all__ = ['cart', 'item', 'process'] class SatchlessBaseError(Exception): """Base Exception class :note: This will try to use the logging module :param message: the Exception message :type message: str :param data: Used to format the message string """ def __init__(self, message, data=None): try: message = message % data except: pass # log the message using the class name logging.getLogger( self.__class__.__name__ ).exception( message ) Exception.__init__(self, message) class SatchlessBaseClass(object): """Base class used throughout satchless """ ArgsError = SatchlessBaseError KwargsError = SatchlessBaseError ParamError = SatchlessBaseError LOG = None def logit(self, message, level=logging.DEBUG): """Write `message` to logging :param message: String to send :param level: Desired log level (Default: logging.DEBUG) :raises: satchless.SBase.ParamError """ if not self.LOG: # use subclass name, not SBase self.LOG = getLogger( self.__class__.__name__ ) try: getattr( self.LOG, level )(message) except: raise ParamError("could not find level (%s) in self.LOG" % level)
UTF-8
Python
false
false
2,014
7,687,991,486,985
50365dfc06393327853deaacfa32952c005b877a
7067cffb99b4adbedc3f82b519744452498d6317
/kakao/kakao_auth/auth.py
9dbc0b34486079d4b5f7a674d1086bad35740ef9
[]
no_license
joke111/MealMenuBot
https://github.com/joke111/MealMenuBot
1ac0ea95948f353b3a0c43a0b324b0c263831910
6215307a654ee0cf9a3fdd95da03a58907d0c512
refs/heads/master
2020-06-02T22:35:24.611554
2014-07-14T00:15:44
2014-07-14T00:15:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import requests import json import hashlib import sys import base64 import config import sys import os sys.path.append(os.path.abspath("../kakao_status")) from response_status import KakaoResponseStatus class KakaoAuth: def __init__(self): self.__initialize_session_key() self.__initialize_url() self.__initialize_data() self.__initialize_header() def __initialize_session_key(self): self.__session_key = "" def __initialize_url(self): self.__url = {} self.__url["LOGIN_URL"] = "https://sb-talk.kakao.com/api/v1/sub_device/login" def __initialize_data(self): self.__data = {} self.__data["email"] = config.USER["EMAIL"] self.__data["password"] = config.USER["PASSWORD"] self.__data["name"] = config.USER["NAME"] self.__data["auto_login"] = False self.__data["device_uuid"] = self.__generate_device_uuid() def __initialize_header(self): self.__headers = {} self.__headers["A"] = "mac/0.9.0/ko" self.__headers["Accept"] = "application/json" self.__headers["Accept-Language"] = "ko" self.__headers["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8" self.__headers["User-Agent"] = "KT/0.9.0 Mc/10.9 ko" self.__headers["X-VC"] = self.__generate_x_vc_token() def auth(self): self.__send_auth_request() print (self.get_user_key()) print ("auth_request success") def __send_auth_request(self): request = requests.post(self.__url["LOGIN_URL"], data=self.__data, headers=self.__headers) response = json.loads(request.text) if (KakaoResponseStatus().is_registration_required(response["status"])): self.__do_auth_request_registration() self.__do_auth_accept_registration() elif (KakaoResponseStatus().is_request_success(response["status"])): self.__set_session_key(response["sessionKey"]) else: print (response) print ("error auth_request") sys.exit() def __do_auth_request_registration(self): self.__data["once"] = False request = requests.post(self.__url["LOGIN_URL"], data=self.__data, headers=self.__headers) response = json.loads(request.text) if (not KakaoResponseStatus().is_request_success(response["status"])): print (response) print ("error auth_request_registration") sys.exit() def __do_auth_accept_registration(self): self.__data["forced"] = False self.__data["passcode"] = input("input passcode: ") request = requests.post(self.__url["LOGIN_URL"], data=self.__data, headers=self.__headers) response = json.loads(request.text) if (KakaoResponseStatus().is_request_success(response["status"])): self.__set_session_key(response["sessionKey"]) print ("auth_accept_registration success") else: print (response) print ("error auth_accept_registration") sys.exit() def get_session_key(self): return self.__session_key def get_user_key(self): return self.__session_key + "-" + self.__data["device_uuid"] def __set_session_key(self, session_key): self.__session_key = session_key def __generate_x_vc_token(self): #Change "NITSUA" and "HSOJ" if kakao version is updated #0.9.0 = JOSH, AUSTIN #0.9.1 = NITSUA, HSOJ x_vc = "JOSH|" + self.__headers["User-Agent"] + "|AUSTIN|" + self.__data["email"] + "|" + self.__data["device_uuid"] x_vc = x_vc.encode("UTF-8") hashed_x_vc = hashlib.sha512(x_vc).hexdigest() return hashed_x_vc[:16] def __generate_device_uuid(self): device_uuid = config.USER["DEVICE_UUID"].encode("UTF-8") sha1_hashed_device_uuid = hashlib.sha1(device_uuid).digest() sha256_hashed_device_uuid = hashlib.sha256(device_uuid).digest() return base64.b64encode(sha1_hashed_device_uuid + sha256_hashed_device_uuid).decode("UTF-8")
UTF-8
Python
false
false
2,014
8,873,402,466,246
78068a4258e7d281e1e5e60d03646cdd506a6c8c
665fd7e53648189946c73e7a9f50c2b1bc98e179
/src/dbmanage.py
a4ceb1311ba5c45169814177e31aeb20004a61ea
[ "GPL-2.0-only" ]
non_permissive
asymworks/python-divelog
https://github.com/asymworks/python-divelog
b93bfc6b940ef493a6ac281152a99551196fe3d0
5ca81e7cbe558092410ab98cca053946e24e9e27
refs/heads/master
2016-09-16T06:01:35.419248
2011-06-21T03:11:25
2011-06-21T03:11:25
1,899,779
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python from migrate.versioning.shell import main main(debug='False', repository='divelog/db/migrations')
UTF-8
Python
false
false
2,011
5,334,349,384,102
71ef0b520f4aa4ce40aedd90b343a0c250e57664
a4c8215e29b32e2d9d9cbc57fd56db71abcad21f
/posts/models.py
e7d002e37f4c9c6ea534e304841bbd74768554aa
[]
no_license
mdamien/legoit
https://github.com/mdamien/legoit
3aa9cd889a2aba316f3a588b1032139d941ac7e7
81f602bb6055be64990d550afccc4baa2130c399
refs/heads/master
2021-01-21T11:45:16.995221
2014-03-17T04:41:00
2014-03-17T04:41:00
17,783,262
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db import models from django_extensions.db.fields import json import markdown, re def parse_comment(text): return markdown.markdown(text, safe_mode='remove') class Post(models.Model): submission = json.JSONField() parent = json.JSONField() comment = json.JSONField() created = models.IntegerField() def comment_to_html(self): return parse_comment(self.comment.get('body'), display_images=True) def comment_img_src(self): match = re.search('http://.*\.jpg', self.comment.get('body')) if match: return match.group() def parent_as_title(self): if self.parent.get('body') != self.comment.get('body'): return parse_comment(self.parent.get('body')) else: return self.submission.get('title') def is_simple_image_post(self): return self.comment_img_src() is not None def get_context_url(self): link = self.submission.get('permalink') comment_id = self.comment.get('id')#.split('_')[1] return "http://reddit.com/{}/{}/?context=2".format(link,comment_id) def __str__(self): return "%s -> %s" % (self.parent.get('body'), self.comment.get('body')) class Meta: ordering = ('-created',)
UTF-8
Python
false
false
2,014
13,108,240,222,542
c633d7cfbd3bfc81971b43b4b4dc28c6fe2138f8
6ceaefa85cce2ae5983ca69879cb84034a6580a7
/minmax_tree.py
0bc3bce0f38766e5f23f6bfd500a01283a1e1360
[]
no_license
mateusduboli/ia-projeto-1
https://github.com/mateusduboli/ia-projeto-1
7c971b5dda56d8c117a66eb8039b53304fa04ecb
39bf87d385f8211629ef645f61bb9deaf84ddbb5
refs/heads/master
2016-09-05T09:21:45.095284
2013-04-16T23:25:36
2013-04-16T23:25:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from random import shuffle class MinmaxTree( object ): def __init__( self, obj_func, depth ): self.depth = depth self.obj_func = obj_func self.value = float( "-Inf" ) self.order = range( 7 ) shuffle( self.order ) def build( self, game ): self.value = self.__rec_build( game, 0, True, float( "-Inf" ), float( "Inf" ) ) print self.value, self.move def __rec_build( self, game, depth, is_max, alpha, beta ): if depth >= self.depth or game.has_ended(): obj_value = self.obj_func( game ) return obj_value n_alpha = alpha n_beta = beta move = -1 state = game if is_max : obj_value = float( "-inf" ) else: obj_value = float( "inf" ) temp_obj_value = obj_value for i in self.order : new_game = game.copy() x, y = new_game.drop_disc( i ) if not ( ( x, y ) == ( -1, -1 ) ): new_state = new_game new_obj_value = self.__rec_build( new_game, depth + 1, not is_max, n_alpha, n_beta ) if is_max: n_alpha = max( n_alpha, new_obj_value ) temp_obj_value = max( obj_value, new_obj_value ) else : n_beta = min( n_beta, new_obj_value ) temp_obj_value = min( obj_value, new_obj_value ) if temp_obj_value <> obj_value: obj_value = temp_obj_value move = i if n_alpha >= n_beta: break self.move = move return obj_value def __str__( self ): return str( self.root ) def __repr__( self ): return str( self )
UTF-8
Python
false
false
2,013
5,102,421,192,597
77b74a233caa0459e48d793935eb85d2bbbbb722
793fae70e87a4914923d2938f1bf2875352c9a51
/cjkcodecs/tests/testall.py
4aad33600776e9a7d4f970d988864583f90d9914
[ "BSD-2-Clause" ]
permissive
BackupTheBerlios/cjkpython
https://github.com/BackupTheBerlios/cjkpython
63bcad9670943c7d058154b4f83c0ae412568196
16b7f2be8a71ebad2512de1fb3bb4aad760cb38a
refs/heads/master
2020-06-07T00:32:20.432891
2004-08-21T01:04:05
2004-08-21T01:04:05
40,040,041
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # # testall.py # Run all unittests. # # $Id: testall.py,v 1.3 2004/06/19 06:09:55 perky Exp $ import sys import os, unittest from test import test_support def findtests(testdir='.'): tests = [] for name in os.listdir(testdir): if (name.startswith('test_') and name.endswith('.py') and not name.endswith('support.py')): tests.append(name[:-3]) return tests def loadtests(test): mod = __import__(test, globals(), locals(), []) return unittest.findTestCases(mod) def main(): suite = unittest.TestSuite() for test in findtests(): try: suite.addTest(loadtests(test)) except test_support.TestSkipped, msg: print "%s - skipped: %s" % (test, msg) test_support.run_suite(suite) if __name__ == '__main__': main()
UTF-8
Python
false
false
2,004
5,823,975,668,018
09936aedd93d5ccba15c9ef9bbbbaaf29c9053ec
52bcc86627af891908eb827300cdda4ce3c26bfe
/apps/journals/migrations/0023_auto__add_evaluationimage__add_evaluation__add_evaluationattachment__a.py
d13ba48587866237a4e74e66d06ef05d41618968
[]
no_license
jamiecurle/reflection
https://github.com/jamiecurle/reflection
4518e2a0e982bdd00bc60f33dda903485be2ef3f
8665ab07ebc6c1ec0e77a86e5b7605dad3d19a75
refs/heads/master
2021-01-22T06:58:46.838301
2011-04-05T04:24:59
2011-04-05T04:24:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'EvaluationImage' db.create_table('journals_evaluationimage', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('evaluation', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['journals.Evaluation'])), ('src', self.gf('apps.utils.fields.ImageWithThumbsField')(null=True)), ('order', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=10)), )) db.send_create_signal('journals', ['EvaluationImage']) # Adding model 'Evaluation' db.create_table('journals_evaluation', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('title', self.gf('django.db.models.fields.CharField')(max_length=255)), ('content', self.gf('django.db.models.fields.TextField')()), ('action', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['journals.Action'], unique=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])), ('created_on', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2011, 3, 3, 15, 10, 8, 22979), auto_now_add=True, blank=True)), ('modified_on', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2011, 3, 3, 15, 10, 8, 23097), auto_now=True, blank=True)), )) db.send_create_signal('journals', ['Evaluation']) # Adding model 'EvaluationAttachment' db.create_table('journals_evaluationattachment', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('evaluation', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['journals.Evaluation'])), ('src', self.gf('django.db.models.fields.files.FileField')(max_length=100, null=True, blank=True)), ('order', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=10)), )) db.send_create_signal('journals', ['EvaluationAttachment']) # Adding field 'Action.status' db.add_column('journals_action', 'status', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=0), keep_default=False) def backwards(self, orm): # Deleting model 'EvaluationImage' db.delete_table('journals_evaluationimage') # Deleting model 'Evaluation' db.delete_table('journals_evaluation') # Deleting model 'EvaluationAttachment' db.delete_table('journals_evaluationattachment') # Deleting field 'Action.status' db.delete_column('journals_action', 'status') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'journals.action': { 'Meta': {'object_name': 'Action'}, 'created_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2011, 3, 3, 15, 10, 8, 71565)', 'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2011, 3, 3, 15, 10, 8, 71685)', 'auto_now': 'True', 'blank': 'True'}), 'research': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['journals.Research']", 'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'journals.evaluation': { 'Meta': {'object_name': 'Evaluation'}, 'action': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['journals.Action']", 'unique': 'True'}), 'content': ('django.db.models.fields.TextField', [], {}), 'created_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2011, 3, 3, 15, 10, 8, 75494)', 'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2011, 3, 3, 15, 10, 8, 75612)', 'auto_now': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'journals.evaluationattachment': { 'Meta': {'ordering': "['order']", 'object_name': 'EvaluationAttachment'}, 'evaluation': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['journals.Evaluation']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'order': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '10'}), 'src': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}) }, 'journals.evaluationimage': { 'Meta': {'ordering': "['order']", 'object_name': 'EvaluationImage'}, 'evaluation': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['journals.Evaluation']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'order': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '10'}), 'src': ('apps.utils.fields.ImageWithThumbsField', [], {'null': 'True'}) }, 'journals.issue': { 'Meta': {'object_name': 'Issue'}, 'addressed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'content': ('django.db.models.fields.TextField', [], {}), 'created_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2011, 3, 3, 15, 10, 8, 76724)', 'auto_now_add': 'True', 'blank': 'True'}), 'external': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2011, 3, 3, 15, 10, 8, 76848)', 'auto_now': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'journals.question': { 'Meta': {'object_name': 'Question'}, 'answered': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'content': ('django.db.models.fields.TextField', [], {}), 'created_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2011, 3, 3, 15, 10, 8, 69873)', 'auto_now_add': 'True', 'blank': 'True'}), 'external': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2011, 3, 3, 15, 10, 8, 69996)', 'auto_now': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'journals.reflection': { 'Meta': {'ordering': "['-created_on']", 'object_name': 'Reflection'}, 'action': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['journals.Action']", 'null': 'True', 'blank': 'True'}), 'content': ('django.db.models.fields.TextField', [], {}), 'created_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.date(2011, 3, 3)', 'auto_now_add': 'True', 'blank': 'True'}), 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.date(2011, 3, 3)', 'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'journals.research': { 'Meta': {'object_name': 'Research'}, 'created_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2011, 3, 3, 15, 10, 8, 73033)', 'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'issues': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['journals.Issue']", 'null': 'True', 'blank': 'True'}), 'modified_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2011, 3, 3, 15, 10, 8, 73153)', 'auto_now': 'True', 'blank': 'True'}), 'questions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['journals.Question']", 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'journals.researchattachment': { 'Meta': {'ordering': "['order']", 'object_name': 'ResearchAttachment'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'order': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '10'}), 'research': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['journals.Research']"}), 'src': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}) }, 'journals.researchimage': { 'Meta': {'ordering': "['order']", 'object_name': 'ResearchImage'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'order': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '10'}), 'research': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['journals.Research']"}), 'src': ('apps.utils.fields.ImageWithThumbsField', [], {'null': 'True'}) }, 'journals.thought': { 'Meta': {'ordering': "['-created_on']", 'object_name': 'Thought'}, 'content': ('django.db.models.fields.TextField', [], {}), 'created_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.date(2011, 3, 3)', 'auto_now_add': 'True', 'blank': 'True'}), 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.date(2011, 3, 3)', 'auto_now': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'taggit.tag': { 'Meta': {'object_name': 'Tag'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}) }, 'taggit.taggeditem': { 'Meta': {'object_name': 'TaggedItem'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_tagged_items'", 'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_items'", 'to': "orm['taggit.Tag']"}) } } complete_apps = ['journals']
UTF-8
Python
false
false
2,011
10,376,641,023,383
76c795414ffcf82205f2bfced68d72a2b9e862d6
3519e91220798b791150352b100d4bb75f5f5132
/share/gespeak/lib/gespeak/GeSpeakClass.py
381f06f8b3b8a75070b1dd5230f6e78228153b52
[ "GPL-3.0-only" ]
non_permissive
InFog/GeSpeak
https://github.com/InFog/GeSpeak
f9c96df1d874692cf723c9b71dc6bfa52269dfb4
49c4d82f3a138ac1fec3655df3572ab8def0d45a
refs/heads/master
2021-01-23T12:16:42.888043
2009-12-07T00:52:40
2009-12-07T00:52:40
10,092,522
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# GeSpeakClass.py # # This file is part of the GeSpeak project # http://gespeak.googlecode.com # # Copyright 2009 Evaldo Junior (InFog) <junior@casoft.info> # # 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, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # import sys import os import commands import string import ConfigParser __doc__ = """ This is the main module of GeSpeak In this file is the GeSpeak class which is the one that calls eSpeak with the arguments from the GTK interface """ __author__="GeSpeak Team" class GeSpeak: __doc__ = """ This is the GeSpeak class it's mainly function is to call eSpeak with the arguments from the GTK interface But it also controls the preferences file which contains some options about de user interface """ def __init__(self): """ This is the constructor of the GeSpeak class """ self.version = "0.4" self.espeak = "" # variable containing eSpeak's bin if self.pre_setup() == 0: self.load_prefs() self.load_langs() else: return 1 def exit(self): """ This function saves the preferences file and terminates GeSpeak """ conf_file = open(self.__gespeak_conf_file, 'w') conf_text = [] conf_text.append("[gespeak]\n") conf_text.append("amplitude = %i\n" % self.__amplitude) conf_text.append("pitch = %i\n" % self.__pitch) conf_text.append("speed = %i\n" % self.__speed) conf_text.append("language = %s\n" % self.__language) conf_file.writelines(conf_text) conf_file.close() def pre_setup(self): """ This function searches for the eSpeak binary and the conf dir of GeSpeak (~/.gespeak) If the eSpeak binary isn't istalled then the value 1 is returned. If the conf dir isn't created then it will be created. If everything is okay then it returns 0 """ self.espeak = commands.getoutput("which espeak") self.espeak = str(self.espeak) if (self.espeak != ""): return 0 else: print("eSpeak not found!") return 1 def load_prefs(self): """ This function reads the preferences from the prefs file ~/.gespeak/gespeak.xml If the preferences file don't exists it will be created """ self.__amplitude = 10 self.__pitch = 30 self.__speed = 70 self.__language = "en-us" self.__voice = "Male" self.__wavfile = "" gespeak_dir = os.environ["HOME"] + "/.gespeak" if (os.path.exists(gespeak_dir) == False) : os.mkdir(gespeak_dir) self.__gespeak_conf_file = gespeak_dir + "/gespeak.conf" if (os.path.exists(self.__gespeak_conf_file) == False) : conf_file = open(self.__gespeak_conf_file, 'w') conf_text = [] conf_text.append("[gespeak]\n") conf_text.append("amplitude = 10\n") conf_text.append("pitch = 30\n") conf_text.append("speed = 70\n") conf_text.append("language = en-us\n") conf_file.writelines(conf_text) conf_file.close() else: conf_file = ConfigParser.ConfigParser() conf_file.read(self.__gespeak_conf_file) self.__amplitude = int(conf_file.get("gespeak", "amplitude")) self.__pitch = int(conf_file.get("gespeak", "pitch")) self.__speed = int(conf_file.get("gespeak", "speed")) self.__language = conf_file.get("gespeak", "language") def load_langs(self): """ This function gets the languages that espeak supports by reading files and directories under /usr/share/espeak-data/voices """ self.__languages_names = [] languages_files_or_dirs = os.listdir('/usr/share/espeak-data/voices') for file_or_dir in languages_files_or_dirs : if file_or_dir != '!v' and file_or_dir != 'mb' : if os.path.isfile('/usr/share/espeak-data/voices/%s' % file_or_dir) : self.load_language_from_file(lang_file='/usr/share/espeak-data/voices/%s' % file_or_dir) else : languages_sub_files_or_dirs = os.listdir('/usr/share/espeak-data/voices/%s' % file_or_dir) for sub_file_or_dir in languages_sub_files_or_dirs : if os.path.isfile('/usr/share/espeak-data/voices/%s/%s' % (file_or_dir,sub_file_or_dir)) : self.load_language_from_file(lang_file='/usr/share/espeak-data/voices/%s/%s' % (file_or_dir,sub_file_or_dir)) def load_language_from_file(self, lang_file): lfile = open(lang_file, 'r') name_ok = False for line in lfile: if name_ok == False: if line.find('name ') != -1 : name_ok = True self.__languages_names.append(line.split(' ')[1].split('\n')[0]) lfile.close() def get_languages_names(self): """ This functios return a list of languages names supported by espeak """ return self.__languages_names def set_amplitude(self, amplitude): """ This function sets the amplitude Params Amplitude must be an integer betwwn 1 and 20 """ if amplitude > 0 and amplitude <= 20 : self.__amplitude = amplitude def get_amplitude(self): """ This function just returns the amplitude an integer number """ return self.__amplitude def set_pitch(self, pitch): """ this function sets the pitch Params Pitch must be an integer between 1 and 99 """ if pitch > 0 and pitch < 100 : self.__pitch = pitch def get_pitch(self): """ This function just returns the pitch an integer number """ return self.__pitch def set_speed(self, speed): """ this function sets the speed Params Speed must be an integer between 30 and 200 """ if speed >= 30 and speed <= 200 : self.__speed = speed def get_speed(self): """ This function gets the speed an integer number """ return self.__speed def set_language(self, language): """ This functions sets the language Language must be a string in a format supported by espeak Examples: en English pt Portuguese For more information see espeak's manual """ self.__language = language def get_language(self): """ this function gets the language """ return self.__language def set_voice(self, voice): """ This function sets the voice Params An empty string for male "+12" for female Only some languages supports female voice """ self.__voice = voice def get_voice(self): """ this function gets the voice """ return self.__voice def set_wav_file(self, wav_file): """ This function sets the wav file to write output rather than speaking it directly """ self.__wavfile = wav_file def write_wav_file(self, text): """ This function calls to the talk function with the option to write a wav file """ self.talk(text=text, wav=1) def talk(self, text, wav=0): """ This function is called to run espeak with the parameters from UI Params text = The text you want espeak to "talk" Usage: talk("Text to talk") Make sure you have set up all parameters before calling this function """ # A little easter egg if text == '==tell me a story==' : text = self.tell_a_story() speak_this = open("/tmp/speak_this", "w") text = str(text) speak_this.write(text) speak_this.close() espeak_command = self.espeak if (wav == 1): espeak_command += " -w " + self.__wavfile espeak_command += " -a " + str(self.__amplitude) espeak_command += " -v " + self.__language + self.__voice espeak_command += " -s " + str(self.__speed) espeak_command += " -p " + str(self.__pitch) espeak_command += " -f /tmp/speak_this > /dev/null &" os.system(espeak_command) def stop(self): """ This function stops espeak from talking """ os.system("killall espeak > /dev/null &") def tell_a_story(self): story = """ Once time ago, in a seaside city, lived a little girl who loved to play with her parrot. And what a nice parrot it was. She used to sing to the parrot, and he, to yell, so happy was the parrot, because other people didn't like him, but she liked. The parrot really enjoyed the time with the girl. And then the girl grew up and got a boyfriend. The parrot became a little jealous, but the girl always had time to play and sing with him. Some years later the girl got married and left home. The parrot was alone, the girl didn't take the parrot to her new home. The parrot was alone, he didn't sing anymore, he didn't yell anymore... """ return story
UTF-8
Python
false
false
2,009
10,239,202,077,632
0a196846482f1f97ed70df345275ba7a9fd420f9
7b1a88df7534be4a45ccfa01707511df577e57cb
/victor/testing.py
e0b608c4ef69a7e8370e8e19069c5a86d1015414
[ "MIT" ]
permissive
alexph/victor
https://github.com/alexph/victor
3e639f4adb15da8eaadb5087ff3de914804daf26
d7b23761908dc44ba88614f0bf99db1c60e726e9
refs/heads/master
2021-01-15T17:41:26.090521
2014-09-10T09:11:44
2014-09-10T09:11:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from victor import Victor dummy_app = Victor()
UTF-8
Python
false
false
2,014
7,773,890,850,313
71846146f33020b26c4cb6de133d3e02ca67e1cb
45dbbdbdc4e242c88f59b9eb615b5b92df4eacab
/server/utils.py
fb26f94ce6c4db8171f4f2e2471da152e9a5f736
[]
no_license
gdut-library/mars
https://github.com/gdut-library/mars
1328e97081243cec78d801f6fde9a8a2b7a5e254
041a3dfdd84112058bb7c28e79a009977768d1c8
refs/heads/master
2016-09-11T03:24:06.155736
2013-11-01T15:33:24
2013-11-01T15:33:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#coding: utf-8 import time from functools import wraps from contextlib import contextmanager from logging.handlers import SMTPHandler as _SMTPHandler from flask import make_response, request from flask import jsonify as _jsonify import pyisbn from isbn_hyphenate import isbn_hyphenate from server.db import db @contextmanager def ignores(*exceptions): try: yield except exceptions: pass class SMTPHandler(_SMTPHandler): '''SMTP logging handler adapter''' def __init__(self, *args, **kwargs): super(SMTPHandler, self).__init__(*args, **kwargs) self._timeout = 15 # give me more time! def json_view(func): @wraps(func) def allow_CORS(*args, **kwargs): resp = func(*args, **kwargs) #: Handle the different cases of #: http://flask.pocoo.org/docs/quickstart/#about-responses rv = None status = None headers = None if isinstance(resp, tuple): if len(resp) == 3: rv, status, headers = resp else: rv, status = resp else: rv = resp if isinstance(rv, str) or isinstance(rv, unicode): rv = make_response(rv) origin = request.headers.get('Origin', None) if origin: rv.headers.add('Access-Control-Allow-Origin', origin) return rv, status, headers return allow_CORS def jsonify(**kwargs): def dictify(model): return model.__dictify__ for k, v in kwargs.items(): with ignores(AttributeError): if isinstance(v, db.Model): kwargs[k] = dictify(v) elif isinstance(v, list): kwargs[k] = [dictify(i) for i in v] return _jsonify(**kwargs) def error(msg, status_code=500, *args, **kwargs): return jsonify(error=msg, *args, **kwargs), status_code class LogDuration(object): def __init__(self, log, start, end, log_duration=True): self.log = log self.start = start or '' self.end = end or '' self.log_duration = log_duration def __call__(self, func): @wraps(func) def wrapper(*args, **kwargs): start = time.time() self.log(self.start) resp = func(*args, **kwargs) if self.log_duration: self.log(self.end % (time.time() - start)) else: self.log(self.end) return resp return wrapper def parse_isbn(raw): '''将 isbn 转换成 10 / 13 位以及带 hyphen 形式''' a, b = raw, raw isbn = { 'isbn10': raw, 'isbn13': raw, 'isbn10-hyphen': raw, 'isbn13-hyphen': raw } with ignores(pyisbn.IsbnError): a = pyisbn.convert(raw) b = pyisbn.convert(a) isbn = {'isbn%d' % len(i): i for i in [a, b]} with ignores(isbn_hyphenate.IsbnMalformedError): isbn['isbn10-hyphen'] = isbn_hyphenate.hyphenate(isbn['isbn10']) isbn['isbn13-hyphen'] = isbn_hyphenate.hyphenate(isbn['isbn13']) return isbn
UTF-8
Python
false
false
2,013
2,963,527,436,433
53bdc54c70312be31f045dfc49bf4620c03b67b2
ee5a88adcb4b8248d415ee17af6e5969dcaba9ea
/blogger2octopresspage.py
d82fd244b3624ba054f4fe20fcf0b00423326daa
[]
no_license
PyYoshi/blogger2octopresspage
https://github.com/PyYoshi/blogger2octopresspage
92701a45d1b93f12bccada3643a7c7b465ef40d5
922daa7ce1a26a4605c678b0d56cbc3e9cc1a20d
refs/heads/master
2023-06-12T05:59:33.753910
2013-05-06T09:44:12
2013-05-06T09:44:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding:utf8 -*- __author__ = 'PyYoshi' from optparse import OptionParser import os import sys import datetime try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse try: from lxml import etree except ImportError: import xml.etree.cElementTree as etree import jinja2 def isoparse(s): try: return datetime.datetime(int(s[0:4]),int(s[5:7]),int(s[8:10]),int(s[11:13]), int(s[14:16]), int(s[17:19])) except: return None def parse(markup): el = etree.fromstring(markup) entries = [] drafts = [] blog_title = el.find('{http://www.w3.org/2005/Atom}title').text for entry in el.findall('{http://www.w3.org/2005/Atom}entry'): category_type = None categories = [] for category in entry.findall('{http://www.w3.org/2005/Atom}category'): category_tmp = category.get('term') category_tmp_type = category_tmp.split('#') if len(category_tmp_type) == 2: category_type = category_tmp_type[1] else: categories.append(category.get('term')) if category_type == 'post': published = entry.find('{http://www.w3.org/2005/Atom}published') title = entry.find('{http://www.w3.org/2005/Atom}title') content = entry.find('{http://www.w3.org/2005/Atom}content') link = entry.find('{http://www.w3.org/2005/Atom}link[@rel="alternate"]') url = None if link != None: url = link.get('href') permalink = None if url != None: permalink = urlparse(url).path uuid = entry.find('{http://www.w3.org/2005/Atom}id').text.split('-')[-1] d = isoparse(published.text) entry_obj = { 'title' : title.text, 'published' : d, 'content': content.text, 'url' : url, 'uuid' : uuid, 'categories' : categories, 'permalink' : permalink } if url: entries.append(entry_obj) else: drafts.append(entry_obj) return blog_title, entries, drafts def save_file(text, path, encode='utf8'): with open(path, 'wb') as f: f.write(text.encode(encode)) def gen_pages(page_name, entries, drafts, output_dir): post_dir = os.path.join(output_dir, '_post') draft_dir = os.path.join(output_dir, '_draft') if not os.path.exists(post_dir): os.makedirs(post_dir) if not os.path.exists(draft_dir): os.makedirs(draft_dir) with open('templates/page/entry.html', 'r') as f: template_entry_html = f.read() for entry in entries: html = jinja2.Environment().from_string(template_entry_html).render(entry) filename = entry['published'].strftime('%Y-%m-%d-%H-%M-%S') + '_' + entry['permalink'].split('/')[-1] save_file(html,os.path.join(post_dir, filename)) with open('templates/page/index.markdown', 'r') as f: template_index_markdown = f.read() now = datetime.datetime.now() markdown = jinja2.Environment().from_string(template_index_markdown).render(page_name=page_name, entries=entries, date=now.strftime('%Y-%m-%d %H:%M')) save_file(markdown, os.path.join(post_dir, 'index.markdown')) for entry in drafts: html = jinja2.Environment().from_string(template_entry_html).render(entry) filename = entry['published'].strftime('%Y-%m-%d-%H-%M-%S') + '_draft_post.html' save_file(html,os.path.join(draft_dir, filename)) def main(): parser = OptionParser(usage="Usage: python %s <Blogger's xml path>" % os.path.basename(__file__)) parser.add_option('-o', '--output_dir', dest='output', type='string', default='blogger_posts') parser.add_option('-n', '--page_name', dest='page_name', type='string', default='oldblog', help='Page directory name. e.g) rake new_page["old blog"] page_name="old-blog"') options, args = parser.parse_args() if len(args) == 0: parser.print_help() sys.exit() if not os.path.exists(args[0]): parser.print_help() raise Exception('%s can not be found.' % args[0]) with open(args[0], 'rb') as f: markup = f.read() blog_title, entries, drafts = parse(markup) gen_pages(options.page_name, entries, drafts, options.output) if __name__ == '__main__': main() sys.exit()
UTF-8
Python
false
false
2,013
12,859,132,087,582
f864a5f88e225ab7632a6425b9686f03a6c9d83d
a3b306df800059a5b74975793251a28b8a5f49c7
/Graphs/LX-2/molecule_otsu = False/BioImageXD-1.0/ITK/lib/InsightToolkit/WrapITK/lib/itkBinaryThresholdProjectionImageFilterPython.py
c356418e1906b9b8b0135d581fecadfd011fbcaa
[]
no_license
giacomo21/Image-analysis
https://github.com/giacomo21/Image-analysis
dc17ba2b6eb53f48963fad931568576fda4e1349
ea8bafa073de5090bd8f83fb4f5ca16669d0211f
refs/heads/master
2016-09-06T21:42:13.530256
2013-07-22T09:35:56
2013-07-22T09:35:56
11,384,784
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# This file was automatically generated by SWIG (http://www.swig.org). # Version 1.3.40 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info if version_info >= (3,0,0): new_instancemethod = lambda func, inst, cls: _itkBinaryThresholdProjectionImageFilterPython.SWIG_PyInstanceMethod_New(func) else: from new import instancemethod as new_instancemethod if version_info >= (2,6,0): def swig_import_helper(): from os.path import dirname import imp fp = None try: fp, pathname, description = imp.find_module('_itkBinaryThresholdProjectionImageFilterPython', [dirname(__file__)]) except ImportError: import _itkBinaryThresholdProjectionImageFilterPython return _itkBinaryThresholdProjectionImageFilterPython if fp is not None: try: _mod = imp.load_module('_itkBinaryThresholdProjectionImageFilterPython', fp, pathname, description) finally: fp.close() return _mod _itkBinaryThresholdProjectionImageFilterPython = swig_import_helper() del swig_import_helper else: import _itkBinaryThresholdProjectionImageFilterPython del version_info try: _swig_property = property except NameError: pass # Python < 2.2 doesn't have 'property'. def _swig_setattr_nondynamic(self,class_type,name,value,static=1): if (name == "thisown"): return self.this.own(value) if (name == "this"): if type(value).__name__ == 'SwigPyObject': self.__dict__[name] = value return method = class_type.__swig_setmethods__.get(name,None) if method: return method(self,value) if (not static) or hasattr(self,name): self.__dict__[name] = value else: raise AttributeError("You cannot add attributes to %s" % self) def _swig_setattr(self,class_type,name,value): return _swig_setattr_nondynamic(self,class_type,name,value,0) def _swig_getattr(self,class_type,name): if (name == "thisown"): return self.this.own() method = class_type.__swig_getmethods__.get(name,None) if method: return method(self) raise AttributeError(name) def _swig_repr(self): try: strthis = "proxy of " + self.this.__repr__() except: strthis = "" return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) try: _object = object _newclass = 1 except AttributeError: class _object : pass _newclass = 0 def _swig_setattr_nondynamic_method(set): def set_attr(self,name,value): if (name == "thisown"): return self.this.own(value) if hasattr(self,name) or (name == "this"): set(self,name,value) else: raise AttributeError("You cannot add attributes to %s" % self) return set_attr import itkImageToImageFilterBPython import ITKRegionsPython import ITKCommonBasePython import itkEventObjectsPython import pyBasePython import itkSizePython import itkIndexPython import itkOffsetPython import itkImagePython import itkFixedArrayPython import itkCovariantVectorPython import vnl_vectorPython import vcl_complexPython import vnl_matrixPython import itkVectorPython import vnl_vector_refPython import itkPointPython import itkMatrixPython import vnl_matrix_fixedPython import itkRGBAPixelPython import itkSymmetricSecondRankTensorPython import itkRGBPixelPython import itkImageSourcePython import itkVectorImagePython import itkVariableLengthVectorPython import itkImageToImageFilterAPython def itkBinaryThresholdProjectionImageFilterID3ID2_New(): return itkBinaryThresholdProjectionImageFilterID3ID2.New() def itkBinaryThresholdProjectionImageFilterID3ID2_Superclass_New(): return itkBinaryThresholdProjectionImageFilterID3ID2_Superclass.New() def itkBinaryThresholdProjectionImageFilterIF3IF2_New(): return itkBinaryThresholdProjectionImageFilterIF3IF2.New() def itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass_New(): return itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass.New() def itkBinaryThresholdProjectionImageFilterIUS3IUS2_New(): return itkBinaryThresholdProjectionImageFilterIUS3IUS2.New() def itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass_New(): return itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass.New() def itkBinaryThresholdProjectionImageFilterIUL3IUL2_New(): return itkBinaryThresholdProjectionImageFilterIUL3IUL2.New() def itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass_New(): return itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass.New() def itkBinaryThresholdProjectionImageFilterIUC3IUC2_New(): return itkBinaryThresholdProjectionImageFilterIUC3IUC2.New() def itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass_New(): return itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass.New() def itkBinaryThresholdProjectionImageFilterID3ID3_New(): return itkBinaryThresholdProjectionImageFilterID3ID3.New() def itkBinaryThresholdProjectionImageFilterID3ID3_Superclass_New(): return itkBinaryThresholdProjectionImageFilterID3ID3_Superclass.New() def itkBinaryThresholdProjectionImageFilterID2ID2_New(): return itkBinaryThresholdProjectionImageFilterID2ID2.New() def itkBinaryThresholdProjectionImageFilterID2ID2_Superclass_New(): return itkBinaryThresholdProjectionImageFilterID2ID2_Superclass.New() def itkBinaryThresholdProjectionImageFilterIF3IF3_New(): return itkBinaryThresholdProjectionImageFilterIF3IF3.New() def itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass_New(): return itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass.New() def itkBinaryThresholdProjectionImageFilterIF2IF2_New(): return itkBinaryThresholdProjectionImageFilterIF2IF2.New() def itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass_New(): return itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass.New() def itkBinaryThresholdProjectionImageFilterIUS3IUS3_New(): return itkBinaryThresholdProjectionImageFilterIUS3IUS3.New() def itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass_New(): return itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass.New() def itkBinaryThresholdProjectionImageFilterIUS2IUS2_New(): return itkBinaryThresholdProjectionImageFilterIUS2IUS2.New() def itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass_New(): return itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass.New() def itkBinaryThresholdProjectionImageFilterIUL3IUL3_New(): return itkBinaryThresholdProjectionImageFilterIUL3IUL3.New() def itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass_New(): return itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass.New() def itkBinaryThresholdProjectionImageFilterIUL2IUL2_New(): return itkBinaryThresholdProjectionImageFilterIUL2IUL2.New() def itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass_New(): return itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass.New() def itkBinaryThresholdProjectionImageFilterIUC3IUC3_New(): return itkBinaryThresholdProjectionImageFilterIUC3IUC3.New() def itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass_New(): return itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass.New() def itkBinaryThresholdProjectionImageFilterIUC2IUC2_New(): return itkBinaryThresholdProjectionImageFilterIUC2IUC2.New() def itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass_New(): return itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass.New() class itkBinaryThresholdProjectionImageFilterID2ID2_Superclass(itkImageToImageFilterAPython.itkImageToImageFilterID2ID2): """Proxy of C++ itkBinaryThresholdProjectionImageFilterID2ID2_Superclass class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_Superclass_InputImageDimension OutputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_Superclass_OutputImageDimension ImageDimensionCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_Superclass_ImageDimensionCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_Superclass___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetProjectionDimension(self, *args): """SetProjectionDimension(self, unsigned int _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_Superclass_SetProjectionDimension(self, *args) def GetProjectionDimension(self): """GetProjectionDimension(self) -> unsigned int""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_Superclass_GetProjectionDimension(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterID2ID2_Superclass def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterID2ID2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_Superclass_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterID2ID2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_Superclass_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterID2ID2_Superclass Create a new object of the class itkBinaryThresholdProjectionImageFilterID2ID2_Superclass and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterID2ID2_Superclass.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterID2ID2_Superclass.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterID2ID2_Superclass.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterID2ID2_Superclass.SetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_Superclass_SetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterID2ID2_Superclass) itkBinaryThresholdProjectionImageFilterID2ID2_Superclass.GetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_Superclass_GetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterID2ID2_Superclass) itkBinaryThresholdProjectionImageFilterID2ID2_Superclass.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_Superclass_GetPointer,None,itkBinaryThresholdProjectionImageFilterID2ID2_Superclass) itkBinaryThresholdProjectionImageFilterID2ID2_Superclass_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_Superclass_swigregister itkBinaryThresholdProjectionImageFilterID2ID2_Superclass_swigregister(itkBinaryThresholdProjectionImageFilterID2ID2_Superclass) def itkBinaryThresholdProjectionImageFilterID2ID2_Superclass___New_orig__(): """itkBinaryThresholdProjectionImageFilterID2ID2_Superclass___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_Superclass___New_orig__() def itkBinaryThresholdProjectionImageFilterID2ID2_Superclass_cast(*args): """itkBinaryThresholdProjectionImageFilterID2ID2_Superclass_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterID2ID2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_Superclass_cast(*args) class itkBinaryThresholdProjectionImageFilterID3ID2_Superclass(itkImageToImageFilterBPython.itkImageToImageFilterID3ID2): """Proxy of C++ itkBinaryThresholdProjectionImageFilterID3ID2_Superclass class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_Superclass_InputImageDimension OutputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_Superclass_OutputImageDimension ImageDimensionCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_Superclass_ImageDimensionCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_Superclass___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetProjectionDimension(self, *args): """SetProjectionDimension(self, unsigned int _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_Superclass_SetProjectionDimension(self, *args) def GetProjectionDimension(self): """GetProjectionDimension(self) -> unsigned int""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_Superclass_GetProjectionDimension(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterID3ID2_Superclass def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterID3ID2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_Superclass_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterID3ID2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_Superclass_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterID3ID2_Superclass Create a new object of the class itkBinaryThresholdProjectionImageFilterID3ID2_Superclass and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterID3ID2_Superclass.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterID3ID2_Superclass.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterID3ID2_Superclass.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterID3ID2_Superclass.SetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_Superclass_SetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterID3ID2_Superclass) itkBinaryThresholdProjectionImageFilterID3ID2_Superclass.GetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_Superclass_GetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterID3ID2_Superclass) itkBinaryThresholdProjectionImageFilterID3ID2_Superclass.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_Superclass_GetPointer,None,itkBinaryThresholdProjectionImageFilterID3ID2_Superclass) itkBinaryThresholdProjectionImageFilterID3ID2_Superclass_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_Superclass_swigregister itkBinaryThresholdProjectionImageFilterID3ID2_Superclass_swigregister(itkBinaryThresholdProjectionImageFilterID3ID2_Superclass) def itkBinaryThresholdProjectionImageFilterID3ID2_Superclass___New_orig__(): """itkBinaryThresholdProjectionImageFilterID3ID2_Superclass___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_Superclass___New_orig__() def itkBinaryThresholdProjectionImageFilterID3ID2_Superclass_cast(*args): """itkBinaryThresholdProjectionImageFilterID3ID2_Superclass_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterID3ID2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_Superclass_cast(*args) class itkBinaryThresholdProjectionImageFilterID3ID3_Superclass(itkImageToImageFilterAPython.itkImageToImageFilterID3ID3): """Proxy of C++ itkBinaryThresholdProjectionImageFilterID3ID3_Superclass class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_Superclass_InputImageDimension OutputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_Superclass_OutputImageDimension ImageDimensionCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_Superclass_ImageDimensionCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_Superclass___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetProjectionDimension(self, *args): """SetProjectionDimension(self, unsigned int _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_Superclass_SetProjectionDimension(self, *args) def GetProjectionDimension(self): """GetProjectionDimension(self) -> unsigned int""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_Superclass_GetProjectionDimension(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterID3ID3_Superclass def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterID3ID3_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_Superclass_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterID3ID3_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_Superclass_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterID3ID3_Superclass Create a new object of the class itkBinaryThresholdProjectionImageFilterID3ID3_Superclass and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterID3ID3_Superclass.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterID3ID3_Superclass.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterID3ID3_Superclass.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterID3ID3_Superclass.SetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_Superclass_SetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterID3ID3_Superclass) itkBinaryThresholdProjectionImageFilterID3ID3_Superclass.GetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_Superclass_GetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterID3ID3_Superclass) itkBinaryThresholdProjectionImageFilterID3ID3_Superclass.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_Superclass_GetPointer,None,itkBinaryThresholdProjectionImageFilterID3ID3_Superclass) itkBinaryThresholdProjectionImageFilterID3ID3_Superclass_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_Superclass_swigregister itkBinaryThresholdProjectionImageFilterID3ID3_Superclass_swigregister(itkBinaryThresholdProjectionImageFilterID3ID3_Superclass) def itkBinaryThresholdProjectionImageFilterID3ID3_Superclass___New_orig__(): """itkBinaryThresholdProjectionImageFilterID3ID3_Superclass___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_Superclass___New_orig__() def itkBinaryThresholdProjectionImageFilterID3ID3_Superclass_cast(*args): """itkBinaryThresholdProjectionImageFilterID3ID3_Superclass_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterID3ID3_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_Superclass_cast(*args) class itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass(itkImageToImageFilterAPython.itkImageToImageFilterIF2IF2): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass_InputImageDimension OutputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass_OutputImageDimension ImageDimensionCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass_ImageDimensionCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetProjectionDimension(self, *args): """SetProjectionDimension(self, unsigned int _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass_SetProjectionDimension(self, *args) def GetProjectionDimension(self): """GetProjectionDimension(self) -> unsigned int""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass_GetProjectionDimension(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass Create a new object of the class itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass.SetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass_SetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass) itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass.GetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass_GetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass) itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass_GetPointer,None,itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass) itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass_swigregister itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass_swigregister(itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass) def itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass___New_orig__(): """itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass___New_orig__() def itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass_cast(*args): """itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass_cast(*args) class itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass(itkImageToImageFilterBPython.itkImageToImageFilterIF3IF2): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass_InputImageDimension OutputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass_OutputImageDimension ImageDimensionCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass_ImageDimensionCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetProjectionDimension(self, *args): """SetProjectionDimension(self, unsigned int _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass_SetProjectionDimension(self, *args) def GetProjectionDimension(self): """GetProjectionDimension(self) -> unsigned int""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass_GetProjectionDimension(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass Create a new object of the class itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass.SetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass_SetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass) itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass.GetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass_GetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass) itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass_GetPointer,None,itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass) itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass_swigregister itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass_swigregister(itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass) def itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass___New_orig__(): """itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass___New_orig__() def itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass_cast(*args): """itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass_cast(*args) class itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass(itkImageToImageFilterAPython.itkImageToImageFilterIF3IF3): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass_InputImageDimension OutputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass_OutputImageDimension ImageDimensionCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass_ImageDimensionCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetProjectionDimension(self, *args): """SetProjectionDimension(self, unsigned int _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass_SetProjectionDimension(self, *args) def GetProjectionDimension(self): """GetProjectionDimension(self) -> unsigned int""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass_GetProjectionDimension(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass Create a new object of the class itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass.SetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass_SetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass) itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass.GetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass_GetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass) itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass_GetPointer,None,itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass) itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass_swigregister itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass_swigregister(itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass) def itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass___New_orig__(): """itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass___New_orig__() def itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass_cast(*args): """itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass_cast(*args) class itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass(itkImageToImageFilterAPython.itkImageToImageFilterIUC2IUC2): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass_InputImageDimension OutputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass_OutputImageDimension ImageDimensionCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass_ImageDimensionCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetProjectionDimension(self, *args): """SetProjectionDimension(self, unsigned int _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass_SetProjectionDimension(self, *args) def GetProjectionDimension(self): """GetProjectionDimension(self) -> unsigned int""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass_GetProjectionDimension(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass Create a new object of the class itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass.SetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass_SetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass) itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass.GetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass_GetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass) itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass_GetPointer,None,itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass) itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass_swigregister itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass_swigregister(itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass) def itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass___New_orig__(): """itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass___New_orig__() def itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass_cast(*args): """itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass_cast(*args) class itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass(itkImageToImageFilterBPython.itkImageToImageFilterIUC3IUC2): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass_InputImageDimension OutputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass_OutputImageDimension ImageDimensionCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass_ImageDimensionCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetProjectionDimension(self, *args): """SetProjectionDimension(self, unsigned int _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass_SetProjectionDimension(self, *args) def GetProjectionDimension(self): """GetProjectionDimension(self) -> unsigned int""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass_GetProjectionDimension(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass Create a new object of the class itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass.SetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass_SetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass) itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass.GetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass_GetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass) itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass_GetPointer,None,itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass) itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass_swigregister itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass_swigregister(itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass) def itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass___New_orig__(): """itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass___New_orig__() def itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass_cast(*args): """itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass_cast(*args) class itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass(itkImageToImageFilterAPython.itkImageToImageFilterIUC3IUC3): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass_InputImageDimension OutputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass_OutputImageDimension ImageDimensionCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass_ImageDimensionCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetProjectionDimension(self, *args): """SetProjectionDimension(self, unsigned int _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass_SetProjectionDimension(self, *args) def GetProjectionDimension(self): """GetProjectionDimension(self) -> unsigned int""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass_GetProjectionDimension(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass Create a new object of the class itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass.SetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass_SetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass) itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass.GetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass_GetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass) itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass_GetPointer,None,itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass) itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass_swigregister itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass_swigregister(itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass) def itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass___New_orig__(): """itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass___New_orig__() def itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass_cast(*args): """itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass_cast(*args) class itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass(itkImageToImageFilterAPython.itkImageToImageFilterIUL2IUL2): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass_InputImageDimension OutputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass_OutputImageDimension ImageDimensionCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass_ImageDimensionCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetProjectionDimension(self, *args): """SetProjectionDimension(self, unsigned int _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass_SetProjectionDimension(self, *args) def GetProjectionDimension(self): """GetProjectionDimension(self) -> unsigned int""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass_GetProjectionDimension(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass Create a new object of the class itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass.SetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass_SetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass) itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass.GetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass_GetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass) itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass_GetPointer,None,itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass) itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass_swigregister itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass_swigregister(itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass) def itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass___New_orig__(): """itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass___New_orig__() def itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass_cast(*args): """itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass_cast(*args) class itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass(itkImageToImageFilterBPython.itkImageToImageFilterIUL3IUL2): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass_InputImageDimension OutputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass_OutputImageDimension ImageDimensionCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass_ImageDimensionCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetProjectionDimension(self, *args): """SetProjectionDimension(self, unsigned int _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass_SetProjectionDimension(self, *args) def GetProjectionDimension(self): """GetProjectionDimension(self) -> unsigned int""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass_GetProjectionDimension(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass Create a new object of the class itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass.SetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass_SetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass) itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass.GetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass_GetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass) itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass_GetPointer,None,itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass) itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass_swigregister itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass_swigregister(itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass) def itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass___New_orig__(): """itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass___New_orig__() def itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass_cast(*args): """itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass_cast(*args) class itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass(itkImageToImageFilterAPython.itkImageToImageFilterIUL3IUL3): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass_InputImageDimension OutputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass_OutputImageDimension ImageDimensionCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass_ImageDimensionCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetProjectionDimension(self, *args): """SetProjectionDimension(self, unsigned int _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass_SetProjectionDimension(self, *args) def GetProjectionDimension(self): """GetProjectionDimension(self) -> unsigned int""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass_GetProjectionDimension(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass Create a new object of the class itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass.SetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass_SetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass) itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass.GetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass_GetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass) itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass_GetPointer,None,itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass) itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass_swigregister itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass_swigregister(itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass) def itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass___New_orig__(): """itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass___New_orig__() def itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass_cast(*args): """itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass_cast(*args) class itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass(itkImageToImageFilterAPython.itkImageToImageFilterIUS2IUS2): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass_InputImageDimension OutputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass_OutputImageDimension ImageDimensionCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass_ImageDimensionCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetProjectionDimension(self, *args): """SetProjectionDimension(self, unsigned int _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass_SetProjectionDimension(self, *args) def GetProjectionDimension(self): """GetProjectionDimension(self) -> unsigned int""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass_GetProjectionDimension(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass Create a new object of the class itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass.SetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass_SetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass) itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass.GetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass_GetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass) itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass_GetPointer,None,itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass) itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass_swigregister itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass_swigregister(itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass) def itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass___New_orig__(): """itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass___New_orig__() def itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass_cast(*args): """itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass_cast(*args) class itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass(itkImageToImageFilterBPython.itkImageToImageFilterIUS3IUS2): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass_InputImageDimension OutputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass_OutputImageDimension ImageDimensionCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass_ImageDimensionCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetProjectionDimension(self, *args): """SetProjectionDimension(self, unsigned int _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass_SetProjectionDimension(self, *args) def GetProjectionDimension(self): """GetProjectionDimension(self) -> unsigned int""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass_GetProjectionDimension(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass Create a new object of the class itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass.SetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass_SetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass) itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass.GetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass_GetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass) itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass_GetPointer,None,itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass) itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass_swigregister itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass_swigregister(itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass) def itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass___New_orig__(): """itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass___New_orig__() def itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass_cast(*args): """itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass_cast(*args) class itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass(itkImageToImageFilterAPython.itkImageToImageFilterIUS3IUS3): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass_InputImageDimension OutputImageDimension = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass_OutputImageDimension ImageDimensionCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass_ImageDimensionCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetProjectionDimension(self, *args): """SetProjectionDimension(self, unsigned int _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass_SetProjectionDimension(self, *args) def GetProjectionDimension(self): """GetProjectionDimension(self) -> unsigned int""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass_GetProjectionDimension(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass Create a new object of the class itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass.SetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass_SetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass) itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass.GetProjectionDimension = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass_GetProjectionDimension,None,itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass) itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass_GetPointer,None,itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass) itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass_swigregister itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass_swigregister(itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass) def itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass___New_orig__(): """itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass___New_orig__() def itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass_cast(*args): """itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass_cast(*args) class itkBinaryThresholdProjectionImageFilterID2ID2(itkBinaryThresholdProjectionImageFilterID2ID2_Superclass): """Proxy of C++ itkBinaryThresholdProjectionImageFilterID2ID2 class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputPixelTypeGreaterThanComparable = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_InputPixelTypeGreaterThanComparable InputHasNumericTraitsCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_InputHasNumericTraitsCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetForegroundValue(self, *args): """SetForegroundValue(self, double _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_SetForegroundValue(self, *args) def GetForegroundValue(self): """GetForegroundValue(self) -> double""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_GetForegroundValue(self) def SetBackgroundValue(self, *args): """SetBackgroundValue(self, double _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_SetBackgroundValue(self, *args) def GetBackgroundValue(self): """GetBackgroundValue(self) -> double""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_GetBackgroundValue(self) def SetThresholdValue(self, *args): """SetThresholdValue(self, double _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_SetThresholdValue(self, *args) def GetThresholdValue(self): """GetThresholdValue(self) -> double""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_GetThresholdValue(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterID2ID2 def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterID2ID2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterID2ID2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterID2ID2 Create a new object of the class itkBinaryThresholdProjectionImageFilterID2ID2 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterID2ID2.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterID2ID2.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterID2ID2.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterID2ID2.SetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_SetForegroundValue,None,itkBinaryThresholdProjectionImageFilterID2ID2) itkBinaryThresholdProjectionImageFilterID2ID2.GetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_GetForegroundValue,None,itkBinaryThresholdProjectionImageFilterID2ID2) itkBinaryThresholdProjectionImageFilterID2ID2.SetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_SetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterID2ID2) itkBinaryThresholdProjectionImageFilterID2ID2.GetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_GetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterID2ID2) itkBinaryThresholdProjectionImageFilterID2ID2.SetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_SetThresholdValue,None,itkBinaryThresholdProjectionImageFilterID2ID2) itkBinaryThresholdProjectionImageFilterID2ID2.GetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_GetThresholdValue,None,itkBinaryThresholdProjectionImageFilterID2ID2) itkBinaryThresholdProjectionImageFilterID2ID2.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_GetPointer,None,itkBinaryThresholdProjectionImageFilterID2ID2) itkBinaryThresholdProjectionImageFilterID2ID2_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_swigregister itkBinaryThresholdProjectionImageFilterID2ID2_swigregister(itkBinaryThresholdProjectionImageFilterID2ID2) def itkBinaryThresholdProjectionImageFilterID2ID2___New_orig__(): """itkBinaryThresholdProjectionImageFilterID2ID2___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2___New_orig__() def itkBinaryThresholdProjectionImageFilterID2ID2_cast(*args): """itkBinaryThresholdProjectionImageFilterID2ID2_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterID2ID2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID2ID2_cast(*args) class itkBinaryThresholdProjectionImageFilterID3ID2(itkBinaryThresholdProjectionImageFilterID3ID2_Superclass): """Proxy of C++ itkBinaryThresholdProjectionImageFilterID3ID2 class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputPixelTypeGreaterThanComparable = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_InputPixelTypeGreaterThanComparable InputHasNumericTraitsCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_InputHasNumericTraitsCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetForegroundValue(self, *args): """SetForegroundValue(self, double _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_SetForegroundValue(self, *args) def GetForegroundValue(self): """GetForegroundValue(self) -> double""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_GetForegroundValue(self) def SetBackgroundValue(self, *args): """SetBackgroundValue(self, double _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_SetBackgroundValue(self, *args) def GetBackgroundValue(self): """GetBackgroundValue(self) -> double""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_GetBackgroundValue(self) def SetThresholdValue(self, *args): """SetThresholdValue(self, double _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_SetThresholdValue(self, *args) def GetThresholdValue(self): """GetThresholdValue(self) -> double""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_GetThresholdValue(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterID3ID2 def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterID3ID2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterID3ID2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterID3ID2 Create a new object of the class itkBinaryThresholdProjectionImageFilterID3ID2 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterID3ID2.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterID3ID2.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterID3ID2.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterID3ID2.SetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_SetForegroundValue,None,itkBinaryThresholdProjectionImageFilterID3ID2) itkBinaryThresholdProjectionImageFilterID3ID2.GetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_GetForegroundValue,None,itkBinaryThresholdProjectionImageFilterID3ID2) itkBinaryThresholdProjectionImageFilterID3ID2.SetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_SetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterID3ID2) itkBinaryThresholdProjectionImageFilterID3ID2.GetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_GetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterID3ID2) itkBinaryThresholdProjectionImageFilterID3ID2.SetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_SetThresholdValue,None,itkBinaryThresholdProjectionImageFilterID3ID2) itkBinaryThresholdProjectionImageFilterID3ID2.GetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_GetThresholdValue,None,itkBinaryThresholdProjectionImageFilterID3ID2) itkBinaryThresholdProjectionImageFilterID3ID2.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_GetPointer,None,itkBinaryThresholdProjectionImageFilterID3ID2) itkBinaryThresholdProjectionImageFilterID3ID2_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_swigregister itkBinaryThresholdProjectionImageFilterID3ID2_swigregister(itkBinaryThresholdProjectionImageFilterID3ID2) def itkBinaryThresholdProjectionImageFilterID3ID2___New_orig__(): """itkBinaryThresholdProjectionImageFilterID3ID2___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2___New_orig__() def itkBinaryThresholdProjectionImageFilterID3ID2_cast(*args): """itkBinaryThresholdProjectionImageFilterID3ID2_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterID3ID2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID2_cast(*args) class itkBinaryThresholdProjectionImageFilterID3ID3(itkBinaryThresholdProjectionImageFilterID3ID3_Superclass): """Proxy of C++ itkBinaryThresholdProjectionImageFilterID3ID3 class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputPixelTypeGreaterThanComparable = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_InputPixelTypeGreaterThanComparable InputHasNumericTraitsCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_InputHasNumericTraitsCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetForegroundValue(self, *args): """SetForegroundValue(self, double _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_SetForegroundValue(self, *args) def GetForegroundValue(self): """GetForegroundValue(self) -> double""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_GetForegroundValue(self) def SetBackgroundValue(self, *args): """SetBackgroundValue(self, double _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_SetBackgroundValue(self, *args) def GetBackgroundValue(self): """GetBackgroundValue(self) -> double""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_GetBackgroundValue(self) def SetThresholdValue(self, *args): """SetThresholdValue(self, double _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_SetThresholdValue(self, *args) def GetThresholdValue(self): """GetThresholdValue(self) -> double""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_GetThresholdValue(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterID3ID3 def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterID3ID3""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterID3ID3""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterID3ID3 Create a new object of the class itkBinaryThresholdProjectionImageFilterID3ID3 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterID3ID3.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterID3ID3.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterID3ID3.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterID3ID3.SetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_SetForegroundValue,None,itkBinaryThresholdProjectionImageFilterID3ID3) itkBinaryThresholdProjectionImageFilterID3ID3.GetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_GetForegroundValue,None,itkBinaryThresholdProjectionImageFilterID3ID3) itkBinaryThresholdProjectionImageFilterID3ID3.SetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_SetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterID3ID3) itkBinaryThresholdProjectionImageFilterID3ID3.GetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_GetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterID3ID3) itkBinaryThresholdProjectionImageFilterID3ID3.SetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_SetThresholdValue,None,itkBinaryThresholdProjectionImageFilterID3ID3) itkBinaryThresholdProjectionImageFilterID3ID3.GetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_GetThresholdValue,None,itkBinaryThresholdProjectionImageFilterID3ID3) itkBinaryThresholdProjectionImageFilterID3ID3.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_GetPointer,None,itkBinaryThresholdProjectionImageFilterID3ID3) itkBinaryThresholdProjectionImageFilterID3ID3_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_swigregister itkBinaryThresholdProjectionImageFilterID3ID3_swigregister(itkBinaryThresholdProjectionImageFilterID3ID3) def itkBinaryThresholdProjectionImageFilterID3ID3___New_orig__(): """itkBinaryThresholdProjectionImageFilterID3ID3___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3___New_orig__() def itkBinaryThresholdProjectionImageFilterID3ID3_cast(*args): """itkBinaryThresholdProjectionImageFilterID3ID3_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterID3ID3""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterID3ID3_cast(*args) class itkBinaryThresholdProjectionImageFilterIF2IF2(itkBinaryThresholdProjectionImageFilterIF2IF2_Superclass): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIF2IF2 class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputPixelTypeGreaterThanComparable = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_InputPixelTypeGreaterThanComparable InputHasNumericTraitsCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_InputHasNumericTraitsCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetForegroundValue(self, *args): """SetForegroundValue(self, float _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_SetForegroundValue(self, *args) def GetForegroundValue(self): """GetForegroundValue(self) -> float""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_GetForegroundValue(self) def SetBackgroundValue(self, *args): """SetBackgroundValue(self, float _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_SetBackgroundValue(self, *args) def GetBackgroundValue(self): """GetBackgroundValue(self) -> float""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_GetBackgroundValue(self) def SetThresholdValue(self, *args): """SetThresholdValue(self, float _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_SetThresholdValue(self, *args) def GetThresholdValue(self): """GetThresholdValue(self) -> float""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_GetThresholdValue(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIF2IF2 def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIF2IF2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIF2IF2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIF2IF2 Create a new object of the class itkBinaryThresholdProjectionImageFilterIF2IF2 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIF2IF2.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIF2IF2.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIF2IF2.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIF2IF2.SetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_SetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIF2IF2) itkBinaryThresholdProjectionImageFilterIF2IF2.GetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_GetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIF2IF2) itkBinaryThresholdProjectionImageFilterIF2IF2.SetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_SetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIF2IF2) itkBinaryThresholdProjectionImageFilterIF2IF2.GetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_GetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIF2IF2) itkBinaryThresholdProjectionImageFilterIF2IF2.SetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_SetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIF2IF2) itkBinaryThresholdProjectionImageFilterIF2IF2.GetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_GetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIF2IF2) itkBinaryThresholdProjectionImageFilterIF2IF2.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_GetPointer,None,itkBinaryThresholdProjectionImageFilterIF2IF2) itkBinaryThresholdProjectionImageFilterIF2IF2_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_swigregister itkBinaryThresholdProjectionImageFilterIF2IF2_swigregister(itkBinaryThresholdProjectionImageFilterIF2IF2) def itkBinaryThresholdProjectionImageFilterIF2IF2___New_orig__(): """itkBinaryThresholdProjectionImageFilterIF2IF2___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2___New_orig__() def itkBinaryThresholdProjectionImageFilterIF2IF2_cast(*args): """itkBinaryThresholdProjectionImageFilterIF2IF2_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIF2IF2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF2IF2_cast(*args) class itkBinaryThresholdProjectionImageFilterIF3IF2(itkBinaryThresholdProjectionImageFilterIF3IF2_Superclass): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIF3IF2 class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputPixelTypeGreaterThanComparable = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_InputPixelTypeGreaterThanComparable InputHasNumericTraitsCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_InputHasNumericTraitsCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetForegroundValue(self, *args): """SetForegroundValue(self, float _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_SetForegroundValue(self, *args) def GetForegroundValue(self): """GetForegroundValue(self) -> float""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_GetForegroundValue(self) def SetBackgroundValue(self, *args): """SetBackgroundValue(self, float _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_SetBackgroundValue(self, *args) def GetBackgroundValue(self): """GetBackgroundValue(self) -> float""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_GetBackgroundValue(self) def SetThresholdValue(self, *args): """SetThresholdValue(self, float _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_SetThresholdValue(self, *args) def GetThresholdValue(self): """GetThresholdValue(self) -> float""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_GetThresholdValue(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIF3IF2 def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIF3IF2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIF3IF2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIF3IF2 Create a new object of the class itkBinaryThresholdProjectionImageFilterIF3IF2 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIF3IF2.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIF3IF2.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIF3IF2.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIF3IF2.SetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_SetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIF3IF2) itkBinaryThresholdProjectionImageFilterIF3IF2.GetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_GetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIF3IF2) itkBinaryThresholdProjectionImageFilterIF3IF2.SetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_SetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIF3IF2) itkBinaryThresholdProjectionImageFilterIF3IF2.GetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_GetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIF3IF2) itkBinaryThresholdProjectionImageFilterIF3IF2.SetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_SetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIF3IF2) itkBinaryThresholdProjectionImageFilterIF3IF2.GetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_GetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIF3IF2) itkBinaryThresholdProjectionImageFilterIF3IF2.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_GetPointer,None,itkBinaryThresholdProjectionImageFilterIF3IF2) itkBinaryThresholdProjectionImageFilterIF3IF2_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_swigregister itkBinaryThresholdProjectionImageFilterIF3IF2_swigregister(itkBinaryThresholdProjectionImageFilterIF3IF2) def itkBinaryThresholdProjectionImageFilterIF3IF2___New_orig__(): """itkBinaryThresholdProjectionImageFilterIF3IF2___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2___New_orig__() def itkBinaryThresholdProjectionImageFilterIF3IF2_cast(*args): """itkBinaryThresholdProjectionImageFilterIF3IF2_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIF3IF2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF2_cast(*args) class itkBinaryThresholdProjectionImageFilterIF3IF3(itkBinaryThresholdProjectionImageFilterIF3IF3_Superclass): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIF3IF3 class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputPixelTypeGreaterThanComparable = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_InputPixelTypeGreaterThanComparable InputHasNumericTraitsCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_InputHasNumericTraitsCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetForegroundValue(self, *args): """SetForegroundValue(self, float _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_SetForegroundValue(self, *args) def GetForegroundValue(self): """GetForegroundValue(self) -> float""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_GetForegroundValue(self) def SetBackgroundValue(self, *args): """SetBackgroundValue(self, float _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_SetBackgroundValue(self, *args) def GetBackgroundValue(self): """GetBackgroundValue(self) -> float""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_GetBackgroundValue(self) def SetThresholdValue(self, *args): """SetThresholdValue(self, float _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_SetThresholdValue(self, *args) def GetThresholdValue(self): """GetThresholdValue(self) -> float""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_GetThresholdValue(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIF3IF3 def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIF3IF3""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIF3IF3""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIF3IF3 Create a new object of the class itkBinaryThresholdProjectionImageFilterIF3IF3 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIF3IF3.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIF3IF3.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIF3IF3.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIF3IF3.SetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_SetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIF3IF3) itkBinaryThresholdProjectionImageFilterIF3IF3.GetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_GetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIF3IF3) itkBinaryThresholdProjectionImageFilterIF3IF3.SetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_SetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIF3IF3) itkBinaryThresholdProjectionImageFilterIF3IF3.GetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_GetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIF3IF3) itkBinaryThresholdProjectionImageFilterIF3IF3.SetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_SetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIF3IF3) itkBinaryThresholdProjectionImageFilterIF3IF3.GetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_GetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIF3IF3) itkBinaryThresholdProjectionImageFilterIF3IF3.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_GetPointer,None,itkBinaryThresholdProjectionImageFilterIF3IF3) itkBinaryThresholdProjectionImageFilterIF3IF3_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_swigregister itkBinaryThresholdProjectionImageFilterIF3IF3_swigregister(itkBinaryThresholdProjectionImageFilterIF3IF3) def itkBinaryThresholdProjectionImageFilterIF3IF3___New_orig__(): """itkBinaryThresholdProjectionImageFilterIF3IF3___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3___New_orig__() def itkBinaryThresholdProjectionImageFilterIF3IF3_cast(*args): """itkBinaryThresholdProjectionImageFilterIF3IF3_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIF3IF3""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIF3IF3_cast(*args) class itkBinaryThresholdProjectionImageFilterIUC2IUC2(itkBinaryThresholdProjectionImageFilterIUC2IUC2_Superclass): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIUC2IUC2 class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputPixelTypeGreaterThanComparable = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_InputPixelTypeGreaterThanComparable InputHasNumericTraitsCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_InputHasNumericTraitsCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetForegroundValue(self, *args): """SetForegroundValue(self, unsigned char _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_SetForegroundValue(self, *args) def GetForegroundValue(self): """GetForegroundValue(self) -> unsigned char""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_GetForegroundValue(self) def SetBackgroundValue(self, *args): """SetBackgroundValue(self, unsigned char _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_SetBackgroundValue(self, *args) def GetBackgroundValue(self): """GetBackgroundValue(self) -> unsigned char""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_GetBackgroundValue(self) def SetThresholdValue(self, *args): """SetThresholdValue(self, unsigned char _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_SetThresholdValue(self, *args) def GetThresholdValue(self): """GetThresholdValue(self) -> unsigned char""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_GetThresholdValue(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIUC2IUC2 def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUC2IUC2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIUC2IUC2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIUC2IUC2 Create a new object of the class itkBinaryThresholdProjectionImageFilterIUC2IUC2 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIUC2IUC2.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIUC2IUC2.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIUC2IUC2.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIUC2IUC2.SetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_SetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIUC2IUC2) itkBinaryThresholdProjectionImageFilterIUC2IUC2.GetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_GetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIUC2IUC2) itkBinaryThresholdProjectionImageFilterIUC2IUC2.SetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_SetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIUC2IUC2) itkBinaryThresholdProjectionImageFilterIUC2IUC2.GetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_GetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIUC2IUC2) itkBinaryThresholdProjectionImageFilterIUC2IUC2.SetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_SetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIUC2IUC2) itkBinaryThresholdProjectionImageFilterIUC2IUC2.GetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_GetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIUC2IUC2) itkBinaryThresholdProjectionImageFilterIUC2IUC2.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_GetPointer,None,itkBinaryThresholdProjectionImageFilterIUC2IUC2) itkBinaryThresholdProjectionImageFilterIUC2IUC2_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_swigregister itkBinaryThresholdProjectionImageFilterIUC2IUC2_swigregister(itkBinaryThresholdProjectionImageFilterIUC2IUC2) def itkBinaryThresholdProjectionImageFilterIUC2IUC2___New_orig__(): """itkBinaryThresholdProjectionImageFilterIUC2IUC2___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2___New_orig__() def itkBinaryThresholdProjectionImageFilterIUC2IUC2_cast(*args): """itkBinaryThresholdProjectionImageFilterIUC2IUC2_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUC2IUC2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC2IUC2_cast(*args) class itkBinaryThresholdProjectionImageFilterIUC3IUC2(itkBinaryThresholdProjectionImageFilterIUC3IUC2_Superclass): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIUC3IUC2 class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputPixelTypeGreaterThanComparable = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_InputPixelTypeGreaterThanComparable InputHasNumericTraitsCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_InputHasNumericTraitsCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetForegroundValue(self, *args): """SetForegroundValue(self, unsigned char _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_SetForegroundValue(self, *args) def GetForegroundValue(self): """GetForegroundValue(self) -> unsigned char""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_GetForegroundValue(self) def SetBackgroundValue(self, *args): """SetBackgroundValue(self, unsigned char _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_SetBackgroundValue(self, *args) def GetBackgroundValue(self): """GetBackgroundValue(self) -> unsigned char""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_GetBackgroundValue(self) def SetThresholdValue(self, *args): """SetThresholdValue(self, unsigned char _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_SetThresholdValue(self, *args) def GetThresholdValue(self): """GetThresholdValue(self) -> unsigned char""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_GetThresholdValue(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIUC3IUC2 def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUC3IUC2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIUC3IUC2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIUC3IUC2 Create a new object of the class itkBinaryThresholdProjectionImageFilterIUC3IUC2 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIUC3IUC2.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIUC3IUC2.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIUC3IUC2.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIUC3IUC2.SetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_SetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIUC3IUC2) itkBinaryThresholdProjectionImageFilterIUC3IUC2.GetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_GetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIUC3IUC2) itkBinaryThresholdProjectionImageFilterIUC3IUC2.SetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_SetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIUC3IUC2) itkBinaryThresholdProjectionImageFilterIUC3IUC2.GetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_GetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIUC3IUC2) itkBinaryThresholdProjectionImageFilterIUC3IUC2.SetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_SetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIUC3IUC2) itkBinaryThresholdProjectionImageFilterIUC3IUC2.GetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_GetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIUC3IUC2) itkBinaryThresholdProjectionImageFilterIUC3IUC2.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_GetPointer,None,itkBinaryThresholdProjectionImageFilterIUC3IUC2) itkBinaryThresholdProjectionImageFilterIUC3IUC2_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_swigregister itkBinaryThresholdProjectionImageFilterIUC3IUC2_swigregister(itkBinaryThresholdProjectionImageFilterIUC3IUC2) def itkBinaryThresholdProjectionImageFilterIUC3IUC2___New_orig__(): """itkBinaryThresholdProjectionImageFilterIUC3IUC2___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2___New_orig__() def itkBinaryThresholdProjectionImageFilterIUC3IUC2_cast(*args): """itkBinaryThresholdProjectionImageFilterIUC3IUC2_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUC3IUC2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC2_cast(*args) class itkBinaryThresholdProjectionImageFilterIUC3IUC3(itkBinaryThresholdProjectionImageFilterIUC3IUC3_Superclass): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIUC3IUC3 class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputPixelTypeGreaterThanComparable = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_InputPixelTypeGreaterThanComparable InputHasNumericTraitsCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_InputHasNumericTraitsCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetForegroundValue(self, *args): """SetForegroundValue(self, unsigned char _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_SetForegroundValue(self, *args) def GetForegroundValue(self): """GetForegroundValue(self) -> unsigned char""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_GetForegroundValue(self) def SetBackgroundValue(self, *args): """SetBackgroundValue(self, unsigned char _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_SetBackgroundValue(self, *args) def GetBackgroundValue(self): """GetBackgroundValue(self) -> unsigned char""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_GetBackgroundValue(self) def SetThresholdValue(self, *args): """SetThresholdValue(self, unsigned char _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_SetThresholdValue(self, *args) def GetThresholdValue(self): """GetThresholdValue(self) -> unsigned char""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_GetThresholdValue(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIUC3IUC3 def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUC3IUC3""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIUC3IUC3""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIUC3IUC3 Create a new object of the class itkBinaryThresholdProjectionImageFilterIUC3IUC3 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIUC3IUC3.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIUC3IUC3.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIUC3IUC3.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIUC3IUC3.SetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_SetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIUC3IUC3) itkBinaryThresholdProjectionImageFilterIUC3IUC3.GetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_GetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIUC3IUC3) itkBinaryThresholdProjectionImageFilterIUC3IUC3.SetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_SetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIUC3IUC3) itkBinaryThresholdProjectionImageFilterIUC3IUC3.GetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_GetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIUC3IUC3) itkBinaryThresholdProjectionImageFilterIUC3IUC3.SetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_SetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIUC3IUC3) itkBinaryThresholdProjectionImageFilterIUC3IUC3.GetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_GetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIUC3IUC3) itkBinaryThresholdProjectionImageFilterIUC3IUC3.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_GetPointer,None,itkBinaryThresholdProjectionImageFilterIUC3IUC3) itkBinaryThresholdProjectionImageFilterIUC3IUC3_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_swigregister itkBinaryThresholdProjectionImageFilterIUC3IUC3_swigregister(itkBinaryThresholdProjectionImageFilterIUC3IUC3) def itkBinaryThresholdProjectionImageFilterIUC3IUC3___New_orig__(): """itkBinaryThresholdProjectionImageFilterIUC3IUC3___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3___New_orig__() def itkBinaryThresholdProjectionImageFilterIUC3IUC3_cast(*args): """itkBinaryThresholdProjectionImageFilterIUC3IUC3_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUC3IUC3""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUC3IUC3_cast(*args) class itkBinaryThresholdProjectionImageFilterIUL2IUL2(itkBinaryThresholdProjectionImageFilterIUL2IUL2_Superclass): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIUL2IUL2 class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputPixelTypeGreaterThanComparable = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_InputPixelTypeGreaterThanComparable InputHasNumericTraitsCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_InputHasNumericTraitsCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetForegroundValue(self, *args): """SetForegroundValue(self, unsigned long _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_SetForegroundValue(self, *args) def GetForegroundValue(self): """GetForegroundValue(self) -> unsigned long""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_GetForegroundValue(self) def SetBackgroundValue(self, *args): """SetBackgroundValue(self, unsigned long _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_SetBackgroundValue(self, *args) def GetBackgroundValue(self): """GetBackgroundValue(self) -> unsigned long""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_GetBackgroundValue(self) def SetThresholdValue(self, *args): """SetThresholdValue(self, unsigned long _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_SetThresholdValue(self, *args) def GetThresholdValue(self): """GetThresholdValue(self) -> unsigned long""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_GetThresholdValue(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIUL2IUL2 def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUL2IUL2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIUL2IUL2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIUL2IUL2 Create a new object of the class itkBinaryThresholdProjectionImageFilterIUL2IUL2 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIUL2IUL2.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIUL2IUL2.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIUL2IUL2.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIUL2IUL2.SetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_SetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIUL2IUL2) itkBinaryThresholdProjectionImageFilterIUL2IUL2.GetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_GetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIUL2IUL2) itkBinaryThresholdProjectionImageFilterIUL2IUL2.SetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_SetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIUL2IUL2) itkBinaryThresholdProjectionImageFilterIUL2IUL2.GetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_GetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIUL2IUL2) itkBinaryThresholdProjectionImageFilterIUL2IUL2.SetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_SetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIUL2IUL2) itkBinaryThresholdProjectionImageFilterIUL2IUL2.GetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_GetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIUL2IUL2) itkBinaryThresholdProjectionImageFilterIUL2IUL2.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_GetPointer,None,itkBinaryThresholdProjectionImageFilterIUL2IUL2) itkBinaryThresholdProjectionImageFilterIUL2IUL2_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_swigregister itkBinaryThresholdProjectionImageFilterIUL2IUL2_swigregister(itkBinaryThresholdProjectionImageFilterIUL2IUL2) def itkBinaryThresholdProjectionImageFilterIUL2IUL2___New_orig__(): """itkBinaryThresholdProjectionImageFilterIUL2IUL2___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2___New_orig__() def itkBinaryThresholdProjectionImageFilterIUL2IUL2_cast(*args): """itkBinaryThresholdProjectionImageFilterIUL2IUL2_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUL2IUL2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL2IUL2_cast(*args) class itkBinaryThresholdProjectionImageFilterIUL3IUL2(itkBinaryThresholdProjectionImageFilterIUL3IUL2_Superclass): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIUL3IUL2 class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputPixelTypeGreaterThanComparable = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_InputPixelTypeGreaterThanComparable InputHasNumericTraitsCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_InputHasNumericTraitsCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetForegroundValue(self, *args): """SetForegroundValue(self, unsigned long _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_SetForegroundValue(self, *args) def GetForegroundValue(self): """GetForegroundValue(self) -> unsigned long""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_GetForegroundValue(self) def SetBackgroundValue(self, *args): """SetBackgroundValue(self, unsigned long _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_SetBackgroundValue(self, *args) def GetBackgroundValue(self): """GetBackgroundValue(self) -> unsigned long""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_GetBackgroundValue(self) def SetThresholdValue(self, *args): """SetThresholdValue(self, unsigned long _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_SetThresholdValue(self, *args) def GetThresholdValue(self): """GetThresholdValue(self) -> unsigned long""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_GetThresholdValue(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIUL3IUL2 def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUL3IUL2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIUL3IUL2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIUL3IUL2 Create a new object of the class itkBinaryThresholdProjectionImageFilterIUL3IUL2 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIUL3IUL2.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIUL3IUL2.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIUL3IUL2.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIUL3IUL2.SetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_SetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIUL3IUL2) itkBinaryThresholdProjectionImageFilterIUL3IUL2.GetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_GetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIUL3IUL2) itkBinaryThresholdProjectionImageFilterIUL3IUL2.SetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_SetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIUL3IUL2) itkBinaryThresholdProjectionImageFilterIUL3IUL2.GetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_GetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIUL3IUL2) itkBinaryThresholdProjectionImageFilterIUL3IUL2.SetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_SetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIUL3IUL2) itkBinaryThresholdProjectionImageFilterIUL3IUL2.GetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_GetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIUL3IUL2) itkBinaryThresholdProjectionImageFilterIUL3IUL2.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_GetPointer,None,itkBinaryThresholdProjectionImageFilterIUL3IUL2) itkBinaryThresholdProjectionImageFilterIUL3IUL2_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_swigregister itkBinaryThresholdProjectionImageFilterIUL3IUL2_swigregister(itkBinaryThresholdProjectionImageFilterIUL3IUL2) def itkBinaryThresholdProjectionImageFilterIUL3IUL2___New_orig__(): """itkBinaryThresholdProjectionImageFilterIUL3IUL2___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2___New_orig__() def itkBinaryThresholdProjectionImageFilterIUL3IUL2_cast(*args): """itkBinaryThresholdProjectionImageFilterIUL3IUL2_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUL3IUL2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL2_cast(*args) class itkBinaryThresholdProjectionImageFilterIUL3IUL3(itkBinaryThresholdProjectionImageFilterIUL3IUL3_Superclass): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIUL3IUL3 class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputPixelTypeGreaterThanComparable = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_InputPixelTypeGreaterThanComparable InputHasNumericTraitsCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_InputHasNumericTraitsCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetForegroundValue(self, *args): """SetForegroundValue(self, unsigned long _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_SetForegroundValue(self, *args) def GetForegroundValue(self): """GetForegroundValue(self) -> unsigned long""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_GetForegroundValue(self) def SetBackgroundValue(self, *args): """SetBackgroundValue(self, unsigned long _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_SetBackgroundValue(self, *args) def GetBackgroundValue(self): """GetBackgroundValue(self) -> unsigned long""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_GetBackgroundValue(self) def SetThresholdValue(self, *args): """SetThresholdValue(self, unsigned long _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_SetThresholdValue(self, *args) def GetThresholdValue(self): """GetThresholdValue(self) -> unsigned long""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_GetThresholdValue(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIUL3IUL3 def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUL3IUL3""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIUL3IUL3""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIUL3IUL3 Create a new object of the class itkBinaryThresholdProjectionImageFilterIUL3IUL3 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIUL3IUL3.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIUL3IUL3.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIUL3IUL3.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIUL3IUL3.SetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_SetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIUL3IUL3) itkBinaryThresholdProjectionImageFilterIUL3IUL3.GetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_GetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIUL3IUL3) itkBinaryThresholdProjectionImageFilterIUL3IUL3.SetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_SetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIUL3IUL3) itkBinaryThresholdProjectionImageFilterIUL3IUL3.GetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_GetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIUL3IUL3) itkBinaryThresholdProjectionImageFilterIUL3IUL3.SetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_SetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIUL3IUL3) itkBinaryThresholdProjectionImageFilterIUL3IUL3.GetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_GetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIUL3IUL3) itkBinaryThresholdProjectionImageFilterIUL3IUL3.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_GetPointer,None,itkBinaryThresholdProjectionImageFilterIUL3IUL3) itkBinaryThresholdProjectionImageFilterIUL3IUL3_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_swigregister itkBinaryThresholdProjectionImageFilterIUL3IUL3_swigregister(itkBinaryThresholdProjectionImageFilterIUL3IUL3) def itkBinaryThresholdProjectionImageFilterIUL3IUL3___New_orig__(): """itkBinaryThresholdProjectionImageFilterIUL3IUL3___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3___New_orig__() def itkBinaryThresholdProjectionImageFilterIUL3IUL3_cast(*args): """itkBinaryThresholdProjectionImageFilterIUL3IUL3_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUL3IUL3""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUL3IUL3_cast(*args) class itkBinaryThresholdProjectionImageFilterIUS2IUS2(itkBinaryThresholdProjectionImageFilterIUS2IUS2_Superclass): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIUS2IUS2 class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputPixelTypeGreaterThanComparable = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_InputPixelTypeGreaterThanComparable InputHasNumericTraitsCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_InputHasNumericTraitsCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetForegroundValue(self, *args): """SetForegroundValue(self, unsigned short _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_SetForegroundValue(self, *args) def GetForegroundValue(self): """GetForegroundValue(self) -> unsigned short""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_GetForegroundValue(self) def SetBackgroundValue(self, *args): """SetBackgroundValue(self, unsigned short _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_SetBackgroundValue(self, *args) def GetBackgroundValue(self): """GetBackgroundValue(self) -> unsigned short""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_GetBackgroundValue(self) def SetThresholdValue(self, *args): """SetThresholdValue(self, unsigned short _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_SetThresholdValue(self, *args) def GetThresholdValue(self): """GetThresholdValue(self) -> unsigned short""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_GetThresholdValue(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIUS2IUS2 def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUS2IUS2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIUS2IUS2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIUS2IUS2 Create a new object of the class itkBinaryThresholdProjectionImageFilterIUS2IUS2 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIUS2IUS2.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIUS2IUS2.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIUS2IUS2.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIUS2IUS2.SetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_SetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIUS2IUS2) itkBinaryThresholdProjectionImageFilterIUS2IUS2.GetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_GetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIUS2IUS2) itkBinaryThresholdProjectionImageFilterIUS2IUS2.SetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_SetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIUS2IUS2) itkBinaryThresholdProjectionImageFilterIUS2IUS2.GetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_GetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIUS2IUS2) itkBinaryThresholdProjectionImageFilterIUS2IUS2.SetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_SetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIUS2IUS2) itkBinaryThresholdProjectionImageFilterIUS2IUS2.GetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_GetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIUS2IUS2) itkBinaryThresholdProjectionImageFilterIUS2IUS2.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_GetPointer,None,itkBinaryThresholdProjectionImageFilterIUS2IUS2) itkBinaryThresholdProjectionImageFilterIUS2IUS2_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_swigregister itkBinaryThresholdProjectionImageFilterIUS2IUS2_swigregister(itkBinaryThresholdProjectionImageFilterIUS2IUS2) def itkBinaryThresholdProjectionImageFilterIUS2IUS2___New_orig__(): """itkBinaryThresholdProjectionImageFilterIUS2IUS2___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2___New_orig__() def itkBinaryThresholdProjectionImageFilterIUS2IUS2_cast(*args): """itkBinaryThresholdProjectionImageFilterIUS2IUS2_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUS2IUS2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS2IUS2_cast(*args) class itkBinaryThresholdProjectionImageFilterIUS3IUS2(itkBinaryThresholdProjectionImageFilterIUS3IUS2_Superclass): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIUS3IUS2 class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputPixelTypeGreaterThanComparable = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_InputPixelTypeGreaterThanComparable InputHasNumericTraitsCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_InputHasNumericTraitsCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetForegroundValue(self, *args): """SetForegroundValue(self, unsigned short _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_SetForegroundValue(self, *args) def GetForegroundValue(self): """GetForegroundValue(self) -> unsigned short""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_GetForegroundValue(self) def SetBackgroundValue(self, *args): """SetBackgroundValue(self, unsigned short _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_SetBackgroundValue(self, *args) def GetBackgroundValue(self): """GetBackgroundValue(self) -> unsigned short""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_GetBackgroundValue(self) def SetThresholdValue(self, *args): """SetThresholdValue(self, unsigned short _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_SetThresholdValue(self, *args) def GetThresholdValue(self): """GetThresholdValue(self) -> unsigned short""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_GetThresholdValue(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIUS3IUS2 def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUS3IUS2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIUS3IUS2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIUS3IUS2 Create a new object of the class itkBinaryThresholdProjectionImageFilterIUS3IUS2 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIUS3IUS2.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIUS3IUS2.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIUS3IUS2.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIUS3IUS2.SetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_SetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIUS3IUS2) itkBinaryThresholdProjectionImageFilterIUS3IUS2.GetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_GetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIUS3IUS2) itkBinaryThresholdProjectionImageFilterIUS3IUS2.SetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_SetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIUS3IUS2) itkBinaryThresholdProjectionImageFilterIUS3IUS2.GetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_GetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIUS3IUS2) itkBinaryThresholdProjectionImageFilterIUS3IUS2.SetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_SetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIUS3IUS2) itkBinaryThresholdProjectionImageFilterIUS3IUS2.GetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_GetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIUS3IUS2) itkBinaryThresholdProjectionImageFilterIUS3IUS2.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_GetPointer,None,itkBinaryThresholdProjectionImageFilterIUS3IUS2) itkBinaryThresholdProjectionImageFilterIUS3IUS2_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_swigregister itkBinaryThresholdProjectionImageFilterIUS3IUS2_swigregister(itkBinaryThresholdProjectionImageFilterIUS3IUS2) def itkBinaryThresholdProjectionImageFilterIUS3IUS2___New_orig__(): """itkBinaryThresholdProjectionImageFilterIUS3IUS2___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2___New_orig__() def itkBinaryThresholdProjectionImageFilterIUS3IUS2_cast(*args): """itkBinaryThresholdProjectionImageFilterIUS3IUS2_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUS3IUS2""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS2_cast(*args) class itkBinaryThresholdProjectionImageFilterIUS3IUS3(itkBinaryThresholdProjectionImageFilterIUS3IUS3_Superclass): """Proxy of C++ itkBinaryThresholdProjectionImageFilterIUS3IUS3 class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr InputPixelTypeGreaterThanComparable = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_InputPixelTypeGreaterThanComparable InputHasNumericTraitsCheck = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_InputHasNumericTraitsCheck def __New_orig__(): """__New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3___New_orig__() __New_orig__ = staticmethod(__New_orig__) def SetForegroundValue(self, *args): """SetForegroundValue(self, unsigned short _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_SetForegroundValue(self, *args) def GetForegroundValue(self): """GetForegroundValue(self) -> unsigned short""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_GetForegroundValue(self) def SetBackgroundValue(self, *args): """SetBackgroundValue(self, unsigned short _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_SetBackgroundValue(self, *args) def GetBackgroundValue(self): """GetBackgroundValue(self) -> unsigned short""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_GetBackgroundValue(self) def SetThresholdValue(self, *args): """SetThresholdValue(self, unsigned short _arg)""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_SetThresholdValue(self, *args) def GetThresholdValue(self): """GetThresholdValue(self) -> unsigned short""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_GetThresholdValue(self) __swig_destroy__ = _itkBinaryThresholdProjectionImageFilterPython.delete_itkBinaryThresholdProjectionImageFilterIUS3IUS3 def cast(*args): """cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUS3IUS3""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_cast(*args) cast = staticmethod(cast) def GetPointer(self): """GetPointer(self) -> itkBinaryThresholdProjectionImageFilterIUS3IUS3""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_GetPointer(self) def New(*args, **kargs): """New() -> itkBinaryThresholdProjectionImageFilterIUS3IUS3 Create a new object of the class itkBinaryThresholdProjectionImageFilterIUS3IUS3 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first non named parameter in the first input, etc. The named parameters are used by calling the method with the same name prefixed by 'Set'. Ex: itkBinaryThresholdProjectionImageFilterIUS3IUS3.New( reader, Threshold=10 ) is (most of the time) equivalent to: obj = itkBinaryThresholdProjectionImageFilterIUS3IUS3.New() obj.SetInput( 0, reader.GetOutput() ) obj.SetThreshold( 10 ) """ obj = itkBinaryThresholdProjectionImageFilterIUS3IUS3.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj New = staticmethod(New) itkBinaryThresholdProjectionImageFilterIUS3IUS3.SetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_SetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIUS3IUS3) itkBinaryThresholdProjectionImageFilterIUS3IUS3.GetForegroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_GetForegroundValue,None,itkBinaryThresholdProjectionImageFilterIUS3IUS3) itkBinaryThresholdProjectionImageFilterIUS3IUS3.SetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_SetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIUS3IUS3) itkBinaryThresholdProjectionImageFilterIUS3IUS3.GetBackgroundValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_GetBackgroundValue,None,itkBinaryThresholdProjectionImageFilterIUS3IUS3) itkBinaryThresholdProjectionImageFilterIUS3IUS3.SetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_SetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIUS3IUS3) itkBinaryThresholdProjectionImageFilterIUS3IUS3.GetThresholdValue = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_GetThresholdValue,None,itkBinaryThresholdProjectionImageFilterIUS3IUS3) itkBinaryThresholdProjectionImageFilterIUS3IUS3.GetPointer = new_instancemethod(_itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_GetPointer,None,itkBinaryThresholdProjectionImageFilterIUS3IUS3) itkBinaryThresholdProjectionImageFilterIUS3IUS3_swigregister = _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_swigregister itkBinaryThresholdProjectionImageFilterIUS3IUS3_swigregister(itkBinaryThresholdProjectionImageFilterIUS3IUS3) def itkBinaryThresholdProjectionImageFilterIUS3IUS3___New_orig__(): """itkBinaryThresholdProjectionImageFilterIUS3IUS3___New_orig__()""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3___New_orig__() def itkBinaryThresholdProjectionImageFilterIUS3IUS3_cast(*args): """itkBinaryThresholdProjectionImageFilterIUS3IUS3_cast(itkLightObject obj) -> itkBinaryThresholdProjectionImageFilterIUS3IUS3""" return _itkBinaryThresholdProjectionImageFilterPython.itkBinaryThresholdProjectionImageFilterIUS3IUS3_cast(*args)
UTF-8
Python
false
false
2,013
8,126,078,153,341
769d24311beb53ac4e1595ca9c35c76fbf196981
75e016230b7ceda4dfadfdf2448a12501f2df101
/bake/lib/git.py
d584c67d0ea0006be51a20ad8094152dd46cb32a
[ "LicenseRef-scancode-warranty-disclaimer" ]
non_permissive
siq-legacy/bake
https://github.com/siq-legacy/bake
75ec886391c3c9095cd85085e962b8a731da1a9a
747e11faafc8ae662fc1e1f645c6ff00ee876cad
refs/heads/master
2020-12-24T15:04:58.484689
2013-05-10T15:41:42
2013-05-10T15:41:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from scheme import * from bake.path import path from bake.process import Process from bake.task import * class Repository(object): """A git repository.""" def __init__(self, root, binary='git'): if not isinstance(root, path): root = path(root) self.binary = binary self.root = root.abspath() @property def tags(self): return self.execute(['tag']).stdout.strip().split('\n') def checkout(self, commit): self.execute(['checkout', commit]) def clone(self, url): self.execute(['clone', url, str(self.root)], False) def execute(self, tokens, cwd=True): if cwd: cwd = str(self.root) else: cwd = None process = Process([self.binary] + tokens) if process(cwd=cwd) == 0: return process else: raise RuntimeError(process.stderr or '') def get_file(self, filename, commit='HEAD'): filename = '%s:%s' % (commit, filename) return self.execute(['show', filename]).stdout def create_tag(self, tag, message): self.execute(['tag', '-a', tag, '-m', '"%s"' % message]) class GitTask(Task): parameters = { 'binary': Text(description='path to git binary', default='git'), } class GitClone(GitTask): name = 'git.clone' description = 'clones a git repository' parameters = { 'path': Text(description='path to destination directory'), 'url': Text(description='url of git repository', required=True), } def run(self, runtime): options = [self['binary'], 'clone', self['url']] if self['path']: options.append(self['path']) runtime.shell(options)
UTF-8
Python
false
false
2,013
936,302,912,881
0b5661e5d0de542c10143ff71f629f00622429af
e1560b0c174b0ce5ee6c83fd1b5d6f129594818c
/Examples/QLD Fire/self_updating_rss.py
824a86b056e347980e9246a877458d7798147bf8
[]
no_license
FraserThompson/thundermaps-rss
https://github.com/FraserThompson/thundermaps-rss
7566b46efa1f18e7982fbfaa25bee9384cc3ad50
d9a0c618d5a685979b464449eefc9e19f69b9ed5
refs/heads/master
2021-01-01T19:39:02.100554
2014-01-21T02:05:02
2014-01-21T02:05:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # Used to update Thundermaps with events from QLD Fire. import updater # Key, account, categories... THUNDERMAPS_API_KEY = "" THUNDERMAPS_ACCOUNT_ID = "" RSS_FEED_URL = 'http://www.rfs.nsw.gov.au/feeds/majorIncidents.xml' # Create updater fire_updater = updater.Updater(THUNDERMAPS_API_KEY, THUNDERMAPS_ACCOUNT_ID, RSS_FEED_URL) # Start updating fire_updater.start()
UTF-8
Python
false
false
2,014
12,146,167,551,003
99f8a661a13373821ae0da22203a195f03dd32ef
60532e6ca6b9324c9920b0d8948cf26cbd43ee57
/__init__.py
9e77a6b236106dcfda41d10a03d5326b6317f40f
[]
no_license
seveneightn9ne/nomic
https://github.com/seveneightn9ne/nomic
84208522d8f25bb6ddd337d1eecc9d9dbaa0bfdd
d3582f4821e642e142cb8a4bafec937844a4c0e5
refs/heads/master
2021-01-20T09:01:14.393564
2014-09-16T22:21:35
2014-09-16T22:21:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from flask import Flask, redirect, request, render_template, url_for from flask.ext.mongoengine import MongoEngine from proxy import ReverseProxied # from nomic.views import proposals, votes app = Flask(__name__) app.config["MONGODB_SETTINGS"] = {'DB': "nomic_db"} app.wsgi_app = ReverseProxied(app.wsgi_app) db = MongoEngine(app) from models import Proposal, Vote def get_sanitized_proposals(): proposals = Proposal.objects(archived=False) for proposal in proposals: if not proposal.votes_revealed: for vote in proposal.votes: vote.vote = "[hidden]" vote.hate_upon = "[hidden]" vote.love = "[hidden]" return proposals @app.route('/', methods=['GET', 'POST']) def list(): if request.method == 'GET': return render_template('proposals/list.html', proposals=get_sanitized_proposals()) else: # POST proposal = Proposal(created_by=request.form['created_by'], number=request.form['number']) proposal.save() return render_template('proposals/list.html', proposals=get_sanitized_proposals()) @app.route('/vote/<proposal_id>', methods=['POST']) def add_vote(proposal_id): vote = Vote(name=request.form['name'], vote=request.form['vote'], hate_upon=request.form['hate_upon']) proposal = Proposal.objects.get_or_404(id=proposal_id) existing_votes = filter(lambda v: v.name.lower().strip() == vote.name.lower().strip(), proposal.votes) if len(existing_votes) > 0: existing_vote = existing_votes[0] existing_vote.created_at = vote.created_at existing_vote.vote = vote.vote existing_vote.hate_upon = vote.hate_upon existing_vote.love = vote.love else: proposal.votes.append(vote) proposal.save() return redirect(url_for('list')) @app.route('/archive/<proposal_id>') def archive(proposal_id): proposal = Proposal.objects.get(id=proposal_id) proposal.archived = True proposal.save() return redirect(url_for('list')) @app.route('/reveal/<proposal_id>') def reveal(proposal_id): proposal = Proposal.objects.get(id=proposal_id) proposal.votes_revealed = True proposal.save() return redirect(url_for('list')) if __name__ == "__main__": app.run()
UTF-8
Python
false
false
2,014
9,096,740,743,507
c934409808640256dc0e1d6bd2e3e32cbc372675
5204d166e2196a9a171f1579654847a71d060ba8
/glance/api/v2/schemas.py
4cb303794db2165f0d374cfd7145dfa19473d093
[ "Apache-2.0" ]
permissive
altai/glance
https://github.com/altai/glance
1c4fefd7d29133a050a1e870058c3a87b0d7411b
eb568c5ffb4543b676208c96de7af2c62e455329
refs/heads/master
2020-12-25T16:14:25.445061
2012-10-17T06:50:53
2012-10-17T10:25:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright 2012 OpenStack LLC. # 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 glance.api.v2.base from glance.common import wsgi import glance.schema class Controller(glance.api.v2.base.Controller): def __init__(self, conf, schema_api): super(Controller, self).__init__(conf) self.schema_api = schema_api def index(self, req): links = [ {'rel': 'image', 'href': '/v2/schemas/image'}, {'rel': 'access', 'href': '/v2/schemas/image/access'}, ] return {'links': links} def image(self, req): return self.schema_api.get_schema('image') def access(self, req): return self.schema_api.get_schema('access') def create_resource(conf, schema_api): controller = Controller(conf, schema_api) return wsgi.Resource(controller)
UTF-8
Python
false
false
2,012
10,230,612,117,851
18b4db597b78e8aadda680c42af384c7c1b188b6
a2ac73af04a07bb070cd85c88778608b561dd3e4
/addons/sale_analytic_plans/sale_analytic_plans.py
01284b520a589fd4bc0c6185890e02d5afc39dbe
[]
no_license
sannareddy/openerp-heimai
https://github.com/sannareddy/openerp-heimai
c849586d6099cc7548dec8b3f1cc7ba8be49594a
58255ecbcea7bf9780948287cf4551ed6494832a
refs/heads/master
2021-01-15T21:34:46.162550
2014-05-13T09:20:37
2014-05-13T09:20:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/usr/share/pyshared/openerp/addons/sale_analytic_plans/sale_analytic_plans.py
UTF-8
Python
false
false
2,014
6,657,199,350,939
e669d4090df1492170a6bde8971b01043dd0584e
13e2c705dd4292e8889bcfbac80978963157851a
/pyconca/tests/test_util.py
cb85197ccddd90dc0d74c18d1edbc4947d12f3ee
[]
no_license
pombredanne/2012-web
https://github.com/pombredanne/2012-web
53bc06288ecc999e649f8ea47291bf55e69044a9
0039a0b5015a93eef881ca4b931ad85a78ff7490
refs/heads/master
2017-05-02T18:20:08.792941
2013-04-29T03:15:53
2013-04-29T03:15:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from nose.tools import eq_ from pyconca.util import * def test_camel_to_under_single_name(): eq_('foo', camel_to_under('Foo')) def test_camel_to_under_double_name(): eq_('foo_bar', camel_to_under('FooBar')) def test_camel_to_under_triple_name(): eq_('foo_bar_baz', camel_to_under('FooBarBaz')) def test_under_to_camel_single_name(): eq_('Foo', under_to_camel('foo')) def test_under_to_camel_double_name(): eq_('FooBar', under_to_camel('foo_bar')) def test_under_to_camel_triple_name(): eq_('FooBarBaz', under_to_camel('foo_bar_baz'))
UTF-8
Python
false
false
2,013
7,971,459,310,074
2b12f1e6225e19afb528b8025f377caec9ae8410
7b5b547e4f1183ca340a02c2b3e8248d264d808b
/server/src/persona/personad/handlers/cmd/__init__.py
44a46a05d616372f0a64f860250cc97d899e8d5a
[]
no_license
ovty/persona_wt
https://github.com/ovty/persona_wt
c5800f68885ae6c01df971701ffe295f66ed6370
c6455b54d11eb3d5c81b65215a5e7b1b1bff07f1
refs/heads/master
2016-09-06T15:12:41.801659
2014-10-13T04:26:49
2014-10-13T04:26:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- import cmd cmdmap = cmd.CmdProc.cmdmap()
UTF-8
Python
false
false
2,014
15,831,249,471,694
6b34ed98620a06e7732e08ec213afc8e76ee008f
fbdf061dee362ec0dbf937179b6ccd896eada546
/mcman/mcman.py
aa3dc0d24a78152ef9f4ba8e0f202ebc6d711104
[ "GPL-3.0-or-later" ]
non_permissive
CubeEngine/mc-man
https://github.com/CubeEngine/mc-man
5fd7f566e1621c321395039ae133b186b51fea59
cd95b1192279e8df890acb23b565a6ccd4c5ce4d
refs/heads/master
2020-04-20T01:27:13.643828
2014-04-30T20:16:00
2014-04-30T20:16:00
9,530,565
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# "mcman" - An utility for managing Minecraft server jars and plugins. # Copyright (C) 2014 Tobias Laundal <totokaka> # # 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/>. """ mcman main module. """ import argparse import sys import mcman from mcman.commands.plugins import PluginsCommand from mcman.commands.servers import ServersCommand from mcman.commands.import_cmd import ImportCommand from mcman.commands.export import ExportCommand def negative(argument): """ Turn a number negative. """ return -abs(int(argument)) def setup_import_command(sub_parsers, parent): """ Setup the command for import. """ # The server command parser parser = sub_parsers.add_parser( 'import', aliases=['i'], help='import a server', description='Import a server - Its server jars and plugins', parents=[parent]) parser.set_defaults(command=ImportCommand) parser.add_argument( 'input', type=argparse.FileType('r'), default=sys.stdin, help=('the json file contating the server and plugin information. ' '"-" may be used to mark stdin')) parser.add_argument( 'destination', default='./', nargs='?', help='the destination folder. defaults to ./') return parser def setup_export_command(sub_parsers, parent): """ Setup the command for export. """ # The server command parser parser = sub_parsers.add_parser( 'export', aliases=['e'], help='export the server', description='Export the server - Its server jars and plugins', parents=[parent]) parser.set_defaults(command=ExportCommand) parser.add_argument( 'output', type=argparse.FileType('w'), default=sys.stdout, help='the file to output the json to. "-" may be used to mark stdout') parser.add_argument( '--types', default='plugins,servers', help='what to save. A comma separated list of "servers" and "plugins"') parser.add_argument( '--quiet', action='store_true', help="don't print anything other than the result") return parser def setup_server_commands(sub_parsers, parent): """ Setup the commands and subcommands for server. """ # The parent parser for server and it's sub commands sub_parent = argparse.ArgumentParser(add_help=False, parents=[parent]) # Base URL sub_parent.add_argument( '--base-url', metavar='base-url', default='http://spacegdn.totokaka.io/v1/', help='the base URL to use for SpaceGDN') # The server command parser parser = sub_parsers.add_parser( 'server', aliases=['s'], help='manage server jars', description='Download, identify and list Minecraft server jars.', parents=[sub_parent]) parser.set_defaults(command=ServersCommand) # The server sub commands sub_parsers = parser.add_subparsers(title='subcommands') # servers, sub command of server servers_parser = sub_parsers.add_parser( 'servers', aliases=['s'], help='list available servers', description='List all server jars available for download.', parents=[sub_parent]) servers_parser.set_defaults(subcommand='servers') # channels, sub command of server channels_parser = sub_parsers.add_parser( 'channels', aliases=['c'], help='list channels for the specified server', description='List all available channels for the server specified.', parents=[sub_parent]) channels_parser.set_defaults(subcommand='channels') channels_parser.add_argument( 'server', help='the server to get channels for') # versions, sub command of server versions_parser = sub_parsers.add_parser( 'versions', aliases=['v'], help='list versions for the specified server', description='List all available versions for the server specified, ' + 'or only the versions in the specified channel.', parents=[sub_parent]) versions_parser.set_defaults(subcommand='versions') versions_parser.add_argument( 'server', help='the server to get versions for') versions_parser.add_argument( 'channel', nargs='?', help='the channel to get versions for') # builds, sub command of server builds_parser = sub_parsers.add_parser( 'builds', aliases=['b'], help='list builds for the specified server', description='List all available builds for the server specified, ' + 'or only the ones in the specified channel, or version', parents=[sub_parent]) builds_parser.set_defaults(subcommand='builds') builds_parser.add_argument( 'server', help='the server to get builds for') builds_parser.add_argument( 'channel', nargs='?', help='the channel to get builds for') builds_parser.add_argument( 'version', nargs='?', help='the version to get builds for') # download, sub command of server download_parser = sub_parsers.add_parser( 'download', aliases=['d'], help='download the newest version of the server', description='Download the newest, the newest in the channel, or the ' + 'specified version of the jar.', parents=[sub_parent]) download_parser.set_defaults(subcommand='download') download_parser.add_argument( 'server', help='the server to download') download_parser.add_argument( 'channel', nargs='?', help='the channel to dowload from') download_parser.add_argument( 'version', nargs='?', help='the specific version to download') download_parser.add_argument( 'build', nargs='?', help='the specific build to download') download_parser.add_argument( '-o', '--output', help='filename to download to') # identify, sub command of server identify_parser = sub_parsers.add_parser( 'identify', aliases=['i'], help='identify the server and version of the jar file', description='Identifies the server, version and possibly channel of ' + 'the jar file specified.', parents=[sub_parent]) identify_parser.set_defaults(subcommand='identify') identify_parser.add_argument( 'jar', type=argparse.FileType('rb', 0), help='the jar file to identify') return parser def setup_plugin_commands(sub_parsers, parent): """ Setup the commands and subcommands for plugin. """ # The parent parser for plugin and it's sub commands sub_parent = argparse.ArgumentParser(add_help=False, parents=[parent]) # Base URL sub_parent.add_argument( '--base-url', default='http://api.bukget.org/3/', help='the base URL to use for BukGet') sub_parent.add_argument( '--server', default='bukkit', help='the server to get plugins for. This is sent to BukGet, ' + 'and will affect what plugins you can download') sub_parent.add_argument( '--beta', action='store_const', dest='version', const='beta', help="find latest beta version, instead of latest release for " + "plugins where a version isn't specified.") sub_parent.add_argument( '--alpha', action='store_const', dest='version', const='alpha', help="find latest alpha version, instead of latest release for " + "plugins where a version isn't specified.") sub_parent.add_argument( '--latest', action='store_const', dest='version', const='latest', help="find latest version, no matter type, instead of latest release " + "for plugins where a version isn't specified.") sub_parent.add_argument( '--no-resolve-dependencies', action='store_false', dest='resolve_dependencies', help='do not resolve dependencies') sub_parent.set_defaults(version='release') # The plugin command parser parser = sub_parsers.add_parser( 'plugin', aliases=['p'], help='manage plugins', description='Find, download and update plugins.', parents=[sub_parent]) parser.set_defaults(command=PluginsCommand) # The plugin sub commands sub_parsers = parser.add_subparsers(title='subcommands') # search, sub command of plugin search_parser = sub_parsers.add_parser( 'search', aliases=['s'], help='search for a plugin', description='Search for a plugin using partial matching of the name.', parents=[sub_parent]) search_parser.set_defaults(subcommand='search') search_parser.add_argument( 'query', help='search query') # info, sub command of plugin info_parser = sub_parsers.add_parser( 'info', aliases=['i'], help='get info about a plugin(s)', description='Get info about one, or more plugins.', parents=[sub_parent]) info_parser.set_defaults(subcommand='info') info_parser.add_argument( 'plugins', metavar='plugin', type=str, help='plugin(s) to get info for') # download, sub command of plugin download_parser = sub_parsers.add_parser( 'download', aliases=['d'], help='download a plugin(s)', description='Download the specified plugin(s). A version can be ' + 'specified by appending "#<version>" to the plugin name', parents=[sub_parent]) download_parser.set_defaults(subcommand='download') download_parser.add_argument( 'plugins', metavar='plugin', type=str, nargs='+', help='plugin(s) to download, and extract if they are zipped') download_parser.add_argument( '--ignore', metavar='plugin', type=str, nargs='+', dest='ignored', help='plugin(s) to ignore') # update, sub command of plugin update_parser = sub_parsers.add_parser( 'update', aliases=['u'], help='update a plugin(s)', description='Update the specified plugins, or all.', parents=[sub_parent]) update_parser.set_defaults(subcommand='update') update_parser.add_argument( 'plugins', metavar='plugin', type=str, nargs='*', help='plugin(s) update') update_parser.add_argument( '--ignore', metavar='plugin', type=str, nargs='+', dest='ignored', help='plugin(s) to ignore') # list, sub command of plugin list_parser = sub_parsers.add_parser( 'list', aliases=['l'], help='list installed plugins', description='List installed plugins, their versions, and the newest ' + 'version.', parents=[sub_parent]) list_parser.set_defaults(subcommand='list') return parser def setup_parse_command(): """ Setup commands, and parse them. """ # Parent parser parent = argparse.ArgumentParser(add_help=False) # Commands that can be used for all sub commands parent.add_argument( '--version', help='show the version of mcman, then quit', action='store_true', dest='show_version') parent.add_argument( '--user-agent', metavar='agent', type=str, default='mcman ' + mcman.__version__, help='alternative user agent to report to BukGet and SpaceGDN') # Head and tail, they are mutually exclusive group = parent.add_mutually_exclusive_group() group.add_argument( '--head', '--size', metavar='size', type=int, dest='size', nargs='?', default=10, const=5, help='how many entries that should be displayed, from the top') group.add_argument( '--tail', metavar='size', type=negative, dest='size', nargs='?', default=10, const=-5, help='how many entries that should be displayed, from the bottom') parent.add_argument( '--no-confirm', action='store_true', help='do not wait for confirmation, just continue') # The top level command parser = argparse.ArgumentParser( description='Manage Minecraft server jars and plugins', epilog='Powered by BukGet and SpaceGDN', parents=[parent]) # The sub commands, plugin and server sub_parsers = parser.add_subparsers(title='subcommands') server_parser = setup_server_commands(sub_parsers, parent) plugin_parser = setup_plugin_commands(sub_parsers, parent) setup_import_command(sub_parsers, parent) setup_export_command(sub_parsers, parent) return server_parser, plugin_parser, parser def main(): """ Main function. """ server_parser, plugin_parser, parser = setup_parse_command() args = parser.parse_args() if args.show_version: print('Version: {}'.format(mcman.__version__)) elif 'command' not in args: parser.print_help() elif 'subcommand' not in args and not (args.command == ExportCommand or args.command == ImportCommand): if args.command is PluginsCommand: plugin_parser.print_help() elif args.command is ServersCommand: server_parser.print_help() else: if 'ignored' in args and args.ignored is None: args.ignored = [] try: args.command(args) except KeyboardInterrupt: print() return
UTF-8
Python
false
false
2,014
5,454,608,479,713
98799f4acedf928cb420c425cb4ff772cafe5797
690ebb2944abe83b92b628df089873265d5086e4
/dependencies/src/4Suite-XML-1.0.2/Ft/Lib/TestSuite/TestLoader.py
6acce44085950197f701b27c963677c3b7cd1653
[ "MIT", "LicenseRef-scancode-4suite-1.1" ]
non_permissive
flaub/Peach
https://github.com/flaub/Peach
5085536740b5ac1ff277ce6c22a193c5982e4aed
d32c01d73274af28a62c2af10879fdfa1b5c8916
refs/heads/master
2016-08-11T05:30:01.058455
2012-08-28T20:32:13
2012-08-28T20:32:13
49,538,561
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
######################################################################## # $Header: /var/local/cvsroot/4Suite/Ft/Lib/TestSuite/TestLoader.py,v 1.1 2006/08/11 15:50:12 jkloth Exp $ """ Provides the TestLoader class for loading test modules or packages. Copyright 2006 Fourthought, Inc. (USA). Detailed license and copyright information: http://4suite.org/COPYRIGHT Project home, documentation, distributions: http://4suite.org/ """ from Ft.Lib.TestSuite import TestObject class TestLoader(TestObject.TestObject): def __init__(self, name, path, addModes, skipModes, allModes): TestObject.TestObject.__init__(self, name) self.path = path self.addModes = addModes self.skipModes = skipModes self.allModes = allModes self.tests = [] return def loadTest(self, name): from Ft.Lib.TestSuite import TestModule # 'name' is relative to this loader if self.path: module_name = self.path + '.' + name else: module_name = name module = __import__(module_name, {}, {}, ['*']) return TestModule.TestModule(name, module, self.addModes, self.skipModes, self.allModes) def addTest(self, name): test = self.loadTest(name) self.tests.append(test) return test def getTests(self): return self.tests
UTF-8
Python
false
false
2,012
11,673,721,124,193
1e52881b130c5ab01635df7cd4d4d5cd1b62f774
b39d9ef9175077ac6f03b66d97b073d85b6bc4d0
/Relestat,_0,5_mg_per_ml_eye_drops,_solution_SmPC.py
e2c1193548af60ce9ef9f08ba74523be4c711968
[]
no_license
urudaro/data-ue
https://github.com/urudaro/data-ue
2d840fdce8ba7e759b5551cb3ee277d046464fe0
176c57533b66754ee05a96a7429c3e610188e4aa
refs/heads/master
2021-01-22T12:02:16.931087
2013-07-16T14:05:41
2013-07-16T14:05:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
{'_data': [['Common', [['Eye', u'sveda/\xf6gonirritation']]], ['Uncommon', [['Nervous system', u'huvudv\xe4rk'], ['Eye', u'konjunktival/okul\xe4r hyperemi, v\xe4tskande \xf6gon, torra \xf6gon, ,\xf6gonkl\xe5da synst\xf6rning, \xf6kat t\xe5rfl\xf6de *, \xf6gonsm\xe4rta *'], ['Respiratory', u'astma, irritation i n\xe4san, rinit'], <<<<<<< HEAD ['GI', u'dysgeusi']]]], ======= ['GI', u'dysgeusi * Vid klinisk anv\xe4ndning av Relestat efter marknadsintroduktion har \xf6kat t\xe5rfl\xf6de och \xf6gonsm\xe4rta identifierats.']]]], >>>>>>> eb0dbf7cfbd3e1c8a568eedcf6ca5658233104cc '_pages': [3, 4], u'_rank': 5, u'_type': u'LSFU'}
UTF-8
Python
false
false
2,013
11,596,411,734,428
f22e20b29d2a1b1890277c350e5ffbff2b5da8a3
35e73b2989520545db464f08cbf118ce903aa609
/BoulderDjangoDev/utils/urls.py
fa8e33a7ab8d5153fa99ad3acd0d67d6f64f2e84
[]
no_license
pydeveloper94/BoulderDjangoDev
https://github.com/pydeveloper94/BoulderDjangoDev
a7a410cba29190815fd17ca6f29f227e55526fdd
b219178697242e5ac1b0a210c67d599febaa0763
refs/heads/master
2020-12-30T09:57:36.895603
2014-02-20T00:03:15
2014-02-20T00:03:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from config import BASE_URL from django.core.urlresolvers import reverse from .errors import InvalidViewNameError def reverse_url(view_name, args=None, kwargs=None, current_app=None): try: url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) return "%s%s" % (BASE_URL, url) except: raise InvalidViewNameError("You must specify a valid view name " "when you call reverse_url in the utils.urls file.")
UTF-8
Python
false
false
2,014
11,613,591,598,001
b31490d5f4aa57aa699ade34abb8a6ea70c0c9f3
4aaad3e4e8b62e408bc201cd4370498ac47d0924
/tool/inf/parsing/samples/sample4.py
5d3a32034cedbe4b17007dda8163b0c3653c9680
[]
no_license
pynfer/pynfer
https://github.com/pynfer/pynfer
a60089b0cd29b3c43b153128804ad5a44af0be1c
267577fa0010ee6ef0dba1c04763ee363df09feb
refs/heads/master
2016-09-06T12:00:25.129606
2014-05-04T13:56:38
2014-05-04T13:56:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Pokus: def __init__(self): self.x= #dunno; todo self.y=2 return return 2 def mul(self): return self.x*self.y def confuse_ast(self): while x<10: y+= return y objekt: objekt. if dummy: mumly
UTF-8
Python
false
false
2,014
11,364,483,476,388
96c930370a7ea7e400e49358ab26096052f3666c
3404978caf496d4c64a09a4b86a0ffec248e1f3a
/test/test_misc.py
bfed69f60d3af91dad002baf8fb1cd4a8b6e0d74
[ "BSD-2-Clause" ]
permissive
kball/ambry
https://github.com/kball/ambry
bcc8e3550e8fad532beaabb6bda6d074b816a19a
ae865245128b92693d654fbdbb3efc9ef29e9745
refs/heads/master
2021-01-01T17:56:21.357529
2014-04-22T18:40:07
2014-04-22T18:40:07
19,428,611
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Created on Aug 31, 2012 @author: eric """ import unittest from test_base import TestBase # @UnresolvedImport class Test(TestBase): def setUp(self): pass def tearDown(self): pass def test_lru(self): from ambry.util import lru_cache from time import sleep @lru_cache(maxsize=3) def f(x): from random import randint return (x,randint(0,1000)) o = f(1) self.assertEquals(o, f(1)) self.assertEquals(o, f(1)) f(2) self.assertEquals(o, f(1)) f(3) f(4) f(5) self.assertNotEquals(o, f(1)) # # Verify expiration based on time. # @lru_cache(maxtime=3) def g(x): from random import randint return (x, randint(0, 1000)) o = g(1) sleep(2) self.assertEquals(o, g(1)) sleep(4) self.assertNotEquals(o, g(1)) def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(Test)) return suite if __name__ == "__main__": unittest.TextTestRunner().run(suite())
UTF-8
Python
false
false
2,014
10,144,712,779,675
0186c9f077b2d52b58c969c1cc9be99cc01d8a8f
d305e47f7f760e3cb3cfcd101c34f4f2cf30fcbf
/python/DataStructure/src/DataStructure/knnA.py
93e71ede14493b7fdaa865bfd7a0debdbc967ee8
[]
no_license
wherego/python
https://github.com/wherego/python
1fe2e46998bbd58f678ead829c1a3f2bbb843d22
bdd5715b24f9f32fc223420ede9b1f28d1531385
refs/heads/master
2020-12-24T15:49:41.060934
2014-12-07T14:00:34
2014-12-07T14:00:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#-*- coding: utf-8 -*- from numpy import * import operator '''构造数据''' def createDataSet(): characters=array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]]) labels=['A','A','B','B'] return characters,labels def classify(sample,dataSet,labels,k): dataSetSize=dataSet.shape[0] #数据集行数即数据集记录数 '''距离计算''' diffMat=tile(sample,(dataSetSize,1))-dataSet #样本与原先所有样本的差值矩阵 sqDiffMat=diffMat**2 #差值矩阵平方 sqDistances=sqDiffMat.sum(axis=1) #计算每一行上元素的和 distances=sqDistances**0.5 #开方 sortedDistIndicies=distances.argsort() #按distances中元素进行升序排序后得到的对应下标的列表 '''选择距离最小的k个点''' classCount={} for i in range(k): voteIlabel=labels[sortedDistIndicies[i]] classCount[voteIlabel]=classCount.get(voteIlabel,0)+1 '''从大到小排序''' sortedClassCount=sorted(classCount.items(),key=operator.itemgetter(1),reverse=True) return sortedClassCount[0][0] def main(): sample=[0,0] k=3 group,labels=createDataSet() label=classify(sample,group,labels,k) print("Classified Label:"+label) if __name__=='__main__': main()
UTF-8
Python
false
false
2,014
11,029,476,022,571
c0984de05f6a8dfc09ea7923e3427a97e7d777dc
fec06757167bc0976b67411a2e41e48d16a775e6
/src/template_repl/templatetags/repl.py
473348c737250d20f3c25ade778eb7fbeddc9f0f
[ "BSD-2-Clause" ]
permissive
carljm/django-template-repl
https://github.com/carljm/django-template-repl
12378a050ea8c6342701c8625d9148bca3dde89f
5e764bb0daf3ee5d4d69e27124c9e099b6cb9a3a
refs/heads/master
2021-01-15T21:03:05.297774
2009-12-10T17:39:22
2009-12-10T17:39:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from template_repl.repl import setup_readline_history, run_shell from django.template import Node, Library register = Library() class REPLNode(Node): def render(self, context): setup_readline_history() run_shell(context) return '' @register.tag def repl(parser, token): return REPLNode()
UTF-8
Python
false
false
2,009
10,050,223,481,347
26e30acbea1be519fb23c0fff05bb82bdccff8fa
f96a65ef4f63b51d5f15289bbb4174afef040538
/crafty/migrations/0011_auto_20141102_1948.py
5e984b2b8cf00426dc7d5f06c0502be616bf7e9d
[]
no_license
ScottBuchanan/liquor_panda
https://github.com/ScottBuchanan/liquor_panda
f6adc63c15daa7fcdd34e961e017865365f4f112
9a1d092af80e3c92a9ee9be78d51b5354ea4b4b5
HEAD
2017-12-21T19:25:01.701270
2014-11-07T07:09:11
2014-11-07T07:09:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('crafty', '0010_auto_20141102_1937'), ] operations = [ migrations.AlterField( model_name='brewery', name='lat', field=models.FloatField(default=49.25, max_length=200, verbose_name=b'lat'), ), migrations.AlterField( model_name='brewery', name='lon', field=models.FloatField(default=123.1, max_length=200, verbose_name=b'lon'), ), migrations.AlterField( model_name='store', name='lat', field=models.FloatField(default=49.25, max_length=200, verbose_name=b'lat'), ), migrations.AlterField( model_name='store', name='lon', field=models.FloatField(default=123.1, max_length=200, verbose_name=b'lon'), ), ]
UTF-8
Python
false
false
2,014
4,432,406,265,785
9ec18f828d45723a472cdec6081ea15eb28402ee
77ccdbd8b3ade1a3e5db3afc96593d2aa05d8dc4
/internal/internal/urls.py
1fa0cb645310b3fefe1e064c56424a3b1f1f7005
[]
no_license
asilvaC/kalite-internal
https://github.com/asilvaC/kalite-internal
b1856267e5b099866a02303ad8403af63505f0e8
6765e67e366f3fc3b5ad4cd5f98f3d16ce93397f
refs/heads/master
2021-01-15T17:21:15.768650
2013-09-03T02:28:00
2013-09-03T02:28:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import * # Uncomment the next two lines to enable the admin: from django.contrib import admin import feedbacks.urls import profiles.urls import projects.urls import views admin.autodiscover() urlpatterns = patterns('', url('^$', profiles.urls.profile_index, name='home'), url(r'^login/$', 'django.contrib.auth.views.login', {'template_name' : 'internal/login.html'}), url(r'^logout/$', 'profiles.views.logout', name='logout'), url(r'^admin/', include(admin.site.urls)), url(r'^profiles/', include(profiles.urls)), url(r'^projects/', include(projects.urls)), url(r'^feedbacks/', include(feedbacks.urls)), url(r'^contact/', views.contact) )
UTF-8
Python
false
false
2,013
13,932,873,958,574
e3684c6f7d1922edc5e9a0db1acf451fefb12467
175aa821c27b55444cc0808732e12c1df33119ec
/myproject/manager/templatetags/custom_filters.py
01d967f67b59d5a4bdf6935fb8ec592816384182
[]
no_license
deftone/kvmmanager
https://github.com/deftone/kvmmanager
6c8101f7711f9fa2eb3638d145e4f93a370ff854
13ae2e5d26538ffc5fa14e2cfdb48f309aead7f6
refs/heads/master
2016-08-04T06:35:13.779072
2013-05-27T22:57:22
2013-05-27T22:57:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django import template register = template.Library() @register.filter def key(d, key_name): out_mem=d[key_name]['Memory'] out_cpu=d[key_name]['CPU'] output = 'Memory - %sMB, CPU - %s' % (out_mem, out_cpu) return output def vnc_port(d,key_name): port=d[key_name]['VNC'] return port def graph_parse(d, key_name): output=d[key_name] return output key = register.filter('key', key) graph_parse = register.filter('graph_parse', graph_parse) vnc_port = register.filter('vnc_port', vnc_port)
UTF-8
Python
false
false
2,013
1,047,972,024,942
cf8eff9dea17234409bec5e7ad16ea03ff90a305
984959f729615658dc4e2947db33e92d3588ca9d
/crawler/config.py
7ff9019c36b050adb5c0d7f3f7ee83f605b5d5c2
[ "MIT" ]
permissive
plrthink/musicians
https://github.com/plrthink/musicians
153c5a8d127a2963c310f81c3226270cd90bf1e1
dfd914a384f9609d44948cb21514e09ab6fb19cd
refs/heads/master
2020-12-11T05:51:55.944597
2014-12-21T08:35:13
2014-12-21T08:35:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from firebase import firebase MUSICIANS_PAGE_PICKLE_PATH = 'musicians.pickle' FIREBASE_BASE_PATH = "https://musicians.firebaseio.com/" MUSICIAN_STORE = 'musicians' firebase = firebase.FirebaseApplication( FIREBASE_BASE_PATH, None )
UTF-8
Python
false
false
2,014
721,554,556,262
080b9294e29a6b5c4ebc819490ed0da01113a19e
c1469b5d50d4f102f108487bf81be8e78dc4238b
/symantecssl/exceptions.py
9df85d228730cd8de19cf586c58389d0f5b0f58f
[ "Apache-2.0" ]
permissive
dmendiza/symantecssl
https://github.com/dmendiza/symantecssl
3fb19a6cdb340bfa57e193a20816d15d811551b7
20b0dfa202c2d5fffe9e7e96dbe4ebf3f3b7cc9b
refs/heads/master
2021-12-14T17:06:09.629539
2014-04-29T02:16:22
2014-04-29T02:16:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from __future__ import absolute_import, division, print_function class SymantecValueError(ValueError): def __init__(self, *args, **kwargs): self.errors = kwargs.pop("errors") super(SymantecValueError, self).__init__(*args, **kwargs)
UTF-8
Python
false
false
2,014
5,007,931,868,294
b0fb7340819a9a9db1652c06ac708c02b973c75f
4dfbf3396f7294b6868f65a844d506ec89511bba
/Aplicacion.py
6c9c56765f6eb902b12ede2e707d1e35fcab9e7b
[]
no_license
Pablo--Martinez/HumTemp
https://github.com/Pablo--Martinez/HumTemp
611cb8a88f954be2780b96f9a6e809961f2e6e73
8c587ca13be25dfb8c2f4847b4ac821e50bbb7b1
refs/heads/master
2016-09-05T15:56:16.530324
2014-02-26T18:22:32
2014-02-26T18:22:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import subprocess import pygtk import datetime pygtk.require("2.0") import gtk import gtk.glade import psycopg2 import psycopg2.extras import sys from time import sleep from Plot import plot from os import mkdir CONF_PATH = "/home/pi/digitemp.conf" USB_ADAPTER = "digitemp_DS9097U" USB_PATH = "/dev/ttyUSB0" NO_USB_ADAPTER = "DigiTemp v3.5.0 Copyright 1996-2007 by Brian C. Lane\nGNU General Public License v2.0 - http://www.digitemp.com\n" separador = ";" pines = ["4","17","18","22","23","24","25","27"] errores = ["Ya existe sesion activa","Debe terminar la sesion activa para bajar datos", "No existe sesion activa actualmente","No es posible bajar datos de sesion actual"] def IniciarCensado(gui,nombre,ciclo,terminal): """ Inicia el ciclo de sensado, los datos son almacenados cada "ciclo" minutos bajo el nombre de "nombre", se asume que no esta censando actualmente """ if (Estado() == 0): db = psycopg2.connect(database="MapeoDB", user="pi", password="bioguardpassword") cursor = db.cursor(cursor_factory=psycopg2.extras.DictCursor) cursor.execute("INSERT INTO sesion (\"NOMBRE\",\"CICLO\",\"CONT\",\"GPIO\",\"ONEWIRE\",\"INICIO\") VALUES (%s,%s,%s,'{0,0,0,0,0,0,0,0}',0,%s)",(nombre,ciclo-1,ciclo-1,datetime.datetime.now().strftime('%Y-%m-%d %H:%M'))) db.commit() cursor.execute("SELECT \"ID\" FROM sesion WHERE \"NOMBRE\"=%s",(nombre,)) sesion = cursor.fetchone() cursor.execute("UPDATE control SET \"ID_SESION\"=%s, \"ESTADO\"=1 WHERE \"ID\"=1",(sesion["ID"],)) db.commit() """if (sensor == 1): #db.UpdateRegisterInTable(ctr,["id",1],["sensor",11]) cursor.execute("UPDATE \"control\" SET \"name\"=%s, \"ciclo\"=%s, \"sensor\"=%s, \"veces\"=%s, \"status\"=%s WHERE \"id\"=1",(nombre,ciclo-1,11,0,1)) else: #db.UpdateRegisterInTable(ctr,["id",1],["sensor",22]) cursor.execute("UPDATE \"control\" SET \"name\"=%s, \"ciclo\"=%s, \"sensor\"=%s, \"veces\"=%s, \"status\"=%s WHERE \"id\"=1",(nombre,ciclo-1,22,0,1)) db.commit()""" #Configuro los sensores 1wire salida = subprocess.Popen(["sudo",USB_ADAPTER,"-i","-s",USB_PATH,"-c",CONF_PATH],stdout=subprocess.PIPE).communicate()[0] if (salida != NO_USB_ADAPTER): f = open("/home/pi/digitemp.conf","r") lines = f.readlines() lines = lines[7:] cursor.execute("UPDATE sesion SET \"ONEWIRE\"=%s WHERE \"ID\"=%s",(len(lines),sesion["ID"])) db.commit() #gui.glade.get_object("label23").set_markup('<span color="green">%i</span>'%(len(lines))) f.close() else: gui.glade.get_object("label23").set_markup('<span color="red">-</span>') #Busco que sensor de temp/hum esta conectado for i in range(len(pines)): intentos = 0 MAX_INTENTOS = 3 salida = subprocess.Popen(["sudo","/home/pi/Desktop/HumTemp/Adafruit_DHT2","22",pines[i]],stdout=subprocess.PIPE).communicate()[0] while (salida == "" and intentos <= MAX_INTENTOS): #Intento tomar la medida sleep(1) salida = subprocess.Popen(["sudo","/home/pi/Desktop/HumTemp/Adafruit_DHT2","22",pines[i]],stdout=subprocess.PIPE).communicate()[0] intentos += +1 if (intentos <= MAX_INTENTOS):#Hay sensor cursor.execute("UPDATE sesion SET \"GPIO\"[%s]=%s WHERE \"ID\"=%s",(i+1,1,sesion["ID"])) db.commit() else: cursor.execute("UPDATE sesion SET \"GPIO\"[%s]=%s WHERE \"ID\"=%s",(i+1,0,sesion["ID"])) db.commit() sleep(1) intentos = 0 db.close() if (not terminal): sensores = SensoresActivos() gui.glade.get_object("label23").set_markup('<span color="green">%i</span>'%(sensores[1])) if (sensores[0][0] == 1): gui.glade.get_object("label7").set_markup('<span color="green">OK</span>') else: gui.glade.get_object("label7").set_markup('<span color="red">-</span>') if (sensores[0][1] == 1): gui.glade.get_object("label11").set_markup('<span color="green">OK</span>') else: gui.glade.get_object("label11").set_markup('<span color="red">-</span>') if (sensores[0][2] == 1): gui.glade.get_object("label15").set_markup('<span color="green">OK</span>') else: gui.glade.get_object("label15").set_markup('<span color="red">-</span>') if (sensores[0][3] == 1): gui.glade.get_object("label19").set_markup('<span color="green">OK</span>') else: gui.glade.get_object("label19").set_markup('<span color="red">-</span>') if (sensores[0][4] == 1): gui.glade.get_object("label9").set_markup('<span color="green">OK</span>') else: gui.glade.get_object("label9").set_markup('<span color="red">-</span>') if (sensores[0][5] == 1): gui.glade.get_object("label13").set_markup('<span color="green">OK</span>') else: gui.glade.get_object("label13").set_markup('<span color="red">-</span>') if (sensores[0][6] == 1): gui.glade.get_object("label17").set_markup('<span color="green">OK</span>') else: gui.glade.get_object("label17").set_markup('<span color="red">-</span>') if (sensores[0][7] == 1): gui.glade.get_object("label21").set_markup('<span color="green">OK</span>') else: gui.glade.get_object("label21").set_markup('<span color="red">-</span>') GUI_Mensaje("%s: Sesion iniciada"%(Nombre())) else: print("%s: Sesion iniciada"%(Nombre())) else: if (not terminal): GUI_Mensaje(errores[0]) else: print(errores[0]) def TerminarCensado(gui,terminal): """ Cancela el censado actual, asume que actualmente se esta censando """ db = psycopg2.connect(database="MapeoDB", user="pi", password="bioguardpassword") cursor = db.cursor() if (Estado() == 1): cursor.execute("UPDATE control SET \"ESTADO\"=0 WHERE \"ID\"=1") cursor.execute("UPDATE sesion SET \"FIN\"=%s",(datetime.datetime.now().strftime('%Y-%m-%d %H:%M'),)) db.commit() if (not terminal): gui.glade.get_object("label23").set_markup('<span color="red">-</span>') BajarDatos(Nombre(),0) GUI_Mensaje("%s: Sesion terminada"%(Nombre())) else: BajarDatos(Nombre(),1) print("%s: Sesion terminada"%(Nombre())) else: if (not terminal): GUI_Mensaje(errores[2]) else: print(errores[2]) db.close() def BajarDatos(nombre,terminal): """ Baja los datos de la sesion con nombre pasado como parametro """ if (Nombre() != nombre or Estado() == 0): db = psycopg2.connect(database="MapeoDB", user="pi", password="bioguardpassword") cursor = db.cursor(cursor_factory=psycopg2.extras.DictCursor) cursor.execute("SELECT \"ID\" FROM sesion WHERE \"NOMBRE\"=%s",(nombre,)) sesion = cursor.fetchone() if(type(sesion) == psycopg2.extras.DictRow): cursor.execute("SELECT * FROM registro WHERE \"ID_SESION\"=%s ORDER BY \"ID\"",(sesion["ID"],)) rows = cursor.fetchall() if (len(rows) > 0): dir = "/home/pi/Desktop/HumTemp/Archivos/%s" % nombre mkdir(dir) f = open("/home/pi/Desktop/HumTemp/Archivos/" + nombre + "/humedad.txt","w") g = open("/home/pi/Desktop/HumTemp/Archivos/" + nombre + "/temperatura.txt","w") one_wire = False; for row in rows: if(row["TIPO"] == "H"): linea = str(row["SENSOR"]) + separador + str(row["FECHA"]) + separador + str(row["TEMP"]) + separador + str(row["HUM"]) f.write(linea+"\n") else: one_wire = True linea = str(row["SENSOR"]) + separador + str(row["FECHA"]) + separador + str(row["TEMP"]) + separador g.write(linea+"\n") f.close() g.close() if (one_wire): f = open("/home/pi/digitemp.conf","r") lineas = f.readlines() lineas = lineas[7:] sensor_roms = open("/home/pi/Desktop/HumTemp/Archivos/" + nombre + "/ROMS.txt","w") for i in range(len(lineas)): rom = lineas[i][lineas[i].find("0x"):-2] sensor_roms.write("SENSOR:%i -> ROM:%s\n"%(i,rom)) f.close() sensor_roms.close() if (not terminal): GUI_Mensaje("%s: Datos guardados correctamente" %(nombre)) else: print("%s: Datos guardados correctamente" %(nombre)) else: if (not terminal): GUI_Mensaje("%s: No existen registros" %(nombre)) else: print("%s: No existen registros" %(nombre)) db.close() else: if (not terminal): GUI_Mensaje(errores[3]) else: print(errores[3]) def Estado(): """ Retorna el estado actual del censado """ db = psycopg2.connect(database="MapeoDB", user="pi", password="bioguardpassword") cursor = db.cursor(cursor_factory=psycopg2.extras.DictCursor) cursor.execute("SELECT \"ESTADO\" FROM control WHERE \"ID\"=1") control = cursor.fetchone() db.close() return control["ESTADO"] def Nombre(): """ Retorna el nombre del censado actual """ db = psycopg2.connect(database="MapeoDB", user="pi", password="bioguardpassword") cursor = db.cursor(cursor_factory=psycopg2.extras.DictCursor) cursor.execute("SELECT \"ID_SESION\" FROM control WHERE \"ID\"=1") control = cursor.fetchone() cursor.execute("SELECT \"NOMBRE\" FROM sesion WHERE \"ID\"=%s",(control["ID_SESION"],)) sesion = cursor.fetchone() db.close() return sesion["NOMBRE"] def Ciclo(): """ Retorna el ciclo del censado actual """ db = psycopg2.connect(database="MapeoDB", user="pi", password="bioguardpassword") cursor = db.cursor(cursor_factory=psycopg2.extras.DictCursor) cursor.execute("SELECT \"ID_SESION\" FROM control WHERE \"ID\"=1") control = cursor.fetchone() cursor.execute("SELECT \"CICLO\" FROM sesion WHERE \"ID\"=%s",(control["ID_SESION"],)) sesion = cursor.fetchone() db.close() return sesion["CICLO"] + 1 """ def Sensor(): #db = PostgreSQL.PostgreSQL(namedb="BioGuardDB",username="BioGuard",host='localhost',passw="bioguardpassword") #row = db.SelectFromTable(ctr,["id",1]) #db.CloseDB() #return row[0][5] db = psycopg2.connect(database="MapeoDB", user="pablo", password="bioguardpassword") cursor = db.cursor(cursor_factory=psycopg2.extras.DictCursor) cursor.execute("SELECT \"sensor\" FROM \"control\" WHERE \"ID\"=1") row = cursor.fetchone() db.close() return row["sensor"] """ def SensoresActivos(): """ Retorna una lista con los sensores, activos y desactivos """ db = psycopg2.connect(database="MapeoDB", user="pi", password="bioguardpassword") cursor = db.cursor(cursor_factory=psycopg2.extras.DictCursor) cursor.execute("SELECT \"ID_SESION\" FROM control WHERE \"ID\"=1") control = cursor.fetchone() cursor.execute("SELECT \"GPIO\", \"ONEWIRE\" FROM sesion WHERE \"ID\"=%s",(control["ID_SESION"],)) sesion= cursor.fetchone() db.close() sensores = sesion["GPIO"] one_wire = sesion["ONEWIRE"] return [sensores,one_wire] class GUI_Mensaje(): def __init__(self,texto): error = gtk.MessageDialog(parent=None, flags=0, buttons=gtk.BUTTONS_OK) error.set_title("BioGuard") error.set_size_request(400,150) error.connect("delete-event", gtk.main_quit) label = gtk.Label(texto) error.vbox.pack_start(label) error.show_all() error.run() error.destroy() class App(): def __init__(self): self.gladefile = "/home/pi/Desktop/HumTemp/app.glade" self.glade = gtk.Builder() self.glade.add_from_file(self.gladefile) self.glade.connect_signals(self) self.glade.get_object("MainWindow") self.glade.get_object("window1").set_title("BioGuard") self.glade.get_object("window1").connect("delete-event", gtk.main_quit) self.functions = {"start":self.startButton, "stop":self.stopButton, "download":self.downloadData, "plot":self.plotData, "exit":self.exit} if (Estado() == 1): self.glade.get_object("label5").set_markup('<span color="green">CENSANDO</span>') self.glade.get_object("button2").set_sensitive(True) self.glade.get_object("button1").set_sensitive(False) self.glade.get_object("entry3").set_sensitive(False) self.glade.get_object("entry3").set_text(Nombre()) self.glade.get_object("entry4").set_sensitive(False) self.glade.get_object("entry4").set_text(str(Ciclo())) #self.glade.get_object("combobox1").set_sensitive(False) listaelementos=gtk.ListStore(str) """ if (Sensor() == 11): listaelementos.append(["DHT22"]) listaelementos.append(["DHT11"]) else: listaelementos.append(["DHT11"]) listaelementos.append(["DHT22"]) self.glade.get_object("combobox1").set_model(listaelementos) render = gtk.CellRendererText() self.glade.get_object("combobox1").pack_start(render, True) self.glade.get_object("combobox1").add_attribute(render, 'text', 0) """ sensores = SensoresActivos() if (sensores[1] != 0): self.glade.get_object("label23").set_markup('<span color="green">%i</span>'%(sensores[1])) else: self.glade.get_object("label23").set_markup('<span color="red">-</span>') if (sensores[0][0] == 1): self.glade.get_object("label7").set_markup('<span color="green">OK</span>') else: self.glade.get_object("label7").set_markup('<span color="red">-</span>') if (sensores[0][1] == 1): self.glade.get_object("label11").set_markup('<span color="green">OK</span>') else: self.glade.get_object("label11").set_markup('<span color="red">-</span>') if (sensores[0][2] == 1): self.glade.get_object("label15").set_markup('<span color="green">OK</span>') else: self.glade.get_object("label15").set_markup('<span color="red">-</span>') if (sensores[0][3] == 1): self.glade.get_object("label19").set_markup('<span color="green">OK</span>') else: self.glade.get_object("label19").set_markup('<span color="red">-</span>') if (sensores[0][4] == 1): self.glade.get_object("label9").set_markup('<span color="green">OK</span>') else: self.glade.get_object("label9").set_markup('<span color="red">-</span>') if (sensores[0][5] == 1): self.glade.get_object("label13").set_markup('<span color="green">OK</span>') else: self.glade.get_object("label13").set_markup('<span color="red">-</span>') if (sensores[0][6] == 1): self.glade.get_object("label17").set_markup('<span color="green">OK</span>') else: self.glade.get_object("label17").set_markup('<span color="red">-</span>') if (sensores[0][7] == 1): self.glade.get_object("label21").set_markup('<span color="green">OK</span>') else: self.glade.get_object("label21").set_markup('<span color="red">-</span>') else: self.glade.get_object("button2").set_sensitive(False) self.glade.get_object("label5").set_markup('<span color="red">SIN CENSAR</span>') self.glade.get_object("button1").set_sensitive(True) self.glade.get_object("entry3").set_sensitive(True) self.glade.get_object("entry4").set_sensitive(True) #self.glade.get_object("combobox1").set_sensitive(True) self.glade.get_object("label7").set_markup('<span color="red">-</span>') self.glade.get_object("label11").set_markup('<span color="red">-</span>') self.glade.get_object("label15").set_markup('<span color="red">-</span>') self.glade.get_object("label19").set_markup('<span color="red">-</span>') self.glade.get_object("label9").set_markup('<span color="red">-</span>') self.glade.get_object("label13").set_markup('<span color="red">-</span>') self.glade.get_object("label17").set_markup('<span color="red">-</span>') self.glade.get_object("label21").set_markup('<span color="red">-</span>') listaelementos=gtk.ListStore(str) listaelementos.append(["DHT22"]) listaelementos.append(["DHT11"]) #self.glade.get_object("combobox1").set_model(listaelementos) render = gtk.CellRendererText() #self.glade.get_object("combobox1").pack_start(render, True) #self.glade.get_object("combobox1").add_attribute(render, 'text', 0) def startButton(self,widget): """ Starts a new session """ #Desactivo la sensibilidad de algunos elementos widget.set_sensitive(False) self.glade.get_object("label5").set_markup('<span color="green">CENSANDO</span>') self.glade.get_object("button2").set_sensitive(True) self.glade.get_object("entry3").set_sensitive(False) self.glade.get_object("entry4").set_sensitive(False) #self.glade.get_object("combobox1").set_sensitive(False) #Obtengo los datos para iniciar la sesion} nombre= str(self.glade.get_object("entry3").get_text()) ciclo = int(self.glade.get_object("entry4").get_text()) #sensor = int(self.glade.get_object("combobox1").get_active()) IniciarCensado(self,nombre,ciclo,0) def stopButton(self,widget): """ Stops the current session """ widget.set_sensitive(False) self.glade.get_object("label5").set_markup('<span color="red">SIN CENSAR</span>') self.glade.get_object("button1").set_sensitive(True) self.glade.get_object("entry3").set_sensitive(True) self.glade.get_object("entry4").set_sensitive(True) #self.glade.get_object("combobox1").set_sensitive(True) self.glade.get_object("label7").set_markup('<span color="red">-</span>') self.glade.get_object("label11").set_markup('<span color="red">-</span>') self.glade.get_object("label15").set_markup('<span color="red">-</span>') self.glade.get_object("label19").set_markup('<span color="red">-</span>') self.glade.get_object("label9").set_markup('<span color="red">-</span>') self.glade.get_object("label13").set_markup('<span color="red">-</span>') self.glade.get_object("label17").set_markup('<span color="red">-</span>') self.glade.get_object("label21").set_markup('<span color="red">-</span>') TerminarCensado(self,0) def downloadData(self,widget): """ Donwload specific data from a session """ nombre = self.glade.get_object("entry1").get_text() BajarDatos(nombre,0) def plotData(self,widget): """ Plot specific data, if widget.get_text() == "" plot the current session """ nombre = self.glade.get_object("entry2").get_text() plot(nombre) def exit(self,widget): gtk.main_quit() class Terminal(): """ Permite ejecutar la aplicacion en version terminal """ comandos = ["ayuda","iniciar","terminar","bajar","estado","salir"] def __init__(self): comando = raw_input("BIOGUARD $ ").split(" ") while (comando[0] != "salir"): if (comando[0] == "iniciar"): #Inicio de sesion if (len(comando) >= 4): #Cantidad de comandos correctos if (Estado() == 0): #No se esta censando acutalmente if (type(comando[2] == "int")): #El ciclo es un numero IniciarCensado("",comando[1],int(comando[2]),comando[3],1) print("Sesion iniciada...") else: print("ciclo incorrecto...") else: print(errores[0]) else: print("Argumentos faltantes...") elif(comando[0] == "terminar"): #Terminar sesion activa TerminarCensado("",1) elif(comando[0] == "estado"): #Imprimo los valores actuales de la sesion si esta activa if (Estado() == 1): print(" -Estado --> Corriendo") print(" -Nombre --> %s" %(Nombre())) print(" -Ciclo --> %i" %(Ciclo())) """if (Sensor() == 0): print(" -Sensor --> DHT11") else: print(" -Sensor --> DHT22")""" else: print(" -Estado --> Detenido") elif(comando[0] == "bajar"): #Bajo los datos de la sesion actual if (len(comando) >= 2): BajarDatos(comando[1],1) else: print("Argumentos faltantes...") elif(comando[0] == "ayuda"): #Imprimo ayuda en pantalla print(" -ayuda --> Menu de ayuda") print(" -iniciar nombre ciclo --> Crea una nueva sesion") print(" -terminar --> Termina la sesion actual") print(" -bajar nombre --> Baja los datos de la sesion actual") print(" -estado --> Muestra el estado del sistema ") else: print("Comando desconocido...") comando = raw_input("BIOGUARD $ ").split(" ") sys.exit() if __name__ == "__main__": if (len(sys.argv) >= 2): if (sys.argv[1] == "-t"): Terminal() else: gui = App() gtk.main()
UTF-8
Python
false
false
2,014
17,042,430,274,377
71b53752276d13de186c2ec6985d84cd80ede193
1a1aae59eb1b4108cc23a2a15ca16d7c07bb88ca
/celery/worker/heartbeat.py
fde7b0f6834b1d30f7caaece6d975f8722710995
[ "BSD-3-Clause" ]
permissive
dmishe/celery
https://github.com/dmishe/celery
b493ccd16e60c6c4eae1f785050ed8eba4b4dc7f
80cf4c9876ac5e10852a5c3bc279b796fca245b7
refs/heads/master
2021-01-18T06:41:57.018382
2009-12-08T13:45:12
2009-12-08T13:45:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import threading from time import time, sleep class Heart(threading.Thread): interval = 60 def __init__(self, eventer, interval=None): super(Heart, self).__init__() self.eventer = eventer self.interval = interval or self.interval self._shutdown = threading.Event() self._stopped = threading.Event() self.setDaemon(True) self._state = None def run(self): self._state = "RUN" interval = self.interval dispatch = self.eventer.send dispatch("worker-online") # We can't sleep all of the interval, because then # it takes 60 seconds (or value of interval) to shutdown # the thread. last_beat = None while 1: if self._shutdown.isSet(): break now = time() if not last_beat or now > last_beat + interval: last_beat = now dispatch("worker-heartbeat") sleep(1) try: dispatch("worker-offline") finally: self._stopped.set() def stop(self): """Gracefully shutdown the thread.""" if not self._state == "RUN": return self._state = "CLOSE" self._shutdown.set() self._stopped.wait() # block until this thread is done
UTF-8
Python
false
false
2,009
11,158,325,047,922
aaab94d307795e651f0ebdb074424c61d627e67a
0f6c37a56a36398ed9319ed30e335747f966ca94
/polychart/main/views/user.py
8c668148711fcb066592c65c83f7941fafea2041
[ "AGPL-3.0-only" ]
non_permissive
Polychart/builder
https://github.com/Polychart/builder
11fd618765ded27fd3fe2fa7d0225e33885d562a
a352ccd62a145c7379e954253c722e9704178f20
refs/heads/master
2020-05-20T02:24:15.921708
2014-07-01T16:51:44
2014-07-01T16:51:44
16,490,552
47
15
null
false
2016-02-05T17:25:07
2014-02-03T19:37:18
2016-02-04T15:02:33
2014-07-01T16:51:44
2,199
82
25
3
Python
null
null
""" Tornado Request handlers for the user settings page (/settings) """ import django.db import logging from django import forms from django.contrib.auth import authenticate from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.shortcuts import render from polychart.main import models as m from polychart.main.utils import secureStorage class UserInfoForm(forms.Form): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(UserInfoForm, self).__init__(*args, **kwargs) email = forms.EmailField(max_length = 75) name = forms.CharField(max_length = 30) company = forms.CharField(max_length = 128, required = False) website = forms.CharField(max_length = 128, required = False) def clean_email(self): email = self.cleaned_data['email'] # see if any other user uses this email. if User.objects.filter(email=email).exclude(pk=self.user.pk).exists(): raise ValidationError('Email %s is already being used.' % email) return email class PasswordForm(forms.Form): old = forms.CharField(widget = forms.PasswordInput, required = True) new = forms.CharField(widget = forms.PasswordInput, required = True) veri = forms.CharField(widget = forms.PasswordInput, required = True) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(PasswordForm, self).__init__(*args, **kwargs) def clean(self): if self.cleaned_data.get('new', None) != self.cleaned_data.get('veri', None): raise ValidationError("New passwords did not match.") return self.cleaned_data def clean_old(self): old = self.cleaned_data.get('old', None) if authenticate(username=self.user.username, password=old) != self.user: raise ValidationError("Old password is incorrect.") return old @login_required def userSettings(request): def createUserInfoForm(user): userInfo = m.UserInfo.objects.get(user=request.user) return UserInfoForm( initial={ 'company': userInfo.company, 'email': user.email, 'name': user.first_name, 'website': userInfo.website, }, user=request.user ) if request.method == 'GET': return render(request, 'settings.tmpl', dict( userinfo_form=createUserInfoForm(request.user), password_form=PasswordForm() )) if request.method == 'POST': action = request.REQUEST.get('action', None) if action == 'change-pswd': user = request.user password_form = PasswordForm(request.REQUEST, user = user) result = None errorMsg = None if password_form.is_valid(): new = password_form.cleaned_data['new'] user.set_password(new) user.save() salt = m.UserInfo.objects.get(user=user).secure_storage_salt request.session['secureStorageKey'] = secureStorage.getEncryptionKey(new, salt) result = 'success' else: if password_form.errors.get('__all__', None): errorMsg = password_form.errors['__all__'][0] else: errorMsg = "There was an error while updating the password." result = 'error' return render(request, 'settings.tmpl', dict( userinfo_form = createUserInfoForm(request.user), password_form = password_form, action = action, result = result, errorMsg = errorMsg )) if action == 'update-info': user = request.user userinfo_form = UserInfoForm(request.REQUEST, user = user) result = None errorMsg = None if userinfo_form.is_valid(): user.email = userinfo_form.cleaned_data['email'] user.first_name = userinfo_form.cleaned_data['name'] try: user.save() except django.db.IntegrityError: # TODO - error must be handled here. logging.exception('error while changing the email of the user.') else: # update the company info. userinfo = user.userinfo userinfo.company = userinfo_form.cleaned_data['company'] userinfo.website = userinfo_form.cleaned_data['website'] userinfo.save() result = 'success' else: if userinfo_form.errors.get('__all__', None): errorMsg = userinfo_form.errors['__all__'][0] else: errorMsg = "There was an error while updating the personal information." result = 'error' return render(request, 'settings.tmpl', dict( userinfo_form = userinfo_form, password_form = PasswordForm(), action = action, result = result, errorMsg = errorMsg )) return render(request, 'settings.tmpl')
UTF-8
Python
false
false
2,014
1,958,505,113,410
b7437e51ff9a0fa388dc02339e02912c9a457a94
fc24c61fc2635ac9cebb8095fd92b37469c07cb6
/PyRAF-Aqua/pyraf/lib/pyraf
4f7361ee64c5889aa39b2f3b8c60e73267bed286
[ "BSD-2-Clause" ]
permissive
BackupTheBerlios/pyimtool-svn
https://github.com/BackupTheBerlios/pyimtool-svn
2c935462194ff694a7d07a8bd1ce2d9d4bf501fb
91ccfbae21aa4a142c1660f1a69c440673b8c19d
refs/heads/master
2021-03-12T23:50:14.410488
2005-03-30T00:06:13
2005-03-30T00:06:13
40,801,646
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! python -i """ Copyright (C) 2003 Association of Universities for Research in Astronomy (AURA) See LICENSE.txt in the docs directory of the source distribution for the terms of use. Usage: pyraf [options] [savefile] where savefile is an optional save file to start from and options are one or more of: -s Silent initialization (does not print startup messages) -n No splash screen during startup -v Set verbosity level (may be repeated to increase verbosity) -m Run command line wrapper to provide extra capabilities (default) -i Do not run command line wrapper, just run standard Python front end -h Print this message Long versions of options: -s --silent -n --nosplash -v --verbose -m --commandwrapper=yes -i --commandwrapper=no -h --help """ # $Id: pyraf,v 1.2 2003/10/08 19:11:48 dencheva Exp $ # # R. White, 2000 January 21 import sys, os # set search path to include directory above this script and current directory # ... but do not want the pyraf package directory itself in the path, since # that messes things up by allowing direct imports of pyraf submodules # (bypassing the __init__ mechanism.) # follow links to get to the real executable filename executable = sys.argv[0] while os.path.islink(executable): executable = os.readlink(executable) pyrafDir = os.path.dirname(executable) del executable try: sys.path.remove(pyrafDir) except ValueError: pass absPyrafDir = os.path.abspath(os.path.join(pyrafDir,'..')) if absPyrafDir not in sys.path: sys.path.insert(0, absPyrafDir) del absPyrafDir, pyrafDir if "." not in sys.path: sys.path.insert(0, ".") # read the user's startup file (if there is one) if os.environ.has_key("PYTHONSTARTUP") and \ os.path.isfile(os.environ["PYTHONSTARTUP"]): execfile(os.environ["PYTHONSTARTUP"]) from pyraf import doCmdline, iraf, __version__ from pyraf.irafpar import makeIrafPar from pyraf.irafglobals import yes, no, INDEF, EOF logout = quit = exit = 'Use ".exit" to exit' print "PyRAF", __version__, "Copyright (c) 2002 AURA" # just print first line of Python copyright (long in v2.0) print "Python", sys.version.split()[0], sys.copyright.split('\n')[0] if doCmdline: del doCmdline # Start up command line wrapper keeping definitions in main name space # Keep the command-line object in namespace too for access to history import pyraf.pycmdline _pycmdline = pyraf.pycmdline.PyCmdLine(locals=globals()) _pycmdline.start() else: del doCmdline
UTF-8
Python
false
false
2,005
13,881,334,323,431
5bbf2cc7bdc2b32024ad029a13abba0214e76ab7
2030cb70d78fc84e59cc06fab27544802649795c
/Binary Tree Preorder Traversal.py
3645fb2d331f8c2bcf51d694005d2217f313690b
[]
no_license
archangelys/leetcode
https://github.com/archangelys/leetcode
dbcead25e75d0c6541e9ca84dcd52cd583bb78c8
242d34f2a3179128741ad13e876778f42e9bb5ac
refs/heads/master
2020-05-18T11:18:27.716664
2014-03-19T13:46:05
2014-03-19T13:46:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__author__ = 'song.yang' # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of integers def preorderTraversal(self, root): order = [] self._traver(root,order) def _traver(self, node, order): if node.left: order = self._traver(node.left, order) order.append(node.val) if node.right: self._traver(node.right, order)
UTF-8
Python
false
false
2,014
13,168,369,751,968
23622aa046caa30b1c504e74603dc4af4f443452
c091b77ce16967971b9e98671c2a37697419e17c
/httpclient/request.py
db8f3fe157c001e6251182ad5c83b9b9c7f73b30
[]
no_license
waytai/httpclient
https://github.com/waytai/httpclient
b35925ba1e9b17d418864cb1fa96c498b16f85a0
559def074a1e979f53822639cc3c5f86945ecc2d
refs/heads/master
2021-01-22T02:34:19.502730
2013-10-13T22:56:28
2013-10-13T22:56:28
14,086,912
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"""http request""" import base64 import collections import email.message import http.client import http.cookies import io import itertools import mimetypes import os import uuid import urllib.parse import tulip import tulip.http class HttpRequest: GET_METHODS = {'DELETE', 'GET', 'HEAD', 'OPTIONS'} POST_METHODS = {'PATCH', 'POST', 'PUT', 'TRACE'} ALL_METHODS = GET_METHODS.union(POST_METHODS) DEFAULT_HEADERS = { 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', } body = b'' def __init__(self, method, url, *, params=None, headers=None, data=None, cookies=None, files=None, auth=None, encoding='utf-8', version=(1, 1), compress=None, chunked=None): self.method = method.upper() self.encoding = encoding if isinstance(version, str): v = [l.strip() for l in version.split('.', 1)] version = int(v[0]), int(v[1]) self.version = version scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url) if not netloc: raise ValueError() if not path: path = '/' else: path = urllib.parse.unquote(path) # check domain idna encoding try: netloc = netloc.encode('idna').decode('utf-8') except UnicodeError: raise ValueError('URL has an invalid label.') if '@' in netloc: authinfo, netloc = netloc.split('@', 1) if not auth: auth = authinfo.split(':', 1) if len(auth) == 1: auth.append('') # extract host and port ssl = scheme == 'https' if ':' in netloc: netloc, port_s = netloc.split(':', 1) port = int(port_s) else: if ssl: port = http.client.HTTPS_PORT else: port = http.client.HTTP_PORT self.host = netloc self.port = port self.ssl = ssl # build url query if isinstance(params, dict): params = list(params.items()) if data and self.method in self.GET_METHODS: # include data to query if isinstance(data, dict): data = data.items() params = list(itertools.chain(params or (), data)) data = None if params: params = urllib.parse.urlencode(params) if query: query = '%s&%s' % (query, params) else: query = params # build path path = urllib.parse.quote(path) self.path = urllib.parse.urlunsplit(('', '', path, query, fragment)) # headers self.headers = email.message.Message() if headers: if isinstance(headers, dict): headers = list(headers.items()) for key, value in headers: self.headers[key] = value for hdr, val in self.DEFAULT_HEADERS.items(): if hdr not in self.headers: self.headers[hdr] = val # host if 'host' not in self.headers: self.headers['Host'] = self.host # cookies if cookies: c = http.cookies.SimpleCookie() if 'cookie' in self.headers: c.load(self.headers.get('cookie', '')) del self.headers['cookie'] for name, value in cookies.items(): if isinstance(value, http.cookies.Morsel): dict.__setitem__(c, name, value) else: c[name] = value self.headers['cookie'] = c.output(header='', sep=';').strip() # auth if auth: if isinstance(auth, (tuple, list)) and len(auth) == 2: # basic auth self.headers['Authorization'] = 'Basic %s' % ( base64.b64encode( ('%s:%s' % (auth[0], auth[1])).encode('latin1')) .strip().decode('latin1')) else: raise ValueError("Only basic auth is supported") self._params = (chunked, compress, files, data, encoding) def start(self, transport): chunked, compress, files, data, encoding = self._params request = tulip.http.Request( transport, self.method, self.path, self.version) # Content-encoding enc = self.headers.get('Content-Encoding', '').lower() if enc: if not chunked: # enable chunked, no need to deal with length chunked = True request.add_compression_filter(enc) elif compress: if not chunked: # enable chunked, no need to deal with length chunked = True compress = compress if isinstance(compress, str) else 'deflate' self.headers['Content-Encoding'] = compress request.add_compression_filter(compress) # form data (x-www-form-urlencoded) if isinstance(data, dict): data = list(data.items()) if data and not files: if not isinstance(data, str): data = urllib.parse.urlencode(data, doseq=True) self.body = data.encode(encoding) if 'content-type' not in self.headers: self.headers['content-type'] = ( 'application/x-www-form-urlencoded') if 'content-length' not in self.headers: self.headers['content-length'] = len(self.body) # files (multipart/form-data) elif files: fields = [] if data: for field, val in data: fields.append((field, str_to_bytes(val))) if isinstance(files, dict): files = list(files.items()) for rec in files: if not isinstance(rec, (tuple, list)): rec = (rec,) ft = None if len(rec) == 1: k = guess_filename(rec[0], 'unknown') fields.append((k, k, rec[0])) elif len(rec) == 2: k, fp = rec fn = guess_filename(fp, k) fields.append((k, fn, fp)) else: k, fp, ft = rec fn = guess_filename(fp, k) fields.append((k, fn, fp, ft)) chunked = chunked or 8192 boundary = uuid.uuid4().hex self.body = encode_multipart_data( fields, bytes(boundary, 'latin1')) if 'content-type' not in self.headers: self.headers['content-type'] = ( 'multipart/form-data; boundary=%s' % boundary) # chunked te = self.headers.get('transfer-encoding', '').lower() if chunked: self.chunked = True if 'content-length' in self.headers: del self.headers['content-length'] if 'chunked' not in te: self.headers['Transfer-encoding'] = 'chunked' chunk_size = chunked if type(chunked) is int else 8196 request.add_chunking_filter(chunk_size) else: if 'chunked' in te: self.chunked = True request.add_chunking_filter(8196) else: self.chunked = False self.headers['content-length'] = len(self.body) request.add_headers(*self.headers.items()) request.send_headers() if isinstance(self.body, (str, bytes)): self.body = (self.body,) for chunk in self.body: request.write(chunk) request.write_eof() return [] def str_to_bytes(s, encoding='utf-8'): if isinstance(s, str): return s.encode(encoding) return s def guess_filename(obj, default=None): name = getattr(obj, 'name', None) if name and name[0] != '<' and name[-1] != '>': return os.path.split(name)[-1] return default def encode_multipart_data(fields, boundary, encoding='utf-8', chunk_size=8196): """ Encode a list of fields using the multipart/form-data MIME format. fields: List of (name, value) or (name, filename, io) or (name, filename, io, MIME type) field tuples. """ for rec in fields: yield b'--' + boundary + b'\r\n' field, *rec = rec if len(rec) == 1: data = rec[0] yield (('Content-Disposition: form-data; name="%s"\r\n\r\n' % (field,)).encode(encoding)) yield data + b'\r\n' else: if len(rec) == 3: fn, fp, ct = rec else: fn, fp = rec ct = (mimetypes.guess_type(fn)[0] or 'application/octet-stream') yield ('Content-Disposition: form-data; name="%s"; ' 'filename="%s"\r\n' % (field, fn)).encode(encoding) yield ('Content-Type: %s\r\n\r\n' % (ct,)).encode(encoding) if isinstance(fp, str): fp = fp.encode(encoding) if isinstance(fp, bytes): fp = io.BytesIO(fp) while True: chunk = fp.read(chunk_size) if not chunk: break yield str_to_bytes(chunk) yield b'\r\n' yield b'--' + boundary + b'--\r\n'
UTF-8
Python
false
false
2,013
6,399,501,278,739
9d24ff120d47399082a0ffb99e1907ab8d537070
a66172351a91a1d29edd203a269f2a98bac6a363
/InfoCoin.py
6eea639d96945b003f834c9fc75708ba6016939f
[]
no_license
lucasbfernandes/coderun
https://github.com/lucasbfernandes/coderun
c1ff2dbc0db34194d33506b2ee9a1072e2d283bd
44a7a66b45b62c0b1eac4b4ad08bb76a390b8709
refs/heads/master
2016-07-26T15:59:35.639058
2014-07-17T03:32:23
2014-07-17T03:32:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import pygame import time import Sprite_image from time import clock from pygame import * class InfoCoin(pygame.sprite.Sprite): indexArray = [(998,327),(2808,316),(4230,320),(5411,320),(7735,320)] def __init__(self, index): pygame.sprite.Sprite.__init__(self) self.coinSprite = Sprite_image.Sprite_image("images/InfoCoin - GameUFU.png",1,(102,102)) self.rect = pygame.Rect(self.coinSprite.images[0].get_rect()) self.image = self.coinSprite.images[0] self.rect.topleft = self.indexArray[index] self.collideRect = pygame.Rect((self.rect.left + 22, self.rect.top + 18), (59,61)) def update(self, personagem, coinStatus): if personagem.collideBody.colliderect(self.rect) or personagem.collideBody.colliderect(self.rect) and coinStatus.statusSprite.frame < 4: coinStatus.statusSprite.frame += 1 self.kill()
UTF-8
Python
false
false
2,014
884,763,294,882
f642fa02100c9f84619a64987cf7160b51b50cd0
ea054ec4fddbfeda2323f15667aa6a10c212c515
/practice_1/simeon.py
aa850e6957452a589b06193326374c61cd095f70
[]
no_license
yakovkoshkin/python-basics
https://github.com/yakovkoshkin/python-basics
7a19b8a4923bdc0f31b7d9339de2d2cc70b34965
af501496b38277ccc2e0617487cb407d75cb8225
refs/heads/master
2020-12-25T20:20:32.580679
2014-03-27T05:35:48
2014-03-27T05:35:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sha name = raw_input("What's your first name? > ") name = name.lower() file_name = '{}.txt'.format(name) with open(file_name, 'w') as f: name_hash = sha.new(name).hexdigest() f.write(name_hash) print('Hash saved to {}.'.format(file_name))
UTF-8
Python
false
false
2,014
18,657,337,954,008
3b56e0346368df5caeb1e7641dc2db605c6f3958
5eeeefea5c77584dcb2228e3964b7f662d359d63
/tests/test_LSH.py
c7e5783338cabc62989f5df2d402a582902fdde6
[]
no_license
escherba/lsh
https://github.com/escherba/lsh
209a2bebff0649a53123ce01ccea2f2d10b293f6
eec964de93cbcfba36d9fb4f7f2ffcbbb7f7e79c
refs/heads/master
2021-01-18T20:27:33.977297
2013-12-26T12:38:55
2013-12-26T12:38:55
15,404,669
1
0
null
true
2013-12-26T08:44:23
2013-12-23T21:08:44
2013-12-26T08:44:22
2013-12-26T08:44:22
116
0
0
0
Python
null
null
__author__ = 'escherba' import unittest from ann import L1HashFamily, L2HashFamily, CosineHashFamily class MyTestCase(unittest.TestCase): def test_L1HashFamily(self): hf_d = 5 hf_w = 100 hf = L1HashFamily(hf_d, hf_w) self.assertEqual(hf.d, hf_d) self.assertEqual(hf.w, hf_w) def test_L2HashFamily(self): hf_d = 5 hf_w = 100 hf = L2HashFamily(hf_d, hf_w) self.assertEqual(hf.d, hf_d) self.assertEqual(hf.w, hf_w) def test_CosineHashFamily(self): hf_d = 5 hf = CosineHashFamily(hf_d) self.assertEqual(hf.d, hf_d) if __name__ == '__main__': unittest.main()
UTF-8
Python
false
false
2,013
5,437,428,635,673
04b61ca55eba33d040cba0911aa3bb4427367d01
8cd474a11db2906530fbbdf69daec9b9f57c268a
/surfmanage/roster/views/__init__.py
8cf54138af4b16d47ff1c8029e1bc777f391c8bf
[ "BSD-3-Clause", "MIT" ]
permissive
team294/surfmanage
https://github.com/team294/surfmanage
26fce3dd390d20d9c80216b047b8f495a00c148c
df89f261fb731f752f6f5d0eb85925743e856642
refs/heads/master
2016-09-10T19:48:33.336275
2013-06-22T18:33:28
2013-06-22T18:33:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from flask import render_template, current_app, send_from_directory, abort from flask.ext.login import login_required, current_user import os from .blueprint import * from ..models import * @roster.route('/') @roster.permission_required('view-roster') @roster.menu('index', None) def index(): return render_template('roster/index.html') @roster.route('/people') @roster.permission_required('view-roster') @roster.menu('people', 'index', icon='icon-book') def people(): return render_template('roster/people.html') @roster.route('/badge/<int:id>.jpeg') @login_required def badge_photo(id): # Allow current user to see their own photo; otherwise need view-photo. if current_user.person_id == id: pass elif not current_user.has_permissions(set('view-photo')): abort(403) dir_path = current_app.config['BADGE_FOLDER'] fn = '%d.jpeg' % id return send_from_directory(dir_path, fn, as_attachment=False) from .contact import * from .info import * from .config import * from .signin import *
UTF-8
Python
false
false
2,013
9,758,165,720,672
0a11b2fb6fb683b26c61ef1e1d1d9bd6b6391fe9
395ab809345028f6ba63ad332339ec1118f521be
/mi/instrument/seabird/sbe37smb/ooicore/driver.py
cbc6cb9a62ad95c5ff5a222be9e45b0923933462
[]
no_license
cwingard/marine-integrations
https://github.com/cwingard/marine-integrations
f15ce07216432de3a5ac7f4d40bb914240779cd4
c93a9c138df4a3b779df4e6c6e9d42661f97cd5f
refs/heads/master
2017-05-02T17:13:11.257072
2013-12-17T20:27:00
2013-12-17T20:27:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python """ @package ion.services.mi.drivers.sbe37.sbe37.sbe37_driver @file ion/services/mi/drivers/sbe37/sbe37_driver.py @author Edward Hunter @brief Driver class for sbe37 CTD instrument. """ __author__ = 'Edward Hunter' __license__ = 'Apache 2.0' import base64 import logging import time import re import datetime from threading import Timer import string import ntplib import json from mi.core.common import BaseEnum from mi.core.instrument.instrument_protocol import InitializationType from mi.core.instrument.protocol_param_dict import ParameterDictType from mi.core.instrument.protocol_param_dict import ParameterDictVisibility from mi.core.instrument.instrument_protocol import CommandResponseInstrumentProtocol from mi.core.instrument.instrument_fsm import ThreadSafeFSM from mi.core.instrument.instrument_driver import SingleConnectionInstrumentDriver from mi.core.instrument.instrument_driver import DriverEvent from mi.core.instrument.instrument_driver import DriverAsyncEvent from mi.core.instrument.instrument_driver import DriverProtocolState from mi.core.instrument.instrument_driver import DriverParameter from mi.core.instrument.instrument_driver import ResourceAgentState from mi.core.instrument.instrument_driver import ResourceAgentEvent from mi.core.instrument.data_particle import DataParticle, DataParticleKey, CommonDataParticleType from mi.core.instrument.driver_dict import DriverDictKey from mi.core.instrument.chunker import StringChunker from mi.core.exceptions import InstrumentTimeoutException from mi.core.exceptions import InstrumentParameterException from mi.core.exceptions import SampleException from mi.core.exceptions import InstrumentStateException from mi.core.exceptions import InstrumentProtocolException from mi.core.log import get_logger log = get_logger() class DataParticleType(BaseEnum): RAW = CommonDataParticleType.RAW PARSED = 'parsed' DEVICE_CALIBRATION = 'device_calibration_parsed' # supported in preload even? DEVICE_STATUS = 'device_status_parsed' # supported in preload even? class InstrumentCmds(BaseEnum): """ Device specific commands Represents the commands the driver implements and the string that must be sent to the instrument to execute the command. """ DISPLAY_CALIBRATION = 'dc' DISPLAY_STATUS = 'ds' TAKE_SAMPLE = 'ts' START_LOGGING = 'startnow' STOP_LOGGING = 'stop' SET = 'set' #'tc' #'tt' #'tp' class SBE37ProtocolState(BaseEnum): """ Protocol states for SBE37. Cherry picked from DriverProtocolState enum. """ UNKNOWN = DriverProtocolState.UNKNOWN COMMAND = DriverProtocolState.COMMAND AUTOSAMPLE = DriverProtocolState.AUTOSAMPLE TEST = DriverProtocolState.TEST CALIBRATE = DriverProtocolState.CALIBRATE DIRECT_ACCESS = DriverProtocolState.DIRECT_ACCESS class SBE37ProtocolEvent(BaseEnum): """ Protocol events for SBE37. Cherry picked from DriverEvent enum. """ ENTER = DriverEvent.ENTER EXIT = DriverEvent.EXIT GET = DriverEvent.GET SET = DriverEvent.SET DISCOVER = DriverEvent.DISCOVER ACQUIRE_SAMPLE = DriverEvent.ACQUIRE_SAMPLE START_AUTOSAMPLE = DriverEvent.START_AUTOSAMPLE STOP_AUTOSAMPLE = DriverEvent.STOP_AUTOSAMPLE INIT_PARAMS = DriverEvent.INIT_PARAMS TEST = DriverEvent.TEST RUN_TEST = DriverEvent.RUN_TEST CALIBRATE = DriverEvent.CALIBRATE EXECUTE_DIRECT = DriverEvent.EXECUTE_DIRECT START_DIRECT = DriverEvent.START_DIRECT STOP_DIRECT = DriverEvent.STOP_DIRECT ACQUIRE_STATUS = DriverEvent.ACQUIRE_STATUS # DS ACQUIRE_CONFIGURATION = "PROTOCOL_EVENT_ACQUIRE_CONFIGURATION" # DC class SBE37Capability(BaseEnum): """ Protocol events that should be exposed to users (subset of above). """ ACQUIRE_SAMPLE = SBE37ProtocolEvent.ACQUIRE_SAMPLE START_AUTOSAMPLE = SBE37ProtocolEvent.START_AUTOSAMPLE STOP_AUTOSAMPLE = SBE37ProtocolEvent.STOP_AUTOSAMPLE TEST = SBE37ProtocolEvent.TEST ACQUIRE_STATUS = SBE37ProtocolEvent.ACQUIRE_STATUS ACQUIRE_CONFIGURATION = SBE37ProtocolEvent.ACQUIRE_CONFIGURATION # Device specific parameters. class SBE37Parameter(DriverParameter): """ Device parameters for SBE37. """ OUTPUTSAL = 'OUTPUTSAL' OUTPUTSV = 'OUTPUTSV' NAVG = 'NAVG' SAMPLENUM = 'SAMPLENUM' INTERVAL = 'INTERVAL' STORETIME = 'STORETIME' TXREALTIME = 'TXREALTIME' SYNCMODE = 'SYNCMODE' SYNCWAIT = 'SYNCWAIT' TCALDATE = 'TCALDATE' TA0 = 'TA0' TA1 = 'TA1' TA2 = 'TA2' TA3 = 'TA3' CCALDATE = 'CCALDATE' CG = 'CG' CH = 'CH' CI = 'CI' CJ = 'CJ' WBOTC = 'WBOTC' CTCOR = 'CTCOR' CPCOR = 'CPCOR' PCALDATE = 'PCALDATE' PA0 = 'PA0' PA1 = 'PA1' PA2 = 'PA2' PTCA0 = 'PTCA0' PTCA1 = 'PTCA1' PTCA2 = 'PTCA2' PTCB0 = 'PTCB0' PTCB1 = 'PTCB1' PTCB2 = 'PTCB2' POFFSET = 'POFFSET' RCALDATE = 'RCALDATE' RTCA0 = 'RTCA0' RTCA1 = 'RTCA1' RTCA2 = 'RTCA2' # Device prompts. class SBE37Prompt(BaseEnum): """ SBE37 io prompts. """ COMMAND = 'S>' BAD_COMMAND = '?cmd S>' AUTOSAMPLE = 'S>\r\n' START_NOW = 'start now' # SBE37 newline. NEWLINE = '\r\n' # SBE37 default timeout. SBE37_TIMEOUT = 60 # Sample looks something like: # '#87.9140,5.42747, 556.864, 37.1829, 1506.961, 02 Jan 2001, 15:34:51' # Where C, T, and D are first 3 number fields respectively # Breaks it down a bit SAMPLE_PATTERN = r'#? *(-?\d+\.\d+), *(-?\d+\.\d+), *(-?\d+\.\d+)' SAMPLE_PATTERN += r'(, *(-?\d+\.\d+))?(, *(-?\d+\.\d+))?' SAMPLE_PATTERN += r'(, *(\d+) +([a-zA-Z]+) +(\d+), *(\d+):(\d+):(\d+))?' SAMPLE_PATTERN += r'(, *(\d+)-(\d+)-(\d+), *(\d+):(\d+):(\d+))?' SAMPLE_PATTERN_MATCHER = re.compile(SAMPLE_PATTERN) #STATUS_DATA_REGEX = r"(SBE37-SMP V [\d\.]+ SERIAL NO.*? deg C)" STATUS_DATA_REGEX = r"(SBE37-SMP.*? deg C.*)" STATUS_DATA_REGEX_MATCHER = re.compile(STATUS_DATA_REGEX, re.DOTALL) #CALIBRATION_DATA_REGEX = r"(SBE37-SM V [\d\.]+.*?RTCA2 = -?[\d\.e\-\+]+)" CALIBRATION_DATA_REGEX = r"(SBE37-SM.*?RTCA2 = -?[\d\.e\-\+]+)" CALIBRATION_DATA_REGEX_MATCHER = re.compile(CALIBRATION_DATA_REGEX, re.DOTALL) ############################################################################### # Seabird Electronics 37-SMP MicroCAT Driver. ############################################################################### class SBE37Driver(SingleConnectionInstrumentDriver): """ InstrumentDriver subclass for SBE37 driver. Subclasses SingleConnectionInstrumentDriver with connection state machine. """ def __init__(self, evt_callback): """ InstrumentDriver constructor. @param evt_callback Driver process event callback. """ #Construct superclass. SingleConnectionInstrumentDriver.__init__(self, evt_callback) ######################################################################## # Superclass overrides for resource query. ######################################################################## ######################################################################## # Protocol builder. ######################################################################## def _build_protocol(self): """ Construct the driver protocol state machine. """ self._protocol = SBE37Protocol(SBE37Prompt, NEWLINE, self._driver_event) def apply_startup_params(self): """ Overload the default behavior which is to pass the buck to the protocol. Alternatively we could retrofit the protocol to better handle the apply startup params feature which would be preferred in production drivers. @raise InstrumentParameterException If the config cannot be applied """ config = self._protocol.get_startup_config() if not isinstance(config, dict): raise InstrumentParameterException("Incompatible initialization parameters") self.set_resource(config) class SBE37DataParticleKey(BaseEnum): TEMP = "temp" CONDUCTIVITY = "conductivity" DEPTH = "pressure" class SBE37DataParticle(DataParticle): """ Routines for parsing raw data into a data particle structure. Override the building of values, and the rest should come along for free. """ _data_particle_type = DataParticleType.PARSED def _build_parsed_values(self): """ Take something in the autosample/TS format and split it into C, T, and D values (with appropriate tags) @throws SampleException If there is a problem with sample creation """ match = SAMPLE_PATTERN_MATCHER.match(self.raw_data) if not match: raise SampleException("No regex match of parsed sample data: [%s]" % self.raw_data) try: temperature = float(match.group(1)) conductivity = float(match.group(2)) depth = float(match.group(3)) except ValueError: raise SampleException("ValueError while decoding floats in data: [%s]" % self.raw_data) #TODO: Get 'temp', 'cond', and 'depth' from a paramdict result = [{DataParticleKey.VALUE_ID: SBE37DataParticleKey.TEMP, DataParticleKey.VALUE: temperature}, {DataParticleKey.VALUE_ID: SBE37DataParticleKey.CONDUCTIVITY, DataParticleKey.VALUE: conductivity}, {DataParticleKey.VALUE_ID: SBE37DataParticleKey.DEPTH, DataParticleKey.VALUE: depth}] return result ## ## BEFORE ADDITION ## class SBE37DeviceCalibrationParticleKey(BaseEnum): TCALDATE = 'calibration_date_temperature' TA0 = 'sbe37_coeff_ta0' TA1 = 'sbe37_coeff_ta1' TA2 = 'sbe37_coeff_ta2' TA3 = 'sbe37_coeff_ta3' CCALDATE = 'calibration_date_conductivity' G = 'sbe37_coeff_g' H = 'sbe37_coeff_h' I = 'sbe37_coeff_i' J = 'sbe37_coeff_j' CPCOR = 'sbe37_coeff_cpcor' CTCOR = 'sbe37_coeff_ctcor' WBOTC = 'sbe37_coeff_wbotc' PCALDATE = 'calibration_date_pressure' PSN = 'sbe37_coeff_serial_number' PRANGE = 'sbe37_coeff_pressure_range' PA0 = 'sbe37_coeff_pa0' PA1 = 'sbe37_coeff_pa1' PA2 = 'sbe37_coeff_pa2' PTCA0 = 'sbe37_coeff_ptca0' PTCA1 = 'sbe37_coeff_ptca1' PTCA2 = 'sbe37_coeff_ptca2' PTCSB0 = 'sbe37_coeff_ptcsb0' PTCSB1 = 'sbe37_coeff_ptcsb1' PTCSB2 = 'sbe37_coeff_ptcsb2' POFFSET = 'sbe37_coeff_poffset' RTC = 'sbe37_coeff_rtc' RTCA0 = 'sbe37_coeff_rtca0' RTCA1 = 'sbe37_coeff_rtca1' RTCA2 = 'sbe37_coeff_rtca2' class SBE37DeviceCalibrationParticle(DataParticle): """ Routines for parsing raw data into a data particle structure. Override the building of values, and the rest should come along for free. """ _data_particle_type = DataParticleType.DEVICE_CALIBRATION @staticmethod def _string_to_date(datestr, fmt): """ Extract a date tuple from an sbe37 date string. @param str a string containing date information in sbe37 format. @retval a date tuple. @throws InstrumentParameterException if datestr cannot be formatted to a date. """ if not isinstance(datestr, str): raise InstrumentParameterException('Value %s is not a string.' % str(datestr)) try: date_time = time.strptime(datestr, fmt) date = (date_time[2],date_time[1],date_time[0]) except ValueError: raise InstrumentParameterException('Value %s could not be formatted to a date.' % str(datestr)) return date def _build_parsed_values(self): """ Take something in the dc format and split it into values with appropriate tags @throws SampleException If there is a problem with sample creation """ log.debug("in SBE37DeviceCalibrationParticle._build_parsed_values") single_var_matchers = { SBE37DeviceCalibrationParticleKey.TCALDATE: ( re.compile(r'temperature:\s+(\d+-[a-zA-Z]+-\d+)'), lambda match : self._string_to_date(match.group(1), '%d-%b-%y') ), SBE37DeviceCalibrationParticleKey.TA0: ( re.compile(r'\s+TA0 = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.TA1: ( re.compile(r'\s+TA1 = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.TA2: ( re.compile(r'\s+TA2 = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.TA3: ( re.compile(r'\s+TA3 = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.CCALDATE: ( re.compile(r'conductivity:\s+(\d+-[a-zA-Z]+-\d+)'), lambda match : self._string_to_date(match.group(1), '%d-%b-%y') ), SBE37DeviceCalibrationParticleKey.G: ( re.compile(r'\s+G = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.H: ( re.compile(r'\s+H = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.I: ( re.compile(r'\s+I = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.J: ( re.compile(r'\s+J = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.CPCOR: ( re.compile(r'\s+CPCOR = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.CTCOR: ( re.compile(r'\s+CTCOR = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.WBOTC: ( re.compile(r'\s+WBOTC = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.PCALDATE: ( re.compile(r'pressure S/N (\d+), range = ([\d\.]+) psia:\s+(\d+-[a-zA-Z]+-\d+)'), lambda match : self._string_to_date(match.group(3), '%d-%b-%y') ), SBE37DeviceCalibrationParticleKey.PRANGE: ( re.compile(r'pressure S/N (\d+), range = ([\d\.]+) psia:\s+(\d+-[a-zA-Z]+-\d+)'), lambda match : float(match.group(2)) ), SBE37DeviceCalibrationParticleKey.PSN: ( re.compile(r'pressure S/N (\d+), range = ([\d\.]+) psia:\s+(\d+-[a-zA-Z]+-\d+)'), lambda match : int(match.group(1)) ), SBE37DeviceCalibrationParticleKey.PA0: ( re.compile(r'\s+PA0 = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.PA1: ( re.compile(r'\s+PA1 = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.PA2: ( re.compile(r'\s+PA2 = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.PTCA0: ( re.compile(r'\s+PTCA0 = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.PTCA1: ( re.compile(r'\s+PTCA1 = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.PTCA2: ( re.compile(r'\s+PTCA2 = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.PTCSB0: ( re.compile(r'\s+PTCSB0 = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.PTCSB1: ( re.compile(r'\s+PTCSB1 = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.PTCSB2: ( re.compile(r'\s+PTCSB2 = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.POFFSET: ( re.compile(r'\s+POFFSET = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.RTC: ( re.compile(r'rtc:\s+(\d+-[a-zA-Z]+-\d+)'), lambda match : self._string_to_date(match.group(1), '%d-%b-%y') ), SBE37DeviceCalibrationParticleKey.RTCA0: ( re.compile(r'\s+RTCA0 = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.RTCA1: ( re.compile(r'\s+RTCA1 = (-?[\d\.e\-\+]+)'), lambda match : float(match.group(1)) ), SBE37DeviceCalibrationParticleKey.RTCA2: ( re.compile(r'\s+RTCA2 = (-?[\d\.e\-\+]+)' ), lambda match : float(match.group(1)) ) } result = [] # Final storage for particle vals = {} # intermediate storage for particle values so they can be set to null first. for (key, (matcher, l_func)) in single_var_matchers.iteritems(): vals[key] = None for line in self.raw_data.split(NEWLINE): for (key, (matcher, l_func)) in single_var_matchers.iteritems(): match = matcher.match(line) if match: vals[key] = l_func(match) for (key, val) in vals.iteritems(): result.append({DataParticleKey.VALUE_ID: key, DataParticleKey.VALUE: val}) return result class SBE37DeviceStatusParticleKey(BaseEnum): # DS SERIAL_NUMBER = "sbe37_serial_number" DATE_TIME = "sbe37_date_time" LOGGING = "sbe37_logging" SAMPLE_INTERVAL = "sbe37_sample_interval" SAMPLE_NUMBER = "sbe37_sample_number" MEMORY_FREE = "sbe37_memory_free" TX_REALTIME = "sbe37_tx_realtime" OUTPUT_SALINITY = "sbe37_output_salinity" OUTPUT_SOUND_VELOCITY = "sbe37_output_sound_velocity" STORE_TIME = "sbe37_store_time" NUMBER_OF_SAMPLES_TO_AVERAGE = "sbe37_number_of_samples_to_average" REFERENCE_PRESSURE = "sbe37_reference_pressure" SERIAL_SYNC_MODE = "sbe37_serial_sync_mode" SERIAL_SYNC_WAIT = "sbe37_serial_sync_wait" INTERNAL_PUMP = "sbe37_internal_pump_installed" TEMPERATURE = "sbe37_temperature" # LOW_BATTERY_WARNING = "sbe37_low_battery_warning" class SBE37DeviceStatusParticle(DataParticle): """ Routines for parsing raw data into a data particle structure. Override the building of values, and the rest should come along for free. """ _data_particle_type = DataParticleType.DEVICE_STATUS @staticmethod def _string_to_ntp_date_time(datestr, fmt): """ Extract a date tuple from an sbe37 date string. @param str a string containing date information in sbe37 format. @retval a date tuple. @throws InstrumentParameterException if datestr cannot be formatted to a date. """ if not isinstance(datestr, str): raise InstrumentParameterException('Value %s is not a string.' % str(datestr)) try: date_time = time.strptime(datestr, fmt) timestamp = ntplib.system_to_ntp_time(time.mktime(date_time)) except ValueError: raise InstrumentParameterException('Value %s could not be formatted to a date.' % str(datestr)) return timestamp def _build_parsed_values(self): """ Take something in the dc format and split it into values with appropriate tags @throws SampleException If there is a problem with sample creation """ log.debug("in SBE37DeviceStatusParticle._build_parsed_values") single_var_matchers = { SBE37DeviceStatusParticleKey.SERIAL_NUMBER: ( re.compile(r'SBE37-SMP V 2.6 SERIAL NO. (\d+) (\d\d [a-zA-Z]+ \d\d\d\d\s+[ \d]+:\d\d:\d\d)'), lambda match : int(match.group(1)) ), SBE37DeviceStatusParticleKey.DATE_TIME: ( re.compile(r'SBE37-SMP V 2.6 SERIAL NO. (\d+) (\d\d [a-zA-Z]+ \d\d\d\d\s+[ \d]+:\d\d:\d\d)'), lambda match : float(self._string_to_ntp_date_time(match.group(2), "%d %b %Y %H:%M:%S")) ), SBE37DeviceStatusParticleKey.LOGGING: ( re.compile(r'(logging data)'), lambda match : True if (match) else False, ), SBE37DeviceStatusParticleKey.SAMPLE_INTERVAL: ( re.compile(r'sample interval = (\d+) seconds'), lambda match : int(match.group(1)) ), SBE37DeviceStatusParticleKey.SAMPLE_NUMBER: ( re.compile(r'samplenumber = (\d+), free = (\d+)'), lambda match : int(match.group(1)) ), SBE37DeviceStatusParticleKey.MEMORY_FREE: ( re.compile(r'samplenumber = (\d+), free = (\d+)'), lambda match : int(match.group(2)) ), SBE37DeviceStatusParticleKey.TX_REALTIME: ( re.compile(r'do not transmit real-time data'), lambda match : False if (match) else True, ), SBE37DeviceStatusParticleKey.OUTPUT_SALINITY: ( re.compile(r'do not output salinity with each sample'), lambda match : False if (match) else True, ), SBE37DeviceStatusParticleKey.OUTPUT_SOUND_VELOCITY: ( re.compile(r'do not output sound velocity with each sample'), lambda match : False if (match) else True, ), SBE37DeviceStatusParticleKey.STORE_TIME: ( re.compile(r'do not store time with each sample'), lambda match : False if (match) else True, ), SBE37DeviceStatusParticleKey.NUMBER_OF_SAMPLES_TO_AVERAGE: ( re.compile(r'number of samples to average = (\d+)'), lambda match : int(match.group(1)) ), SBE37DeviceStatusParticleKey.REFERENCE_PRESSURE: ( re.compile(r'reference pressure = ([\d\.]+) db'), lambda match : float(match.group(1)) ), SBE37DeviceStatusParticleKey.SERIAL_SYNC_MODE: ( re.compile(r'serial sync mode disabled'), lambda match : False if (match) else True, ), SBE37DeviceStatusParticleKey.SERIAL_SYNC_WAIT: ( re.compile(r'wait time after serial sync sampling = (\d+) seconds'), lambda match : int(match.group(1)) ), SBE37DeviceStatusParticleKey.INTERNAL_PUMP: ( re.compile(r'internal pump is installed'), lambda match : True if (match) else False, ), SBE37DeviceStatusParticleKey.TEMPERATURE: ( re.compile(r'temperature = ([\d\.\-]+) deg C'), lambda match : float(match.group(1)) ), # Move to engineering? # SBE37DeviceStatusParticleKey.LOW_BATTERY_WARNING: ( # re.compile(r'WARNING: LOW BATTERY VOLTAGE!!'), # lambda match : True if (match.group(1)=='WARNING: LOW BATTERY VOLTAGE!!') else False, # ) } result = [] # Final storage for particle vals = {} # intermediate storage for particle values so they can be set to null first. for (key, (matcher, l_func)) in single_var_matchers.iteritems(): vals[key] = None for line in self.raw_data.split(NEWLINE): for (key, (matcher, l_func)) in single_var_matchers.iteritems(): match = matcher.match(line) if match: vals[key] = l_func(match) for (key, val) in vals.iteritems(): result.append({DataParticleKey.VALUE_ID: key, DataParticleKey.VALUE: val}) return result ## ## AFTER ADDITION ## ############################################################################### # Seabird Electronics 37-SMP MicroCAT protocol. ############################################################################### class SBE37Protocol(CommandResponseInstrumentProtocol): """ Instrument protocol class for SBE37 driver. Subclasses CommandResponseInstrumentProtocol """ def __init__(self, prompts, newline, driver_event): """ SBE37Protocol constructor. @param prompts A BaseEnum class containing instrument prompts. @param newline The SBE37 newline. @param driver_event Driver process event callback. """ # Construct protocol superclass. CommandResponseInstrumentProtocol.__init__(self, prompts, newline, driver_event) # Build SBE37 protocol state machine. self._protocol_fsm = ThreadSafeFSM(SBE37ProtocolState, SBE37ProtocolEvent, SBE37ProtocolEvent.ENTER, SBE37ProtocolEvent.EXIT) # Add event handlers for protocol state machine. self._protocol_fsm.add_handler(SBE37ProtocolState.UNKNOWN, SBE37ProtocolEvent.ENTER, self._handler_unknown_enter) self._protocol_fsm.add_handler(SBE37ProtocolState.UNKNOWN, SBE37ProtocolEvent.EXIT, self._handler_unknown_exit) self._protocol_fsm.add_handler(SBE37ProtocolState.UNKNOWN, SBE37ProtocolEvent.DISCOVER, self._handler_unknown_discover) self._protocol_fsm.add_handler(SBE37ProtocolState.COMMAND, SBE37ProtocolEvent.ENTER, self._handler_command_enter) self._protocol_fsm.add_handler(SBE37ProtocolState.COMMAND, SBE37ProtocolEvent.EXIT, self._handler_command_exit) self._protocol_fsm.add_handler(SBE37ProtocolState.COMMAND, SBE37ProtocolEvent.ACQUIRE_SAMPLE, self._handler_command_acquire_sample) self._protocol_fsm.add_handler(SBE37ProtocolState.COMMAND, SBE37ProtocolEvent.START_AUTOSAMPLE, self._handler_command_start_autosample) self._protocol_fsm.add_handler(SBE37ProtocolState.COMMAND, SBE37ProtocolEvent.GET, self._handler_command_autosample_test_get) self._protocol_fsm.add_handler(SBE37ProtocolState.COMMAND, SBE37ProtocolEvent.SET, self._handler_command_set) self._protocol_fsm.add_handler(SBE37ProtocolState.COMMAND, SBE37ProtocolEvent.TEST, self._handler_command_test) self._protocol_fsm.add_handler(SBE37ProtocolState.COMMAND, SBE37ProtocolEvent.START_DIRECT, self._handler_command_start_direct) self._protocol_fsm.add_handler(SBE37ProtocolState.COMMAND, SBE37ProtocolEvent.ACQUIRE_STATUS, self._handler_command_acquire_status) self._protocol_fsm.add_handler(SBE37ProtocolState.COMMAND, SBE37ProtocolEvent.ACQUIRE_CONFIGURATION, self._handler_command_acquire_configuration) self._protocol_fsm.add_handler(SBE37ProtocolState.COMMAND, SBE37ProtocolEvent.INIT_PARAMS, self._handler_command_init_params) self._protocol_fsm.add_handler(SBE37ProtocolState.AUTOSAMPLE, SBE37ProtocolEvent.ENTER, self._handler_autosample_enter) self._protocol_fsm.add_handler(SBE37ProtocolState.AUTOSAMPLE, SBE37ProtocolEvent.EXIT, self._handler_autosample_exit) self._protocol_fsm.add_handler(SBE37ProtocolState.AUTOSAMPLE, SBE37ProtocolEvent.GET, self._handler_command_autosample_test_get) self._protocol_fsm.add_handler(SBE37ProtocolState.AUTOSAMPLE, SBE37ProtocolEvent.STOP_AUTOSAMPLE, self._handler_autosample_stop_autosample) self._protocol_fsm.add_handler(SBE37ProtocolState.AUTOSAMPLE, SBE37ProtocolEvent.INIT_PARAMS, self._handler_autosample_init_params) self._protocol_fsm.add_handler(SBE37ProtocolState.TEST, SBE37ProtocolEvent.ENTER, self._handler_test_enter) self._protocol_fsm.add_handler(SBE37ProtocolState.TEST, SBE37ProtocolEvent.EXIT, self._handler_test_exit) self._protocol_fsm.add_handler(SBE37ProtocolState.TEST, SBE37ProtocolEvent.RUN_TEST, self._handler_test_run_tests) self._protocol_fsm.add_handler(SBE37ProtocolState.TEST, SBE37ProtocolEvent.GET, self._handler_command_autosample_test_get) self._protocol_fsm.add_handler(SBE37ProtocolState.DIRECT_ACCESS, SBE37ProtocolEvent.ENTER, self._handler_direct_access_enter) self._protocol_fsm.add_handler(SBE37ProtocolState.DIRECT_ACCESS, SBE37ProtocolEvent.EXIT, self._handler_direct_access_exit) self._protocol_fsm.add_handler(SBE37ProtocolState.DIRECT_ACCESS, SBE37ProtocolEvent.EXECUTE_DIRECT, self._handler_direct_access_execute_direct) self._protocol_fsm.add_handler(SBE37ProtocolState.DIRECT_ACCESS, SBE37ProtocolEvent.STOP_DIRECT, self._handler_direct_access_stop_direct) # Construct the parameter dictionary containing device parameters, # current parameter values, and set formatting functions. self._build_param_dict() self._build_driver_dict() self._build_command_dict() # Add build handlers for device commands. self._add_build_handler(InstrumentCmds.DISPLAY_STATUS, self._build_simple_command) self._add_build_handler(InstrumentCmds.DISPLAY_CALIBRATION, self._build_simple_command) self._add_build_handler(InstrumentCmds.TAKE_SAMPLE, self._build_simple_command) self._add_build_handler(InstrumentCmds.START_LOGGING, self._build_simple_command) self._add_build_handler(InstrumentCmds.STOP_LOGGING, self._build_simple_command) self._add_build_handler('tc', self._build_simple_command) self._add_build_handler('tt', self._build_simple_command) self._add_build_handler('tp', self._build_simple_command) self._add_build_handler(InstrumentCmds.SET, self._build_set_command) # Add response handlers for device commands. self._add_response_handler(InstrumentCmds.DISPLAY_STATUS, self._parse_dsdc_response) self._add_response_handler(InstrumentCmds.DISPLAY_CALIBRATION, self._parse_dsdc_response) self._add_response_handler(InstrumentCmds.TAKE_SAMPLE, self._parse_ts_response) self._add_response_handler(InstrumentCmds.SET, self._parse_set_response) self._add_response_handler('tc', self._parse_test_response) self._add_response_handler('tt', self._parse_test_response) self._add_response_handler('tp', self._parse_test_response) # Add sample handlers. # State state machine in UNKNOWN state. self._protocol_fsm.start(SBE37ProtocolState.UNKNOWN) # commands sent sent to device to be filtered in responses for telnet DA self._sent_cmds = [] self._chunker = StringChunker(self.sieve_function) @staticmethod def sieve_function(raw_data): """ Chunker sieve method to help the chunker identify chunks. @returns a list of chunks identified, if any. The chunks are all the same type. """ sieve_matchers = [SAMPLE_PATTERN_MATCHER, STATUS_DATA_REGEX_MATCHER, CALIBRATION_DATA_REGEX_MATCHER] return_list = [] for matcher in sieve_matchers: for match in matcher.finditer(raw_data): return_list.append((match.start(), match.end())) return return_list def _filter_capabilities(self, events): """ """ events_out = [x for x in events if SBE37Capability.has(x)] return events_out ######################################################################## # Unknown handlers. ######################################################################## def _handler_unknown_enter(self, *args, **kwargs): """ Enter unknown state. """ # Tell driver superclass to send a state change event. # Superclass will query the state. self._driver_event(DriverAsyncEvent.STATE_CHANGE) def _handler_unknown_exit(self, *args, **kwargs): """ Exit unknown state. """ pass def _handler_unknown_discover(self, *args, **kwargs): """ Discover current state; can be COMMAND or AUTOSAMPLE. @retval (next_state, result), (SBE37ProtocolState.COMMAND or SBE37State.AUTOSAMPLE, None) if successful. @throws InstrumentTimeoutException if the device cannot be woken. @throws InstrumentStateException if the device response does not correspond to an expected state. """ (protocol_state, agent_state) = self._discover() if(protocol_state == SBE37ProtocolState.COMMAND): agent_state = ResourceAgentState.IDLE return (protocol_state, agent_state) def _discover(self): """ Discover current state; can be COMMAND or AUTOSAMPLE or UNKNOWN. @retval (next_protocol_state, next_agent_state) @throws InstrumentTimeoutException if the device cannot be woken. @throws InstrumentStateException if the device response does not correspond to an expected state. """ logging = self._is_logging() if(logging == True): return (SBE37ProtocolState.AUTOSAMPLE, ResourceAgentState.STREAMING) else: return (SBE37ProtocolState.COMMAND, ResourceAgentState.COMMAND) #elif(logging == False): # return (SBE37ProtocolState.COMMAND, ResourceAgentState.COMMAND) #else: # when will this ever be called? # return (SBE37ProtocolState.UNKNOWN, ResourceAgentState.ACTIVE_UNKNOWN) def _is_logging(self, ds_result=None): """ Wake up the instrument and inspect the prompt to determine if we are in streaming @param: ds_result, optional ds result used for testing @return: True - instrument logging, False - not logging, None - unknown logging state @raise: InstrumentProtocolException if we can't identify the prompt """ if(ds_result == None): log.debug("Running DS command") ds_result = self._do_cmd_resp(InstrumentCmds.DISPLAY_STATUS, response_regex=STATUS_DATA_REGEX_MATCHER) #ds_result = self._do_cmd_resp(InstrumentCmds.DISPLAY_STATUS, expected_prompt=SBE37Prompt.COMMAND) log.debug("DS command result: %s", ds_result) log.debug("_is_logging: DS result: %s", ds_result) match = STATUS_DATA_REGEX_MATCHER.search(ds_result) if(not match): log.debug("Failed to get status, trying again") ds_result = self._do_cmd_resp(InstrumentCmds.DISPLAY_STATUS, response_regex=STATUS_DATA_REGEX_MATCHER) #ds_result = self._do_cmd_resp(InstrumentCmds.DISPLAY_STATUS, expected_prompt=SBE37Prompt.COMMAND) log.debug("DS command result: %s", ds_result) autosample_re = re.compile(r'.*logging data', re.DOTALL) command_re = re.compile(r'.*not logging', re.DOTALL) # DS returns "no logging: received stop command" when in command if(command_re.match(ds_result)): return False # DS returns "logging data" when streaming elif(autosample_re.match(ds_result)): return True else: log.error("_is_logging, no match: %s", ds_result) return None ######################################################################## # Command handlers. ######################################################################## def _handler_command_enter(self, *args, **kwargs): """ Enter command state. @throws InstrumentTimeoutException if the device cannot be woken. @throws InstrumentProtocolException if the update commands and not recognized. """ # Command device to initialize parameters and send a config change event. self._protocol_fsm.on_event(SBE37ProtocolEvent.INIT_PARAMS) # Tell driver superclass to send a state change event. # Superclass will query the state. self._driver_event(DriverAsyncEvent.STATE_CHANGE) def _handler_command_init_params(self, *args, **kwargs): """ initialize parameters """ next_state = None result = None self._init_params() return (next_state, result) def _handler_command_exit(self, *args, **kwargs): """ Exit command state. """ pass def _handler_command_set(self, *args, **kwargs): """ Perform a set command. @param args[0] parameter : value dict. @retval (next_state, result) tuple, (None, None). @throws InstrumentParameterException if missing set parameters, if set parameters not ALL and not a dict, or if paramter can't be properly formatted. @throws InstrumentTimeoutException if device cannot be woken for set command. @throws InstrumentProtocolException if set command could not be built or misunderstood. """ next_state = None result = None # Retrieve required parameter. # Raise if no parameter provided, or not a dict. try: params = args[0] except IndexError: raise InstrumentParameterException('Set command requires a parameter dict.') if not isinstance(params, dict): raise InstrumentParameterException('Set parameters not a dict.') # For each key, val in the dict, issue set command to device. # Raise if the command not understood. else: for (key, val) in params.iteritems(): result = self._do_cmd_resp(InstrumentCmds.SET, key, val, **kwargs) self._update_params() return (next_state, result) def _handler_command_acquire_sample(self, *args, **kwargs): """ Acquire sample from SBE37. @retval (next_state, result) tuple, (None, sample dict). @throws InstrumentTimeoutException if device cannot be woken for command. @throws InstrumentProtocolException if command could not be built or misunderstood. @throws SampleException if a sample could not be extracted from result. """ next_state = None next_agent_state = None result = None result = self._do_cmd_resp(InstrumentCmds.TAKE_SAMPLE, *args, **kwargs) return (next_state, (next_agent_state, result)) def _handler_command_start_autosample(self, *args, **kwargs): """ Switch into autosample mode. @retval (next_state, result) tuple, (SBE37ProtocolState.AUTOSAMPLE, None) if successful. @throws InstrumentTimeoutException if device cannot be woken for command. @throws InstrumentProtocolException if command could not be built or misunderstood. """ next_state = None next_agent_state = None result = None # Assure the device is transmitting. if not self._param_dict.get(SBE37Parameter.TXREALTIME): self._do_cmd_resp(InstrumentCmds.SET, SBE37Parameter.TXREALTIME, True, **kwargs) # Issue start command and switch to autosample if successful. self._do_cmd_no_resp(InstrumentCmds.START_LOGGING, *args, **kwargs) if self._is_logging(): log.debug("SBE confirmed in logging mode!") next_state = SBE37ProtocolState.AUTOSAMPLE next_agent_state = ResourceAgentState.STREAMING else: log.debug("Trying again to send %s command", InstrumentCmds.START_LOGGING) self._do_cmd_no_resp(InstrumentCmds.START_LOGGING, *args, **kwargs) if self._is_logging(): log.debug("SBE confirmed in logging mode!") next_state = SBE37ProtocolState.AUTOSAMPLE next_agent_state = ResourceAgentState.STREAMING return (next_state, (next_agent_state, result)) def _handler_command_test(self, *args, **kwargs): """ Switch to test state to perform instrument tests. @retval (next_state, result) tuple, (SBE37ProtocolState.TEST, None). """ next_state = None result = None next_state = SBE37ProtocolState.TEST next_agent_state = ResourceAgentState.TEST return (next_state, (next_agent_state, result)) def _handler_command_start_direct(self): """ """ next_state = None result = None next_state = SBE37ProtocolState.DIRECT_ACCESS next_agent_state = ResourceAgentState.DIRECT_ACCESS return (next_state, (next_agent_state, result)) ######################################################################## # Autosample handlers. ######################################################################## def _handler_autosample_enter(self, *args, **kwargs): """ Enter autosample state. """ self._protocol_fsm.on_event(SBE37ProtocolEvent.INIT_PARAMS) # Tell driver superclass to send a state change event. # Superclass will query the state. self._driver_event(DriverAsyncEvent.STATE_CHANGE) def _handler_autosample_exit(self, *args, **kwargs): """ Exit autosample state. """ pass def _handler_autosample_init_params(self, *args, **kwargs): """ initialize parameters. For this instrument we need to put the instrument into command mode, apply the changes then put it back. """ next_state = None result = None error = None try: self._do_cmd_resp(InstrumentCmds.STOP_LOGGING, expected_prompt=SBE37Prompt.COMMAND) self._init_params() # Catch all error so we can put ourself back into # streaming. Then rethrow the error except Exception as e: error = e finally: # Switch back to streaming logging = self._is_logging() if(logging == False): log.debug("sbe start logging again") self._do_cmd_no_resp(InstrumentCmds.START_LOGGING) if(logging == None): log.debug("could not determine logging state") self._async_agent_state_change(ResourceAgentState.ACTIVE_UNKNOWN) next_state = DriverProtocolState.UNKNOWN if(error): log.error("Error in apply_startup_params: %s", error) raise error return (next_state, result) def _handler_autosample_stop_autosample(self, *args, **kwargs): """ Stop autosample and switch back to command mode. @retval (next_state, result) tuple, (SBE37ProtocolState.COMMAND, None) if successful. @throws InstrumentTimeoutException if device cannot be woken for command. @throws InstrumentProtocolException if command misunderstood or incorrect prompt received. """ next_state = None result = None # Wake up the device, continuing until autosample prompt seen. timeout = kwargs.get('timeout', SBE37_TIMEOUT) tries = kwargs.get('tries',5) notries = 0 try: self._wakeup_until(timeout, SBE37Prompt.AUTOSAMPLE) except InstrumentTimeoutException: notries = notries + 1 if notries >=tries: raise # Issue the stop command. self._do_cmd_resp(InstrumentCmds.STOP_LOGGING, *args, **kwargs) # Prompt device until command prompt is seen. self._wakeup_until(timeout, SBE37Prompt.COMMAND) next_state = SBE37ProtocolState.COMMAND next_agent_state = ResourceAgentState.COMMAND return (next_state, (next_agent_state, result)) ######################################################################## # Common handlers. ######################################################################## def _handler_command_autosample_test_get(self, *args, **kwargs): """ Get device parameters from the parameter dict. @param args[0] list of parameters to retrieve, or DriverParameter.ALL. @throws InstrumentParameterException if missing or invalid parameter. """ return self._handler_get(*args, **kwargs) ######################################################################## # Test handlers. ######################################################################## def _handler_test_enter(self, *args, **kwargs): """ Enter test state. Setup the secondary call to run the tests. """ # Tell driver superclass to send a state change event. # Superclass will query the state. self._driver_event(DriverAsyncEvent.STATE_CHANGE) # Forward the test event again to run the test handler and # switch back to command mode afterward. Timer(1, lambda: self._protocol_fsm.on_event(SBE37ProtocolEvent.RUN_TEST)).start() def _handler_test_exit(self, *args, **kwargs): """ Exit test state. """ pass def _handler_test_run_tests(self, *args, **kwargs): """ Run test routines and validate results. @throws InstrumentTimeoutException if device cannot be woken for command. @throws InstrumentProtocolException if command misunderstood or incorrect prompt received. """ next_state = None result = None tc_pass = False tt_pass = False tp_pass = False tc_result = None tt_result = None tp_result = None test_result = {} try: tc_pass, tc_result = self._do_cmd_resp('tc', timeout=200) tt_pass, tt_result = self._do_cmd_resp('tt', timeout=200) tp_pass, tp_result = self._do_cmd_resp('tp', timeout=200) except Exception as e: test_result['exception'] = e test_result['message'] = 'Error running instrument tests.' finally: test_result['cond_test'] = 'Passed' if tc_pass else 'Failed' test_result['cond_data'] = tc_result test_result['temp_test'] = 'Passed' if tt_pass else 'Failed' test_result['temp_data'] = tt_result test_result['pres_test'] = 'Passed' if tp_pass else 'Failed' test_result['pres_data'] = tp_result test_result['success'] = 'Passed' if (tc_pass and tt_pass and tp_pass) else 'Failed' test_result['desc'] = 'SBE37 self-test result' test_result['cmd'] = DriverEvent.TEST self._driver_event(DriverAsyncEvent.RESULT, test_result) self._driver_event(DriverAsyncEvent.AGENT_EVENT, ResourceAgentEvent.DONE) #TODO send event to switch agent state. next_state = SBE37ProtocolState.COMMAND return (next_state, result) ######################################################################## # Direct access handlers. ######################################################################## def _handler_direct_access_enter(self, *args, **kwargs): """ Enter direct access state. """ # Tell driver superclass to send a state change event. # Superclass will query the state. self._driver_event(DriverAsyncEvent.STATE_CHANGE) self._sent_cmds = [] def _handler_direct_access_exit(self, *args, **kwargs): """ Exit direct access state. """ pass def _handler_direct_access_execute_direct(self, data): """ """ next_state = None result = None next_agent_state = None self._do_cmd_direct(data) # add sent command to list for 'echo' filtering in callback self._sent_cmds.append(data) return (next_state, (next_agent_state, result)) def _handler_direct_access_stop_direct(self): """ @throw InstrumentProtocolException on invalid command """ next_state = None result = None log.debug("_handler_direct_access_stop_direct: starting discover") (next_state, next_agent_state) = self._discover() log.debug("_handler_direct_access_stop_direct: next_state: %s, next agent state: %s", next_state, next_agent_state) return (next_state, (next_agent_state, result)) def _handler_command_acquire_status(self, *args, **kwargs): """ @param args: @param kwargs: @return: """ next_state = None next_agent_state = None kwargs['timeout'] = 30 result = self._do_cmd_resp(InstrumentCmds.DISPLAY_STATUS, *args, **kwargs) return (next_state, (next_agent_state, result)) def _handler_command_acquire_configuration(self, *args, **kwargs): """ @param args: @param kwargs: @return: """ next_state = None next_agent_state = None kwargs['timeout'] = 30 result = self._do_cmd_resp(InstrumentCmds.DISPLAY_CALIBRATION, *args, **kwargs) return (next_state, (next_agent_state, result)) ######################################################################## # Private helpers. ######################################################################## def _send_wakeup(self): """ Send a newline to attempt to wake the SBE37 device. """ self._connection.send(NEWLINE) def _set_params(self, *args, **kwargs): """ Issue commands to the instrument to set various parameters """ startup = False try: params = args[0] except IndexError: raise InstrumentParameterException('Set command requires a parameter dict.') try: startup = args[1] except IndexError: pass self._verify_not_readonly(*args, **kwargs) for (key, val) in params.iteritems(): log.debug("KEY = " + str(key) + " VALUE = " + str(val)) result = self._do_cmd_resp(InstrumentCmds.SET, key, val, **kwargs) self._update_params() def _update_params(self, *args, **kwargs): """ Update the parameter dictionary. Wake the device then issue display status and display calibration commands. The parameter dict will match line output and udpate itself. @throws InstrumentTimeoutException if device cannot be timely woken. @throws InstrumentProtocolException if ds/dc misunderstood. """ # Get old param dict config. old_config = self._param_dict.get_config() # Issue display commands and parse results. timeout = kwargs.get('timeout', SBE37_TIMEOUT) self._do_cmd_resp(InstrumentCmds.DISPLAY_STATUS,timeout=timeout) self._do_cmd_resp(InstrumentCmds.DISPLAY_CALIBRATION,timeout=timeout) # Get new param dict config. If it differs from the old config, # tell driver superclass to publish a config change event. new_config = self._param_dict.get_config() if new_config != old_config: self._driver_event(DriverAsyncEvent.CONFIG_CHANGE) def _build_simple_command(self, cmd): """ Build handler for basic SBE37 commands. @param cmd the simple sbe37 command to format. @retval The command to be sent to the device. """ return cmd+NEWLINE def _build_set_command(self, cmd, param, val): """ Build handler for set commands. param=val followed by newline. String val constructed by param dict formatting function. @param param the parameter key to set. @param val the parameter value to set. @ retval The set command to be sent to the device. @throws InstrumentProtocolException if the parameter is not valid or if the formatting function could not accept the value passed. """ try: str_val = self._param_dict.format(param, val) set_cmd = '%s=%s' % (param, str_val) set_cmd = set_cmd + NEWLINE except KeyError: raise InstrumentParameterException('Unknown driver parameter %s' % param) return set_cmd def _parse_set_response(self, response, prompt): """ Parse handler for set command. @param response command response string. @param prompt prompt following command response. @throws InstrumentProtocolException if set command misunderstood. """ if prompt.strip() != SBE37Prompt.COMMAND: raise InstrumentProtocolException('Set command not recognized: %s' % response) def _parse_dsdc_response(self, response, prompt): """ Parse handler for dsdc commands. @param response command response string. @param prompt prompt following command response. @throws InstrumentProtocolException if dsdc command misunderstood. """ log.debug("DS Response: %s, prompt: %s", response, prompt) if (prompt.strip() != SBE37Prompt.COMMAND) and (prompt.strip() != ""): raise InstrumentProtocolException('dsdc command not recognized: %s.' % response) for line in response.split(NEWLINE): self._param_dict.update(line) return response def _parse_ts_response(self, response, prompt): """ Response handler for ts command. @param response command response string. @param prompt prompt following command response. @retval sample dictionary containig c, t, d values. @throws InstrumentProtocolException if ts command misunderstood. @throws InstrumentSampleException if response did not contain a sample """ if prompt.strip() != SBE37Prompt.COMMAND: raise InstrumentProtocolException('ts command not recognized: %s', response) # don't know why we are returning a particle here #sample = None #for line in response.split(NEWLINE): # sample = self._extract_sample(SBE37DataParticle, SAMPLE_PATTERN_MATCHER, line, None, False) # if sample: # break # #if not sample: # raise SampleException('Response did not contain sample: %s' % repr(response)) # # return sample return response def _parse_test_response(self, response, prompt): """ Do minimal checking of test outputs. @param response command response string. @param promnpt prompt following command response. @retval tuple of pass/fail boolean followed by response """ success = False lines = response.split() if len(lines)>2: data = lines[1:-1] bad_count = 0 for item in data: try: float(item) except ValueError: bad_count += 1 if bad_count == 0: success = True return (success, response) def _got_chunk(self, chunk, timestamp): """ The base class got_data has gotten a chunk from the chunker. Pass it to extract_sample with the appropriate particle objects and REGEXes. """ # need to verify it works correctly. #if self.get_current_state() == SBE37ProtocolState.AUTOSAMPLE: # self._extract_sample(SBE37DataParticle, SAMPLE_PATTERN_MATCHER, chunk) result = self._extract_sample(SBE37DataParticle, SAMPLE_PATTERN_MATCHER, chunk, timestamp) result = self._extract_sample(SBE37DeviceStatusParticle, STATUS_DATA_REGEX_MATCHER, chunk, timestamp) result = self._extract_sample(SBE37DeviceCalibrationParticle, CALIBRATION_DATA_REGEX_MATCHER, chunk, timestamp) def _build_driver_dict(self): """ Populate the driver dictionary with options """ self._driver_dict.add(DriverDictKey.VENDOR_SW_COMPATIBLE, True) def _build_command_dict(self): """ Populate the command dictionary with command. """ self._cmd_dict.add(SBE37Capability.ACQUIRE_STATUS, display_name="acquire status") self._cmd_dict.add(SBE37Capability.TEST, display_name="test instrument") self._cmd_dict.add(SBE37Capability.START_AUTOSAMPLE, display_name="start autosample") self._cmd_dict.add(SBE37Capability.STOP_AUTOSAMPLE, display_name="stop autosample") self._cmd_dict.add(SBE37Capability.ACQUIRE_CONFIGURATION, display_name="get configuration data") self._cmd_dict.add(SBE37Capability.ACQUIRE_SAMPLE, display_name="acquire sample") def _build_param_dict(self): """ Populate the parameter dictionary with SBE37 parameters. For each parameter key, add match stirng, match lambda function, and value formatting function for set commands. """ # Add parameter handlers to parameter dict. self._param_dict.add(SBE37Parameter.OUTPUTSAL, r'(do not )?output salinity with each sample', lambda match : False if match.group(1) else True, self._true_false_to_string, type=ParameterDictType.BOOL) self._param_dict.add(SBE37Parameter.OUTPUTSV, r'(do not )?output sound velocity with each sample', lambda match : False if match.group(1) else True, self._true_false_to_string, type=ParameterDictType.BOOL) self._param_dict.add(SBE37Parameter.NAVG, r'number of samples to average = (\d+)', lambda match : int(match.group(1)), self._int_to_string, direct_access=True, type=ParameterDictType.INT) self._param_dict.add(SBE37Parameter.SAMPLENUM, r'samplenumber = (\d+), free = \d+', lambda match : int(match.group(1)), self._int_to_string, type=ParameterDictType.INT) self._param_dict.add(SBE37Parameter.INTERVAL, r'sample interval = (\d+) seconds', lambda match : int(match.group(1)), self._int_to_string, default_value=1, startup_param=True, direct_access = True, type=ParameterDictType.INT) self._param_dict.add(SBE37Parameter.STORETIME, r'(do not )?store time with each sample', lambda match : False if match.group(1) else True, self._true_false_to_string, type=ParameterDictType.BOOL) self._param_dict.add(SBE37Parameter.TXREALTIME, r'(do not )?transmit real-time data', lambda match : False if match.group(1) else True, self._true_false_to_string, type=ParameterDictType.BOOL) self._param_dict.add(SBE37Parameter.SYNCMODE, r'serial sync mode (enabled|disabled)', lambda match : False if (match.group(1)=='disabled') else True, self._true_false_to_string, type=ParameterDictType.BOOL) self._param_dict.add(SBE37Parameter.SYNCWAIT, r'wait time after serial sync sampling = (\d+) seconds', lambda match : int(match.group(1)), self._int_to_string, type=ParameterDictType.INT) self._param_dict.add(SBE37Parameter.TCALDATE, r'temperature: +((\d+)-([a-zA-Z]+)-(\d+))', lambda match : self._string_to_date(match.group(1), '%d-%b-%y'), self._date_to_string, type=ParameterDictType.LIST, visibility=ParameterDictVisibility.READ_ONLY) self._param_dict.add(SBE37Parameter.TA0, r' +TA0 = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.TA1, r' +TA1 = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.TA2, r' +TA2 = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.TA3, r' +TA3 = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.CCALDATE, r'conductivity: +((\d+)-([a-zA-Z]+)-(\d+))', lambda match : self._string_to_date(match.group(1), '%d-%b-%y'), self._date_to_string, type=ParameterDictType.LIST, visibility=ParameterDictVisibility.READ_ONLY) self._param_dict.add(SBE37Parameter.CG, r' +G = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.CH, r' +H = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.CI, r' +I = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.CJ, r' +J = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.WBOTC, r' +WBOTC = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.CTCOR, r' +CTCOR = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.CPCOR, r' +CPCOR = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.PCALDATE, r'pressure .+ ((\d+)-([a-zA-Z]+)-(\d+))', lambda match : self._string_to_date(match.group(1), '%d-%b-%y'), self._date_to_string, type=ParameterDictType.LIST, visibility=ParameterDictVisibility.READ_ONLY) self._param_dict.add(SBE37Parameter.PA0, r' +PA0 = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.PA1, r' +PA1 = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.PA2, r' +PA2 = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.PTCA0, r' +PTCA0 = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.PTCA1, r' +PTCA1 = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.PTCA2, r' +PTCA2 = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.PTCB0, r' +PTCSB0 = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.PTCB1, r' +PTCSB1 = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.PTCB2, r' +PTCSB2 = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.POFFSET, r' +POFFSET = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.RCALDATE, r'rtc: +((\d+)-([a-zA-Z]+)-(\d+))', lambda match : self._string_to_date(match.group(1), '%d-%b-%y'), self._date_to_string, type=ParameterDictType.LIST) self._param_dict.add(SBE37Parameter.RTCA0, r' +RTCA0 = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.RTCA1, r' +RTCA1 = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) self._param_dict.add(SBE37Parameter.RTCA2, r' +RTCA2 = (-?\d.\d\d\d\d\d\de[-+]\d\d)', lambda match : float(match.group(1)), self._float_to_string, type=ParameterDictType.FLOAT) ######################################################################## # Static helpers to format set commands. ######################################################################## @staticmethod def _true_false_to_string(v): """ Write a boolean value to string formatted for sbe37 set operations. @param v a boolean value. @retval A yes/no string formatted for sbe37 set operations. @throws InstrumentParameterException if value not a bool. """ if not isinstance(v,bool): raise InstrumentParameterException('Value %s is not a bool.' % str(v)) if v: return 'y' else: return 'n' @staticmethod def _int_to_string(v): """ Write an int value to string formatted for sbe37 set operations. @param v An int val. @retval an int string formatted for sbe37 set operations. @throws InstrumentParameterException if value not an int. """ if not isinstance(v,int): raise InstrumentParameterException('Value %s is not an int.' % str(v)) else: return '%i' % v @staticmethod def _float_to_string(v): """ Write a float value to string formatted for sbe37 set operations. @param v A float val. @retval a float string formatted for sbe37 set operations. @throws InstrumentParameterException if value is not a float. """ if not isinstance(v,float): raise InstrumentParameterException('Value %s is not a float.' % v) else: return '%e' % v @staticmethod def _date_to_string(v): """ Write a date tuple to string formatted for sbe37 set operations. @param v a date tuple: (day,month,year). @retval A date string formatted for sbe37 set operations. @throws InstrumentParameterException if date tuple is not valid. """ if not isinstance(v,(list,tuple)): raise InstrumentParameterException('Value %s is not a list, tuple.' % str(v)) if not len(v)==3: raise InstrumentParameterException('Value %s is not length 3.' % str(v)) months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep', 'Oct','Nov','Dec'] day = v[0] month = v[1] year = v[2] if len(str(year)) > 2: year = int(str(year)[-2:]) if not isinstance(day,int) or day < 1 or day > 31: raise InstrumentParameterException('Value %s is not a day of month.' % str(day)) if not isinstance(month,int) or month < 1 or month > 12: raise InstrumentParameterException('Value %s is not a month.' % str(month)) if not isinstance(year,int) or year < 0 or year > 99: raise InstrumentParameterException('Value %s is not a 0-99 year.' % str(year)) return '%02i-%s-%02i' % (day,months[month-1],year) @staticmethod def _string_to_date(datestr,fmt): """ Extract a date tuple from an sbe37 date string. @param str a string containing date information in sbe37 format. @retval a date tuple. @throws InstrumentParameterException if datestr cannot be formatted to a date. """ if not isinstance(datestr,str): raise InstrumentParameterException('Value %s is not a string.' % str(datestr)) try: date_time = time.strptime(datestr,fmt) date = (date_time[2],date_time[1],date_time[0]) except ValueError: raise InstrumentParameterException('Value %s could not be formatted to a date.' % str(datestr)) return date
UTF-8
Python
false
false
2,013
7,395,933,684,901
b9c55e15ed8c929ef4b59cd0b5f120bf9ec508f6
f9e6d3b2a7afcffef172af6f606fc5991a8b0baa
/channelguide/recommendations/utils.py
e236505753b5a56e604665ac96cac8175c189156
[ "AGPL-3.0-only", "AGPL-3.0-or-later" ]
non_permissive
kmshi/miroguide
https://github.com/kmshi/miroguide
a231298c1d4f7ed61d666e2d32ed212604fe79e9
e1e29a3a8e821bf27c0cad7df95944622c9b9c18
refs/heads/master
2020-05-15T21:58:18.733575
2011-05-30T07:53:15
2011-05-30T07:53:15
1,476,870
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright (c) 2008-2009 Participatory Culture Foundation # See LICENSE for details. import math from datetime import datetime, timedelta from channelguide.channels.models import Channel from channelguide.ratings.models import Rating from channelguide.subscriptions.models import Subscription def filter_scores(scores, numScores): valid = [id for id in numScores if numScores[id] > 3] if not valid: return scores channels = Channel.objects.approved().filter(pk__in=valid, archived=0) return dict((c.id, scores[c.id]) for c in channels) def calculate_scores(recommendations, ratings): simTable = {} scores = {} topThree = {} numScores = {} totalSim = {} for similarity in recommendations: channel1_id, channel2_id, cosine = \ similarity.channel1_id, similarity.channel2_id, similarity.cosine if channel1_id in ratings: simTable.setdefault(channel1_id, {})[channel2_id] = cosine if channel2_id in ratings: simTable.setdefault(channel2_id, {})[channel1_id] = cosine for channel1_id in simTable: rating = ratings.get(channel1_id) if rating is None: continue for channel2_id, cosine in simTable[channel1_id].items(): if channel2_id in ratings: continue scores.setdefault(channel2_id, 0) totalSim.setdefault(channel2_id, 0) numScores.setdefault(channel2_id, 0) score = (cosine * (rating-2.5)) scores[channel2_id] += score totalSim[channel2_id] += abs(cosine) numScores[channel2_id] += 1 if rating > 2: topThree.setdefault(channel2_id, []) thisTop = topThree[channel2_id] thisTop.append((score, channel1_id)) thisTop.sort() scores = dict((id, (scores[id] / totalSim[id]) + 2.5) for id in scores) return scores, numScores, topThree def find_relevant_similar(channel): #return set( # find_relevant_similar_subscription(channel, connection)) | return set( find_relevant_similar_rating(channel)) def find_relevant_similar_subscription(channel, ip_address=None): """ Returns a list of integers representing channel ids. """ query = Subscription.objects.filter( channel__state=Channel.APPROVED, timestamp__gt=(datetime.now()-timedelta(days=31)), ignore_for_recommendations=False).exclude( ip_address='0.0.0.0').exclude( channel=channel) if ip_address is None: query = query.filter( ip_address__in=Subscription.objects.filter( channel=channel, timestamp__gt=(datetime.now()-timedelta(days=31)), ignore_for_recommendations=False).exclude( ip_address='0.0.0.0').values_list('ip_address', flat=True).distinct()) else: query = query.filter(ip_address=ip_address) return query.values_list('channel', flat=True).distinct() def find_relevant_similar_rating(channel): ratings = Rating.objects.filter(channel=channel) if not ratings.count(): return [] return Rating.objects.filter( user__in=ratings.values_list('user', flat=True).distinct()).exclude( channel=channel).values_list('channel', flat=True).distinct() def get_similarity(channel, other): """ Returns the similarity between two channels. channel and other are Channel objects. """ #from_sub = get_similarity_from_subscriptions(channel, other) from_rat = get_similarity_from_ratings(channel, other) from_lang = get_similarity_from_languages(channel, other) from_cat = get_similarity_from_categories(channel, other) return sum((from_rat * 6, from_lang * 3, from_cat)) / 10 def get_similarity_from_subscriptions(channel, other): entries = Subscription.objects.filter( channel__in=[channel, other], timestamp__gt=(datetime.now()-timedelta(days=31)), ignore_for_recommendations=False).exclude( ip_address='0.0.0.0') if not entries: return 0.0 vectors = {} for subscription in entries: vectors.setdefault(subscription.ip_address, [False, False]) i = subscription.channel_id if i == channel.id: vectors[subscription.ip_address][0] = True elif i == other.id: vectors[subscription.ip_address][1] = True else: raise RuntimeError("%r != to %r or %r" % (i, channel.id, other)) keys = vectors.keys() keys.sort() v1 = [vectors[k][0] for k in keys] v2 = [vectors[k][1] for k in keys] c = cosine(v1, v2) return c def get_similarity_from_ratings(channel, other): vectors = {} for rating in Rating.objects.filter(channel__in=[channel, other]): vectors.setdefault(rating.user, [None, None]) i = int(rating.channel_id) if not rating.rating: continue if i == channel.id: vectors[rating.user][0] = rating.rating else: vectors[rating.user][1] = rating.rating keys = [key for key in vectors.keys() if None not in vectors[key]] keys.sort() v1 = [vectors[k][0] for k in keys] v2 = [vectors[k][1] for k in keys] pc = pearson_coefficient(v1, v2) if len(v1) < 5: pc /= 2 return pc def get_similarity_from_categories(channel, other): cat1 = set(channel.categories.all()) cat2 = set(other.categories.all()) if not len(cat1 | cat2): return 0.0 return float(len(cat1 & cat2)) / len(cat1 | cat2) def get_similarity_from_languages(channel, other): lang1 = set([channel.language]) lang2 = set([other.language]) if not len(lang1 | lang2): return 0.0 return float(len(lang1 & lang2)) / len(lang1 | lang2) def pearson_coefficient(vector1, vector2): n = float(len(vector1)) if n < 3: # two points always have a linear corelation return 0.0 sum1 = sum(vector1) sum2 = sum(vector2) sq1 = sum([v**2 for v in vector1]) sq2 = sum([v**2 for v in vector2]) dp = dotProduct(vector1, vector2) numerator = dp - (sum1*sum2/n) denominator = math.sqrt((sq1 - sum1**2 / n) * (sq2 - sum2**2 / n)) if denominator == 0: return 0.0 else: return numerator / denominator def dotProduct(vector1, vector2): return sum([v1*v2 for v1, v2 in zip(vector1, vector2)]) def length(vector): return math.sqrt(sum([v**2 for v in vector])) def cosine(v1, v2): l1 = length(v1) l2 = length(v2) if l1 == 0 or l2 == 0: return 0.0 return dotProduct(v1, v2)/(l1 * l2)
UTF-8
Python
false
false
2,011
8,461,085,614,363
1166e3d2d6aa626a4d23447c1b7e463331b8eed4
5107c33d9466f67266cd5bb936461beab60a5a4f
/was-config-scripts/modify_connect22.py
9b46e65ecff683786c707430a8c7a0a8e645010a
[]
no_license
huy/was_scripts
https://github.com/huy/was_scripts
1158dcf7fc24190efa3322bb750289e31bd78cd1
4eb293489d570109a3a094238d7bec33ce81b88e
refs/heads/master
2021-01-10T22:06:33.857375
2011-10-03T04:22:06
2011-10-03T04:22:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from set_server_port import * from set_jvm_param import * nodeName = 'FCASAWNODE02' serverName = 'connect22' startingPort = 10363 hostName='jpsasfap32' setServerPort(adminTask=AdminTask, nodeName=nodeName, serverName=serverName, hostName=hostName, startingPort=startingPort) setJVMParam(adminConfig=AdminConfig, nodeName=nodeName, serverName=serverName, jvmId='112', userHome='/sit/home/flexapp/FCCONNECT/system/home', wsExtDirs='/sit/home/flexapp/FCCONNECT/system/build/classes:/sit/home/flexapp/FCCONNECT/system/build/extclasses/jars:/sit/home/flexapp/FCCONNECT/system/build/extclasses/FCRJars:/sit/home/flexapp/FCCONNECT/fcrconfig/FCR.CONFIG') AdminConfig.save()
UTF-8
Python
false
false
2,011
3,169,685,876,454
39bb33029adc8bd1681f3ca33e0424c50ac96499
ce59674b3e2227944cf68a12b5fc8d620beddf1d
/resistencia/contest/round.py
09e3d4167169dd2978a213a0d20e6efc317fd953
[ "GPL-3.0-only" ]
non_permissive
pablorecio/resistencia-1812
https://github.com/pablorecio/resistencia-1812
132a65c89808c1f18331c158dea12c78695e56f8
758980ae712624f6d554ec91cb22a94a2a5f9380
refs/heads/master
2020-05-18T17:53:35.206037
2011-01-08T12:31:13
2011-01-08T12:31:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # --------------------------------------------------------------------- # This file is part of Resistencia Cadiz 1812. # # 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 # 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/>. # Copyright (C) 2010, Pablo Recio Quijano #---------------------------------------------------------------------- from guadaboard import guada_board from resistencia import xdg _pieceA = xdg.get_data_path('images/piece-orange.png') _pieceB = xdg.get_data_path('images/piece-violete.png') class Error(Exception): """Base class for exceptions in this module.""" pass class RoundError(Error): """Exception raised for errors in the round iteration Attributes: msg -- explanation of the error """ def __init__(self, msg): self.msg = msg class Round(object): def __init__(self, matchs, translator, log_file, num_turns = 150): self.round = [] #Formed by tuples ((teamA, teamB), played, result) for match in matchs: self.round.append((match, False, 0)) self.completed = False self.log_file = log_file self.next_game = 0 self.number_games = len(self.round) self.translator = translator self.num_turns = num_turns def get_number_of_games(self): return self.number_games def get_game_result(self, id_game): if self.round[id_game][1] == True: return (self.round[id_game][0], self.round[id_game][2]) else: raise RoundError('The game ' + str(id_game) + ' has not been played yet') def get_round_results(self): results = [] if self.completed: for match in self.round: results.append((match[0], match[2])) return results else: raise RoundError('Not all games played') def get_winners(self): winners = [] if self.completed: for match in self.round: result = match[2] if result == 1: winners.append(match[0][0]) elif result == -1: winners.append(match[0][1]) return winners else: raise RoundError('Not all games played') def get_puntuation(self): results = {} if self.completed: for match in self.round: result = match[2] teamA = match[0][0] teamB = match[0][1] if result == 0: results[teamA] = 1 results[teamB] = 1 elif result == 1: results[teamA] = 3 results[teamB] = 0 elif result == -1: results[teamA] = 0 results[teamB] = 3 return results else: raise RoundError('Not all games played') def log_tournament(self, full=False): if self.completed: f_log = open(self.log_file, 'a') for match in self.round: teamA = match[0][0] teamB = match[0][1] s = teamA + ' - ' + teamB n = 50 - len(s) res = '' if match[2] == 0: res = 'X' elif match[2] == 1: res = '1' else: #match[2] == -1: res = '2' f_log.write(s + ' ' + '-'*n + '-' + res + "\n") f_log.close() else: raise RoundError('Not all games played') def play_match(self, fast=False, cant_draw=False): teamA_key = self.round[self.next_game][0][0] teamB_key = self.round[self.next_game][0][1] teamA = None teamB = None result = 0 if (not teamA_key == 'aux_ghost_team') and (not teamB_key == 'aux_ghost_team'): teamA = (self.translator[teamA_key], _pieceA) teamB = (self.translator[teamB_key], _pieceB) result = guada_board.run(teamA, teamB, fast=fast, hidden=True, number_turns=self.num_turns, cant_draw=cant_draw) else: if teamA_key == 'aux_ghost_team': result = -1 else: #teamB_key == 'aux_ghost_team': result = 1 print "The result of the game '" + teamA_key + "' - '"+ teamB_key + "' was:" if result == 0: print 'Draw' elif result == 1: print teamA_key + ' won' elif result == -1: print teamB_key + ' won' self.round[self.next_game] = (self.round[self.next_game][0], True, result) #self.round[self.next_game][1] = True #self.round[self.next_game][2] = result self.next_game = self.next_game + 1 self.completed = (self.next_game == self.number_games) return (self.round[self.next_game-1][0], self.round[self.next_game-1][2]) def is_complete(self): return self.completed
UTF-8
Python
false
false
2,011
15,805,479,656,639
9e2c315dfe91ca44e5c5f5b270e7fbc343f5e29d
c78025e319eec372898c851c0f95715757c14cc5
/rgba2png.py
edbcc7c93370e3b7bb8088bcea021fa953692998
[]
no_license
DamienCassou/proteus
https://github.com/DamienCassou/proteus
017df3acad26fe881716a8c4d4cb8aa8fdc78530
dac9866918dd74c931e503396b6e3e93a5cd70cc
refs/heads/master
2021-01-19T21:28:35.219362
2011-06-16T12:28:24
2011-06-16T12:28:24
1,831,141
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import sys import png import math import numpy import struct def rgba8_png(raw_file): fd = open(raw_file, 'rb') buff = fd.read() fd.close() # buff: bytes(VideoTexture.ImageRender.image) (cf. Blender 2.5 API & MORSE ) image_size = int(math.sqrt(len(buff) / 4)) image2d = numpy.reshape([struct.unpack('B', b)[0] for b in buff], (-1, image_size * 4)) png_writer = png.Writer(width = image_size, height = image_size, alpha = True) out_png = open(raw_file + '.png', 'wb') png_writer.write(out_png, image2d) out_png.close() #("mencoder", "mf://*.png", "-mf", "fps="+fps+":type=png", "-sws", "6", "-o", videoname, "-ovc", "x264", "-x264encopts", "bitrate="+x264bitrate) def main(args): for f in args[1:]: rgba8_png(f) help() def help(): print('Convert RAW RGBA8 bytes to PNG image') print('usage: '+sys.argv[0]+' file1 [file2 [file3 [...]]]') print('TIPS: use MEncoder to build a video:') print('mencoder mf://*.png -mf fps=2:type=png -sws 6 -o rgba8.avi -ovc x264') print('mencoder mf:///tmp/morse_camera*.png -mf fps=2:type=png -flip -o rgba8.avi -ovc x264') if __name__ == '__main__': main(sys.argv)
UTF-8
Python
false
false
2,011
17,532,056,531,311
252290cf9187e88409dd254468aa53bc65a22a9a
3d51c5c6cd7cc4b6267fd6c796cadb0a64df6716
/week_0/day_1/contain_digs.py
43eaf4a3d4de037ca35e73b75dfda5a9596ae49c
[]
no_license
SlaviSotirov/HackBulgaria
https://github.com/SlaviSotirov/HackBulgaria
b8f671d5937250307ef6edefbd7aeb2ebf4af6d3
f2a6bd87dcf845896731cbc05a5d18862c1ac70c
refs/heads/master
2021-01-25T12:20:34.121759
2014-12-05T18:00:53
2014-12-05T18:00:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def contains_digit(number, digit): string = str(number) char = str(digit) for symbol in string: if symbol == char: return True return False print(contains_digit(143, 2))
UTF-8
Python
false
false
2,014
19,318,762,934,096
aa48596fdd5afb508dc4dde35442222e0fdd38ef
8e7a81a1fd4096b9dcefb6ef293c27a9cb1a22e9
/configuration/datatypes.py
b4f37072789d5908c67423014977a2d8569b755a
[ "GPL-3.0-only" ]
non_permissive
bitsworking/blink-cocoa
https://github.com/bitsworking/blink-cocoa
61a2526f3c3d2e90c4ed6b2d34e9accf37d97faa
0f282283fd4a775fead0d518000a4b51d8ddf6cb
refs/heads/master
2021-01-25T07:27:36.110564
2014-04-25T15:05:54
2014-04-25T15:05:54
22,062,521
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright (C) 2010 AG Projects. See LICENSE for details. # """ Definitions of datatypes for use in settings extensions. """ __all__ = ['Digits', 'AccountSoundFile', 'AnsweringMachineSoundFile', 'AccountTLSCertificate', 'SoundFile', 'UserDataPath', 'UserIcon', 'UserSoundFile','HTTPURL', 'LDAPdn', 'LDAPusername', 'NightVolume'] from Foundation import NSLocalizedString import ldap import os import hashlib import urlparse from application.python.descriptor import WriteOnceAttribute from resources import ApplicationData, Resources from sipsimple.configuration.datatypes import Hostname ## PSTN datatypes class Digits(str): pass ## Path datatypes class UserDataPath(unicode): def __new__(cls, path): path = os.path.expanduser(os.path.normpath(path)) if path.startswith(ApplicationData.directory+os.path.sep): path = path[len(ApplicationData.directory+os.path.sep):] return unicode.__new__(cls, path) @property def normalized(self): return ApplicationData.get(self) class SoundFile(object): def __init__(self, path, volume=100): self.path = path self.volume = int(volume) if self.volume < 0 or self.volume > 100: raise ValueError(NSLocalizedString("Illegal volume level: %d", "Preference option error") % self.volume) def __getstate__(self): return u'%s,%s' % (self.__dict__['path'], self.volume) def __setstate__(self, state): try: path, volume = state.rsplit(u',', 1) except ValueError: self.__init__(state) else: self.__init__(path, volume) def __repr__(self): return '%s(%r, %r)' % (self.__class__.__name__, self.path, self.volume) def _get_path(self): return Resources.get(self.__dict__['path']) def _set_path(self, path): path = os.path.normpath(path) if path.startswith(Resources.directory+os.path.sep): path = path[len(Resources.directory+os.path.sep):] self.__dict__['path'] = path path = property(_get_path, _set_path) del _get_path, _set_path class NightVolume(object): def __init__(self, start_hour=22, end_hour=8, volume=10): self.start_hour = int(start_hour) self.end_hour = int(end_hour) self.volume = int(volume) if self.volume < 0 or self.volume > 100: raise ValueError(NSLocalizedString("Illegal volume level: %d", "Preference option error") % self.volume) if self.start_hour < 0 or self.start_hour > 23: raise ValueError(NSLocalizedString("Illegal start hour value: %d", "Preference option error") % self.start_hour) if self.end_hour < 0 or self.end_hour > 23: raise ValueError(NSLocalizedString("Illegal end hour value: %d", "Preference option error") % self.end_hour) def __getstate__(self): return u'%s,%s,%s' % (self.start_hour, self.end_hour, self.volume) def __setstate__(self, state): try: start_hour, end_hour, volume = state.split(u',') except ValueError: self.__init__(state) else: self.__init__(start_hour, end_hour, volume) def __repr__(self): return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_hour, self.end_hour, self.volume) class AccountSoundFile(object): class DefaultSoundFile(object): def __init__(self, setting): self.setting = setting def __repr__(self): return 'AccountSoundFile.DefaultSoundFile(%s)' % self.setting __str__ = __repr__ def __init__(self, sound_file, *args, **kwargs): if isinstance(sound_file, self.DefaultSoundFile): self._sound_file = sound_file if args or kwargs: raise ValueError("other parameters cannot be specified if sound file is instance of DefaultSoundFile") else: self._sound_file = SoundFile(sound_file, *args, **kwargs) def __getstate__(self): if isinstance(self._sound_file, self.DefaultSoundFile): return u'default:%s' % self._sound_file.setting else: return u'file:%s' % self._sound_file.__getstate__() def __setstate__(self, state): type, value = state.split(u':', 1) if type == u'default': self._sound_file = self.DefaultSoundFile(value) elif type == u'file': self._sound_file = SoundFile.__new__(SoundFile) self._sound_file.__setstate__(value) @property def sound_file(self): if isinstance(self._sound_file, self.DefaultSoundFile): from sipsimple.configuration.settings import SIPSimpleSettings setting = SIPSimpleSettings() for comp in self._sound_file.setting.split('.'): setting = getattr(setting, comp) return setting else: return self._sound_file def __repr__(self): if isinstance(self._sound_file, self.DefaultSoundFile): return '%s(%r)' % (self.__class__.__name__, self._sound_file) else: return '%s(%r, volume=%d)' % (self.__class__.__name__, self._sound_file.path, self._sound_file.volume) def __unicode__(self): if isinstance(self._sound_file, self.DefaultSoundFile): return u'DEFAULT' else: return u'%s,%d' % (self._sound_file.path, self._sound_file.volume) class AnsweringMachineSoundFile(object): class DefaultSoundFile(object): def __init__(self, setting): self.setting = setting def __repr__(self): return 'AnsweringMachineSoundFile.DefaultSoundFile(%s)' % self.setting __str__ = __repr__ def __init__(self, sound_file, volume=100): if isinstance(sound_file, self.DefaultSoundFile): self._sound_file = sound_file else: self._sound_file = UserSoundFile(sound_file, volume) def __getstate__(self): if isinstance(self._sound_file, self.DefaultSoundFile): return u'default:%s' % self._sound_file.setting else: return u'file:%s' % self._sound_file.__getstate__() def __setstate__(self, state): type, value = state.split(u':', 1) if type == u'default': self._sound_file = self.DefaultSoundFile(value) elif type == u'file': self._sound_file = UserSoundFile.__new__(UserSoundFile) self._sound_file.__setstate__(value) @property def sound_file(self): if isinstance(self._sound_file, self.DefaultSoundFile): return UserSoundFile(Resources.get(self._sound_file.setting)) else: return self._sound_file def __repr__(self): if isinstance(self._sound_file, self.DefaultSoundFile): return '%s(%r)' % (self.__class__.__name__, self._sound_file) else: return '%s(%r, volume=%d)' % (self.__class__.__name__, self._sound_file.path, self._sound_file.volume) def __unicode__(self): if isinstance(self._sound_file, self.DefaultSoundFile): return u'DEFAULT' else: return u'%s,%d' % (self._sound_file.path, self._sound_file.volume) class UserSoundFile(SoundFile): def _get_path(self): return ApplicationData.get(self.__dict__['path']) def _set_path(self, path): path = os.path.normpath(path) if path.startswith(ApplicationData.directory+os.path.sep): path = path[len(ApplicationData.directory+os.path.sep):] self.__dict__['path'] = path path = property(_get_path, _set_path) del _get_path, _set_path class AccountTLSCertificate(object): class DefaultTLSCertificate(unicode): pass def __init__(self, path): if not path or path.lower() == u'default': path = self.DefaultTLSCertificate() self.path = path def __getstate__(self): if isinstance(self.__dict__['path'], self.DefaultTLSCertificate): return u'default' else: return self.path def __setstate__(self, state): self.__init__(state) def __unicode__(self): if isinstance(self.__dict__['path'], self.DefaultTLSCertificate): return u'Default' else: return self.__dict__['path'] def _get_path(self): if isinstance(self.__dict__['path'], self.DefaultTLSCertificate): return Resources.get(self.__dict__['path']) else: return ApplicationData.get(self.__dict__['path']) def _set_path(self, path): if not path or path.lower() == u'default': path = self.DefaultTLSCertificate() if not isinstance(path, self.DefaultTLSCertificate): path = os.path.normpath(path) if path.startswith(ApplicationData.directory+os.path.sep): path = path[len(ApplicationData.directory+os.path.sep):] self.__dict__['path'] = path path = property(_get_path, _set_path) del _get_path, _set_path @property def normalized(self): return self.path ## Miscellaneous datatypes class HTTPURL(object): url = WriteOnceAttribute() def __init__(self, value): url = urlparse.urlparse(value) if url.scheme not in (u'http', u'https'): raise ValueError(NSLocalizedString("Illegal HTTP URL scheme (http and https only): %s", "Preference option error") % url.scheme) # check port and hostname Hostname(url.hostname) if url.port is not None: if not (0 < url.port < 65536): raise ValueError(NSLocalizedString("Illegal port value: %d", "Preference option error") % url.port) self.url = url def __getstate__(self): return unicode(self.url.geturl()) def __setstate__(self, state): self.__init__(state) def __getitem__(self, index): return self.url.__getitem__(index) def __getattr__(self, attr): if attr in ('scheme', 'netloc', 'path', 'params', 'query', 'fragment', 'username', 'password', 'hostname', 'port'): return getattr(self.url, attr) else: raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, attr)) def __unicode__(self): return unicode(self.url.geturl()) class LDAPdn(str): def __new__(cls, value): value = str(value) try: ldap.dn.str2dn(value) except ldap.DECODING_ERROR: raise ValueError(NSLocalizedString("Illegal LDAP DN format: %s", "Preference option error") % value) return value class LDAPusername(str): def __new__(cls, value): value = str(value) if "," in value: try: ldap.dn.str2dn(value) except ldap.DECODING_ERROR: raise ValueError(NSLocalizedString("Illegal LDAP DN format for username: %s", "Preference option error") % value) return value class UserIcon(object): def __init__(self, path, etag=None): self.path = path self.etag = etag def __getstate__(self): return u'%s,%s' % (self.path, self.etag) def __setstate__(self, state): try: path, etag = state.rsplit(u',', 1) except ValueError: self.__init__(state) else: self.__init__(path, etag) def __eq__(self, other): if isinstance(other, UserIcon): return self.path==other.path and self.etag==other.etag return NotImplemented def __ne__(self, other): equal = self.__eq__(other) return NotImplemented if equal is NotImplemented else not equal def __repr__(self): return '%s(%r, %r)' % (self.__class__.__name__, self.path, self.etag)
UTF-8
Python
false
false
2,014
5,634,997,130,959
bf591fc084eb50665876364c24ec7210f8a0da4d
7faded5b2b6f063763b661f2d93d44c93f5f808b
/common/json_utils.py
f59ff3e36fd88f142c6df952cd845a6a76e927d9
[]
no_license
liangqun/tools
https://github.com/liangqun/tools
f51daeaf04003f28495eabb5d650c12ddf352fbb
43af916ef24a6cb9be5e666f3458f32b146138f1
refs/heads/master
2016-09-06T11:30:35.420885
2012-04-30T11:07:23
2012-04-30T11:07:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from common import minjson def obj_to_dict(obj,current_level=0,max_level=5): current_level += 1 if not obj: return obj if isinstance(obj, (str,int,long,unicode)): return obj if isinstance(obj, (list,tuple,set)): new_list = [] for item in obj: if isinstance(item, (str,int,long,unicode)): new_list.append(item) else: if current_level <= max_level: new_list.append(obj_to_dict(item, current_level, max_level)) return new_list if isinstance(obj, dict): keys_to_pop = [key for key in obj if key.startswith('_')] for key in keys_to_pop: obj.pop(key) new_dict = {} for key,value in obj.iteritems(): if isinstance(value, (str,int,long,unicode)): new_dict[key] = value else: if current_level <= max_level: new_dict[key] = obj_to_dict(value, current_level, max_level) return new_dict if current_level <= max_level: try: return obj_to_dict(obj.__dict__, current_level, max_level) except: pass return None def obj_to_json_for_ajax(obj): if isinstance(obj, (list,tuple)): data = obj_to_dict(obj[1]) else: data = obj_to_dict(obj) return minjson.write(data) return minjson.write([obj[0],data]) def obj_to_json(obj): return minjson.write(obj_to_dict(obj,max_level=2))
UTF-8
Python
false
false
2,012
16,389,595,243,279
e79aeeb3b0d8dd2084055594cc06c5929d769842
dbcaf17b39b4302abf2341dd68de31854f7d2989
/midware.py
3f7eb5fb5a3efa3c645e5e0275703e92bb5d11ef
[]
no_license
vissible/webserver
https://github.com/vissible/webserver
1d56e9db66f1a932a0144d326e8160980abb5f0a
ee9b146746dce59250328dd64d3972e027ff54df
refs/heads/master
2020-12-25T16:24:41.499221
2012-09-04T06:43:01
2012-09-04T06:43:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @date: 2012-09-03 @author: shell.xu ''' import re, time, heapq, random, urllib, cPickle, logging from http import * cache_logger = logging.getLogger('cache') class Dispatch(object): def __init__(self, urlmap=None): self.urlmap = [[re.compile(i[0]),] + list(i[1:]) for i in urlmap] def __call__(self, req): for o in self.urlmap: m = o[0].match(req.url.path) if not m: continue req.url_match = m.groups() req.url_param = o[2:] return o[1](req) return self.default_handler(req) def default_handler(req): return response_http(404, body='File Not Found') class Cache(object): def __call__(self, func): def inner(req): pd = self.get_data(req.url.path) if pd: cache_logger.info('cache hit in %s', req.url.path) return cPickle.loads(pd) res = func(req) if res is not None and res.cache and hasattr(res, 'body'): res.set_header('cache-control', 'max-age=%d' % res.cache) pd = cPickle.dumps(res, 2) self.set_data(req.url.path, pd, res.cache) return res return inner class ObjHeap(object): ''' 使用lru算法的对象缓存容器,感谢Evan Prodromou <evan@bad.dynu.ca>。 thx for Evan Prodromou <evan@bad.dynu.ca>. ''' class __node(object): def __init__(self, k, v, f): self.k, self.v, self.f = k, v, f def __cmp__(self, o): return self.f > o.f def __init__(self, size): self.size, self.f = size, 0 self.__dict, self.__heap = {}, [] def __len__(self): return len(self.__dict) def __contains__(self, k): return self.__dict.has_key(k) def __setitem__(self, k, v): if self.__dict.has_key(k): n = self.__dict[k] n.v = v self.f += 1 n.f = self.f heapq.heapify(self.__heap) else: while len(self.__heap) >= self.size: del self.__dict[heapq.heappop(self.__heap).k] self.f = 0 for n in self.__heap: n.f = 0 n = self.__node(k, v, self.f) self.__dict[k] = n heapq.heappush(self.__heap, n) def __getitem__(self, k): n = self.__dict[k] self.f += 1 n.f = self.f heapq.heapify(self.__heap) return n.v def __delitem__(self, k): n = self.__dict[k] del self.__dict[k] self.__heap.remove(n) heapq.heapify(self.__heap) return n.v def __iter__(self): c = self.__heap[:] while len(c): yield heapq.heappop(c).k raise StopIteration class MemoryCache(Cache): def __init__(self, size): super(MemoryCache, self).__init__() self.oh = ObjHeap(size) def get_data(self, k): try: o = self.oh[k] except KeyError: return None if o[1] >= time.time(): return o[0] del self.oh[k] return None def set_data(self, k, v, exp): self.oh[k] = (v, time.time() + exp) sess_logger = logging.getLogger('sess') random.seed() alpha = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/' def get_rnd_sess(): return ''.join(random.sample(alpha, 32)) def get_params_dict(data, sp = '&'): if not data: return {} rslt = {} for p in data.split(sp): i = p.strip().split('=', 1) rslt[i[0]] = urllib.unquote(i[1]) return rslt class Cookie(object): def __init__(self, cookie): if not cookie: self.v = {} else: self.v = get_params_dict(cookie, ';') self.m = set() def get(self, k, d): return self.v.get(k, d) def __contains__(self, k): return k in self.v def __getitem__(self, k): return self.v[k] def __delitem__(self, k): self.m.add(k) del self.v[k] def __setitem__(self, k, v): self.m.add(k) self.v[k] = v def set_cookie(self, res): for k in self.m: res.add_header('set-cookie', '%s=%s' % (k, urllib.quote(self.v[k]))) class Session(object): def __init__(self, timeout): self.exp = timeout def __call__(self, func): def inner(req): req.cookie = Cookie(req.get_header('cookie', None)) sessionid = req.cookie.get('sessionid', '') if not sessionid: sessionid = get_rnd_sess() req.cookie['sessionid'] = sessionid data = None else: data = self.get_data(sessionid) if data: req.session = cPickle.loads(data) else: req.session = {} sess_logger.info('sessionid: %s' % sessionid) sess_logger.info('session: %s' % str(req.session)) res = func(req) self.set_data(sessionid, cPickle.dumps(req.session, 2)) req.cookie.set_cookie(res) return res return inner class MemorySession(Session): def __init__(self, timeout): super(MemorySession, self).__init__(timeout) self.sessions = {} def get_data(self, sessionid): return self.sessions.get(sessionid, None) def set_data(self, sessionid, data): self.sessions[sessionid] = data
UTF-8
Python
false
false
2,012
7,516,192,818,181
7d93e3367142d5575d16d34f19639e358bed746b
ebf42d399474f268069e96a4d81c5574cf2314ae
/project/apps/leechy/cache.py
e79913c1a96411b0d94ccc113a22d5113d2c8d81
[]
no_license
flupke/leechy
https://github.com/flupke/leechy
f9ee1d9b5222fdae1822184c72a752672565a1aa
61fdd9b7e5eba987f6ac85de95cf624041b7f8a1
refs/heads/master
2016-08-07T14:16:12.268591
2013-05-22T05:01:42
2013-05-22T05:01:42
1,972,744
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import os.path as op import logging from django.core.cache import cache from leechy import settings from leechy.utils import force_utf8 logger = logging.getLogger(__name__) def dir_cache_key(path): """ Get the cache key for *path*. """ path = force_utf8(path) name = op.abspath(path).replace(" ", "_") return "leechy-dir-cache-%s" % name def listdir(path): """ Retrieve the contents of directory at *path*. """ path = force_utf8(path) cache_key = dir_cache_key(path) data = cache.get(cache_key) if data is not None: return data return dir_cache_data(path) def dir_cache_data(path): """ Return the data to store in the cache for directory at *path*. """ path = force_utf8(path) files = [] directories = [] for entry in os.listdir(path): for pattern in settings.EXCLUDE_FILES: if pattern.match(entry): continue entry_path = op.join(path, entry) if not op.exists(entry_path): # File was deleted during directory listing continue timestamp = op.getmtime(entry_path) if op.isdir(entry_path): size = 0 for dirpath, dirnames, filenames in \ os.walk(entry_path): for f in filenames: fp = op.join(dirpath, f) if op.exists(fp): size += op.getsize(fp) directories.append((entry, size, timestamp)) else: size = op.getsize(entry_path) files.append((entry, size, timestamp)) return directories, files def cache_directory(path): """ Put the directory at *path* in the cache. """ path = force_utf8(path) cache_key = dir_cache_key(path) if op.exists(path): cache.set(cache_key, dir_cache_data(path)) else: cache.delete(cache_key)
UTF-8
Python
false
false
2,013
6,098,853,588,376
370f269c894296059548198c27071be4bb7fb7fe
17a25c937c79f360fe2d94d0f166d9d87ce77325
/models.py
ca879d8f42aa57c037a2b9ce61834ed1b7caef64
[]
no_license
imclab/Batty
https://github.com/imclab/Batty
6e1cf420cd4f7ca36ac5a69c878d51ae56b6e244
dea85e84d0bca119bbff52fba95fcc1972c2651e
refs/heads/master
2021-01-15T15:23:58.812283
2011-12-06T14:05:19
2011-12-06T14:05:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import datetime from dictshield.document import Document from dictshield.fields import StringField from dictshield.fields import ObjectIdField from dictshield.fields import IntField from dictshield.fields import DateTimeField import simplejson as json import redis class Client(object): def __init__(self, **kwargs): self.connection_settings = kwargs or {'host': 'localhost', 'port': 6379, 'db': 0} def redis(self): return redis.Redis(**self.connection_settings) def update(self, d): self.connection_settings.update(d) def connection_setup(**kwargs): global connection, client if client: client.update(kwargs) else: client = Client(**kwargs) connection = client.redis() def get_client(): global connection return connection client = Client() connection = client.redis() class BaseDocument(Document): def save(self, redis_client = None): redis_client = redis_client or connection if self.key is None: #generate the key as well id = redis_client.incr('global_unique_counter') self.id = id self.key = '%s%s' % (self.key_prefix, id) redis_client.set(self.key, self.to_json()) return self @classmethod def get(cls, id, redis_client = None): """Quick helper function to retrieve an object""" redis_client = redis_client or connection key = '%s%s' % (cls.key_prefix, id) json_str = redis_client.get(key) if json_str: return cls(**json.loads(json_str)) else: return None @classmethod def multi_get(cls, redis_client, *keys): """Quick helper function to retrieve an object""" redis_client = redis_client or connection if not keys: return [] redis_strings = redis_client.mget(*keys) objects = [] for json_str in redis_strings: if json_str: objects.append(cls(**json.loads(json_str))) return objects @classmethod def get_all(cls, redis_client = None): """Quick helper function to retrieve an object""" redis_client = redis_client or connection keys = redis_client.keys('%s*' % (cls.key_prefix)) if keys: return cls.multi_get(redis_client, *keys) else: return [] def reload(self, redis_client = None): """Quick function to reload current object from datastore""" redis_client = redis_client or connection self = self.__class__.get(self.key, redis_client) return self def delete(self, redis_client = None): """Quick function to delete a redis client""" redis_client = redis_client or connection redis_client.delete(self.key) class Conference(BaseDocument): id = StringField(default = None) key = StringField(default = None) url_title = StringField() title = StringField(required = True) desc = StringField() venue = StringField() start_date = DateTimeField() end_date = DateTimeField() twitter_handle = StringField() twitter_hashcode = StringField() url_key_prefix = 'conference:url:' key_prefix = 'conference:id:' session_set_prefix = 'conference:sessions:' def update_url_key(self, redis_client = None): redis_client = redis_client or connection url_key = '%s%s' % (Conference.url_key_prefix, self.url_title) redis_client.set(url_key, self.id) @staticmethod def get_id_from_url_title(url_title, redis_client = None): redis_client = redis_client or connection url_key = '%s%s' % (Conference.url_key_prefix, url_title) return redis_client.get(url_key) def add_session(self, session, redis_client = None): set_key = '%s%s' % (Conference.session_set_prefix, self.id) import time redis_client = redis_client or connection redis_client.zadd(set_key, **{'%s' % (session.id): time.mktime(session.start_date.timetuple())}) def get_sessions_keys(self, redis_client = None): redis_client = redis_client or connection set_key = '%s%s' % (Conference.session_set_prefix, self.id) session_keys = ['%s%s' % (Session.key_prefix, x) for x in redis_client.zrange(set_key, 0, 100)] return session_keys class Session(BaseDocument): id = StringField(default = None) key = StringField(default = None) conf_id = StringField(required = True) talk_type = StringField(default = 'Talk') title = StringField(required = True) desc = StringField() venue = StringField() duration = IntField() start_date = DateTimeField() end_date = DateTimeField() speaker_title = StringField() key_prefix = 'session:id:' def json_friendly(self): day = self.start_date.strftime('%A') time_label = '%s' % (self.start_date.strftime('%I:%M%p')) d = self.to_json(encode = False) d['day'] = day d['time_label'] = time_label return d class Speaker(BaseDocument): id = StringField(default = None) key = StringField(default = None) first_name = StringField() last_name = StringField() desc = StringField() twitter_handle = StringField() key_prefix = 'speaker:id:'
UTF-8
Python
false
false
2,011
2,224,793,102,491
89553ab440802ee022cb2b08eeb05351be47cdd6
21588d77a875c4f2b7f92ffed0b4f3d1a8b1aa7c
/models/task.py
eb82b049fccb202941b0881befae85004f4d943b
[]
no_license
Daduce/dd_server
https://github.com/Daduce/dd_server
af1ea82fb8f94b01303de18c1088090ccf671f16
1dcfd382820992d703f737ae790cf55a90e0f872
refs/heads/dev
2018-01-07T10:34:35.002429
2013-10-24T04:14:29
2013-10-24T04:14:29
12,789,781
0
0
null
false
2016-07-20T14:59:11
2013-09-12T17:19:28
2014-10-28T03:04:55
2013-11-18T23:14:10
25,780
0
0
37
JavaScript
null
null
import sys import os import time from subprocess import Popen from multiprocessing import Pool try: from rq import Worker, Queue from redis import Redis except: print('Could not load modules rq and redis.') def start_worker(): interpreter = str(sys.executable) #python interpreter path = '/home/wroscoe/code/daduce/lib' script = 'rqworker.py' cmd = interpreter + ' ' + os.path.join(path, script) r = Popen([interpreter,os.path.join(path, script)], stderr=subprocess.STDOUT) if r.poll(): print('worker did not start') return r.pid def kill_worker(pid): os.kill(pid, signal.SIGINT) class Task(): def __init__(self): self.pool = Pool(processes=4) def rq_exists(self): try: __import__('rq') except ImportError: return False else: return True def run(self, func, args=None, kwargs=None, cache=False, cache_key=None, ptype='serial'): args = [] if not args else args kwargs = {} if not kwargs else kwargs if ptype=='sync': result = f(*args, **kwargs) elif ptype=='async': async_result = self.pool.apply_async(func, args, kwargs) result = async_result.get(timeout=10) elif ptype=='queue': #use RQ as a task queue, this does not return results! if not self.rq_exists(): raise NameError('RQ must be installed for you to queue tasks') q = Queue(connection=Redis()) a = Worker.all(connection=Redis()) if not a: raise NameError('You must have a worker started to use queue') return result def close(self): self.pool.terminate() t = Task() print ( t.run(f, ptype='queue') ) t.close() t.rq_exists()
UTF-8
Python
false
false
2,013
3,693,671,917,840
8a7ca292b88de2f06f8859805f6e1b6d6fb292bf
76899bcd2e8e4b21c288eb24ace308637b391754
/possiblecity/apps/philadelphia/tasks.py
d5909bb2ddf0b90b56546ecba75e2492f2522da2
[]
no_license
possiblecity/possiblecity
https://github.com/possiblecity/possiblecity
b894d71a544c4dff833cc747a78943ccd47861df
85fff452726dbec95fbece7aeb3f154325235049
refs/heads/master
2020-05-30T10:47:31.582801
2014-02-11T14:57:05
2014-02-11T14:57:05
1,536,890
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# philadelphia/tasks.py import datetime import os import json import requests from django.conf import settings from django.contrib.gis.utils import LayerMapping from models import LotProfile from celery import task from apps.lotxlot.utils import queryset_iterator pwd_parcel_mapping = { 'opa_code': 'TENCODE', 'brt_id': 'BRT_ID', 'address': 'ADDRESS', 'pwd_parcel': 'MULTIPOLYGON' } def _get_filepath(file): return os.path.abspath(os.path.join(settings.PROJECT_ROOT, 'data', file)) @task() def map(): data_source = _get_filepath('all_the_rest/pwd_parcels_all_the_rest.shp') lm = LayerMapping(LotProfile, data_source, pwd_parcel_mapping, transform=False, encoding='iso-8859-1', unique='TENCODE') lm.save(verbose=True, step=1000) @task() def check_landuse_vacancy(): """ Check landuse data source to get vacancy status. Update database accordingly. """ from apps.lotxlot.models import Lot t = datetime.datetime.now() - datetime.timedelta(days=1) queryset = queryset_iterator(Lot.objects.filter(created__gt=t)) for lot in queryset: lon = lot.coord.x lat = lot.coord.y source = settings.PHL_DATA["LAND_USE"] + "query" params = {"geometry":"%f, %f" % (lon, lat), "geometryType":"esriGeometryPoint", "returnGeometry":"false", "inSR":"4326", "spatialRel":"esriSpatialRelWithin", "outFields":"C_DIG3", "f":"json"} req = requests.get(source, params=params) data = json.loads(req.text) if data: if "features" in data: features = data["features"] if features[0]: attributes = features[0]["attributes"] if "C_DIG3" in attributes: if attributes["C_DIG3"] == 911: lot.is_vacant = True lot.save(update_fields=["is_vacant",]) print("updated lot %s") % lot.address else: print(lot.id) @task() def check_public(): """ Check papl assets data source to get public status. Update database accordingly. """ from apps.lotxlot.models import Lot t = datetime.datetime.now() - datetime.timedelta(days=1) queryset = queryset_iterator(Lot.objects.vacant()) #queryset = queryset_iterator(Lot.objects.filter(created__gt=t)) for lot in queryset: lon = lot.coord.x lat = lot.coord.y source = settings.PHL_DATA["PAPL_ASSETS"] + "query" params = {"geometry":"%f, %f" % (lon, lat), "geometryType":"esriGeometryPoint", "returnGeometry":"false", "inSR":"4326", "spatialRel":"esriSpatialRelWithin", "outFields":"C_DIG3", "f":"json"} req = requests.get(source, params=params) data = json.loads(req.text) if data: if "features" in data: features = data["features"] if features: if features[0]: lot.is_public = True lot.save(update_fields=["is_public",]) print("updated lot %s") % lot.address @task() def get_basereg(): """ Check papl parcel data source to get basereg number. Update database accordingly. """ from .models import LotProfile queryset = queryset_iterator(LotProfile.objects.filter(basereg='')) for lot_profile in queryset: lon = lot_profile.get_center().x lat = lot_profile.get_center().y source = settings.PHL_DATA["PAPL_PARCELS"] + "query" params = {"geometry":"%f, %f" % (lon, lat), "geometryType":"esriGeometryPoint", "returnGeometry":"false", "inSR":"4326", "spatialRel":"esriSpatialRelWithin", "outFields":"BASEREG", "f":"json"} req = requests.get(source, params=params) data = json.loads(req.text) if data: if "features" in data: features = data["features"] if features: if features[0]: attributes = features[0]["attributes"] lot_profile.basereg = attributes["BASEREG"] lot_profile.save(update_fields=["basereg",]) print("updated lot %s") % lot_profile.address @task def update_vacancy(public=False): """ Check vacancy indicators and mark is_vacant appropriately """ from apps.lotxlot.models import Lot t = datetime.datetime.now() - datetime.timedelta(days=14) if public: queryset = queryset_iterator(Lot.objects.public()) else: queryset = queryset_iterator(Lot.objects.filter(is_vacant=False, updated__lt=t)) for lot in queryset: vacant = lot.is_vacant if lot.profile.is_bldg_desc_vacant: vacant=True indicator="bldg desc" elif lot.profile.is_land_use_vacant: vacant=True indicator="land use" elif lot.profile.has_license: vacant=True indicator="license" elif lot.profile.has_violation: vacant=True indicator="violation" elif lot.profile.is_for_sale: vacant=True indicator="for sale" else: vacant=False indicator="Not Vacant" lot.is_vacant = vacant lot.save(update_fields=["is_vacant", "updated"]) print("updated lot %s: %s") % (lot.id, indicator)
UTF-8
Python
false
false
2,014
17,772,574,690,857
e8ddedfa0ce7d5ce17857ea7f0cf1cee909caab9
17a7054dd40949e77e55ecfa92f63cc9fb402ef2
/openslides/utils/forms.py
f42c2f09f275823b40cb4eac8f3f83fd20681003
[ "MIT", "GPL-2.0-only", "GPL-2.0-or-later", "BSD-3-Clause" ]
non_permissive
frauenknecht/OpenSlides
https://github.com/frauenknecht/OpenSlides
3bcb399fa9eb2461b42677ae6c6fdc63ffef78d4
6521d6b095bca33dc0c5f09f59067551800ea1e3
refs/heads/master
2021-01-17T16:51:42.806826
2014-04-28T22:02:52
2014-04-28T22:02:52
5,261,424
1
0
null
true
2013-02-15T09:23:05
2012-08-01T16:03:25
2013-02-15T09:23:04
2013-02-15T09:23:04
344
null
0
0
Python
null
null
# -*- coding: utf-8 -*- import bleach from django import forms from django.utils.translation import ugettext as _ from django.utils.translation import ugettext_lazy # Allowed tags, attributes and styles allowed in textareas edited with a JS # editor. Everything not in these whitelists is stripped. HTML_TAG_WHITELIST = ('a', 'i', 'em', 'b', 'strong', 'ul', 'ol', 'li', 'p', 'br', 'span', 'strike', 'u', 'pre', 'h1', 'h2', 'h3',) HTML_ATTRIBUTES_WHITELIST = { 'a': ['href'], '*': ['style'], } HTML_STYLES_WHITELIST = ('color', 'background-color', 'list-style') class CssClassMixin(object): error_css_class = 'error' required_css_class = 'required' class LocalizedModelChoiceField(forms.ModelChoiceField): """ Subclass of Django's ModelChoiceField to translate the labels of the model's objects. """ def label_from_instance(self, *args, **kwargs): """ Translates the output from Django's label_from_instance method. """ return _(super(LocalizedModelChoiceField, self).label_from_instance(*args, **kwargs)) class LocalizedModelMultipleChoiceField(forms.ModelMultipleChoiceField): def __init__(self, *args, **kwargs): self.to_field_name = kwargs.get('to_field_name', None) super(LocalizedModelMultipleChoiceField, self).__init__(*args, **kwargs) def _localized_get_choices(self): if hasattr(self, '_choices'): return self._choices c = [] for (id, text) in super(LocalizedModelMultipleChoiceField, self)._get_choices(): text = text.split(' | ')[-1] c.append((id, ugettext_lazy(text))) return c choices = property(_localized_get_choices, forms.ChoiceField._set_choices) class CleanHtmlFormMixin(object): """ A form mixin that pre-processes the form, cleaning up the HTML code found in the fields in clean_html. All HTML tags, attributes and styles not in the whitelists are stripped from the output, leaving only the text content: <table><tr><td>foo</td></tr></table> simply becomes 'foo' """ clean_html_fields = () def get_clean_html_fields(self): """ The list of elements to strip of potential malicious HTML. """ return self.clean_html_fields def clean(self): cleaned_data = super(CleanHtmlFormMixin, self).clean() for field in self.get_clean_html_fields(): try: cleaned_data[field] = bleach.clean( cleaned_data[field], tags=HTML_TAG_WHITELIST, attributes=HTML_ATTRIBUTES_WHITELIST, styles=HTML_STYLES_WHITELIST, strip=True) except KeyError: # The field 'field' is not pressent. Do not change cleaned_data pass return cleaned_data class CSVImportForm(CssClassMixin, forms.Form): """ Form for the CSVImportView. """ csvfile = forms.FileField( widget=forms.FileInput(attrs={'size': '50'}), label=ugettext_lazy('CSV File'), help_text=ugettext_lazy('The file has to be encoded in UTF-8.'))
UTF-8
Python
false
false
2,014
1,297,080,168,525
74c781af7db9245ee23eb5bc6c8409b6138c2613
f25104e14aa67739a5b98c920a96c7b79fec4503
/dataset/utils.py
7bd014d4cce52a5a8a108b6a7cf8c3bc310bffc9
[]
no_license
neozhangthe1/social-influence-analysis
https://github.com/neozhangthe1/social-influence-analysis
9f56edf0ae79bfc705e540c0a3fd8d35f3c878f8
790832bfb99735a8c529c7de86a8d2de63b4ceaf
refs/heads/master
2021-01-19T12:32:44.851525
2012-12-25T15:02:42
2012-12-25T15:02:42
7,318,260
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on Dec 23, 2012 @author: Yutao '''
UTF-8
Python
false
false
2,012
6,098,853,578,022
129a7489754b2d8abaaac788b833cf59a11f0ecd
efa3e9531a21c5454198227d82892c20b2214832
/src/plivo/core/freeswitch/eventtypes.py
40b2a70b66a43c4f37246d97c9057fdfd38b8a82
[ "MPL-1.1", "LicenseRef-scancode-unknown-license-reference" ]
non_permissive
chrismatthieu/plivo
https://github.com/chrismatthieu/plivo
80dabd9affb191321f1a6df23ce2afd68123b936
23e75709301d0d3a0ee53917187ef6281598129f
refs/heads/master
2020-04-08T16:39:44.190012
2011-05-21T18:01:12
2011-05-21T18:01:12
1,781,808
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # Copyright (c) 2011 Plivo Team. See LICENSE for details. """ Event Types classes """ from urllib import unquote from urllib import quote class Event(object): '''Event class''' def __init__(self, buffer=""): self._headers = {} self._raw_body = '' self._raw_headers = '' self._u_raw_headers = '' if buffer: # Sets event headers from buffer. for line in buffer.splitlines(): try: var, val = line.rstrip().split(': ', 1) self.set_header(var, val) except ValueError: pass def __getitem__(self, key): return self.get_header(key) def __setitem__(self, key, value): self.set_header(key, value) def get_content_length(self): ''' Gets Content-Length header as integer. Returns 0 If length not found. ''' length = self.get_header('Content-Length') if length: try: return int(length) except: return 0 return 0 def get_reply_text(self): ''' Gets Reply-Text header as string. Returns None if header not found. ''' return self.get_header('Reply-Text') def is_reply_text_success(self): ''' Returns True if ReplyText header begins with +OK. Returns False otherwise. ''' reply = self.get_reply_text() return reply and reply[:3] == '+OK' def get_content_type(self): ''' Gets Content-Type header as string. Returns None if header not found. ''' return self.get_header('Content-Type') def get_headers(self): ''' Gets all headers as a python dict. ''' return self._headers def set_headers(self, headers): ''' Sets all headers from dict. ''' self._headers = headers.copy() def get_header(self, key, defaultvalue=None): ''' Gets a specific header as string. Returns None if header not found. ''' try: return self._headers[key] except KeyError: return defaultvalue def set_header(self, key, value): ''' Sets a specific header. ''' key = key.strip() value = value.strip() u_value = unquote(value) self._raw_headers += "%s: %s\n" % (key, value) self._u_raw_headers += "%s: %s\n" % (key, u_value) self._headers[key] = u_value def get_body(self): ''' Gets raw Event body. ''' return self._raw_body def set_body(self, data): ''' Sets raw Event body. ''' self._raw_body = data def get_raw_headers(self): ''' Gets raw headers (quoted). ''' return self._raw_headers def get_unquoted_raw_headers(self): ''' Gets raw headers (unquoted). ''' return self._u_raw_headers def get_raw_event(self): ''' Gets raw Event (quoted). ''' return self._raw_headers + self._raw_body + '\n' def get_unquoted_raw_event(self): ''' Gets raw Event (unquoted). ''' return self._u_raw_headers + self._raw_body + '\n' def __str__(self): return '<%s headers=%s, body=%s>' \ % (self.__class__.__name__, str(self.get_unquoted_raw_headers().replace('\n', '\\n')), str(self.get_body()).replace('\n', '\\n')) class ApiResponse(Event): def __init__(self, buffer=""): Event.__init__(self, buffer) @classmethod def cast(self, event): ''' Makes an ApiResponse instance from Event instance. ''' cls = ApiResponse(event.get_raw_headers()) cls.set_body(event.get_body()) return cls def get_response(self): ''' Gets response for api command. ''' return self.get_body().strip() def is_success(self): ''' Returns True if api command is a success. Otherwise returns False. ''' return self._raw_body and self._raw_body[:3] == '+OK' class BgapiResponse(Event): def __init__(self, buffer=""): Event.__init__(self, buffer) @classmethod def cast(self, event): ''' Makes a BgapiResponse instance from Event instance. ''' cls = BgapiResponse(event.get_raw_headers()) cls.set_body(event.get_body()) return cls def get_response(self): ''' Gets response for bgapi command. ''' return self.get_reply_text() def get_job_uuid(self): ''' Gets Job-UUID from bgapi command. ''' return self.get_header('Job-UUID') def is_success(self): ''' Returns True if bgapi command is a success. Otherwise returns False. ''' return self.is_reply_text_success() class CommandResponse(Event): def __init__(self, buffer=""): Event.__init__(self, buffer) @classmethod def cast(self, event): ''' Makes a CommandResponse instance from Event instance. ''' cls = CommandResponse(event.get_raw_headers()) cls.set_body(event.get_body()) return cls def get_response(self): ''' Gets response for a command. ''' return self.get_reply_text() def is_success(self): ''' Returns True if command is a success. Otherwise returns False. ''' return self.is_reply_text_success()
UTF-8
Python
false
false
2,011
3,822,520,904,217
5e165d13613b5b3ef3a1ea38b80ce7be49c059de
ab9251c29abe6e177ba7aa3881cf5ca98c631c85
/Decorator.py
d2a666bc7266e79e5abe83e61f0c2be232f1b73b
[]
no_license
shao362/python-design-pattern
https://github.com/shao362/python-design-pattern
e29076c1076288841ee0ab7fce172f8c5ac670fa
560d16db64fa4bd22bfa103eda56892b54859f17
refs/heads/master
2020-04-24T04:02:53.996597
2013-08-26T16:27:17
2013-08-26T16:27:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
################## design ################## Concrete class ################## use case def main(): pass if __name__ == '__main__': main()
UTF-8
Python
false
false
2,013
10,307,921,555,891
e64dd2d7183a4f14161d1afe2a3c792f778a3e15
9286f6defe88ac0da418fa6629717dce6d0751f0
/rabbitvcs/util/decorators.py
914551876b1c189c9f04d847d2232cf8bd11681f
[ "GPL-2.0-only" ]
non_permissive
kuznetz/rabbitvcs
https://github.com/kuznetz/rabbitvcs
bec92121af0d45f1f0bae802c077dcdf436476b5
e5dcaaab32e34d388d78840a646b70e9fb899b9e
refs/heads/master
2018-12-29T20:35:09.620833
2011-10-04T13:59:24
2011-10-04T13:59:24
2,511,790
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# # This is an extension to the Nautilus file manager to allow better # integration with the Subversion source control system. # # Copyright (C) 2006-2008 by Jason Field <jason@jasonfield.com> # Copyright (C) 2007-2008 by Bruce van der Kooij <brucevdkooij@gmail.com> # Copyright (C) 2008-2010 by Adam Plumb <adamplumb@gmail.com> # # RabbitVCS 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 2 of the License, or # (at your option) any later version. # # RabbitVCS 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 RabbitVCS; If not, see <http://www.gnu.org/licenses/>. # """ Simple decorators (usable in Python >= 2.4). Decorators should be named as verbs (present or paste tense). See: - https://linkchecker.svn.sourceforge.net/svnroot/linkchecker/trunk/linkchecker/linkcheck/decorators.py - http://wiki.python.org/moin/PythonDecoratorLibrary """ import time import warnings import threading from rabbitvcs.util.log import Log log = Log("rabbitvcs.util.decorators") def update_func_meta(fake_func, real_func): """ Set meta information (eg. __doc__) of fake function to that of the real function. @rtype: function @return Fake function with metadata of the real function. """ fake_func.__module__ = real_func.__module__ fake_func.__name__ = real_func.__name__ fake_func.__doc__ = real_func.__doc__ fake_func.__dict__.update(real_func.__dict__) return fake_func def deprecated(func): """ A decorator which can be used to mark functions as deprecated. It emits a warning when the function is called. @type func: function @param func: The function to be designated as deprecated. """ def newfunc(*args, **kwargs): """ Print deprecated warning and execute original function. """ warnings.warn("Call to deprecated function %s." % func.__name__, category=DeprecationWarning) return func(*args, **kwargs) return update_func_meta(newfunc, func) def timeit(func): """ This is a decorator which times a function and prints the time it took in milliseconds to stdout. Based on the timeit function from LinkChecker. @type func: function @param func: The function to be timed. """ def newfunc(*args, **kwargs): """Execute function and print execution time.""" start_time = time.time() result = func(*args, **kwargs) duration = (time.time() - start_time) * 1000.0 log.info("%s() took %0.4f milliseconds" % (func.__name__, duration)) return result return update_func_meta(newfunc, func) def disable(func): """ Disable a function. @type func: function @param func: The function to be disabled. """ def newfunc(*args, **kwargs): return return update_func_meta(newfunc, func) def gtk_unsafe(func): """ Used to wrap a function that makes calls to GTK from a thread in gtk.gdk.threads_enter() and gtk.gdk.threads_leave(). """ import gtk def newfunc(*args, **kwargs): gtk.gdk.threads_enter() result = func(*args, **kwargs) gtk.gdk.threads_leave() return result return update_func_meta(newfunc, func) def debug_calls(caller_log, show_caller=False): """ Given a log to write messages to, wrap a function and log its invocation and return. Use like: @debug_calls(my_modules_log) def actual_function(...): ... Warning: do not use with DBUS decorated methods, as this will play havoc with introspection. """ # We need a function within a function to be able to use the log argument. def real_debug(func): def newfunc(*args, **kwargs): caller_log.debug("Calling: %s (%s)" % (func.__name__, threading.currentThread().getName())) result = func(*args, **kwargs) caller_log.debug("Returned: %s (%s)" % (func.__name__, threading.currentThread().getName())) return result return update_func_meta(newfunc, func) return real_debug
UTF-8
Python
false
false
2,011
5,360,119,198,907
045952c91b2ca1209f0d19fe852f8eb1baf6ef77
495ffcd7b09d6baa610cce67aa5618d4699a03eb
/apps/shared/lib/processTrace.py
6280c134f34e9776c0ca591fd2d2f20bb0f28967
[]
no_license
3taps/geo
https://github.com/3taps/geo
42f874212fb1f85ed84e97193ea940b7bff289c1
9b8994d99ad62cf44f99d22cdcfe9666ae687726
refs/heads/master
2019-04-02T09:21:16.330617
2011-11-23T17:02:01
2011-11-23T17:02:01
2,388,730
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" processTrace.py This module traces process usage on the current computer. It produces a record of all running processes on the computer, including how much CPU and memory they are using. This is intended to be written to a file for later analysis. """ import os.path import subprocess import sys import time ############################################################################# def get_process_summary(): """ Calculate a summary of the currently running processes. We calculate and return information about each running process on this computer. For each process, we return a tuple with the following entries: * The process ID (pid). * The amount of real memory used by this process, in kilobytes. * The amount of virtual memory used by this process, in kilobytes. * The percentage of CPU time used by this process. * The number of page faults this process has had. * The number of worker threads in this process. * The command-line and arguments associated with this process. Other useful options: majflt -- number of page faults. wq -- number of workqueue threads. """ if sys.platform.startswith("linux"): cmd = "ps ax -o pid,rss,vsz,%cpu,maj_flt,nlwp,args" else: cmd = "ps -ax -o pid,rss,vsz,%cpu,pagein,wq,args" process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) lines = process.communicate()[0].split("\n")[1:] results = [] for line in lines: if len(line) == 0: continue parts = line.split() pid = int(parts[0]) realMem = int(parts[1]) virtMem = int(parts[2]) cpuPercent = float(parts[3]) try: pageFaults = int(parts[4]) except ValueError: pageFaults = 0 try: numThreads = int(parts[5]) except ValueError: numThreads = 1 cmdLine = " ".join(parts[6:]) results.append((pid, realMem, virtMem, cpuPercent, pageFaults, numThreads, cmdLine)) return results ############################################################################# def dump_process_summary(dir_name): """ Dump a copy of the process summary to the given directory. We write the process summary to a timestamped file in the given directory. """ process_summary = get_process_summary() cur_time = time.time() timestamp = time.strftime("%y%m%d-%H%M%S", time.localtime(cur_time)) fraction = cur_time - int(cur_time) sFraction = "%0.4f" % fraction sFraction = sFraction[1:] # Remove leading zero. f = open(os.path.join(dir_name, timestamp + sFraction + ".txt"), "w") f.write("pid\treal_mem\tvirt_mem\tcpu_pct\tpage_faults\tthreads\tcmd_line\n") for entry in process_summary: f.write("%d\t%d\t%d\t%0.2f\t%d\t%d\t%s\n" % (entry[0], entry[1], entry[2], entry[3], entry[4], entry[5], entry[6])) f.close() ############################################################################# if __name__ == "__main__": for entry in get_process_summary(): print entry
UTF-8
Python
false
false
2,011
11,605,001,678,371
749b422d0f45985de1cd30eb9ec674553518eea3
1a834dbac96ee9330054e30d5c60ddf48343fd43
/example/users/models.py
b491d54d5e8eba5c9814b7131f28d8540683d842
[ "Unlicense" ]
permissive
hackhands/dagny
https://github.com/hackhands/dagny
c470a3ae106a860e7e345c93cbe5863b44714c1f
309f6689d984a1c7cf941d8dcb438d4683ee90a2
refs/heads/master
2017-05-28T10:59:01.866591
2014-02-27T09:32:59
2014-02-27T09:32:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
## Empty files deserve poetry. # She dwelt among the untrodden ways # Beside the springs of Dove, # A Maid whom there were none to praise # And very few to love: # # A violet by a mossy stone # Half hidden from the eye! # Fair as a star, when only one # Is shining in the sky. # # She lived unknown, and few could know # When Lucy ceased to be; # But she is in her grave, and oh, # The difference to me! # # -- William Wordsworth
UTF-8
Python
false
false
2,014
16,947,940,993,201
8961adb9aeacb6ac97cf5cd45e694f0381deaa83
dfc06c1bf7424270a6835e09da71c6f886fbdf48
/ecommerce_free/contact/admin.py
9dd3f499a5aeecf54c9ed7e608d392e4e3213639
[ "MIT" ]
permissive
rustoceans/tryecommercefree
https://github.com/rustoceans/tryecommercefree
142de1f9501109454aa03d83d57c8a8a59e9b9fe
f63ddf9d244922e0b37137316a5e3adf5686d2ae
refs/heads/master
2023-04-08T13:42:23.210652
2014-06-27T04:07:51
2014-06-27T04:07:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.contrib import admin # Register your models here. from .models import Contact # Register your models here. class ContactAdmin(admin.ModelAdmin): class Meta: model = Contact admin.site.register(Contact, ContactAdmin)
UTF-8
Python
false
false
2,014
1,812,476,214,069
ea62b7311f4e0d37a54e5ca4d68b17677f5039ce
c9212cb6ec824861f9b97b3dddc1beac7e9f8ca7
/content/sample_generator.py
4c2df795c7d6b31a407191a1c818a02672ae1eb4
[]
no_license
MGDevelopment/front-end
https://github.com/MGDevelopment/front-end
bb96125e1e417c14602230d8fdc8d4480d856882
ea9fe57986cc802ee11567d1f487b33524810d8c
refs/heads/master
2016-09-05T14:32:01.319348
2014-03-27T13:35:07
2014-03-27T13:35:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys, getopt from ecommerce.storage import FilesystemStorage, S3Storage import jinja2 from json import dumps as js_dump import sample.sample_data import sample.sample_data_books_1 import sample.sample_data_books_1_1 import sample.sample_data_books_1_1_1 import sample.sample_data_books_1_1_1_1 import sample.sample_data_games_3 import sample.sample_data_music_4 import sample.sample_data_music_4_1 import sample.sample_data_movies_5 import sample.sample_product_book_413418 import sample.sample_product_book_465771 import sample.sample_product_music_530185 import sample.sample_product_movie_529368 # String to wrap HTML content with JS loader JS_WRAP = '''with(window.open("","_blank","width="+screen.width*.6+",left="+screen.width*.2+",height="+screen.height*.9+",resizable,scrollbars=yes")){document.write( %s );document.close();}void 0''' # # Config # # What S3 bucket is target for what host.domain storage = { 's3': { "dynamic": "beta1.testmatika.com", "static": "beta1.testmatika.com", }, 'folder': { "dynamic": "./out", "static": "./out" } } ############################################################ ############################################################ ############################################################ # # URLs # homeURL = { "cannonical" : "/", "urls" : [ "/index.html", "/index.jsp" ], "static" : "http://estatico.tematika.com", "dynamic" : "http://www.tematika.com", "search" : "http://buscador.tematika.com", "checkout" : "http://seguro.tematika.com", "service" : "http://servicios.tematika.com", "images" : "http://img-tmk.tematika.com", "data" : "http://beta1.testmatika.com.s3-website-us-east-1.amazonaws.com" } librosURL = { "cannonical" : "/libros/", "urls" : [ "/libros", "/libros/index.html", "/libros/index.jsp" ], "static" : "http://estatico.tematika.com", "dynamic" : "http://www.tematika.com", "search" : "http://buscador.tematika.com", "checkout" : "http://seguro.tematika.com", "service" : "http://servicios.tematika.com", "images" : "http://img-tmk.tematika.com", "data" : "http://beta1.testmatika.com.s3-website-us-east-1.amazonaws.com" } musicaURL = { "cannonical" : "/musica/", "urls" : [ "/musica", "/musica/index.html", "/musica/index.jsp" ], "static" : "http://estatico.tematika.com", "dynamic" : "http://www.tematika.com", "search" : "http://buscador.tematika.com", "checkout" : "http://seguro.tematika.com", "service" : "http://servicios.tematika.com", "images" : "http://img-tmk.tematika.com", "data" : "http://beta1.testmatika.com.s3-website-us-east-1.amazonaws.com" } peliculasURL = { "cannonical" : "/peliculas/", "urls" : [ "/peliculas", "/peliculas/index.html", "/peliculas/index.jsp" ], "static" : "http://estatico.tematika.com", "dynamic" : "http://www.tematika.com", "search" : "http://buscador.tematika.com", "checkout" : "http://seguro.tematika.com", "service" : "http://servicios.tematika.com", "images" : "http://img-tmk.tematika.com", "data" : "http://beta1.testmatika.com.s3-website-us-east-1.amazonaws.com" } pasatiemposURL = { "cannonical" : "/pasatiempos/", "urls" : [ "/pasatiempos", "/pasatiempos/index.html", "/pasatiempos/index.jsp" ], "static" : "http://estatico.tematika.com", "dynamic" : "http://www.tematika.com", "search" : "http://buscador.tematika.com", "checkout" : "http://seguro.tematika.com", "service" : "http://servicios.tematika.com", "images" : "http://img-tmk.tematika.com", "data" : "http://beta1.testmatika.com.s3-website-us-east-1.amazonaws.com" } ############################################################ ############################################################ ############################################################ # # DOCUMENTOS A GENERAR # documentos = [ ####################################################### # # home - html # ########## /index.html { "EntityType" : "PAGE", "EntityId" : 1, "dataset" : "homeMain", "_data" : sample.sample_data.homeMainData, "_url" : homeURL, "template" : "home/index.html", "headers" : { "Content-Type" : "text/html", "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/index.html", "target.repo" : "dynamic" }, ########## /index.html { "EntityType" : "PAGE", "EntityId" : 1, "dataset" : "homeMain", "_data" : sample.sample_data.homeMainData, "_url" : homeURL, "template" : "home/index.html", "headers" : { "Content-Type" : "text/html", "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/index.jsp", "target.repo" : "dynamic" }, # # home - vidrieras # { "EntityType" : "PAGE", "EntityId" : 1, "dataset" : "homeShowcase", "_data" : sample.sample_data.homeShowcaseData, "_url" : homeURL, "template" : "home/showcase.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/home-showcase.js", "target.repo" : "static" }, # # home - comentarios # { "EntityType" : "PAGE", "EntityId" : 1, "dataset" : "homeComments", "_data" : sample.sample_data.homeCommentsData, "_url" : homeURL, "template" : "home/comments.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/home-comments.js", "target.repo" : "static" }, ####################################################### # # libros - html # ########## /libros # { # "EntityType" : "SUBJ", # "EntityId" : 1, # "dataset" : "subjectMain", "_data" : sample.sample_data_books_1.books_1_main, # "_url" : librosURL, # "template" : "subject/index.html", # "headers" : { # "Content-Type" : "text/html", # "Content-Encoding" : "gzip", # "Cache-Control" : "max-age=3600" # }, # "target.path" : "/libros", # "target.repo" : "dynamic" # }, ########## /libros/index.html { "EntityType" : "SUBJ", "EntityId" : 1, "dataset" : "subjectMain", "_data" : sample.sample_data_books_1.books_1_main, "_url" : librosURL, "template" : "subject/index.html", "headers" : { "Content-Type" : "text/html", "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/libros/index.html", "target.repo" : "dynamic" }, ########## /catalogo/libros.js More { "EntityType" : "SUBJ", "EntityId" : 1, "dataset" : "subjectComments", "_data" : sample.sample_data_books_1.books_1_data, "_url" : librosURL, "template" : "subject/catalog.js", "headers" : { "Content-Type" : "text/javascript", "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/catalog/libros.js", "target.repo" : "static" }, # # libros - vidrieras # { "EntityType" : "SUBJ", "EntityId" : 1, "dataset" : "subjectShowcase", "_data" : sample.sample_data_books_1.books_1_data, "_url" : librosURL, "template" : "subject/showcase.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/showcase/libros.js", "target.repo" : "static" }, # # libros - comentarios # { "EntityType" : "SUBJ", "EntityId" : 1, "dataset" : "subjectComments", "_data" : sample.sample_data_books_1.books_1_comments, "_url" : librosURL, "template" : "subject/comments.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/comments/libros.js", "target.repo" : "static" }, ########## /catalogo/libros/ficcion_y_literatura--1.htm { "EntityType" : "SUBJ", "EntityId" : 1, "dataset" : "subjectMain", "_data" : sample.sample_data_books_1_1.books_1_1_main, "_url" : dict(librosURL, **{'cannonical': "/catalogo/libros/ficcion_y_literatura--1"}), "template" : "subject/index.html", "headers" : { "Content-Type" : "text/html", "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/catalogo/libros/ficcion_y_literatura--1.htm", "target.repo" : "dynamic" }, ########## /catalogo/libros/ficcion_y_literatura--1 showcase { "EntityType" : "SUBJ", "EntityId" : 1, "dataset" : "subjectShowcase", "_data" : sample.sample_data_books_1_1.books_1_1_data, "_url" : librosURL, "template" : "subject/showcase.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/showcase/catalogo/libros/ficcion_y_literatura--1.js", "target.repo" : "static" }, ########## /catalogo/libros/ficcion_y_literatura--1 comments { "EntityType" : "SUBJ", "EntityId" : 1, "dataset" : "subjectComments", "_data" : sample.sample_data_books_1_1.books_1_1_comments, "_url" : librosURL, "template" : "subject/comments.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/comments/catalogo/libros/ficcion_y_literatura--1.js", "target.repo" : "static" }, ########## /catalogo/libros/ficcion_y_literatura--1 More { "EntityType" : "SUBJ", "EntityId" : 1, "dataset" : "subjectComments", "_data" : sample.sample_data_books_1_1.books_1_1_data, "_url" : librosURL, "template" : "subject/catalog.js", "headers" : { "Content-Type" : "text/javascript", "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/catalog/catalogo/libros/ficcion_y_literatura--1.js", "target.repo" : "static" }, # # MUSICA # ########## /musica/index.html { "EntityType" : "SUBJ", "EntityId" : 1, "dataset" : "subjectMain", "_data" : sample.sample_data_music_4.music_4_main, "_url" : musicaURL, "template" : "subject/index.html", "headers" : { "Content-Type" : "text/html", "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/musica/index.html", "target.repo" : "dynamic" }, ########## /catalogo/musica.js More { "EntityType" : "SUBJ", "EntityId" : 1, "dataset" : "subjectComments", "_data" : sample.sample_data_music_4.music_4_data, "_url" : musicaURL, "template" : "subject/catalog.js", "headers" : { "Content-Type" : "text/javascript", "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/catalog/musica.js", "target.repo" : "static" }, # # musica - vidrieras # { "EntityType" : "SUBJ", "EntityId" : 1, "dataset" : "subjectShowcase", "_data" : sample.sample_data_music_4.music_4_data, "_url" : musicaURL, "template" : "subject/showcase.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/showcase/musica.js", "target.repo" : "static" }, # # musica - comentarios # { "EntityType" : "SUBJ", "EntityId" : 1, "dataset" : "subjectComments", "_data" : sample.sample_data_music_4.music_4_comments, "_url" : musicaURL, "template" : "subject/comments.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/comments/musica.js", "target.repo" : "static" }, ########## /catalogo/cds/rp_internacional--1.htm { "EntityType" : "SUBJ", "EntityId" : 1, "dataset" : "subjectMain", "_data" : sample.sample_data_music_4_1.music_4_1_main, "_url" : dict(librosURL, **{'cannonical': "/catalogo/cds/rp_internacional--1"}), "template" : "subject/index.html", "headers" : { "Content-Type" : "text/html", "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/catalogo/cds/rp_internacional--1.htm", "target.repo" : "dynamic" }, ########## /catalogo/cds/rp_internacional--1 showcase { "EntityType" : "SUBJ", "EntityId" : 1, "dataset" : "subjectShowcase", "_data" : sample.sample_data_music_4_1.music_4_1_data, "_url" : librosURL, "template" : "subject/showcase.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/showcase/catalogo/cds/rp_internacional--1.js", "target.repo" : "static" }, ########## /catalogo/cds/rp_internacional--1 comments { "EntityType" : "SUBJ", "EntityId" : 1, "dataset" : "subjectComments", "_data" : sample.sample_data_music_4_1.music_4_1_comments, "_url" : librosURL, "template" : "subject/comments.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/comments/catalogo/cds/rp_internacional--1.js", "target.repo" : "static" }, ########## /catalogo/cds/rp_internacional--1 More { "EntityType" : "SUBJ", "EntityId" : 1, "dataset" : "subjectComments", "_data" : sample.sample_data_music_4_1.music_4_1_data, "_url" : librosURL, "template" : "subject/catalog.js", "headers" : { "Content-Type" : "text/javascript", "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/catalog/catalogo/cds/rp_internacional--1.js", "target.repo" : "static" }, ########## /peliculas/index.html { "EntityType" : "SUBJ", "EntityId" : 1, "dataset" : "subjectMain", "_data" : sample.sample_data_movies_5.movies_5_main, "_url" : peliculasURL, "template" : "subject/index.html", "headers" : { "Content-Type" : "text/html", "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/peliculas/index.html", "target.repo" : "dynamic" }, { "EntityType" : "SUBJ", "EntityId" : 1, "dataset" : "subjectMain", "_data" : sample.sample_data_games_3.games_3_main, "_url" : pasatiemposURL, "template" : "subject/index.html", "headers" : { "Content-Type" : "text/html", "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/juguetes/index.html", "target.repo" : "dynamic" }, # home - exchange # { "EntityType" : "PAGE", "EntityId" : 1, "dataset" : "homeExchange", "_data" : sample.sample_data.homePriceData, "_url" : homeURL, "template" : "home/exchange.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/home-exchange.js", "target.repo" : "static" }, # # product - comentarios # { "EntityType" : "PAGE", "EntityId" : 1, "dataset" : "productComments", "_data" : sample.sample_product_book_413418.products_413418_comments, "_url" : homeURL, "template" : "product/comments.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/comments/libros/ciencias_de_la_salud__naturales_y_divulgacion_cientifica--7/divulgacion_cientifica--1/en_general--1/matematica___estas_ahi_sobre_numeros__personajes__problemas_y_curiosidades--413418.js", "target.repo" : "static" }, # # product - related # { "EntityType" : "PAGE", "EntityId" : 1, "dataset" : "productRelated", "_data" : sample.sample_product_book_413418.products_413418_related, "_url" : homeURL, "template" : "product/related.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/related/libros/ciencias_de_la_salud__naturales_y_divulgacion_cientifica--7/divulgacion_cientifica--1/en_general--1/matematica___estas_ahi_sobre_numeros__personajes__problemas_y_curiosidades--413418.js", "target.repo" : "static" }, # # product - price # { "EntityType" : "PAGE", "EntityId" : 1, "dataset" : "productPrice", "_data" : sample.sample_product_book_413418.products_413418_price, "_url" : homeURL, "template" : "product/price.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/price/libros/ciencias_de_la_salud__naturales_y_divulgacion_cientifica--7/divulgacion_cientifica--1/en_general--1/matematica___estas_ahi_sobre_numeros__personajes__problemas_y_curiosidades--413418.js", "target.repo" : "static" }, ########## /index.html { "EntityType" : "PAGE", "EntityId" : 1, "dataset" : "main", "_data" : sample.sample_product_book_413418.products_413418_main, "_url" : homeURL, "_url" : dict(librosURL, **{'cannonical': "/libros/ciencias_de_la_salud__naturales_y_divulgacion_cientifica--7/divulgacion_cientifica--1/en_general--1/matematica___estas_ahi_sobre_numeros__personajes__problemas_y_curiosidades--413418" }), "template" : "product/index.html", "headers" : { "Content-Type" : "text/html", "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/libros/ciencias_de_la_salud__naturales_y_divulgacion_cientifica--7/divulgacion_cientifica--1/en_general--1/matematica___estas_ahi_sobre_numeros__personajes__problemas_y_curiosidades--413418.htm", "target.repo" : "dynamic" }, ########## prouct page { "EntityType" : "PAGE", "EntityId" : 1, "dataset" : "main", "_data" : sample.sample_product_book_465771.products_465771_main, "_url" : homeURL, "_url" : dict(librosURL, **{'cannonical': "/libros/ficcion_y_literatura--1/novelas--1/general--1/comer__rezar__amar--465771"}), "template" : "product/index.html", "headers" : { "Content-Type" : "text/html", "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/libros/ficcion_y_literatura--1/novelas--1/general--1/comer__rezar__amar--465771.htm", "target.repo" : "dynamic" }, # # product music - comentarios # { "EntityType" : "PAGE", "EntityId" : 1, "dataset" : "productComments", "_data" : sample.sample_product_music_530185.products_530185_comments, "_url" : homeURL, "template" : "product/comments.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/comments/cds/rp_internacional--1/rp_internacional--1/true_sacd--530185.js", "target.repo" : "static" }, # # product - related # { "EntityType" : "PAGE", "EntityId" : 1, "dataset" : "productRelated", "_data" : sample.sample_product_music_530185.products_530185_related, "_url" : homeURL, "template" : "product/related.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/related/cds/rp_internacional--1/rp_internacional--1/true_sacd--530185.js", "target.repo" : "static" }, # # product - price # { "EntityType" : "PAGE", "EntityId" : 1, "dataset" : "productPrice", "_data" : sample.sample_product_music_530185.products_530185_price, "_url" : homeURL, "template" : "product/price.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/price/cds/rp_internacional--1/rp_internacional--1/true_sacd--530185.js", "target.repo" : "static" }, ########## /index.html { "EntityType" : "PAGE", "EntityId" : 1, "dataset" : "main", "_data" : sample.sample_product_music_530185.products_530185_main, "_url" : homeURL, "_url" : dict(musicaURL, **{'cannonical': "/libros/ficcion_y_literatura--1/novelas--1/general--1/comer__rezar__amar--465771"}), "template" : "product/index.html", "headers" : { "Content-Type" : "text/html", "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/cds/rp_internacional--1/rp_internacional--1/true_sacd--530185.htm", "target.repo" : "dynamic" }, # # product movies - comentarios # { "EntityType" : "PAGE", "EntityId" : 1, "dataset" : "productComments", "_data" : sample.sample_product_movie_529368.products_529368_comments, "_url" : homeURL, "template" : "product/comments.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/comments/dvds/serie_tv--15/millennium_3_la_reina_en_el_palacio_de_las_corrientes_de_aire--529368.js", "target.repo" : "static" }, # # product - related # { "EntityType" : "PAGE", "EntityId" : 1, "dataset" : "productRelated", "_data" : sample.sample_product_movie_529368.products_529368_related, "_url" : homeURL, "template" : "product/related.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/related/dvds/serie_tv--15/millennium_3_la_reina_en_el_palacio_de_las_corrientes_de_aire--529368.js", "target.repo" : "static" }, # # product - price # { "EntityType" : "PAGE", "EntityId" : 1, "dataset" : "productPrice", "_data" : sample.sample_product_movie_529368.products_529368_price, "_url" : homeURL, "template" : "product/price.js", "headers" : { "Content-Type" : "text/javascript", # requerido por IE "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/price/dvds/serie_tv--15/millennium_3_la_reina_en_el_palacio_de_las_corrientes_de_aire--529368.js", "target.repo" : "static" }, ########## /index.html { "EntityType" : "PAGE", "EntityId" : 1, "dataset" : "main", "_data" : sample.sample_product_movie_529368.products_529368_main, "_url" : homeURL, "_url" : dict(musicaURL, **{'cannonical': "/libros/ficcion_y_literatura--1/novelas--1/general--1/comer__rezar__amar--465771"}), "template" : "product/index.html", "headers" : { "Content-Type" : "text/html", "Content-Encoding" : "gzip", "Cache-Control" : "max-age=3600" }, "target.path" : "/dvds/serie_tv--15/millennium_3_la_reina_en_el_palacio_de_las_corrientes_de_aire--529368.htm", "target.repo" : "dynamic" } ] def templating(template, data, urls, targetPath): """Generates the a document Parameters: template --- the template to use (it must be loaded) data --- the data that the template requires urls --- the urls that apply to the document targetPath --- the target path of the document, it can be one of the urls in urls["urls"] """ result = "TARGET [%s]\nTEMPLATE [%s]\n" \ "DATA--------\n%s\nURLS--------\n%s\n" % \ (targetPath, template, data, urls) return result def save(document, headers, targetRepo, targetPath): """Saves a document Parameters: document --- the document contents headers --- the document headers targetRepo --- the repository name targetPath --- the target path of the document """ ########### DO SOMETHING USEFUL HERE!!! return True #print "------------------------" #print "Por generar %d documentos" % len(documentos) #for i in range(len(documentos)): # # # obtenemos los datos # entityType = documentos[i]["EntityType"] # entityId = documentos[i]["EntityId"] # data = documentos[i]["_data"] # url = documentos[i]["_url"] # template = documentos[i]["template"] # headers = documentos[i]["headers"] # targetPath = documentos[i]["target.path"] # targetRepo = documentos[i]["target.repo"] # # print "- generando para %s/%d target %s@%s" % \ # (entityType, entityId, targetRepo, targetPath), # no new line # # # generate document from template # document = templating(template, data, url, targetPath) # # # save document to file # saved = save(document, headers, targetRepo, targetPath) # print "%s" % ("OK" if saved else "ERR") class Storage_Cache(object): '''Cache of bucket objects''' def __init__(self, type='folder'): self._save = {} if type == 'folder': self._st = FilesystemStorage elif type == 's3': self._st = S3Storage else: sys.exit(2) def __call__(self, name): '''Get a bucket object from cache or create a new one''' if not self._save.has_key(name): self._save[name] = self._st(name) return self._save[name] if __name__ == '__main__': env = jinja2.Environment(loader=jinja2.FileSystemLoader('templates')) script_tag = False # No script tag by default storage_type = 'folder' # Default to folder output target = None try: opts, args = getopt.getopt(sys.argv[1:], 's:jt:', ['storage=', 'jshack', 'target=']) except getopt.GetoptError, e: print e sys.exit(2) for opt, arg in opts: if opt in ('-j', '--jshack'): script_tag = True elif opt in ('-s', '--storage'): if arg not in ('s3', 'folder'): print 'invalid storage ', arg sys.exit(2) storage_type = arg elif opt in ('-t', '--target'): target = arg else: print 'usage:\n', sys.argv[0], ' -s <s3, folder>' sys.exit(2) storage_cache = Storage_Cache(storage_type) for d in documentos: if target and d['target.path'] != target: continue # skip targets not solicited print "Generating: ", storage_type, d['target.path'], " for ", \ d['target.repo'], storage[storage_type][d['target.repo']] # Get corresponding bucket from storage connection cache s = storage_cache(storage[storage_type][d['target.repo']]) t = env.get_template(d['template']) t_params = { 'd': d['_data'], 'url': d['_url'].copy() } if script_tag: # trick HTML to load from same source as remote script t_params['url']['gen_script'] = t_params['url']['data'] page_html = t.render(t_params).encode('utf-8') target_path = d['target.path'] headers = d['headers'].copy() content_type = headers['Content-Type'] if script_tag: # No cache this trick (helps with development, no refresh) headers['Cache-Control'] = "no-cache" if content_type == 'text/html': # Convert to script tag replacing document.body target_path = target_path.replace('.html', '_html.js') target_path = target_path.replace('.htm', '_htm.js') headers['Content-Type'] = 'text/javascript' page_html = JS_WRAP % js_dump(page_html) s.send(target_path, page_html, headers) #break # XXX
UTF-8
Python
false
false
2,014
18,021,682,779,189
1903ddce12719e4f297deabd97bc84a2c4a0a4fc
ff3c423cf4d5e8374b375cfcfc1852e5bdb9f604
/cng22_tests/feature_detection/canny_test.py
300def6e56609c2f1eb63af6eded8cfd7f204b49
[ "Apache-2.0" ]
permissive
rc500/ardrone_archive_aarons_laptop
https://github.com/rc500/ardrone_archive_aarons_laptop
a46532a8e35e1b5bd5ea6c70416ab704ee8c3241
fde2336bf8dcce51741437ffbc23883f80290291
HEAD
2016-09-09T20:21:12.013804
2012-09-02T15:06:26
2012-09-02T15:06:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from PIL import Image import ImageFilter import cv import numpy as np import sys #load greyscale image img = cv.LoadImageM("bx5.jpg",cv.CV_LOAD_IMAGE_GRAYSCALE) #load colour image for displaying im = cv.LoadImageM("bx5.jpg"); edges= cv.CreateImage(cv.GetSize(img), 8, 1); cv.Canny(img,edges, 50, 200.0); #smooth resulting image of edges by a Gaussian of kernel size 25 cv.Smooth(edges, edges, cv.CV_GAUSSIAN,25) cv.NamedWindow("test1",cv.CV_WINDOW_AUTOSIZE) cv.ShowImage("test1", edges) cv.WaitKey(0)
UTF-8
Python
false
false
2,012
17,093,969,874,275
3c62c899790180e5c5593bf5d97334b39d301c54
eaa2655229355d4ffb896777bf0917453072667f
/r2/r2/lib/migrate.py
a1651695779d1e14bbc57c3426776eb5e8643473
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference", "MPL-1.1", "CPAL-1.0", "LicenseRef-scancode-proprietary-license" ]
non_permissive
sztomi/szimpatikus.hu
https://github.com/sztomi/szimpatikus.hu
3c9700b3411a8691b4cb76fdaf8b29a5a8584071
68043603df64c543eb4e8b399479f4fea920f5c3
refs/heads/master
2021-01-02T08:09:27.505980
2011-12-19T17:39:00
2011-12-19T17:39:00
1,957,036
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# The contents of this file are subject to the Common Public Attribution # License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public # License Version 1.1, but Sections 14 and 15 have been added to cover use of # software over a computer network and provide for limited attribution for the # Original Developer. In addition, Exhibit A has been modified to be consistent # with Exhibit B. # # Software distributed under the License is distributed on an "AS IS" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for # the specific language governing rights and limitations under the License. # # The Original Code is Reddit. # # The Original Developer is the Initial Developer. The Initial Developer of the # Original Code is CondeNet, Inc. # # All portions of the code written by CondeNet are Copyright (c) 2006-2010 # CondeNet, Inc. All Rights Reserved. ################################################################################ """ One-time use functions to migrate from one reddit-version to another """ from r2.lib.promote import * def add_allow_top_to_srs(): "Add the allow_top property to all stored subreddits" from r2.models import Subreddit from r2.lib.db.operators import desc from r2.lib.utils import fetch_things2 q = Subreddit._query(Subreddit.c._spam == (True,False), sort = desc('_date')) for sr in fetch_things2(q): sr.allow_top = True; sr._commit() def subscribe_to_blog_and_annoucements(filename): import re from time import sleep from r2.models import Account, Subreddit r_blog = Subreddit._by_name("blog") r_announcements = Subreddit._by_name("announcements") contents = file(filename).read() numbers = [ int(s) for s in re.findall("\d+", contents) ] # d = Account._byID(numbers, data=True) # for i, account in enumerate(d.values()): for i, account_id in enumerate(numbers): account = Account._byID(account_id, data=True) for sr in r_blog, r_announcements: if sr.add_subscriber(account): sr._incr("_ups", 1) print ("%d: subscribed %s to %s" % (i, account.name, sr.name)) else: print ("%d: didn't subscribe %s to %s" % (i, account.name, sr.name)) def upgrade_messages(update_comments = True, update_messages = True, update_trees = True): from r2.lib.db import queries from r2.lib import comment_tree, cache from r2.models import Account from pylons import g accounts = set() def batch_fn(items): g.reset_caches() return items if update_messages or update_trees: q = Message._query(Message.c.new == True, sort = desc("_date"), data = True) for m in fetch_things2(q, batch_fn = batch_fn): print m,m._date if update_messages: accounts = accounts | queries.set_unread(m, m.new) else: accounts.add(m.to_id) if update_comments: q = Comment._query(Comment.c.new == True, sort = desc("_date")) q._filter(Comment.c._id < 26152162676) for m in fetch_things2(q, batch_fn = batch_fn): print m,m._date queries.set_unread(m, True) print "Precomputing comment trees for %d accounts" % len(accounts) for i, a in enumerate(accounts): if not isinstance(a, Account): a = Account._byID(a) print i, a comment_tree.user_messages(a) def recompute_unread(min_date = None): from r2.models import Inbox, Account, Comment, Message from r2.lib.db import queries def load_accounts(inbox_rel): accounts = set() q = inbox_rel._query(eager_load = False, data = False, sort = desc("_date")) if min_date: q._filter(inbox_rel.c._date > min_date) for i in fetch_things2(q): accounts.add(i._thing1_id) return accounts accounts_m = load_accounts(Inbox.rel(Account, Message)) for i, a in enumerate(accounts_m): a = Account._byID(a) print "%s / %s : %s" % (i, len(accounts_m), a) queries.get_unread_messages(a).update() queries.get_unread_comments(a).update() queries.get_unread_selfreply(a).update() accounts = load_accounts(Inbox.rel(Account, Comment)) - accounts_m for i, a in enumerate(accounts): a = Account._byID(a) print "%s / %s : %s" % (i, len(accounts), a) queries.get_unread_comments(a).update() queries.get_unread_selfreply(a).update() def pushup_permacache(verbosity=1000): """When putting cassandra into the permacache chain, we need to push everything up into the rest of the chain, so this is everything that uses the permacache, as of that check-in.""" from pylons import g from r2.models import Link, Subreddit, Account from r2.lib.db.operators import desc from r2.lib.comment_tree import comments_key, messages_key from r2.lib.utils import fetch_things2, in_chunks from r2.lib.utils import last_modified_key from r2.lib.promote import promoted_memo_key from r2.lib.subreddit_search import load_all_reddits from r2.lib.db import queries from r2.lib.cache import CassandraCacheChain authority = g.permacache.caches[-1] nonauthority = CassandraCacheChain(g.permacache.caches[1:-1]) def populate(keys): vals = authority.simple_get_multi(keys) if vals: nonauthority.set_multi(vals) def gen_keys(): yield promoted_memo_key # just let this one do its own writing load_all_reddits() yield queries.get_all_comments().iden l_q = Link._query(Link.c._spam == (True, False), Link.c._deleted == (True, False), sort=desc('_date'), data=True, ) for link in fetch_things2(l_q, verbosity): yield comments_key(link._id) yield last_modified_key(link, 'comments') if not getattr(link, 'is_self', False) and hasattr(link, 'url'): yield Link.by_url_key(link.url) a_q = Account._query(Account.c._spam == (True, False), sort=desc('_date'), ) for account in fetch_things2(a_q, verbosity): yield messages_key(account._id) yield last_modified_key(account, 'overview') yield last_modified_key(account, 'commented') yield last_modified_key(account, 'submitted') yield last_modified_key(account, 'liked') yield last_modified_key(account, 'disliked') yield queries.get_comments(account, 'new', 'all').iden yield queries.get_submitted(account, 'new', 'all').iden yield queries.get_liked(account).iden yield queries.get_disliked(account).iden yield queries.get_hidden(account).iden yield queries.get_saved(account).iden yield queries.get_inbox_messages(account).iden yield queries.get_unread_messages(account).iden yield queries.get_inbox_comments(account).iden yield queries.get_unread_comments(account).iden yield queries.get_inbox_selfreply(account).iden yield queries.get_unread_selfreply(account).iden yield queries.get_sent(account).iden sr_q = Subreddit._query(Subreddit.c._spam == (True, False), sort=desc('_date'), ) for sr in fetch_things2(sr_q, verbosity): yield last_modified_key(sr, 'stylesheet_contents') yield queries.get_links(sr, 'hot', 'all').iden yield queries.get_links(sr, 'new', 'all').iden for sort in 'top', 'controversial': for time in 'hour', 'day', 'week', 'month', 'year', 'all': yield queries.get_links(sr, sort, time, merge_batched=False).iden yield queries.get_spam_links(sr).iden yield queries.get_spam_comments(sr).iden yield queries.get_reported_links(sr).iden yield queries.get_reported_comments(sr).iden yield queries.get_subreddit_messages(sr).iden yield queries.get_unread_subreddit_messages(sr).iden done = 0 for keys in in_chunks(gen_keys(), verbosity): g.reset_caches() done += len(keys) print 'Done %d: %r' % (done, keys[-1]) populate(keys) def add_byurl_prefix(): """Run one before the byurl prefix is set, and once after (killing it after it gets when it started the first time""" from datetime import datetime from r2.models import Link from r2.lib.filters import _force_utf8 from pylons import g from r2.lib.utils import fetch_things2 from r2.lib.db.operators import desc from r2.lib.utils import base_url now = datetime.now(g.tz) print 'started at %s' % (now,) l_q = Link._query( Link.c._date < now, data=True, sort=desc('_date')) # from link.py def by_url_key(url, prefix=''): s = _force_utf8(base_url(url.lower())) return '%s%s' % (prefix, s) done = 0 for links in fetch_things2(l_q, 1000, chunks=True): done += len(links) print 'Doing: %r, %s..%s' % (done, links[-1]._date, links[0]._date) # only links with actual URLs links = filter(lambda link: (not getattr(link, 'is_self', False) and getattr(link, 'url', '')), links) # old key -> new key translate = dict((by_url_key(link.url), by_url_key(link.url, prefix='byurl_')) for link in links) old = g.permacache.get_multi(translate.keys()) new = dict((translate[old_key], value) for (old_key, value) in old.iteritems()) g.permacache.set_multi(new) # alter table bids DROP constraint bids_pkey; # alter table bids add column campaign integer; # update bids set campaign = 0; # alter table bids ADD primary key (transaction, campaign); def promote_v2(): # alter table bids add column campaign integer; # update bids set campaign = 0; from r2.models import Link, NotFound, PromoteDates, Bid from datetime import datetime from pylons import g for p in PromoteDates.query(): try: l = Link._by_fullname(p.thing_name, data = True, return_dict = False) if not l: raise NotFound, p.thing_name # update the promote status l.promoted = True l.promote_status = getattr(l, "promote_status", STATUS.unseen) l._date = datetime(*(list(p.start_date.timetuple()[:7]) + [g.tz])) set_status(l, l.promote_status) # add new campaign print (l, (p.start_date, p.end_date), p.bid, None) if not p.bid: print "no bid? ", l p.bid = 20 new_campaign(l, (p.start_date, p.end_date), p.bid, None) print "updated: %s (%s)" % (l, l._date) except NotFound: print "NotFound: %s" % p.thing_name print "updating campaigns" for b in Bid.query(): l = Link._byID(int(b.thing_id)) print "updating: ", l campaigns = getattr(l, "campaigns", {}).copy() indx = b.campaign if indx in campaigns: sd, ed, bid, sr, trans_id = campaigns[indx] campaigns[indx] = sd, ed, bid, sr, b.transaction l.campaigns = campaigns l._commit() else: print "no campaign information: ", l def shorten_byurl_keys(): """We changed by_url keys from a format like byurl_google.com... to: byurl(1d5920f4b44b27a802bd77c4f0536f5a, google.com...) so that they would fit in memcache's 251-char limit """ from datetime import datetime from hashlib import md5 from r2.models import Link from r2.lib.filters import _force_utf8 from pylons import g from r2.lib.utils import fetch_things2, in_chunks from r2.lib.db.operators import desc from r2.lib.utils import base_url, progress # from link.py def old_by_url_key(url): prefix='byurl_' s = _force_utf8(base_url(url.lower())) return '%s%s' % (prefix, s) def new_by_url_key(url): maxlen = 250 template = 'byurl(%s,%s)' keyurl = _force_utf8(base_url(url.lower())) hexdigest = md5(keyurl).hexdigest() usable_len = maxlen-len(template)-len(hexdigest) return template % (hexdigest, keyurl[:usable_len]) verbosity = 1000 l_q = Link._query( Link.c._spam == (True, False), data=True, sort=desc('_date')) for links in ( in_chunks( progress( fetch_things2(l_q, verbosity), key = lambda link: link._date, verbosity=verbosity, estimate=int(9.9e6), persec=True, ), verbosity)): # only links with actual URLs links = filter(lambda link: (not getattr(link, 'is_self', False) and getattr(link, 'url', '')), links) # old key -> new key translate = dict((old_by_url_key(link.url), new_by_url_key(link.url)) for link in links) old = g.permacache.get_multi(translate.keys()) new = dict((translate[old_key], value) for (old_key, value) in old.iteritems()) g.permacache.set_multi(new) def prime_url_cache(f, verbosity = 10000): import gzip, time from pylons import g handle = gzip.open(f, 'rb') counter = 0 start_time = time.time() for line in handle: try: tid, key, url, kind = line.split('|') tid = int(tid) if url.lower() != "self": key = Link.by_url_key(url) link_ids = g.urlcache.get(key) or [] if tid not in link_ids: link_ids.append(tid) g.urlcache.set(key, link_ids) except ValueError: print "FAIL: %s" % line counter += 1 if counter % verbosity == 0: print "%6d: %s" % (counter, line) print "--> doing %5.2f / s" % (float(counter) / (time.time() - start_time))
UTF-8
Python
false
false
2,011
17,832,704,222,631
c0ed8b3620bfb78d9aab2232efae5d2139e0fdda
f0b7c291b9dc9fdb59123dcb5e7d1f13527aa60d
/salt/modules/ebuild.py
6d9788bff1c70808f76907bf3805e03654d88fcf
[ "Apache-2.0" ]
permissive
zidadi/salt
https://github.com/zidadi/salt
93d6ee5f2f8cc3979dc7a7ac8762fa76e33f489a
fcfa0b96226ba8b8d2bbd62365c2cab3f6e42d99
HEAD
2019-04-13T02:53:32.728489
2012-11-19T07:11:19
2012-11-19T07:11:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Support for Portage :optdepends: - portage Python adapter ''' try: import portage except ImportError: pass def __virtual__(): ''' Confirm this module is on a Gentoo based system ''' return 'pkg' if __grains__['os'] == 'Gentoo' else False def _vartree(): return portage.db[portage.root]['vartree'] def _porttree(): return portage.db[portage.root]['porttree'] def _cpv_to_name(cpv): if cpv == '': return '' return str(portage.cpv_getkey(cpv)) def _cpv_to_version(cpv): if cpv == '': return '' return str(cpv[len(_cpv_to_name(cpv)+'-'):]) def available_version(name): ''' The available version of the package in the repository CLI Example:: salt '*' pkg.available_version <package name> ''' return _cpv_to_version(_porttree().dep_bestmatch(name)) def version(name): ''' Returns a version if the package is installed, else returns an empty string CLI Example:: salt '*' pkg.version <package name> ''' return _cpv_to_version(_vartree().dep_bestmatch(name)) def list_pkgs(): ''' List the packages currently installed in a dict:: {'<package_name>': '<version>'} CLI Example:: salt '*' pkg.list_pkgs ''' ret = {} pkgs = _vartree().dbapi.cpv_all() for cpv in pkgs: ret[_cpv_to_name(cpv)] = _cpv_to_version(cpv) return ret def refresh_db(): ''' Updates the portage tree (emerge --sync) CLI Example:: salt '*' pkg.refresh_db ''' return __salt__['cmd.retcode']('emerge --sync --quiet') == 0 def install(pkg, refresh=False, **kwargs): ''' Install the passed package Return a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>']} CLI Example:: salt '*' pkg.install <package name> ''' if(refresh): refresh_db() ret_pkgs = {} old_pkgs = list_pkgs() cmd = 'emerge --quiet {0}'.format(pkg) __salt__['cmd.retcode'](cmd) new_pkgs = list_pkgs() for pkg in new_pkgs: if pkg in old_pkgs: if old_pkgs[pkg] == new_pkgs[pkg]: continue else: ret_pkgs[pkg] = {'old': old_pkgs[pkg], 'new': new_pkgs[pkg]} else: ret_pkgs[pkg] = {'old': '', 'new': new_pkgs[pkg]} return ret_pkgs def update(pkg, refresh=False): ''' Updates the passed package (emerge --update package) Return a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>']} CLI Example:: salt '*' pkg.update <package name> ''' if(refresh): refresh_db() ret_pkgs = {} old_pkgs = list_pkgs() cmd = 'emerge --update --quiet {0}'.format(pkg) __salt__['cmd.retcode'](cmd) new_pkgs = list_pkgs() for pkg in new_pkgs: if pkg in old_pkgs: if old_pkgs[pkg] == new_pkgs[pkg]: continue else: ret_pkgs[pkg] = {'old': old_pkgs[pkg], 'new': new_pkgs[pkg]} else: ret_pkgs[pkg] = {'old': '', 'new': new_pkgs[pkg]} return ret_pkgs def upgrade(refresh=False): ''' Run a full system upgrade (emerge --update world) Return a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>']} CLI Example:: salt '*' pkg.upgrade ''' if(refresh): refresh_db() ret_pkgs = {} old_pkgs = list_pkgs() __salt__['cmd.retcode']('emerge --update --quiet world') new_pkgs = list_pkgs() for pkg in new_pkgs: if pkg in old_pkgs: if old_pkgs[pkg] == new_pkgs[pkg]: continue else: ret_pkgs[pkg] = {'old': old_pkgs[pkg], 'new': new_pkgs[pkg]} else: ret_pkgs[pkg] = {'old': '', 'new': new_pkgs[pkg]} return ret_pkgs def remove(pkg): ''' Remove a single package via emerge --unmerge Return a list containing the names of the removed packages: CLI Example:: salt '*' pkg.remove <package name> ''' ret_pkgs = [] old_pkgs = list_pkgs() cmd = 'emerge --unmerge --quiet --quiet-unmerge-warn {0}'.format(pkg) __salt__['cmd.retcode'](cmd) new_pkgs = list_pkgs() for pkg in old_pkgs: if not pkg in new_pkgs: ret_pkgs.append(pkg) return ret_pkgs def purge(pkg): ''' Portage does not have a purge, this function calls remove Return a list containing the removed packages: CLI Example:: salt '*' pkg.purge <package name> ''' return remove(pkg)
UTF-8
Python
false
false
2,012