repo_name
stringlengths
5
92
path
stringlengths
4
221
copies
stringclasses
19 values
size
stringlengths
4
6
content
stringlengths
766
896k
license
stringclasses
15 values
hash
int64
-9,223,277,421,539,062,000
9,223,102,107B
line_mean
float64
6.51
99.9
line_max
int64
32
997
alpha_frac
float64
0.25
0.96
autogenerated
bool
1 class
ratio
float64
1.5
13.6
config_test
bool
2 classes
has_no_keywords
bool
2 classes
few_assignments
bool
1 class
dials/dials
tests/algorithms/indexing/test_non_primitive_basis.py
1
1945
import pytest import scitbx.matrix from cctbx import sgtbx from cctbx.sgtbx import bravais_types from dxtbx.model import Crystal, Experiment, ExperimentList from dials.algorithms.indexing import assign_indices, non_primitive_basis from dials.array_family import flex @pytest.mark.parametrize("space_group_symbol", bravais_types.acentric) def test_detect(space_group_symbol): sgi = sgtbx.space_group_info(space_group_symbol) cs = sgi.any_compatible_crystal_symmetry(volume=1000) ms = cs.build_miller_set(anomalous_flag=True, d_min=1).expand_to_p1() result = non_primitive_basis.detect(ms.indices()) if sgi.group().conventional_centring_type_symbol() != "P": assert result is not None assert isinstance(result, scitbx.matrix.sqr) assert result.n == (3, 3) else: assert result is None @pytest.mark.parametrize("space_group_symbol", bravais_types.acentric) def test_correct(space_group_symbol): sgi = sgtbx.space_group_info(space_group_symbol) cs = sgi.any_compatible_crystal_symmetry(volume=1000) ms = cs.build_miller_set(anomalous_flag=True, d_min=1).expand_to_p1() # the reciprocal matrix B = scitbx.matrix.sqr(cs.unit_cell().fractionalization_matrix()).transpose() crystal = Crystal(B, sgtbx.space_group()) expts = ExperimentList([Experiment(crystal=crystal)]) refl = flex.reflection_table() refl["miller_index"] = ms.indices() refl["rlp"] = B.elems * ms.indices().as_vec3_double() refl["imageset_id"] = flex.int(len(refl)) refl["xyzobs.mm.value"] = flex.vec3_double(len(refl)) non_primitive_basis.correct(expts, refl, assign_indices.AssignIndicesGlobal()) cs_corrected = expts.crystals()[0].get_crystal_symmetry() assert cs_corrected.change_of_basis_op_to_primitive_setting().is_identity_op() assert ( cs.change_of_basis_op_to_primitive_setting().apply(ms.indices()) == refl["miller_index"] )
bsd-3-clause
7,598,806,288,202,229,000
37.137255
82
0.705398
false
3.020186
false
false
false
usc-isi/horizon-old
horizon/horizon/dashboards/settings/user/urls.py
1
1066
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2011 Nebula, 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. from django.conf.urls.defaults import patterns, url from django.views.generic import TemplateView urlpatterns = patterns('', url(r'^$', TemplateView.as_view( template_name='settings/user/settings.html'), name='index'))
apache-2.0
-3,605,575,973,021,152,000
37.071429
78
0.722326
false
4.084291
false
false
false
codelucas/facebook-context
backend-flask/backend/example.py
1
15518
#!/usr/bin/env python # Copyright 2013 AlchemyAPI # # 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. from __future__ import print_function from alchemyapi import AlchemyAPI import json demo_text = 'Yesterday dumb Bob destroyed my fancy iPhone in beautiful Denver, Colorado. I guess I will have to head over to the Apple Store and buy a new one.' demo_url = 'http://www.npr.org/2013/11/26/247336038/dont-stuff-the-turkey-and-other-tips-from-americas-test-kitchen' demo_html = '<html><head><title>Python Demo | AlchemyAPI</title></head><body><h1>Did you know that AlchemyAPI works on HTML?</h1><p>Well, you do now.</p></body></html>' print('') print('') print(' , ') print(' .I7777~ ') print(' .I7777777 ') print(' +. 77777777 ') print(' =???, I7777777= ') print('=?????? 7777777? ,:::===? ') print('=???????. 777777777777777777~ .77: ?? :7 =$, :$$$$$$+ =$? ') print(' ????????: .777777777777777777 II77 ?? :7 $$7 :$? 7$7 =$? ') print(' .???????= +7777777777777777 .7 =7: ?? :7777+ :7:I777? ?777I= 77~777? ,777I I7 77 +$?$: :$? $$ =$? ') print(' ???????+ ~777???+===::: :7+ ~7 ?? .77 +7 :7?. II 7~ ,I7 77+ I77 ~7 ?7 =7: .$, =$ :$? ,$$? =$? ') print(' ,???????~ 77 7: ?? ?I. 7 :7 :7 ~7 7 77 =7: 7 7 7~ 7$ $= :$$$$$$~ =$? ') print(' .??????? ,???I77777777777~ :77777777~ ?? 7: :7 :7 777777777:77 =7 7 +7 ~7 $$$$$$$$I :$? =$? ') print(' .??????? ,7777777777777777 7= 77 ?? I+ 7 :7 :7 ?? 7,77 =7 7 7~ 7, =$7 $$, :$? =$? ') print(' .???????. I77777777777777777 +7 ,7??? 77 I7 :7 :7 7~ .?7 77 =7 7 ,77I $+ 7$ :$? =$? ') print(' ,???????= :77777777777777777~ 7= ~7?? ~I77777 :7 :7 ,777777. 77 =7 7 77, +$ .$::$? =$? ') print(',??????? :7777777 77 ') print(' =????? ,7777777 77= ') print(' +?+ 7777777? ') print(' + ~7777777 ') print(' I777777 ') print(' :~ ') #Create the AlchemyAPI Object alchemyapi = AlchemyAPI() print('') print('') print('############################################') print('# Entity Extraction Example #') print('############################################') print('') print('') print('Processing text: ', demo_text) print('') response = alchemyapi.entities('text',demo_text, { 'sentiment':1 }) if response['status'] == 'OK': print('## Response Object ##') print(json.dumps(response, indent=4)) print('') print('## Entities ##') for entity in response['entities']: print('text: ', entity['text'].encode('utf-8')) print('type: ', entity['type']) print('relevance: ', entity['relevance']) print('sentiment: ', entity['sentiment']['type']) if 'score' in entity['sentiment']: print('sentiment score: ' + entity['sentiment']['score']) print('') else: print('Error in entity extraction call: ', response['statusInfo']) print('') print('') print('') print('############################################') print('# Keyword Extraction Example #') print('############################################') print('') print('') print('Processing text: ', demo_text) print('') response = alchemyapi.keywords('text',demo_text, { 'sentiment':1 }) if response['status'] == 'OK': print('## Response Object ##') print(json.dumps(response, indent=4)) print('') print('## Keywords ##') for keyword in response['keywords']: print('text: ', keyword['text'].encode('utf-8')) print('relevance: ', keyword['relevance']) print('sentiment: ', keyword['sentiment']['type']) if 'score' in keyword['sentiment']: print('sentiment score: ' + keyword['sentiment']['score']) print('') else: print('Error in keyword extaction call: ', response['statusInfo']) print('') print('') print('') print('############################################') print('# Concept Tagging Example #') print('############################################') print('') print('') print('Processing text: ', demo_text) print('') response = alchemyapi.concepts('text',demo_text) if response['status'] == 'OK': print('## Object ##') print(json.dumps(response, indent=4)) print('') print('## Concepts ##') for concept in response['concepts']: print('text: ', concept['text']) print('relevance: ', concept['relevance']) print('') else: print('Error in concept tagging call: ', response['statusInfo']) print('') print('') print('') print('############################################') print('# Sentiment Analysis Example #') print('############################################') print('') print('') print('Processing html: ', demo_html) print('') response = alchemyapi.sentiment('html',demo_html) if response['status'] == 'OK': print('## Response Object ##') print(json.dumps(response, indent=4)) print('') print('## Document Sentiment ##') print('type: ', response['docSentiment']['type']) if 'score' in response['docSentiment']: print('score: ', response['docSentiment']['score']) else: print('Error in sentiment analysis call: ', response['statusInfo']) print('') print('') print('') print('############################################') print('# Targeted Sentiment Analysis Example #') print('############################################') print('') print('') print('Processing text: ', demo_text) print('') response = alchemyapi.sentiment_targeted('text',demo_text, 'Denver') if response['status'] == 'OK': print('## Response Object ##') print(json.dumps(response, indent=4)) print('') print('## Targeted Sentiment ##') print('type: ', response['docSentiment']['type']) if 'score' in response['docSentiment']: print('score: ', response['docSentiment']['score']) else: print('Error in targeted sentiment analysis call: ', response['statusInfo']) print('') print('') print('') print('############################################') print('# Text Extraction Example #') print('############################################') print('') print('') print('Processing url: ', demo_url) print('') response = alchemyapi.text('url',demo_url) if response['status'] == 'OK': print('## Response Object ##') print(json.dumps(response, indent=4)) print('') print('## Text ##') print('text: ', response['text'].encode('utf-8')) print('') else: print('Error in text extraction call: ', response['statusInfo']) print('') print('') print('') print('############################################') print('# Author Extraction Example #') print('############################################') print('') print('') print('Processing url: ', demo_url) print('') response = alchemyapi.author('url',demo_url) if response['status'] == 'OK': print('## Response Object ##') print(json.dumps(response, indent=4)) print('') print('## Author ##') print('author: ', response['author'].encode('utf-8')) print('') else: print('Error in author extraction call: ', response['statusInfo']) print('') print('') print('') print('############################################') print('# Language Detection Example #') print('############################################') print('') print('') print('Processing text: ', demo_text) print('') response = alchemyapi.language('text',demo_text) if response['status'] == 'OK': print('## Response Object ##') print(json.dumps(response, indent=4)) print('') print('## Language ##') print('language: ', response['language']) print('iso-639-1: ', response['iso-639-1']) print('native speakers: ', response['native-speakers']) print('') else: print('Error in language detection call: ', response['statusInfo']) print('') print('') print('') print('############################################') print('# Title Extraction Example #') print('############################################') print('') print('') print('Processing url: ', demo_url) print('') response = alchemyapi.title('url',demo_url) if response['status'] == 'OK': print('## Response Object ##') print(json.dumps(response, indent=4)) print('') print('## Title ##') print('title: ', response['title'].encode('utf-8')) print('') else: print('Error in title extraction call: ', response['statusInfo']) print('') print('') print('') print('############################################') print('# Relation Extraction Example #') print('############################################') print('') print('') print('Processing text: ', demo_text) print('') response = alchemyapi.relations('text',demo_text) if response['status'] == 'OK': print('## Object ##') print(json.dumps(response, indent=4)) print('') print('## Relations ##') for relation in response['relations']: if 'subject' in relation: print('Subject: ', relation['subject']['text'].encode('utf-8')) if 'action' in relation: print('Action: ', relation['action']['text'].encode('utf-8')) if 'object' in relation: print('Object: ', relation['object']['text'].encode('utf-8')) print('') else: print('Error in relation extaction call: ', response['statusInfo']) print('') print('') print('') print('############################################') print('# Text Categorization Example #') print('############################################') print('') print('') print('Processing text: ', demo_text) print('') response = alchemyapi.category('text',demo_text) if response['status'] == 'OK': print('## Response Object ##') print(json.dumps(response, indent=4)) print('') print('## Category ##') print('text: ', response['category']) print('score: ', response['score']) print('') else: print('Error in text categorization call: ', response['statusInfo']) print('') print('') print('') print('############################################') print('# Feed Detection Example #') print('############################################') print('') print('') print('Processing url: ', demo_url) print('') response = alchemyapi.feeds('url',demo_url) if response['status'] == 'OK': print('## Response Object ##') print(json.dumps(response, indent=4)) print('') print('## Feeds ##') for feed in response['feeds']: print('feed: ', feed['feed']) else: print('Error in feed detection call: ', response['statusInfo']) print('') print('') print('') print('') print('') print('############################################') print('# Microformats Parsing Example #') print('############################################') print('') print('') print('Processing url: ', demo_url) print('') response = alchemyapi.microformats('url',demo_url) if response['status'] == 'OK': print('## Response Object ##') print(json.dumps(response, indent=4)) print('') print('## Microformats ##') for microformat in response['microformats']: print('Field: ', microformat['field'].encode('utf-8')) print('Data: ', microformat['data']) print('') else: print('Error in microformats parsing call: ', response['statusInfo']) print('') print('') print('') print('') print('') print('############################################') print('# Image Extraction Example #') print('############################################') print('') print('') print('Processing url: ', demo_url) print('') response = alchemyapi.imageExtraction('url',demo_url) if response['status'] == 'OK': print('## Response Object ##') print(json.dumps(response, indent=4)) print('') print('## Image ##') print('Image: ', response['image']) print('') else: print('Error in image extraction call: ', response['statusInfo']) print('') print('') print('') print('') print('') print('############################################') print('# Taxonomy Example #') print('############################################') print('') print('') print('Processing text: ', demo_text) print('') response = alchemyapi.taxonomy('text',demo_text) if response['status'] == 'OK': print('## Response Object ##') print(json.dumps(response, indent=4)) print('') print('## Categories ##') for category in response['taxonomy']: print(category['label'], ' : ', category['score']) print('') else: print('Error in taxonomy call: ', response['statusInfo']) print('') print('') print('') print('') print('') print('############################################') print('# Combined Example #') print('############################################') print('') print('') print('Processing text: ', demo_text) print('') response = alchemyapi.combined('text',demo_text) if response['status'] == 'OK': print('## Response Object ##') print(json.dumps(response, indent=4)) print('') print('## Keywords ##') for keyword in response['keywords']: print(keyword['text'], ' : ', keyword['relevance']) print('') print('## Concepts ##') for concept in response['concepts']: print(concept['text'], ' : ', concept['relevance']) print('') print('## Entities ##') for entity in response['entities']: print(entity['type'], ' : ', entity['text'], ', ', entity['relevance']) print(' ') else: print('Error in combined call: ', response['statusInfo']) print('') print('')
apache-2.0
-368,163,000,386,899,300
27.163339
168
0.47345
false
3.758295
false
false
false
oblique-labs/pyVM
rpython/rlib/unicodedata/test/test_unicodedata.py
1
6594
# encoding: utf-8 import random import unicodedata import py from rpython.rlib.unicodedata import ( unicodedb_3_2_0, unicodedb_5_2_0, unicodedb_6_0_0, unicodedb_6_2_0, unicodedb_8_0_0) class TestUnicodeData(object): def setup_class(cls): if unicodedata.unidata_version != '5.2.0': py.test.skip('Needs python with unicode 5.2.0 database.') seed = random.getrandbits(32) print "random seed: ", seed random.seed(seed) cls.charlist = charlist = [] cls.nocharlist = nocharlist = [] while len(charlist) < 1000 or len(nocharlist) < 1000: chr = unichr(random.randrange(65536)) try: charlist.append((chr, unicodedata.name(chr))) except ValueError: nocharlist.append(chr) def test_random_charnames(self): for chr, name in self.charlist: assert unicodedb_5_2_0.name(ord(chr)) == name assert unicodedb_5_2_0.lookup(name) == ord(chr) def test_random_missing_chars(self): for chr in self.nocharlist: py.test.raises(KeyError, unicodedb_5_2_0.name, ord(chr)) def test_isprintable(self): assert unicodedb_5_2_0.isprintable(ord(' ')) assert unicodedb_5_2_0.isprintable(ord('a')) assert not unicodedb_5_2_0.isprintable(127) assert unicodedb_5_2_0.isprintable(0x00010346) # GOTHIC LETTER FAIHU assert unicodedb_5_2_0.isprintable(0xfffd) # REPLACEMENT CHARACTER assert unicodedb_5_2_0.isprintable(0xfffd) # REPLACEMENT CHARACTER assert not unicodedb_5_2_0.isprintable(0xd800) # SURROGATE assert not unicodedb_5_2_0.isprintable(0xE0020) # TAG SPACE def test_identifier(self): assert unicodedb_5_2_0.isxidstart(ord('A')) assert not unicodedb_5_2_0.isxidstart(ord('_')) assert not unicodedb_5_2_0.isxidstart(ord('0')) assert not unicodedb_5_2_0.isxidstart(ord('(')) assert unicodedb_5_2_0.isxidcontinue(ord('A')) assert unicodedb_5_2_0.isxidcontinue(ord('_')) assert unicodedb_5_2_0.isxidcontinue(ord('0')) assert not unicodedb_5_2_0.isxidcontinue(ord('(')) oc = ord(u'日') assert unicodedb_5_2_0.isxidstart(oc) def test_compare_functions(self): def getX(fun, code): try: return getattr(unicodedb_5_2_0, fun)(code) except KeyError: return -1 for code in range(0x10000): char = unichr(code) assert unicodedata.digit(char, -1) == getX('digit', code) assert unicodedata.numeric(char, -1) == getX('numeric', code) assert unicodedata.decimal(char, -1) == getX('decimal', code) assert unicodedata.category(char) == unicodedb_5_2_0.category(code) assert unicodedata.bidirectional(char) == unicodedb_5_2_0.bidirectional(code) assert unicodedata.decomposition(char) == unicodedb_5_2_0.decomposition(code) assert unicodedata.mirrored(char) == unicodedb_5_2_0.mirrored(code) assert unicodedata.combining(char) == unicodedb_5_2_0.combining(code) def test_compare_methods(self): for code in range(0x10000): char = unichr(code) assert char.isalnum() == unicodedb_5_2_0.isalnum(code) assert char.isalpha() == unicodedb_5_2_0.isalpha(code) assert char.isdecimal() == unicodedb_5_2_0.isdecimal(code) assert char.isdigit() == unicodedb_5_2_0.isdigit(code) assert char.islower() == unicodedb_5_2_0.islower(code) assert char.isnumeric() == unicodedb_5_2_0.isnumeric(code) assert char.isspace() == unicodedb_5_2_0.isspace(code), hex(code) assert char.istitle() == (unicodedb_5_2_0.isupper(code) or unicodedb_5_2_0.istitle(code)), code assert char.isupper() == unicodedb_5_2_0.isupper(code) assert char.lower() == unichr(unicodedb_5_2_0.tolower(code)) assert char.upper() == unichr(unicodedb_5_2_0.toupper(code)) assert char.title() == unichr(unicodedb_5_2_0.totitle(code)), hex(code) def test_hangul_difference_520(self): assert unicodedb_5_2_0.name(40874) == 'CJK UNIFIED IDEOGRAPH-9FAA' def test_differences(self): assert unicodedb_5_2_0.name(9187) == 'BENZENE RING WITH CIRCLE' assert unicodedb_5_2_0.lookup('BENZENE RING WITH CIRCLE') == 9187 py.test.raises(KeyError, unicodedb_3_2_0.lookup, 'BENZENE RING WITH CIRCLE') py.test.raises(KeyError, unicodedb_3_2_0.name, 9187) def test_casefolding(self): assert unicodedb_6_2_0.casefold_lookup(223) == [115, 115] assert unicodedb_6_2_0.casefold_lookup(976) == [946] assert unicodedb_5_2_0.casefold_lookup(42592) == None # 1010 has been remove between 3.2.0 and 5.2.0 assert unicodedb_3_2_0.casefold_lookup(1010) == [963] assert unicodedb_5_2_0.casefold_lookup(1010) == None # 7838 has been added in 5.2.0 assert unicodedb_3_2_0.casefold_lookup(7838) == None assert unicodedb_5_2_0.casefold_lookup(7838) == [115, 115] # Only lookup who cannot be resolved by `lower` are stored in database assert unicodedb_3_2_0.casefold_lookup(ord('E')) == None class TestUnicodeData600(object): def test_some_additions(self): additions = { ord(u"\u20B9"): 'INDIAN RUPEE SIGN', # u'\U0001F37A' 127866: 'BEER MUG', # u'\U0001F37B' 127867: 'CLINKING BEER MUGS', # u"\U0001F0AD" 127149: 'PLAYING CARD QUEEN OF SPADES', # u"\U0002B740" 177984: "CJK UNIFIED IDEOGRAPH-2B740", } for un, name in additions.iteritems(): assert unicodedb_6_0_0.name(un) == name assert unicodedb_6_0_0.isprintable(un) def test_special_casing(self): assert unicodedb_6_0_0.tolower_full(ord('A')) == [ord('a')] # The German es-zed is special--the normal mapping is to SS. assert unicodedb_6_0_0.tolower_full(ord(u'\xdf')) == [0xdf] assert unicodedb_6_0_0.toupper_full(ord(u'\xdf')) == map(ord, 'SS') assert unicodedb_6_0_0.totitle_full(ord(u'\xdf')) == map(ord, 'Ss') def test_islower(self): assert unicodedb_6_2_0.islower(0x2177) class TestUnicodeData800(object): def test_changed_in_version_8(self): assert unicodedb_6_2_0.toupper_full(0x025C) == [0x025C] assert unicodedb_8_0_0.toupper_full(0x025C) == [0xA7AB]
mit
-4,423,305,646,221,714,000
42.946667
107
0.614381
false
3.130104
true
false
false
dereneaton/ipyrad
ipyrad/core/paramsinfo.py
1
21970
#!/usr/bin/env python """ Return explanation and options for each parameter. ip.get_params_info(1) or ip.get_params_info("project_dir") return the same result. If not argument, a summary of the available parameters and their numbered references is returned. Parameter info is stored as a dict of tuples. Each tuple consists of a short and a long desription for each parameter. By default if you as for a parameter you'll get the long description """ from __future__ import print_function from collections import OrderedDict pinfo = OrderedDict([ ("0", (""" (0) assembly_name ---------------------------------------------------- This is the name of your assembly. It will be the prefix for all directories inside the project directory. An easy default for this parameter is the name of your project directory. For example if your project directory is ./white-crowns, then your assembly name could be white-crowns. Assembly name is variable because you might want to fork assemblies within a project to try different runs with different minimum coverage values, different levels of indels allowed, etc. Examples: ---------------------------------------------------------------------- data.set_params('assembly_name', "white-crowns") ## verbose ---------------------------------------------------------------------- """, "Assembly name. Used to name output directories for assembly steps") ), ("1", (""" (1) project_dir ------------------------------------------------------ Project name / path for working directory where all data files will be saved. This parameter affects all steps of assembly (1-7). Examples: ---------------------------------------------------------------------- data.set_params('project_dir', "./") ## verbose ---------------------------------------------------------------------- """, "Project dir (made in curdir if not present)") ), ("2", (""" (2) raw_fastq_path --------------------------------------------------- The directory or files (selected with * wildcard selector) in which FASTQ data files reside. Files can be gzipped. This parameter affects only step 1 of assembly. Examples: ---------------------------------------------------------------------- data.set_params("raw_fastq_path", "raw/*.fastq.gz") ## verbose ---------------------------------------------------------------------- """, "Location of raw non-demultiplexed fastq files") ), ("3", (""" (3) barcodes_path ---------------------------------------------------- Path to the barcodes file used in step 1 of assembly for demultiplexing. If data are already demultiplexed this can be left blank. This parameter affects only step 1 of assembly. NB: iPyrad can only handle one barcodes file at a time, so if you have multiple barcodes files and multiple raw files then you'll need to run each separately. Examples: ---------------------------------------------------------------------- data.set_params("barcodes_path", "./barcodes.txt") ## verbose ---------------------------------------------------------------------- """, "Location of barcodes file") ), ("4", (""" (4) sorted_fastq_path ------------------------------------------------ Path to demultiplexed fastq data. If left blank, this is assigned automatically to <data.name>_fastq/ within the working directory. If your data are already demultiplexed then you must enter the location of your data here. Wildcard selectors can be used to select a subsample of files within a directory, else all files are selected in the directory. This parameter affects only step 2 of assembly. Examples: ---------------------------------------------------------------------- data.set_params("sorted_fastq_path", "data/*.gz") ## ---------------------------------------------------------------------- """, "Location of demultiplexed/sorted fastq files") ), ("5", (""" (5) assembly_method -------------------------------------------------- A string specifying the desired assembly method. There are four available options for assembly method: denovo - Denovo assembly is the classic pyrad method, and it is the <default> unless otherwise specified. Denovo will cluster and align all reads from scratch reference - Reference assembly will map and align reads to the provided reference sequence, which must be specified in parameter 28 (reference_sequence). Strict refer- ence assembly will throw out all unmapped reads, which could be a significant proportion depending on the distance between your reference and study species.'. ---------------------------------------------------------------------- data.set_params("assembly_method", "denovo") ## verbose ---------------------------------------------------------------------- """, "Assembly method (denovo, reference)") ), ("6", (""" (6) reference_sequence ----------------------------------------------- The path to the reference sequence you desire to map your reads to. The reference may be either fasta or gzipped fasta. It should be a complete reference sequence, including all chromosomes, scaffolds, and contigs in one huge file (most reference sequences available will be in this format, especially non-model references). The first time you attempt to use this sequence it will be indexed (we are using bwa for reference mapping). This is a time intensive process so expect the first run to take some time, certainly more than ten minutes, but less than an hour. If you desire to index the reference yourself you can do this, but best not to unless you really care about bwa indexing settings. We chose conservative defaults that have worked well for us on other projects. A word on the format of the path (this is important). The path may either be a full path (desirable) or a path relative to the directory you are running ipyrad from (supported but be careful of the path). ---------------------------------------------------------------------- data.set_params(6) = /home/wat/data/reference.fa ## set a full path data.set_params(6) = ./data/reference.fa.gz ## set a relative path data.set_params("reference_sequence") = ./data/reference.fa ## verbose ---------------------------------------------------------------------- """, "Location of reference sequence file") ), ("7", (""" (7) datatype --------------------------------------------------------- Options: rad, gbs, 2brad, ddrad, pairddrad, pairgbs, pair3rad, This parameter affects all steps of assembly (1-7). Examples: ---------------------------------------------------------------------- data.set_params(7) = 'rad' ## rad data type data.set_params(7) = 'gbs' ## gbs data type data.set_params(7) = 'pairddrad' ## gbs data type data.set_params("datatype") = 'ddrad' ## verbose ---------------------------------------------------------------------- """, "Datatype (see docs): rad, gbs, ddrad, etc.") ), ("8", (""" (8) restriction_overhang --------------------------------------------- A tuple containing one or two restriction overhangs. Single digest RADseq with sonication requires only one overhange, all other data types should have two. The first is used for detecting barcodes, the second is not required, but is used in filtering, and is needed for removal from short DNA fragments. This parameter affects steps 1,2,4,5, and 7 of assembly. Examples: ---------------------------------------------------------------------- data.set_params(8) = ("TGCAG", "") ## default rad (PstI) data.set_params(8) = ("CWGC", "CWGC") ## gbs or pairgbs (ApeKI) data.set_params(8) = ("CAGT", "AATT") ## ddrad (ApeKI, MSI) data.set_params(8) = ("CAGT", "AATT") ## pairddrad (ApeKI, MSI) data.set_params("restriction_overhang") = ("CAGT", "AATT") ## verbose ---------------------------------------------------------------------- """, "Restriction overhang (cut1,) or (cut1, cut2)") ), ("9", (""" (9) max_low_qual_bases ----------------------------------------------- Examples: ---------------------------------------------------------------------- data.set_params(9) = 10 data.set_params("max_low_qual_bases") = 6 ---------------------------------------------------------------------- """, "Max low quality base calls (Q<20) in a read") ), ("10", (""" (10) phred_Qscore_offset --------------------------------------------- The threshold at which a base call is considered low quality during step 2 filtering is determined by the phred_Qscore_offset. The default offset is 33, which is equivalent to a minimum qscore of 20 (99% call confidence). Some older data use a qscore offset of 64. You can toggle the offset number to change the threshold for low qual bases. For example, reducing the offset to 26 is equivalent to a minimum qscore of 13, which is approximately 95% probability of a correct base call. Examples: ---------------------------------------------------------------------- data.set_params(10) = 33 data.set_params("phred_Qscore_offset") = 26 ## 95% confidence data.set_params("phred_Qscore_offset") = 43 ## 99.9% confidence data.set_params("phred_Qscore_offset") = 33 ---------------------------------------------------------------------- """, "phred Q score offset (33 is default and very standard)") ), ("11", (""" (11) mindepth_statistical -------------------------------------------- An integer value indicating the mindepth for statistical base calls based a binomial probability with H and E estimated from the data. Base calls are made at >= the value entered. For most reasonable estimates of E and H, statistical base calls cannot be made below 5 or 6, and will instead be called N. The parameter affects steps 5 and 7 of assembly. Examples: ---------------------------------------------------------------------- data.set_params(11) = (6, 6) ## only stat base calls down to depth=6 data.set_params(11) = (10, 5) ## stat calls above 9, majrule from 9-5. data.set_params(11) = (10, 1) ## stat calls above 9, majrule from 9-1. data.set_params(mindepth_statistical) = 6 ## verbose ---------------------------------------------------------------------- """, "Min depth for statistical base calling") ), ("12", (""" (12) mindepth_majrule ------------------------------------------------ An integer value indicating the mindepth for majority-rule base calls. Base calls are made at >= the value entered. It may often be advant- ageous to use a low value for majrule calls to preserve most data during assembly within-samples, so that more data is clustered between samples. Low depth data can be filtered out later from the final data set if needed. The parameter affects steps 5 and 7 of assembly. Examples: ---------------------------------------------------------------------- data.set_params(12) = (6, 6) ## only stat base calls down to depth=6 data.set_params(12) = (10, 5) ## stat calls above 9, majrule from 9-5. data.set_params(12) = (10, 1) ## stat calls above 9, majrule from 9-1. data.set_params(mindepth_majrule) = 6 ## verbose ---------------------------------------------------------------------- """, "Min depth for majority-rule base calling") ), ("13", (""" (13) maxdepth -------------------------------------------------------- Examples: ---------------------------------------------------------------------- data.set_params(13) = 33 data.set_params("maxdepth") = 33 ---------------------------------------------------------------------- """, "Max cluster depth within samples") ), ("14", (""" (14) clust_threshold ------------------------------------------------- Clustering threshold. Examples: ---------------------------------------------------------------------- data.set_params(14) = .85 ## clustering similarity threshold data.set_params(14) = .90 ## clustering similarity threshold data.set_params(14) = .95 ## very high values not recommended data.set_params("clust_threshold") = .83 ## verbose ---------------------------------------------------------------------- """, "Clustering threshold for de novo assembly") ), ("15", (""" (15) max_barcode_mismatch -------------------------------------------- Examples: ---------------------------------------------------------------------- data.set_params(15) = 1 data.set_params("max_barcode_mismatch") = 1 ---------------------------------------------------------------------- """, "Max number of allowable mismatches in barcodes") ), ("16", (""" (16) filter_adapters ---------------------------------------------- Examples: ------------------------------------------------------------------- data.set_params(16) = 1 data.set_params("filter_adapters") = 1 ------------------------------------------------------------------- """, "Filter for adapters/primers (1 or 2=stricter)") ), ("17", (""" (17) filter_min_trim_len --------------------------------------------- Examples: ---------------------------------------------------------------------- data.set_params(17) = 1 data.set_params("filter_min_trim_len") = 1 ---------------------------------------------------------------------- """, "Min length of reads after adapter trim") ), ("18", (""" (18) max_alleles_consens --------------------------------------------- Examples: ---------------------------------------------------------------------- data.set_params(18) = 1 data.set_params("max_alleles_consens") = 1 ---------------------------------------------------------------------- """, "Max alleles per site in consensus sequences") ), ("19", (""" (19) max_Ns_consens -------------------------------------------------- Examples: ---------------------------------------------------------------------- data.set_params(19) = 1 data.set_params("max_Ns_consens") = 1 ---------------------------------------------------------------------- """, "Max N's (uncalled bases) in consensus") ), ("20", (""" (20) max_Hs_consens -------------------------------------------------- Examples: ---------------------------------------------------------------------- data.set_params(20) = 1 data.set_params("max_Hs_consens") = 1 ---------------------------------------------------------------------- """, "Max Hs (heterozygotes) in consensus") ), ("21", (""" (21) min_samples_locus ----------------------------------------------- Minimum number of samples a locus must be shared across to be included in the exported data set following filtering for sequencing depth, paralogs, ... Examples ---------------------------------------------------------------------- data.set_params(21) = 4 ## min 4; most inclusive phylo data data.set_params(21) = 20 ## min 20; less data, less missing data.set_params(21) = 1 ## min 1; most data, most missing data.set_params("min_samples_locus") = 4 ## verbose ---------------------------------------------------------------------- """, "Min # samples per locus for output") ), ("22", (""" (22) max_SNPs_locus -------------------------------------------------- Examples: ---------------------------------------------------------------------- data.set_params(22) = 1 data.set_params("max_SNPs_locus") = 1 ---------------------------------------------------------------------- """, "Max # SNPs per locus") ), ("23", (""" (23) max_Indels_locus ------------------------------------------------ Examples: ---------------------------------------------------------------------- data.set_params(23) = 1 data.set_params("max_Indels_locus") = 1 ---------------------------------------------------------------------- """, "Max # of indels per locus") ), ("24", (""" (24) max_shared_Hs_locus --------------------------------------------- ... ---------------------------------------------------------------------- data.set_params(24) = .25 ## set as proportion of samples data.set_params(24) = 4 ## set as number of samples data.set_params(24) = 9999 ## set arbitrarily high data.set_params("max_shared_Hs_locus") = 4 ## verbose ---------------------------------------------------------------------- """, "Max # heterozygous sites per locus") ), ("25", (""" (25) trim_reads -- --------------------------------------------------- Examples: ---------------------------------------------------------------------- data.set_params("trim_reads") = (0, -5, 0, 0) ## trims last 5 from R1 data.set_params("trim_reads") = (5, 85, 0, 0) ## trims R1 from 5-85 data.set_params("trim_reads") = (5, 85, 5, 85) ## trims both pairs 5-85 ---------------------------------------------------------------------- """, "Trim raw read edges (R1>, <R1, R2>, <R2) (see docs)") ), ("26", (""" (26) trim_loci ------------------------------------------------------- Examples: ---------------------------------------------------------------------- data.set_params("trim_loci") = (0, 5, 5, 0) ---------------------------------------------------------------------- """, "Trim locus edges (see docs) (R1>, <R1, R2>, <R2)") ), ("27", (""" (27) output_formats -------------------------------------------------- Examples: ---------------------------------------------------------------------- * ## [27] output_formats: * means all formats vcf, phy, nex ## [27] list subset of formats if you want ---------------------------------------------------------------------- """, "Output formats (see docs)") ), ("28", (""" (28) pop_assign_file ------------------------------------------------- Examples: ---------------------------------------------------------------------- ./popfile.txt ## [28] pop_assign_file /home/users/Documents/popfile.txt ## [28] pop_assign_file ---------------------------------------------------------------------- """, "Path to population assignment file") ), ("29", (""" (29) reference_as_filter --------------------------------------------- Examples: ---------------------------------------------------------------------- data.set_params("reference_as_filter") = ./data/reference.fa ## verbose ---------------------------------------------------------------------- """, "Reads mapped to this reference are removed in step 3") ), ]) def paramname(param=""): """ Get the param name from the dict index value. """ try: name = pinfo[str(param)][0].strip().split(" ")[1] except (KeyError, ValueError) as err: ## TODO: paramsinfo get description by param string not working. ## It would be cool to have an assembly object bcz then you could ## just do this: ## ## print(pinfo[data.paramsinfo.keys().index(param)]) print("\tKey name/number not recognized - ".format(param), err) raise return name def paraminfo(param="", short=False): """ Returns detailed information for the numbered parameter. Further information is available in the tutorial. Unlike params() this function doesn't deal well with * It only takes one parameter at a time and returns the desc """ ## If the short flag is set return the short description, otherwise ## return the long. if short: desc = 1 else: desc = 0 try: description = pinfo[str(param)][desc] except (KeyError, ValueError) as err: ## TODO: paramsinfo get description by param string not working. ## It would be cool to have an assembly object bcz then you could ## just do this: ## ## print(pinfo[data.paramsinfo.keys().index(param)]) print("\tKey name/number not recognized - ".format(param), err) raise return description def paramsinfo(param="", short=False): """ This is the human readable version of the paramsinfo() function. You give it a param and it prints to stdout. """ if short: desc = 1 else: desc = 0 if param == "*": for key in pinfo: print(pinfo[str(key)][desc]) elif param: try: print(pinfo[str(param)][desc]) except (KeyError, ValueError) as err: ## TODO: paramsinfo get description by param string not working. ## It would be cool to have an assembly object bcz then you could ## just do this: ## ## print(pinfo[data.paramsinfo.keys().index(param)]) print("\tKey name/number not recognized", err) raise else: print("Enter a name or number for explanation of the parameter\n") for key in pinfo: print(pinfo[str(key)][desc].split("\n")[1][2:-10]) if __name__ == "__main__": pass
gpl-3.0
1,552,804,021,922,965,200
44.298969
82
0.454802
false
4.884393
false
false
false
pshchelo/heat
heat/engine/resources/stack_resource.py
1
20765
# # 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 copy import hashlib import json from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_utils import excutils import six from heat.common import exception from heat.common.i18n import _ from heat.common.i18n import _LW from heat.common import identifier from heat.common import template_format from heat.engine import attributes from heat.engine import environment from heat.engine import resource from heat.engine import scheduler from heat.engine import stack as parser from heat.engine import template from heat.rpc import api as rpc_api LOG = logging.getLogger(__name__) class StackResource(resource.Resource): ''' An abstract Resource subclass that allows the management of an entire Stack as a resource in a parent stack. ''' # Assume True as this is evaluated before the stack is created # so there is no way to know for sure without subclass-specific # template parsing. requires_deferred_auth = True def __init__(self, name, json_snippet, stack): super(StackResource, self).__init__(name, json_snippet, stack) self._nested = None self.resource_info = None def validate(self): super(StackResource, self).validate() self.validate_nested_stack() def validate_nested_stack(self): try: name = "%s-%s" % (self.stack.name, self.name) nested_stack = self._parse_nested_stack( name, self.child_template(), self.child_params()) nested_stack.strict_validate = False nested_stack.validate() except AssertionError: raise except Exception as ex: raise exception.StackValidationFailed( error=_("Failed to validate"), path=[self.stack.t.get_section_name('resources'), self.name], message=six.text_type(ex)) def _outputs_to_attribs(self, json_snippet): outputs = json_snippet.get('Outputs') if not self.attributes and outputs: self.attributes_schema = ( attributes.Attributes.schema_from_outputs(outputs)) self.attributes = attributes.Attributes(self.name, self.attributes_schema, self._resolve_attribute) def _needs_update(self, after, before, after_props, before_props, prev_resource): # Always issue an update to the nested stack and let the individual # resources in it decide if they need updating. return True @scheduler.wrappertask def update(self, after, before=None, prev_resource=None): try: yield super(StackResource, self).update(after, before, prev_resource) except StopIteration: with excutils.save_and_reraise_exception(): stack_identity = identifier.HeatIdentifier( self.context.tenant_id, self.physical_resource_name(), self.resource_id) self.rpc_client().stack_cancel_update(self.context, stack_identity) def nested(self, force_reload=False, show_deleted=False): '''Return a Stack object representing the nested (child) stack. :param force_reload: Forces reloading from the DB instead of returning the locally cached Stack object :param show_deleted: Returns the stack even if it's been deleted ''' if force_reload: self._nested = None if self._nested is None and self.resource_id is not None: self._nested = parser.Stack.load(self.context, self.resource_id, show_deleted=show_deleted, force_reload=force_reload) if self._nested is None: raise exception.NotFound(_("Nested stack not found in DB")) return self._nested def child_template(self): ''' Default implementation to get the child template. Resources that inherit from StackResource should override this method with specific details about the template used by them. ''' raise NotImplementedError() def child_params(self): ''' Default implementation to get the child params. Resources that inherit from StackResource should override this method with specific details about the parameters used by them. ''' raise NotImplementedError() def preview(self): ''' Preview a StackResource as resources within a Stack. This method overrides the original Resource.preview to return a preview of all the resources contained in this Stack. For this to be possible, the specific resources need to override both ``child_template`` and ``child_params`` with specific information to allow the stack to be parsed correctly. If any of these methods is missing, the entire StackResource will be returned as if it were a regular Resource. ''' try: child_template = self.child_template() params = self.child_params() except NotImplementedError: LOG.warn(_LW("Preview of '%s' not yet implemented"), self.__class__.__name__) return self name = "%s-%s" % (self.stack.name, self.name) self._nested = self._parse_nested_stack(name, child_template, params) return self.nested().preview_resources() def _parse_child_template(self, child_template, child_env): parsed_child_template = child_template if isinstance(parsed_child_template, template.Template): parsed_child_template = parsed_child_template.t return template.Template(parsed_child_template, files=self.stack.t.files, env=child_env) def _parse_nested_stack(self, stack_name, child_template, child_params, timeout_mins=None, adopt_data=None): if timeout_mins is None: timeout_mins = self.stack.timeout_mins stack_user_project_id = self.stack.stack_user_project_id new_nested_depth = self._child_nested_depth() child_env = environment.get_child_environment( self.stack.env, child_params, child_resource_name=self.name, item_to_remove=self.resource_info) parsed_template = self._child_parsed_template(child_template, child_env) # Note we disable rollback for nested stacks, since they # should be rolled back by the parent stack on failure nested = parser.Stack(self.context, stack_name, parsed_template, timeout_mins=timeout_mins, disable_rollback=True, parent_resource=self.name, owner_id=self.stack.id, user_creds_id=self.stack.user_creds_id, stack_user_project_id=stack_user_project_id, adopt_stack_data=adopt_data, nested_depth=new_nested_depth) return nested def _child_nested_depth(self): if self.stack.nested_depth >= cfg.CONF.max_nested_stack_depth: msg = _("Recursion depth exceeds %d." ) % cfg.CONF.max_nested_stack_depth raise exception.RequestLimitExceeded(message=msg) return self.stack.nested_depth + 1 def _child_parsed_template(self, child_template, child_env): parsed_template = self._parse_child_template(child_template, child_env) self._validate_nested_resources(parsed_template) # Don't overwrite the attributes_schema for subclasses that # define their own attributes_schema. if not hasattr(type(self), 'attributes_schema'): self.attributes = None self._outputs_to_attribs(parsed_template) return parsed_template def _validate_nested_resources(self, templ): total_resources = (len(templ[templ.RESOURCES]) + self.stack.root_stack.total_resources()) if self.nested(): # It's an update and these resources will be deleted total_resources -= len(self.nested().resources) if (total_resources > cfg.CONF.max_resources_per_stack): message = exception.StackResourceLimitExceeded.msg_fmt raise exception.RequestLimitExceeded(message=message) def create_with_template(self, child_template, user_params=None, timeout_mins=None, adopt_data=None): """Create the nested stack with the given template.""" name = self.physical_resource_name() if timeout_mins is None: timeout_mins = self.stack.timeout_mins stack_user_project_id = self.stack.stack_user_project_id if user_params is None: user_params = self.child_params() child_env = environment.get_child_environment( self.stack.env, user_params, child_resource_name=self.name, item_to_remove=self.resource_info) new_nested_depth = self._child_nested_depth() parsed_template = self._child_parsed_template(child_template, child_env) adopt_data_str = None if adopt_data is not None: if 'environment' not in adopt_data: adopt_data['environment'] = child_env.user_env_as_dict() if 'template' not in adopt_data: adopt_data['template'] = child_template adopt_data_str = json.dumps(adopt_data) args = {rpc_api.PARAM_TIMEOUT: timeout_mins, rpc_api.PARAM_DISABLE_ROLLBACK: True, rpc_api.PARAM_ADOPT_STACK_DATA: adopt_data_str} try: result = self.rpc_client()._create_stack( self.context, name, parsed_template.t, child_env.user_env_as_dict(), parsed_template.files, args, owner_id=self.stack.id, user_creds_id=self.stack.user_creds_id, stack_user_project_id=stack_user_project_id, nested_depth=new_nested_depth, parent_resource_name=self.name) except Exception as ex: self.raise_local_exception(ex) self.resource_id_set(result['stack_id']) def raise_local_exception(self, ex): ex_type = ex.__class__.__name__ is_remote = ex_type.endswith('_Remote') if is_remote: ex_type = ex_type[:-len('_Remote')] full_message = six.text_type(ex) if full_message.find('\n') > -1 and is_remote: message, msg_trace = full_message.split('\n', 1) else: message = full_message if (isinstance(ex, exception.ActionInProgress) and self.stack.action == self.stack.ROLLBACK): # The update was interrupted and the rollback is already in # progress, so just ignore the error and wait for the rollback to # finish return if isinstance(ex, exception.HeatException): message = ex.message local_ex = copy.copy(getattr(exception, ex_type)) local_ex.msg_fmt = "%(message)s" raise local_ex(message=message) def check_create_complete(self, cookie=None): return self._check_status_complete(resource.Resource.CREATE) def _check_status_complete(self, action, show_deleted=False, cookie=None): try: nested = self.nested(force_reload=True, show_deleted=show_deleted) except exception.NotFound: if action == resource.Resource.DELETE: return True # It's possible the engine handling the create hasn't persisted # the stack to the DB when we first start polling for state return False if nested is None: return True if nested.action != action: return False # Has the action really started? # # The rpc call to update does not guarantee that the stack will be # placed into IN_PROGRESS by the time it returns (it runs stack.update # in a thread) so you could also have a situation where we get into # this method and the update hasn't even started. # # So we are using a mixture of state (action+status) and updated_at # to see if the action has actually progressed. # - very fast updates (like something with one RandomString) we will # probably miss the state change, but we should catch the updated_at. # - very slow updates we won't see the updated_at for quite a while, # but should see the state change. if cookie is not None: prev_state = cookie['previous']['state'] prev_updated_at = cookie['previous']['updated_at'] if (prev_updated_at == nested.updated_time and prev_state == nested.state): return False if nested.status == resource.Resource.IN_PROGRESS: return False elif nested.status == resource.Resource.COMPLETE: return True elif nested.status == resource.Resource.FAILED: raise resource.ResourceUnknownStatus( resource_status=nested.status, status_reason=nested.status_reason) else: raise resource.ResourceUnknownStatus( resource_status=nested.status, result=_('Stack unknown status')) def check_adopt_complete(self, cookie=None): return self._check_status_complete(resource.Resource.ADOPT) def update_with_template(self, child_template, user_params=None, timeout_mins=None): """Update the nested stack with the new template.""" if self.id is None: self._store() nested_stack = self.nested() if nested_stack is None: # if the create failed for some reason and the nested # stack was not created, we need to create an empty stack # here so that the update will work. def _check_for_completion(creator_fn): while not self.check_create_complete(creator_fn): yield empty_temp = template_format.parse( "heat_template_version: '2013-05-23'") stack_creator = self.create_with_template(empty_temp, {}) checker = scheduler.TaskRunner(_check_for_completion, stack_creator) checker(timeout=self.stack.timeout_secs()) if stack_creator is not None: stack_creator.run_to_completion() nested_stack = self.nested() if timeout_mins is None: timeout_mins = self.stack.timeout_mins if user_params is None: user_params = self.child_params() child_env = environment.get_child_environment( self.stack.env, user_params, child_resource_name=self.name, item_to_remove=self.resource_info) parsed_template = self._child_parsed_template(child_template, child_env) cookie = {'previous': { 'updated_at': nested_stack.updated_time, 'state': nested_stack.state}} args = {rpc_api.PARAM_TIMEOUT: timeout_mins} try: self.rpc_client().update_stack( self.context, nested_stack.identifier(), parsed_template.t, child_env.user_env_as_dict(), parsed_template.files, args) except Exception as ex: LOG.exception('update_stack') self.raise_local_exception(ex) return cookie def check_update_complete(self, cookie=None): return self._check_status_complete(resource.Resource.UPDATE, cookie=cookie) def delete_nested(self): ''' Delete the nested stack. ''' stack_identity = identifier.HeatIdentifier( self.context.tenant_id, self.physical_resource_name(), self.resource_id) try: self.rpc_client().delete_stack(self.context, stack_identity) except Exception as ex: self.rpc_client().ignore_error_named(ex, 'NotFound') def check_delete_complete(self, cookie=None): return self._check_status_complete(resource.Resource.DELETE, show_deleted=True) def handle_suspend(self): stack = self.nested() if stack is None: raise exception.Error(_('Cannot suspend %s, stack not created') % self.name) stack_identity = identifier.HeatIdentifier( self.context.tenant_id, self.physical_resource_name(), self.resource_id) self.rpc_client().stack_suspend(self.context, stack_identity) def check_suspend_complete(self, cookie=None): return self._check_status_complete(resource.Resource.SUSPEND) def handle_resume(self): stack = self.nested() if stack is None: raise exception.Error(_('Cannot resume %s, stack not created') % self.name) stack_identity = identifier.HeatIdentifier( self.context.tenant_id, self.physical_resource_name(), self.resource_id) self.rpc_client().stack_resume(self.context, stack_identity) def check_resume_complete(self, cookie=None): return self._check_status_complete(resource.Resource.RESUME) def handle_check(self): stack = self.nested() if stack is None: raise exception.Error(_('Cannot check %s, stack not created') % self.name) stack_identity = identifier.HeatIdentifier( self.context.tenant_id, self.physical_resource_name(), self.resource_id) self.rpc_client().stack_check(self.context, stack_identity) def check_check_complete(self, cookie=None): return self._check_status_complete(resource.Resource.CHECK) def prepare_abandon(self): return self.nested().prepare_abandon() def get_output(self, op): ''' Return the specified Output value from the nested stack. If the output key does not exist, raise an InvalidTemplateAttribute exception. ''' stack = self.nested() if stack is None: return None if op not in stack.outputs: raise exception.InvalidTemplateAttribute(resource=self.name, key=op) return stack.output(op) def _resolve_attribute(self, name): return self.get_output(name) def implementation_signature(self): schema_names = ([prop for prop in self.properties_schema] + [at for at in self.attributes_schema]) schema_hash = hashlib.sha256(';'.join(schema_names)) definition = {'template': self.child_template(), 'files': self.stack.t.files} definition_hash = hashlib.sha256(jsonutils.dumps(definition)) return (schema_hash.hexdigest(), definition_hash.hexdigest())
apache-2.0
-4,581,617,663,593,579,000
38.932692
79
0.584589
false
4.578831
false
false
false
hds-lab/coding-ml
msgvis/apps/enhance/migrations/0002_auto_20160222_0230.py
1
1306
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('enhance', '0001_initial'), (b'auth', b'__first__'), # This line and the next line is for fixing the "Lookup failed auth.User" error (b'contenttypes', b'__first__'), ] operations = [ migrations.AddField( model_name='feature', name='created_at', field=models.DateTimeField(default=None, auto_now_add=True), preserve_default=True, ), migrations.AddField( model_name='feature', name='last_updated', field=models.DateTimeField(default=None, auto_now=True, auto_now_add=True), preserve_default=True, ), migrations.AddField( model_name='feature', name='valid', field=models.BooleanField(default=True), preserve_default=True, ), migrations.AlterField( model_name='feature', name='source', field=models.ForeignKey(related_name='features', default=None, to=settings.AUTH_USER_MODEL), preserve_default=True, ), ]
mit
-7,770,648,743,024,572,000
30.853659
119
0.570444
false
4.367893
false
false
false
jj1bdx/wspr
WsprMod/iq.py
1
4726
#------------------------------------------------------------------ iq from Tkinter import * import Pmw import g import w import time import tkMessageBox import pickle def done(): root.withdraw() root=Toplevel() root.withdraw() root.protocol('WM_DELETE_WINDOW',done) if g.Win32: root.iconbitmap("wsjt.ico") root.title("I-Q Mode") def iq2(t): root.geometry(t) root.deiconify() root.focus_set() j=ib.get() lab0.configure(text=str(mb[j])+' m') iqmode=IntVar() iqrx=IntVar() iqtx=IntVar() fiq=IntVar() iqrxapp=IntVar() iqrxadj=IntVar() isc2=IntVar() isc2.set(0) isc2a=IntVar() isc2a.set(0) isc3=IntVar() isc3.set(0) isc3a=IntVar() isc3a.set(0) ib=IntVar() gain=DoubleVar() phdeg=DoubleVar() mb=[0,600,160,80,60,40,30,20,17,15,12,10,6,4,2,0] tbal=[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0] tpha=[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0] rbal=[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0] rpha=[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0] allbands=0 def saveband(event=NONE): global allbands,tbal,tpha,rbal,rpha if allbands: for j in range(1,15): tbal[j]=isc2.get() + 0.02*isc2a.get() tpha[j]=isc3.get() + 0.02*isc3a.get() rbal[j]=w.acom1.gain rpha[j]=57.2957795*w.acom1.phase else: j=ib.get() tbal[j]=isc2.get() + 0.02*isc2a.get() tpha[j]=isc3.get() + 0.02*isc3a.get() rbal[j]=w.acom1.gain rpha[j]=57.2957795*w.acom1.phase f=open(g.appdir+'/iqpickle',mode='w') pickle.dump(tbal,f) pickle.dump(tpha,f) pickle.dump(rbal,f) pickle.dump(rpha,f) f.close() def saveall(event=NONE): global allbands allbands=1 saveband() allbands=0 def restore(): global tbal,tpha,rbal,rpha try: f=open(g.appdir+'/iqpickle',mode='r') tbal=pickle.load(f) tpha=pickle.load(f) rbal=pickle.load(f) rpha=pickle.load(f) f.close() except: pass newband() def newband(): j=ib.get() lab0.configure(text=str(mb[j])+' m') w.acom1.gain=rbal[j] w.acom1.phase=rpha[j]/57.2957795 isc2.set(int(tbal[j])) isc2a.set(int((tbal[j]-isc2.get())/0.02)) isc3.set(int(tpha[j])) isc3a.set(int((tpha[j]-isc3.get())/0.02)) #-------------------------------------------------------- Create GUI widgets g1=Pmw.Group(root,tag_pyclass=None) lab0=Label(g1.interior(),text='160 m',bg='yellow',pady=5) lab0.place(x=180,y=40, anchor='e') #lab0.pack(anchor=W,padx=5,pady=4) biqmode=Checkbutton(g1.interior(),text='Enable I/Q mode',variable=iqmode) biqmode.pack(anchor=W,padx=5,pady=2) biqtx=Checkbutton(g1.interior(),text='Reverse Tx I,Q',variable=iqtx) biqtx.pack(anchor=W,padx=5,pady=2) biqrx=Checkbutton(g1.interior(),text='Reverse Rx I,Q',variable=iqrx) biqrx.pack(anchor=W,padx=5,pady=2) biqrxapp=Checkbutton(g1.interior(),text='Apply Rx phasing corrections', \ variable=iqrxapp) biqrxapp.pack(anchor=W,padx=5,pady=2) biqrxadj=Checkbutton(g1.interior(),text='Adjust Rx phasing', \ variable=iqrxadj) biqrxadj.pack(anchor=W,padx=5,pady=2) lab1=Label(g1.interior(),text='',justify=LEFT) lab1.pack(anchor=W,padx=5,pady=4) fiq_entry=Pmw.EntryField(g1.interior(),labelpos=W,label_text='Fiq (Hz): ', value='12000',entry_textvariable=fiq,entry_width=10, validate={'validator':'integer','min':-24000,'max':24000, 'minstrict':0,'maxstrict':0}) fiq_entry.pack(fill=X,padx=2,pady=4) sc2=Scale(g1.interior(),orient=HORIZONTAL,length=200,from_=-30, \ to=30,variable=isc2,label='Tx I/Q Balance (0.1 dB)', \ relief=SOLID,bg='#EEDD82') sc2.pack(side=TOP,padx=4,pady=2) sc2a=Scale(g1.interior(),orient=HORIZONTAL,length=200,from_=-50, \ to=50,variable=isc2a,label='Tx I/Q Balance (0.002 dB)', \ relief=SOLID,bg='#EEDD82') sc2a.pack(side=TOP,padx=4,pady=2) sc3=Scale(g1.interior(),orient=HORIZONTAL,length=200,from_=-20, \ to=20,variable=isc3,label='Tx Phase (deg)', \ relief=SOLID,bg='#AFeeee') sc3.pack(side=TOP,padx=4,pady=2) sc3a=Scale(g1.interior(),orient=HORIZONTAL,length=200,from_=-50, \ to=50,variable=isc3a,label='Tx Phase (0.02 deg)', \ relief=SOLID,bg='#AFeeee') sc3a.pack(side=TOP,padx=4,pady=2) bsave=Button(g1.interior(), text='Save for this band',command=saveband, width=32,padx=1,pady=2) bsave.pack(padx=2,pady=4) bsaveall=Button(g1.interior(), text='Save for all bands',command=saveall, width=32,padx=1,pady=2) bsaveall.pack(padx=2,pady=4) f1=Frame(g1.interior(),width=100,height=1) f1.pack() g1.pack(side=LEFT,fill=BOTH,expand=1,padx=4,pady=4)
gpl-2.0
-423,385,164,766,437,600
27.46988
82
0.621244
false
2.233459
false
false
false
zestyr/lbry
lbrynet/core/server/ServerRequestHandler.py
1
5866
import json import logging from twisted.internet import interfaces, defer from zope.interface import implements from lbrynet.interfaces import IRequestHandler log = logging.getLogger(__name__) class ServerRequestHandler(object): """This class handles requests from clients. It can upload blobs and return request for information about more blobs that are associated with streams. """ implements(interfaces.IPushProducer, interfaces.IConsumer, IRequestHandler) def __init__(self, consumer): self.consumer = consumer self.production_paused = False self.request_buff = '' self.response_buff = '' self.producer = None self.request_received = False self.CHUNK_SIZE = 2**14 self.query_handlers = {} # {IQueryHandler: [query_identifiers]} self.blob_sender = None self.consumer.registerProducer(self, True) #IPushProducer stuff def pauseProducing(self): self.production_paused = True def stopProducing(self): if self.producer is not None: self.producer.stopProducing() self.producer = None self.production_paused = True self.consumer.unregisterProducer() def resumeProducing(self): from twisted.internet import reactor self.production_paused = False self._produce_more() if self.producer is not None: reactor.callLater(0, self.producer.resumeProducing) def _produce_more(self): from twisted.internet import reactor if self.production_paused: return chunk = self.response_buff[:self.CHUNK_SIZE] self.response_buff = self.response_buff[self.CHUNK_SIZE:] if chunk == '': return log.trace("writing %s bytes to the client", len(chunk)) self.consumer.write(chunk) reactor.callLater(0, self._produce_more) #IConsumer stuff def registerProducer(self, producer, streaming): self.producer = producer assert streaming is False producer.resumeProducing() def unregisterProducer(self): self.producer = None def write(self, data): from twisted.internet import reactor self.response_buff = self.response_buff + data self._produce_more() def get_more_data(): if self.producer is not None: log.trace("Requesting more data from the producer") self.producer.resumeProducing() reactor.callLater(0, get_more_data) #From Protocol def data_received(self, data): log.debug("Received data") log.debug("%s", str(data)) if self.request_received is False: return self._parse_data_and_maybe_send_blob(data) else: log.warning( "The client sent data when we were uploading a file. This should not happen") def _parse_data_and_maybe_send_blob(self, data): self.request_buff = self.request_buff + data msg = self.try_to_parse_request(self.request_buff) if msg: self.request_buff = '' self._process_msg(msg) else: log.debug("Request buff not a valid json message") log.debug("Request buff: %s", self.request_buff) def _process_msg(self, msg): d = self.handle_request(msg) if self.blob_sender: d.addCallback(lambda _: self.blob_sender.send_blob_if_requested(self)) d.addCallbacks(lambda _: self.finished_response(), self.request_failure_handler) ######### IRequestHandler ######### def register_query_handler(self, query_handler, query_identifiers): self.query_handlers[query_handler] = query_identifiers def register_blob_sender(self, blob_sender): self.blob_sender = blob_sender #response handling def request_failure_handler(self, err): log.warning("An error occurred handling a request. Error: %s", err.getErrorMessage()) self.stopProducing() return err def finished_response(self): self.request_received = False self._produce_more() def send_response(self, msg): m = json.dumps(msg) log.debug("Sending a response of length %s", str(len(m))) log.debug("Response: %s", str(m)) self.response_buff = self.response_buff + m self._produce_more() return True def handle_request(self, msg): log.debug("Handling a request") log.debug(str(msg)) def create_response_message(results): response = {} for success, result in results: if success is True: response.update(result) else: # result is a Failure return result log.debug("Finished making the response message. Response: %s", str(response)) return response def log_errors(err): log.warning( "An error occurred handling a client request. Error message: %s", err.getErrorMessage()) return err def send_response(response): self.send_response(response) return True ds = [] for query_handler, query_identifiers in self.query_handlers.iteritems(): queries = {q_i: msg[q_i] for q_i in query_identifiers if q_i in msg} d = query_handler.handle_queries(queries) d.addErrback(log_errors) ds.append(d) dl = defer.DeferredList(ds) dl.addCallback(create_response_message) dl.addCallback(send_response) return dl def try_to_parse_request(self, request_buff): try: msg = json.loads(request_buff) return msg except ValueError: return None
mit
8,375,703,638,704,539,000
30.537634
93
0.608421
false
4.335551
false
false
false
diegodelemos/reana-job-controller
tests/test_job_manager.py
1
4870
# -*- coding: utf-8 -*- # # This file is part of REANA. # Copyright (C) 2019 CERN. # # REANA is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """REANA-Job-Controller Job Manager tests.""" import json import os import uuid import mock import pytest from reana_db.models import Job, JobStatus from reana_job_controller.job_manager import JobManager from reana_job_controller.kubernetes_job_manager import KubernetesJobManager def test_execute_kubernetes_job( app, session, sample_serial_workflow_in_db, sample_workflow_workspace, default_user, empty_user_secrets, corev1_api_client_with_user_secrets, monkeypatch, ): """Test execution of Kubernetes job.""" workflow_uuid = sample_serial_workflow_in_db.id_ workflow_workspace = next(sample_workflow_workspace(str(workflow_uuid))) env_var_key = "key" env_var_value = "value" expected_env_var = {env_var_key: env_var_value} expected_image = "busybox" expected_command = ["ls"] monkeypatch.setenv("REANA_USER_ID", str(default_user.id_)) job_manager = KubernetesJobManager( docker_img=expected_image, cmd=expected_command, env_vars=expected_env_var, workflow_uuid=workflow_uuid, workflow_workspace=workflow_workspace, ) with mock.patch( "reana_job_controller.kubernetes_job_manager." "current_k8s_batchv1_api_client" ) as kubernetes_client: with mock.patch( "reana_commons.k8s.secrets." "current_k8s_corev1_api_client", corev1_api_client_with_user_secrets(empty_user_secrets), ): kubernetes_job_id = job_manager.execute() created_job = ( session.query(Job) .filter_by(backend_job_id=kubernetes_job_id) .one_or_none() ) assert created_job assert created_job.docker_img == expected_image assert created_job.cmd == json.dumps(expected_command) assert json.dumps(expected_env_var) in created_job.env_vars assert created_job.status == JobStatus.created kubernetes_client.create_namespaced_job.assert_called_once() body = kubernetes_client.create_namespaced_job.call_args[1]["body"] env_vars = body["spec"]["template"]["spec"]["containers"][0]["env"] image = body["spec"]["template"]["spec"]["containers"][0]["image"] command = body["spec"]["template"]["spec"]["containers"][0]["command"] assert len(env_vars) == 3 assert {"name": env_var_key, "value": env_var_value} in env_vars assert image == expected_image assert command == expected_command def test_stop_kubernetes_job( app, session, sample_serial_workflow_in_db, sample_workflow_workspace, empty_user_secrets, default_user, corev1_api_client_with_user_secrets, monkeypatch, ): """Test stop of Kubernetes job.""" workflow_uuid = sample_serial_workflow_in_db.id_ workflow_workspace = next(sample_workflow_workspace(str(workflow_uuid))) expected_env_var_name = "env_var" expected_env_var_value = "value" expected_image = "busybox" expected_command = ["ls"] monkeypatch.setenv("REANA_USER_ID", str(default_user.id_)) job_manager = KubernetesJobManager( docker_img=expected_image, cmd=expected_command, env_vars={expected_env_var_name: expected_env_var_value}, workflow_uuid=workflow_uuid, workflow_workspace=workflow_workspace, ) with mock.patch( "reana_job_controller.kubernetes_job_manager." "current_k8s_batchv1_api_client" ) as kubernetes_client: with mock.patch( "reana_commons.k8s.secrets." "current_k8s_corev1_api_client", corev1_api_client_with_user_secrets(empty_user_secrets), ): kubernetes_job_id = job_manager.execute() kubernetes_client.create_namespaced_job.assert_called_once() job_manager.stop(kubernetes_job_id) kubernetes_client.delete_namespaced_job.assert_called_once() def test_execution_hooks(): """Test hook execution order.""" class TestJobManger(JobManager): @JobManager.execution_hook def execute(self): self.order_list.append(2) job_id = str(uuid.uuid4()) return job_id def before_execution(self): self.order_list = [] self.order_list.append(1) def create_job_in_db(self, job_id): self.order_list.append(3) def cache_job(self): self.order_list.append(4) job_manager = TestJobManger("busybox", "ls", {}) job_manager.execute() assert job_manager.order_list == [1, 2, 3, 4]
mit
-5,248,791,011,333,741,000
34.289855
87
0.634702
false
3.637043
true
false
false
kencochrane/docker-django-demo
dockerdemo/voting/migrations/0001_initial.py
1
1782
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-02-16 20:05 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Choice', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('choice_text', models.CharField(max_length=200)), ], ), migrations.CreateModel( name='Question', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('question_text', models.CharField(max_length=200)), ('pub_date', models.DateTimeField(auto_now_add=True, verbose_name='date published')), ('last_update', models.DateTimeField(auto_now=True, verbose_name='last updated')), ], ), migrations.CreateModel( name='Vote', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('vote_date', models.DateTimeField(auto_now=True, verbose_name='date voted')), ('ip_address', models.GenericIPAddressField()), ('selection', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='voting.Choice')), ], ), migrations.AddField( model_name='choice', name='question', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='voting.Question'), ), ]
mit
-4,280,010,848,897,716,000
36.914894
114
0.574635
false
4.304348
false
false
false
todddeluca/diabric
diabric/files.py
1
11396
''' Fabric utilities for working with files. ''' import StringIO import contextlib import os import shutil import subprocess import uuid from fabric.api import sudo, run, settings, hide, put, local from fabric.contrib.files import exists ################## # HELPER FUNCTIONS # These functions are reusable snippets meant to improve the consistency # and modularity of files.py code def set_mode(path, mode, remote=True, use_sudo=False): ''' To improve code consistency and composition, this function changes the mode of `path` to `mode`. path: the path to the file or directory whose mode is being set. remote: indicates that filename is a located on a remote host and `run` or `sudo` should be used to set the mode. use_sudo: only applies when remote is True. Use `sudo` instead of `run`. ''' func = local if not remote else sudo if use_sudo else run func('chmod {} {}'.format(oct(mode), path)) def backup_file(filename, remote=True, use_sudo=False, extension='.bak'): ''' filename: path to a local or remote file If filename exists, copy filename to filename.bak ''' func = local if not remote else sudo if use_sudo else run if exists(filename): func("cp %s %s.bak" % (filename, filename)) def normalize_dest(src, dest, remote=True, use_sudo=False): ''' src: a file path dest: a file or directory path If dest is an existing directory, this returns a path to the basename of src within the directory dest. Otherwise, if dest is returned unchanged. This is useful for getting an actual filename when destination can be a file or a directory. ''' func = local if not remote else sudo if use_sudo else run # Normalize dest to be an actual filename, due to using StringIO with settings(hide('everything'), warn_only=True): if func('test -d %s' % dest).succeeded: dest = os.path.join(dest, os.path.basename(src)) return dest ################ # FILE FUNCTIONS def file_template(filename, destination, context=None, use_jinja=False, template_dir=None, backup=True, mirror_local_mode=False, mode=None): """ This is the local version of upload_template. Render and copy a template text file to a local destination. ``filename`` should be the path to a text file, which may contain `Python string interpolation formatting <http://docs.python.org/release/2.5.4/lib/typesseq-strings.html>`_ and will be rendered with the given context dictionary ``context`` (if given.) Alternately, if ``use_jinja`` is set to True and you have the Jinja2 templating library available, Jinja will be used to render the template instead. Templates will be loaded from the invoking user's current working directory by default, or from ``template_dir`` if given. The resulting rendered file will be written to the local file path ``destination``. If the destination file already exists, it will be renamed with a ``.bak`` extension unless ``backup=False`` is specified. The ``mirror_local_mode`` and ``mode`` kwargs are used in a similar manner as in `~fabric.operations.put`; please see its documentation for details on these two options. """ func = local # make sure destination is a file name, not a directory name. destination = normalize_dest(filename, destination, remote=False) # grab mode before writing destination, in case filename and destination # are the same. if mirror_local_mode and mode is None: # mode is numeric. See os.chmod or os.stat. mode = os.stat(src).st_mode # Process template text = None if use_jinja: try: from jinja2 import Environment, FileSystemLoader jenv = Environment(loader=FileSystemLoader(template_dir or '.')) text = jenv.get_template(filename).render(**context or {}) except ImportError: import traceback tb = traceback.format_exc() abort(tb + "\nUnable to import Jinja2 -- see above.") else: with open(filename) as inputfile: text = inputfile.read() if context: text = text % context if backup: backup_file(destination, remote=False) # write the processed text with open(destination, 'w') as fh: fh.write(text) if mode: set_mode(destination, mode, remote=False) def fix_shebang(shebang, handle): ''' shebang: a shebang line, e.g. #!/usr/bin/env python or #!/bin/sh. If shebang does not start with '#!', then '#!' will be prepended to it. If shebang does not end with a newline, a newline will be appended. handle: a iterable of lines, presumably the contents of a file that needs a shebang line or a new shebang line. Yield shebang and then the lines in handle except the first line in handle if it is a shebang line. ''' # make sure shebang is starts with '#!' and ends with a newline. if not shebang.startswith('#!'): shebang = '#!' + shebang if not shebang.endswith('\n'): shebang += '\n' for i, line in enumerate(handle): if i == 0: yield shebang if not line.startswith('#!'): yield line else: yield line def upload_shebang(filename, destination, shebang, use_sudo=False, backup=True, mirror_local_mode=False, mode=None): """ Upload a text file to a remote host, adding or updating the shebang line. ``filename`` should be the path to a text file. ``shebang`` should be a string containing a shebang line. E.g. "#!/usr/bin/python\n". If shebang does not start with '#!' or end with a newline, these will be added. If the first line in filename starts with '#!' it will be replaced with shebang. If the first line does not start with #!, shebang will be prepended to the contents of filename. The resulting file will be uploaded to the remote file path ``destination``. If the destination file already exists, it will be renamed with a ``.bak`` extension unless ``backup=False`` is specified. By default, the file will be copied to ``destination`` as the logged-in user; specify ``use_sudo=True`` to use `sudo` instead. The ``mirror_local_mode`` and ``mode`` kwargs are passed directly to an internal `~fabric.operations.put` call; please see its documentation for details on these two options. """ func = use_sudo and sudo or run # Normalize destination to be an actual filename, due to using StringIO with settings(hide('everything'), warn_only=True): if func('test -d %s' % destination).succeeded: sep = "" if destination.endswith('/') else "/" destination += sep + os.path.basename(filename) # Use mode kwarg to implement mirror_local_mode, again due to using # StringIO if mirror_local_mode and mode is None: mode = os.stat(filename).st_mode # To prevent put() from trying to do this # logic itself mirror_local_mode = False # process filename text = None with open(filename) as inputfile: text = ''.join(fix_shebang(shebang, inputfile)) # Back up original file if backup and exists(destination): func("cp %s{,.bak}" % destination) # Upload the file. put( local_path=StringIO.StringIO(text), remote_path=destination, use_sudo=use_sudo, mirror_local_mode=mirror_local_mode, mode=mode ) def upload_format(filename, destination, args=None, kws=None, use_sudo=False, backup=True, mirror_local_mode=False, mode=None): """ Read in the contents of filename, format the contents via contents.format(*args, **kws), and upload the results to the destination on the remote host. ``filename`` should be the path to a text file. The contents of ``filename`` will be read in. Format the contents, using contents.format(*args, **kws). If args is None, it will not be included in the format() call. Likewise for kws. The resulting contents will be uploaded to the remote file path ``destination``. If the destination file already exists, it will be renamed with a ``.bak`` extension unless ``backup=False`` is specified. By default, the file will be copied to ``destination`` as the logged-in user; specify ``use_sudo=True`` to use `sudo` instead. The ``mirror_local_mode`` and ``mode`` kwargs are passed directly to an internal `~fabric.operations.put` call; please see its documentation for details on these two options. """ func = use_sudo and sudo or run # Normalize destination to be an actual filename, due to using StringIO with settings(hide('everything'), warn_only=True): if func('test -d %s' % destination).succeeded: sep = "" if destination.endswith('/') else "/" destination += sep + os.path.basename(filename) # Use mode kwarg to implement mirror_local_mode, again due to using # StringIO if mirror_local_mode and mode is None: mode = os.stat(filename).st_mode # To prevent put() from trying to do this # logic itself mirror_local_mode = False # process filename text = None with open(filename) as inputfile: if not args: args = [] if not kws: kws = {} text = inputfile.read().format(*args, **kws) # Back up original file if backup and exists(destination): func("cp %s{,.bak}" % destination) # Upload the file. put( local_path=StringIO.StringIO(text), remote_path=destination, use_sudo=use_sudo, mirror_local_mode=mirror_local_mode, mode=mode ) def file_format(infile, outfile, args=None, kws=None): ''' Consider using fabric.contrib.files.upload_template or upload_format infile: a local file path outfile: a local file path. Read the contents of infile as a string, ''.format() the string using args and kws, and write the formatted string to outfile. This is useful if infile is a "template" and args and kws contain the concrete values for the template. ''' if args is None: args = [] if kws is None: kws is {} with open(infile) as fh: text = fh.read() new_text = text.format(*args, **kws) with open(outfile, 'w') as fh2: fh2.write(new_text) def rsync(options, src, dest, user=None, host=None, cwd=None): ''' Consider using fabric.contrib.project.rsync_project. options: list of rsync options, e.g. ['--delete', '-avz'] src: source directory (or files). Note: rsync behavior varies depending on whether or not src dir ends in '/'. dest: destination directory. cwd: change (using subprocess) to cwd before running rsync. This is a helper function for running rsync locally, via subprocess. Note: shell=False. ''' # if remote user and host specified, copy there instead of locally. if user and host: destStr = '{}@{}:{}'.format(user, host, dest) else: destStr = dest args = ['rsync'] + options + [src, destStr] print args subprocess.check_call(args, cwd=cwd)
mit
3,146,706,489,054,374,400
33.850153
115
0.650053
false
4.106667
false
false
false
zeroSteiner/boltons
boltons/formatutils.py
1
11298
# -*- coding: utf-8 -*- """`PEP 3101`_ introduced the :meth:`str.format` method, and what would later be called "new-style" string formatting. For the sake of explicit correctness, it is probably best to refer to Python's dual string formatting capabilities as *bracket-style* and *percent-style*. There is overlap, but one does not replace the other. * Bracket-style is more pluggable, slower, and uses a method. * Percent-style is simpler, faster, and uses an operator. Bracket-style formatting brought with it a much more powerful toolbox, but it was far from a full one. :meth:`str.format` uses `more powerful syntax`_, but `the tools and idioms`_ for working with that syntax are not well-developed nor well-advertised. ``formatutils`` adds several functions for working with bracket-style format strings: * :class:`DeferredValue`: Defer fetching or calculating a value until format time. * :func:`get_format_args`: Parse the positional and keyword arguments out of a format string. * :func:`tokenize_format_str`: Tokenize a format string into literals and :class:`BaseFormatField` objects. * :func:`construct_format_field_str`: Assists in progammatic construction of format strings. * :func:`infer_positional_format_args`: Converts anonymous references in 2.7+ format strings to explicit positional arguments suitable for usage with Python 2.6. .. _more powerful syntax: https://docs.python.org/2/library/string.html#format-string-syntax .. _the tools and idioms: https://docs.python.org/2/library/string.html#string-formatting .. _PEP 3101: https://www.python.org/dev/peps/pep-3101/ """ # TODO: also include percent-formatting utils? # TODO: include lithoxyl.formatters.Formatter (or some adaptation)? from __future__ import print_function import re from string import Formatter __all__ = ['DeferredValue', 'get_format_args', 'tokenize_format_str', 'construct_format_field_str', 'infer_positional_format_args', 'BaseFormatField'] _pos_farg_re = re.compile('({{)|' # escaped open-brace '(}})|' # escaped close-brace '({[:!.\[}])') # anon positional format arg def construct_format_field_str(fname, fspec, conv): """ Constructs a format field string from the field name, spec, and conversion character (``fname``, ``fspec``, ``conv``). See Python String Formatting for more info. """ if fname is None: return '' ret = '{' + fname if conv: ret += '!' + conv if fspec: ret += ':' + fspec ret += '}' return ret def split_format_str(fstr): """Does very basic spliting of a format string, returns a list of strings. For full tokenization, see :func:`tokenize_format_str`. """ ret = [] for lit, fname, fspec, conv in Formatter().parse(fstr): if fname is None: ret.append((lit, None)) continue field_str = construct_format_field_str(fname, fspec, conv) ret.append((lit, field_str)) return ret def infer_positional_format_args(fstr): """Takes format strings with anonymous positional arguments, (e.g., "{}" and {:d}), and converts them into numbered ones for explicitness and compatibility with 2.6. Returns a string with the inferred positional arguments. """ # TODO: memoize ret, max_anon = '', 0 # look for {: or {! or {. or {[ or {} start, end, prev_end = 0, 0, 0 for match in _pos_farg_re.finditer(fstr): start, end, group = match.start(), match.end(), match.group() if prev_end < start: ret += fstr[prev_end:start] prev_end = end if group == '{{' or group == '}}': ret += group continue ret += '{%s%s' % (max_anon, group[1:]) max_anon += 1 ret += fstr[prev_end:] return ret # This approach is hardly exhaustive but it works for most builtins _INTCHARS = 'bcdoxXn' _FLOATCHARS = 'eEfFgGn%' _TYPE_MAP = dict([(x, int) for x in _INTCHARS] + [(x, float) for x in _FLOATCHARS]) _TYPE_MAP['s'] = str def get_format_args(fstr): """ Turn a format string into two lists of arguments referenced by the format string. One is positional arguments, and the other is named arguments. Each element of the list includes the name and the nominal type of the field. # >>> get_format_args("{noun} is {1:d} years old{punct}") # ([(1, <type 'int'>)], [('noun', <type 'str'>), ('punct', <type 'str'>)]) # XXX: Py3k >>> get_format_args("{noun} is {1:d} years old{punct}") == \ ([(1, int)], [('noun', str), ('punct', str)]) True """ # TODO: memoize formatter = Formatter() fargs, fkwargs, _dedup = [], [], set() def _add_arg(argname, type_char='s'): if argname not in _dedup: _dedup.add(argname) argtype = _TYPE_MAP.get(type_char, str) # TODO: unicode try: fargs.append((int(argname), argtype)) except ValueError: fkwargs.append((argname, argtype)) for lit, fname, fspec, conv in formatter.parse(fstr): if fname is not None: type_char = fspec[-1:] fname_list = re.split('[.[]', fname) if len(fname_list) > 1: raise ValueError('encountered compound format arg: %r' % fname) try: base_fname = fname_list[0] assert base_fname except (IndexError, AssertionError): raise ValueError('encountered anonymous positional argument') _add_arg(fname, type_char) for sublit, subfname, _, _ in formatter.parse(fspec): # TODO: positional and anon args not allowed here. if subfname is not None: _add_arg(subfname) return fargs, fkwargs def tokenize_format_str(fstr, resolve_pos=True): """Takes a format string, turns it into a list of alternating string literals and :class:`BaseFormatField` tokens. By default, also infers anonymous positional references into explict, numbered positional references. To disable this behavior set *resolve_pos* to ``False``. """ ret = [] if resolve_pos: fstr = infer_positional_format_args(fstr) formatter = Formatter() for lit, fname, fspec, conv in formatter.parse(fstr): if lit: ret.append(lit) if fname is None: continue ret.append(BaseFormatField(fname, fspec, conv)) return ret class BaseFormatField(object): """A class representing a reference to an argument inside of a bracket-style format string. For instance, in ``"{greeting}, world!"``, there is a field named "greeting". These fields can have many options applied to them. See the Python docs on `Format String Syntax`_ for the full details. .. _Format String Syntax: https://docs.python.org/2/library/string.html#string-formatting """ def __init__(self, fname, fspec='', conv=None): self.set_fname(fname) self.set_fspec(fspec) self.set_conv(conv) def set_fname(self, fname): "Set the field name." path_list = re.split('[.[]', fname) # TODO self.base_name = path_list[0] self.fname = fname self.subpath = path_list[1:] self.is_positional = not self.base_name or self.base_name.isdigit() def set_fspec(self, fspec): "Set the field spec." fspec = fspec or '' subfields = [] for sublit, subfname, _, _ in Formatter().parse(fspec): if subfname is not None: subfields.append(subfname) self.subfields = subfields self.fspec = fspec self.type_char = fspec[-1:] self.type_func = _TYPE_MAP.get(self.type_char, str) def set_conv(self, conv): """There are only two built-in converters: ``s`` and ``r``. They are somewhat rare and appearlike ``"{ref!r}"``.""" # TODO self.conv = conv self.conv_func = None # TODO @property def fstr(self): "The current state of the field in string format." return construct_format_field_str(self.fname, self.fspec, self.conv) def __repr__(self): cn = self.__class__.__name__ args = [self.fname] if self.conv is not None: args.extend([self.fspec, self.conv]) elif self.fspec != '': args.append(self.fspec) args_repr = ', '.join([repr(a) for a in args]) return '%s(%s)' % (cn, args_repr) def __str__(self): return self.fstr _UNSET = object() class DeferredValue(object): """:class:`DeferredValue` is a wrapper type, used to defer computing values which would otherwise be expensive to stringify and format. This is most valuable in areas like logging, where one would not want to waste time formatting a value for a log message which will subsequently be filtered because the message's log level was DEBUG and the logger was set to only emit CRITICAL messages. The :class:``DeferredValue`` is initialized with a callable that takes no arguments and returns the value, which can be of any type. By default DeferredValue only calls that callable once, and future references will get a cached value. This behavior can be disabled by setting *cache_value* to ``False``. Args: func (function): A callable that takes no arguments and computes the value being represented. cache_value (bool): Whether subsequent usages will call *func* again. Defaults to ``True``. >>> import sys >>> dv = DeferredValue(lambda: len(sys._current_frames())) >>> output = "works great in all {0} threads!".format(dv) PROTIP: To keep lines shorter, use: ``from formatutils import DeferredValue as DV`` """ def __init__(self, func, cache_value=True): self.func = func self.cache_value = True self._value = _UNSET def get_value(self): """Computes, optionally caches, and returns the value of the *func*. If ``get_value()`` has been called before, a cached value may be returned depending on the *cache_value* option passed to the constructor. """ if self._value is not _UNSET and self.cache_value: value = self._value else: value = self.func() if self.cache_value: self._value = value return value def __int__(self): return int(self.get_value()) def __float__(self): return float(self.get_value()) def __str__(self): return str(self.get_value()) def __unicode__(self): return unicode(self.get_value()) def __repr__(self): return repr(self.get_value()) def __format__(self, fmt): value = self.get_value() pt = fmt[-1:] # presentation type type_conv = _TYPE_MAP.get(pt, str) try: return value.__format__(fmt) except (ValueError, TypeError): # TODO: this may be overkill return type_conv(value).__format__(fmt) # end formatutils.py
bsd-3-clause
5,633,073,641,725,229,000
33.340426
93
0.610816
false
3.842857
false
false
false
iandees/all-the-places
locations/spiders/sunloan.py
1
2377
# -*- coding: utf-8 -*- import scrapy import json import re from locations.items import GeojsonPointItem DAYS={ 'Monday':'Mo', 'Tuesday':'Tu', 'Wednesday':'We', 'Friday':'Fr', 'Thursday':'Th', 'Saturday':'Sa', 'Sunday':'Su', } class SunLoanSpider(scrapy.Spider): name = "sunloan" allowed_domains = ["sunloan.com"] start_urls = ( 'https://www.sunloan.com/locations/', ) download_delay = 0.5 def parse(self, response): urls = response.xpath('//div[@id="custom-locations-2"]//div[@class="location-box"]/div/p/strong/a/@href').extract() for url in urls: yield scrapy.Request(response.urljoin(url), callback=self.parse_store) def parse_store(self, response): try: data = response.xpath('//script[contains(text(),"latitude")]/text()').extract_first() data = json.loads(data) except TypeError: return except json.JSONDecodeError: data = data.replace('"hasMap": \r\n', '') data = json.loads(data) if not data: return properties = { 'lat' : float(data['geo']['latitude']), 'lon' : float(data['geo']['longitude']), 'website' : response.url, 'ref' : response.url, 'addr_full' : data['address']['streetAddress'], 'city' : data['address']['addressLocality'], 'state' : data['address']['addressRegion'], 'postcode' : data['address']['postalCode'], 'country' : 'US', 'name' : data['name'], } try: hours = data['openingHours'] if hours: properties['opening_hours'] = hours except: pass yield GeojsonPointItem(**properties) # yield GeojsonPointItem( # lat=float(data['geo']['latitude']), # lon=float(data['geo']['longitude']), # website=response.url, # ref=response.url, # #opening_hours=data['openingHours'], # addr_full=data['address']['streetAddress'], # city=data['address']['addressLocality'], # state=data['address']['addressRegion'], # postcode=data['address']['postalCode'], # country='US', # name=data['name'], # )
mit
2,616,339,130,988,153,000
27.987805
123
0.519983
false
3.90312
false
false
false
PiaBianca/PyMaster
pymasterlib/ask.py
1
1995
# PyMaster # Copyright (C) 2014, 2015 FreedomOfRestriction <FreedomOfRestriction@openmailbox.org> # # 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/>. import pymasterlib as lib from pymasterlib.constants import * def load_text(ID): return lib.message.load_text("ask", ID) def what(): m = load_text("ask_what") c = [load_text("choice_rules"), load_text("choice_chore"), load_text("choice_punishments"), load_text("choice_nothing")] choice = lib.message.get_choice(m, c, len(c) - 1) if choice == 0: lib.scripts.show_rules() elif choice == 1: chore() elif choice == 2: punishments() def chore(): if lib.slave.queued_chore is not None: lib.message.show(lib.slave.queued_chore["text"]) else: lib.message.show(load_text("no_chore")) def punishments(): lib.slave.forget() punishments_ = [] for i in lib.slave.misdeeds: for misdeed in lib.slave.misdeeds[i]: if not misdeed["punished"] and misdeed["punishment"] is not None: punishments_.append(misdeed["punishment"]) if punishments_: if len(punishments_) > 1: m = load_text("punishments").format(len(punishments_)) lib.message.show(m) for punishment in punishments_: lib.message.show(punishment["text"]) else: lib.message.show(load_text("no_punishments"))
gpl-3.0
-6,075,815,982,666,345,000
30.666667
86
0.66416
false
3.421955
false
false
false
dark1729dragon/pixutils
pixutils/vplayer/PlayImgs.py
1
2169
from __future__ import nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals from .videoutils import * def default_labeller(x): try: return int(x.split('_')[1].split('.')[0]) except: try: return int(basename(x).split('_')[1].split('.')[0]) except: return 0 class Im2Video(): ''' def labeller(impath): return impath.replace('.jpg','').split('_')[1] vpath = join(dbpath, r'videoimgs/*.*') cam = Imgs2Video(vpath, labeller) video = Player(cam) cam = ThreadIt(cam) imshow = win(video) for fno, img in video.play(): imshow('show_video', img, 1) ''' def __init__(self, opaths, labeller=None): labeller = labeller or default_labeller if type(opaths) not in (list, tuple): paths = glob(opaths) else: paths = opaths if not paths: raise Exception('No file found in %s' % opaths) paths = [(int(labeller(path)), path) for path in paths] self.paths = sorted(paths, key=lambda x: x[0]) self.frameno, self.paths = list(zip(*self.paths)) self.row, self.col = cv2.imread(self.paths[0]).shape[:2] self.index = -1 def release(self): pass def read(self): self.index += 1 if len(self.paths) <= self.index: return False, None try: return True, cv2.imread(self.paths[self.index]) except: return None, None def get(self, i): if i == 3: return self.col elif i == 4: return self.row elif i == 5: return 30 elif i == 7: return len(self.paths) def set(self, i, start_frame): self.index += (start_frame - 1) def GetFeed(vpath, *a, **kw): if type(vpath) == int: return 'stream', cv2.VideoCapture(vpath) elif type(vpath) in (list,tuple) or '*' in vpath: return 'imgs', Im2Video(vpath, *a, **kw) else: assert exists(vpath), 'Video File missing: %s' % vpath return 'video', cv2.VideoCapture(vpath)
bsd-2-clause
8,355,155,217,002,081,000
27.552632
125
0.545874
false
3.464856
false
false
false
jonathf/chaospy
chaospy/distributions/baseclass/operator.py
1
2655
"""Operator transformation.""" import numpy import chaospy from ..baseclass import Distribution class OperatorDistribution(Distribution): """Operator transformation.""" def __init__(self, left, right, exclusion=None, repr_args=None): if not isinstance(left, Distribution): left = numpy.atleast_1d(left) if left.ndim > 1: raise chaospy.UnsupportedFeature( "distribution operators limited to at-most 1D arrays.") if not isinstance(right, Distribution): right = numpy.atleast_1d(right) if right.ndim > 1: raise chaospy.UnsupportedFeature( "distribution operators limited to at-most 1D arrays.") dependencies, parameters, rotation = chaospy.declare_dependencies( distribution=self, parameters=dict(left=left, right=right), is_operator=True, ) super(OperatorDistribution, self).__init__( parameters=parameters, dependencies=dependencies, exclusion=exclusion, repr_args=repr_args, ) self._cache_copy = {} self._lower_cache = {} self._upper_cache = {} def get_parameters(self, idx, cache, assert_numerical=True): parameters = super(OperatorDistribution, self).get_parameters( idx, cache, assert_numerical=assert_numerical) assert set(parameters) == {"cache", "left", "right", "idx"} if isinstance(parameters["left"], Distribution): parameters["left"] = parameters["left"]._get_cache(idx, cache=parameters["cache"], get=0) elif len(parameters["left"]) > 1 and idx is not None: parameters["left"] = parameters["left"][idx] if isinstance(parameters["right"], Distribution): parameters["right"] = parameters["right"]._get_cache(idx, cache=parameters["cache"], get=0) elif len(parameters["right"]) > 1 and idx is not None: parameters["right"] = parameters["right"][idx] if assert_numerical: assert (not isinstance(parameters["left"], Distribution) or not isinstance(parameters["right"], Distribution)) if cache is not self._cache_copy: self._cache_copy = cache self._lower_cache = {} self._upper_cache = {} if idx is None: del parameters["idx"] return parameters def _cache(self, idx, cache, get): assert get == 0 parameters = self.get_parameters(idx, cache) return self._operator(parameters["left"], parameters["right"])
mit
8,029,556,839,526,679,000
39.227273
103
0.59548
false
4.561856
false
false
false
usingnamespace/pyramid_authsanity
src/pyramid_authsanity/policy.py
1
6144
import base64 import os from pyramid.authorization import Authenticated, Everyone from pyramid.interfaces import IAuthenticationPolicy, IDebugLogger from zope.interface import implementer from .util import _find_services, _session_registered, add_vary_callback def _clean_principal(princid): """Utility function that cleans up the passed in principal This can easily also be extended for example to make sure that certain usernames are automatically off-limits. """ if princid in (Authenticated, Everyone): princid = None return princid _marker = object() @implementer(IAuthenticationPolicy) class AuthServicePolicy(object): def _log(self, msg, methodname, request): logger = request.registry.queryUtility(IDebugLogger) if logger: cls = self.__class__ classname = cls.__module__ + "." + cls.__name__ methodname = classname + "." + methodname logger.debug(methodname + ": " + msg) _find_services = staticmethod(_find_services) # Testing _session_registered = staticmethod(_session_registered) # Testing _have_session = _marker def __init__(self, debug=False): self.debug = debug def unauthenticated_userid(self, request): """ We do not allow the unauthenticated userid to be used. """ def authenticated_userid(self, request): """ Returns the authenticated userid for this request. """ debug = self.debug (sourcesvc, authsvc) = self._find_services(request) request.add_response_callback(add_vary_callback(sourcesvc.vary)) try: userid = authsvc.userid() except Exception: debug and self._log( "authentication has not yet been completed", "authenticated_userid", request, ) (principal, ticket) = sourcesvc.get_value() debug and self._log( "source service provided information: (principal: %r, ticket: %r)" % (principal, ticket), "authenticated_userid", request, ) # Verify the principal and the ticket, even if None authsvc.verify_ticket(principal, ticket) try: # This should now return None or the userid userid = authsvc.userid() except Exception: userid = None debug and self._log( "authenticated_userid returning: %r" % (userid,), "authenticated_userid", request, ) return userid def effective_principals(self, request): """ A list of effective principals derived from request. """ debug = self.debug effective_principals = [Everyone] userid = self.authenticated_userid(request) (_, authsvc) = self._find_services(request) if userid is None: debug and self._log( "authenticated_userid returned %r; returning %r" % (userid, effective_principals), "effective_principals", request, ) return effective_principals if _clean_principal(userid) is None: debug and self._log( ( "authenticated_userid returned disallowed %r; returning %r " "as if it was None" % (userid, effective_principals) ), "effective_principals", request, ) return effective_principals effective_principals.append(Authenticated) effective_principals.append(userid) effective_principals.extend(authsvc.groups()) debug and self._log( "returning effective principals: %r" % (effective_principals,), "effective_principals", request, ) return effective_principals def remember(self, request, principal, **kw): """ Returns a list of headers that are to be set from the source service. """ debug = self.debug if self._have_session is _marker: self._have_session = self._session_registered(request) prev_userid = self.authenticated_userid(request) (sourcesvc, authsvc) = self._find_services(request) request.add_response_callback(add_vary_callback(sourcesvc.vary)) value = {} value["principal"] = principal value["ticket"] = ticket = ( base64.urlsafe_b64encode(os.urandom(32)).rstrip(b"=").decode("ascii") ) debug and self._log( "Remember principal: %r, ticket: %r" % (principal, ticket), "remember", request, ) authsvc.add_ticket(principal, ticket) # Clear the previous session if self._have_session: if prev_userid != principal: request.session.invalidate() else: # We are logging in the same user that is already logged in, we # still want to generate a new session, but we can keep the # existing data data = dict(request.session.items()) request.session.invalidate() request.session.update(data) request.session.new_csrf_token() return sourcesvc.headers_remember([principal, ticket]) def forget(self, request): """ A list of headers which will delete appropriate cookies.""" debug = self.debug if self._have_session is _marker: self._have_session = self._session_registered(request) (sourcesvc, authsvc) = self._find_services(request) request.add_response_callback(add_vary_callback(sourcesvc.vary)) (_, ticket) = sourcesvc.get_value() debug and self._log("Forgetting ticket: %r" % (ticket,), "forget", request) authsvc.remove_ticket(ticket) # Clear the session by invalidating it if self._have_session: request.session.invalidate() return sourcesvc.headers_forget()
isc
-7,210,039,205,602,359,000
32.032258
85
0.585938
false
4.578241
false
false
false
CroceRossaItaliana/jorvik
formazione/migrations/0035_auto_20190510_1149.py
1
2215
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2019-05-10 11:49 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('formazione', '0034_auto_20190408_1047'), ] operations = [ migrations.CreateModel( name='RelazioneCorso', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('creazione', models.DateTimeField(db_index=True, default=django.utils.timezone.now)), ('ultima_modifica', models.DateTimeField(auto_now=True, db_index=True)), ('note_esplicative', models.TextField(help_text='note esplicative in relazione ai cambiamenti effettuati rispetto alla programmazione approvata in fase di pianificazione iniziale del corso.', verbose_name='Note esplicative')), ('raggiungimento_obiettivi', models.TextField(help_text="Analisi sul raggiungimento degli obiettivi del corso (generali rispetto all'evento e specifici di apprendimento).", verbose_name='Raggiungimento degli obiettivi del corso')), ('annotazioni_corsisti', models.TextField(verbose_name='Annotazioni relative alla partecipazione dei corsisti')), ('annotazioni_risorse', models.TextField(help_text='Annotazioni relative a risorse e competenze di particolare rilevanza emerse durante il percorso formativo')), ('annotazioni_organizzazione_struttura', models.TextField(help_text="Annotazioni e segnalazioni sull'organizzazione e la logistica e della struttura ospitante il corso")), ('descrizione_attivita', models.TextField(help_text='Descrizione delle eventuali attività di tirocinio/affiancamento con indicazione dei Tutor')), ('corso', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='formazione.CorsoBase')), ], options={ 'verbose_name': 'Relazione del Direttore', 'verbose_name_plural': 'Relazioni dei Direttori', }, ), ]
gpl-3.0
6,304,392,364,393,148,000
60.5
247
0.681572
false
3.432558
false
false
false
kgullikson88/General
Analyze_CCF.py
1
9048
""" This is a module to read in an HDF5 file with CCFs. Use this to determine the best parameters, and plot the best CCF for each star/date """ from collections import defaultdict import logging import h5py import numpy as np import pandas as pd from scipy.interpolate import InterpolatedUnivariateSpline as spline class CCF_Interface(object): def __init__(self, filename, vel=np.arange(-900, 900, 1)): self.hdf5 = h5py.File(filename, 'r') self.velocities = vel self._df = None def __getitem__(self, path): return self.hdf5[path] def list_stars(self, print2screen=False): """ List the stars available in the HDF5 file, and the dates available for each :return: A list of the stars """ if print2screen: for star in sorted(self.hdf5.keys()): print(star) for date in sorted(self.hdf5[star].keys()): print('\t{}'.format(date)) return sorted(self.hdf5.keys()) def list_dates(self, star, print2screen=False): """ List the dates available for the given star :param star: The name of the star :return: A list of dates the star was observed """ if print2screen: for date in sorted(self.hdf5[star].keys()): print(date) return sorted(self.hdf5[star].keys()) def load_cache(self, addmode='simple'): """ Read in the whole HDF5 file. This will take a while and take a few Gb of memory, but will speed things up considerably :keyword addmode: The way the individual CCFs were added. Options are: - 'simple' - 'ml' - 'all' (saves all addmodes) """ self._df = self._compile_data(addmode=addmode) def _compile_data(self, starname=None, date=None, addmode='simple', read_ccf=True): """ Private function. This reads in all the datasets for the given star and date :param starname: the name of the star. Must be in self.hdf5 :param date: The date to search. Must be in self.hdf5[star] :keyword addmode: The way the individual CCFs were added. Options are: - 'simple' - 'ml' - 'all' (saves all addmodes) :return: a pandas DataFrame with the columns: - star - date - temperature - log(g) - [Fe/H] - vsini - addmode - rv (at maximum CCF value) - CCF height (maximum) """ if starname is None: df_list = [] star_list = self.list_stars() for star in star_list: date_list = self.list_dates(star) for date in date_list: logging.debug('Reading in metadata for star {}, date {}'.format(star, date)) df_list.append(self._compile_data(star, date, addmode=addmode, read_ccf=read_ccf)) return pd.concat(df_list, ignore_index=True) elif starname is not None and date is None: df_list = [] date_list = self.list_dates(starname) for date in date_list: logging.debug('Reading in metadata for date {}'.format(date)) df_list.append(self._compile_data(starname, date, addmode=addmode, read_ccf=read_ccf)) return pd.concat(df_list, ignore_index=True) else: if self._df is not None: return self._df.loc[(self._df['Star'] == starname) & (self._df['Date'] == date)].copy() #print('Stars: ', self.list_stars()) datasets = self.hdf5[starname][date].keys() data = defaultdict(list) for ds_name, ds in self.hdf5[starname][date].iteritems(): # in datasets: #ds = self.hdf5[starname][date][ds_name] try: am = ds.attrs['addmode'] if addmode == 'all' or addmode == am: data['T'].append(ds.attrs['T']) data['logg'].append(ds.attrs['logg']) data['[Fe/H]'].append(ds.attrs['[Fe/H]']) data['vsini'].append(ds.attrs['vsini']) data['addmode'].append(am) data['name'].append(ds.name) try: data['ccf_max'].append(ds.attrs['ccf_max']) data['vel_max'].append(ds.attrs['vel_max']) except KeyError: vel, corr = ds.value idx = np.argmax(corr) data['ccf_max'].append(corr[idx]) data['vel_max'].append(vel[idx]) if read_ccf: v = ds.value vel, corr = v[0], v[1] sorter = np.argsort(vel) fcn = spline(vel[sorter], corr[sorter]) data['ccf'].append(fcn(self.velocities)) except: raise IOError('Something weird happened with dataset {}!'.format(ds.name)) data['Star'] = [starname] * len(data['T']) data['Date'] = [date] * len(data['T']) df = pd.DataFrame(data=data) return df def get_temperature_run(self, starname=None, date=None, df=None): """ Return the maximum ccf height for each temperature. Either starname AND date, or df must be given :param starname: The name of the star :param date: The date of the observation :param df: Input dataframe, such as from _compile_data. Overrides starname and date, if given :return: a pandas DataFrame with all the best parameters for each temperature """ # Get the dataframe if it isn't given if df is None: if starname is None or date is None: raise ValueError('Must give either starname or date to get_temperature_run!') df = self._compile_data(starname, date) # Find the maximum CCF for each set of parameters fcn = lambda row: (np.max(row), self.velocities[np.argmax(row)]) vals = df['ccf'].map(fcn) df['ccf_max'] = vals.map(lambda l: l[0]) df['rv'] = vals.map(lambda l: l[1]) # Find the best parameters for each temperature d = defaultdict(list) temperatures = pd.unique(df['T']) for T in temperatures: good = df.loc[df['T'] == T] best = good.loc[good.ccf_max == good.ccf_max.max()] d['vsini'].append(best['vsini'].item()) d['logg'].append(best['logg'].item()) d['[Fe/H]'].append(best['[Fe/H]'].item()) d['rv'].append(best['rv'].item()) d['ccf_value'].append(best.ccf_max.item()) d['T'].append(T) d['metal'].append(best['[Fe/H]'].item()) return pd.DataFrame(data=d) def get_ccf(self, params, df=None): """ Get the ccf with the given parameters. A dataframe can be given to speed things up :param params: All the parameters necessary to define a single ccf. This should be a python dictionary with the keys: - 'starname': The name of the star. Try self.list_stars() for the options. - 'date': The UT date of the observations. Try self.list_dates() for the options. - 'T': temperature of the model - 'logg': the log(g) of the model - 'vsini': the vsini by which the model was broadened before correlation - '[Fe/H]': the metallicity of the model - 'addmode': The way the order CCFs were added to make a total one. Can be: - 'simple' - 'ml' - 'weighted' - 'dc' :param df: a pandas DataFrame such as outputted by _compile_data :return: a pandas DataFrame with columns of velocity and CCF power """ if df is None: try: df = self._compile_data(params['starname'], params['date']) except KeyError: raise KeyError('Must give get_ccf params with starname and date keywords, if df is not given!') Tvals = df['T'].unique() T = Tvals[np.argmin(abs(Tvals - params['T']))] good = df.loc[(df['T'] == T) & (df.logg == params['logg']) & (df.vsini == params['vsini']) \ & (df['[Fe/H]'] == params['[Fe/H]']) & (df.addmode == params['addmode'])] return pd.DataFrame(data={'velocity': self.velocities, 'CCF': good['ccf'].item()})
gpl-3.0
5,668,383,523,431,874,000
42.710145
126
0.513263
false
4.11647
false
false
false
clausqr/HTPC-Manager
modules/qbittorrent.py
1
12490
#!/usr/bin/env python # -*- coding: utf-8 -*- import htpc import cherrypy import json import logging import time import math from cherrypy.lib.auth2 import require from htpc.helpers import striphttp, sizeof import requests from requests.auth import HTTPDigestAuth class Qbittorrent(object): session = requests.Session() def __init__(self): self.logger = logging.getLogger('modules.qbittorrent') self.newapi = False self.authenticated = False self.testapi = None htpc.MODULES.append({ 'name': 'qBittorrent', 'id': 'qbittorrent', 'test': htpc.WEBDIR + 'qbittorrent/ping', 'fields': [ {'type': 'bool', 'label': 'Enable', 'name': 'qbittorrent_enable'}, {'type': 'text', 'label': 'Menu name', 'name': 'qbittorrent_name'}, {'type': 'text', 'label': 'IP / Host', 'placeholder': 'localhost', 'name': 'qbittorrent_host'}, {'type': 'text', 'label': 'Port', 'placeholder': '8080', 'name': 'qbittorrent_port'}, {'type': 'text', 'label': 'Username', 'name': 'qbittorrent_username'}, {'type': 'password', 'label': 'Password', 'name': 'qbittorrent_password'}, {'type': 'bool', 'label': 'Use SSL', 'name': 'qbittorrent_ssl'}, {'type': 'text', 'label': 'Reverse proxy link', 'placeholder': '', 'desc': 'Reverse proxy link ex: https://qbt.domain.com', 'name': 'qbittorrent_reverse_proxy_link'}, ] }) @cherrypy.expose() @require() def index(self): return htpc.LOOKUP.get_template('qbittorrent.html').render(scriptname='qbittorrent', webinterface=self.webinterface()) def webinterface(self): host = striphttp(htpc.settings.get('qbittorrent_host', '')) port = htpc.settings.get('qbittorrent_port', '') ssl = 's' if htpc.settings.get('qbittorrent_ssl', 0) else '' url = 'http%s://%s:%s/' % (ssl, host, port) if htpc.settings.get('qbittorrent_reverse_proxy_link'): url = htpc.settings.get('qbittorrent_reverse_proxy_link') return url def qbturl(self): host = striphttp(htpc.settings.get('qbittorrent_host', '')) port = htpc.settings.get('qbittorrent_port', '') ssl = 's' if htpc.settings.get('qbittorrent_ssl', 0) else '' url = 'http%s://%s:%s/' % (ssl, host, port) return url @cherrypy.expose() @require() def login(self): self.logger.debug('Trying to login to qbittorrent') try: d = {'username': htpc.settings.get('qbittorrent_username', ''), 'password': htpc.settings.get('qbittorrent_password', '') } # F33d da cookie monster r = self.session.post(self.qbturl() + 'login', data=d, verify=False, timeout=5) if r.content == 'Ok.': self.logger.debug('Successfully logged in with new api') self.authenticated = True self.newapi = True else: self.logger.error('Check your username and password') return r.content except Exception as e: self.logger.error('Failed to auth with new api %s' % e) return def _fetch(self, u, post=False, params={}, data=None): host = striphttp(htpc.settings.get('qbittorrent_host', '')) port = htpc.settings.get('qbittorrent_port', '') ssl = 's' if htpc.settings.get('qbittorrent_ssl') else '' url = 'http%s://%s:%s/' % (ssl, host, port) username = htpc.settings.get('qbittorrent_username', '') password = htpc.settings.get('qbittorrent_password', '') url += u if self.testapi is None: self.ping() if self.newapi: if self.authenticated is False: self.login() if post: if self.newapi: r = self.session.post(url, data=data, verify=False, timeout=8) else: r = self.session.post(url, data=data, verify=False, timeout=8, auth=HTTPDigestAuth(username, password)) else: if self.newapi: r = self.session.get(url, verify=False, timeout=8) else: r = self.session.get(url, verify=False, timeout=8, auth=HTTPDigestAuth(username, password)) return r @cherrypy.expose() @require() @cherrypy.tools.json_out() def fetch(self): try: if self.newapi: result = self._fetch('query/torrents?filter=all&sort=size&reverse=false') torrents = result.json() l = [] for torrent in torrents: t = {} for k, v in torrent.items(): t[k] = v if k == 'size': t['size'] = sizeof(int(v)) if k == 'eta': eta = time.strftime('%H:%M:%S', time.gmtime(v)) if eta == '00:00:00': eta = u'\u221E' t['eta'] = eta if k == 'ratio': t['ratio'] = math.ceil(v) l.append(t) return l else: result = self._fetch('json/torrents') # r.json() does not like the infinity return json.loads(result.content) except Exception as e: self.logger.error("Couldn't get torrents %s" % e) @cherrypy.expose() @require() @cherrypy.tools.json_out() def get_speed(self): ''' Get total download and upload speed ''' try: d = {} if not self.newapi: result = self._fetch('json/transferInfo/') result = result.json() speeddown = result['dl_info'] speedup = result['up_info'] list_of_down = speeddown.split() list_of_up = speedup.split() ds = list_of_down[1] + ' ' + list_of_down[2] dlstat = list_of_down[5] + ' ' + list_of_down[6] us = list_of_up[1] + ' ' + list_of_up[2] ulstat = list_of_down[5] + ' ' + list_of_down[6] d = { 'qbittorrent_speed_down': ds, 'qbittorrent_speed_up': us, 'qbittorrent_total_dl': dlstat, 'qbittorrent_total_ul': ulstat } else: # new api stuff result = self._fetch('query/transferInfo') result = result.json() d = { 'qbittorrent_speed_down': sizeof(result['dl_info_speed']), 'qbittorrent_speed_up': sizeof(result['up_info_speed']), 'qbittorrent_total_dl': sizeof(result['dl_info_data']), 'qbittorrent_total_ul': sizeof(result['up_info_data']) } return d except Exception as e: self.logger.error("Couldn't get total download and uploads speed %s" % e) def get_global_dl_limit(self): try: result = self._fetch('command/getGlobalDlLimit/') speed = int(result.content) speed /= 1024 return speed except Exception as e: self.logger.error("Couldn't get global download limit %s" % e) def get_global_ul_limit(self): try: result = self._fetch('command/getGlobalUpLimit') speed = int(result.content) speed /= 1024 return speed except Exception as e: self.logger.error("Couldn't get global upload limit %s" % e) @cherrypy.expose() @require() @cherrypy.tools.json_out() def get_global_limit(self): try: d = {} d['dl_limit'] = self.get_global_dl_limit() d['ul_limit'] = self.get_global_ul_limit() return d except Exception as e: self.logger.debug("Couldn't get global upload and download limits %s" % e) @cherrypy.expose() @require() def command(self, cmd=None, hash=None, name=None, dlurl=None): ''' Handles pause, resume, delete singel torrents ''' try: self.logger.debug('%s %s' % (cmd, name)) data = {} if cmd == 'delete': data['hashes'] = hash elif cmd == 'download': data['urls'] = dlurl elif cmd == 'resumeall' or cmd == 'pauseall': # this does not work, bug in qbt see # https://github.com/qbittorrent/qBittorrent/issues/3016 if self.newapi: cmd = cmd[:-3] + 'All' else: data['hash'] = hash url = 'command/%s' % cmd # data is form encode.. r = self._fetch(url, post=True, data=data) return r.content except Exception as e: self.logger.error('Failed at %s %s %s %s' % (cmd, name, hash, e)) @cherrypy.expose() @require() def to_client(self, link, torrentname, **kwargs): ''' Is used by torrent search ''' try: url = 'command/download/' data = {} data['urls'] = link return self._fetch(url, data=data, post=True) self.logger.info('%s %s is sendt to qBittorrent' % (torrentname, link)) except Exception as e: self.logger.error('Failed to send %s %s to qBittorrent %s' % (link, torrentname, e)) @cherrypy.expose() @require() def set_speedlimit(self, type=None, speed=None): ''' Sets global upload and download speed ''' try: self.logger.debug('Setting %s to %s' % (type, speed)) speed = int(speed) if speed == 0: speed = 0 else: speed = speed * 1024 url = 'command/' + type + '/' data = {} data['limit'] = speed r = self._fetch(url, data=data, post=True) return r.content except Exception as e: self.logger.error('Failed to set %s to %s %s' % (type, speed, e)) @cherrypy.expose() @require() @cherrypy.tools.json_out() def ping(self, qbittorrent_host='', qbittorrent_port='', qbittorrent_username='', qbittorrent_password='', qbittorrent_ssl=False, **kw): self.logger.debug('Trying to connect to qBittorret') host = qbittorrent_host or htpc.settings.get('qbittorrent_host') port = qbittorrent_port or htpc.settings.get('qbittorrent_port') username = qbittorrent_username or htpc.settings.get('qbittorrent_username') password = qbittorrent_password or htpc.settings.get('qbittorrent_password') ssl = 's' if qbittorrent_ssl or htpc.settings.get('qbittorrent_ssl') else '' url = 'http%s://%s:%s/' % (ssl, host, port) self.newapi = False self.authenticated = False try: # We assume that its atleast 3.2 if this works. r = requests.get(url + 'version/api', timeout=8, verify=False) self.logger.debug('Trying to connect with new API %s' % r.url) # Old api returns a empty page if r.content != '' and r.ok: self.newapi = r.content self.testapi = True return r.content else: raise requests.ConnectionError except Exception as e: self.logger.debug('Failed to figure out what api version, trying old API') try: r = requests.post(url + 'json/torrents', auth=HTTPDigestAuth(username, password), timeout=10, verify=False) if r.ok: self.logger.debug('Old API works %s' % r.url) # Disable new api stuff self.testapi = True self.newapi = False self.authenticated = False except Exception as e: self.newapi = False self.authenticated = False self.logger.debug('Failed to contact qBittorrent via old and newapi') self.logger.error('Cant contact qBittorrent, check you settings and try again %s' % e)
mit
-863,452,485,712,000,900
36.507508
182
0.517374
false
3.945041
false
false
false
SpaceGroupUCL/qgisSpaceSyntaxToolkit
esstoolkit/external/networkx/algorithms/swap.py
4
9829
"""Swap edges in a graph. """ import math from networkx.utils import py_random_state import networkx as nx __all__ = ["double_edge_swap", "connected_double_edge_swap"] @py_random_state(3) def double_edge_swap(G, nswap=1, max_tries=100, seed=None): """Swap two edges in the graph while keeping the node degrees fixed. A double-edge swap removes two randomly chosen edges u-v and x-y and creates the new edges u-x and v-y:: u--v u v becomes | | x--y x y If either the edge u-x or v-y already exist no swap is performed and another attempt is made to find a suitable edge pair. Parameters ---------- G : graph An undirected graph nswap : integer (optional, default=1) Number of double-edge swaps to perform max_tries : integer (optional) Maximum number of attempts to swap edges seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- G : graph The graph after double edge swaps. Notes ----- Does not enforce any connectivity constraints. The graph G is modified in place. """ if G.is_directed(): raise nx.NetworkXError("double_edge_swap() not defined for directed graphs.") if nswap > max_tries: raise nx.NetworkXError("Number of swaps > number of tries allowed.") if len(G) < 4: raise nx.NetworkXError("Graph has less than four nodes.") # Instead of choosing uniformly at random from a generated edge list, # this algorithm chooses nonuniformly from the set of nodes with # probability weighted by degree. n = 0 swapcount = 0 keys, degrees = zip(*G.degree()) # keys, degree cdf = nx.utils.cumulative_distribution(degrees) # cdf of degree discrete_sequence = nx.utils.discrete_sequence while swapcount < nswap: # if random.random() < 0.5: continue # trick to avoid periodicities? # pick two random edges without creating edge list # choose source node indices from discrete distribution (ui, xi) = discrete_sequence(2, cdistribution=cdf, seed=seed) if ui == xi: continue # same source, skip u = keys[ui] # convert index to label x = keys[xi] # choose target uniformly from neighbors v = seed.choice(list(G[u])) y = seed.choice(list(G[x])) if v == y: continue # same target, skip if (x not in G[u]) and (y not in G[v]): # don't create parallel edges G.add_edge(u, x) G.add_edge(v, y) G.remove_edge(u, v) G.remove_edge(x, y) swapcount += 1 if n >= max_tries: e = ( f"Maximum number of swap attempts ({n}) exceeded " f"before desired swaps achieved ({nswap})." ) raise nx.NetworkXAlgorithmError(e) n += 1 return G @py_random_state(3) def connected_double_edge_swap(G, nswap=1, _window_threshold=3, seed=None): """Attempts the specified number of double-edge swaps in the graph `G`. A double-edge swap removes two randomly chosen edges `(u, v)` and `(x, y)` and creates the new edges `(u, x)` and `(v, y)`:: u--v u v becomes | | x--y x y If either `(u, x)` or `(v, y)` already exist, then no swap is performed so the actual number of swapped edges is always *at most* `nswap`. Parameters ---------- G : graph An undirected graph nswap : integer (optional, default=1) Number of double-edge swaps to perform _window_threshold : integer The window size below which connectedness of the graph will be checked after each swap. The "window" in this function is a dynamically updated integer that represents the number of swap attempts to make before checking if the graph remains connected. It is an optimization used to decrease the running time of the algorithm in exchange for increased complexity of implementation. If the window size is below this threshold, then the algorithm checks after each swap if the graph remains connected by checking if there is a path joining the two nodes whose edge was just removed. If the window size is above this threshold, then the algorithm performs do all the swaps in the window and only then check if the graph is still connected. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- int The number of successful swaps Raises ------ NetworkXError If the input graph is not connected, or if the graph has fewer than four nodes. Notes ----- The initial graph `G` must be connected, and the resulting graph is connected. The graph `G` is modified in place. References ---------- .. [1] C. Gkantsidis and M. Mihail and E. Zegura, The Markov chain simulation method for generating connected power law random graphs, 2003. http://citeseer.ist.psu.edu/gkantsidis03markov.html """ if not nx.is_connected(G): raise nx.NetworkXError("Graph not connected") if len(G) < 4: raise nx.NetworkXError("Graph has less than four nodes.") n = 0 swapcount = 0 deg = G.degree() # Label key for nodes dk = list(n for n, d in G.degree()) cdf = nx.utils.cumulative_distribution(list(d for n, d in G.degree())) discrete_sequence = nx.utils.discrete_sequence window = 1 while n < nswap: wcount = 0 swapped = [] # If the window is small, we just check each time whether the graph is # connected by checking if the nodes that were just separated are still # connected. if window < _window_threshold: # This Boolean keeps track of whether there was a failure or not. fail = False while wcount < window and n < nswap: # Pick two random edges without creating the edge list. Choose # source nodes from the discrete degree distribution. (ui, xi) = discrete_sequence(2, cdistribution=cdf, seed=seed) # If the source nodes are the same, skip this pair. if ui == xi: continue # Convert an index to a node label. u = dk[ui] x = dk[xi] # Choose targets uniformly from neighbors. v = seed.choice(list(G.neighbors(u))) y = seed.choice(list(G.neighbors(x))) # If the target nodes are the same, skip this pair. if v == y: continue if x not in G[u] and y not in G[v]: G.remove_edge(u, v) G.remove_edge(x, y) G.add_edge(u, x) G.add_edge(v, y) swapped.append((u, v, x, y)) swapcount += 1 n += 1 # If G remains connected... if nx.has_path(G, u, v): wcount += 1 # Otherwise, undo the changes. else: G.add_edge(u, v) G.add_edge(x, y) G.remove_edge(u, x) G.remove_edge(v, y) swapcount -= 1 fail = True # If one of the swaps failed, reduce the window size. if fail: window = int(math.ceil(window / 2)) else: window += 1 # If the window is large, then there is a good chance that a bunch of # swaps will work. It's quicker to do all those swaps first and then # check if the graph remains connected. else: while wcount < window and n < nswap: # Pick two random edges without creating the edge list. Choose # source nodes from the discrete degree distribution. (ui, xi) = nx.utils.discrete_sequence(2, cdistribution=cdf) # If the source nodes are the same, skip this pair. if ui == xi: continue # Convert an index to a node label. u = dk[ui] x = dk[xi] # Choose targets uniformly from neighbors. v = seed.choice(list(G.neighbors(u))) y = seed.choice(list(G.neighbors(x))) # If the target nodes are the same, skip this pair. if v == y: continue if x not in G[u] and y not in G[v]: G.remove_edge(u, v) G.remove_edge(x, y) G.add_edge(u, x) G.add_edge(v, y) swapped.append((u, v, x, y)) swapcount += 1 n += 1 wcount += 1 # If the graph remains connected, increase the window size. if nx.is_connected(G): window += 1 # Otherwise, undo the changes from the previous window and decrease # the window size. else: while swapped: (u, v, x, y) = swapped.pop() G.add_edge(u, v) G.add_edge(x, y) G.remove_edge(u, x) G.remove_edge(v, y) swapcount -= 1 window = int(math.ceil(window / 2)) return swapcount
gpl-3.0
5,574,572,882,945,417,000
35.539033
85
0.550005
false
4.220266
false
false
false
durandj/ynot-django
ynot/django/themes/templatetags/breadcrumbs.py
1
2421
from django import template as django_template from django.template import defaulttags as django_defaulttags from django.utils import encoding as django_encoding # pylint: disable=invalid-name, too-few-public-methods register = django_template.Library() # pylint: disable=unused-argument @register.tag def breadcrumb(parser, token): """ Render breadcrumbs in the form of: {% breadcrumb 'Breadcrumb title' url %} """ return BreadcrumbNode(token.split_contents()[1:]) # pylint: enable=unused-argument @register.tag def breadcrumb_url(parser, token): """ Render breadcrumbs in the form of: {% breadcrumb 'Breadcrumb title' url args %} """ contents = token.split_contents() if len(contents) == 2: return breadcrumb(parser, token) # Shortcut to normal breadcrumbs title = contents.pop(1) token.contents = ' '.join(contents) url = django_defaulttags.url(parser, token) return UrlBreadcrumbNode(title, url) class BreadcrumbNode(django_template.Node): def __init__(self, args): self.args = [django_template.Variable(arg) for arg in args] def render(self, context): title = self.args[0].var if title.find('\'') == -1 and title.find('\"') == -1: try: val = self.args[0] title = val.resolve(context) except: title = '' else: title = django_encoding.smart_unicode(title.strip('\'').strip('\"')) url = None if len(self.args) > 1: val = self.args[1] try: url = val.resolve(context) except django_template.VariableDoesNotExist: url = None return render_breadcrumb(title, url = url) class UrlBreadcrumbNode(django_template.Node): def __init__(self, title, url_node): self.title = django_template.Variable(title) self.url_node = url_node def render(self, context): title = self.title.var if title.find('\'') == -1 and title.find('\"') == -1: try: val = self.title title = val.resolve(context) except: title = '' else: title = django_encoding.smart_unicode(title.strip('\'').strip('\"')) url = self.url_node.render(context) return render_breadcrumb(title, url = url) def render_breadcrumb(title, url = None): if url: breadcrumb_node = '<a href="{url}">{title}</a>'.format( title = title, url = url, ) else: breadcrumb_node = '<span>{title}</span>'.format(title = title) breadcrumb_node = '<span class="ynot-breadcrumb">{}</span>'.format(breadcrumb_node) return breadcrumb
mit
-5,690,095,699,108,651,000
24.21875
84
0.674515
false
3.030038
false
false
false
edx/edx-enterprise
enterprise/migrations/0111_pendingenterprisecustomeradminuser.py
1
3009
# Generated by Django 2.2.15 on 2020-09-09 14:31 import simple_history.models import django.db.models.deletion import django.utils.timezone from django.conf import settings from django.db import migrations, models import model_utils.fields class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('enterprise', '0110_add_default_contract_discount'), ] operations = [ migrations.CreateModel( name='HistoricalPendingEnterpriseCustomerAdminUser', fields=[ ('id', models.IntegerField(auto_created=True, blank=True, db_index=True, verbose_name='ID')), ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('user_email', models.EmailField(max_length=254)), ('history_id', models.AutoField(primary_key=True, serialize=False)), ('history_date', models.DateTimeField()), ('history_change_reason', models.CharField(max_length=100, null=True)), ('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)), ('enterprise_customer', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='enterprise.EnterpriseCustomer')), ('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)), ], options={ 'get_latest_by': 'history_date', 'verbose_name': 'historical pending enterprise customer admin user', 'ordering': ('-history_date', '-history_id'), }, bases=(simple_history.models.HistoricalChanges, models.Model), ), migrations.CreateModel( name='PendingEnterpriseCustomerAdminUser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('user_email', models.EmailField(max_length=254)), ('enterprise_customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='enterprise.EnterpriseCustomer')), ], options={ 'unique_together': {('enterprise_customer', 'user_email')}, 'ordering': ['created'], }, ), ]
agpl-3.0
-8,918,742,934,730,054,000
52.732143
205
0.627783
false
4.256011
false
false
false
blueshed/blueshed-micro
blueshed/micro/utils/executor.py
1
2437
from blueshed.micro.utils import resources from tornado.concurrent import Future from tornado.ioloop import IOLoop from tornado.autoreload import add_reload_hook from functools import wraps import logging import os import inspect from concurrent.futures.process import ProcessPoolExecutor LOGGER = logging.getLogger(__name__) _pool_ = None def pool_init(pool): global _pool_ _pool_ = pool def pool_init_processes(pool_size, debug=False): micro_pool = ProcessPoolExecutor(pool_size) pool_init(micro_pool) if debug is True: add_reload_hook(micro_pool.shutdown) logging.info("pool intialized with %s processes", pool_size) return micro_pool def global_pool(): global _pool_ return _pool_ def register_pool(name, pool): resources.set_resource(name, pool) def has_micro_context(f): for k, v in inspect.signature(f).parameters.items(): if v.annotation == 'micro_context': return k def run_in_pool(_pid, _f, _has_context, context, *args, **kwargs): # globals from the parent process in the # IOLoop so clear them. subprocess = os.getpid() != _pid if subprocess and IOLoop.current(False): LOGGER.debug("clearing tornado globals") IOLoop.clear_current() IOLoop.clear_instance() LOGGER.debug("running %s %s", os.getpid(), context) if _has_context: kwargs[_has_context] = context result = _f(*args, **kwargs) if not subprocess: return result if isinstance(result, Future): LOGGER.debug('running up tornado to complete') def done(*args, **kwargs): LOGGER.debug('stopping tornado') IOLoop.current().stop() result.add_done_callback(done) IOLoop.current().start() result = result.result() return context, result def pool(_f, resource_name=None): has_context = has_micro_context(_f) @wraps(_f) def call(_f, context, *args, **kwargs): global _pool_ if resource_name: pool = resources.get_resource(resource_name) elif _pool_: pool = _pool_ if pool: result = pool.submit(run_in_pool, os.getpid(), _f, has_context, context, *args, **kwargs) else: if has_context: kwargs[has_context] = context result = _f(*args, **kwargs) return result return call
mit
-5,598,329,544,635,889,000
26.077778
71
0.623718
false
3.886762
false
false
false
espressofiend/NCIL-SOC-2015
PsychoPy/stroop_lastrun.py
1
14481
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ This experiment was created using PsychoPy2 Experiment Builder (v1.82.00), Mon Jun 22 22:53:33 2015 If you publish work using this script please cite the relevant PsychoPy publications Peirce, JW (2007) PsychoPy - Psychophysics software in Python. Journal of Neuroscience Methods, 162(1-2), 8-13. Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy. Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008 """ from __future__ import division # so that 1/3=0.333 instead of 1/3=0 from psychopy import visual, core, data, event, logging, sound, gui from psychopy.constants import * # things like STARTED, FINISHED import numpy as np # whole numpy lib is available, prepend 'np.' from numpy import sin, cos, tan, log, log10, pi, average, sqrt, std, deg2rad, rad2deg, linspace, asarray from numpy.random import random, randint, normal, shuffle import os # handy system and path functions # Ensure that relative paths start from the same directory as this script _thisDir = os.path.dirname(os.path.abspath(__file__)) os.chdir(_thisDir) # Store info about the experiment session expName = u'stroop' # from the Builder filename that created this script expInfo = {u'session': u'001', u'participant': u''} dlg = gui.DlgFromDict(dictionary=expInfo, title=expName) if dlg.OK == False: core.quit() # user pressed cancel expInfo['date'] = data.getDateStr() # add a simple timestamp expInfo['expName'] = expName # Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc filename = _thisDir + os.sep + 'data/%s_%s_%s' %(expInfo['participant'], expName, expInfo['date']) # An ExperimentHandler isn't essential but helps with data saving thisExp = data.ExperimentHandler(name=expName, version='', extraInfo=expInfo, runtimeInfo=None, originPath=u'/Users/aaron/Documents/GitHub/NCIL-SOC-2015/PsychoPy/stroop.psyexp', savePickle=True, saveWideText=True, dataFileName=filename) #save a log file for detail verbose info logFile = logging.LogFile(filename+'.log', level=logging.EXP) logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file endExpNow = False # flag for 'escape' or other condition => quit the exp # Start Code - component code to be run before the window creation # Setup the Window win = visual.Window(size=(2560, 1440), fullscr=True, screen=0, allowGUI=False, allowStencil=False, monitor=u'testMonitor', color=[0,0,0], colorSpace='rgb', blendMode='avg', useFBO=True, ) # store frame rate of monitor if we can measure it successfully expInfo['frameRate']=win.getActualFrameRate() if expInfo['frameRate']!=None: frameDur = 1.0/round(expInfo['frameRate']) else: frameDur = 1.0/60.0 # couldn't get a reliable measure so guess # Initialize components for Routine "instr" instrClock = core.Clock() instructionText = visual.TextStim(win=win, ori=0, name='instructionText', text=u'Press left arrow if colour matches word\n\nPress right arrow if colour does not match word\n\nPress either arrow to start.', font=u'Arial', pos=[0, 0], height=0.1, wrapWidth=None, color=u'white', colorSpace='rgb', opacity=1, depth=0.0) # Initialize components for Routine "trial" trialClock = core.Clock() ISI = core.StaticPeriod(win=win, screenHz=expInfo['frameRate'], name='ISI') text = visual.TextStim(win=win, ori=0, name='text', text=u'XXXXXX', font=u'Arial', pos=[0, 0], height=0.1, wrapWidth=None, color=u'white', colorSpace='rgb', opacity=1, depth=-1.0) text_2 = visual.TextStim(win=win, ori=0, name='text_2', text=u'+', font=u'Arial', pos=[0, 0], height=0.1, wrapWidth=None, color=u'blue', colorSpace='rgb', opacity=1, depth=-2.0) text_3 = visual.TextStim(win=win, ori=0, name='text_3', text='default text', font=u'Arial', pos=[0, 0], height=0.1, wrapWidth=None, color=1.0, colorSpace='rgb', opacity=1, depth=-3.0) # Create some handy timers globalClock = core.Clock() # to track the time since experiment started routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine #------Prepare to start Routine "instr"------- t = 0 instrClock.reset() # clock frameN = -1 # update component parameters for each repeat key_resp_3 = event.BuilderKeyResponse() # create an object of type KeyResponse key_resp_3.status = NOT_STARTED # keep track of which components have finished instrComponents = [] instrComponents.append(instructionText) instrComponents.append(key_resp_3) for thisComponent in instrComponents: if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED #-------Start Routine "instr"------- continueRoutine = True while continueRoutine: # get current time t = instrClock.getTime() frameN = frameN + 1 # number of completed frames (so 0 is the first frame) # update/draw components on each frame # *instructionText* updates if t >= 0.0 and instructionText.status == NOT_STARTED: # keep track of start time/frame for later instructionText.tStart = t # underestimates by a little under one frame instructionText.frameNStart = frameN # exact frame index instructionText.setAutoDraw(True) # *key_resp_3* updates if t >= 0.0 and key_resp_3.status == NOT_STARTED: # keep track of start time/frame for later key_resp_3.tStart = t # underestimates by a little under one frame key_resp_3.frameNStart = frameN # exact frame index key_resp_3.status = STARTED # keyboard checking is just starting key_resp_3.clock.reset() # now t=0 event.clearEvents(eventType='keyboard') if key_resp_3.status == STARTED: theseKeys = event.getKeys(keyList=['left', 'right']) # check for quit: if "escape" in theseKeys: endExpNow = True if len(theseKeys) > 0: # at least one key was pressed key_resp_3.keys = theseKeys[-1] # just the last key pressed key_resp_3.rt = key_resp_3.clock.getTime() # a response ends the routine continueRoutine = False # check if all components have finished if not continueRoutine: # a component has requested a forced-end of Routine routineTimer.reset() # if we abort early the non-slip timer needs reset break continueRoutine = False # will revert to True if at least one component still running for thisComponent in instrComponents: if hasattr(thisComponent, "status") and thisComponent.status != FINISHED: continueRoutine = True break # at least one component has not yet finished # check for quit (the Esc key) if endExpNow or event.getKeys(keyList=["escape"]): core.quit() # refresh the screen if continueRoutine: # don't flip if this routine is over or we'll get a blank screen win.flip() else: # this Routine was not non-slip safe so reset non-slip timer routineTimer.reset() #-------Ending Routine "instr"------- for thisComponent in instrComponents: if hasattr(thisComponent, "setAutoDraw"): thisComponent.setAutoDraw(False) # check responses if key_resp_3.keys in ['', [], None]: # No response was made key_resp_3.keys=None # store data for thisExp (ExperimentHandler) thisExp.addData('key_resp_3.keys',key_resp_3.keys) if key_resp_3.keys != None: # we had a response thisExp.addData('key_resp_3.rt', key_resp_3.rt) thisExp.nextEntry() # set up handler to look after randomisation of conditions etc trials = data.TrialHandler(nReps=1, method='random', extraInfo=expInfo, originPath=u'/Users/aaron/Documents/GitHub/NCIL-SOC-2015/PsychoPy/stroop.psyexp', trialList=data.importConditions(u'psychopy_playing_conditions.xlsx'), seed=666, name='trials') thisExp.addLoop(trials) # add the loop to the experiment thisTrial = trials.trialList[0] # so we can initialise stimuli with some values # abbreviate parameter names if possible (e.g. rgb=thisTrial.rgb) if thisTrial != None: for paramName in thisTrial.keys(): exec(paramName + '= thisTrial.' + paramName) for thisTrial in trials: currentLoop = trials # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb) if thisTrial != None: for paramName in thisTrial.keys(): exec(paramName + '= thisTrial.' + paramName) #------Prepare to start Routine "trial"------- t = 0 trialClock.reset() # clock frameN = -1 routineTimer.add(5.000000) # update component parameters for each repeat text_3.setColor(colour, colorSpace='rgb') text_3.setText(word) key_resp_2 = event.BuilderKeyResponse() # create an object of type KeyResponse key_resp_2.status = NOT_STARTED # keep track of which components have finished trialComponents = [] trialComponents.append(ISI) trialComponents.append(text) trialComponents.append(text_2) trialComponents.append(text_3) trialComponents.append(key_resp_2) for thisComponent in trialComponents: if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED #-------Start Routine "trial"------- continueRoutine = True while continueRoutine and routineTimer.getTime() > 0: # get current time t = trialClock.getTime() frameN = frameN + 1 # number of completed frames (so 0 is the first frame) # update/draw components on each frame # *text* updates if t >= 0.0 and text.status == NOT_STARTED: # keep track of start time/frame for later text.tStart = t # underestimates by a little under one frame text.frameNStart = frameN # exact frame index text.setAutoDraw(True) if text.status == STARTED and t >= (0.0 + (1.0-win.monitorFramePeriod*0.75)): #most of one frame period left text.setAutoDraw(False) # *text_2* updates if t >= 1.5 and text_2.status == NOT_STARTED: # keep track of start time/frame for later text_2.tStart = t # underestimates by a little under one frame text_2.frameNStart = frameN # exact frame index text_2.setAutoDraw(True) if text_2.status == STARTED and t >= (1.5 + (1.0-win.monitorFramePeriod*0.75)): #most of one frame period left text_2.setAutoDraw(False) # *text_3* updates if t >= 3 and text_3.status == NOT_STARTED: # keep track of start time/frame for later text_3.tStart = t # underestimates by a little under one frame text_3.frameNStart = frameN # exact frame index text_3.setAutoDraw(True) if text_3.status == STARTED and t >= (3 + (2-win.monitorFramePeriod*0.75)): #most of one frame period left text_3.setAutoDraw(False) # *key_resp_2* updates if t >= 3 and key_resp_2.status == NOT_STARTED: # keep track of start time/frame for later key_resp_2.tStart = t # underestimates by a little under one frame key_resp_2.frameNStart = frameN # exact frame index key_resp_2.status = STARTED # keyboard checking is just starting key_resp_2.clock.reset() # now t=0 event.clearEvents(eventType='keyboard') if key_resp_2.status == STARTED and t >= (3 + (2-win.monitorFramePeriod*0.75)): #most of one frame period left key_resp_2.status = STOPPED if key_resp_2.status == STARTED: theseKeys = event.getKeys(keyList=['left', 'right']) # check for quit: if "escape" in theseKeys: endExpNow = True if len(theseKeys) > 0: # at least one key was pressed key_resp_2.keys = theseKeys[-1] # just the last key pressed key_resp_2.rt = key_resp_2.clock.getTime() # was this 'correct'? if (key_resp_2.keys == str(corrAns)) or (key_resp_2.keys == corrAns): key_resp_2.corr = 1 else: key_resp_2.corr = 0 # a response ends the routine continueRoutine = False # *ISI* period if t >= 0.0 and ISI.status == NOT_STARTED: # keep track of start time/frame for later ISI.tStart = t # underestimates by a little under one frame ISI.frameNStart = frameN # exact frame index ISI.start(0.5) elif ISI.status == STARTED: #one frame should pass before updating params and completing ISI.complete() #finish the static period # check if all components have finished if not continueRoutine: # a component has requested a forced-end of Routine routineTimer.reset() # if we abort early the non-slip timer needs reset break continueRoutine = False # will revert to True if at least one component still running for thisComponent in trialComponents: if hasattr(thisComponent, "status") and thisComponent.status != FINISHED: continueRoutine = True break # at least one component has not yet finished # check for quit (the Esc key) if endExpNow or event.getKeys(keyList=["escape"]): core.quit() # refresh the screen if continueRoutine: # don't flip if this routine is over or we'll get a blank screen win.flip() #-------Ending Routine "trial"------- for thisComponent in trialComponents: if hasattr(thisComponent, "setAutoDraw"): thisComponent.setAutoDraw(False) # check responses if key_resp_2.keys in ['', [], None]: # No response was made key_resp_2.keys=None # was no response the correct answer?! if str(corrAns).lower() == 'none': key_resp_2.corr = 1 # correct non-response else: key_resp_2.corr = 0 # failed to respond (incorrectly) # store data for trials (TrialHandler) trials.addData('key_resp_2.keys',key_resp_2.keys) trials.addData('key_resp_2.corr', key_resp_2.corr) if key_resp_2.keys != None: # we had a response trials.addData('key_resp_2.rt', key_resp_2.rt) thisExp.nextEntry() # completed 1 repeats of 'trials' win.close() core.quit()
mit
883,825,306,107,728,600
43.832817
153
0.653477
false
3.55886
false
false
false
SauloAislan/ironic
ironic/common/keystone.py
1
4019
# coding=utf-8 # # 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. """Central place for handling Keystone authorization and service lookup.""" from keystoneauth1 import exceptions as kaexception from keystoneauth1 import loading as kaloading from oslo_log import log as logging import six from ironic.common import exception from ironic.conf import CONF LOG = logging.getLogger(__name__) def ks_exceptions(f): """Wraps keystoneclient functions and centralizes exception handling.""" @six.wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) except kaexception.EndpointNotFound: service_type = kwargs.get('service_type', 'baremetal') endpoint_type = kwargs.get('endpoint_type', 'internal') raise exception.CatalogNotFound( service_type=service_type, endpoint_type=endpoint_type) except (kaexception.Unauthorized, kaexception.AuthorizationFailure): raise exception.KeystoneUnauthorized() except (kaexception.NoMatchingPlugin, kaexception.MissingRequiredOptions) as e: raise exception.ConfigInvalid(six.text_type(e)) except Exception as e: LOG.exception('Keystone request failed: %(msg)s', {'msg': six.text_type(e)}) raise exception.KeystoneFailure(six.text_type(e)) return wrapper @ks_exceptions def get_session(group, **session_kwargs): """Loads session object from options in a configuration file section. The session_kwargs will be passed directly to keystoneauth1 Session and will override the values loaded from config. Consult keystoneauth1 docs for available options. :param group: name of the config section to load session options from """ return kaloading.load_session_from_conf_options( CONF, group, **session_kwargs) @ks_exceptions def get_auth(group, **auth_kwargs): """Loads auth plugin from options in a configuration file section. The auth_kwargs will be passed directly to keystoneauth1 auth plugin and will override the values loaded from config. Note that the accepted kwargs will depend on auth plugin type as defined by [group]auth_type option. Consult keystoneauth1 docs for available auth plugins and their options. :param group: name of the config section to load auth plugin options from """ try: auth = kaloading.load_auth_from_conf_options(CONF, group, **auth_kwargs) except kaexception.MissingRequiredOptions: LOG.error('Failed to load auth plugin from group %s', group) raise return auth # NOTE(pas-ha) Used by neutronclient and resolving ironic API only # FIXME(pas-ha) remove this while moving to kesytoneauth adapters @ks_exceptions def get_service_url(session, **kwargs): """Find endpoint for given service in keystone catalog. If 'interrace' is provided, fetches service url of this interface. Otherwise, first tries to fetch 'internal' endpoint, and then the 'public' one. :param session: keystoneauth Session object :param kwargs: any other arguments accepted by Session.get_endpoint method """ if 'interface' in kwargs: return session.get_endpoint(**kwargs) try: return session.get_endpoint(interface='internal', **kwargs) except kaexception.EndpointNotFound: return session.get_endpoint(interface='public', **kwargs)
apache-2.0
4,339,364,489,607,921,700
35.87156
78
0.700423
false
4.368478
true
false
false
gnoack/ukechord
chordpro.py
1
4308
"""Read ChordPro files and output them through a PDFWriter object""" import re import song import uke class ChordProError(Exception): """Error in a ChordPro input.""" pass def _analyze_chordpro_textline(line): """Analyze the text and chords in a line of text. Args: line: The line of text, with chords in square brackets. Returns: A list of (chord, textchunk) tuples. The chord is None for a leading piece of text without preceding chord. Example: Input: "This is [Dm]an example [C]line." Output: [(None, "This is "), ("Dm", "an example "), ("C", "line.")] """ matches = list(re.finditer(r"\[([^\]]+)\]([^\[]*)", line)) if matches: result = [] if matches[0].start(0): result.append((None, line[:matches[0].start(0)])) for match in matches: result.append(match.groups()) return result return [(None, line)] def _chordpro_line(line): """Analyze a ChordPro line into a key value pair. For commands of the form "{key:value}", those will be the key and value. For empty lines, key is "$empty", and value is None. For text lines, returns "$lyrics" as key and a list of (chord, text) tuples as value """ line = line.strip() if not line or line.startswith("#"): return ("$empty", None) if line.startswith("{") and line.endswith("}"): key, unused_colon, value = line[1:-1].partition(":") return (key, value) else: return ("$lyrics", _analyze_chordpro_textline(line)) def _parse_chord_definition(value): # TODO: Is it required to define 'fingers' in each chord definition? match = re.match( r"\s+(?P<name>[A-Za-z0-9/+#]*)\s+" r"frets\s+(?P<frets>[\d\s]+)" r"fingers\s+(?P<fingers>[\d\s]+)$", value) # TODO: Implement finger positioning support # TODO: Catch too high fret values if not match: raise ChordProError("Chord definition parsing failed", value) frets = [int(fret) for fret in match.group('frets').split(' ') if fret] if any(fret > uke.MAX_FRET for fret in frets): raise ChordProError("Frets beyond %d don't exist.", uke.MAX_FRET) return match.group('name'), tuple(frets) def _convert_lines_to_ast_nodes(lines, chords, end_of_section_markers=()): result = [] for key, value in lines: if key in end_of_section_markers: break elif key == "$empty": pass # ignore elif key in ("$lyrics", "comment"): if key == "$lyrics": first_verse_item = song.Line(value) elif key == "comment": first_verse_item = song.Comment(value) else: raise ChordProError("Should never happen. - Programming error") # Text if end_of_section_markers: # If we're in a section, lines are fine. result.append(first_verse_item) else: verse_lines = _convert_lines_to_ast_nodes( lines, chords=chords, end_of_section_markers=("$empty")) result.append(song.Verse([first_verse_item] + verse_lines)) elif key in ("soc", "start-of-chorus", "start_of_chorus"): if end_of_section_markers: raise ChordProError("ChordPro: Nested choruses are not supported.") result.append(song.Chorus( _convert_lines_to_ast_nodes( lines, chords=chords, end_of_section_markers=("eoc", "end-of-chorus", "end_of_chorus")))) elif key == "define": name, frets = _parse_chord_definition(value) chords[name] = frets elif key in ("title", "subtitle"): continue # Handled earlier. elif key == "fontsize": # TODO: How to handle font size? pass # Should translate to pdf_writer.setFontsize(int(value)) elif key in ("eoc", "end-of-chorus", "end_of_chorus"): # If not already part of breaking condition. raise ChordProError( "End-of-chorus ChordPro command without matching start.") else: raise ChordProError("Unknown ChordPro command: %s", key) return result def to_ast(infile): lines = [_chordpro_line(line) for line in infile.readlines()] keys_and_values = dict(lines) title = keys_and_values.get("title", "").strip() subtitle = keys_and_values.get("subtitle", "").strip() chords = {} children = _convert_lines_to_ast_nodes(iter(lines), chords=chords) return song.Song(children, title=title, subtitle=subtitle, chords=chords)
apache-2.0
-5,033,884,073,311,483,000
31.885496
77
0.634401
false
3.293578
false
false
false
remind101/stacker_blueprints
stacker_blueprints/policies.py
1
6595
from awacs.aws import ( Action, Allow, Policy, Principal, Statement, ) from troposphere import ( Sub, Join, Region, AccountId, AWSHelperFn ) from awacs import ( sts, s3, logs, ec2, dynamodb, cloudwatch, ) def make_simple_assume_statement(*principals): return Statement( Principal=Principal('Service', principals), Effect=Allow, Action=[sts.AssumeRole]) def make_simple_assume_policy(*principals): return Policy( Statement=[ make_simple_assume_statement(*principals)]) def dynamodb_arn(table_name): return 'arn:aws:dynamodb:::table/{}'.format(table_name) def dynamodb_arns(table_names): return [dynamodb_arn(table_name) for table_name in table_names] def s3_arn(bucket): if isinstance(bucket, AWSHelperFn): return Sub('arn:aws:s3:::${Bucket}', Bucket=bucket) else: return 'arn:aws:s3:::%s' % bucket def s3_objects_arn(bucket, folder="*"): if isinstance(bucket, AWSHelperFn): return Sub('arn:aws:s3:::${Bucket}/%s' % folder, Bucket=bucket) else: return 'arn:aws:s3:::%s/%s' % (bucket, folder) def read_only_s3_bucket_policy_statements(buckets, folder="*"): """ Read only policy an s3 bucket. """ list_buckets = [s3_arn(b) for b in buckets] object_buckets = [s3_objects_arn(b, folder) for b in buckets] bucket_resources = list_buckets + object_buckets return [ Statement( Effect=Allow, Resource=[s3_arn("*")], Action=[s3.ListAllMyBuckets] ), Statement( Effect=Allow, Resource=bucket_resources, Action=[Action('s3', 'Get*'), Action('s3', 'List*')] ) ] def read_only_s3_bucket_policy(buckets): return Policy(Statement=read_only_s3_bucket_policy_statements(buckets)) def read_write_s3_bucket_policy_statements(buckets, folder="*"): list_buckets = [s3_arn(b) for b in buckets] object_buckets = [s3_objects_arn(b, folder) for b in buckets] return [ Statement( Effect="Allow", Action=[ s3.GetBucketLocation, s3.ListAllMyBuckets, ], Resource=[s3_arn("*")] ), Statement( Effect=Allow, Action=[ s3.ListBucket, s3.GetBucketVersioning, ], Resource=list_buckets, ), Statement( Effect=Allow, Action=[ s3.GetObject, s3.PutObject, s3.PutObjectAcl, s3.DeleteObject, s3.GetObjectVersion, s3.DeleteObjectVersion, ], Resource=object_buckets, ), ] def read_write_s3_bucket_policy(buckets): return Policy(Statement=read_write_s3_bucket_policy_statements(buckets)) def static_website_bucket_policy(bucket): """ Attach this policy directly to an S3 bucket to make it a static website. This policy grants read access to **all unauthenticated** users. """ return Policy( Statement=[ Statement( Effect=Allow, Principal=Principal("*"), Action=[s3.GetObject], Resource=[s3_objects_arn(bucket)], ) ] ) def log_stream_arn(log_group_name, log_stream_name): return Join( '', [ "arn:aws:logs:", Region, ":", AccountId, ":log-group:", log_group_name, ":log-stream:", log_stream_name ] ) def write_to_cloudwatch_logs_stream_statements(log_group_name, log_stream_name): return [ Statement( Effect=Allow, Action=[logs.PutLogEvents], Resource=[log_stream_arn(log_group_name, log_stream_name)] ) ] def write_to_cloudwatch_logs_stream_policy(log_group_name, log_stream_name): return Policy( Statement=write_to_cloudwatch_logs_stream_statements(log_group_name, log_stream_name) ) def cloudwatch_logs_write_statements(log_group=None): resources = ["arn:aws:logs:*:*:*"] if log_group: log_group_parts = ["arn:aws:logs:", Region, ":", AccountId, ":log-group:", log_group] log_group_arn = Join("", log_group_parts) log_stream_wild = Join("", log_group_parts + [":*"]) resources = [log_group_arn, log_stream_wild] return [ Statement( Effect=Allow, Resource=resources, Action=[ logs.CreateLogGroup, logs.CreateLogStream, logs.PutLogEvents ] ) ] def lambda_basic_execution_statements(function_name): log_group = Join("/", ["/aws/lambda", function_name]) return cloudwatch_logs_write_statements(log_group) def lambda_basic_execution_policy(function_name): return Policy(Statement=lambda_basic_execution_statements(function_name)) def lambda_vpc_execution_statements(): """Allow Lambda to manipuate EC2 ENIs for VPC support.""" return [ Statement( Effect=Allow, Resource=['*'], Action=[ ec2.CreateNetworkInterface, ec2.DescribeNetworkInterfaces, ec2.DeleteNetworkInterface, ] ) ] def flowlogs_assumerole_policy(): return make_simple_assume_policy("vpc-flow-logs.amazonaws.com") # reference: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html#cfn-dynamodb-table-examples-application-autoscaling # noqa def dynamodb_autoscaling_policy(tables): """Policy to allow AutoScaling a list of DynamoDB tables.""" return Policy( Statement=[ Statement( Effect=Allow, Resource=dynamodb_arns(tables), Action=[ dynamodb.DescribeTable, dynamodb.UpdateTable, ] ), Statement( Effect=Allow, Resource=['*'], Action=[ cloudwatch.PutMetricAlarm, cloudwatch.DescribeAlarms, cloudwatch.GetMetricStatistics, cloudwatch.SetAlarmState, cloudwatch.DeleteAlarms, ] ), ] )
bsd-2-clause
-2,938,821,598,821,418,500
25.808943
167
0.549659
false
3.963341
false
false
false
osborne6/luminotes
view/Page_navigation.py
1
1736
from Tags import P, Span, A, Strong class Page_navigation( P ): def __init__( self, page_path, displayed_item_count, total_item_count, start, items_per_page, return_text = None ): if start is None or items_per_page is None: P.__init__( self ) return if displayed_item_count == 1 and displayed_item_count < total_item_count: if not return_text: P.__init__( self ) return P.__init__( self, Span( A( return_text, href = "%s" % page_path, ), ), ) return if start == 0 and items_per_page >= total_item_count: P.__init__( self ) return P.__init__( self, ( start > 0 ) and Span( A( u"previous", href = self.href( page_path, max( start - items_per_page, 0 ), items_per_page ), ), u" | ", ) or None, [ Span( ( start == page_start ) and Strong( unicode( page_number + 1 ) ) or A( Strong( unicode( page_number + 1 ) ), href = self.href( page_path, page_start, items_per_page ), ), ) for ( page_number, page_start ) in enumerate( range( 0, total_item_count, items_per_page ) ) ], ( start + items_per_page < total_item_count ) and Span( u" | ", A( u"next", href = self.href( page_path, min( start + items_per_page, total_item_count - 1 ), items_per_page ), ), ) or None, ) @staticmethod def href( page_path, start, count ): # if start is zero, leave off start and count parameters and just use the defaults if start == 0: return page_path return u"%s?start=%d&count=%d" % ( page_path, start, count )
gpl-3.0
-6,957,415,015,767,892,000
28.423729
117
0.522465
false
3.535642
false
false
false
tambetm/gymexperiments
a2c_atari.py
1
10250
import argparse import os import multiprocessing from multiprocessing import Process, Queue, Array import pickle import gym from gym.spaces import Box, Discrete from keras.models import Model from keras.layers import Input, TimeDistributed, Convolution2D, Flatten, LSTM, Dense from keras.objectives import categorical_crossentropy from keras.optimizers import Adam from keras.utils import np_utils import keras.backend as K import numpy as np from atari_utils import RandomizedResetEnv, AtariRescale42x42Env def create_env(env_id): env = gym.make(env_id) env = RandomizedResetEnv(env) env = AtariRescale42x42Env(env) return env def create_model(env, batch_size, num_steps): # network inputs are observations and advantages h = x = Input(batch_shape=(batch_size, num_steps) + env.observation_space.shape, name="x") A = Input(batch_shape=(batch_size, num_steps), name="A") # convolutional layers h = TimeDistributed(Convolution2D(32, 3, 3, subsample=(2, 2), border_mode="same", activation='elu', dim_ordering='tf'), name='c1')(h) h = TimeDistributed(Convolution2D(32, 3, 3, subsample=(2, 2), border_mode="same", activation='elu', dim_ordering='tf'), name='c2')(h) h = TimeDistributed(Convolution2D(32, 3, 3, subsample=(2, 2), border_mode="same", activation='elu', dim_ordering='tf'), name='c3')(h) h = TimeDistributed(Convolution2D(64, 3, 3, subsample=(2, 2), border_mode="same", activation='elu', dim_ordering='tf'), name='c4')(h) h = TimeDistributed(Flatten(), name="fl")(h) # recurrent layer h = LSTM(32, return_sequences=True, stateful=True, name="r1")(h) # policy network p = TimeDistributed(Dense(env.action_space.n, activation='softmax'), name="p")(h) # baseline network b = TimeDistributed(Dense(1), name="b")(h) # inputs to the model are observation and advantages, # outputs are action probabilities and baseline model = Model(input=[x, A], output=[p, b]) # policy gradient loss and entropy bonus def policy_gradient_loss(l_sampled, l_predicted): return K.mean(A * categorical_crossentropy(l_sampled, l_predicted), axis=1) \ - 0.01 * K.mean(categorical_crossentropy(l_predicted, l_predicted), axis=1) # baseline is optimized with MSE model.compile(optimizer='adam', loss=[policy_gradient_loss, 'mse']) return model def predict(model, observation): # create inputs for batch (and timestep) of size 1 x = np.array([[observation]]) A = np.zeros((1, 1)) # dummy advantage # predict action probabilities (and baseline state value) p, b = model.predict_on_batch([x, A]) # return action probabilities and baseline return p[0, 0], b[0, 0, 0] def discount(rewards, terminals, v, gamma): # calculate discounted future rewards for this trajectory returns = [] # start with the predicted value of the last state R = v for r, t in zip(reversed(rewards), reversed(terminals)): # if it was terminal state then restart from 0 if t: R = 0 R = r + R * gamma returns.insert(0, R) return returns def runner(shared_buffer, fifo, num_timesteps, monitor, args): proc_name = multiprocessing.current_process().name print("Runner %s started" % proc_name) # local environment for runner env = create_env(args.env_id) # start monitor to record statistics and videos if monitor: env.monitor.start(args.env_id) # copy of model model = create_model(env, batch_size=1, num_steps=1) # record episode lengths and rewards for statistics episode_rewards = [] episode_lengths = [] episode_reward = 0 episode_length = 0 observation = env.reset() for i in range(num_timesteps // args.num_local_steps): # copy weights from main network at the beginning of iteration # the main network's weights are only read, never modified # but we create our own model instance, because Keras is not thread-safe model.set_weights(pickle.loads(shared_buffer.raw)) observations = [] actions = [] rewards = [] terminals = [] baselines = [] for t in range(args.num_local_steps): if args.display: env.render() # predict action probabilities (and baseline state value) p, b = predict(model, observation) # sample action using those probabilities p /= np.sum(p) # ensure p-s sum up to 1 action = np.random.choice(env.action_space.n, p=p) # log data observations.append(observation) actions.append(action) baselines.append(b) # step environment observation, reward, terminal, _ = env.step(int(action)) rewards.append(reward) terminals.append(terminal) episode_reward += reward episode_length += 1 # reset if terminal state if terminal: episode_rewards.append(episode_reward) episode_lengths.append(episode_length) episode_reward = 0 episode_length = 0 observation = env.reset() # calculate discounted returns if terminal: # if the last was terminal state then start from 0 returns = discount(rewards, terminals, 0, 0.99) else: # otherwise calculate the value of the last state _, v = predict(model, observation) returns = discount(rewards, terminals, v, 0.99) # convert to numpy arrays observations = np.array(observations) actions = np_utils.to_categorical(actions, env.action_space.n) baselines = np.array(baselines) returns = np.array(returns) advantages = returns - baselines # send observations, actions, rewards and returns. blocks if fifo is full. fifo.put((observations, actions, returns, advantages, episode_rewards, episode_lengths)) episode_rewards = [] episode_lengths = [] if monitor: env.monitor.close() print("Runner %s finished" % proc_name) def trainer(model, fifos, shared_buffer, args): proc_name = multiprocessing.current_process().name print("Trainer %s started" % proc_name) episode_rewards = [] episode_lengths = [] timestep = 0 while len(multiprocessing.active_children()) > 0 and timestep < args.num_timesteps: batch_observations = [] batch_actions = [] batch_returns = [] batch_advantages = [] # loop over fifos from all runners for q, fifo in enumerate(fifos): # wait for a new trajectory and statistics observations, actions, returns, advantages, rewards, lengths = fifo.get() # add to batch batch_observations.append(observations) batch_actions.append(actions) batch_returns.append(returns) batch_advantages.append(advantages) # log statistics episode_rewards += rewards episode_lengths += lengths timestep += len(observations) # form training data from observations, actions and returns x = np.array(batch_observations) p = np.array(batch_actions) R = np.array(batch_returns)[:, :, np.newaxis] A = np.array(batch_advantages) # anneal learning rate model.optimizer.lr = max(0.001 * (args.num_timesteps - timestep) / args.num_timesteps, 0) # train the model total_loss, policy_loss, baseline_loss = model.train_on_batch([x, A], [p, R]) # share model parameters shared_buffer.raw = pickle.dumps(model.get_weights(), pickle.HIGHEST_PROTOCOL) if timestep % args.stats_interval == 0: print("Step %d/%d: episodes %d, mean episode reward %.2f, mean episode length %.2f." % (timestep, args.num_timesteps, len(episode_rewards), np.mean(episode_rewards), np.mean(episode_lengths))) episode_rewards = [] episode_lengths = [] print("Trainer %s finished" % proc_name) def run(args): # create dummy environment to be able to create model env = create_env(args.env_id) assert isinstance(env.observation_space, Box) assert isinstance(env.action_space, Discrete) print("Observation space: " + str(env.observation_space)) print("Action space: " + str(env.action_space)) # create main model model = create_model(env, batch_size=args.num_runners, num_steps=args.num_local_steps) model.summary() env.close() # for better compatibility with Theano and Tensorflow multiprocessing.set_start_method('spawn') # create shared buffer for sharing weights blob = pickle.dumps(model.get_weights(), pickle.HIGHEST_PROTOCOL) shared_buffer = Array('c', len(blob)) shared_buffer.raw = blob # force runner processes to use cpu, child processes inherit environment variables os.environ["CUDA_VISIBLE_DEVICES"] = "" # create fifos and processes for all runners fifos = [] for i in range(args.num_runners): fifo = Queue(args.queue_length) fifos.append(fifo) process = Process(target=runner, args=(shared_buffer, fifo, args.num_timesteps // args.num_runners, args.monitor and i == 0, args)) process.start() # start trainer in main thread trainer(model, fifos, shared_buffer, args) print("All done") if __name__ == '__main__': parser = argparse.ArgumentParser() # parallelization parser.add_argument('--num_runners', type=int, default=2) parser.add_argument('--queue_length', type=int, default=2) # how long parser.add_argument('--num_timesteps', type=int, default=5000000) parser.add_argument('--num_local_steps', type=int, default=20) parser.add_argument('--stats_interval', type=int, default=10000) # technical parser.add_argument('--display', action='store_true', default=False) parser.add_argument('--monitor', action='store_true', default=False) # mandatory parser.add_argument('env_id') args = parser.parse_args() run(args)
mit
6,621,470,067,187,979,000
34.590278
137
0.639805
false
3.831776
false
false
false
SymbiFlow/symbiflow-arch-defs
utils/lib/parse_route.py
1
1541
""" Library for parsing route output from VPR route files. """ from collections import namedtuple Node = namedtuple('Node', 'inode x_low y_low x_high y_high ptc') def format_name(s): """ Converts VPR parenthesized name to just name. """ assert s[0] == '(' assert s[-1] == ')' return s[1:-1] def format_coordinates(coord): """ Parses coordinates from VPR route file in format of (x,y). """ coord = format_name(coord) x, y = coord.split(',') return int(x), int(y) def find_net_sources(f): """ Yields tuple of (net string, Node namedtuple) from file object. File object should be formatted as VPR route output file. """ net = None for e in f: tokens = e.strip().split() if not tokens: continue elif tokens[0][0] == '#': continue elif tokens[0] == 'Net': net = format_name(tokens[2]) elif e == "\n\nUsed in local cluster only, reserved one CLB pin\n\n": continue else: if net is not None: inode = int(tokens[1]) assert tokens[2] == 'SOURCE' x, y = format_coordinates(tokens[3]) if tokens[4] == 'to': x2, y2 = format_coordinates(tokens[5]) offset = 2 else: x2, y2 = x, y offset = 0 ptc = int(tokens[5 + offset]) yield net, Node(inode, x, y, x2, y2, ptc) net = None
isc
6,817,013,597,185,511,000
27.018182
77
0.506814
false
3.862155
false
false
false
NaohiroTamura/python-ironicclient
ironicclient/v1/chassis.py
1
6569
# -*- coding: utf-8 -*- # # Copyright © 2013 Red Hat, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from ironicclient.common import base from ironicclient.common.i18n import _ from ironicclient.common import utils from ironicclient import exc class Chassis(base.Resource): def __repr__(self): return "<Chassis %s>" % self._info class ChassisManager(base.CreateManager): resource_class = Chassis _resource_name = 'chassis' _creation_attributes = ['description', 'extra', 'uuid'] def list(self, marker=None, limit=None, sort_key=None, sort_dir=None, detail=False, fields=None): """Retrieve a list of chassis. :param marker: Optional, the UUID of a chassis, eg the last chassis from a previous result set. Return the next result set. :param limit: The maximum number of results to return per request, if: 1) limit > 0, the maximum number of chassis to return. 2) limit == 0, return the entire list of chassis. 3) limit param is NOT specified (None), the number of items returned respect the maximum imposed by the Ironic API (see Ironic's api.max_limit option). :param sort_key: Optional, field used for sorting. :param sort_dir: Optional, direction of sorting, either 'asc' (the default) or 'desc'. :param detail: Optional, boolean whether to return detailed information about chassis. :param fields: Optional, a list with a specified set of fields of the resource to be returned. Can not be used when 'detail' is set. :returns: A list of chassis. """ if limit is not None: limit = int(limit) if detail and fields: raise exc.InvalidAttribute(_("Can't fetch a subset of fields " "with 'detail' set")) filters = utils.common_filters(marker, limit, sort_key, sort_dir, fields) path = '' if detail: path += 'detail' if filters: path += '?' + '&'.join(filters) if limit is None: return self._list(self._path(path), "chassis") else: return self._list_pagination(self._path(path), "chassis", limit=limit) def list_nodes(self, chassis_id, marker=None, limit=None, sort_key=None, sort_dir=None, detail=False, fields=None, associated=None, maintenance=None, provision_state=None): """List all the nodes for a given chassis. :param chassis_id: The UUID of the chassis. :param marker: Optional, the UUID of a node, eg the last node from a previous result set. Return the next result set. :param limit: The maximum number of results to return per request, if: 1) limit > 0, the maximum number of nodes to return. 2) limit == 0, return the entire list of nodes. 3) limit param is NOT specified (None), the number of items returned respect the maximum imposed by the Ironic API (see Ironic's api.max_limit option). :param sort_key: Optional, field used for sorting. :param sort_dir: Optional, direction of sorting, either 'asc' (the default) or 'desc'. :param detail: Optional, boolean whether to return detailed information about nodes. :param fields: Optional, a list with a specified set of fields of the resource to be returned. Can not be used when 'detail' is set. :param associated: Optional. Either a Boolean or a string representation of a Boolean that indicates whether to return a list of associated (True or "True") or unassociated (False or "False") nodes. :param maintenance: Optional. Either a Boolean or a string representation of a Boolean that indicates whether to return nodes in maintenance mode (True or "True"), or not in maintenance mode (False or "False"). :param provision_state: Optional. String value to get only nodes in that provision state. :returns: A list of nodes. """ if limit is not None: limit = int(limit) if detail and fields: raise exc.InvalidAttribute(_("Can't fetch a subset of fields " "with 'detail' set")) filters = utils.common_filters(marker, limit, sort_key, sort_dir, fields) if associated is not None: filters.append('associated=%s' % associated) if maintenance is not None: filters.append('maintenance=%s' % maintenance) if provision_state is not None: filters.append('provision_state=%s' % provision_state) path = "%s/nodes" % chassis_id if detail: path += '/detail' if filters: path += '?' + '&'.join(filters) if limit is None: return self._list(self._path(path), "nodes") else: return self._list_pagination(self._path(path), "nodes", limit=limit) def get(self, chassis_id, fields=None): return self._get(resource_id=chassis_id, fields=fields) def delete(self, chassis_id): return self._delete(resource_id=chassis_id) def update(self, chassis_id, patch): return self._update(resource_id=chassis_id, patch=patch)
apache-2.0
1,744,163,797,057,530,600
37.635294
79
0.564708
false
4.668088
false
false
false
1905410/Misago
misago/threads/views/admin/attachments.py
1
3500
from django.contrib import messages from django.core.urlresolvers import reverse from django.db import transaction from django.db.models import Count from django.shortcuts import redirect from django.utils.translation import ugettext_lazy as _ from misago.admin.views import generic from ...forms import SearchAttachmentsForm from ...models import Attachment, Post class AttachmentAdmin(generic.AdminBaseMixin): root_link = 'misago:admin:system:attachments:index' Model = Attachment templates_dir = 'misago/admin/attachments' message_404 = _("Requested attachment could not be found.") def get_queryset(self): qs = super(AttachmentAdmin, self).get_queryset() return qs.select_related('filetype', 'uploader', 'post', 'post__thread', 'post__category') class AttachmentsList(AttachmentAdmin, generic.ListView): items_per_page = 20 ordering = ( ('-id', _("From newest")), ('id', _("From oldest")), ('filename', _("A to z")), ('-filename', _("Z to a")), ('size', _("Smallest files")), ('-size', _("Largest files")), ) selection_label = _('With attachments: 0') empty_selection_label = _('Select attachments') mass_actions = [ { 'action': 'delete', 'name': _("Delete attachments"), 'icon': 'fa fa-times-circle', 'confirmation': _("Are you sure you want to delete selected attachments?"), 'is_atomic': False } ] def get_search_form(self, request): return SearchAttachmentsForm def action_delete(self, request, attachments): deleted_attachments = [] desynced_posts = [] for attachment in attachments: if attachment.post: deleted_attachments.append(attachment.pk) desynced_posts.append(attachment.post_id) if desynced_posts: with transaction.atomic(): for post in Post.objects.select_for_update().filter(id__in=desynced_posts): self.delete_from_cache(post, deleted_attachments) for attachment in attachments: attachment.delete() message = _("Selected attachments have been deleted.") messages.success(request, message) def delete_from_cache(self, post, attachments): if not post.attachments_cache: return # admin action may be taken due to desynced state clean_cache = [] for a in post.attachments_cache: if a['id'] not in attachments: clean_cache.append(a) post.attachments_cache = clean_cache or None post.save(update_fields=['attachments_cache']) class DeleteAttachment(AttachmentAdmin, generic.ButtonView): def button_action(self, request, target): if target.post: self.delete_from_cache(target) target.delete() message = _('Attachment "%(filename)s" has been deleted.') messages.success(request, message % {'filename': target.filename}) def delete_from_cache(self, attachment): if not attachment.post.attachments_cache: return # admin action may be taken due to desynced state clean_cache = [] for a in attachment.post.attachments_cache: if a['id'] != attachment.id: clean_cache.append(a) attachment.post.attachments_cache = clean_cache or None attachment.post.save(update_fields=['attachments_cache'])
gpl-2.0
-8,330,892,099,958,133,000
33.653465
98
0.626857
false
4.358655
false
false
false
pombredanne/blivet-1
tests/devicelibs_test/edd_test.py
1
9403
import mock class EddTestCase(mock.TestCase): def setUp(self): self.setupModules( ['_isys', 'logging', 'pyanaconda.anaconda_log', 'block']) def tearDown(self): self.tearDownModules() def test_biosdev_to_edd_dir(self): from blivet.devicelibs import edd path = edd.biosdev_to_edd_dir(138) self.assertEqual("/sys/firmware/edd/int13_dev8a", path) def test_collect_edd_data(self): from blivet.devicelibs import edd # test with vda, vdb fs = EddTestFS(self, edd).vda_vdb() edd_dict = edd.collect_edd_data() self.assertEqual(len(edd_dict), 2) self.assertEqual(edd_dict[0x80].type, "SCSI") self.assertEqual(edd_dict[0x80].scsi_id, 0) self.assertEqual(edd_dict[0x80].scsi_lun, 0) self.assertEqual(edd_dict[0x80].pci_dev, "00:05.0") self.assertEqual(edd_dict[0x80].channel, 0) self.assertEqual(edd_dict[0x80].sectors, 16777216) self.assertEqual(edd_dict[0x81].pci_dev, "00:06.0") # test with sda, vda fs = EddTestFS(self, edd).sda_vda() edd_dict = edd.collect_edd_data() self.assertEqual(len(edd_dict), 2) self.assertEqual(edd_dict[0x80].type, "ATA") self.assertEqual(edd_dict[0x80].scsi_id, None) self.assertEqual(edd_dict[0x80].scsi_lun, None) self.assertEqual(edd_dict[0x80].pci_dev, "00:01.1") self.assertEqual(edd_dict[0x80].channel, 0) self.assertEqual(edd_dict[0x80].sectors, 2097152) self.assertEqual(edd_dict[0x80].ata_device, 0) self.assertEqual(edd_dict[0x80].mbr_signature, "0x000ccb01") def test_collect_edd_data_cciss(self): from blivet.devicelibs import edd fs = EddTestFS(self, edd).sda_cciss() edd_dict = edd.collect_edd_data() self.assertEqual(edd_dict[0x80].pci_dev, None) self.assertEqual(edd_dict[0x80].channel, None) def test_edd_entry_str(self): from blivet.devicelibs import edd fs = EddTestFS(self, edd).sda_vda() edd_dict = edd.collect_edd_data() expected_output = """\ttype: ATA, ata_device: 0 \tchannel: 0, mbr_signature: 0x000ccb01 \tpci_dev: 00:01.1, scsi_id: None \tscsi_lun: None, sectors: 2097152""" self.assertEqual(str(edd_dict[0x80]), expected_output) def test_matcher_device_path(self): from blivet.devicelibs import edd fs = EddTestFS(self, edd).sda_vda() edd_dict = edd.collect_edd_data() analyzer = edd.EddMatcher(edd_dict[0x80]) path = analyzer.devname_from_pci_dev() self.assertEqual(path, "sda") analyzer = edd.EddMatcher(edd_dict[0x81]) path = analyzer.devname_from_pci_dev() self.assertEqual(path, "vda") def test_bad_device_path(self): from blivet.devicelibs import edd fs = EddTestFS(self, edd).sda_vda_no_pcidev() edd_dict = edd.collect_edd_data() analyzer = edd.EddMatcher(edd_dict[0x80]) path = analyzer.devname_from_pci_dev() self.assertEqual(path, None) def test_bad_host_bus(self): from blivet.devicelibs import edd fs = EddTestFS(self, edd).sda_vda_no_host_bus() edd_dict = edd.collect_edd_data() # 0x80 entry is basted so fail without an exception analyzer = edd.EddMatcher(edd_dict[0x80]) devname = analyzer.devname_from_pci_dev() self.assertEqual(devname, None) # but still succeed on 0x81 analyzer = edd.EddMatcher(edd_dict[0x81]) devname = analyzer.devname_from_pci_dev() self.assertEqual(devname, "vda") def test_get_edd_dict_1(self): """ Test get_edd_dict()'s pci_dev matching. """ from blivet.devicelibs import edd fs = EddTestFS(self, edd).sda_vda() self.assertEqual(edd.get_edd_dict([]), {'sda' : 0x80, 'vda' : 0x81}) def test_get_edd_dict_2(self): """ Test get_edd_dict()'s pci_dev matching. """ from blivet.devicelibs import edd edd.collect_mbrs = mock.Mock(return_value = { 'sda' : '0x000ccb01', 'vda' : '0x0006aef1'}) fs = EddTestFS(self, edd).sda_vda_missing_details() self.assertEqual(edd.get_edd_dict([]), {'sda' : 0x80, 'vda' : 0x81}) def test_get_edd_dict_3(self): """ Test scenario when the 0x80 and 0x81 edd directories contain the same data and give no way to distinguish among the two devices. """ from blivet.devicelibs import edd edd.log = mock.Mock() edd.collect_mbrs = mock.Mock(return_value={'sda' : '0x000ccb01', 'vda' : '0x0006aef1'}) fs = EddTestFS(self, edd).sda_sdb_same() self.assertEqual(edd.get_edd_dict([]), {}) self.assertIn((('edd: both edd entries 0x80 and 0x81 seem to map to sda',), {}), edd.log.info.call_args_list) class EddTestFS(object): def __init__(self, test_case, target_module): self.fs = mock.DiskIO() test_case.take_over_io(self.fs, target_module) def sda_vda_missing_details(self): self.fs["/sys/firmware/edd/int13_dev80"] = self.fs.Dir() self.fs["/sys/firmware/edd/int13_dev80/mbr_signature"] = "0x000ccb01\n" self.fs["/sys/firmware/edd/int13_dev81"] = self.fs.Dir() self.fs["/sys/firmware/edd/int13_dev81/mbr_signature"] = "0x0006aef1\n" def sda_vda(self): self.fs["/sys/firmware/edd/int13_dev80"] = self.fs.Dir() self.fs["/sys/firmware/edd/int13_dev80/host_bus"] = "PCI 00:01.1 channel: 0\n" self.fs["/sys/firmware/edd/int13_dev80/interface"] = "ATA device: 0\n" self.fs["/sys/firmware/edd/int13_dev80/mbr_signature"] = "0x000ccb01\n" self.fs["/sys/firmware/edd/int13_dev80/sectors"] = "2097152\n" self.fs["/sys/firmware/edd/int13_dev81"] = self.fs.Dir() self.fs["/sys/firmware/edd/int13_dev81/host_bus"] = "PCI 00:05.0 channel: 0\n" self.fs["/sys/firmware/edd/int13_dev81/interface"] = "SCSI id: 0 lun: 0\n" self.fs["/sys/firmware/edd/int13_dev81/mbr_signature"] = "0x0006aef1\n" self.fs["/sys/firmware/edd/int13_dev81/sectors"] = "16777216\n" self.fs["/sys/devices/pci0000:00/0000:00:01.1/host0/target0:0:0/0:0:0:0/block"] = self.fs.Dir() self.fs["/sys/devices/pci0000:00/0000:00:01.1/host0/target0:0:0/0:0:0:0/block/sda"] = self.fs.Dir() self.fs["/sys/devices/pci0000:00/0000:00:05.0/virtio2/block"] = self.fs.Dir() self.fs["/sys/devices/pci0000:00/0000:00:05.0/virtio2/block/vda"] = self.fs.Dir() return self.fs def sda_vda_no_pcidev(self): self.sda_vda() entries = [e for e in self.fs.fs if e.startswith("/sys/devices/pci")] map(self.fs.os_remove, entries) return self.fs def sda_vda_no_host_bus(self): self.sda_vda() self.fs["/sys/firmware/edd/int13_dev80/host_bus"] = "PCI 00:01.1 channel: \n" self.fs.os_remove("/sys/firmware/edd/int13_dev80/mbr_signature") self.fs.os_remove("/sys/firmware/edd/int13_dev81/mbr_signature") def sda_cciss(self): self.fs["/sys/firmware/edd/int13_dev80"] = self.fs.Dir() self.fs["/sys/firmware/edd/int13_dev80/host_bus"] = "PCIX 05:00.0 channel: 0\n" self.fs["/sys/firmware/edd/int13_dev80/interface"] = "RAID identity_tag: 0\n" self.fs["/sys/firmware/edd/int13_dev80/mbr_signature"] = "0x000ccb01\n" self.fs["/sys/firmware/edd/int13_dev80/sectors"] = "2097152\n" return self.fs def vda_vdb(self): self.fs["/sys/firmware/edd/int13_dev80"] = self.fs.Dir() self.fs["/sys/firmware/edd/int13_dev80/host_bus"] = "PCI 00:05.0 channel: 0\n" self.fs["/sys/firmware/edd/int13_dev80/interface"] = "SCSI id: 0 lun: 0\n" self.fs["/sys/firmware/edd/int13_dev80/sectors"] = "16777216\n" self.fs["/sys/firmware/edd/int13_dev81"] = self.fs.Dir() self.fs["/sys/firmware/edd/int13_dev81/host_bus"] = "PCI 00:06.0 channel: 0\n" self.fs["/sys/firmware/edd/int13_dev81/interface"] = "SCSI id: 0 lun: 0\n" self.fs["/sys/firmware/edd/int13_dev81/sectors"] = "4194304\n" return self.fs def sda_sdb_same(self): self.fs["/sys/firmware/edd/int13_dev80"] = self.fs.Dir() self.fs["/sys/firmware/edd/int13_dev80/host_bus"] = "PCI 00:01.1 channel: 0\n" self.fs["/sys/firmware/edd/int13_dev80/interface"] = "ATA device: 0\n" self.fs["/sys/firmware/edd/int13_dev80/mbr_signature"] = "0x000ccb01" self.fs["/sys/firmware/edd/int13_dev80/sectors"] = "2097152\n" self.fs["/sys/firmware/edd/int13_dev81"] = self.fs.Dir() self.fs["/sys/firmware/edd/int13_dev81/host_bus"] = "PCI 00:01.1 channel: 0\n" self.fs["/sys/firmware/edd/int13_dev81/interface"] = "ATA device: 0\n" self.fs["/sys/firmware/edd/int13_dev81/mbr_signature"] = "0x0006aef1" self.fs["/sys/firmware/edd/int13_dev81/sectors"] = "2097152\n" self.fs["/sys/devices/pci0000:00/0000:00:01.1/host0/target0:0:0/0:0:0:0/block"] = self.fs.Dir() self.fs["/sys/devices/pci0000:00/0000:00:01.1/host0/target0:0:0/0:0:0:0/block/sda"] = self.fs.Dir()
gpl-2.0
2,521,215,230,570,225,700
43.353774
107
0.605764
false
2.787726
true
false
false
Marcelpv96/SITWprac2017
sportsBetting/migrations/0018_auto_20170515_1009.py
1
1050
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-05-15 10:09 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('sportsBetting', '0017_auto_20170510_1614'), ] operations = [ migrations.RemoveField( model_name='event', name='api_id', ), migrations.AddField( model_name='event', name='id', field=models.AutoField(auto_created=True, default=1, primary_key=True, serialize=False, verbose_name='ID'), preserve_default=False, ), migrations.AddField( model_name='team', name='created_by', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), preserve_default=False, ), ]
gpl-3.0
7,969,951,120,777,904,000
29.882353
121
0.612381
false
4.007634
false
false
false
djb1815/Essex-MuSoc
musoc_web/schedule/views.py
1
1465
from django.shortcuts import render, redirect from django.db import transaction from django.contrib.auth.decorators import login_required from .forms import ProfileNameForm, ProfileDetailForm from django.contrib import messages # Create your views here. def index(request): # Add variables in the custom_variables dict below to make them available within the rendered page title = "Welcome" custom_variables = { 'title': title } return render(request, "schedule/home.html", custom_variables) @login_required @transaction.atomic def profile(request): title = "Account Settings" if request.method == 'POST': name_form = ProfileNameForm(request.POST, instance=request.user) detail_form = ProfileDetailForm(request.POST, instance=request.user.profile) if name_form.is_valid() and detail_form.is_valid(): name_form.save() detail_form.save() messages.success(request, 'Your profile has been successfully updated!') return redirect('profile') else: messages.error(request, 'Please correct the error below.') else: name_form = ProfileNameForm(instance=request.user) detail_form = ProfileDetailForm(instance=request.user.profile) custom_variables = { 'title': title, 'name_form': name_form, 'detail_form': detail_form } return render(request, "account/profile.html", custom_variables)
mit
6,622,172,651,528,371,000
34.731707
102
0.686689
false
4.221902
false
false
false
cloughrm/Flask-Angular-Template
backend/pastry/resources/v1/users.py
1
1720
from pastry.db import mongo from pastry.models import User from pastry.resources.auth import login_required from pastry.resources import validators, httpcodes from bson.objectid import ObjectId from flask import request from flask.ext.restful import Resource, reqparse class UsersResource(Resource): @login_required def get(self, id): return mongo.db.users.find_one_or_404({'_id': ObjectId(id)}) @login_required def delete(self, id): return mongo.db.users.remove({'_id': ObjectId(id)}) class UsersListResource(Resource): def __init__(self): self.parser = reqparse.RequestParser() if request.method == 'GET': self.parser.add_argument('limit', type=int, default=20) self.parser.add_argument('offset', type=int, default=0) elif request.method == 'POST': self.parser.add_argument('username', type=validators.email_address, required=True) self.parser.add_argument('password', type=str, required=True) super(UsersListResource, self).__init__() @login_required def get(self): args = self.parser.parse_args() users = mongo.db.users.find().skip(args.offset).limit(args.limit) return { 'objects': users, 'offset': args.offset, 'limit': args.limit, } @login_required def post(self): args = self.parser.parse_args() user = User(args.username, args.password) if mongo.db.users.find_one({'username': user.username}): return {'message': 'User {} already exists'.format(user.username)}, httpcodes.BAD_REQUEST user_id = user.create() return {'id': user_id}, httpcodes.CREATED
mit
-4,205,179,780,906,292,700
33.4
101
0.640116
false
3.813747
false
false
false
shanksauce/mintr
mintr/__init__.py
1
1862
import requests import time import re from pprint import pprint auth_headers = {} def _validate_credentials(fn): def wrapper(*args): def is_not_populated(d,r): return reduce( lambda x,y: x or y, map(lambda k: k not in d or not d[k], r) ) if is_not_populated(auth_headers, ('cookie', 'token')): raise Exception('Login first') return fn(*args) return wrapper def login(username, password): if username is None or password is None: raise Exception('Use valid credentials') a = requests.get('https://wwws.mint.com/login.event') session_id = a.cookies.get('MINTJSESSIONID') route_id = a.cookies.get('ROUTEID') b = requests.post( 'https://wwws.mint.com/loginUserSubmit.xevent', cookies = a.cookies, headers = { 'Accept': 'application/json', 'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Cookie': 'MINTJSESSIONID={0}; ROUTEID={1}'.format(session_id, route_id) }, data = { 'username': username, 'password': password, 'task': 'L' } ) csrf_token = b.json()['CSRFToken'] match = re.search('MINTJSESSIONID=(.*?);', b.headers['set-cookie']) if match is None: raise Exception('No MINTJSESSIONID') b_session_id = match.groups(0)[0] #@_validate_credentials def get_account_summaries(jwt=None): if jwt is None: return {} try: d = requests.get( 'https://mint.finance.intuit.com/v1/accounts?limit=1000', headers = {'Authorization': 'Bearer ' + jwt} ) accounts = dict(map( lambda x: ( x['fiName'] + ' ' + x['cpAccountName'], x['currentBalance'] ), filter( lambda x: x['accountStatus'] == 'ACTIVE' and x['currentBalance'] > 0, d.json()['Account'] ) )) return accounts except Exception as ex: return {}
mit
3,864,896,717,037,192,700
24.162162
77
0.605263
false
3.342908
false
false
false
davidtrem/ThunderStorm
thunderstorm/lightning/utils.py
1
5027
# -*- coding: utf-8 -*- # Copyright (C) 2010-2013 Trémouilles David #This file is part of Thunderstorm. # #ThunderStrom is free software: you can redistribute it and/or modify #it under the terms of the GNU Lesser General Public License as published by #the Free Software Foundation, either version 3 of the License, or #(at your option) any later version. # #ThunderStorm 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 Lesser General Public License for more details. # #You should have received a copy of the GNU Lesser General Public License #along with ThunderStorm. If not, see <http://www.gnu.org/licenses/>. """ Various utility functions """ import matplotlib from weakref import WeakValueDictionary from weakref import WeakKeyDictionary import warnings class UniversalCursors(object): def __init__(self): self.all_cursor_orient = WeakKeyDictionary() self.all_canvas = WeakValueDictionary() self.all_axes = WeakValueDictionary() self.backgrounds = {} self.visible = True self.needclear = False def _onmove(self, event): for canvas in self.all_canvas.values(): if not canvas.widgetlock.available(self): return if event.inaxes is None or not self.visible: if self.needclear: self._update(event) for canvas in self.all_canvas.values(): canvas.draw() self.needclear = False return self._update(event) def _update(self, event): # 1/ Reset background for canvas in self.all_canvas.values(): canvas.restore_region(self.backgrounds[id(canvas)]) # 2/ update cursors for cursors in self.all_cursor_orient.keys(): orient = self.all_cursor_orient[cursors] if (event.inaxes in [line.get_axes() for line in cursors] and self.visible): visible = True self.needclear = True else: visible = False for line in cursors: if orient == 'vertical': line.set_xdata((event.xdata, event.xdata)) if orient == 'horizontal': line.set_ydata((event.ydata, event.ydata)) line.set_visible(visible) ax = line.get_axes() ax.draw_artist(line) # 3/ update canvas for canvas in self.all_canvas.values(): canvas.blit(canvas.figure.bbox) def _clear(self, event): """clear the cursor""" self.backgrounds = {} for canvas in self.all_canvas.values(): self.backgrounds[id(canvas)] = ( canvas.copy_from_bbox(canvas.figure.bbox)) for cursor in self.all_cursor_orient.keys(): for line in cursor: line.set_visible(False) def add_cursor(self, axes=(), orient='vertical', **lineprops): class CursorList(list): def __hash__(self): return hash(tuple(self)) cursors = CursorList() # Required to keep weakref for ax in axes: self.all_axes[id(ax)] = ax ax_canvas = ax.get_figure().canvas if ax_canvas not in self.all_canvas.values(): #if not ax_canvas.supports_blit: # warnings.warn("Must use canvas that support blit") # return self.all_canvas[id(ax_canvas)] = ax_canvas ax_canvas.mpl_connect('motion_notify_event', self._onmove) ax_canvas.mpl_connect('draw_event', self._clear) if orient == 'vertical': line = ax.axvline(ax.get_xbound()[0], visible=False, animated=True, **lineprops) if orient == 'horizontal': line = ax.axhline(ax.get_ybound()[0], visible=False, animated=True, **lineprops) cursors.append(line) self.all_cursor_orient[cursors] = orient return cursors def autoscale_visible_lines(axs): """ Function to autoscale only on visible lines. """ mplt_ver = [int(elem) for elem in matplotlib.__version__.split('.')[0:2]] ignore = True for line in (axs.lines): if not line.get_visible(): continue # jump to next line if this one is not visible if mplt_ver[0] == 0 and mplt_ver[1] < 98: axs.dataLim.update_numerix(line.get_xdata(), line.get_ydata(), ignore) else: axs.dataLim.update_from_data_xy(line.get_xydata(), ignore) ignore = False axs.autoscale_view() return None def neg_bool_list(a_list): return [not elem for elem in a_list]
gpl-3.0
895,360,067,562,563,700
35.686131
77
0.569041
false
4.129827
false
false
false
MicroPyramid/forex-python
setup.py
1
1589
import io import os from setuptools import setup, find_packages VERSION = '1.6' long_description_text = """Forex Python is a Free Foreign exchange rates and currency conversion. Features: List all currency rates. BitCoin price for all curuncies. Converting amount to BitCoins. Get historical rates for any day since 1999. Conversion rate for one currency(ex; USD to INR). Convert amount from one currency to other.('USD 10$' to INR). Currency symbols. Currency names. Documentation: http://forex-python.readthedocs.io/en/latest/usage.html GitHub: https://github.com/MicroPyramid/forex-python """ setup( name='forex-python', version=VERSION, author='Micro Pyramid Informatic Pvt. Ltd.', author_email='hello@micropyramid.com', url='https://github.com/MicroPyramid/forex-python', description='Foreign exchange rates and currency conversion.', long_description=long_description_text, packages=find_packages(exclude=['tests', 'tests.*']), include_package_data=True, install_requires=[ 'requests', 'simplejson', ], classifiers=[ 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Internationalization', ], )
mit
7,102,093,925,092,458,000
32.104167
97
0.680931
false
4.032995
false
false
false
answer-huang/StatisticsCodeLines
statistics.py
1
3024
#coding=utf-8 __author__ = 'answer-huang' import sys reload(sys) sys.setdefaultencoding('utf8') """ 代码行统计工具 """ import wx from MyInfo import AboutMe from AHDropTarget import AHDropTarget import os class AHFrame(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, -1, title, wx.DefaultPosition, wx.Size(500, 380), style=wx.DEFAULT_FRAME_STYLE ^ (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX)) #style=wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX) self.SetTransparent(250) self.statusbar = self.CreateStatusBar() self.statusbar.SetForegroundColour('red') self.statusbar.SetFieldsCount(2) self.statusbar.SetStatusWidths([-2, -1]) #大小比例2:1 toolbar = self.CreateToolBar() toolbar.AddSeparator() toolbar.AddSimpleTool(1, wx.Image('about.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap(), "关于我", "") toolbar.AddSeparator() toolbar.AddSimpleTool(2, wx.Image('donate.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap(), "捐助我", "") toolbar.Realize() #准备显示工具栏 wx.EVT_TOOL(self, 1, self.OnAboutMe) wx.EVT_TOOL(self, 2, self.OnDonate) self.panel = wx.Panel(self) self.panel.SetDropTarget(AHDropTarget(self)) self.font = wx.Font(18, wx.SCRIPT, wx.BOLD, wx.LIGHT) self.selectedPath = wx.StaticText(self.panel, -1, u'将项目拖拽到这里', pos=(178, 280)) self.selectedPath.SetFont(self.font) self.panel.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow) self.panel.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow) self.panel.Bind(wx.EVT_MOTION, self.OnMotion) def OnEnterWindow(self, event): #print event.LeftIsDown() event.Skip() def OnLeaveWindow(self, event): #print "leave" event.Skip() def OnMotion(self, event): if event.Dragging() and event.LeftIsDown(): print '按住了鼠标移动' event.Skip() def UpdateStatus(self, path, codes_num): self.statusbar.SetStatusText(path, 0) self.statusbar.SetStatusText(codes_num, 1) def ShowImage(self, img): self.image = wx.Image(img, wx.BITMAP_TYPE_JPEG).Rescale(500, 350, quality=wx.IMAGE_QUALITY_HIGH) bitmap = self.image.ConvertToBitmap() self.logo = wx.StaticBitmap(self.panel, bitmap=bitmap, pos=(0, 0), size=(500, 350)) def ShowPathDir(self, dirList): wx.CheckListBox(self.panel, -1, choices=dirList) def OnAboutMe(self, event): aboutMe = AboutMe(self) aboutMe.ShowModal() aboutMe.Destroy() def OnDonate(self, event): #wx.BeginBusyCursor() import webbrowser webbrowser.open('https://me.alipay.com/huangaiwu') #wx.EndBusyCursor() if __name__ == '__main__': app = wx.App(redirect=False) frame = AHFrame(None, '代码统计工具') frame.Show(True) app.MainLoop()
mit
6,652,973,643,853,062,000
30.902174
105
0.630198
false
3.043568
false
false
false
klahnakoski/ActiveData
vendor/mo_testing/fuzzytestcase.py
1
9712
# encoding: utf-8 # # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Contact: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import unicode_literals import datetime import types import unittest from mo_collections.unique_index import UniqueIndex import mo_dots from mo_dots import coalesce, is_container, is_list, literal_field, unwrap, to_data, is_data, is_many from mo_future import is_text, zip_longest, first from mo_logs import Except, Log, suppress_exception from mo_logs.strings import expand_template, quote import mo_math from mo_math import is_number, log10 from mo_times import dates class FuzzyTestCase(unittest.TestCase): """ COMPARE STRUCTURE AND NUMBERS! ONLY THE ATTRIBUTES IN THE expected STRUCTURE ARE TESTED TO EXIST EXTRA ATTRIBUTES ARE IGNORED. NUMBERS ARE MATCHED BY ... * places (UP TO GIVEN SIGNIFICANT DIGITS) * digits (UP TO GIVEN DECIMAL PLACES, WITH NEGATIVE MEANING LEFT-OF-UNITS) * delta (MAXIMUM ABSOLUTE DIFFERENCE FROM expected) """ def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) self.default_places=15 def set_default_places(self, places): """ WHEN COMPARING float, HOW MANY DIGITS ARE SIGNIFICANT BY DEFAULT """ self.default_places=places def assertAlmostEqual(self, test_value, expected, msg=None, digits=None, places=None, delta=None): if delta or digits: assertAlmostEqual(test_value, expected, msg=msg, digits=digits, places=places, delta=delta) else: assertAlmostEqual(test_value, expected, msg=msg, digits=digits, places=coalesce(places, self.default_places), delta=delta) def assertEqual(self, test_value, expected, msg=None, digits=None, places=None, delta=None): self.assertAlmostEqual(test_value, expected, msg=msg, digits=digits, places=places, delta=delta) def assertRaises(self, problem=None, function=None, *args, **kwargs): if function is None: return RaiseContext(self, problem=problem or Exception) with RaiseContext(self, problem=problem): function(*args, **kwargs) class RaiseContext(object): def __init__(self, this, problem=Exception): self.this = this self.problem = problem def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): if not exc_val: Log.error("Expecting an error") f = Except.wrap(exc_val) if isinstance(self.problem, (list, tuple)): problems = self.problem else: problems = [self.problem] causes = [] for problem in problems: if isinstance(problem, object.__class__) and issubclass(problem, BaseException) and isinstance(exc_val, problem): return True try: self.this.assertIn(problem, f) return True except Exception as cause: causes.append(cause) Log.error("problem is not raised", cause=first(causes)) def assertAlmostEqual(test, expected, digits=None, places=None, msg=None, delta=None): show_detail = True test = unwrap(test) expected = unwrap(expected) try: if test is None and (is_null_op(expected) or expected is None): return elif test is expected: return elif is_text(expected): assertAlmostEqualValue(test, expected, msg=msg, digits=digits, places=places, delta=delta) elif isinstance(test, UniqueIndex): if test ^ expected: Log.error("Sets do not match") elif is_data(expected) and is_data(test): for k, e in unwrap(expected).items(): t = test.get(k) assertAlmostEqual(t, e, msg=coalesce(msg, "")+"key "+quote(k)+": ", digits=digits, places=places, delta=delta) elif is_data(expected): if is_many(test): test = list(test) if len(test) != 1: Log.error("Expecting data, not a list") test = test[0] for k, e in expected.items(): try: t = test[k] assertAlmostEqual(t, e, msg=msg, digits=digits, places=places, delta=delta) continue except: pass t = mo_dots.get_attr(test, literal_field(k)) assertAlmostEqual(t, e, msg=msg, digits=digits, places=places, delta=delta) elif is_container(test) and isinstance(expected, set): test = set(to_data(t) for t in test) if len(test) != len(expected): Log.error( "Sets do not match, element count different:\n{{test|json|indent}}\nexpecting{{expectedtest|json|indent}}", test=test, expected=expected ) try: return len(set(test)|expected) == len(expected) except: for e in expected: for t in test: try: assertAlmostEqual(t, e, msg=msg, digits=digits, places=places, delta=delta) break except Exception as _: pass else: Log.error("Sets do not match. {{value|json}} not found in {{test|json}}", value=e, test=test) elif isinstance(expected, types.FunctionType): return expected(test) elif hasattr(test, "__iter__") and hasattr(expected, "__iter__"): if test.__class__.__name__ == "ndarray": # numpy test = test.tolist() elif test.__class__.__name__ == "DataFrame": # pandas test = test[test.columns[0]].values.tolist() elif test.__class__.__name__ == "Series": # pandas test = test.values.tolist() if not expected and test == None: return if expected == None: expected = [] # REPRESENT NOTHING for t, e in zip_longest(test, expected): assertAlmostEqual(t, e, msg=msg, digits=digits, places=places, delta=delta) else: assertAlmostEqualValue(test, expected, msg=msg, digits=digits, places=places, delta=delta) except Exception as cause: Log.error( "{{test|json|limit(10000)}} does not match expected {{expected|json|limit(10000)}}", test=test if show_detail else "[can not show]", expected=expected if show_detail else "[can not show]", cause=cause ) def assertAlmostEqualValue(test, expected, digits=None, places=None, msg=None, delta=None): """ Snagged from unittest/case.py, then modified (Aug2014) """ if is_null_op(expected): if test == None: # pandas dataframes reject any comparision with an exception! return else: raise AssertionError(expand_template("{{test|json}} != NULL", locals())) if expected == None: # None has no expectations return if test == expected: # shortcut return if isinstance(expected, (dates.Date, datetime.datetime, datetime.date)): return assertAlmostEqualValue( dates.Date(test).unix, dates.Date(expected).unix, msg=msg, digits=digits, places=places, delta=delta ) if not is_number(expected): # SOME SPECIAL CASES, EXPECTING EMPTY CONTAINERS IS THE SAME AS EXPECTING NULL if is_list(expected) and len(expected) == 0 and test == None: return if is_data(expected) and not expected.keys() and test == None: return if test != expected: raise AssertionError(expand_template("{{test|json}} != {{expected|json}}", locals())) return elif not is_number(test): try: # ASSUME IT IS A UTC DATE test = dates.parse(test).unix except Exception as e: raise AssertionError(expand_template("{{test|json}} != {{expected}}", locals())) num_param = 0 if digits != None: num_param += 1 if places != None: num_param += 1 if delta != None: num_param += 1 if num_param > 1: raise TypeError("specify only one of digits, places or delta") if digits is not None: with suppress_exception: diff = log10(abs(test-expected)) if diff < digits: return standardMsg = expand_template("{{test|json}} != {{expected|json}} within {{digits}} decimal places", locals()) elif delta is not None: if abs(test - expected) <= delta: return standardMsg = expand_template("{{test|json}} != {{expected|json}} within {{delta}} delta", locals()) else: if places is None: places = 15 with suppress_exception: diff = mo_math.log10(abs(test-expected)) if diff == None: return # Exactly the same if diff < mo_math.ceiling(mo_math.log10(abs(test)))-places: return standardMsg = expand_template("{{test|json}} != {{expected|json}} within {{places}} places", locals()) raise AssertionError(coalesce(msg, "") + ": (" + standardMsg + ")") def is_null_op(v): return v.__class__.__name__ == "NullOp"
mpl-2.0
-932,436,513,672,928,600
36.210728
134
0.576091
false
4.138049
true
false
false
PopCap/GameIdea
Engine/Extras/Maya_AnimationRiggingTools/MayaTools/General/Scripts/perforceUtils.py
1
32585
import maya.cmds as cmds from P4 import P4,P4Exception import os, cPickle from functools import partial # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def p4_getLatestRevision(fileName, *args): fileArg = fileName #try to connect p4 = P4() try: p4.connect() except: cmds.confirmDialog(title = "Perforce", icon = "critical", message = "Unable to connect to perforce server.") return #find currently opened file name if fileName == None: fileName = cmds.file(q = True, sceneName = True) syncFiles = [] try: #client info spec = p4.run( "client", "-o" )[0] client = spec.get("Client") owner = spec.get("Owner") p4.user = owner p4.client = client except: cmds.confirmDialog(title = "Perforce", icon = "critical", message = "Unable to obtain client spec information.") #try to get the current file revision on local, and compare to depot try: #Find out the revision of the local version of the file myFile = p4.run_have(fileName)[0] #This will find the revision number of your local file. localRevision = int(myFile['haveRev']) #find out the revision number of the depot version of the file depotVersion = p4.run_files(myFile['depotFile'])[0] #find the depot file path depotFile = depotVersion['depotFile'] #find the depot revision number of the file depotRevision = int(depotVersion['rev']) #check for latest if localRevision != depotRevision: syncFiles.append(depotFile) #Check for scene references in the file allRefs = [] references = cmds.file(q = True, reference = True) for reference in references: nestedRef = cmds.file(reference, q = True, reference = True) allRefs.append(reference) allRefs.append(nestedRef) #loop through all found references and check for latest for ref in allRefs: #get revision of local file myFile = p4.run_have(ref)[0] #get revision number localRefRevision = int(myFile['haveRev']) #grab depot file info depotRefVersion = p4.run_files(myFile['depotFile'])[0] #depot file path depotFile = depotRefVersion['depotFile'] #get depot's revision # depotRefRevision = int(depotRefVersion['rev']) #compare if localRefRevision != depotRefRevision: syncFiles.append(depotFile) #if there are files to sync, do it now if len(syncFiles) > 0: message = "The following files are not at latest revision:\n\n" for file in syncFiles: message += file + "\n" result = cmds.confirmDialog(title = "Perforce", icon = "warning", message = message, button = ["Sync", "Cancel"]) if result == "Sync": #sync files for f in syncFiles: p4.run_sync(f) #ask if user would like to reopen if fileArg == None: result = cmds.confirmDialog(title = "Perforce", icon = "question", message = "Sync Complete. Reopen file to get changes?", button = ["Yes", "Cancel"]) if result == "Yes": cmds.file(fileName, open = True, force = True) else: cmds.confirmDialog(title = "Perforce", icon = "information", message = "This file is already at head revision.", button = "Close") #disconnect from server p4.disconnect() #Handle any p4 errors that come back from trying to run the above code except P4Exception: errorString = "The following errors were encountered:\n\n" for e in p4.errors: errorString += e + "\n" cmds.confirmDialog(title = "Perforce", icon = "critical", message = errorString) p4.disconnect() return # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def p4_checkOutCurrentFile(fileName, *args): fileArg = fileName #try to connect p4 = P4() try: p4.connect() except: cmds.confirmDialog(title = "Perforce", icon = "critical", message = "Unable to connect to perforce server.") return False #find currently opened file name if fileName == None: fileName = cmds.file(q = True, sceneName = True) reopen = False syncFiles = [] try: #client info spec = p4.run( "client", "-o" )[0] client = spec.get("Client") owner = spec.get("Owner") p4.user = owner p4.client = client except: cmds.confirmDialog(title = "Perforce", icon = "critical", message = "Unable to obtain client spec information.") try: #check to see if file is at head revision myFile = p4.run_have(fileName)[0] #This will find the revision number of your local file. localRevision = int(myFile['haveRev']) #find out the revision number of the depot version of the file depotVersion = p4.run_files(myFile['depotFile'])[0] #find the depot file path depotFile = depotVersion['depotFile'] #find the depot revision number of the file depotRevision = int(depotVersion['rev']) #check for latest if localRevision != depotRevision: result = cmds.confirmDialog(title = "Perforce", icon = "warning", message = "This file is not at head revision. Please get latest and try again.", button = ["Get Latest", "Cancel"]) if result == "Get Latest": p4_getLatestRevision(fileArg) p4.disconnect() else: return False else: try: #check to see if file is checked out opened = p4.run_opened(depotFile) if len(opened) > 0: user = opened[0]['user'] cmds.confirmDialog(title = "Perforce", icon = "warning", message = "This file is already checked out by: " + user, button = "Close") p4.disconnect() else: #check out the file p4.run_edit(depotFile) cmds.confirmDialog(title = "Perfoce", icon = "information", message = "This file is now checked out.", button = "Close") p4.disconnect() #tools path toolsPath = cmds.internalVar(usd = True) + "mayaTools.txt" if os.path.exists(toolsPath): f = open(toolsPath, 'r') mayaToolsDir = f.readline() f.close() return True #Handle any p4 errors that come back from trying to run the above code except P4Exception: errorString = "The following errors were encountered:\n\n" for e in p4.errors: errorString += e + "\n" cmds.confirmDialog(title = "Perforce", icon = "critical", message = errorString) return False #Handle any p4 errors that come back from trying to run the above code except P4Exception: errorString = "The following errors were encountered:\n\n" for e in p4.errors: errorString += e + "\n" cmds.confirmDialog(title = "Perforce", icon = "critical", message = errorString) p4.disconnect() return False # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def p4_getRevisionHistory(*args): #try to connect p4 = P4() try: p4.connect() except: cmds.confirmDialog(title = "Perforce", icon = "critical", message = "Unable to connect to perforce server.") return #find currently opened file name clientFile = cmds.file(q = True, sceneName = True) reopen = False syncFiles = [] try: #client info spec = p4.run( "client", "-o" )[0] client = spec.get("Client") owner = spec.get("Owner") p4.user = owner p4.client = client except: cmds.confirmDialog(title = "Perforce", icon = "critical", message = "Unable to obtain client spec information.") #get revision history of current file try: #check to see if file is at head revision myFile = p4.run_have(clientFile)[0] depotVersion = p4.run_files(myFile['depotFile'])[0] depotFile = depotVersion['depotFile'] history = p4.run_changes(depotFile) info = "" for h in history: user = h.get("user") change = h.get("change") desc = h.get("desc") if desc.find("\n") == -1: desc = desc + "...\n" else: desc = desc.partition("\n")[0] + "...\n" info += change + " by " + user + ": " + desc #print report into a confirm dialog cmds.confirmDialog(title = "History", icon = "information", ma = "left", message = info, button = "Close") p4.disconnect() except P4Exception: errorString = "The following errors were encountered:\n\n" for e in p4.errors: errorString += e + "\n" cmds.confirmDialog(title = "Perforce", icon = "critical", message = errorString) p4.disconnect() return # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def p4_submitCurrentFile(fileName, desc, *args): fileArg = fileName #try to connect p4 = P4() try: p4.connect() except: cmds.confirmDialog(title = "Perforce", icon = "critical", message = "Unable to connect to perforce server.") return #find currently opened file name if fileName == None: fileName = cmds.file(q = True, sceneName = True) reopen = False syncFiles = [] try: #client info spec = p4.run( "client", "-o" )[0] client = spec.get("Client") owner = spec.get("Owner") p4.user = owner p4.client = client except: cmds.confirmDialog(title = "Perforce", icon = "critical", message = "Unable to obtain client spec information.") #SUBMIT try: if desc == None: result = cmds.promptDialog(title = "Perforce", message = "Please Enter a Description..", button = ["Accept", "Cancel"], defaultButton = "Accept", dismissString = "Cancel", cancelButton = "Cancel") else: result = "Accept" #process if result == "Accept": #description = "test" myFile = p4.run_have(fileName)[0] depotVersion = p4.run_files(myFile['depotFile'])[0] depotFile = depotVersion['depotFile'] #check to see if file is checked out opened = p4.run_opened(depotFile) if len(opened) > 0: opendBy = opened[0]['user'] if opendBy.lower() != owner.lower(): cmds.confirmDialog(title = "Perforce", icon = "warning", message = "This file is already checked out by: " + opendBy, button = "Close") p4.disconnect() return else: #fetch the description if desc == None: desc = cmds.promptDialog(q = True, text = True) #save the file locally (so depot and HD are in sync) openedFile = cmds.file(q = True, sceneName = True) saveFileName = openedFile.rpartition("/")[2] if fileArg == None: cmds.file(f = True, save = True, options = "v = 0", type = "mayaBinary") #grab the name of the file fileNameWithExt = openedFile.rpartition("/")[2] fileName = fileNameWithExt.rpartition(".")[0] description = (desc + "\n Affected Files: " + openedFile) #create new changelist newChange = p4.fetch_change() newChange._description = description #make sure we don't add existing default changelist files. newChange._files = [] #determine the new number so we can refetch it. newChangeNum = int(p4.save_change(newChange)[0].split()[1]) #change changelist number p4.run_reopen('-c', newChangeNum, depotFile) #submit the changelist p4.run_submit('-c', newChangeNum) #tell the user submit was successful if fileArg == None: cmds.confirmDialog(title = "Perforce", icon = "information", message = "Submit Operation was successful!", button = "Close") else: return True else: #if the file is not checked out by the user, let them know result = cmds.confirmDialog(title = "Perforce", icon = "warning", message = "File is not checked out. Unable to continue submit operation on this file:\n\n" + fileName) except P4Exception: if fileArg == None: errorString = "The following errors were encountered:\n\n" for e in p4.errors: errorString += e + "\n" cmds.confirmDialog(title = "Perforce", icon = "critical", message = errorString) p4.disconnect() return False # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def p4_addAndSubmitCurrentFile(fileName, description, *args): fileArg = fileName #try to connect p4 = P4() try: p4.connect() except: cmds.confirmDialog(title = "Perforce", icon = "critical", message = "Unable to connect to perforce server.") return #find currently opened file name if fileName == None: fileName = cmds.file(q = True, sceneName = True) reopen = False syncFiles = [] try: #client info spec = p4.run( "client", "-o" )[0] client = spec.get("Client") owner = spec.get("Owner") p4.user = owner p4.client = client except: cmds.confirmDialog(title = "Perforce", icon = "critical", message = "Unable to obtain client spec information.") #find currently opened file name proceed = False if fileArg == None: fileName = cmds.file(q = True, sceneName = True) if fileName == "": cmds.confirmDialog(title = "Perforce", icon = "warning", message = "Cannot Add file to perforce as file has no name.", button = "Close") p4.disconnect() return else: proceed = True else: proceed = True #if the file has a filename, if proceed: try: clientRoot = p4.fetch_client(p4.client)._Root #check to make sure client root is in the client file path if os.path.normpath(fileName).find(os.path.normpath(clientRoot)) == 0: #if it was, then get a description for the changelist if description == None: result = cmds.promptDialog(title = "Perforce", message = "Please Enter a Description..", button = ["Accept", "Cancel"], defaultButton = "Accept", dismissString = "Cancel", cancelButton = "Cancel") else: result = "Accept" if result == "Accept": #get changelist description if description == None: description = cmds.promptDialog(q = True, text = True) #create changelist newChange = p4.fetch_change() newChange._description = description #make sure we don't add existing default changelist files. newChange._files = [] #determine the new number so we can refetch it. newChangeNum = int(p4.save_change(newChange)[0].split()[1]) #description = "test" p4.run_add('-c', newChangeNum, fileName) #submit the changelist p4.run_submit('-c', newChangeNum) #tell user operation was successful if fileArg == None: result = cmds.confirmDialog(title = "Perforce", icon = "information", message = "File has been successfully added to perforce and submitted!", button = ["Close", "Check Out File"]) if result == "Close": p4.disconnect() return if result == "Check Out File": p4_checkOutCurrentFile(fileName) #return operation succuessful return True else: p4.disconnect() return else: cmds.confirmDialog(title = "Perforce", icon = "warning", message = "Cannot proceed. File is not under client's root, " + clientRoot, button = "Close") p4.disconnect() return False except P4Exception: errorString = "The following errors were encountered:\n\n" for e in p4.errors: errorString += e + "\n" cmds.confirmDialog(title = "Perforce", icon = "critical", message = errorString) p4.disconnect() return False # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def p4_checkForUpdates(*args): #try to connect p4 = P4() #get maya tools path toolsPath = cmds.internalVar(usd = True) + "mayaTools.txt" if os.path.exists(toolsPath): f = open(toolsPath, 'r') mayaToolsDir = f.readline() f.close() #connect to p4 try: p4.connect() except: cmds.confirmDialog(title = "Perforce", icon = "critical", message = "Unable to connect to perforce server.") return #find currently opened file name clientFile = cmds.file(q = True, sceneName = True) reopen = False syncFiles = [] try: #client info spec = p4.run( "client", "-o" )[0] client = spec.get("Client") owner = spec.get("Owner") p4.user = owner p4.client = client except: cmds.confirmDialog(title = "Perforce", icon = "critical", message = "Unable to obtain client spec information.") #this will check the maya tools directory in p4 for any updates try: syncFiles = [] clientRoot = p4.fetch_client(p4.client)._Root depotDirectories = [] #get current project if os.path.exists(mayaToolsDir + "/General/Scripts/projectSettings.txt"): #read to find current project f = open(mayaToolsDir + "/General/Scripts/projectSettings.txt", 'r') settings = cPickle.load(f) f.close() #write out new settings project = settings.get("CurrentProject") if os.path.exists(mayaToolsDir + "/General/Scripts/" + project + "_Project_Settings.txt"): #read the depot paths to sync from the project settings f = open(mayaToolsDir + "/General/Scripts/" + project + "_Project_Settings.txt", 'r') settings = cPickle.load(f) f.close() depotDirectories = settings.get("depotPaths") print depotDirectories #look at each directory inside MayaTools for dir in depotDirectories: depotFiles = p4.run_files(dir + "...") for each in depotFiles: #try to compare depot to local. It is possible that there are local files not in depot, and vise versa try: fileInfo = p4.run_files(each['depotFile'])[0] depotFilePath = fileInfo['depotFile'] fileName = depotFilePath.rpartition("/")[2] #compare local files localFile = p4.run_have(depotFilePath)[0] localRevision = int(localFile['haveRev']) depotRevision = int(fileInfo['rev']) if localRevision < depotRevision: syncFiles.append(depotFilePath) except: try: #check to see if it errors out because we don't have a local version of the file fileInfo = p4.run_files(each['depotFile'])[0] depotFilePath = fileInfo['depotFile'] fileName = depotFilePath.rpartition("/")[2] localFile = p4.run_have(depotFilePath)[0] except: action = each.get("action") if action != "delete": syncFiles.append(depotFilePath) pass #check size of syncFiles and ask user if they want to sync if len(syncFiles) > 0: result = cmds.confirmDialog(title = "MayaTools", icon = "warning", message = "There are new updates available to the depot directories specified by your project settings.", button = ["Update", "Not Now"]) if result == "Update": for file in syncFiles: p4.run_sync(file) cmds.confirmDialog(title = "MayaTools", icon = "information", message = "Tools are now up to date!", button = "Close") p4.disconnect() else: p4.disconnect() return #handle any errors except P4Exception: errorString = "The following errors were encountered:\n\n" for e in p4.errors: errorString += e + "\n" cmds.confirmDialog(title = "Perforce", icon = "critical", message = errorString) p4.disconnect() return # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def createNewProject(*args): if cmds.window("createNewARTProject_Window", exists = True): cmds.deleteUI("createNewARTProject_Window") #create window window = cmds.window("createNewARTProject_Window", w = 400, h = 600, mnb = False, mxb = False, title = "Create New Project") #frameLayouts for settings: Perforce/Auto-Sync mainLayout = cmds.columnLayout(w = 400, h = 600) #project name field projectName = cmds.textFieldGrp("newARTProjectNameField", label = "Project Name: ", w = 400, h = 30, parent = mainLayout, cal = [1, "left"]) scrollLayout = cmds.scrollLayout(w = 400, h = 520, parent = mainLayout) columnLayout = cmds.columnLayout(w = 380, parent = scrollLayout) #perforce/auto-sync layout p4Frame = cmds.frameLayout(parent = columnLayout, w = 370, cll = True, label='Perforce/Auto-Sync', borderStyle='in') p4Layout = cmds.columnLayout(w = 360, parent = p4Frame, co = ["both", 5], rs = 5) #create the scrollField with the information cmds.scrollField(parent = p4Layout, w = 350, h = 100, editable = False, wordWrap = True, text = "Add depot paths you would like the tools to check for updates on. If updates are found, you will be notified, and asked if you would like to sync. Valid depot paths look like:\n\n//depot/usr/jeremy_ernst/MayaTools") #crete the add button cmds.button(w = 350, label = "Add Perforce Depot Path", parent = p4Layout, c = partial(addPerforceDepotPath, p4Layout)) #save settings button cmds.button(parent = mainLayout, w = 400, h = 50, label = "Save Settings and Close", c = partial(saveProjectSettings, p4Layout, False)) #show window cmds.showWindow(window) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def editProject(project, *args): if cmds.window("createNewARTProject_Window", exists = True): cmds.deleteUI("createNewARTProject_Window") #create window window = cmds.window("createNewARTProject_Window", w = 400, h = 600, mnb = False, mxb = False, title = "Edit Project") #frameLayouts for settings: Perforce/Auto-Sync mainLayout = cmds.columnLayout(w = 400, h = 600) #project name field projectName = cmds.textFieldGrp("newARTProjectNameField", label = "Project Name: ", text = project, w = 400, h = 30, parent = mainLayout, cal = [1, "left"]) scrollLayout = cmds.scrollLayout(w = 400, h = 520, parent = mainLayout) columnLayout = cmds.columnLayout(w = 380, parent = scrollLayout) #perforce/auto-sync layout p4Frame = cmds.frameLayout(parent = columnLayout, w = 370, cll = True, label='Perforce/Auto-Sync', borderStyle='in') p4Layout = cmds.columnLayout(w = 360, parent = p4Frame, co = ["both", 5], rs = 5) #create the scrollField with the information cmds.scrollField(parent = p4Layout, w = 350, h = 100, editable = False, wordWrap = True, text = "Add depot paths you would like the tools to check for updates on. If updates are found, you will be notified, and asked if you would like to sync. Valid depot paths look like:\n\n//depot/usr/jeremy_ernst/MayaTools") #crete the add button cmds.button(w = 350, label = "Add Perforce Depot Path", parent = p4Layout, c = partial(addPerforceDepotPath, p4Layout)) #get maya tools path toolsPath = cmds.internalVar(usd = True) + "mayaTools.txt" if os.path.exists(toolsPath): f = open(toolsPath, 'r') mayaToolsDir = f.readline() f.close() #open the project settings and auto-fill in the info if os.path.exists(mayaToolsDir + "/General/Scripts/" + project + "_Project_Settings.txt"): f = open(mayaToolsDir + "/General/Scripts/" + project + "_Project_Settings.txt", 'r') settings = cPickle.load(f) f.close() paths = settings.get("depotPaths") if len(paths) > 0: for path in paths: #add the path field = addPerforceDepotPath(p4Layout) cmds.textField(field, edit = True, text = path) #save settings button cmds.button(parent = mainLayout, w = 400, h = 50, label = "Save Settings and Close", c = partial(saveProjectSettings, p4Layout, True)) #show window cmds.showWindow(window) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def addPerforceDepotPath(layout, *args): field = cmds.textField(docTag = "P4DepotPath", w = 350, parent = layout) #add a RMB menu to remove the field menu = cmds.popupMenu(parent = field, b = 3) cmds.menuItem(parent = menu, label = "Remove Path", c = partial(removePerforceDepotPath, field)) return field # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def removePerforceDepotPath(field, *args): cmds.textField(field, edit = True, visible = False, h = 1) #cmds.deleteUI(field) This crashes maya instantly. Come ON AUTODESK # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def saveProjectSettings(perforceLayout, edit, *args): #find p4 depot path textfields children = cmds.columnLayout(perforceLayout, q = True, childArray = True) textFields = [] for child in children: if child.find("textField") == 0: data = cmds.textField(child, q = True, docTag = True) if data == "P4DepotPath": textFields.append(child) #make sure paths are valid savePaths = [] for field in textFields: path = cmds.textField(field, q = True, text = True) if path != "": try: p4 = P4() p4.connect() except: cmds.confirmDialog(title = "Perforce", icon = "critical", message = "Unable to connect to perforce server.") return try: #client info spec = p4.run( "client", "-o" )[0] client = spec.get("Client") owner = spec.get("Owner") p4.user = owner p4.client = client except: cmds.confirmDialog(title = "Perforce", icon = "critical", message = "Unable to obtain client spec information.") #now check try: depotFiles = p4.run_files(path + "...") if len(depotFiles) > 0: savePaths.append(path) #handle any errors except P4Exception: errorString = "The following errors were encountered:\n\n" for e in p4.errors: errorString += e + "\n" cmds.confirmDialog(title = "Perforce", icon = "critical", message = errorString) p4.disconnect() return else: #see if the text field is just hidden or if it is actually blank vis = cmds.textField(field, q = True, visible = True) if vis == True: cmds.confirmDialog(title = "Error", icon = "critical", message = "Empty string not allowed as a path name. Either remove that field, or enter a correct depot path.") return #write out to disk projectName = cmds.textFieldGrp("newARTProjectNameField", q = True, text = True) if projectName == "": cmds.confirmDialog(title = "Error", icon = "critical", message = "Empty string not allowed as a project name.") return #save the new project file under MayaTools/General/Scripts as projName + "_Project_Settings.txt" toolsPath = cmds.internalVar(usd = True) + "mayaTools.txt" if os.path.exists(toolsPath): f = open(toolsPath, 'r') mayaToolsDir = f.readline() f.close() if edit == False: if os.path.exists(mayaToolsDir + "/General/Scripts/" + projectName + "_Project_Settings.txt"): cmds.confirmDialog(title = "Error", icon = "critical", message = "Project already exists with that name") return #save out f = open(mayaToolsDir + "/General/Scripts/" + projectName + "_Project_Settings.txt", 'w') #create a dictionary with values settings = {} settings["depotPaths"] = savePaths #write our dictionary to file cPickle.dump(settings, f) f.close() #delete the UI cmds.deleteUI("createNewARTProject_Window") #add the project to the menu create = True items = cmds.lsUI(menuItems = True) for i in items: data = cmds.menuItem(i, q = True, docTag = True) if data == "P4Proj": label = cmds.menuItem(i, q = True, label = True) print label if label == projectName: create = False if create: menuItem = cmds.menuItem(label = projectName, parent = "perforceProjectList", cl = "perforceProjectRadioMenuCollection", rb = True, docTag = "P4Proj", c = partial(setCurrentProject, projectName)) cmds.menuItem(parent = "perforceProjectList", optionBox = True, c = partial(editProject, projectName)) #open up the projectSettings.txt file and add an entry for current project if os.path.exists(mayaToolsDir + "/General/Scripts/projectSettings.txt"): f = open(mayaToolsDir + "/General/Scripts/projectSettings.txt", 'r') oldSettings = cPickle.load(f) useSourceControl = oldSettings.get("UseSourceControl") f.close() #write out new settings settings = {} settings["UseSourceControl"] = useSourceControl settings["CurrentProject"] = projectName f = open(mayaToolsDir + "/General/Scripts/projectSettings.txt", 'w') cPickle.dump(settings, f) f.close() # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # def setCurrentProject(projectName, *args): #get access to maya tools path toolsPath = cmds.internalVar(usd = True) + "mayaTools.txt" if os.path.exists(toolsPath): f = open(toolsPath, 'r') mayaToolsDir = f.readline() f.close() #re-write settings if os.path.exists(mayaToolsDir + "/General/Scripts/projectSettings.txt"): f = open(mayaToolsDir + "/General/Scripts/projectSettings.txt", 'r') oldSettings = cPickle.load(f) useSourceControl = oldSettings.get("UseSourceControl") f.close() #write out new settings settings = {} settings["UseSourceControl"] = useSourceControl settings["CurrentProject"] = projectName f = open(mayaToolsDir + "/General/Scripts/projectSettings.txt", 'w') cPickle.dump(settings, f) f.close()
bsd-2-clause
-8,773,135,227,386,069,000
14.551724
316
0.561792
false
3.307115
false
false
false
priomsrb/vimswitch
vimswitch/UpdateProfileAction.py
1
1247
from .Action import Action from .Settings import getSettings from .SwitchProfileAction import createSwitchProfileAction class UpdateProfileAction(Action): def __init__(self, settings, switchProfileAction): Action.__init__(self) self.settings = settings self.switchProfileAction = switchProfileAction self.profile = None def execute(self): self.profile = self._getProfile() if self.profile == self.settings.defaultProfile: print('Cannot update default profile') self.exitCode = -1 return self.switchProfileAction.update = True self.switchProfileAction.profile = self.profile self.switchProfileAction.execute() def _getProfile(self): if self.profile is None: if self.settings.currentProfile is None: return self.settings.defaultProfile else: return self.settings.currentProfile else: return self.profile def createUpdateProfileAction(app): settings = getSettings(app) switchProfileAction = createSwitchProfileAction(app) updateProfileAction = UpdateProfileAction(settings, switchProfileAction) return updateProfileAction
gpl-2.0
-8,137,162,348,852,659,000
30.974359
76
0.677626
false
4.85214
false
false
false
indico/indico
indico/modules/events/registration/models/invitations.py
1
3543
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from uuid import uuid4 from sqlalchemy.dialects.postgresql import UUID from indico.core.db import db from indico.core.db.sqlalchemy import PyIntEnum from indico.util.enum import RichIntEnum from indico.util.i18n import L_ from indico.util.locators import locator_property from indico.util.string import format_repr class InvitationState(RichIntEnum): __titles__ = [L_('Pending'), L_('Accepted'), L_('Declined')] pending = 0 accepted = 1 declined = 2 class RegistrationInvitation(db.Model): """An invitation for someone to register.""" __tablename__ = 'invitations' __table_args__ = (db.CheckConstraint('(state = {state}) OR (registration_id IS NULL)' .format(state=InvitationState.accepted), name='registration_state'), db.UniqueConstraint('registration_form_id', 'email'), {'schema': 'event_registration'}) #: The ID of the invitation id = db.Column( db.Integer, primary_key=True ) #: The UUID of the invitation uuid = db.Column( UUID, index=True, unique=True, nullable=False, default=lambda: str(uuid4()) ) #: The ID of the registration form registration_form_id = db.Column( db.Integer, db.ForeignKey('event_registration.forms.id'), index=True, nullable=False ) #: The ID of the registration (if accepted) registration_id = db.Column( db.Integer, db.ForeignKey('event_registration.registrations.id'), index=True, unique=True, nullable=True ) #: The state of the invitation state = db.Column( PyIntEnum(InvitationState), nullable=False, default=InvitationState.pending ) #: Whether registration moderation should be skipped skip_moderation = db.Column( db.Boolean, nullable=False, default=False ) #: The email of the invited person email = db.Column( db.String, nullable=False ) #: The first name of the invited person first_name = db.Column( db.String, nullable=False ) #: The last name of the invited person last_name = db.Column( db.String, nullable=False ) #: The affiliation of the invited person affiliation = db.Column( db.String, nullable=False ) #: The associated registration registration = db.relationship( 'Registration', lazy=True, backref=db.backref( 'invitation', lazy=True, uselist=False ) ) # relationship backrefs: # - registration_form (RegistrationForm.invitations) @locator_property def locator(self): return dict(self.registration_form.locator, invitation_id=self.id) @locator.uuid def locator(self): """A locator suitable for 'display' pages. Instead of the numeric ID it uses the UUID. """ assert self.uuid is not None return dict(self.registration_form.locator, invitation=self.uuid) def __repr__(self): full_name = f'{self.first_name} {self.last_name}' return format_repr(self, 'id', 'registration_form_id', 'email', 'state', _text=full_name)
mit
-4,382,065,804,384,135,000
27.344
109
0.61558
false
3.998871
false
false
false
ajroussel/shell-nouns-data
src/extractor.py
1
3851
#!/usr/bin/env python3 import os import argparse import pickle from lxml import etree from sys import argv from objects import * ## returns a list of ints def to_index(s): outlist = list() spl1 = s.split(',') try: for item in spl1: spl2 = item.split('..') start = int(spl2[0].split('_')[1]) end = int(spl2[1].split('_')[1]) if len(spl2) > 1 else start outlist.extend([i - 1 for i in range(start, end + 1)]) except ValueError: print(s) return outlist def get_SNs(node): snes = list() try: for sn in node.find("shellnouns").iter("shellnoun"): snes.append((sn.get("content_phrases"), to_index(sn.get("span")), sn.get("value"))) except AttributeError: pass return snes if __name__ == '__main__': ap = argparse.ArgumentParser() ap.add_argument("inputfiles", type=str, nargs='+', help="xml input files") ap.add_argument("-o", "--outputfile", type=str, default="sn_data.pickle", help="name of output pickle") ap.add_argument("-a", "--annotated", action="store_true", help="use if xml files are annotated w/SN info") userargs = ap.parse_args() i = 0 corpus = Corpus() for fname in userargs.inputfiles: docroot = etree.parse(fname).getroot() myname, ext = os.path.splitext(fname) print("processing", myname + "...") session_start = i for turn in docroot.iter("turn"): turn_start = i mylang = "de" if "de" in turn.get("turn_id") else "en" for sentence in turn.iter("sent"): sent_start = i for tok in sentence.iter("tok"): corpus.tokens.append(Token(tok.text, tok.attrib, i, mylang, session_start)) i += 1 sent_end = i corpus.sentences.append(range(sent_start, sent_end)) turn_end = i corpus.turns.append(range(turn_start, turn_end)) session_end = i corpus.sessions.append(range(session_start, session_end)) if userargs.annotated: # dict: CP id -> Antecedent cps = dict() for cp in docroot.find("content_phrases").iter("content_phrase"): cp_indices = to_index(cp.get("span")) is_nom = cp.get("nominal") new_ante = Antecedent([corpus.tokens[x + session_start] for x in cp_indices], is_nom) corpus.antecedents.append(new_ante) cps[cp.get("id")] = new_ante # list[tuples] "proto-Anaphor" snes = get_SNs(docroot) for cp_key, sn_indices, val in snes: my_anaphor = Anaphor([corpus.tokens[x + session_start] for x in sn_indices], val) corpus.anaphors.append(my_anaphor) my_antecedents = list() for key in cp_key.split(";"): try: my_antecedents.append(cps[key]) except KeyError: pass my_instance = RefInstance(my_anaphor, *my_antecedents) # only keep (non-empty) entries if my_instance.antecedents: corpus.ref_instances.append(my_instance) with open(userargs.outputfile, 'wb') as outfile: print("read corpus with", len(corpus.tokens), "tokens...") pickle.dump(corpus, outfile) print("done!")
gpl-3.0
7,349,968,066,567,672,000
32.780702
77
0.491041
false
4.015641
false
false
false
CybOXProject/python-cybox
cybox/__init__.py
1
4103
# Copyright (c) 2020, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. from mixbox import entities from mixbox.vendor import six from .version import __version__ # noqa #: Mapping of xsi:types to implementation/extension classes _EXTENSION_MAP = {} def _lookup_unprefixed(typename): """Attempts to resolve a class for the input XML type `typename`. Args: typename: The name of an CybOX XML type (e.g., UnixProcessStatusType) without a namespace prefix. Returns: A stix.Entity implementation class for the `typename`. Raises: ValueError: If no class has been registered for the input `typename`. """ for xsi_type, klass in six.iteritems(_EXTENSION_MAP): if typename in xsi_type: return klass error = "Unregistered extension type: %s" % typename raise ValueError(error) def _lookup_extension(xsi_type): """Returns a Python class for the `xsi_type` value. Args: xsi_type: An xsi:type value string. Returns: An Entity implementation class for the `xsi_type`. Raises: ValueError: If no class has been registered for the `xsi_type`. """ if xsi_type in _EXTENSION_MAP: return _EXTENSION_MAP[xsi_type] raise ValueError("Unregistered xsi:type %s" % xsi_type) def lookup_extension(typeinfo, default=None): """Returns an Entity class for that has been registered for the `typeinfo` value. Note: This is for internal use only. Args: typeinfo: An object or string containing type information. This can be either an xsi:type attribute value or a stix.bindings object. default: Return class if typeinfo is None or contains no xml type information. Returns: An Entity implementation class for the `xsi_type`. Raises: ValueError: If no class has been registered for the `xsi_type`. """ if typeinfo is None and default: return default # If the `typeinfo` was a string, consider it a full xsi:type value. if isinstance(typeinfo, six.string_types): return _lookup_extension(typeinfo) # Most extension bindings include this attribute. if not hasattr(typeinfo, 'xml_type'): if default: return default error = "Input %s is missing xml_type attribute. Cannot lookup class." raise ValueError(error % type(typeinfo)) # Extension binding classes usually (always?) have an `xmlns_prefix` # class attribute. if hasattr(typeinfo, 'xmlns_prefix'): xsi_type = "%s:%s" % (typeinfo.xmlns_prefix, typeinfo.xml_type) return _lookup_extension(xsi_type) # no xmlns_prefix found, try to resolve the class by just the `xml_type` return _lookup_unprefixed(typeinfo.xml_type) def add_extension(cls): """Registers an Entity class as an implementation of an xml type. Classes must have an ``_XSI_TYPE`` class attributes to be registered. The value of this attribute must be a valid xsi:type. Note: This was designed for internal use. """ _EXTENSION_MAP[cls._XSI_TYPE] = cls # noqa def register_extension(cls): """Class decorator for registering a stix.Entity class as an implementation of an xml type. Classes must have an ``_XSI_TYPE`` class attributes to be registered. Note: This was designed for internal use. """ add_extension(cls) return cls # TODO: Should this get moved to mixbox or not? class Unicode(entities.Entity): """Shim class to allow xs:string's in EntityList""" def __init__(self, value): super(Unicode, self).__init__() self.value = value @property def value(self): return self._value @value.setter def value(self, value): self._value = six.text_type(value) def to_obj(self, ns_info=None): return self.value def to_dict(self): return self.value @classmethod def from_obj(cls, cls_obj): return cls(cls_obj) from_dict = from_obj
bsd-3-clause
-1,116,159,880,867,913,500
25.816993
79
0.654155
false
3.995131
false
false
false
mlsecproject/gglsbl-rest
config.py
1
1443
from os import environ import logging.config from apscheduler.schedulers.background import BackgroundScheduler from multiprocessing import cpu_count from subprocess import Popen logging.config.fileConfig('logging.conf') bind = "0.0.0.0:5000" workers = int(environ.get('WORKERS', cpu_count() * 8 + 1)) timeout = int(environ.get('TIMEOUT', 120)) access_log_format = '%(h)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" "%({X-Forwarded-For}i)s" "%({X-Forwarded-Port}i)s" "%({X-Forwarded-Proto}i)s" "%({X-Amzn-Trace-Id}i)s"' max_requests = int(environ.get('MAX_REQUESTS', 16384)) limit_request_line = int(environ.get('LIMIT_REQUEST_LINE', 8190)) keepalive = int(environ.get('KEEPALIVE', 60)) log = logging.getLogger(__name__) def update(): log.info("Starting update process...") po = Popen("python3 update.py", shell=True) log.info("Update started as PID %d", po.pid) rc = po.wait() log.info("Update process finished with status code %d", rc) sched = None def on_starting(server): log.info("Initial database load...") po = Popen("python3 update.py", shell=True) log.info("Update started as PID %d", po.pid) rc = po.wait() log.info("Update process finished with status code %d", rc) log.info("Starting scheduler...") global sched sched = BackgroundScheduler(timezone="UTC") sched.start() sched.add_job(update, id="update", coalesce=True, max_instances=1, trigger='interval', minutes=30)
apache-2.0
-1,130,091,579,888,611,300
33.357143
167
0.677755
false
3.150655
false
false
false
estaban/pyload
module/plugins/hoster/UnrestrictLi.py
1
4420
# -*- coding: utf-8 -*- ############################################################################ # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################ import re from datetime import datetime, timedelta from module.plugins.Hoster import Hoster from module.common.json_layer import json_loads def secondsToMidnight(gmt=0): now = datetime.utcnow() + timedelta(hours=gmt) if now.hour is 0 and now.minute < 10: midnight = now else: midnight = now + timedelta(days=1) midnight = midnight.replace(hour=0, minute=10, second=0, microsecond=0) return int((midnight - now).total_seconds()) class UnrestrictLi(Hoster): __name__ = "UnrestrictLi" __version__ = "0.12" __type__ = "hoster" __pattern__ = r'https?://(?:[^/]*\.)?(unrestrict|unr)\.li' __description__ = """Unrestrict.li hoster plugin""" __author_name__ = "stickell" __author_mail__ = "l.stickell@yahoo.it" def setup(self): self.chunkLimit = 16 self.resumeDownload = True def process(self, pyfile): if re.match(self.__pattern__, pyfile.url): new_url = pyfile.url elif not self.account: self.logError(_("Please enter your %s account or deactivate this plugin") % "Unrestrict.li") self.fail("No Unrestrict.li account provided") else: self.logDebug("Old URL: %s" % pyfile.url) for _ in xrange(5): page = self.req.load('https://unrestrict.li/unrestrict.php', post={'link': pyfile.url, 'domain': 'long'}) self.logDebug("JSON data: " + page) if page != '': break else: self.logInfo("Unable to get API data, waiting 1 minute and retry") self.retry(5, 60, "Unable to get API data") if 'Expired session' in page or ("You are not allowed to " "download from this host" in page and self.premium): self.account.relogin(self.user) self.retry() elif "File offline" in page: self.offline() elif "You are not allowed to download from this host" in page: self.fail("You are not allowed to download from this host") elif "You have reached your daily limit for this host" in page: self.logWarning("Reached daily limit for this host") self.retry(5, secondsToMidnight(gmt=2), "Daily limit for this host reached") elif "ERROR_HOSTER_TEMPORARILY_UNAVAILABLE" in page: self.logInfo("Hoster temporarily unavailable, waiting 1 minute and retry") self.retry(5, 60, "Hoster is temporarily unavailable") page = json_loads(page) new_url = page.keys()[0] self.api_data = page[new_url] if new_url != pyfile.url: self.logDebug("New URL: " + new_url) if hasattr(self, 'api_data'): self.setNameSize() self.download(new_url, disposition=True) if self.getConfig("history"): self.load("https://unrestrict.li/history/&delete=all") self.logInfo("Download history deleted") def setNameSize(self): if 'name' in self.api_data: self.pyfile.name = self.api_data['name'] if 'size' in self.api_data: self.pyfile.size = self.api_data['size']
gpl-3.0
7,935,763,041,935,266,000
43.646465
104
0.541629
false
4.25409
false
false
false
mikeh69/JammerDetect
src/audio_tones.py
1
3644
import math #import needed modules import pyaudio #sudo apt-get install python-pyaudio import struct import pickle from time import sleep PyAudio = pyaudio.PyAudio #initialize pyaudio #See http://en.wikipedia.org/wiki/Bit_rate#Audio BITRATE = 48000 #number of frames per second - 44.1kHz does not work properly on RPi BCM2538! LENGTH = 0.2 #seconds to play sound CHUNKSIZE = int(BITRATE * LENGTH) WAVEDATA_FILE = "/home/pi/wavedata.pickled" class AudioTones: def init(self): self.player = PyAudio() defaultCapability = self.player.get_default_host_api_info() print("Player defaults:") print(defaultCapability) # fmt = self.player.get_format_from_width(2) # fmt = pyaudio.paInt8 # supposedly 8-bit signed-integer fmt = pyaudio.paInt16 # 16-bit signed-integer print(self.player.is_format_supported(output_format = fmt, output_channels = 1, rate = BITRATE, output_device = 3)) self.stream = self.player.open(format = fmt, channels = 1, rate = BITRATE, output = True, frames_per_buffer = CHUNKSIZE) try: print("Trying to load wavedata from file...") f = open(WAVEDATA_FILE, "rb") print(" File opened OK") self.WAVEDATA = pickle.load(f) print(" Wavedata read from file OK") f.close() return except Exception as ex: print(ex) print("Failed to load wavedata from file, re-generating") frequency = 200.0 # start frequency 200Hz self.WAVEDATA = [] for index in range(0, 46): # valid index range 0 - 45, ~10log(32768) num_fadein_frames = int(BITRATE * LENGTH * 0.05) num_loud_frames = int(BITRATE * LENGTH * 0.7) num_fadeout_frames = CHUNKSIZE - (num_loud_frames + num_fadein_frames) self.WAVEDATA.append(struct.pack( "<H", 0 )) for xx in range(num_fadein_frames): x = xx next_sample = int(math.sin(x/((BITRATE/frequency)/math.pi)) * 32000 * (xx/num_fadein_frames)) self.WAVEDATA[index] = self.WAVEDATA[index] + struct.pack( "<h", next_sample ) # little-endian int16 for xx in range(num_loud_frames): x = xx + num_fadein_frames next_sample = int(math.sin(x/((BITRATE/frequency)/math.pi)) * 32000) self.WAVEDATA[index] = self.WAVEDATA[index] + struct.pack( "<h", next_sample ) # little-endian int16 for xx in range(num_fadeout_frames): x = xx + num_loud_frames + num_fadein_frames next_sample = int(math.sin(x/((BITRATE/frequency)/math.pi)) * 32000 * (1 - (xx/num_fadeout_frames))) # next_sample = 0 self.WAVEDATA[index] = self.WAVEDATA[index] + struct.pack( "<h", next_sample) frequency *= 1.0594631 # semitone ratio # Save the newly-generated data to a file using Pickle: print("Saving wavedata to file") f = open(WAVEDATA_FILE, "wb") pickle.dump(self.WAVEDATA, f) f.close() def test(self): for index in range(0, 40): self.stream.write(self.WAVEDATA[index]) index += 1 self.stream.stop_stream() def play(self, index): self.stream.write(self.WAVEDATA[index]) def close(self): self.stream.stop_stream() self.stream.close() self.player.terminate() if __name__ == "__main__": tones = AudioTones() tones.init() for i in range(0, 40): tones.play(i) sleep(0.3)
mit
-6,694,274,719,032,910,000
37.357895
128
0.586718
false
3.370953
false
false
false
mirkobronzi/finance-analyzer
lib/entries.py
1
3600
""" classes Entry and Entries """ __author__ = 'bronzi' from datetime import datetime import re #TODO: should be configurable PUNCTUATION_REMOVER = re.compile("[0-9,\.#\-_/']") SPACE_REMOVER = re.compile(" +") def string_to_float(string): """ simply convert a string into a float string : basestring """ return 0.0 if string.strip() == '' else float(string.replace(',', '.')) class Entry: """ classes Entry - representing an expense/income entry """ def __init__(self, date, name, money_out=0.0, money_in=0.0, comments=None): self.date = date self.name = name self.money_in = money_in self.money_out = money_out self.comments = comments if comments else {} self.normalized_name = Entry._normalize_entry(name) @staticmethod def parse(date, name, money_out='0', money_in='0', comments=None): """ method to parse strings and convert them into an Entry object (all parameter are basestring) """ parsed_date = datetime.strptime(date, "%m/%d/%Y").date() parsed_comments = [] if not comments else\ [x.strip().split(':') for x in comments.split(',')] fixed_parsed_comments = map( lambda x : x if len(x) > 1 else (x[0], ''), parsed_comments) return Entry(parsed_date, name, string_to_float(money_out), string_to_float(money_in), dict(fixed_parsed_comments)) def as_tuple(self): return (self.date, self.name, self.money_in, self.money_out, self.comments) @staticmethod def _normalize_entry(name): normalized_name = re.sub(PUNCTUATION_REMOVER, "", name) normalized_name = re.sub(SPACE_REMOVER, " ", normalized_name) return normalized_name.strip() def __eq__(self, other): return (self.date == other.date and self.name == other.name and self.money_in == other.money_in and self.money_out == other.money_out and self.comments == other.comments) def __hash__(self): # TODO: check a better way to implement this # try to generate a frozen dictionary from the beginning comments_hash = hash(frozenset(self.comments.keys())) +\ hash(frozenset(self.comments.values())) return hash(self.date) +\ hash(self.name) +\ hash(self.money_in) +\ hash(self.money_out) +\ comments_hash def __repr__(self): return (str(self.date) + ' : ' + self.name + ' => (' + str(self.money_in) + ', -' + str(self.money_out) + ') [' + str(self.comments) + ']') class Entries: """ classes Entries - representing a collection of Entry """ def __init__(self, *args): self.entries = list(args) def add(self, entry): """ method to add an Entry to the collection entry : Entry """ self.entries.append(entry) def extend(self, entries): """ method to merge the given Entries into this one entries : Entries """ self.entries.extend(entries.entries) def sorted(self): entries_as_tuple = [entry.as_tuple() for entry in self.entries] to_return = sorted(entries_as_tuple) return Entries(*to_return) def __eq__(self, other): return self.entries == other.entries def __repr__(self): return str(self.entries) def __iter__(self): return iter(self.entries)
gpl-3.0
-7,055,621,584,990,460,000
29
76
0.563889
false
3.829787
false
false
false
Si-elegans/Web-based_GUI_Tools
spirit/forms/comment_like.py
1
1042
#-*- coding: utf-8 -*- from django import forms from django.utils.translation import ugettext as _ from spirit.models.comment_like import CommentLike class LikeForm(forms.ModelForm): class Meta: model = CommentLike fields = [] def __init__(self, user=None, comment=None, *args, **kwargs): super(LikeForm, self).__init__(*args, **kwargs) self.user = user self.comment = comment def clean(self): cleaned_data = super(LikeForm, self).clean() like = CommentLike.objects.filter(user=self.user, comment=self.comment) if like.exists(): # Do this since some of the unique_together fields are excluded. raise forms.ValidationError(_("This like already exists")) return cleaned_data def save(self, commit=True): if not self.instance.pk: self.instance.user = self.user self.instance.comment = self.comment return super(LikeForm, self).save(commit)
apache-2.0
6,114,016,247,906,903,000
27.189189
76
0.606526
false
4.288066
false
false
false
vIiRuS/Lagerregal
users/forms.py
1
1438
from django import forms from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext from users.models import Lageruser, DepartmentUser from Lagerregal import settings class SettingsForm(forms.ModelForm): error_css_class = 'has-error' class Meta: model = Lageruser fields = ["pagelength", "timezone", "theme", "main_department"] help_texts = { "pagelength": _("The number of items displayed on one page in a list."), "main_department": _("Your Main department determines, which department devices you create are assigned to."), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["timezone"].choices[0] = ("", ugettext("Default ({0})".format(settings.TIME_ZONE))) self.fields["timezone"].widget.choices[0] = ("", ugettext("Default ({0})".format(settings.TIME_ZONE))) class AvatarForm(forms.ModelForm): error_css_class = 'has-error' avatar_clear = forms.BooleanField(required=False) class Meta: model = Lageruser fields = ["avatar"] widgets = { "avatar": forms.FileInput() } class DepartmentAddUserForm(forms.ModelForm): error_css_class = 'has-error' class Meta: model = DepartmentUser widgets = { "department": forms.HiddenInput() } fields = '__all__'
bsd-3-clause
492,863,469,276,929,150
30.26087
122
0.626565
false
4.144092
false
false
false
dmsimard/ansible
lib/ansible/plugins/filter/core.py
1
21532
# (c) 2012, Jeroen Hoekx <jeroen@hoekx.be> # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import base64 import glob import hashlib import json import ntpath import os.path import re import sys import time import uuid import yaml import datetime from functools import partial from random import Random, SystemRandom, shuffle from jinja2.filters import environmentfilter, do_groupby as _do_groupby from ansible.errors import AnsibleError, AnsibleFilterError, AnsibleFilterTypeError from ansible.module_utils.six import string_types, integer_types, reraise, text_type from ansible.module_utils.six.moves import shlex_quote from ansible.module_utils._text import to_bytes, to_native, to_text from ansible.module_utils.common.collections import is_sequence from ansible.module_utils.common._collections_compat import Mapping from ansible.parsing.ajson import AnsibleJSONEncoder from ansible.parsing.yaml.dumper import AnsibleDumper from ansible.template import recursive_check_defined from ansible.utils.display import Display from ansible.utils.encrypt import passlib_or_crypt from ansible.utils.hashing import md5s, checksum_s from ansible.utils.unicode import unicode_wrap from ansible.utils.vars import merge_hash display = Display() UUID_NAMESPACE_ANSIBLE = uuid.UUID('361E6D51-FAEC-444A-9079-341386DA8E2E') def to_yaml(a, *args, **kw): '''Make verbose, human readable yaml''' default_flow_style = kw.pop('default_flow_style', None) transformed = yaml.dump(a, Dumper=AnsibleDumper, allow_unicode=True, default_flow_style=default_flow_style, **kw) return to_text(transformed) def to_nice_yaml(a, indent=4, *args, **kw): '''Make verbose, human readable yaml''' transformed = yaml.dump(a, Dumper=AnsibleDumper, indent=indent, allow_unicode=True, default_flow_style=False, **kw) return to_text(transformed) def to_json(a, *args, **kw): ''' Convert the value to JSON ''' return json.dumps(a, cls=AnsibleJSONEncoder, *args, **kw) def to_nice_json(a, indent=4, sort_keys=True, *args, **kw): '''Make verbose, human readable JSON''' return to_json(a, indent=indent, sort_keys=sort_keys, separators=(',', ': '), *args, **kw) def to_bool(a): ''' return a bool for the arg ''' if a is None or isinstance(a, bool): return a if isinstance(a, string_types): a = a.lower() if a in ('yes', 'on', '1', 'true', 1): return True return False def to_datetime(string, format="%Y-%m-%d %H:%M:%S"): return datetime.datetime.strptime(string, format) def strftime(string_format, second=None): ''' return a date string using string. See https://docs.python.org/2/library/time.html#time.strftime for format ''' if second is not None: try: second = float(second) except Exception: raise AnsibleFilterError('Invalid value for epoch value (%s)' % second) return time.strftime(string_format, time.localtime(second)) def quote(a): ''' return its argument quoted for shell usage ''' if a is None: a = u'' return shlex_quote(to_text(a)) def fileglob(pathname): ''' return list of matched regular files for glob ''' return [g for g in glob.glob(pathname) if os.path.isfile(g)] def regex_replace(value='', pattern='', replacement='', ignorecase=False, multiline=False): ''' Perform a `re.sub` returning a string ''' value = to_text(value, errors='surrogate_or_strict', nonstring='simplerepr') flags = 0 if ignorecase: flags |= re.I if multiline: flags |= re.M _re = re.compile(pattern, flags=flags) return _re.sub(replacement, value) def regex_findall(value, regex, multiline=False, ignorecase=False): ''' Perform re.findall and return the list of matches ''' value = to_text(value, errors='surrogate_or_strict', nonstring='simplerepr') flags = 0 if ignorecase: flags |= re.I if multiline: flags |= re.M return re.findall(regex, value, flags) def regex_search(value, regex, *args, **kwargs): ''' Perform re.search and return the list of matches or a backref ''' value = to_text(value, errors='surrogate_or_strict', nonstring='simplerepr') groups = list() for arg in args: if arg.startswith('\\g'): match = re.match(r'\\g<(\S+)>', arg).group(1) groups.append(match) elif arg.startswith('\\'): match = int(re.match(r'\\(\d+)', arg).group(1)) groups.append(match) else: raise AnsibleFilterError('Unknown argument') flags = 0 if kwargs.get('ignorecase'): flags |= re.I if kwargs.get('multiline'): flags |= re.M match = re.search(regex, value, flags) if match: if not groups: return match.group() else: items = list() for item in groups: items.append(match.group(item)) return items def ternary(value, true_val, false_val, none_val=None): ''' value ? true_val : false_val ''' if value is None and none_val is not None: return none_val elif bool(value): return true_val else: return false_val def regex_escape(string, re_type='python'): string = to_text(string, errors='surrogate_or_strict', nonstring='simplerepr') '''Escape all regular expressions special characters from STRING.''' if re_type == 'python': return re.escape(string) elif re_type == 'posix_basic': # list of BRE special chars: # https://en.wikibooks.org/wiki/Regular_Expressions/POSIX_Basic_Regular_Expressions return regex_replace(string, r'([].[^$*\\])', r'\\\1') # TODO: implement posix_extended # It's similar to, but different from python regex, which is similar to, # but different from PCRE. It's possible that re.escape would work here. # https://remram44.github.io/regex-cheatsheet/regex.html#programs elif re_type == 'posix_extended': raise AnsibleFilterError('Regex type (%s) not yet implemented' % re_type) else: raise AnsibleFilterError('Invalid regex type (%s)' % re_type) def from_yaml(data): if isinstance(data, string_types): return yaml.safe_load(data) return data def from_yaml_all(data): if isinstance(data, string_types): return yaml.safe_load_all(data) return data @environmentfilter def rand(environment, end, start=None, step=None, seed=None): if seed is None: r = SystemRandom() else: r = Random(seed) if isinstance(end, integer_types): if not start: start = 0 if not step: step = 1 return r.randrange(start, end, step) elif hasattr(end, '__iter__'): if start or step: raise AnsibleFilterError('start and step can only be used with integer values') return r.choice(end) else: raise AnsibleFilterError('random can only be used on sequences and integers') def randomize_list(mylist, seed=None): try: mylist = list(mylist) if seed: r = Random(seed) r.shuffle(mylist) else: shuffle(mylist) except Exception: pass return mylist def get_hash(data, hashtype='sha1'): try: h = hashlib.new(hashtype) except Exception as e: # hash is not supported? raise AnsibleFilterError(e) h.update(to_bytes(data, errors='surrogate_or_strict')) return h.hexdigest() def get_encrypted_password(password, hashtype='sha512', salt=None, salt_size=None, rounds=None): passlib_mapping = { 'md5': 'md5_crypt', 'blowfish': 'bcrypt', 'sha256': 'sha256_crypt', 'sha512': 'sha512_crypt', } hashtype = passlib_mapping.get(hashtype, hashtype) try: return passlib_or_crypt(password, hashtype, salt=salt, salt_size=salt_size, rounds=rounds) except AnsibleError as e: reraise(AnsibleFilterError, AnsibleFilterError(to_native(e), orig_exc=e), sys.exc_info()[2]) def to_uuid(string, namespace=UUID_NAMESPACE_ANSIBLE): uuid_namespace = namespace if not isinstance(uuid_namespace, uuid.UUID): try: uuid_namespace = uuid.UUID(namespace) except (AttributeError, ValueError) as e: raise AnsibleFilterError("Invalid value '%s' for 'namespace': %s" % (to_native(namespace), to_native(e))) # uuid.uuid5() requires bytes on Python 2 and bytes or text or Python 3 return to_text(uuid.uuid5(uuid_namespace, to_native(string, errors='surrogate_or_strict'))) def mandatory(a, msg=None): from jinja2.runtime import Undefined ''' Make a variable mandatory ''' if isinstance(a, Undefined): if a._undefined_name is not None: name = "'%s' " % to_text(a._undefined_name) else: name = '' if msg is not None: raise AnsibleFilterError(to_native(msg)) else: raise AnsibleFilterError("Mandatory variable %s not defined." % name) return a def combine(*terms, **kwargs): recursive = kwargs.pop('recursive', False) list_merge = kwargs.pop('list_merge', 'replace') if kwargs: raise AnsibleFilterError("'recursive' and 'list_merge' are the only valid keyword arguments") # allow the user to do `[dict1, dict2, ...] | combine` dictionaries = flatten(terms, levels=1) # recursively check that every elements are defined (for jinja2) recursive_check_defined(dictionaries) if not dictionaries: return {} if len(dictionaries) == 1: return dictionaries[0] # merge all the dicts so that the dict at the end of the array have precedence # over the dict at the beginning. # we merge the dicts from the highest to the lowest priority because there is # a huge probability that the lowest priority dict will be the biggest in size # (as the low prio dict will hold the "default" values and the others will be "patches") # and merge_hash create a copy of it's first argument. # so high/right -> low/left is more efficient than low/left -> high/right high_to_low_prio_dict_iterator = reversed(dictionaries) result = next(high_to_low_prio_dict_iterator) for dictionary in high_to_low_prio_dict_iterator: result = merge_hash(dictionary, result, recursive, list_merge) return result def comment(text, style='plain', **kw): # Predefined comment types comment_styles = { 'plain': { 'decoration': '# ' }, 'erlang': { 'decoration': '% ' }, 'c': { 'decoration': '// ' }, 'cblock': { 'beginning': '/*', 'decoration': ' * ', 'end': ' */' }, 'xml': { 'beginning': '<!--', 'decoration': ' - ', 'end': '-->' } } # Pointer to the right comment type style_params = comment_styles[style] if 'decoration' in kw: prepostfix = kw['decoration'] else: prepostfix = style_params['decoration'] # Default params p = { 'newline': '\n', 'beginning': '', 'prefix': (prepostfix).rstrip(), 'prefix_count': 1, 'decoration': '', 'postfix': (prepostfix).rstrip(), 'postfix_count': 1, 'end': '' } # Update default params p.update(style_params) p.update(kw) # Compose substrings for the final string str_beginning = '' if p['beginning']: str_beginning = "%s%s" % (p['beginning'], p['newline']) str_prefix = '' if p['prefix']: if p['prefix'] != p['newline']: str_prefix = str( "%s%s" % (p['prefix'], p['newline'])) * int(p['prefix_count']) else: str_prefix = str( "%s" % (p['newline'])) * int(p['prefix_count']) str_text = ("%s%s" % ( p['decoration'], # Prepend each line of the text with the decorator text.replace( p['newline'], "%s%s" % (p['newline'], p['decoration'])))).replace( # Remove trailing spaces when only decorator is on the line "%s%s" % (p['decoration'], p['newline']), "%s%s" % (p['decoration'].rstrip(), p['newline'])) str_postfix = p['newline'].join( [''] + [p['postfix'] for x in range(p['postfix_count'])]) str_end = '' if p['end']: str_end = "%s%s" % (p['newline'], p['end']) # Return the final string return "%s%s%s%s%s" % ( str_beginning, str_prefix, str_text, str_postfix, str_end) @environmentfilter def extract(environment, item, container, morekeys=None): if morekeys is None: keys = [item] elif isinstance(morekeys, list): keys = [item] + morekeys else: keys = [item, morekeys] value = container for key in keys: value = environment.getitem(value, key) return value @environmentfilter def do_groupby(environment, value, attribute): """Overridden groupby filter for jinja2, to address an issue with jinja2>=2.9.0,<2.9.5 where a namedtuple was returned which has repr that prevents ansible.template.safe_eval.safe_eval from being able to parse and eval the data. jinja2<2.9.0,>=2.9.5 is not affected, as <2.9.0 uses a tuple, and >=2.9.5 uses a standard tuple repr on the namedtuple. The adaptation here, is to run the jinja2 `do_groupby` function, and cast all of the namedtuples to a regular tuple. See https://github.com/ansible/ansible/issues/20098 We may be able to remove this in the future. """ return [tuple(t) for t in _do_groupby(environment, value, attribute)] def b64encode(string, encoding='utf-8'): return to_text(base64.b64encode(to_bytes(string, encoding=encoding, errors='surrogate_or_strict'))) def b64decode(string, encoding='utf-8'): return to_text(base64.b64decode(to_bytes(string, errors='surrogate_or_strict')), encoding=encoding) def flatten(mylist, levels=None, skip_nulls=True): ret = [] for element in mylist: if skip_nulls and element in (None, 'None', 'null'): # ignore null items continue elif is_sequence(element): if levels is None: ret.extend(flatten(element, skip_nulls=skip_nulls)) elif levels >= 1: # decrement as we go down the stack ret.extend(flatten(element, levels=(int(levels) - 1), skip_nulls=skip_nulls)) else: ret.append(element) else: ret.append(element) return ret def subelements(obj, subelements, skip_missing=False): '''Accepts a dict or list of dicts, and a dotted accessor and produces a product of the element and the results of the dotted accessor >>> obj = [{"name": "alice", "groups": ["wheel"], "authorized": ["/tmp/alice/onekey.pub"]}] >>> subelements(obj, 'groups') [({'name': 'alice', 'groups': ['wheel'], 'authorized': ['/tmp/alice/onekey.pub']}, 'wheel')] ''' if isinstance(obj, dict): element_list = list(obj.values()) elif isinstance(obj, list): element_list = obj[:] else: raise AnsibleFilterError('obj must be a list of dicts or a nested dict') if isinstance(subelements, list): subelement_list = subelements[:] elif isinstance(subelements, string_types): subelement_list = subelements.split('.') else: raise AnsibleFilterTypeError('subelements must be a list or a string') results = [] for element in element_list: values = element for subelement in subelement_list: try: values = values[subelement] except KeyError: if skip_missing: values = [] break raise AnsibleFilterError("could not find %r key in iterated item %r" % (subelement, values)) except TypeError: raise AnsibleFilterTypeError("the key %s should point to a dictionary, got '%s'" % (subelement, values)) if not isinstance(values, list): raise AnsibleFilterTypeError("the key %r should point to a list, got %r" % (subelement, values)) for value in values: results.append((element, value)) return results def dict_to_list_of_dict_key_value_elements(mydict, key_name='key', value_name='value'): ''' takes a dictionary and transforms it into a list of dictionaries, with each having a 'key' and 'value' keys that correspond to the keys and values of the original ''' if not isinstance(mydict, Mapping): raise AnsibleFilterTypeError("dict2items requires a dictionary, got %s instead." % type(mydict)) ret = [] for key in mydict: ret.append({key_name: key, value_name: mydict[key]}) return ret def list_of_dict_key_value_elements_to_dict(mylist, key_name='key', value_name='value'): ''' takes a list of dicts with each having a 'key' and 'value' keys, and transforms the list into a dictionary, effectively as the reverse of dict2items ''' if not is_sequence(mylist): raise AnsibleFilterTypeError("items2dict requires a list, got %s instead." % type(mylist)) return dict((item[key_name], item[value_name]) for item in mylist) def path_join(paths): ''' takes a sequence or a string, and return a concatenation of the different members ''' if isinstance(paths, string_types): return os.path.join(paths) elif is_sequence(paths): return os.path.join(*paths) else: raise AnsibleFilterTypeError("|path_join expects string or sequence, got %s instead." % type(paths)) class FilterModule(object): ''' Ansible core jinja2 filters ''' def filters(self): return { # jinja2 overrides 'groupby': do_groupby, # base 64 'b64decode': b64decode, 'b64encode': b64encode, # uuid 'to_uuid': to_uuid, # json 'to_json': to_json, 'to_nice_json': to_nice_json, 'from_json': json.loads, # yaml 'to_yaml': to_yaml, 'to_nice_yaml': to_nice_yaml, 'from_yaml': from_yaml, 'from_yaml_all': from_yaml_all, # path 'basename': partial(unicode_wrap, os.path.basename), 'dirname': partial(unicode_wrap, os.path.dirname), 'expanduser': partial(unicode_wrap, os.path.expanduser), 'expandvars': partial(unicode_wrap, os.path.expandvars), 'path_join': path_join, 'realpath': partial(unicode_wrap, os.path.realpath), 'relpath': partial(unicode_wrap, os.path.relpath), 'splitext': partial(unicode_wrap, os.path.splitext), 'win_basename': partial(unicode_wrap, ntpath.basename), 'win_dirname': partial(unicode_wrap, ntpath.dirname), 'win_splitdrive': partial(unicode_wrap, ntpath.splitdrive), # file glob 'fileglob': fileglob, # types 'bool': to_bool, 'to_datetime': to_datetime, # date formatting 'strftime': strftime, # quote string for shell usage 'quote': quote, # hash filters # md5 hex digest of string 'md5': md5s, # sha1 hex digest of string 'sha1': checksum_s, # checksum of string as used by ansible for checksumming files 'checksum': checksum_s, # generic hashing 'password_hash': get_encrypted_password, 'hash': get_hash, # regex 'regex_replace': regex_replace, 'regex_escape': regex_escape, 'regex_search': regex_search, 'regex_findall': regex_findall, # ? : ; 'ternary': ternary, # random stuff 'random': rand, 'shuffle': randomize_list, # undefined 'mandatory': mandatory, # comment-style decoration 'comment': comment, # debug 'type_debug': lambda o: o.__class__.__name__, # Data structures 'combine': combine, 'extract': extract, 'flatten': flatten, 'dict2items': dict_to_list_of_dict_key_value_elements, 'items2dict': list_of_dict_key_value_elements_to_dict, 'subelements': subelements, 'split': partial(unicode_wrap, text_type.split), }
gpl-3.0
2,740,070,881,585,711,600
31.476621
120
0.611694
false
3.874055
false
false
false
stormi/tsunami
src/secondaires/familier/editeurs/famedit/__init__.py
1
6790
# -*-coding:Utf-8 -* # Copyright (c) 2014 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Package contenant l'éditeur 'famedit'. Si des redéfinitions de contexte-éditeur standard doivent être faites, elles seront placées dans ce package """ from primaires.interpreteur.editeur.choix import Choix from primaires.interpreteur.editeur.flag import Flag from primaires.interpreteur.editeur.entier import Entier from primaires.interpreteur.editeur.presentation import Presentation from primaires.interpreteur.editeur.selection import Selection from primaires.interpreteur.editeur.uniligne import Uniligne from primaires.scripting.editeurs.edt_script import EdtScript from secondaires.familier.constantes import * class EdtFamedit(Presentation): """Classe définissant l'éditeur de fiche de familier famedit.""" nom = "famedit" def __init__(self, personnage, fiche): """Constructeur de l'éditeur""" if personnage: instance_connexion = personnage.instance_connexion else: instance_connexion = None Presentation.__init__(self, instance_connexion, fiche) if personnage and fiche: self.construire(fiche) def __getnewargs__(self): return (None, None) def construire(self, fiche): """Construction de l'éditeur""" # Régimes regime = self.ajouter_choix("régime alimentaire", "r", Choix, fiche, "regime", REGIMES) regime.parent = self regime.prompt = "Régime alimentaire du familier : " regime.apercu = "{objet.regime}" regime.aide_courte = \ "Entrez le |ent|régime|ff| du familier ou |cmd|/|ff| pour revenir " \ "à la fenêtre parente.\n\nRégimes disponibles : {}.\n\n" \ "Régime actuel : |bc|{{objet.regime}}|ff|".format( ", ".join(REGIMES)) # Harnachements supportés harnachements = self.ajouter_choix("harnachement supportés", "h", Selection, fiche, "harnachements", TYPES_HARNACHEMENT) harnachements.parent = self harnachements.prompt = "Harnachements supportés : " harnachements.apercu = "{objet.str_harnachements}" harnachements.aide_courte = \ "Entrez un |ent|harnachement supporté|ff| pour l'ajouter " \ "ou le retirer\nou |cmd|/|ff| pour revenir à la fenêtre " \ "parente.\n\nHarnachements possibles : " + \ ", ".join(sorted(TYPES_HARNACHEMENT)) + "\nHarnachements " \ "supportés actuellement : {objet.str_harnachements}" # Stats pouvant progresser stats = self.ajouter_choix("stats pouvant progresser", "st", Selection, fiche, "stats_progres", ["force", "agilite", "robustesse", "intelligence", "charisme", "sensibilite"]) stats.parent = self stats.prompt = "Stats pouvant augmenter automatiquement : " stats.apercu = "{objet.str_stats_progres}" stats.aide_courte = \ "Entrez un |ent|nom de stat|ff| pour l'ajouter " \ "ou le retirer\nou |cmd|/|ff| pour revenir à la fenêtre " \ "parente.\n\nQuand le familier gagne un niveau, il va " \ "choisir aléatoirement parmi ces stats et les\naugmenter " \ "si il a des points d'entraînement disponibles\n\nStats " \ "automatiques actuelles : {objet.str_stats_progres}" # Monture monture = self.ajouter_choix("peut être monté", "m", Flag, fiche, "monture") monture.parent = self # Sorties verticales verticales = self.ajouter_choix( "peut emprunter les sorties verticales", "v", Flag, fiche, "sorties_verticales") verticales.parent = self # Aller en intérieur interieur = self.ajouter_choix("peut aller en intérieur", "l", Flag, fiche, "aller_interieur") interieur.parent = self # Difficulté d'apprivoisement difficulte = self.ajouter_choix("difficulté d'apprivoisement", "d", Entier, fiche, "difficulte_apprivoisement") difficulte.parent = self difficulte.apercu = "{objet.difficulte_apprivoisement}%" difficulte.prompt = "Entrez la difficulté d'apprivoisement du " \ "familier : " difficulte.aide_courte = \ "Entrez |ent|la difficulté d'apprivoisement|ff| du familier\n" \ "(entre |ent|1|ff| et |ent|100|ff|) ou |cmd|/|ff| pour " \ "revenir à la fenêtre parente.\n\nDifficulté actuelle : " \ "{objet.difficulte_apprivoisement}%" # Prix unitaire prix = self.ajouter_choix("prix unitaire", "u", Entier, fiche, "m_valeur") prix.parent = self prix.apercu = "{objet.m_valeur} pièces de bronze" prix.prompt = "Entrez le prix unitaire du familier : " prix.aide_courte = \ "Entrez |ent|le prix unitaire|ff| du familier" \ "ou |cmd|/|ff| pour revenir à la fenêtre parente.\n\n" \ "Prix unitaire actuel : {objet.m_valeur}" # Script scripts = self.ajouter_choix("scripts", "sc", EdtScript, fiche.script) scripts.parent = self
bsd-3-clause
-1,508,693,470,477,261,300
43.394737
81
0.655009
false
3.256757
false
false
false
JukeboxPipeline/jukebox-core
src/jukeboxcore/addons/guerilla/guerillamgmt.py
1
82524
from PySide import QtGui from jukeboxcore.log import get_logger log = get_logger(__name__) from jukeboxcore import ostool from jukeboxcore import djadapter from jukeboxcore.gui.main import JB_MainWindow, JB_Dialog, dt_to_qdatetime from jukeboxcore.gui import treemodel from jukeboxcore.gui import djitemdata from jukeboxcore.plugins import JB_CoreStandaloneGuiPlugin from jukeboxcore.gui.widgets.guerillamgmt_ui import Ui_guerillamgmt_mwin from jukeboxcore.gui.widgets.guerilla.projectcreator_ui import Ui_projectcreator_dialog from jukeboxcore.gui.widgets.guerilla.prjadder_ui import Ui_prjadder_dialog from jukeboxcore.gui.widgets.guerilla.seqcreator_ui import Ui_seqcreator_dialog from jukeboxcore.gui.widgets.guerilla.atypecreator_ui import Ui_atypecreator_dialog from jukeboxcore.gui.widgets.guerilla.atypeadder_ui import Ui_atypeadder_dialog from jukeboxcore.gui.widgets.guerilla.depcreator_ui import Ui_depcreator_dialog from jukeboxcore.gui.widgets.guerilla.depadder_ui import Ui_depadder_dialog from jukeboxcore.gui.widgets.guerilla.usercreator_ui import Ui_usercreator_dialog from jukeboxcore.gui.widgets.guerilla.useradder_ui import Ui_useradder_dialog from jukeboxcore.gui.widgets.guerilla.shotcreator_ui import Ui_shotcreator_dialog from jukeboxcore.gui.widgets.guerilla.assetcreator_ui import Ui_assetcreator_dialog from jukeboxcore.gui.widgets.guerilla.assetadder_ui import Ui_assetadder_dialog from jukeboxcore.gui.widgets.guerilla.taskcreator_ui import Ui_taskcreator_dialog class ProjectCreatorDialog(JB_Dialog, Ui_projectcreator_dialog): """A Dialog to create a project """ def __init__(self, parent=None, flags=0): """Initialize a new project creator dialog :param parent: the parent object :type parent: :class:`QtCore.QObject` :param flags: the window flags :type flags: :data:`QtCore.Qt.WindowFlags` :raises: None """ super(ProjectCreatorDialog, self).__init__(parent, flags) self.project = None self.setupUi(self) self.create_pb.clicked.connect(self.create_prj) def create_prj(self, ): """Create a project and store it in the self.project :returns: None :rtype: None :raises: None """ name = self.name_le.text() short = self.short_le.text() path = self.path_le.text() semester = self.semester_le.text() try: prj = djadapter.models.Project(name=name, short=short, path=path, semester=semester) prj.save() self.project = prj self.accept() except: log.exception("Could not create new project") class ProjectAdderDialog(JB_Dialog, Ui_prjadder_dialog): """A Dialog to add project to a project """ def __init__(self, atype=None, department=None, user=None, parent=None, flags=0): """Initialize a new project creator dialog :param atype: the atype to add the project to :type atype: :class:`djadapter.models.Atype` :param department: the department to add the project to :type department: :class:`djadapter.models.Department` :param parent: the parent object :param user: the user to tadd the project to :type user: :class:`djadapter.models.User` :type parent: :class:`QtCore.QObject` :param flags: the window flags :type flags: :data:`QtCore.Qt.WindowFlags` :raises: None """ super(ProjectAdderDialog, self).__init__(parent, flags) self._atype = atype self._dep = department self._user = user self.projects = [] self.setupUi(self) self.add_pb.clicked.connect(self.add_project) rootdata = treemodel.ListItemData(["Name", "Description"]) rootitem = treemodel.TreeItem(rootdata) if atype: projects = djadapter.projects.exclude(pk__in = atype.projects.all()) elif department: projects = djadapter.projects.exclude(pk__in = department.projects.all()) else: projects = djadapter.projects.exclude(users=user) for project in projects: projectdata = djitemdata.ProjectItemData(project) treemodel.TreeItem(projectdata, rootitem) self.model = treemodel.TreeModel(rootitem) self.prj_tablev.setModel(self.model) def add_project(self, ): """Add a project and store it in the self.projects :returns: None :rtype: None :raises: None """ i = self.prj_tablev.currentIndex() item = i.internalPointer() if item: project = item.internal_data() if self._atype: self._atype.projects.add(project) elif self._dep: self._dep.projects.add(project) else: project.users.add(self._user) self.projects.append(project) item.set_parent(None) class SequenceCreatorDialog(JB_Dialog, Ui_seqcreator_dialog): """A Dialog to create a sequence """ def __init__(self, project, parent=None, flags=0): """Initialize a new sequence creator dialog :param project: The project for the sequence :type project: :class:`jukeboxcore.djadapter.models.Project` :param parent: the parent object :type parent: :class:`QtCore.QObject` :param flags: the window flags :type flags: :data:`QtCore.Qt.WindowFlags` :raises: None """ super(SequenceCreatorDialog, self).__init__(parent, flags) self._project = project self.sequence = None self.setupUi(self) self.create_pb.clicked.connect(self.create_seq) def create_seq(self, ): """Create a sequence and store it in the self.sequence :returns: None :rtype: None :raises: None """ name = self.name_le.text() desc = self.desc_pte.toPlainText() try: seq = djadapter.models.Sequence(name=name, project=self._project, description=desc) seq.save() self.sequence = seq self.accept() except: log.exception("Could not create new sequence") class AtypeCreatorDialog(JB_Dialog, Ui_atypecreator_dialog): """A Dialog to create a atype """ def __init__(self, projects=None, parent=None, flags=0): """Initialize a new atype creator dialog :param parent: the parent object :type parent: :class:`QtCore.QObject` :param flags: the window flags :type flags: :data:`QtCore.Qt.WindowFlags` :raises: None """ super(AtypeCreatorDialog, self).__init__(parent, flags) self.projects = projects or [] self.atype = None self.setupUi(self) self.create_pb.clicked.connect(self.create_atype) def create_atype(self, ): """Create a atype and store it in the self.atype :returns: None :rtype: None :raises: None """ name = self.name_le.text() desc = self.desc_pte.toPlainText() try: atype = djadapter.models.Atype(name=name, description=desc) atype.save() for prj in self.projects: atype.projects.add(prj) self.atype = atype self.accept() except: log.exception("Could not create new assettype") class AtypeAdderDialog(JB_Dialog, Ui_atypeadder_dialog): """A Dialog to add atype to a project """ def __init__(self, project, parent=None, flags=0): """Initialize a new atype creator dialog :param project: The project for the atypes :type project: :class:`jukeboxcore.djadapter.models.Project` :param parent: the parent object :type parent: :class:`QtCore.QObject` :param flags: the window flags :type flags: :data:`QtCore.Qt.WindowFlags` :raises: None """ super(AtypeAdderDialog, self).__init__(parent, flags) self._project = project self.atypes = [] self.setupUi(self) self.add_pb.clicked.connect(self.add_atype) rootdata = treemodel.ListItemData(["Name", "Description"]) rootitem = treemodel.TreeItem(rootdata) atypes = djadapter.atypes.exclude(projects=project) for atype in atypes: atypedata = djitemdata.AtypeItemData(atype) treemodel.TreeItem(atypedata, rootitem) self.model = treemodel.TreeModel(rootitem) self.atype_tablev.setModel(self.model) def add_atype(self, ): """Add a atype and store it in the self.atypes :returns: None :rtype: None :raises: None """ i = self.atype_tablev.currentIndex() item = i.internalPointer() if item: atype = item.internal_data() atype.projects.add(self._project) self.atypes.append(atype) item.set_parent(None) class DepCreatorDialog(JB_Dialog, Ui_depcreator_dialog): """A Dialog to create a dep """ def __init__(self, projects=None, parent=None, flags=0): """Initialize a new dep creator dialog :param parent: the parent object :type parent: :class:`QtCore.QObject` :param flags: the window flags :type flags: :data:`QtCore.Qt.WindowFlags` :raises: None """ super(DepCreatorDialog, self).__init__(parent, flags) self.projects = projects or [] self.dep = None self.setupUi(self) self.create_pb.clicked.connect(self.create_dep) def create_dep(self, ): """Create a dep and store it in the self.dep :returns: None :rtype: None :raises: None """ name = self.name_le.text() short = self.short_le.text() assetflag = self.asset_rb.isChecked() ordervalue = self.ordervalue_sb.value() desc = self.desc_pte.toPlainText() try: dep = djadapter.models.Department(name=name, short=short, assetflag=assetflag, ordervalue=ordervalue, description=desc) dep.save() for prj in self.projects: dep.projects.add(prj) self.dep = dep self.accept() except: log.exception("Could not create new department.") class DepAdderDialog(JB_Dialog, Ui_depadder_dialog): """A Dialog to add departments to a project """ def __init__(self, project, parent=None, flags=0): """Initialize a new dep creator dialog :param project: The project for the deps :type project: :class:`jukeboxcore.djadapter.models.Project` :param parent: the parent object :type parent: :class:`QtCore.QObject` :param flags: the window flags :type flags: :data:`QtCore.Qt.WindowFlags` :raises: None """ super(DepAdderDialog, self).__init__(parent, flags) self._project = project self.deps = [] self.setupUi(self) self.add_pb.clicked.connect(self.add_dep) rootdata = treemodel.ListItemData(["Name", "Description", "Ordervalue"]) rootitem = treemodel.TreeItem(rootdata) deps = djadapter.departments.exclude(projects=project) for dep in deps: depdata = djitemdata.DepartmentItemData(dep) treemodel.TreeItem(depdata, rootitem) self.model = treemodel.TreeModel(rootitem) self.dep_tablev.setModel(self.model) def add_dep(self, ): """Add a dep and store it in the self.deps :returns: None :rtype: None :raises: None """ i = self.dep_tablev.currentIndex() item = i.internalPointer() if item: dep = item.internal_data() dep.projects.add(self._project) self.deps.append(dep) item.set_parent(None) class UserCreatorDialog(JB_Dialog, Ui_usercreator_dialog): """A Dialog to create a user """ def __init__(self, projects=None, tasks=None, parent=None, flags=0): """Initialize a new user creator dialog :param projects: The projects for the user :type projects: list of :class:`jukeboxcore.djadapter.models.Project` :param tasks: The tasks for the user :type tasks: list of :class:`jukeboxcore.djadapter.models.Task` :param parent: the parent object :type parent: :class:`QtCore.QObject` :param flags: the window flags :type flags: :data:`QtCore.Qt.WindowFlags` :raises: None """ super(UserCreatorDialog, self).__init__(parent, flags) self.projects = projects or [] self.tasks = tasks or [] self.user = None self.setupUi(self) self.create_pb.clicked.connect(self.create_user) def create_user(self, ): """Create a user and store it in the self.user :returns: None :rtype: None :raises: None """ name = self.username_le.text() if not name: self.username_le.setPlaceholderText("Please provide a username.") return first = self.first_le.text() last = self.last_le.text() email = self.email_le.text() try: user = djadapter.models.User(username=name, first_name=first, last_name=last, email=email) user.save() for prj in self.projects: prj.users.add(user) for task in self.tasks: task.users.add(user) self.user = user self.accept() except: log.exception("Could not create new assettype") class UserAdderDialog(JB_Dialog, Ui_useradder_dialog): """A Dialog to add user to a project """ def __init__(self, project=None, task=None, parent=None, flags=0): """Initialize a new user creator dialog :param project: The project for the users :type project: :class:`jukeboxcore.djadapter.models.Project` :param task: The task for the users :type task: :class:`jukeboxcore.djadapter.models.Task` :param parent: the parent object :type parent: :class:`QtCore.QObject` :param flags: the window flags :type flags: :data:`QtCore.Qt.WindowFlags` :raises: None """ super(UserAdderDialog, self).__init__(parent, flags) self._project = project self._task = task self.users = [] self.setupUi(self) self.add_pb.clicked.connect(self.add_user) rootdata = treemodel.ListItemData(["Name", "Description"]) rootitem = treemodel.TreeItem(rootdata) if project: users = djadapter.users.exclude(project = project) else: users = djadapter.users.exclude(task = task) for user in users: userdata = djitemdata.UserItemData(user) treemodel.TreeItem(userdata, rootitem) self.model = treemodel.TreeModel(rootitem) self.user_tablev.setModel(self.model) def add_user(self, ): """Add a user and store it in the self.users :returns: None :rtype: None :raises: None """ i = self.user_tablev.currentIndex() item = i.internalPointer() if item: user = item.internal_data() if self._project: self._project.users.add(user) else: self._task.users.add(user) self.users.append(user) item.set_parent(None) class ShotCreatorDialog(JB_Dialog, Ui_shotcreator_dialog): """A Dialog to create a shot """ def __init__(self, sequence, parent=None, flags=0): """Initialize a new shot creator dialog :param sequence: the sequence for the shot :type sequence: :class:`jukeboxcore.djadapter.models.Shot` :param parent: the parent object :type parent: :class:`QtCore.QObject` :param flags: the window flags :type flags: :data:`QtCore.Qt.WindowFlags` :raises: None """ super(ShotCreatorDialog, self).__init__(parent, flags) self.sequence = sequence self.shot = None self.setupUi(self) self.create_pb.clicked.connect(self.create_shot) def create_shot(self, ): """Create a shot and store it in the self.shot :returns: None :rtype: None :raises: None """ name = self.name_le.text() if not name: self.name_le.setPlaceholderText("Please enter a name!") return desc = self.desc_pte.toPlainText() try: shot = djadapter.models.Shot(sequence=self.sequence, project=self.sequence.project, name=name, description=desc) shot.save() self.shot = shot self.accept() except: log.exception("Could not create new shot") class AssetCreatorDialog(JB_Dialog, Ui_assetcreator_dialog): """A Dialog to create a asset """ def __init__(self, project, atype=None, parent=None, flags=0): """Initialize a new asset creator dialog :param project: the project of the asset :type project: :class:`jukeboxcore.djadapter.models.Project` :param parent: the parent object :type parent: :class:`QtCore.QObject` :param flags: the window flags :type flags: :data:`QtCore.Qt.WindowFlags` :raises: None """ super(AssetCreatorDialog, self).__init__(parent, flags) self.project = project self.atype = atype self.asset = None self.setupUi(self) if not self.atype: self.atypes = list(project.atype_set.all()) atrootdata = treemodel.ListItemData(["Name"]) atrootitem = treemodel.TreeItem(atrootdata) for at in self.atypes: data = djitemdata.AtypeItemData(at) treemodel.TreeItem(data, atrootitem) self.atypemodel = treemodel.TreeModel(atrootitem) self.atype_cb.setModel(self.atypemodel) else: self.atype_cb.setVisible(False) self.atype_lb.setVisible(False) self.create_pb.clicked.connect(self.create_asset) def create_asset(self, ): """Create a asset and store it in the self.asset :returns: None :rtype: None :raises: None """ name = self.name_le.text() if not name: self.name_le.setPlaceholderText("Please enter a name!") return desc = self.desc_pte.toPlainText() if not self.atype: atypei = self.atype_cb.currentIndex() assert atypei >= 0 self.atype = self.atypes[atypei] try: asset = djadapter.models.Asset(atype=self.atype, project=self.project, name=name, description=desc) asset.save() self.asset = asset self.accept() except: log.exception("Could not create new asset") class AssetAdderDialog(JB_Dialog, Ui_assetadder_dialog): """A Dialog to add asset to a project """ def __init__(self, shot=None, asset=None, parent=None, flags=0): """Initialize a new asset creator dialog :param shot: The shot for the assets :type shot: :class:`jukeboxcore.djadapter.models.Shot` :param asset: The asset for the assets :type asset: :class:`jukeboxcore.djadapter.models.Asset` :param parent: the parent object :type parent: :class:`QtCore.QObject` :param flags: the window flags :type flags: :data:`QtCore.Qt.WindowFlags` :raises: None """ super(AssetAdderDialog, self).__init__(parent, flags) self._shot = shot self._asset = asset self.assets = [] self.setupUi(self) self.add_pb.clicked.connect(self.add_asset) rootdata = treemodel.ListItemData(["Name"]) rootitem = treemodel.TreeItem(rootdata) self.model = treemodel.TreeModel(rootitem) self.asset_treev.setModel(self.model) atypes = {} if shot: assets = djadapter.assets.exclude(pk__in = shot.assets.all()).filter(project=shot.project) else: assets = djadapter.assets.exclude(pk__in = asset.assets.all()).filter(project=asset.project) for asset in assets: atype = asset.atype atypeitem = atypes.get(atype) if not atypeitem: atypedata = djitemdata.AtypeItemData(atype) atypeitem = treemodel.TreeItem(atypedata, rootitem) atypes[atype] = atypeitem assetdata = djitemdata.AssetItemData(asset) treemodel.TreeItem(assetdata, atypeitem) def add_asset(self, ): """Add a asset and store it in the self.assets :returns: None :rtype: None :raises: None """ i = self.asset_treev.currentIndex() item = i.internalPointer() if item: asset = item.internal_data() if not isinstance(asset, djadapter.models.Asset): return if self._shot: self._shot.assets.add(asset) else: self._asset.assets.add(asset) self.assets.append(asset) item.set_parent(None) class TaskCreatorDialog(JB_Dialog, Ui_taskcreator_dialog): """A Dialog to create a task """ def __init__(self, element, parent=None, flags=0): """Initialize a new task creator dialog :param element: the element for the task :type element: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` :param parent: the parent object :type parent: :class:`QtCore.QObject` :param flags: the window flags :type flags: :data:`QtCore.Qt.WindowFlags` :raises: None """ super(TaskCreatorDialog, self).__init__(parent, flags) self.element = element self.task = None self.setupUi(self) self.create_pb.clicked.connect(self.create_task) qs = djadapter.departments.filter(projects=element.project).exclude(pk__in = element.tasks.all().values_list('department', flat=True)) qs = qs.filter(assetflag=isinstance(element, djadapter.models.Asset)) self.deps = list(qs) atrootdata = treemodel.ListItemData(["Name"]) atrootitem = treemodel.TreeItem(atrootdata) for dep in self.deps: data = djitemdata.DepartmentItemData(dep) treemodel.TreeItem(data, atrootitem) self.model = treemodel.TreeModel(atrootitem) self.dep_cb.setModel(self.model) def create_task(self, ): """Create a task and store it in the self.task :returns: None :rtype: None :raises: None """ depi = self.dep_cb.currentIndex() assert depi >= 0 dep = self.deps[depi] deadline = self.deadline_de.dateTime().toPython() try: task = djadapter.models.Task(department=dep, project=self.element.project, element=self.element, deadline=deadline) task.save() self.task = task self.accept() except: log.exception("Could not create new task") class GuerillaMGMTWin(JB_MainWindow, Ui_guerillamgmt_mwin): """A tool for creating entries in the database and a little project management. """ def __init__(self, parent=None, flags=0): """Initialize a new GuerillaMGMTwin :param parent: the parent object :type parent: :class:`QtCore.QObject` :param flags: the window flags :type flags: :data:`QtCore.Qt.WindowFlags` :raises: None """ super(GuerillaMGMTWin, self).__init__(parent, flags) self.cur_prj = None self.cur_seq = None self.cur_shot = None self.cur_atype = None self.cur_asset = None self.cur_dep = None self.cur_task = None self.cur_user = None self.setupUi(self) self.setup_ui() try: self.setup_signals() except: log.exception("Exception setting up signals") def setup_ui(self, ): """Create all necessary ui elements for the tool :returns: None :rtype: None :raises: None """ log.debug("Setting up the ui") self.setup_prjs_page() self.setup_prj_page() self.setup_seq_page() self.setup_shot_page() self.setup_atype_page() self.setup_asset_page() self.setup_dep_page() self.setup_task_page() self.setup_users_page() self.setup_user_page() def setup_prjs_page(self, ): """Create and set the model on the projects page :returns: None :rtype: None :raises: None """ self.prjs_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents) log.debug("Loading projects for projects page.") rootdata = treemodel.ListItemData(['Name', 'Short', 'Path', 'Created', 'Semester', 'Status', 'Resolution', 'FPS', 'Scale']) rootitem = treemodel.TreeItem(rootdata) prjs = djadapter.projects.all() for prj in prjs: prjdata = djitemdata.ProjectItemData(prj) treemodel.TreeItem(prjdata, rootitem) self.prjs_model = treemodel.TreeModel(rootitem) self.prjs_tablev.setModel(self.prjs_model) def setup_prj_page(self, ): """Create and set the model on the project page :returns: None :rtype: None :raises: None """ self.prj_seq_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents) self.prj_atype_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents) self.prj_dep_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents) self.prj_user_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents) def setup_seq_page(self, ): """Create and set the model on the sequence page :returns: None :rtype: None :raises: None """ self.seq_shot_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents) def setup_shot_page(self, ): """Create and set the model on the shot page :returns: None :rtype: None :raises: None """ self.shot_asset_treev.header().setResizeMode(QtGui.QHeaderView.ResizeToContents) self.shot_task_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents) def setup_atype_page(self, ): """Create and set the model on the atype page :returns: None :rtype: None :raises: None """ pass def setup_asset_page(self, ): """Create and set the model on the asset page :returns: None :rtype: None :raises: None """ self.asset_asset_treev.header().setResizeMode(QtGui.QHeaderView.ResizeToContents) self.asset_task_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents) def setup_dep_page(self, ): """Create and set the model on the department page :returns: None :rtype: None :raises: None """ self.dep_prj_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents) def setup_task_page(self, ): """Create and set the model on the task page :returns: None :rtype: None :raises: None """ self.task_user_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents) def setup_users_page(self, ): """Create and set the model on the users page :returns: None :rtype: None :raises: None """ self.users_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents) log.debug("Loading users for users page.") rootdata = treemodel.ListItemData(['Username', 'First', 'Last', 'Email']) rootitem = treemodel.TreeItem(rootdata) users = djadapter.users.all() for usr in users: usrdata = djitemdata.UserItemData(usr) treemodel.TreeItem(usrdata, rootitem) self.users_model = treemodel.TreeModel(rootitem) self.users_tablev.setModel(self.users_model) def setup_user_page(self, ): """Create and set the model on the user page :returns: None :rtype: None :raises: None """ self.user_prj_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents) self.user_task_treev.header().setResizeMode(QtGui.QHeaderView.ResizeToContents) def setup_signals(self, ): """Connect the signals with the slots to make the ui functional :returns: None :rtype: None :raises: None """ log.debug("Setting up signals.") self.setup_prjs_signals() self.setup_prj_signals() self.setup_seq_signals() self.setup_shot_signals() self.setup_atype_signals() self.setup_asset_signals() self.setup_dep_signals() self.setup_task_signals() self.setup_users_signals() self.setup_user_signals() log.debug("Signals are set up.") def setup_prjs_signals(self, ): """Setup the signals for the projects page :returns: None :rtype: None :raises: None """ log.debug("Setting up projects page signals.") self.prjs_prj_view_pb.clicked.connect(self.prjs_view_prj) self.prjs_prj_create_pb.clicked.connect(self.prjs_create_prj) def setup_prj_signals(self, ): """Setup the signals for the project page :returns: None :rtype: None :raises: None """ log.debug("Setting up project page signals.") self.prj_seq_view_pb.clicked.connect(self.prj_view_seq) self.prj_seq_create_pb.clicked.connect(self.prj_create_seq) self.prj_atype_view_pb.clicked.connect(self.prj_view_atype) self.prj_atype_add_pb.clicked.connect(self.prj_add_atype) self.prj_atype_create_pb.clicked.connect(self.prj_create_atype) self.prj_dep_view_pb.clicked.connect(self.prj_view_dep) self.prj_dep_add_pb.clicked.connect(self.prj_add_dep) self.prj_dep_create_pb.clicked.connect(self.prj_create_dep) self.prj_user_view_pb.clicked.connect(self.prj_view_user) self.prj_user_add_pb.clicked.connect(self.prj_add_user) self.prj_user_remove_pb.clicked.connect(self.prj_remove_user) self.prj_user_create_pb.clicked.connect(self.prj_create_user) self.prj_path_view_pb.clicked.connect(self.prj_show_path) self.prj_desc_pte.textChanged.connect(self.prj_save) self.prj_semester_le.editingFinished.connect(self.prj_save) self.prj_fps_dsb.valueChanged.connect(self.prj_save) self.prj_res_x_sb.valueChanged.connect(self.prj_save) self.prj_res_y_sb.valueChanged.connect(self.prj_save) self.prj_scale_cb.currentIndexChanged.connect(self.prj_save) def setup_seq_signals(self, ): """Setup the signals for the sequence page :returns: None :rtype: None :raises: None """ log.debug("Setting up sequence page signals.") self.seq_prj_view_pb.clicked.connect(self.seq_view_prj) self.seq_shot_view_pb.clicked.connect(self.seq_view_shot) self.seq_shot_create_pb.clicked.connect(self.seq_create_shot) self.seq_desc_pte.textChanged.connect(self.seq_save) def setup_shot_signals(self, ): """Setup the signals for the shot page :returns: None :rtype: None :raises: None """ log.debug("Setting up shot page signals.") self.shot_prj_view_pb.clicked.connect(self.shot_view_prj) self.shot_seq_view_pb.clicked.connect(self.shot_view_seq) self.shot_asset_view_pb.clicked.connect(self.shot_view_asset) self.shot_asset_create_pb.clicked.connect(self.shot_create_asset) self.shot_asset_add_pb.clicked.connect(self.shot_add_asset) self.shot_asset_remove_pb.clicked.connect(self.shot_remove_asset) self.shot_task_view_pb.clicked.connect(self.shot_view_task) self.shot_task_create_pb.clicked.connect(self.shot_create_task) self.shot_start_sb.valueChanged.connect(self.shot_save) self.shot_end_sb.valueChanged.connect(self.shot_save) self.shot_handle_sb.valueChanged.connect(self.shot_save) self.shot_desc_pte.textChanged.connect(self.shot_save) def setup_atype_signals(self, ): """Setup the signals for the assettype page :returns: None :rtype: None :raises: None """ log.debug("Setting up atype page signals.") self.asset_prj_view_pb.clicked.connect(self.asset_view_prj) self.asset_atype_view_pb.clicked.connect(self.asset_view_atype) self.atype_asset_view_pb.clicked.connect(self.atype_view_asset) self.atype_asset_create_pb.clicked.connect(self.atype_create_asset) self.atype_desc_pte.textChanged.connect(self.atype_save) def setup_asset_signals(self, ): """Setup the signals for the asset page :returns: None :rtype: None :raises: None """ log.debug("Setting up asset signals.") self.asset_asset_view_pb.clicked.connect(self.asset_view_asset) self.asset_asset_create_pb.clicked.connect(self.asset_create_asset) self.asset_asset_add_pb.clicked.connect(self.asset_add_asset) self.asset_asset_remove_pb.clicked.connect(self.asset_remove_asset) self.asset_task_view_pb.clicked.connect(self.asset_view_task) self.asset_task_create_pb.clicked.connect(self.asset_create_task) self.asset_desc_pte.textChanged.connect(self.asset_save) def setup_dep_signals(self, ): """Setup the signals for the department page :returns: None :rtype: None :raises: None """ log.debug("Setting up department page signals.") self.dep_prj_view_pb.clicked.connect(self.dep_view_prj) self.dep_prj_add_pb.clicked.connect(self.dep_add_prj) self.dep_prj_remove_pb.clicked.connect(self.dep_remove_prj) self.dep_desc_pte.textChanged.connect(self.dep_save) self.dep_ordervalue_sb.valueChanged.connect(self.dep_save) def setup_task_signals(self, ): """Setup the signals for the task page :returns: None :rtype: None :raises: None """ log.debug("Setting up task page signals.") self.task_user_view_pb.clicked.connect(self.task_view_user) self.task_user_add_pb.clicked.connect(self.task_add_user) self.task_user_remove_pb.clicked.connect(self.task_remove_user) self.task_dep_view_pb.clicked.connect(self.task_view_dep) self.task_link_view_pb.clicked.connect(self.task_view_link) self.task_deadline_de.dateChanged.connect(self.task_save) self.task_status_cb.currentIndexChanged.connect(self.task_save) def setup_users_signals(self, ): """Setup the signals for the users page :returns: None :rtype: None :raises: None """ log.debug("Setting up users page signals.") self.users_user_view_pb.clicked.connect(self.users_view_user) self.users_user_create_pb.clicked.connect(self.create_user) def setup_user_signals(self, ): """Setup the signals for the user page :returns: None :rtype: None :raises: None """ log.debug("Setting up user page signals.") self.user_task_view_pb.clicked.connect(self.user_view_task) self.user_prj_view_pb.clicked.connect(self.user_view_prj) self.user_prj_add_pb.clicked.connect(self.user_add_prj) self.user_prj_remove_pb.clicked.connect(self.user_remove_prj) self.user_username_le.editingFinished.connect(self.user_save) self.user_first_le.editingFinished.connect(self.user_save) self.user_last_le.editingFinished.connect(self.user_save) self.user_email_le.editingFinished.connect(self.user_save) def prjs_view_prj(self, *args, **kwargs): """View the, in the projects table view selected, project. :returns: None :rtype: None :raises: None """ i = self.prjs_tablev.currentIndex() item = i.internalPointer() if item: prj = item.internal_data() self.view_prj(prj) def prjs_create_prj(self, *args, **kwargs): """Create a new project :returns: None :rtype: None :raises: None """ self.create_prj() def view_prj(self, prj): """View the given project on the project page :param prj: the project to view :type prj: :class:`jukeboxcore.djadapter.models.Project` :returns: None :rtype: None :raises: None """ log.debug('Viewing project %s', prj.name) self.cur_prj = None self.pages_tabw.setCurrentIndex(1) self.prj_name_le.setText(prj.name) self.prj_short_le.setText(prj.short) self.prj_path_le.setText(prj.path) self.prj_desc_pte.setPlainText(prj.description) self.prj_created_dte.setDateTime(dt_to_qdatetime(prj.date_created)) self.prj_semester_le.setText(prj.semester) self.prj_fps_dsb.setValue(prj.framerate) self.prj_res_x_sb.setValue(prj.resx) self.prj_res_y_sb.setValue(prj.resy) scalemap = {"m": 2, "meter": 2, "mm": 0, "millimeter": 0, "cm": 1, "centimeter": 1, "km": 3, "kilometer": 3, "inch": 4, "foot": 5, "yard": 6, "mile": 7} scaleindex = scalemap.get(prj.scale, -1) log.debug("Setting index of project scale combobox to %s. Scale is %s", scaleindex, prj.scale) self.prj_scale_cb.setCurrentIndex(scaleindex) seqrootdata = treemodel.ListItemData(['Name', "Description"]) seqrootitem = treemodel.TreeItem(seqrootdata) for seq in prj.sequence_set.all(): seqdata = djitemdata.SequenceItemData(seq) treemodel.TreeItem(seqdata, seqrootitem) self.prj_seq_model = treemodel.TreeModel(seqrootitem) self.prj_seq_tablev.setModel(self.prj_seq_model) atyperootdata = treemodel.ListItemData(['Name', "Description"]) atyperootitem = treemodel.TreeItem(atyperootdata) for atype in prj.atype_set.all(): atypedata = djitemdata.AtypeItemData(atype) treemodel.TreeItem(atypedata, atyperootitem) self.prj_atype_model = treemodel.TreeModel(atyperootitem) self.prj_atype_tablev.setModel(self.prj_atype_model) deprootdata = treemodel.ListItemData(['Name', "Description", "Ordervalue"]) deprootitem = treemodel.TreeItem(deprootdata) for dep in prj.department_set.all(): depdata = djitemdata.DepartmentItemData(dep) treemodel.TreeItem(depdata, deprootitem) self.prj_dep_model = treemodel.TreeModel(deprootitem) self.prj_dep_tablev.setModel(self.prj_dep_model) userrootdata = treemodel.ListItemData(['Username', 'First', 'Last', 'Email']) userrootitem = treemodel.TreeItem(userrootdata) for user in prj.users.all(): userdata = djitemdata.UserItemData(user) treemodel.TreeItem(userdata, userrootitem) self.prj_user_model = treemodel.TreeModel(userrootitem) self.prj_user_tablev.setModel(self.prj_user_model) self.cur_prj = prj def create_prj(self, atypes=None, deps=None): """Create and return a new project :param atypes: add the given atypes to the project :type atypes: list | None :param deps: add the given departmetns to the project :type deps: list | None :returns: The created project or None :rtype: None | :class:`jukeboxcore.djadapter.models.Project` :raises: None """ dialog = ProjectCreatorDialog(parent=self) dialog.exec_() prj = dialog.project if prj and atypes: for at in atypes: at.projects.add(prj) at.save() if prj and deps: for dep in deps: dep.projects.add(prj) dep.save() if prj: prjdata = djitemdata.ProjectItemData(prj) treemodel.TreeItem(prjdata, self.prjs_model.root) return prj def prj_view_seq(self, *args, **kwargs): """View the, in the prj_seq_tablev selected, sequence. :returns: None :rtype: None :raises: None """ if not self.cur_prj: return i = self.prj_seq_tablev.currentIndex() item = i.internalPointer() if item: seq = item.internal_data() self.view_seq(seq) def prj_create_seq(self, *args, **kwargs): """Create a new Sequence for the current project :returns: None :rtype: None :raises: None """ if not self.cur_prj: return seq = self.create_seq(project=self.cur_prj) if seq: seqdata = djitemdata.SequenceItemData(seq) treemodel.TreeItem(seqdata, self.prj_seq_model.root) def view_seq(self, seq): """View the given sequence on the sequence page :param seq: the sequence to view :type seq: :class:`jukeboxcore.djadapter.models.Sequence` :returns: None :rtype: None :raises: None """ log.debug('Viewing sequence %s', seq.name) self.cur_seq = None self.pages_tabw.setCurrentIndex(2) self.seq_name_le.setText(seq.name) self.seq_prj_le.setText(seq.project.name) self.seq_desc_pte.setPlainText(seq.description) shotrootdata = treemodel.ListItemData(['Name', "Description", "Duration", "Start", "End"]) shotrootitem = treemodel.TreeItem(shotrootdata) for shot in seq.shot_set.all(): shotdata = djitemdata.ShotItemData(shot) treemodel.TreeItem(shotdata, shotrootitem) self.seq_shot_model = treemodel.TreeModel(shotrootitem) self.seq_shot_tablev.setModel(self.seq_shot_model) self.cur_seq = seq def create_seq(self, project): """Create and return a new sequence :param project: the project for the sequence :type deps: :class:`jukeboxcore.djadapter.models.Project` :returns: The created sequence or None :rtype: None | :class:`jukeboxcore.djadapter.models.Sequence` :raises: None """ dialog = SequenceCreatorDialog(project=project, parent=self) dialog.exec_() seq = dialog.sequence return seq def prj_view_atype(self, *args, **kwargs): """View the, in the atype table view selected, assettype. :returns: None :rtype: None :raises: None """ if not self.cur_prj: return i = self.prj_atype_tablev.currentIndex() item = i.internalPointer() if item: atype = item.internal_data() self.view_atype(atype) def prj_add_atype(self, *args, **kwargs): """Add more assettypes to the project. :returns: None :rtype: None :raises: None """ if not self.cur_prj: return dialog = AtypeAdderDialog(project=self.cur_prj) dialog.exec_() atypes = dialog.atypes for atype in atypes: atypedata = djitemdata.AtypeItemData(atype) treemodel.TreeItem(atypedata, self.prj_atype_model.root) def prj_create_atype(self, *args, **kwargs): """Create a new project :returns: None :rtype: None :raises: None """ if not self.cur_prj: return atype = self.create_atype(projects=[self.cur_prj]) if atype: atypedata = djitemdata.AtypeItemData(atype) treemodel.TreeItem(atypedata, self.prj_atype_model.root) def create_atype(self, projects): """Create and return a new atype :param projects: the projects for the atype :type projects: :class:`jukeboxcore.djadapter.models.Project` :returns: The created atype or None :rtype: None | :class:`jukeboxcore.djadapter.models.Atype` :raises: None """ dialog = AtypeCreatorDialog(projects=projects, parent=self) dialog.exec_() atype = dialog.atype return atype def view_atype(self, atype): """View the given atype on the atype page :param atype: the atype to view :type atype: :class:`jukeboxcore.djadapter.models.Atype` :returns: None :rtype: None :raises: None """ if not self.cur_prj: return log.debug('Viewing atype %s', atype.name) self.cur_atype = None self.pages_tabw.setCurrentIndex(4) self.atype_name_le.setText(atype.name) self.atype_desc_pte.setPlainText(atype.description) assetrootdata = treemodel.ListItemData(['Name', 'Description']) assetrootitem = treemodel.TreeItem(assetrootdata) self.atype_asset_model = treemodel.TreeModel(assetrootitem) self.atype_asset_treev.setModel(self.atype_asset_model) for a in djadapter.assets.filter(project=self.cur_prj, atype=atype): assetdata = djitemdata.AssetItemData(a) treemodel.TreeItem(assetdata, assetrootitem) self.cur_atype = atype def prj_view_dep(self, *args, **kwargs): """View the, in the dep table view selected, department. :returns: None :rtype: None :raises: None """ if not self.cur_prj: return i = self.prj_dep_tablev.currentIndex() item = i.internalPointer() if item: dep = item.internal_data() self.view_dep(dep) def prj_add_dep(self, *args, **kwargs): """Add more departments to the project. :returns: None :rtype: None :raises: None """ if not self.cur_prj: return dialog = DepAdderDialog(project=self.cur_prj) dialog.exec_() deps = dialog.deps for dep in deps: depdata = djitemdata.DepartmentItemData(dep) treemodel.TreeItem(depdata, self.prj_dep_model.root) def prj_create_dep(self, *args, **kwargs): """Create a new project :returns: None :rtype: None :raises: None """ if not self.cur_prj: return dep = self.create_dep(projects=[self.cur_prj]) if dep: depdata = djitemdata.DepartmentItemData(dep) treemodel.TreeItem(depdata, self.prj_dep_model.root) def create_dep(self, projects): """Create and return a new dep :param projects: the projects for the dep :type projects: :class:`jukeboxcore.djadapter.models.Project` :returns: The created dep or None :rtype: None | :class:`jukeboxcore.djadapter.models.Dep` :raises: None """ dialog = DepCreatorDialog(projects=projects, parent=self) dialog.exec_() dep = dialog.dep return dep def view_dep(self, dep): """View the given department on the department page :param dep: the dep to view :type dep: :class:`jukeboxcore.djadapter.models.Department` :returns: None :rtype: None :raises: None """ log.debug('Viewing department %s', dep.name) self.cur_dep = None self.pages_tabw.setCurrentIndex(6) self.dep_name_le.setText(dep.name) self.dep_short_le.setText(dep.short) self.dep_shot_rb.setChecked(not dep.assetflag) self.dep_asset_rb.setChecked(dep.assetflag) self.dep_ordervalue_sb.setValue(dep.ordervalue) self.dep_desc_pte.setPlainText(dep.description) rootdata = treemodel.ListItemData(['Name', 'Short', 'Path', 'Created', 'Semester', 'Status', 'Resolution', 'FPS', 'Scale']) rootitem = treemodel.TreeItem(rootdata) prjs = dep.projects.all() for prj in prjs: prjdata = djitemdata.ProjectItemData(prj) treemodel.TreeItem(prjdata, rootitem) self.dep_prj_model = treemodel.TreeModel(rootitem) self.dep_prj_tablev.setModel(self.dep_prj_model) self.cur_dep = dep def prj_view_user(self, *args, **kwargs): """View the, in the user table view selected, user. :returns: None :rtype: None :raises: None """ if not self.cur_prj: return i = self.prj_user_tablev.currentIndex() item = i.internalPointer() if item: user = item.internal_data() self.view_user(user) def prj_add_user(self, *args, **kwargs): """Add more users to the project. :returns: None :rtype: None :raises: None """ if not self.cur_prj: return dialog = UserAdderDialog(project=self.cur_prj) dialog.exec_() users = dialog.users for user in users: userdata = djitemdata.UserItemData(user) treemodel.TreeItem(userdata, self.prj_user_model.root) self.cur_prj.save() def prj_remove_user(self, *args, **kwargs): """Remove the, in the user table view selected, user. :returns: None :rtype: None :raises: None """ if not self.cur_prj: return i = self.prj_user_tablev.currentIndex() item = i.internalPointer() if item: user = item.internal_data() log.debug("Removing user %s.", user.username) item.set_parent(None) self.cur_prj.users.remove(user) def prj_create_user(self, *args, **kwargs): """Create a new project :returns: None :rtype: None :raises: None """ if not self.cur_prj: return user = self.create_user(projects=[self.cur_prj]) if user: userdata = djitemdata.UserItemData(user) treemodel.TreeItem(userdata, self.prj_user_model.root) def create_user(self, projects=None, tasks=None): """Create and return a new user :param projects: the projects for the user :type projects: list of :class:`jukeboxcore.djadapter.models.Project` :param tasks: the tasks for the user :type tasks: list of :class:`jukeboxcore.djadapter.models.Task` :returns: The created user or None :rtype: None | :class:`jukeboxcore.djadapter.models.User` :raises: None """ projects = projects or [] tasks = tasks or [] dialog = UserCreatorDialog(projects=projects, tasks=tasks, parent=self) dialog.exec_() user = dialog.user if user: userdata = djitemdata.UserItemData(user) treemodel.TreeItem(userdata, self.users_model.root) return user def view_user(self, user): """View the given user on the user page :param user: the user to view :type user: :class:`jukeboxcore.djadapter.models.User` :returns: None :rtype: None :raises: None """ log.debug('Viewing user %s', user.username) self.cur_user = None self.pages_tabw.setCurrentIndex(9) self.user_username_le.setText(user.username) self.user_first_le.setText(user.first_name) self.user_last_le.setText(user.last_name) self.user_email_le.setText(user.email) prjrootdata = treemodel.ListItemData(['Name', 'Short', 'Path', 'Created', 'Semester', 'Status', 'Resolution', 'FPS', 'Scale']) prjrootitem = treemodel.TreeItem(prjrootdata) prjs = djadapter.projects.filter(users=user) for prj in prjs: prjdata = djitemdata.ProjectItemData(prj) treemodel.TreeItem(prjdata, prjrootitem) self.user_prj_model = treemodel.TreeModel(prjrootitem) self.user_prj_tablev.setModel(self.user_prj_model) taskrootdata = treemodel.ListItemData(['Name']) taskrootitem = treemodel.TreeItem(taskrootdata) self.user_task_model = treemodel.TreeModel(taskrootitem) self.user_task_treev.setModel(self.user_task_model) tasks = djadapter.tasks.filter(users=user) assets = {} shots = {} atypes = {} seqs = {} prjs = {} for t in tasks: tdata = djitemdata.TaskItemData(t) titem = treemodel.TreeItem(tdata) e = t.element if isinstance(e, djadapter.models.Asset): eitem = assets.get(e) if not eitem: edata = djitemdata.AssetItemData(e) eitem = treemodel.TreeItem(edata) assets[e] = eitem egrp = e.atype egrpitem = atypes.get(egrp) if not egrpitem: egrpdata = djitemdata.AtypeItemData(egrp) egrpitem = treemodel.TreeItem(egrpdata) atypes[egrp] = egrpitem else: eitem = shots.get(e) if not eitem: edata = djitemdata.ShotItemData(e) eitem = treemodel.TreeItem(edata) shots[e] = eitem egrp = e.sequence egrpitem = seqs.get(egrp) if not egrpitem: egrpdata = djitemdata.SequenceItemData(egrp) egrpitem = treemodel.TreeItem(egrpdata) seqs[egrp] = egrpitem if eitem not in egrpitem.childItems: eitem.set_parent(egrpitem) prj = egrp.project prjitem = prjs.get(prj) if not prjitem: prjdata = djitemdata.ProjectItemData(prj) prjitem = treemodel.TreeItem(prjdata, taskrootitem) prjs[prj] = prjitem assetdata = treemodel.ListItemData(["Asset"]) assetitem = treemodel.TreeItem(assetdata, prjitem) shotdata = treemodel.ListItemData(["Shot"]) shotitem = treemodel.TreeItem(shotdata, prjitem) else: assetitem = prjitem.child(0) shotitem = prjitem.child(1) if isinstance(egrp, djadapter.models.Atype) and egrpitem not in assetitem.childItems: egrpitem.set_parent(assetitem) elif isinstance(egrp, djadapter.models.Sequence) and egrpitem not in shotitem.childItems: egrpitem.set_parent(shotitem) titem.set_parent(eitem) self.cur_user = user def prj_show_path(self, ): """Show the dir in the a filebrowser of the project :returns: None :rtype: None :raises: None """ f = self.prj_path_le.text() osinter = ostool.get_interface() osinter.open_path(f) def prj_save(self): """Save the current project :returns: None :rtype: None :raises: None """ if not self.cur_prj: return desc = self.prj_desc_pte.toPlainText() semester = self.prj_semester_le.text() fps = self.prj_fps_dsb.value() resx = self.prj_res_x_sb.value() resy = self.prj_res_y_sb.value() scale = self.prj_scale_cb.currentText() self.cur_prj.description = desc self.cur_prj.semester = semester self.cur_prj.framerate = fps self.cur_prj.resx = resx self.cur_prj.resy = resy self.cur_prj.scale = scale self.cur_prj.save() def seq_save(self): """Save the current sequence :returns: None :rtype: None :raises: None """ if not self.cur_seq: return desc = self.seq_desc_pte.toPlainText() self.cur_seq.description = desc self.cur_seq.save() def seq_view_prj(self, ): """View the project or the current sequence :returns: None :rtype: None :raises: None """ if not self.cur_seq: return self.view_prj(self.cur_seq.project) def seq_view_shot(self, ): """View the shot that is selected in the table view of the sequence page :returns: None :rtype: None :raises: None """ if not self.cur_seq: return i = self.seq_shot_tablev.currentIndex() item = i.internalPointer() if item: shot = item.internal_data() self.view_shot(shot) def seq_create_shot(self, *args, **kwargs): """Create a new shot :returns: None :rtype: None :raises: None """ if not self.cur_seq: return shot = self.create_shot(sequence=self.cur_seq) if shot: shotdata = djitemdata.ShotItemData(shot) treemodel.TreeItem(shotdata, self.seq_shot_model.root) def view_shot(self, shot): """View the given shot :param shot: the shot to view :type shot: :class:`jukeboxcore.djadapter.models.Shot` :returns: None :rtype: None :raises: None """ log.debug('Viewing shot %s', shot.name) self.cur_shot = None self.pages_tabw.setCurrentIndex(3) self.shot_name_le.setText(shot.name) self.shot_prj_le.setText(shot.project.name) self.shot_seq_le.setText(shot.sequence.name) self.shot_start_sb.setValue(shot.startframe) self.shot_end_sb.setValue(shot.endframe) self.shot_handle_sb.setValue(shot.handlesize) self.shot_desc_pte.setPlainText(shot.description) assetsrootdata = treemodel.ListItemData(["Name", "Description"]) assetsrootitem = treemodel.TreeItem(assetsrootdata) self.shot_asset_model = treemodel.TreeModel(assetsrootitem) self.shot_asset_treev.setModel(self.shot_asset_model) atypes = {} assets = shot.assets.all() for a in assets: atype = a.atype atypeitem = atypes.get(atype) if not atypeitem: atypedata = djitemdata.AtypeItemData(atype) atypeitem = treemodel.TreeItem(atypedata, assetsrootitem) atypes[atype] = atypeitem assetdata = djitemdata.AssetItemData(a) treemodel.TreeItem(assetdata, atypeitem) tasksrootdata = treemodel.ListItemData(["Name", "Short"]) tasksrootitem = treemodel.TreeItem(tasksrootdata) self.shot_task_model = treemodel.TreeModel(tasksrootitem) self.shot_task_tablev.setModel(self.shot_task_model) tasks = shot.tasks.all() for t in tasks: tdata = djitemdata.TaskItemData(t) treemodel.TreeItem(tdata, tasksrootitem) self.cur_shot = shot def create_shot(self, sequence): """Create and return a new shot :param sequence: the sequence for the shot :type sequence: :class:`jukeboxcore.djadapter.models.Sequence` :returns: The created shot or None :rtype: None | :class:`jukeboxcore.djadapter.models.Shot` :raises: None """ dialog = ShotCreatorDialog(sequence=sequence, parent=self) dialog.exec_() shot = dialog.shot return shot def shot_view_prj(self, ): """View the project of the current shot :returns: None :rtype: None :raises: None """ if not self.cur_shot: return self.view_prj(self.cur_shot.project) def shot_view_seq(self, ): """View the sequence of the current shot :returns: None :rtype: None :raises: None """ if not self.cur_shot: return self.view_seq(self.cur_shot.sequence) def shot_view_task(self, ): """View the task that is currently selected on the shot page :returns: None :rtype: None :raises: None """ if not self.cur_shot: return i = self.shot_task_tablev.currentIndex() item = i.internalPointer() if item: task = item.internal_data() self.view_task(task) def shot_view_asset(self, ): """View the task that is currently selected on the shot page :returns: None :rtype: None :raises: None """ if not self.cur_shot: return i = self.shot_asset_treev.currentIndex() item = i.internalPointer() if item: asset = item.internal_data() if isinstance(asset, djadapter.models.Asset): self.view_asset(asset) def shot_create_task(self, *args, **kwargs): """Create a new task :returns: None :rtype: None :raises: None """ if not self.cur_shot: return task = self.create_task(element=self.cur_shot) if task: taskdata = djitemdata.TaskItemData(task) treemodel.TreeItem(taskdata, self.shot_task_model.root) def create_task(self, element): """Create a new task for the given element :param element: the element for the task :type element: :class:`jukeboxcore.djadapter.models.Shot` | :class:`jukeboxcore.djadapter.models.Asset` :returns: None :rtype: None :raises: None """ dialog = TaskCreatorDialog(element=element, parent=self) dialog.exec_() task = dialog.task return task def view_asset(self, asset): """View the given asset :param asset: the asset to view :type asset: :class:`jukeboxcore.djadapter.models.Asset` :returns: None :rtype: None :raises: None """ log.debug('Viewing asset %s', asset.name) self.cur_asset = None self.pages_tabw.setCurrentIndex(5) name = asset.name prj = asset.project.name atype = asset.atype.name desc = asset.description self.asset_name_le.setText(name) self.asset_prj_le.setText(prj) self.asset_atype_le.setText(atype) self.asset_desc_pte.setPlainText(desc) assetsrootdata = treemodel.ListItemData(["Name", "Description"]) assetsrootitem = treemodel.TreeItem(assetsrootdata) self.asset_asset_model = treemodel.TreeModel(assetsrootitem) self.asset_asset_treev.setModel(self.asset_asset_model) atypes = {} assets = asset.assets.all() for a in assets: atype = a.atype atypeitem = atypes.get(atype) if not atypeitem: atypedata = djitemdata.AtypeItemData(atype) atypeitem = treemodel.TreeItem(atypedata, assetsrootitem) atypes[atype] = atypeitem assetdata = djitemdata.AssetItemData(a) treemodel.TreeItem(assetdata, atypeitem) tasksrootdata = treemodel.ListItemData(["Name", "Short"]) tasksrootitem = treemodel.TreeItem(tasksrootdata) self.asset_task_model = treemodel.TreeModel(tasksrootitem) self.asset_task_tablev.setModel(self.asset_task_model) tasks = asset.tasks.all() for t in tasks: tdata = djitemdata.TaskItemData(t) treemodel.TreeItem(tdata, tasksrootitem) self.cur_asset = asset def shot_add_asset(self, *args, **kwargs): """Add more assets to the shot. :returns: None :rtype: None :raises: None """ if not self.cur_shot: return dialog = AssetAdderDialog(shot=self.cur_shot) dialog.exec_() assets = dialog.assets atypes = {} for c in self.shot_asset_model.root.childItems: atypes[c.internal_data()] = c for asset in assets: atypeitem = atypes.get(asset.atype) if not atypeitem: atypedata = djitemdata.AtypeItemData(asset.atype) atypeitem = treemodel.TreeItem(atypedata, self.shot_asset_model.root) atypes[asset.atype] = atypeitem assetdata = djitemdata.AssetItemData(asset) treemodel.TreeItem(assetdata, atypeitem) self.cur_shot.save() def shot_remove_asset(self, *args, **kwargs): """Remove the, in the asset table view selected, asset. :returns: None :rtype: None :raises: None """ if not self.cur_shot: return i = self.shot_asset_treev.currentIndex() item = i.internalPointer() if item: asset = item.internal_data() if not isinstance(asset, djadapter.models.Asset): return log.debug("Removing asset %s.", asset.name) item.set_parent(None) self.cur_shot.assets.remove(asset) def shot_create_asset(self, *args, **kwargs): """Create a new shot :returns: None :rtype: None :raises: None """ if not self.cur_shot: return asset = self.create_asset(project=self.cur_shot.project, shot=self.cur_shot) if not asset: return atypes = {} for c in self.shot_asset_model.root.childItems: atypes[c.internal_data()] = c atypeitem = atypes.get(asset.atype) if not atypeitem: atypedata = djitemdata.AtypeItemData(asset.atype) atypeitem = treemodel.TreeItem(atypedata, self.shot_asset_model.root) atypes[asset.atype] = atypeitem assetdata = djitemdata.AssetItemData(asset) treemodel.TreeItem(assetdata, atypeitem) def create_asset(self, project, atype=None, shot=None, asset=None): """Create and return a new asset :param project: the project for the asset :type project: :class:`jukeboxcore.djadapter.models.Project` :param atype: the assettype of the asset :type atype: :class:`jukeboxcore.djadapter.models.Atype` :param shot: the shot to add the asset to :type shot: :class:`jukeboxcore.djadapter.models.Shot` :param asset: the asset to add the new asset to :type asset: :class:`jukeboxcore.djadapter.models.Asset` :returns: The created asset or None :rtype: None | :class:`jukeboxcore.djadapter.models.Asset` :raises: None """ element = shot or asset dialog = AssetCreatorDialog(project=project, atype=atype, parent=self) dialog.exec_() asset = dialog.asset if not atype: element.assets.add(asset) return asset def view_task(self, task): """View the given task :param task: the task to view :type task: :class:`jukeboxcore.djadapter.models.Task` :returns: None :rtype: None :raises: None """ log.debug('Viewing task %s', task.name) self.cur_task = None self.pages_tabw.setCurrentIndex(7) self.task_dep_le.setText(task.name) statusmap = {"New": 0, "Open": 1, "Done":2} self.task_status_cb.setCurrentIndex(statusmap.get(task.status, -1)) dt = dt_to_qdatetime(task.deadline) if task.deadline else None self.task_deadline_de.setDateTime(dt) self.task_link_le.setText(task.element.name) userrootdata = treemodel.ListItemData(['Username', 'First', 'Last', 'Email']) userrootitem = treemodel.TreeItem(userrootdata) for user in task.users.all(): userdata = djitemdata.UserItemData(user) treemodel.TreeItem(userdata, userrootitem) self.task_user_model = treemodel.TreeModel(userrootitem) self.task_user_tablev.setModel(self.task_user_model) self.cur_task = task def shot_save(self, ): """Save the current shot :returns: None :rtype: None :raises: None """ if not self.cur_shot: return desc = self.shot_desc_pte.toPlainText() start = self.shot_start_sb.value() end = self.shot_end_sb.value() handle = self.shot_handle_sb.value() self.cur_shot.description = desc self.cur_shot.startframe = start self.cur_shot.endframe = end self.cur_shot.handlesize = handle self.cur_shot.save() def asset_view_prj(self, ): """View the project of the current asset :returns: None :rtype: None :raises: None """ if not self.cur_asset: return prj = self.cur_asset.project self.view_prj(prj) def asset_view_atype(self, ): """View the project of the current atype :returns: None :rtype: None :raises: None """ if not self.cur_asset: return atype = self.cur_asset.atype self.view_atype(atype) def atype_view_asset(self, ): """View the project of the current assettype :returns: None :rtype: None :raises: None """ if not self.cur_atype: return i = self.atype_asset_treev.currentIndex() item = i.internalPointer() if item: asset = item.internal_data() if isinstance(asset, djadapter.models.Asset): self.view_asset(asset) def atype_create_asset(self, ): """Create a new asset :returns: None :rtype: None :raises: None """ if not self.cur_atype: return asset = self.create_asset(project=self.cur_prj, atype=self.cur_atype) if not asset: return assetdata = djitemdata.AssetItemData(asset) treemodel.TreeItem(assetdata, self.atype_asset_model.root) def atype_save(self): """Save the current atype :returns: None :rtype: None :raises: None """ if not self.cur_atype: return desc = self.atype_desc_pte.toPlainText() self.cur_atype.description = desc self.cur_atype.save() def asset_view_asset(self, ): """View the task that is currently selected on the asset page :returns: None :rtype: None :raises: None """ if not self.cur_asset: return i = self.asset_asset_treev.currentIndex() item = i.internalPointer() if item: asset = item.internal_data() if isinstance(asset, djadapter.models.Asset): self.view_asset(asset) def asset_add_asset(self, *args, **kwargs): """Add more assets to the asset. :returns: None :rtype: None :raises: None """ if not self.cur_asset: return dialog = AssetAdderDialog(asset=self.cur_asset) dialog.exec_() assets = dialog.assets atypes = {} for c in self.asset_asset_model.root.childItems: atypes[c.internal_data()] = c for asset in assets: atypeitem = atypes.get(asset.atype) if not atypeitem: atypedata = djitemdata.AtypeItemData(asset.atype) atypeitem = treemodel.TreeItem(atypedata, self.asset_asset_model.root) atypes[asset.atype] = atypeitem assetdata = djitemdata.AssetItemData(asset) treemodel.TreeItem(assetdata, atypeitem) self.cur_asset.save() def asset_remove_asset(self, *args, **kwargs): """Remove the, in the asset table view selected, asset. :returns: None :rtype: None :raises: None """ if not self.cur_asset: return i = self.asset_asset_treev.currentIndex() item = i.internalPointer() if item: asset = item.internal_data() if not isinstance(asset, djadapter.models.Asset): return log.debug("Removing asset %s.", asset.name) item.set_parent(None) self.cur_asset.assets.remove(asset) def asset_create_asset(self, *args, **kwargs): """Create a new asset :returns: None :rtype: None :raises: None """ if not self.cur_asset: return asset = self.create_asset(project=self.cur_asset.project, asset=self.cur_asset) if not asset: return atypes = {} for c in self.asset_asset_model.root.childItems: atypes[c.internal_data()] = c atypeitem = atypes.get(asset.atype) if not atypeitem: atypedata = djitemdata.AtypeItemData(asset.atype) atypeitem = treemodel.TreeItem(atypedata, self.asset_asset_model.root) atypes[asset.atype] = atypeitem assetdata = djitemdata.AssetItemData(asset) treemodel.TreeItem(assetdata, atypeitem) def asset_view_task(self, ): """View the task that is currently selected on the asset page :returns: None :rtype: None :raises: None """ if not self.cur_asset: return i = self.asset_task_tablev.currentIndex() item = i.internalPointer() if item: task = item.internal_data() self.view_task(task) def asset_create_task(self, *args, **kwargs): """Create a new task :returns: None :rtype: None :raises: None """ if not self.cur_asset: return task = self.create_task(element=self.cur_asset) if task: taskdata = djitemdata.TaskItemData(task) treemodel.TreeItem(taskdata, self.asset_task_model.root) def asset_save(self): """Save the current asset :returns: None :rtype: None :raises: None """ if not self.cur_asset: return desc = self.asset_desc_pte.toPlainText() self.cur_asset.description = desc self.cur_asset.save() def dep_view_prj(self, ): """View the project that is currently selected :returns: None :rtype: None :raises: None """ if not self.cur_dep: return i = self.dep_prj_tablev.currentIndex() item = i.internalPointer() if item: prj = item.internal_data() self.view_prj(prj) def dep_add_prj(self, *args, **kwargs): """Add projects to the current department :returns: None :rtype: None :raises: None """ if not self.cur_dep: return dialog = ProjectAdderDialog(department=self.cur_dep) dialog.exec_() prjs = dialog.projects for prj in prjs: prjdata = djitemdata.ProjectItemData(prj) treemodel.TreeItem(prjdata, self.dep_prj_model.root) def dep_remove_prj(self, *args, **kwargs): """Remove the selected project from the department :returns: None :rtype: None :raises: None """ if not self.cur_dep: return i = self.dep_prj_tablev.currentIndex() item = i.internalPointer() if item: prj = item.internal_data() self.cur_dep.projects.remove(prj) item.set_parent(None) def dep_save(self, ): """Save the current department :returns: None :rtype: None :raises: None """ if not self.cur_dep: return ordervalue = self.dep_ordervalue_sb.value() desc = self.dep_desc_pte.toPlainText() self.cur_dep.ordervalue = ordervalue self.cur_dep.description = desc self.cur_dep.save() def task_view_user(self, ): """View the user that is currently selected :returns: None :rtype: None :raises: None """ if not self.cur_task: return i = self.task_user_tablev.currentIndex() item = i.internalPointer() if item: user = item.internal_data() self.view_user(user) def task_add_user(self, *args, **kwargs): """Add users to the current task :returns: None :rtype: None :raises: None """ if not self.cur_task: return dialog = UserAdderDialog(task=self.cur_task) dialog.exec_() users = dialog.users for user in users: userdata = djitemdata.UserItemData(user) treemodel.TreeItem(userdata, self.task_user_model.root) def task_remove_user(self, *args, **kwargs): """Remove the selected user from the task :returns: None :rtype: None :raises: None """ if not self.cur_task: return i = self.task_user_tablev.currentIndex() item = i.internalPointer() if item: user = item.internal_data() self.cur_task.users.remove(user) item.set_parent(None) def task_view_dep(self, ): """View the departmetn of the current task :returns: None :rtype: None :raises: None """ if not self.cur_task: return self.view_dep(self.cur_task.department) def task_view_link(self, ): """View the link of the current task :returns: None :rtype: None :raises: None """ if not self.cur_task: return e = self.cur_task.element if isinstance(e, djadapter.models.Asset): self.view_asset(e) else: self.view_shot(e) def task_save(self, ): """Save the current task :returns: None :rtype: None :raises: None """ if not self.cur_task: return deadline = self.task_deadline_de.dateTime().toPython() status = self.task_status_cb.currentText() self.cur_task.deadline = deadline self.cur_task.status = status self.cur_task.save() def users_view_user(self, ): """View the user that is currently selected :returns: None :rtype: None :raises: None """ i = self.users_tablev.currentIndex() item = i.internalPointer() if item: user = item.internal_data() self.view_user(user) def user_view_task(self, ): """View the task that is selected :returns: None :rtype: None :raises: None """ if not self.cur_user: return i = self.user_task_treev.currentIndex() item = i.internalPointer() if item: task = item.internal_data() if isinstance(task, djadapter.models.Task): self.view_task(task) def user_view_prj(self, ): """View the project that is currently selected :returns: None :rtype: None :raises: None """ i = self.user_prj_tablev.currentIndex() item = i.internalPointer() if item: prj = item.internal_data() self.view_prj(prj) def user_add_prj(self, *args, **kwargs): """Add projects to the current user :returns: None :rtype: None :raises: None """ if not self.cur_user: return dialog = ProjectAdderDialog(user=self.cur_user) dialog.exec_() prjs = dialog.projects for prj in prjs: prjdata = djitemdata.ProjectItemData(prj) treemodel.TreeItem(prjdata, self.user_prj_model.root) def user_remove_prj(self, *args, **kwargs): """Remove the selected project from the user :returns: None :rtype: None :raises: None """ if not self.cur_user: return i = self.user_prj_tablev.currentIndex() item = i.internalPointer() if item: prj = item.internal_data() prj.users.remove(self.cur_user) item.set_parent(None) def user_save(self): """Save the current user :returns: None :rtype: None :raises: None """ if not self.cur_user: return username = self.user_username_le.text() first = self.user_first_le.text() last = self.user_last_le.text() email = self.user_email_le.text() self.cur_user.username = username self.cur_user.first_name = first self.cur_user.last_name = last self.cur_user.email = email self.cur_user.save() class GuerillaMGMT(JB_CoreStandaloneGuiPlugin): """A plugin that can run a GuerillaMGMT tool This can be used as a standalone plugin. Before you call run, make sure that there is a running QApplication running. See :mod:`jukeboxcore.gui.main` for helpful functions. """ author = "David Zuber" copyright = "2015" version = "0.1" description = "A guerilla tool for projectmanagement and creating entries in the database." def init(self, ): """Do nothing on init! Call run() if you want to start the configeditor :returns: None :rtype: None :raises: None """ pass def uninit(self, ): """Do nothing on uninit! :returns: None :rtype: None :raises: None """ pass def run(self, parent=None): """Start the configeditor :returns: None :rtype: None :raises: None """ self.gw = GuerillaMGMTWin(parent=parent) self.gw.show()
bsd-3-clause
-4,366,240,837,862,051,000
32.697019
142
0.592131
false
3.71462
false
false
false
tbullmann/heuhaufen
publication/generators_and_depth/aggregate.py
1
5320
import os import pandas import numpy as np from bokeh.palettes import Viridis4 as palette from bokeh.layouts import layout, column, row from bokeh.plotting import figure, output_file, show, ColumnDataSource from bokeh.models import HoverTool, Div, DataTable, TableColumn, NumberFormatter, LinearAxis, Select, CustomJS, Slider, Button import json # must be imported after bokeh def main(test_path='temp/publication/how_deep/test'): labels = ['membranes', 'synapses', 'mitochondria'] # concatenate the evaluation and parameters for all runs dfs = [] for label in labels: for run in range(1,21): df = read_run_from_json_and_csv(test_path, run, label) dfs.append(df) data = pandas.concat(dfs) # save aggregated data (in long format) data.to_csv(os.path.join(test_path, 'summary_long.csv')) # convert long to wide: label x metric --> label_metric metrics = data.columns.to_series().groupby(data.dtypes).groups[np.dtype('float64')] data2 = data.pivot_table(index=['generator', 'layers', 'sample'], columns='label', values=metrics) data2.columns = ['{}_{}'.format(x, y) for x, y in zip(data2.columns.get_level_values(1), data2.columns.get_level_values(0))] data2 = data2.reset_index() # save aggregated data (in wide format) data2.to_csv(os.path.join(test_path, 'summary_wide.csv')) # TODO: interactive plot with bokeh # bokeh_plot(data2, test_path) # not fully functional, e.g. cannot change label and metric def read_run_from_json_and_csv(test_path, run, label): # path to the test result for a particular model base_path = os.path.join(test_path, '%d' % run) # getting parameters from the options json file with open(os.path.join(base_path, "options.json")) as f: options = dict(json.loads(f.read()).items()) generator = options['generator'] # calculate the number of layers depending on generator network and its specific parameters if generator == 'unet': layers = options['u_depth'] * 2 # 1 for down sampling and 1 for up sampling at each level elif generator == 'densenet': layers = options['n_dense_blocks'] * options['n_dense_layers'] + 6 # 3 for each encoder and decoder elif generator == 'resnet': layers = options['n_res_blocks'] * 2 + 6 # 2 for transformation, 3 for each encoder and decoder elif generator == 'highwaynet': layers = options['n_highway_units'] * 2 + 6 # 2 for transformation, 3 for each encoder and decoder # read evaluation results df = pandas.read_csv(os.path.join(base_path, 'evaluation/%s.csv' % label)) # no index_col # add parameters df['generator'] = generator df['layers'] = layers df['label'] = label df['run'] = run return df def bokeh_plot(data, test_path): networks = ['unet', 'resnet', 'highwaynet', 'densenet'] # assuming all float values are metrics metrics = data.columns.to_series().groupby(data.dtypes).groups[np.dtype('float64')] # calculate mean for each data_mean = data.groupby(['generator', 'layers'])[metrics].mean().reset_index() source = dict() source_mean = dict() for network in networks: source[network] = ColumnDataSource(data[data.generator == network]) source_mean[network] = ColumnDataSource(data_mean[data_mean.generator == network]) output_file(os.path.join(test_path, "select.html")) description = Div(text=""" <h1>Evaluation of network type and depth for generator</h1> <p> Interact with the widgets to select metric and evaluated label. </p> """, width=1000) fig = figure(plot_width=1000, plot_height=1000, tools=['box_select', 'reset']) fig.xaxis.axis_label = "layers" fig.yaxis.axis_label = "value of metric" plots = [] for network, column_color in zip(networks, palette): plot = fig.line('layers', metrics[0], legend=dict(value=network), color=column_color, source=source_mean[network]) plot = fig.scatter('layers', metrics[0], legend=dict(value=network), color=column_color, source=source[network]) # legend which can hide/select a specific metric fig.legend.location = "bottom_right" fig.legend.click_policy = "hide" choices = metrics axis = 'y' axis_callback_code = """ plot.glyph.{axis}.field = cb_obj.value axis.attributes.axis_label = cb_obj.value; axis.trigger('change'); source.change.emit(); """ if axis == 'x': fig.xaxis.visible = None position = 'below' initial_choice = 0 else: fig.yaxis.visible = None position = 'left' initial_choice = 1 linear_axis = LinearAxis(axis_label=choices[initial_choice]) fig.add_layout(linear_axis, position) callback1 = CustomJS(args=dict(source=source[network], axis=linear_axis, plot=plot), code=axis_callback_code.format(axis=axis)) ticker = Select(value=choices[initial_choice], options=choices, title=axis + '-axis') ticker.js_on_change('value', callback1) l = layout([ [description], [ticker], [fig] ], sizing_mode='fixed') show(l) if __name__ == "__main__": main() else: main()
mit
2,667,029,470,658,940,000
37
126
0.644361
false
3.658872
true
false
false
Statoil/libres
python/res/enkf/ert_template.py
1
2187
# Copyright (C) 2012 Equinor ASA, Norway. # # The file 'ert_template.py' is part of ERT - Ensemble based Reservoir Tool. # # ERT 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. # # ERT 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 at <http://www.gnu.org/licenses/gpl.html> # for more details. from cwrap import BaseCClass from res import ResPrototype class ErtTemplate(BaseCClass): TYPE_NAME = "ert_template" _free = ResPrototype("void ert_template_free( ert_template )") _get_template_file = ResPrototype("char* ert_template_get_template_file(ert_template)") _get_target_file = ResPrototype("char* ert_template_get_target_file(ert_template)") _get_arg_list = ResPrototype("subst_list_ref ert_template_get_arg_list( ert_template )") def __init__(self): raise NotImplementedError("Class can not be instantiated directly!") def get_template_file(self): """ @rtype: str """ return self._get_template_file() def get_target_file(self): """ @rtype: str """ return self._get_target_file() def get_args_as_string(self): """ @rtype: str """ args_list = self._get_arg_list() return ", ".join(["{}={}".format(key, args_list.get(key)) for key in args_list.keys()]) def __eq__(self, other): return self.get_template_file() == other.get_template_file() and\ self.get_target_file() == other.get_target_file() and\ self.get_args_as_string() == other.get_args_as_string() def __ne__(self, other): return not self == other def __repr__(self): return "ErtTemplate({}, {}, {})".format( self.get_template_file(), self.get_target_file(), self.get_args_as_string()) def free(self): self._free()
gpl-3.0
87,037,044,405,299,280
36.067797
98
0.631459
false
3.521739
false
false
false
oemof/oemof_base
src/oemof/solph/groupings.py
1
2875
# -*- coding: utf-8 -*- """Groupings needed on an energy system for it to work with solph. If you want to use solph on an energy system, you need to create it with these groupings specified like this: .. code-block: python from oemof.network import EnergySystem import solph energy_system = EnergySystem(groupings=solph.GROUPINGS) SPDX-FileCopyrightText: Uwe Krien <krien@uni-bremen.de> SPDX-FileCopyrightText: Simon Hilpert SPDX-FileCopyrightText: Cord Kaldemeyer SPDX-FileCopyrightText: Stephan Günther SPDX-License-Identifier: MIT """ from oemof.network import groupings as groupings from oemof.solph import blocks def constraint_grouping(node, fallback=lambda *xs, **ks: None): """Grouping function for constraints. This function can be passed in a list to :attr:`groupings` of :class:`oemof.solph.network.EnergySystem`. Parameters ---------- node : :class:`Node <oemof.network.Node` The node for which the figure out a constraint group. fallback : callable, optional A function of one argument. If `node` doesn't have a `constraint_group` attribute, this is used to group the node instead. Defaults to not group the node at all. """ # TODO: Refactor this for looser coupling between modules. # This code causes an unwanted tight coupling between the `groupings` and # `network` modules, resulting in having to do an import at runtime in the # init method of solph's `EnergySystem`. A better way would be to add a # method (maybe `constraints`, `constraint_group`, `constraint_type` or # something like that) to solph's node hierarchy, which gets overridden in # each subclass to return the appropriate value. Then we can just call the # method here. # This even gives other users/us the ability to customize/extend how # constraints are grouped by overriding the method in future subclasses. cg = getattr(node, "constraint_group", fallback) return cg() standard_flow_grouping = groupings.FlowsWithNodes(constant_key=blocks.Flow) def _investment_grouping(stf): if hasattr(stf[2], "investment"): if stf[2].investment is not None: return True else: return False investment_flow_grouping = groupings.FlowsWithNodes( constant_key=blocks.InvestmentFlow, # stf: a tuple consisting of (source, target, flow), so stf[2] is the flow. filter=_investment_grouping, ) def _nonconvex_grouping(stf): if hasattr(stf[2], "nonconvex"): if stf[2].nonconvex is not None: return True else: return False nonconvex_flow_grouping = groupings.FlowsWithNodes( constant_key=blocks.NonConvexFlow, filter=_nonconvex_grouping ) GROUPINGS = [ constraint_grouping, investment_flow_grouping, standard_flow_grouping, nonconvex_flow_grouping, ]
gpl-3.0
3,557,383,444,322,008,600
29.252632
79
0.707376
false
3.615094
false
false
false
NIRALUser/RodentThickness
Applications/RodentThickness/Testing/Data/vtkPointAttributes.py
2
3379
import sys # path="/tools/Python/Python-2.7.3/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg:/tools/Python/Python-2.7.3/lib/python2.7/site-packages/pip-1.0-py2.7.egg:/tools/Python/Python-2.7.3/lib/python2.7/site-packages/VTK-6.0-py2.7.egg:/tools/Python/Python-2.7.3/lib/python2.7/site-packages/distribute-0.6.28-py2.7.egg:/tools/Python/Python-2.7.3/lib/python2.7/site-packages/SimpleITK-0.6.0.dev208-py2.7.egg:/tools/Python/Python-2.7.3/lib/python27.zip:/tools/Python/Python-2.7.3/lib/python2.7:/tools/Python/Python-2.7.3/lib/python2.7/plat-linux2:/tools/Python/Python-2.7.3/lib/python2.7/lib-tk:/tools/Python/Python-2.7.3/lib/python2.7/lib-old:/tools/Python/Python-2.7.3/lib/python2.7/lib-dynload:/tools/Python/Python-2.7.3/lib/python2.7/site-packages".split(":") # for p in path: # sys.path.insert(0, p) from vtk import * from optparse import OptionParser import csv,sys import niralvtk as nv import numpy as np def removeAttributes(opts, args): print args inputvtk = args[0] outputvtk = args[1] inVTK = nv.readVTK(inputvtk); nArrays = inVTK.GetPointData().GetNumberOfArrays() arrayNames = [] for k in range(0,nArrays): arrayNames.append(inVTK.GetPointData().GetArrayName(k)) print arrayNames for name in arrayNames: inVTK.GetPointData().RemoveArray(name) nv.writeVTK(outputvtk, inVTK) def main(opts, argv): inputvtk = argv[0] outputvtk = argv[1] inVTK = nv.readVTK(inputvtk); if (opts.sep == "0"): csvreader = csv.reader(open(opts.csvfile, "r")) elif (opts.sep == "1"): csvreader = csv.reader(open(opts.csvfile, "r"), delimiter=',') elif (opts.sep == "2"): csvreader = csv.reader(open(opts.csvfile, "r"), delimiter='\t') first = csvreader.next() if (opts.header): header = first first = csvreader.next() if (opts.names != ""): header = opts.names.split(",") print header nCols = len(first) nPoints = inVTK.GetNumberOfPoints() data = np.zeros([nPoints,nCols]) for k in range(0,nCols): data[0,k] = float(first[k]) print "# points:", nPoints for j in range(1,nPoints): print j first = csvreader.next() for k in range(0,nCols): data[j,k] = float(first[k]) for k in range(0,nCols): arr = vtkDoubleArray() if (len(header) > 0): arr.SetName(header[k]) arr.SetNumberOfTuples(nPoints) for j in range(0,nPoints): arr.SetValue(j,data[j,k]) inVTK.GetPointData().AddArray(arr) nv.writeVTK(outputvtk, inVTK) if (__name__ == "__main__"): parser = OptionParser(usage="usage: %prog [options] input-vtk output-vtk") parser.add_option("-i", "--input", dest="csvfile", help="input attribute csv file", metavar="CSVFILE") parser.add_option("-t", "--title", dest="header", help="use first line as header", action="store_true", default=False); parser.add_option("-n", "--columnNames", dest="names", help="use this as column names", metavar="NAME1,NAME2,...", default=""); parser.add_option("-r", "--removeAttributes", dest="removeAttrs", help="remove all attributes", action="store_true", default=False); parser.add_option("-s", "--separator", dest="sep", help="separator (0=space, 1=comma, 2=tab)", default="0") (opts, args) = parser.parse_args() if (len(args) < 2): parser.print_help() else: if (opts.removeAttrs): removeAttributes(opts, args) else: main(opts, args)
gpl-3.0
4,282,565,386,402,492,400
33.479592
762
0.669725
false
2.837112
false
false
false
imsut/commons
src/python/twitter/pants/targets/jvm_target.py
1
2954
# ================================================================================================== # Copyright 2011 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this work except in compliance with the License. # You may obtain a copy of the License in the LICENSE file, or at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ================================================================================================== import os from twitter.pants.targets.internal import InternalTarget from twitter.pants.targets.jar_dependency import JarDependency from twitter.pants.targets.with_sources import TargetWithSources class JvmTarget(InternalTarget, TargetWithSources): """A base class for all java module targets that provides path and dependency translation.""" def __init__(self, name, sources, dependencies, excludes=None, buildflags=None, is_meta=False, configurations=None): InternalTarget.__init__(self, name, dependencies, is_meta) TargetWithSources.__init__(self, name, is_meta) self.declared_dependencies = set(dependencies or []) self.add_label('jvm') self.sources = self._resolve_paths(self.target_base, sources) or [] for source in self.sources: rel_path = os.path.join(self.target_base, source) TargetWithSources.register_source(rel_path, self) self.excludes = excludes or [] self.buildflags = buildflags or [] custom_antxml = '%s.xml' % self.name buildfile = self.address.buildfile.full_path custom_antxml_path = os.path.join(os.path.dirname(buildfile), custom_antxml) self.custom_antxml_path = custom_antxml_path if os.path.exists(custom_antxml_path) else None self.configurations = configurations def _as_jar_dependency(self): jar_dependency, _, _ = self._get_artifact_info() jar = JarDependency(org = jar_dependency.org, name = jar_dependency.name, rev = None) jar.id = self.id return jar def _as_jar_dependencies(self): yield self._as_jar_dependency() def _get_artifact_info(self): provides = self._provides() exported = bool(provides) org = provides.org if exported else 'internal' module = provides.name if exported else self.id version = provides.rev if exported else None id = "%s-%s" % (provides.org, provides.name) if exported else self.id return JarDependency(org = org, name = module, rev = version), id, exported def _provides(self): return None
apache-2.0
-2,108,860,342,207,043,300
40.027778
100
0.636425
false
4.21398
false
false
false
ver228/tierpsy-tracker
tierpsy/helper/misc/file_processing.py
1
2071
import os import tables from .misc import TABLE_FILTERS RESERVED_EXT = ['_skeletons.hdf5', '_trajectories.hdf5', '_features.hdf5', '_intensities.hdf5', '_feat_manual.hdf5', '_subsample.avi', '.wcon.zip', '_featuresN.hdf5' ] IMG_EXT = ['.png', '.jpeg', '.jpg', '.tif', '.tiff', '.bmp'] def remove_ext(fname): for rext in RESERVED_EXT: if fname.endswith(rext): return fname.replace(rext, '') return os.path.splitext(fname)[0] def get_base_name(fname): return os.path.basename(remove_ext(fname)) def replace_subdir(original_dir, original_subdir, new_subdir): # construct the results dir on base of the mask_dir_root original_dir = os.path.normpath(original_dir) subdir_list = original_dir.split(os.sep) for ii in range(len(subdir_list))[::-1]: if subdir_list[ii] == original_subdir: subdir_list[ii] = new_subdir break # the counter arrived to zero, add new_subdir at the end of the directory if ii == 0: if subdir_list[-1] == '': del subdir_list[-1] subdir_list.append(new_subdir) return (os.sep).join(subdir_list) def save_modified_table(file_name, modified_table, table_name): tab_recarray = modified_table.to_records(index=False) with tables.File(file_name, "r+") as fid: dum_name = table_name + '_d' if '/' + dum_name in fid: fid.remove_node('/', dum_name) newT = fid.create_table( '/', dum_name, obj=tab_recarray, filters=TABLE_FILTERS) oldT = fid.get_node('/' + table_name) old_args = [x for x in dir(oldT._v_attrs) if not x.startswith('_')] for key in old_args: if not key in newT._v_attrs and not key.startswith('FIELD'): newT.attrs[key] = oldT.attrs[key] fid.remove_node('/', table_name) newT.rename(table_name)
mit
-487,200,462,895,574,000
30.861538
77
0.551424
false
3.50423
false
false
false
attia42/twitter_word2vec
kmeans/experimentm.py
1
3559
import csv import nltk from nltk.tokenize import word_tokenize import string from nltk import pos_tag from gensim.models.word2vec import Word2Vec from gensim import matutils from numpy import array, float32 as REAL from sklearn.cluster import MiniBatchKMeans, KMeans from multiprocessing import Pool from collections import Counter #string.punctuation #string.digits file = 'training.1600000.processed.noemoticon2.csv' #file = 'testdata.manual.2009.06.14.csv' tags = ["NNP", "NN", "NNS"] ncls = 1000 niters = 1000 nreplay_kmeans = 1 lower = False redundant = ["aw", "aww", "awww", "awwww", "haha", "lol", "wow", "wtf", "xd", "yay", "http", "www", "com", "ah", "ahh", "ahhh", "amp"] def preprocess(tweet): ret_tweet = "" i = -1 nn = [] raw_tweet = tweet for ch in string.punctuation.replace("'","") + string.digits: tweet = tweet.replace(ch, " ") tweet_pos = {} if lower: tweet = tweet.lower() try: toks = word_tokenize(tweet) pos = pos_tag(toks) nn = [p for p in pos if p[1] in tags] #nn = [p for p in pos if p == 'NNP'] except: pass if(len(nn)): tweet_pos["NN"] = nn ret_tweet = tweet_pos return ret_tweet raw = [] with open(file, 'rb') as csvfile: content = csv.reader(csvfile, delimiter=',', quotechar='"') for row in content: tweet = row[5] raw.append(tweet) p = Pool(6) tweets = p.map(preprocess, raw) t1 = [] t2 = [] for i in range(len(tweets)): if len(tweets[i]): t1.append(raw[i]) t2.append(tweets[i]) raw = t1 tweets = t2 print "Loading model..." wv = Word2Vec.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True) vectors = [] for i in range(len(tweets)): tweet = tweets[i] nns = tweet['NN'] vector = [] #print nns mean = [] no_wv_tweet = True for w in nns: if len(w[0]) > 1 and w[0] in wv and w[0].lower() not in redundant: no_wv_tweet = False #print w[0] weight = 1 if w[1] == 'NNP': weight = 100 mean.append(weight * wv[w[0]]) if(len(mean)): vectors.append(matutils.unitvec(array(mean).mean(axis=0)).astype(REAL)) else: vectors.append([]) t1 = [] t2 = [] t3 = [] for i in range(len(vectors)): if vectors[i] != None and len(vectors[i]): t1.append(raw[i]) t2.append(tweets[i]) t3.append(vectors[i]) raw = t1 tweets = t2 vectors = t3 #kmeans = KMeans(init='k-means++', n_clusters=ncls, n_init=1) kmeans = MiniBatchKMeans(init='k-means++', n_clusters=ncls, n_init=nreplay_kmeans, max_iter=niters) kmeans.fit(vectors) clss = kmeans.predict(vectors) clusters = [[] for i in range(ncls)] for i in range(len(vectors)): cls = clss[i] clusters[cls].append(i) clusterstags = [[] for i in range(ncls)] countarr = [] for c in clusters: counts = Counter() for i in c: t = [x[0] for x in tweets[i]["NN"] ]#if x[1] == "NNP"] #tn = [x[1] for x in tweets[i]["NN"]] sentence = " ".join(t) #+ tn) counts.update(word.strip('.,?!"\'').lower() for word in sentence.split()) countarr.append(counts) output = "" for i in range(ncls): output = "Most common words for this cluster:\n" output += str(countarr[i].most_common(12)) output += "\n\n\n\n\n\n" output += "Word2vec space of related words:\n" wv_rel = wv.most_similar([kmeans.cluster_centers_[i]], topn=10) output += str(wv_rel) output += "\n\n\n\n\n\n" for t in clusters[i]: output += str(raw[t]) + "\n" #output += "\n\n\n" nm = [x[0] for x in countarr[i].most_common(5)] nm = str(" ".join(nm)) for ch in string.punctuation: nm = nm.replace(ch, " ") f = open('clusters/' + nm +'.txt', 'wb') f.write(output) f.close()
mit
-3,103,478,720,361,940,000
18.662983
134
0.629952
false
2.527699
false
false
false
fga-gpp-mds/2017.2-Receituario-Medico
medical_prescription/exam/test/test_view_list_custom_exam.py
1
2151
# Django imports from django.test import TestCase from django.test.client import RequestFactory from django.contrib.auth.models import AnonymousUser from django.core.exceptions import PermissionDenied # Local Django imports from exam.views import ListCustomExams from user.models import User, Patient, HealthProfessional class ListExamsTest(TestCase): def setUp(self): self.factory = RequestFactory() self.health_professional = HealthProfessional.objects.create_user(email='doctor@doctor.com', password='senha12') self.patient = Patient.objects.create_user(email='patient@patient.com', password='senha12', CEP='72850735', UF='DF', city='Brasília', neighborhood='Asa sul', complement='Bloco 2 QD 701') self.user = User.objects.create_user(email='user@user.com', password='senha12') def teste_exam_get_exam_without_login(self): request = self.factory.get('/exam/list_custom_exams/') request.user = AnonymousUser() response = ListCustomExams.as_view()(request) self.assertEqual(response.status_code, 302) def teste_exam_get_exam_with_patient(self): request = self.factory.get('/exam/list_custom_exams/') request.user = self.patient with self.assertRaises(PermissionDenied): ListCustomExams.as_view()(request) def teste_exam_get_exam_with_user(self): request = self.factory.get('/exam/list_custom_exams/') request.user = self.user with self.assertRaises(PermissionDenied): ListCustomExams.as_view()(request) def teste_exam_get_exam_with_health_professional(self): request = self.factory.get('/exam/list_custom_exams/') request.user = self.health_professional response = ListCustomExams.as_view()(request) self.assertEqual(response.status_code, 200)
mit
-498,659,966,404,250,100
41.156863
120
0.605581
false
4.232283
true
false
false
mxcube/mxcube
mxcubeqt/widgets/optimisation_parameters_widget_layout.py
1
2158
# # Project: MXCuBE # https://github.com/mxcube # # This file is part of MXCuBE software. # # MXCuBE is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # MXCuBE 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with MXCuBE. If not, see <http://www.gnu.org/licenses/>. from mxcubeqt.utils import qt_import __credits__ = ["MXCuBE collaboration"] __license__ = "LGPLv3+" class OptimisationParametersWidgetLayout(qt_import.QWidget): """ Widget is used to define characterisation optimization parameters like maximum resolution, aimed multiplicity, and etc. """ def __init__(self, parent=None, name=None, window_flags=0): qt_import.QWidget.__init__(self, parent, qt_import.Qt.WindowFlags(window_flags)) if not name: self.setObjectName("OptimisationParametersWidgetLayout") # Hardware objects ---------------------------------------------------- # Internal variables -------------------------------------------------- # Graphic elements ---------------------------------------------------- self.opt_param_widget = qt_import.load_ui_file( "optimization_parameters_widget_layout.ui" ) # Layout -------------------------------------------------------------- _main_vlayout = qt_import.QVBoxLayout(self) _main_vlayout.addWidget(self.opt_param_widget) _main_vlayout.setSpacing(0) _main_vlayout.setContentsMargins(0, 0, 0, 0) # Size policies ------------------------------------------------------- # Other --------------------------------------------------------------- self.setAttribute(qt_import.Qt.WA_WState_Polished)
lgpl-3.0
7,412,875,325,961,287,000
36.859649
88
0.579703
false
4.231373
false
false
false
PowerHMC/HmcRestClient
src/managed_system/PowerOnManagedSystem.py
1
2162
# Copyright 2015, 2016 IBM Corp. # # 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. from src.utility import HTTPClient,HmcHeaders,HMCClientLogger import xml.etree.ElementTree as etree import os log = HMCClientLogger.HMCClientLogger(__name__) from src.common.JobStatus import * ROOT = 'ManagedSystem' CONTENT_TYPE ='application/vnd.ibm.powervm.web+xml; type=JobRequest' class PowerOnManagedSystem(JobStatus): """ Power On the Selected ManagedSystem if its not in operating state else shows error """ def __init__(self): """ initializes root and content-type """ self.content_type = CONTENT_TYPE self.root = ROOT def poweron_ManagedSystem(self, ip, managedsystem_uuid, x_api_session): """ Args: ip:ip address of hmc managedsystem_uuid:UUID of managedsystem x_api_session:session to be used """ super().__init__(ip, self.root, self.content_type, x_api_session) log.log_debug("power on managed system started") headers_object=HmcHeaders.HmcHeaders("web") namespace=headers_object.ns["xmlns"] directory = os.path.dirname(__file__) inputpayload=open(directory+"\data\poweron_managedsystem.xml","r") request_object=HTTPClient.HTTPClient('uom',ip,self.root,self.content_type,session_id=x_api_session) request_object.HTTPPut(payload=inputpayload,append=str(managedsystem_uuid)+"/do/PowerOn") log.log_debug(request_object.response) if request_object.response_b: self.get_job_status(request_object)
apache-2.0
6,232,945,339,774,236,000
37.607143
107
0.682701
false
3.813051
false
false
false
Nablaquabla/sns-analysis
ba-missing-files.py
1
5827
import os import time as tm import sys # Handles the creation of condor files for a given set of directories # ----------------------------------------------------------------------------- def createCondorFile(dataDir,outDir,run,day,time): # Condor submission file name convention: run-day-time.condor with open('/home/bjs66/CondorFiles/%s-%s-%s.condor'%(run,day,time),'w') as f: # Fixed program location' f.write('Executable = /home/bjs66/GitHub/sns-analysis/sns-analysis-v3\n') # Arguments passed to the exe: # Set main run directory, e.g. Run-15-10-02-27-32-23/151002 # Set current time to be analzyed (w/o .zip extension!), e.g. 184502 # Set output directory, eg Output/ Run-15-10-02-27-32-23/151002 f.write('Arguments = \"3 %s %s %s 1\"\n'%(dataDir,time,outDir)) # Standard cluster universe f.write('universe = vanilla\n') f.write('getenv = true\n') # Program needs at least 250 MB of free memory to hold unzipped data f.write('request_memory = 300\n') # Output, error and log name convention: run-day-time.log/out/err f.write('log = ../../Logs/%s-%s-%s.log\n'%(run,day,time)) f.write('Output = ../../Outs/%s-%s-%s.out\n'%(run,day,time)) f.write('Error = ../../Errs/%s-%ss-%s.err\n'%(run,day,time)) # Do not write any emails f.write('notification = never\n') f.write('+Department = Physics\n') f.write('should_transfer_files = NO\n') # Add single job to queue f.write('Queue') # Main function handling all internals # ----------------------------------------------------------------------------- def main(runMissing): # Choose main directory, i.e. ~/csi/beam_on_data/Run-15-06-25-xyz/ mainRunDir = '/var/phy/project/phil/grayson/COHERENT/CsI/' # Choose output directory, i.e. ~/output/Run-15-06-25-xyz/ mainOutDir = '/var/phy/project/phil/grayson/COHERENT/CsI/bjs-analysis/' # Choose run to analyze # runDirs = ['Run-15-03-27-12-42-26'] # run = 'Run-15-03-30-13-33-05' # run = 'Run-15-04-08-11-38-28' # run = 'Run-15-04-17-16-56-59' # run = 'Run-15-04-29-16-34-44' # runDirs = ['Run-15-05-05-16-09-12'] # run = 'Run-15-05-11-11-46-30' # run = 'Run-15-05-19-17-04-44' # run = 'Run-15-05-27-11-13-46' # runDirs = ['Run-15-05-05-16-09-12','Run-15-05-11-11-46-30','Run-15-05-19-17-04-44','Run-15-05-27-11-13-46'] runDirs = ['Run-15-03-27-12-42-26','Run-15-03-30-13-33-05','Run-15-04-08-11-38-28','Run-15-04-17-16-56-59','Run-15-04-29-16-34-44', 'Run-15-05-05-16-09-12','Run-15-05-11-11-46-30','Run-15-05-19-17-04-44','Run-15-05-27-11-13-46'] subdirs = {} days_in = {'Run-15-03-27-12-42-26': ['150327','150328','150329','150330'], 'Run-15-03-30-13-33-05': ['150330','150331','150401','150402','150403','150404','150405','150406','150407','150408'], 'Run-15-04-08-11-38-28': ['150408','150409','150410','150411','150412','150413','150414','150415','150416'], 'Run-15-04-17-16-56-59': ['150417','150418','150419','150420','150421','150422','150423','150424','150425','150426','150427','150428','150429'], 'Run-15-04-29-16-34-44': ['150429','150430','150501','150502','150503','150504','150505'], 'Run-15-05-05-16-09-12': ['150505','150506','150507','150508','150509','150510','150511'], 'Run-15-05-11-11-46-30': ['150512','150513','150514','150515','150516','150517','150518','150519'], 'Run-15-05-19-17-04-44': ['150519','150520','150521','150522','150523','150524','150525','150526','150527'], 'Run-15-05-27-11-13-46': ['150527','150528','150529','150530','150531','150601','150602','150603','150604','150605','150606','150607','150608','150609']} for run in runDirs: for day in days_in[run]: subdirs[run] = 'brillance_data' print run,day # Prepare paths for further processing dataRunDir = mainRunDir + '%s/%s/%s'%(subdirs[run],run,day) outDir = mainOutDir + '%s/%s'%(run,day) # Get all times within the day folder chosen inputList = [x.split('.')[0] for x in os.listdir(dataRunDir)] # Get all times within the day folder chosen outputList_B = [x.split('-')[1] for x in os.listdir(outDir) if 'B-' in x] outputList_S = [x.split('-')[1] for x in os.listdir(outDir) if 'S-' in x] outputList_I = [x.split('-')[1] for x in os.listdir(outDir) if 'I-' in x] # Check if there is a file missing in the day folder if len(inputList) != len(outputList_B) or len(inputList) != len(outputList_S) or len(inputList) != len(outputList_I): missingB = set(inputList) - set(outputList_B) missingI = set(inputList) - set(outputList_I) missingS = set(inputList) - set(outputList_S) missing = list((missingB | missingI) | missingS) if len(missing) > 0: print len(missing) if runMissing == '1': for m in missing: createCondorFile(dataRunDir,outDir,run,day,m) cmd = 'condor_submit /home/bjs66/CondorFiles/%s-%s-%s.condor'%(run,day,m) os.system(cmd) if __name__ == '__main__': main(sys.argv[1])
gpl-3.0
-2,322,044,558,256,752,000
42.485075
168
0.519478
false
3.00826
false
false
false
iotaledger/iota.lib.py
iota/transaction/validator.py
1
9563
from typing import Generator, List, Optional, Type from iota.crypto.kerl import Kerl from iota.crypto.signing import validate_signature_fragments from iota.transaction.base import Bundle, Transaction __all__ = [ 'BundleValidator', ] # In very rare cases, the IOTA protocol may switch hash algorithms. # When this happens, the IOTA Foundation will create a snapshot, so # that all new objects on the Tangle use the new hash algorithm. # # However, the snapshot will still contain references to addresses # created using the legacy hash algorithm, so the bundle validator has # to be able to use that as a fallback when validation fails. SUPPORTED_SPONGE = Kerl LEGACY_SPONGE = None # Curl class BundleValidator(object): """ Checks a bundle and its transactions for problems. """ def __init__(self, bundle: Bundle) -> None: super(BundleValidator, self).__init__() self.bundle = bundle self._errors: Optional[List[str]] = [] self._validator = self._create_validator() @property def errors(self) -> List[str]: """ Returns all errors found with the bundle. """ try: self._errors.extend(self._validator) # type: List[str] except StopIteration: pass return self._errors def is_valid(self) -> bool: """ Returns whether the bundle is valid. """ if not self._errors: try: # We only have to check for a single error to determine # if the bundle is valid or not. self._errors.append(next(self._validator)) except StopIteration: pass return not self._errors def _create_validator(self) -> Generator[str, None, None]: """ Creates a generator that does all the work. """ # Group transactions by address to make it easier to iterate # over inputs. grouped_transactions = self.bundle.group_transactions() # Define a few expected values. bundle_hash = self.bundle.hash last_index = len(self.bundle) - 1 # Track a few others as we go along. balance = 0 # Check indices and balance first. # Note that we use a counter to keep track of the current index, # since at this point we can't trust that the transactions have # correct ``current_index`` values. counter = 0 for group in grouped_transactions: for txn in group: balance += txn.value if txn.bundle_hash != bundle_hash: yield 'Transaction {i} has invalid bundle hash.'.format( i=counter, ) if txn.current_index != counter: yield ( 'Transaction {i} has invalid current index value ' '(expected {i}, actual {actual}).'.format( actual=txn.current_index, i=counter, ) ) if txn.last_index != last_index: yield ( 'Transaction {i} has invalid last index value ' '(expected {expected}, actual {actual}).'.format( actual=txn.last_index, expected=last_index, i=counter, ) ) counter += 1 # Bundle must be balanced (spends must match inputs). if balance != 0: yield ( 'Bundle has invalid balance ' '(expected 0, actual {actual}).'.format( actual=balance, ) ) # Signature validation is only meaningful if the transactions # are otherwise valid. if not self._errors: signature_validation_queue: List[List[Transaction]] = [] for group in grouped_transactions: # Signature validation only applies to inputs. if group[0].value >= 0: continue validate_group_signature = True for j, txn in enumerate(group): if (j > 0) and (txn.value != 0): # Input is malformed; signature fragments after # the first should have zero value. yield ( 'Transaction {i} has invalid value ' '(expected 0, actual {actual}).'.format( actual=txn.value, # If we get to this point, we know that # the ``current_index`` value for each # transaction can be trusted. i=txn.current_index, ) ) # We won't be able to validate the signature, # but continue anyway, so that we can check that # the other transactions in the group have the # correct ``value``. validate_group_signature = False continue # After collecting the signature fragment from each # transaction in the group, queue them up to run through # the validator. # # We have to perform signature validation separately so # that we can try different algorithms (for # backwards-compatibility). # # References: # # - https://github.com/iotaledger/kerl#kerl-integration-in-iota if validate_group_signature: signature_validation_queue.append(group) # Once we've finished checking the attributes from each # transaction in the bundle, go back and validate # signatures. if signature_validation_queue: # ``yield from`` is an option here, but for # compatibility with Python 2 clients, we will do it the # old-fashioned way. for error in self._get_bundle_signature_errors( signature_validation_queue ): yield error def _get_bundle_signature_errors( self, groups: List[List[Transaction]] ) -> List[str]: """ Validates the signature fragments in the bundle. :return: List of error messages. If empty, signature fragments are valid. """ # Start with the currently-supported hash algo. current_pos = None current_errors = [] for current_pos, group in enumerate(groups): error = self._get_group_signature_error(group, SUPPORTED_SPONGE) if error: current_errors.append(error) # Pause and retry with the legacy algo. break # If validation failed, then go back and try with the legacy # algo (only applies if we are currently transitioning to a new # algo). if current_errors and LEGACY_SPONGE: for group in groups: if self._get_group_signature_error(group, LEGACY_SPONGE): # Legacy algo doesn't work, either; no point in # continuing. break else: # If we get here, then we were able to validate the # signature fragments successfully using the legacy # algorithm. return [] # If we get here, then validation also failed when using the # legacy algorithm. # At this point, we know that the bundle is invalid, but we will # continue validating with the supported algorithm anyway, so # that we can return an error message for every invalid input. current_errors.extend(filter(None, ( self._get_group_signature_error(group, SUPPORTED_SPONGE) for group in groups[current_pos + 1:] ))) return current_errors @staticmethod def _get_group_signature_error( group: List[Transaction], sponge_type: Type ) -> Optional[str]: """ Validates the signature fragments for a group of transactions using the specified sponge type. Note: this method assumes that the transactions in the group have already passed basic validation (see :py:meth:`_create_validator`). :return: - ``None``: Indicates that the signature fragments are valid. - ``str``: Error message indicating the fragments are invalid. """ validate_group_signature = validate_signature_fragments( fragments=[txn.signature_message_fragment for txn in group], hash_=group[0].bundle_hash, public_key=group[0].address, sponge_type=sponge_type, ) if validate_group_signature: return None return ( 'Transaction {i} has invalid signature ' '(using {fragments} fragments).'.format( fragments=len(group), i=group[0].current_index, ) )
mit
-1,442,031,086,814,618,400
35.361217
79
0.527136
false
5.146932
false
false
false
nilbody/h2o-3
h2o-py/tests/testdir_golden/pyunit_svd_1_golden.py
1
2402
from __future__ import print_function from builtins import zip import sys sys.path.insert(1,"../../") import h2o from tests import pyunit_utils def svd_1_golden(): print("Importing USArrests.csv data...") arrestsH2O = h2o.upload_file(pyunit_utils.locate("smalldata/pca_test/USArrests.csv")) print("Compare with SVD") fitH2O = h2o.svd(x=arrestsH2O[0:4], nv=4, transform="NONE", max_iterations=2000) print("Compare singular values (D)") h2o_d = fitH2O._model_json['output']['d'] r_d = [1419.06139509772, 194.825846110138, 45.6613376308754, 18.0695566224677] print("R Singular Values: {0}".format(r_d)) print("H2O Singular Values: {0}".format(h2o_d)) for r, h in zip(r_d, h2o_d): assert abs(r - h) < 1e-6, "H2O got {0}, but R got {1}".format(h, r) print("Compare right singular vectors (V)") h2o_v = h2o.as_list(h2o.get_frame(fitH2O._model_json['output']['v_key']['name']), use_pandas=False) h2o_v.pop(0) r_v = [[-0.04239181, 0.01616262, -0.06588426, 0.99679535], [-0.94395706, 0.32068580, 0.06655170, -0.04094568], [-0.30842767, -0.93845891, 0.15496743, 0.01234261], [-0.10963744, -0.12725666, -0.98347101, -0.06760284]] print("R Right Singular Vectors: {0}".format(r_v)) print("H2O Right Singular Vectors: {0}".format(h2o_v)) for rl, hl in zip(r_v, h2o_v): for r, h in zip(rl, hl): assert abs(abs(r) - abs(float(h))) < 1e-5, "H2O got {0}, but R got {1}".format(h, r) print("Compare left singular vectors (U)") h2o_u = h2o.as_list(h2o.get_frame(fitH2O._model_json['output']['u_key']['name']), use_pandas=False) h2o_u.pop(0) r_u = [[-0.1716251, 0.096325710, 0.06515480, 0.15369551], [-0.1891166, 0.173452566, -0.42665785, -0.17801438], [-0.2155930, 0.078998111, 0.02063740, -0.28070784], [-0.1390244, 0.059889811, 0.01392269, 0.01610418], [-0.2067788, -0.009812026, -0.17633244, -0.21867425], [-0.1558794, -0.064555293, -0.28288280, -0.11797419]] print("R Left Singular Vectors: {0}".format(r_u)) print("H2O Left Singular Vectors: {0}".format(h2o_u)) for rl, hl in zip(r_u, h2o_u): for r, h in zip(rl, hl): assert abs(abs(r) - abs(float(h))) < 1e-5, "H2O got {0}, but R got {1}".format(h, r) if __name__ == "__main__": pyunit_utils.standalone_test(svd_1_golden) else: svd_1_golden()
apache-2.0
-2,250,794,566,595,891,700
39.711864
117
0.61199
false
2.404404
false
false
false
sophacles/invoke
tests/runner.py
1
8258
import sys import os from spec import eq_, skip, Spec, raises, ok_, trap from invoke.runner import Runner, run from invoke.exceptions import Failure from _utils import support, reset_cwd def _run(returns=None, **kwargs): """ Create a Runner w/ retval reflecting ``returns`` & call ``run(**kwargs)``. """ # Set up return value tuple for Runner.run returns = returns or {} returns.setdefault('exited', 0) value = map( lambda x: returns.get(x, None), ('stdout', 'stderr', 'exited', 'exception'), ) class MockRunner(Runner): def run(self, command, warn, hide): return value # Ensure top level run() uses that runner, provide dummy command. kwargs['runner'] = MockRunner return run("whatever", **kwargs) class Run(Spec): "run()" def setup(self): os.chdir(support) self.both = "echo foo && ./err bar" self.out = "echo foo" self.err = "./err bar" self.sub = "inv -c pty_output hide_%s" def teardown(self): reset_cwd() class return_value: def return_code_in_result(self): """ Result has .return_code (and .exited) containing exit code int """ r = run(self.out, hide='both') eq_(r.return_code, 0) eq_(r.exited, 0) def nonzero_return_code_for_failures(self): result = run("false", warn=True) eq_(result.exited, 1) result = run("goobypls", warn=True, hide='both') eq_(result.exited, 127) def stdout_attribute_contains_stdout(self): eq_(run(self.out, hide='both').stdout, 'foo\n') def stderr_attribute_contains_stderr(self): eq_(run(self.err, hide='both').stderr, 'bar\n') def ok_attr_indicates_success(self): eq_(_run().ok, True) eq_(_run(returns={'exited': 1}, warn=True).ok, False) def failed_attr_indicates_failure(self): eq_(_run().failed, False) eq_(_run(returns={'exited': 1}, warn=True).failed, True) def has_exception_attr(self): eq_(_run().exception, None) class failure_handling: @raises(Failure) def fast_failures(self): run("false") def run_acts_as_success_boolean(self): ok_(not run("false", warn=True)) ok_(run("true")) def non_one_return_codes_still_act_as_False(self): ok_(not run("goobypls", warn=True, hide='both')) def warn_kwarg_allows_continuing_past_failures(self): eq_(run("false", warn=True).exited, 1) def Failure_repr_includes_stderr(self): try: run("./err ohnoz && exit 1", hide='both') assert false # Ensure failure to Failure fails except Failure as f: r = repr(f) assert 'ohnoz' in r, "Sentinel 'ohnoz' not found in %r" % r class output_controls: @trap def _hide_both(self, val): run(self.both, hide=val) eq_(sys.stdall.getvalue(), "") def hide_both_hides_everything(self): self._hide_both('both') def hide_True_hides_everything(self): self._hide_both(True) @trap def hide_out_only_hides_stdout(self): run(self.both, hide='out') eq_(sys.stdout.getvalue().strip(), "") eq_(sys.stderr.getvalue().strip(), "bar") @trap def hide_err_only_hides_stderr(self): run(self.both, hide='err') eq_(sys.stdout.getvalue().strip(), "foo") eq_(sys.stderr.getvalue().strip(), "") @trap def hide_accepts_stderr_alias_for_err(self): run(self.both, hide='stderr') eq_(sys.stdout.getvalue().strip(), "foo") eq_(sys.stderr.getvalue().strip(), "") @trap def hide_accepts_stdout_alias_for_out(self): run(self.both, hide='stdout') eq_(sys.stdout.getvalue().strip(), "") eq_(sys.stderr.getvalue().strip(), "bar") def hide_both_hides_both_under_pty(self): r = run(self.sub % 'both', hide='both') eq_(r.stdout, "") eq_(r.stderr, "") def hide_out_hides_both_under_pty(self): r = run(self.sub % 'out', hide='both') eq_(r.stdout, "") eq_(r.stderr, "") def hide_err_has_no_effect_under_pty(self): r = run(self.sub % 'err', hide='both') eq_(r.stdout, "foo\r\nbar\r\n") eq_(r.stderr, "") @trap def _no_hiding(self, val): r = run(self.both, hide=val) eq_(sys.stdout.getvalue().strip(), "foo") eq_(sys.stderr.getvalue().strip(), "bar") def hide_None_hides_nothing(self): self._no_hiding(None) def hide_False_hides_nothing(self): self._no_hiding(False) @raises(ValueError) def hide_unknown_vals_raises_ValueError(self): run("command", hide="what") def hide_unknown_vals_mention_value_given_in_error(self): value = "penguinmints" try: run("command", hide=value) except ValueError as e: msg = "Error from run(hide=xxx) did not tell user what the bad value was!" msg += "\nException msg: %s" % e ok_(value in str(e), msg) else: assert False, "run() did not raise ValueError for bad hide= value" def hide_does_not_affect_capturing(self): eq_(run(self.out, hide='both').stdout, 'foo\n') class pseudo_terminals: def return_value_indicates_whether_pty_was_used(self): eq_(run("true").pty, False) eq_(run("true", pty=True).pty, True) def pty_defaults_to_off(self): eq_(run("true").pty, False) def complex_nesting_doesnt_break(self): # GH issue 191 substr = " hello\t\t\nworld with spaces" cmd = """ eval 'echo "{0}" ' """.format(substr) # TODO: consider just mocking os.execv here (and in the other # tests) though that feels like too much of a tautology / testing # pexpect expected = ' hello\t\t\r\nworld with spaces\r\n' eq_(run(cmd, pty=True, hide='both').stdout, expected) class command_echo: @trap def does_not_echo_commands_run_by_default(self): run("echo hi") eq_(sys.stdout.getvalue().strip(), "hi") @trap def when_echo_True_commands_echoed_in_bold(self): run("echo hi", echo=True) expected = "\033[1;37mecho hi\033[0m\nhi" eq_(sys.stdout.getvalue().strip(), expected) # # Random edge/corner case junk # def non_stupid_OSErrors_get_captured(self): # Somehow trigger an OSError saying "Input/output error" within # pexpect.spawn().interact() & assert it is in result.exception skip() def KeyboardInterrupt_on_stdin_doesnt_flake(self): # E.g. inv test => Ctrl-C halfway => shouldn't get buffer API errors skip() class funky_characters_in_stdout: def basic_nonstandard_characters(self): # Crummy "doesn't explode with decode errors" test run("cat tree.out", hide='both') def nonprinting_bytes(self): # Seriously non-printing characters (i.e. non UTF8) also don't asplode # load('funky').derp() run("echo '\xff'", hide='both') def nonprinting_bytes_pty(self): # PTY use adds another utf-8 decode spot which can also fail. run("echo '\xff'", pty=True, hide='both') class Local_(Spec): def setup(self): os.chdir(support) self.both = "echo foo && ./err bar" def teardown(self): reset_cwd() def stdout_contains_both_streams_under_pty(self): r = run(self.both, hide='both', pty=True) eq_(r.stdout, 'foo\r\nbar\r\n') def stderr_is_empty_under_pty(self): r = run(self.both, hide='both', pty=True) eq_(r.stderr, '')
bsd-2-clause
-1,536,870,026,090,481,400
31.640316
90
0.541899
false
3.666963
false
false
false
coreymcdermott/artbot
artbot_scraper/spiders/arthouse_spider.py
1
2106
# -*- coding: utf-8 -*- import re from scrapy import Spider, Request from dateutil import parser from artbot_scraper.items import EventItem from pytz import timezone class ArthouseSpider(Spider): name = 'Arthouse Gallery' allowed_domains = ['www.arthousegallery.com.au'] start_urls = ['http://www.arthousegallery.com.au/exhibitions/'] def parse(self, response): for href in response.xpath('//div[contains(@id, "index")]//li//a/@href'): url = response.urljoin(href.extract()) yield Request(url, callback=self.parse_exhibition) def parse_exhibition(self, response): item = EventItem() item['url'] = response.url item['venue'] = self.name item['title'] = response.xpath('//div[contains(@id, "headerTitle")]//text()').extract_first().strip() \ + ' - ' \ + response.xpath('//div[contains(@id, "headerSubTitle")]//em/text()').extract_first().strip() item['description'] = ''.join(response.xpath('//div[contains(@id, "exhibition")]//hr/following-sibling::p//text()').extract()).strip() item['image'] = response.urljoin(response.xpath('//img//@src').extract_first()) season = ''.join(response.xpath('//div[contains(@id, "headerSubTitle")]//text()[not(ancestor::em)]').extract()).strip() match = re.match(u'(?P<start>^[\d\w\s]+)[\s\-\–]*(?P<end>[\d\w\s]+$)', season) if (match): tz = timezone('Australia/Sydney') start = tz.localize(parser.parse(match.group('start'), fuzzy = True)) end = tz.localize(parser.parse(match.group('end'), fuzzy = True)) if (re.match(u'^\d+$', match.group('start'))): start = start.replace(month=end.month, year=end.year) if (re.match(u'^\d+\s+\w+$', match.group('start'))): start = start.replace(year=end.year) item['start'] = start item['end'] = end yield item
mit
2,145,790,434,256,513,000
43.765957
142
0.545627
false
3.665505
false
false
false
mmb90/dftintegrate
dftintegrate/fourier/readdata.py
1
5536
""" Classes:: ReadData -- A collection of functions to collect extracted VASP/QE data into a json file. """ import json from copy import deepcopy from ast import literal_eval from collections import defaultdict class ReadData(object): """ A collection of functions to collect extracted VASP/QE data into a json file. Variables:: name -- A string containing the name to the extracted data. kmax -- A number that determines how many terms can be used in the fourier representation based on the density of the sample points. kgrid -- A list of lists. Each inner list is a triplet that represents a k-point. The outer list is the collection of the triplets or k-points and therefore represents the k-kgrid. Note these are the irreducible k-points. weights -- A list of floats. Since kgrid represents the irreducible wedge, each k-point has a weight that represents in a way how degenerate it is. These are in the same order as their corresponding k-points in kgrid. eigenvals -- A dictionary. At each k-point there is an eigenvalue (energy) for each band that was calculated. The keys are the band numbers and the values are a list of energies for that band at each k-point. symops -- A triple nested list. The outer list is a collection of matrices that represent the symmetry operators for the system calculated. The inner double nested lists are representations of the matrices. trans -- A list of lists. Each symmetry operator has a translation vector associated with it. We aren't sure what they are for but we have them so we can implement them if we figure it out. Functions:: _read_lines -- Read a file yielding one line at a time. Generator. read_kpts_eigenvals -- Read kpts_eigenvals.dat in as a list of k-points and a dictionary. read_symops_trans -- Read symops_trans.dat in as two lists. read_kmax -- Read kmax from kmax.dat in. For example one might run a calulation with a grid of 4 4 4, in this case k is 4. This is needed in the Fourier basis fit to ensure the highest frequency term doesn't exceed the Nyquist frequency. This means that the highest frequency can't exeed k/2, so if k is 4 then the highest frequency can't exeed 2. Since we are in 3D we have to consider sqrt(x^2+x^2+x^2) < k/2, thus x = kmax = ceil(k/(2sqrt(3)). serialize -- Serialize the data to a json file. """ def __init__(self, name_of_data_directory): """ Arguments:: name_of_data_directory -- A string containing the name to the VASP data. """ self.name = name_of_data_directory self.read_kpts_eigenvals() self.read_symops_trans() self.read_kmax() self.serialize() def _read_lines(self, path_to_file): """ Read file, yield line by line. Arguments:: path_to_file -- String containing the path to the file. """ with open(path_to_file) as inf: for line in inf: yield [literal_eval(x) for x in line.strip().split()] def read_kpts_eigenvals(self): """ Read in kpts_eigenvals.dat with _read_lines. Stores the k-pionts in kgrid, the weights in weights, and the band energy (eigenvalues) in eigenvals. See this class's (ReadData) docstring for more details on kgrid, weights, and eigenvals. """ name = self.name kgrid = [] weights = [] eigenvals = defaultdict(list) for line in self._read_lines(name + '/kpts_eigenvals.dat'): if len(line) == 4: kgrid.append(line[:3]) weights.append(line[-1]) elif len(line) == 2: eigenvals[line[0]].append(line[1]) self.kgrid = kgrid self.weights = weights self.eigenvals = eigenvals def read_symops_trans(self): """ Read in symops_trans.dat with _read_lines. Stores the symmetry operators in symops and the translations in trans. See this class's (ReadData) docstring for more details on symops and trans. """ name = self.name symops = [] symop = [] trans = [] lines = self._read_lines(name + '/symops_trans.dat') for line in lines: symop.append(line) symop.append(next(lines)) symop.append(next(lines)) next(lines) tran = next(lines) next(lines) symops.append(deepcopy(symop)) trans.append(tran) symop.clear() self.symops = symops self.trans = trans def read_kmax(self): """ Read in kmax.dat using _read_lines. Only the first line will be read. It will be assigned to self.kmax. """ name = self.name lines = self._read_lines(name + '/kmax.dat') self.kmax = next(lines)[0] def serialize(self): data_dict = {'kmax': self.kmax, 'kgrid': self.kgrid, 'weights': self.weights, 'eigenvals': self.eigenvals, 'symops': self.symops, 'trans': self.trans} with open(self.name + '/data.json', mode='w', encoding='utf-8') as outf: json.dump(data_dict, outf, indent=2)
mit
-6,101,243,481,345,637,000
34.716129
74
0.601156
false
4.052709
false
false
false
nkmk/python-snippets
notebook/pypdf2_metadata_remove.py
1
4178
import PyPDF2 src_pdf = PyPDF2.PdfFileReader('data/src/pdf/sample1.pdf') dst_pdf = PyPDF2.PdfFileWriter() dst_pdf.cloneReaderDocumentRoot(src_pdf) with open('data/temp/sample1_no_meta.pdf', 'wb') as f: dst_pdf.write(f) print(PyPDF2.PdfFileReader('data/temp/sample1_no_meta.pdf').documentInfo) # {'/Producer': 'PyPDF2'} dst_pdf.addMetadata({'/Producer': ''}) with open('data/temp/sample1_no_meta.pdf', 'wb') as f: dst_pdf.write(f) print(PyPDF2.PdfFileReader('data/temp/sample1_no_meta.pdf').documentInfo) # {'/Producer': ''} def remove_all_metadata(src_path, dst_path, producer=''): src_pdf = PyPDF2.PdfFileReader(src_path) dst_pdf = PyPDF2.PdfFileWriter() dst_pdf.cloneReaderDocumentRoot(src_pdf) dst_pdf.addMetadata({'/Producer': producer}) with open(dst_path, 'wb') as f: dst_pdf.write(f) remove_all_metadata('data/src/pdf/sample1.pdf', 'data/temp/sample1_no_meta.pdf') print(PyPDF2.PdfFileReader('data/temp/sample1_no_meta.pdf').documentInfo) # {'/Producer': ''} src_pdf = PyPDF2.PdfFileReader('data/src/pdf/sample1.pdf') dst_pdf = PyPDF2.PdfFileWriter() d = {key: src_pdf.documentInfo[key] for key in src_pdf.documentInfo.keys()} print(d) # {'/Title': 'sample1', '/Producer': 'macOS バージョン10.14.2(ビルド18C54) Quartz PDFContext', '/Creator': 'Keynote', '/CreationDate': "D:20190114072947Z00'00'", '/ModDate': "D:20190114072947Z00'00'"} d.pop('/Creator') d.pop('/Producer') print(d) # {'/Title': 'sample1', '/CreationDate': "D:20190114072947Z00'00'", '/ModDate': "D:20190114072947Z00'00'"} dst_pdf.addMetadata(d) with open('data/temp/sample1_remove_meta.pdf', 'wb') as f: dst_pdf.write(f) print(PyPDF2.PdfFileReader('data/temp/sample1_remove_meta.pdf').documentInfo) # {'/Producer': 'PyPDF2', '/Title': 'sample1', '/CreationDate': "D:20190114072947Z00'00'", '/ModDate': "D:20190114072947Z00'00'"} def remove_metadata(src_path, dst_path, *args, producer=''): src_pdf = PyPDF2.PdfFileReader(src_path) dst_pdf = PyPDF2.PdfFileWriter() dst_pdf.cloneReaderDocumentRoot(src_pdf) d = {key: src_pdf.documentInfo[key] for key in src_pdf.documentInfo.keys() if key not in args} d.setdefault('/Producer', producer) dst_pdf.addMetadata(d) with open(dst_path, 'wb') as f: dst_pdf.write(f) remove_metadata('data/src/pdf/sample1.pdf', 'data/temp/sample1_no_meta.pdf', '/Creator', '/ModDate', '/CreationDate') print(PyPDF2.PdfFileReader('data/temp/sample1_no_meta.pdf').documentInfo) # {'/Producer': 'macOS バージョン10.14.2(ビルド18C54) Quartz PDFContext', '/Title': 'sample1'} remove_metadata('data/src/pdf/sample1.pdf', 'data/temp/sample1_no_meta.pdf', '/Creator', '/ModDate', '/CreationDate', '/Producer') print(PyPDF2.PdfFileReader('data/temp/sample1_no_meta.pdf').documentInfo) # {'/Producer': '', '/Title': 'sample1'} remove_metadata('data/src/pdf/sample1.pdf', 'data/temp/sample1_no_meta.pdf', '/Creator', '/ModDate', '/CreationDate', '/Producer', producer='XXX') print(PyPDF2.PdfFileReader('data/temp/sample1_no_meta.pdf').documentInfo) # {'/Producer': 'XXX', '/Title': 'sample1'} def select_metadata(src_path, dst_path, *args, producer=''): src_pdf = PyPDF2.PdfFileReader(src_path) dst_pdf = PyPDF2.PdfFileWriter() dst_pdf.cloneReaderDocumentRoot(src_pdf) d = {key: src_pdf.documentInfo[key] for key in src_pdf.documentInfo.keys() if key in args} d.setdefault('/Producer', producer) dst_pdf.addMetadata(d) with open(dst_path, 'wb') as f: dst_pdf.write(f) select_metadata('data/src/pdf/sample1.pdf', 'data/temp/sample1_no_meta.pdf', '/Title', '/ModDate') print(PyPDF2.PdfFileReader('data/temp/sample1_no_meta.pdf').documentInfo) # {'/Producer': '', '/Title': 'sample1', '/ModDate': "D:20190114072947Z00'00'"} select_metadata('data/src/pdf/sample1.pdf', 'data/temp/sample1_no_meta.pdf', '/Title', '/Producer') print(PyPDF2.PdfFileReader('data/temp/sample1_no_meta.pdf').documentInfo) # {'/Producer': 'macOS バージョン10.14.2(ビルド18C54) Quartz PDFContext', '/Title': 'sample1'}
mit
287,211,407,982,853,760
37.485981
192
0.675085
false
2.679245
false
false
false
googleapis/googleapis-gen
google/ads/googleads/v8/googleads-py/google/ads/googleads/v8/services/services/payments_account_service/client.py
1
18740
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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. # from collections import OrderedDict from distutils import util import os import re from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore from google.ads.googleads.v8.resources.types import payments_account from google.ads.googleads.v8.services.types import payments_account_service from .transports.base import PaymentsAccountServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import PaymentsAccountServiceGrpcTransport class PaymentsAccountServiceClientMeta(type): """Metaclass for the PaymentsAccountService client. This provides class-level methods for building and retrieving support objects (e.g. transport) without polluting the client instance objects. """ _transport_registry = OrderedDict() # type: Dict[str, Type[PaymentsAccountServiceTransport]] _transport_registry['grpc'] = PaymentsAccountServiceGrpcTransport def get_transport_class(cls, label: str = None, ) -> Type[PaymentsAccountServiceTransport]: """Return an appropriate transport class. Args: label: The name of the desired transport. If none is provided, then the first transport in the registry is used. Returns: The transport class to use. """ # If a specific transport is requested, return that one. if label: return cls._transport_registry[label] # No transport is requested; return the default (that is, the first one # in the dictionary). return next(iter(cls._transport_registry.values())) class PaymentsAccountServiceClient(metaclass=PaymentsAccountServiceClientMeta): """Service to provide payments accounts that can be used to set up consolidated billing. """ @staticmethod def _get_default_mtls_endpoint(api_endpoint): """Convert api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: str: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint mtls_endpoint_re = re.compile( r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" ) m = mtls_endpoint_re.match(api_endpoint) name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint if sandbox: return api_endpoint.replace( "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" ) return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") DEFAULT_ENDPOINT = 'googleads.googleapis.com' DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore DEFAULT_ENDPOINT ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials info. Args: info (dict): The service account private key info. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: PaymentsAccountServiceClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_info(info) kwargs["credentials"] = credentials return cls(*args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: PaymentsAccountServiceClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file( filename) kwargs['credentials'] = credentials return cls(*args, **kwargs) from_service_account_json = from_service_account_file @property def transport(self) -> PaymentsAccountServiceTransport: """Return the transport used by the client instance. Returns: PaymentsAccountServiceTransport: The transport used by the client instance. """ return self._transport @staticmethod def customer_path(customer_id: str,) -> str: """Return a fully-qualified customer string.""" return "customers/{customer_id}".format(customer_id=customer_id, ) @staticmethod def parse_customer_path(path: str) -> Dict[str,str]: """Parse a customer path into its component segments.""" m = re.match(r"^customers/(?P<customer_id>.+?)$", path) return m.groupdict() if m else {} @staticmethod def payments_account_path(customer_id: str,payments_account_id: str,) -> str: """Return a fully-qualified payments_account string.""" return "customers/{customer_id}/paymentsAccounts/{payments_account_id}".format(customer_id=customer_id, payments_account_id=payments_account_id, ) @staticmethod def parse_payments_account_path(path: str) -> Dict[str,str]: """Parse a payments_account path into its component segments.""" m = re.match(r"^customers/(?P<customer_id>.+?)/paymentsAccounts/(?P<payments_account_id>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_billing_account_path(billing_account: str, ) -> str: """Return a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_folder_path(folder: str, ) -> str: """Return a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder, ) @staticmethod def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P<folder>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_organization_path(organization: str, ) -> str: """Return a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization, ) @staticmethod def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P<organization>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_project_path(project: str, ) -> str: """Return a fully-qualified project string.""" return "projects/{project}".format(project=project, ) @staticmethod def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P<project>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_location_path(project: str, location: str, ) -> str: """Return a fully-qualified location string.""" return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path) return m.groupdict() if m else {} def __init__(self, *, credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, PaymentsAccountServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the payments account service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. transport (Union[str, ~.PaymentsAccountServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. client_options (google.api_core.client_options.ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always use the default regular endpoint) and "auto" (auto switch to the default mTLS endpoint if client certificate is present, this is the default value). However, the ``api_endpoint`` property takes precedence if provided. (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable is "true", then the ``client_cert_source`` property can be used to provide client certificate for mutual TLS transport. If not provided, the default SSL client certificate will be used if present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not set, no client certificate will be used. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ if isinstance(client_options, dict): client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() # Create SSL credentials for mutual TLS if needed. use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) ssl_credentials = None is_mtls = False if use_client_cert: if client_options.client_cert_source: import grpc # type: ignore cert, key = client_options.client_cert_source() ssl_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) is_mtls = True else: creds = SslCredentials() is_mtls = creds.is_mtls ssl_credentials = creds.ssl_credentials if is_mtls else None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint else: use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_env == "never": api_endpoint = self.DEFAULT_ENDPOINT elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": api_endpoint = self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, PaymentsAccountServiceTransport): # transport is a PaymentsAccountServiceTransport instance. if credentials: raise ValueError('When providing a transport instance, ' 'provide its credentials directly.') self._transport = transport elif isinstance(transport, str): Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, host=self.DEFAULT_ENDPOINT ) else: self._transport = PaymentsAccountServiceGrpcTransport( credentials=credentials, host=api_endpoint, ssl_channel_credentials=ssl_credentials, client_info=client_info, ) def list_payments_accounts(self, request: payments_account_service.ListPaymentsAccountsRequest = None, *, customer_id: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> payments_account_service.ListPaymentsAccountsResponse: r"""Returns all payments accounts associated with all managers between the login customer ID and specified serving customer in the hierarchy, inclusive. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `HeaderError <>`__ `InternalError <>`__ `PaymentsAccountError <>`__ `QuotaError <>`__ `RequestError <>`__ Args: request (:class:`google.ads.googleads.v8.services.types.ListPaymentsAccountsRequest`): The request object. Request message for fetching all accessible payments accounts. customer_id (:class:`str`): Required. The ID of the customer to apply the PaymentsAccount list operation to. This corresponds to the ``customer_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.ads.googleads.v8.services.types.ListPaymentsAccountsResponse: Response message for [PaymentsAccountService.ListPaymentsAccounts][google.ads.googleads.v8.services.PaymentsAccountService.ListPaymentsAccounts]. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. if request is not None and any([customer_id]): raise ValueError('If the `request` argument is set, then none of ' 'the individual field arguments should be set.') # Minor optimization to avoid making a copy if the user passes # in a payments_account_service.ListPaymentsAccountsRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, payments_account_service.ListPaymentsAccountsRequest): request = payments_account_service.ListPaymentsAccountsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if customer_id is not None: request.customer_id = customer_id # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.list_payments_accounts] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata(( ('customer_id', request.customer_id), )), ) # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response __all__ = ( 'PaymentsAccountServiceClient', )
apache-2.0
-9,072,559,174,270,836,000
43.619048
154
0.631964
false
4.572962
false
false
false
feureau/Small-Scripts
Blender/Blender config/2.91/scripts/addons/bricker_v2-2-1/lib/property_groups/created_model_properties.py
1
35831
# Copyright (C) 2020 Christopher Gearhart # chris@bblanimation.com # http://bblanimation.com/ # # 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/>. # System imports # NONE! # Blender imports import bpy from bpy.props import * # Module imports from .boolean_properties import * from ...functions.property_callbacks import * # Create custom property group class CreatedModelProperties(bpy.types.PropertyGroup): # CMLIST ITEM SETTINGS name = StringProperty(update=uniquify_name) id = IntProperty() idx = IntProperty() # NAME OF SOURCE source_obj = PointerProperty( type=bpy.types.Object, poll=lambda self, object: object.type == "MESH", name="Source Object", description="Name of the source object to Brickify", update=set_default_obj_if_empty, ) # TRANSFORMATION SETTINGS model_loc = StringProperty(default="-1,-1,-1") model_rot = StringProperty(default="-1,-1,-1") model_scale = StringProperty(default="-1,-1,-1") transform_scale = FloatProperty( name="Scale", description="Scale of the brick model", update=update_model_scale, step=1, default=1.0, ) apply_to_source_object = BoolProperty( name="Apply to source", description="Apply transformations to source object when Brick Model is deleted", default=True, ) parent_obj = PointerProperty( type=bpy.types.Object, name="Parent Object", description="Name of the parent object used for model transformations", ) expose_parent = BoolProperty( name="Show Manipulator", description="Expose the parent object for this brick model for viewport manipulation", update=update_parent_exposure, default=False, ) # ANIMATION SETTINGS use_animation = BoolProperty( name="Use Animation", description="Create Brick Model for each frame, from start to stop frame (WARNING: Calculation takes time, and may result in large blend file)", default=False, ) start_frame = IntProperty( name="Start", description="First frame of the brick animation", update=dirty_anim, min=0, max=500000, default=1, ) stop_frame = IntProperty( name="End", description="Final frame of the brick animation", update=dirty_anim, min=0, max=500000, default=10, ) step_frame = IntProperty( name="Step", description="Number of frames to skip forward when generating the brick animation", update=dirty_anim, min=0, max=500000, default=1, ) # BASIC MODEL SETTINGS brick_height = FloatProperty( name="Brick Height", description="Height of the bricks in the final Brick Model (in meters, excluding the stud)", update=dirty_matrix, subtype="DISTANCE", step=1, precision=3, min = 0.000001, soft_min=0.001, soft_max=10, default=0.1, ) gap = FloatProperty( name="Gap Between Bricks", description="Distance between bricks (relative to brick height)", update=dirty_matrix, subtype="PERCENTAGE", step=1, precision=1, min=0.0, max=100.0, default=0.5, ) split_model = BoolProperty( name="Split Model", description="Split model into separate objects (slower)", update=dirty_model, default=False, ) random_loc = FloatProperty( name="Random Location", description="Max random location applied to each brick", update=dirty_model, step=1, precision=3, min=0, soft_max=1, default=0.01, ) random_rot = FloatProperty( name="Random Rotation", description="Max random rotation applied to each brick", update=dirty_model, step=1, precision=3, min=0, soft_max=1, default=0.025, ) shell_thickness = IntProperty( name="Shell Thickness", description="Thickness of the outer shell of bricks", update=dirty_build, min=1, max=50, default=1, ) # MERGE SETTINGS merge_type = EnumProperty( name="Merge Type", description="Type of algorithm used for merging bricks together", items=[ # ("NONE", "None (fast)", "Bricks are not merged"), ("GREEDY", "Greedy", "Creates fewest amount of bricks possible"), ("RANDOM", "Random", "Merges randomly for realistic build"), ], update=dirty_build, default="RANDOM", ) legal_bricks_only = BoolProperty( name="Legal Bricks Only", description="Construct model using only legal brick sizes", update=dirty_build, default=True, ) merge_seed = IntProperty( name="Seed", description="Random seed for brick merging calculations", update=dirty_build, min=0, default=1000, ) align_bricks = BoolProperty( name="Align Bricks Horizontally", description="Keep bricks aligned horizontally, and fill the gaps with plates", update=dirty_build, default=True, ) offset_brick_layers = IntProperty( name="Offset Brick Layers", description="Offset the layers that will be merged into bricks if possible", update=dirty_build, step=1, min=0, max=2, default=0, ) # SMOKE SETTINGS smoke_density = FloatProperty( name="Smoke Density", description="Density of brickified smoke (threshold for smoke: 1 - d)", update=dirty_matrix, min=0, max=1, default=0.9, ) smoke_quality = FloatProperty( name="Smoke Quality", description="Amount of data to analyze for density and color of brickified smoke", update=dirty_matrix, min=1, soft_max=100, default=1, ) smoke_brightness = FloatProperty( name="Smoke Brightness", description="Add brightness to smoke colors read from smoke data", update=dirty_matrix, soft_min=0, soft_max=100, default=1, ) smoke_saturation = FloatProperty( name="Smoke Saturation", description="Change saturation level of smoke colors read from smoke data", update=dirty_matrix, min=0, soft_max=100, default=1, ) flame_color = FloatVectorProperty( name="Hex Value", subtype="COLOR", update=dirty_matrix, default=[1.0, 0.63, 0.2], ) flame_intensity = FloatProperty( name="Flame Intensity", description="Intensity of the flames", update=dirty_matrix, min=1, soft_max=50, default=4, ) # BRICK TYPE SETTINGS brick_type = EnumProperty( name="Brick Type", description="Type of brick used to build the model", items=get_brick_type_items, update=update_brick_type, # default="BRICKS", ) max_width = IntProperty( name="Max Width", description="Maximum brick width in studs", update=dirty_build, step=1, min=1, soft_max=100, default=8, ) max_depth = IntProperty( name="Max Depth", description="Maximum brick depth in studs", update=dirty_build, step=1, min=1, soft_max=100, default=24, ) custom_object1 = PointerProperty( type=bpy.types.Object, poll=lambda self, object: object.type == "MESH" and object != self.source_obj and not object.name.startswith("Bricker_{}".format(self.source_obj.name)), name="Custom Object 1", description="Custom object to use as brick type", ) custom_mesh1 = PointerProperty( type=bpy.types.Mesh, name="Custom Mesh 1", description="Cached mesh from Custom Object 1 with materials applied/transform removed", ) custom_object2 = PointerProperty( type=bpy.types.Object, poll=lambda self, object: object.type == "MESH" and object != self.source_obj and not object.name.startswith("Bricker_{}".format(self.source_obj.name)), name="Custom Object 2", description="Custom object to use as brick type", ) custom_mesh2 = PointerProperty( type=bpy.types.Mesh, name="Custom Mesh 2", description="Cached mesh from Custom Object 2 with materials applied/transform removed", ) custom_object3 = PointerProperty( type=bpy.types.Object, poll=lambda self, object: object.type == "MESH" and object != self.source_obj and not object.name.startswith("Bricker_{}".format(self.source_obj.name)), name="Custom Object 3", description="Custom object to use as brick type", ) custom_mesh3 = PointerProperty( type=bpy.types.Mesh, name="Custom Mesh 3", description="Cached mesh from Custom Object 3 with materials applied/transform removed", ) dist_offset = FloatVectorProperty( name="Offset Distance", description="Offset distance between custom bricks (1.0 = side-by-side)", update=dirty_matrix, step=1, precision=3, subtype="TRANSLATION", min=0.001, soft_max=1.0, default=(1, 1, 1), ) # BOOLEAN SETTINGS booleans = CollectionProperty(type=BooleanProperties) boolean_index = IntProperty(default=-1) # MATERIAL & COLOR SETTINGS material_type = EnumProperty( name="Material Type", description="Choose what materials will be applied to model", items=[ ("NONE", "None", "No material applied to bricks"), ("CUSTOM", "Single Material", "Choose one material to apply to all generated bricks"), ("RANDOM", "Random", "Apply a random material from Brick materials to each generated brick"), ("SOURCE", "Use Source Materials", "Apply material based on closest intersecting face"), ], update=dirty_build, default="SOURCE", ) custom_mat = PointerProperty( type=bpy.types.Material, name="Custom Material", description="Material to apply to all bricks", ) internal_mat = PointerProperty( type=bpy.types.Material, name="Internal Material", description="Material to apply to bricks inside material shell", update=dirty_material, ) mat_shell_depth = IntProperty( name="Shell Material Depth", description="Depth to which the outer materials should be applied (1 = Only exposed bricks)", step=1, min=1, max=50, update=dirty_matrix, default=1, ) merge_internals = EnumProperty( name="Merge Shell with Internals", description="Merge bricks on shell with internal bricks", items=[ ("NEITHER", "Neither", "Don't merge shell bricks with internals in either direction"), ("HORIZONTAL", "Horizontal", "Merge shell bricks with internals horizontally, but not vertically"), ("VERTICAL", "Vertical", "Merge shell bricks with internals vertically, but not horizontally"), ("BOTH", "Horizontal & Vertical", "Merge shell bricks with internals in both directions"), ], update=dirty_build, default="BOTH", ) random_mat_seed = IntProperty( name="Seed", description="Random seed for material assignment", min=0, update=dirty_material, default=1000, ) use_uv_map = BoolProperty( name="Use UV Map", description="Transfer colors from UV map (if disabled or no UV map found, brick color will be based on RGB of first shader node)", update=dirty_build, default=True, ) uv_image = PointerProperty( type=bpy.types.Image, name="UV Image", description="UV Image to use for UV Map color transfer (defaults to active UV if left blank)", update=dirty_build, ) color_snap = EnumProperty( name="Color Mapping", description="Method for mapping source material(s)/texture(s) to new materials", items=[ ("NONE", "None", "Use source material(s)"), ("RGB", "RGB", "Map RGB values to new materials (similar materials will merge into one material based on threshold)"), ("ABS", "ABS", "Map RGB values to nearest ABS Plastic Materials") ], update=dirty_build, default="RGB", ) color_depth = IntProperty( name="Color Depth", description="Number of colors to use in representing the UV texture (2^depth colors are created)", min=1, max=10, update=dirty_build, default=4, ) blur_radius = IntProperty( name="Blur Radius", description="Distance over which to blur the image before sampling", min=0, max=10, update=dirty_build, default=0, # 1 ) color_snap_specular = FloatProperty( name="Specular", description="Specular value for the created materials", subtype="FACTOR", precision=3, min=0.0, soft_max=1.0, update=dirty_material, default=0.5, ) color_snap_roughness = FloatProperty( name="Roughness", description="Roughness value for the created materials", subtype="FACTOR", precision=3, min=0.0, soft_max=1.0, update=dirty_material, default=0.5, ) color_snap_sss = FloatProperty( name="Subsurface Scattering", description="Subsurface scattering value for the created materials", subtype="FACTOR", precision=3, min=0.0, soft_max=1.0, update=dirty_material, default=0.0, ) color_snap_sss_saturation = FloatProperty( name="SSS Saturation", description="Saturation of the subsurface scattering for the created materials (relative to base color value)", subtype="FACTOR", precision=3, min=0.0, soft_max=1.0, update=dirty_material, default=1.0, ) color_snap_ior = FloatProperty( name="IOR", description="IOR value for the created materials", precision=3, min=0.0, soft_max=1000.0, update=dirty_material, default=1.45, ) color_snap_transmission = FloatProperty( name="Transmission", description="Transmission value for the created materials", subtype="FACTOR", precision=3, min=0.0, soft_max=1.0, update=dirty_material, default=0.0, ) color_snap_displacement = FloatProperty( name="Displacement", description="Displacement value for the created materials (overrides ABS Plastic displacement value)", subtype="FACTOR", precision=3, min=0.0, soft_max=1.0, update=dirty_material, default=0.04, ) use_abs_template = BoolProperty( name="Use ABS Template", description="Use the default ABS Plastic Material node tree to build the RGB materials", update=dirty_material, default=True, ) include_transparency = BoolProperty( name="Include Transparency", description="Include alpha value of original material color", update=dirty_build, default=True, ) transparent_weight = FloatProperty( name="Transparency Weight", description="How much the original material's alpha value affects the chosen ABS Plastic Material", precision=1, min=0, soft_max=2, update=dirty_material, default=1, ) target_material = PointerProperty( name="Target Material", type=bpy.types.Material, description="Add material to materials list", update=add_material_to_list, ) target_material_message = StringProperty( description="Message from target material chosen (warning or success)", default="", ) target_material_time = StringProperty( # stored as string because float cuts off digits description="'str(time.time())' from when the material message was created", default="0", ) # BRICK DETAIL SETTINGS stud_detail = EnumProperty( name="Stud Detailing", description="Choose where to draw brick studs", items=[ ("NONE", "None", "Don't include brick studs/logos on bricks"), ("EXPOSED", "Exposed Bricks", "Include brick studs/logos only on bricks with the top exposed"), ("ALL", "All Bricks", "Include brick studs/logos only on bricks with the top exposed"), ], update=dirty_bricks, default="EXPOSED", ) logo_type = EnumProperty( name="Logo Type", description="Choose logo type to draw on brick studs", items=get_logo_types, update=dirty_bricks, # default="NONE", ) logo_resolution = IntProperty( name="Resolution", description="Resolution of the brick logo", update=dirty_bricks, min=1, soft_max=10, default=2, ) logo_decimate = FloatProperty( name="Decimate", description="Decimate the brick logo (lower number for higher resolution)", update=dirty_bricks, precision=0, min=0, max=10, default=7.25, ) logo_object = PointerProperty( type=bpy.types.Object, poll=lambda self, object: object.type == "MESH" and object != self.source_obj and not object.name.startswith("Bricker_{}".format(self.source_obj.name)), name="Logo Object", description="Select a custom logo object to use on top of each stud", update=dirty_bricks, ) logo_scale = FloatProperty( name="Logo Scale", description="Logo scale relative to stud scale", subtype="PERCENTAGE", step=1, update=dirty_bricks, precision=1, min=0.0001, soft_max=100.0, default=78.0, ) logo_inset = FloatProperty( name="Logo Inset", description="How far to inset logo to stud", subtype="PERCENTAGE", step=1, update=dirty_bricks, precision=1, soft_min=0.0, soft_max=100.0, default=50.0, ) hidden_underside_detail = EnumProperty( name="Underside Detailing of Obstructed Bricks", description="Level of detail on underside of bricks with obstructed undersides", items=[ ("FLAT", "Flat", "Draw single face on brick underside", 0), ("LOW", "Low Detail", "Hollow out brick underside and draw tube supports", 1), ("HIGH", "High Detail", "Draw underside of bricks at full detail (support beams, ticks, inset tubes)", 3), ], update=dirty_bricks, default="FLAT", ) exposed_underside_detail = EnumProperty( name="Underside Detailing of Exposed Bricks", description="Level of detail on underside of bricks with exposed undersides", items=[ ("FLAT", "Flat", "Draw single face on brick underside", 0), ("LOW", "Low Detail", "Hollow out brick underside and draw tube supports", 1), ("HIGH", "High Detail", "Draw underside of bricks at full detail (support beams, ticks, inset tubes)", 3), ], update=dirty_bricks, default="FLAT", ) circle_verts = IntProperty( name="Vertices", description="Number of vertices in each circle in brick mesh", update=update_circle_verts, min=4, soft_max=64, default=16, ) # BEVEL SETTINGS bevel_added = BoolProperty( name="Bevel Bricks", description="Bevel brick edges and corners for added realism", default=False, ) bevel_show_render = BoolProperty( name="Render", description="Use modifier during render", update=update_bevel_render, default=True, ) bevel_show_viewport = BoolProperty( name="Realtime", description="Display modifier in viewport", update=update_bevel_viewport, default=True, ) bevel_show_edit_mode = BoolProperty( name="Edit Mode", description="Display modifier in Edit mode", update=update_bevel_edit_mode, default=True, ) bevel_width = FloatProperty( name="Bevel Width", description="Bevel amount (relative to Brick Height)", subtype="DISTANCE", step=1, min=0.0, soft_max=10, update=update_bevel, default=0.01, ) bevel_segments = IntProperty( name="Bevel Resolution", description="Number of segments for round edges/verts", step=1, min=1, max=100, update=update_bevel, default=1, ) bevel_profile = FloatProperty( name="Bevel Profile", description="The profile shape (0.5 = round)", subtype="FACTOR", step=1, min=0.0, max=1.0, update=update_bevel, default=0.7, ) # INTERNAL SUPPORTS SETTINGS internal_supports = EnumProperty( name="Internal Supports", description="Choose what type of brick support structure to use inside your model", items=[ ("NONE", "None", "No internal supports"), ("COLUMNS", "Columns", "Use columns inside model"), ("LATTICE", "Lattice", "Use latice inside model"), ], update=dirty_internal, default="NONE", ) lattice_step = IntProperty( name="Step", description="Distance between cross-beams", update=dirty_internal, step=1, min=2, soft_max=100, default=4, ) lattice_height = IntProperty( name="Height", description="Height of the cross-beams", update=dirty_internal, step=1, min=1, soft_max=100, default=1, ) alternate_xy = BoolProperty( name="Alternate X and Y", description="Alternate back-and-forth and side-to-side beams", update=dirty_internal, default=True, ) col_thickness = IntProperty( name="Thickness", description="Thickness of the columns", update=dirty_internal, min=1, soft_max=100, default=2, ) col_step = IntProperty( name="Step", description="Distance between columns", update=dirty_internal, step=1, min=1, soft_max=100, default=2, ) # ADVANCED SETTINGS insideness_ray_cast_dir = EnumProperty( name="Insideness Ray Cast Direction", description="Ray cast method for calculation of insideness", items=[ ("HIGH_EFFICIENCY", "High Efficiency", "Reuses single intersection ray cast for insideness calculation"), ("X", "X", "Cast rays along X axis for insideness calculations"), ("Y", "Y", "Cast rays along Y axis for insideness calculations"), ("Z", "Z", "Cast rays along Z axis for insideness calculations"), ("XYZ", "XYZ (Best Result)", "Cast rays in all axis directions for insideness calculation (slowest; uses result consistent for at least 2 of the 3 rays)"), ], update=dirty_matrix, default="HIGH_EFFICIENCY", ) brick_shell = EnumProperty( name="Brick Shell", description="Choose whether the outer shell of bricks will be inside or outside the source mesh", items=[ ("INSIDE", "Inside Mesh", "Draw brick shell inside source mesh (recommended)"), ("OUTSIDE", "Outside Mesh", "Draw brick shell outside source mesh"), ("CONSISTENT", "Consistent", "Draw brick shell on a consistent side of the source mesh topology (may fix noisy model if source mesh is not water-tight)"), ], update=update_brick_shell, default="INSIDE", ) calculation_axes = EnumProperty( name="Expanded Axes", description="The brick shell will be drawn on the outside in these directions", items=[ ("XYZ", "XYZ", "XYZ"), ("XY", "XY", "XY"), ("YZ", "YZ", "YZ"), ("XZ", "XZ", "XZ"), ("X", "X", "X"), ("Y", "Y", "Y"), ("Z", "Z", "Z"), ], update=dirty_matrix, default="XY", ) use_normals = BoolProperty( name="Use Normals", description="Use normals to calculate insideness of bricks (may improve the result if normals on source mesh are oriented correctly)", update=dirty_matrix, default=False, ) grid_offset = FloatVectorProperty( name="Grid Offset", description="Offset the brick grid along the volume of the source mesh (factor of brick dimensions)", subtype="XYZ", min=-1, max=1, update=dirty_matrix, default=(0, 0, 0), ) use_absolute_grid = BoolProperty( name="Absolute Grid Coords", description="Place bricks on a fixed grid that is consistent between all models", update=dirty_matrix, default=False, ) use_absolute_grid_anim = BoolProperty( name="Absolute Grid Coords", description="Place bricks on a fixed grid that is consistent between all models", update=dirty_matrix, default=True, ) calc_internals = BoolProperty( name="Calculate Internals", description="Calculate values for bricks inside shell (disable for faster calculation at the loss of the 'Shell Thickness' and 'Supports' features)", update=dirty_matrix, default=True, ) use_local_orient = BoolProperty( name="Use Local Orient", description="Generate bricks based on local orientation of source object", default=False, ) instance_method = EnumProperty( name="Instance Method", description="Method to use for instancing equivalent meshes to save on memory and render times", items=[ ("NONE", "None", "No object instancing"), ("LINK_DATA", "Link Data", "Link mesh data for like objects when 'Split Model' is enabled"), ("POINT_CLOUD", "Point Cloud (experimental)", "Instance a single mesh over a point cloud (this method does not support multiple materials or brick merging)"), ], update=dirty_build, default="LINK_DATA", ) # Deep Cache of bricksdict bfm_cache = StringProperty(default="") # Blender State for Undo Stack blender_undo_state = IntProperty(default=0) # Back-End UI Properties active_key = IntVectorProperty(subtype="XYZ", default=(-1,-1,-1)) # Internal Model Properties model_created = BoolProperty(default=False) brickifying_in_background = BoolProperty(default=False) job_progress = IntProperty( name="", description="", subtype="PERCENTAGE", default=0, soft_min=0, soft_max=100, ) linked_from_external = BoolProperty(default=False) num_animated_frames = IntProperty(default=0) completed_frames = StringProperty(default="") frames_to_animate = IntProperty(default=1) stop_background_process = BoolProperty(default=False) animated = BoolProperty(default=False) armature = BoolProperty(default=False) zstep = IntProperty(default=3) parent_obj = PointerProperty(type=bpy.types.Object) collection = PointerProperty(type=bpy.types.Collection if b280() else bpy.types.Group) mat_obj_abs = PointerProperty(type=bpy.types.Object) mat_obj_random = PointerProperty(type=bpy.types.Object) rgba_vals = StringProperty(default="789c8b8e0500011500b9") # result of `compress_str(json.dumps({}))` customized = BoolProperty(default=True) brick_sizes_used = StringProperty(default="") # list of brick_sizes used separated by | (e.g. '5,4,3|7,4,5|8,6,5') brick_types_used = StringProperty(default="") # list of brick_types used separated by | (e.g. 'PLATE|BRICK|STUD') model_created_on_frame = IntProperty(default=-1) is_smoke = BoolProperty(default=False) has_custom_obj1 = BoolProperty(default=False) has_custom_obj2 = BoolProperty(default=False) has_custom_obj3 = BoolProperty(default=False) # model stats num_bricks_in_model = IntProperty(default=0) num_materials_in_model = IntProperty(default=0) model_weight = IntProperty(default=0) real_world_dimensions = FloatVectorProperty( name="Real World Dimensions", description="", subtype="XYZ", unit="LENGTH", precision=6, default=(0, 0, 0), ) # Properties for checking of model needs updating anim_is_dirty = BoolProperty(default=True) material_is_dirty = BoolProperty(default=True) model_is_dirty = BoolProperty(default=True) build_is_dirty = BoolProperty(default=False) bricks_are_dirty = BoolProperty(default=True) matrix_is_dirty = BoolProperty(default=True) matrix_lost = BoolProperty(default=False) internal_is_dirty = BoolProperty(default=True) last_logo_type = StringProperty(default="NONE") last_split_model = BoolProperty(default=False) last_start_frame = IntProperty( name="Last Start", description="Current start frame of brickified animation", default=-1, ) last_stop_frame = IntProperty( name="Last End", description="Current end frame of brickified animation", default=-1, ) last_step_frame = IntProperty( name="Last Step", description="Current number of frames to skip forward when generating brickified animation", default=-1, ) last_source_mid = StringProperty(default="-1,-1,-1") last_material_type = StringProperty(default="SOURCE") last_use_abs_template = BoolProperty(default=False) last_shell_thickness = IntProperty(default=1) last_internal_supports = StringProperty(default="NONE") last_brick_type = StringProperty(default="BRICKS") last_instance_method = StringProperty(default="LINK_DATA") last_matrix_settings = StringProperty(default="") last_legal_bricks_only = BoolProperty(default=False) last_mat_shell_depth = IntProperty(default=1) last_bevel_width = FloatProperty() last_bevel_segments = IntProperty() last_bevel_profile = IntProperty() last_is_smoke = BoolProperty() # Bricker Version of Model version = StringProperty(default="1.0.4") ### BACKWARDS COMPATIBILITY # v1.0 maxBrickScale1 = IntProperty() maxBrickScale2 = IntProperty() # v1.3 distOffsetX = FloatProperty() distOffsetY = FloatProperty() distOffsetZ = FloatProperty() # v1.4 logoDetail = StringProperty("NONE") # v1.5 source_name = StringProperty() parent_name = StringProperty() # v1.6 modelLoc = StringProperty(default="-1,-1,-1") modelRot = StringProperty(default="-1,-1,-1") modelScale = StringProperty(default="-1,-1,-1") transformScale = FloatProperty(default=1) applyToSourceObject = BoolProperty(default=True) exposeParent = BoolProperty(default=False) useAnimation = BoolProperty(default=False) startFrame = IntProperty(default=1) stopFrame = IntProperty(default=10) maxWorkers = IntProperty(default=5) backProcTimeout = FloatProperty(default=0) brickHeight = FloatProperty(default=0.1) mergeSeed = IntProperty(default=1000) connectThresh = IntProperty(default=1) smokeDensity = FloatProperty(default=0.9) smokeQuality = FloatProperty(default=1) smokeBrightness = FloatProperty(default=1) smokeSaturation = FloatProperty(default=1) flameColor = FloatVectorProperty(default=[1.0, 0.63, 0.2]) flameIntensity = FloatProperty(default=4) splitModel = BoolProperty(default=False) randomLoc = FloatProperty(default=0.01) randomRot = FloatProperty(default=0.025) brickShell = StringProperty(default="INSIDE") calculationAxes = StringProperty(default="XY") shellThickness = IntProperty(default=1) brickType = StringProperty(default="BRICKS") alignBricks = BoolProperty(default=True) offsetBrickLayers = IntProperty(default=0) maxWidth = IntProperty(default=2) maxDepth = IntProperty(default=10) mergeType = StringProperty(default="RANDOM") legalBricksOnly = BoolProperty(default=True) customObject1 = PointerProperty(type=bpy.types.Object) customObject2 = PointerProperty(type=bpy.types.Object) customObject3 = PointerProperty(type=bpy.types.Object) distOffset = FloatVectorProperty(default=(1, 1, 1)) paintbrushMat = PointerProperty(type=bpy.types.Material) materialType = StringProperty(default="NONE") customMat = PointerProperty(type=bpy.types.Material) internalMat = PointerProperty(type=bpy.types.Material) matShellDepth = IntProperty(default=1) mergeInternals = StringProperty(default="BOTH") randomMatSeed = IntProperty(default=1000) useUVMap = BoolProperty(default=True) uvImage = PointerProperty(type=bpy.types.Image) colorSnap = StringProperty(default="RGB") colorSnapAmount = FloatProperty(default=0.001) color_snap_amount = FloatProperty(default=0.001) colorSnapSpecular = FloatProperty(0.5) colorSnapRoughness = FloatProperty(0.5) colorSnapIOR = FloatProperty(1.45) colorSnapTransmission = FloatProperty(0.0) includeTransparency = BoolProperty(default=True) transparentWeight = FloatProperty(default=1) targetMaterial = StringProperty(default="") studDetail = StringProperty(default="EXPOSED") logoType = StringProperty(default="NONE") logoResolution = IntProperty(default=2) logoDecimate = FloatProperty(default=7.25) logoScale = FloatProperty(default=78.0) logoInset = FloatProperty(default=50.0) hiddenUndersideDetail = StringProperty(default="FLAT") exposedUndersideDetail = StringProperty(default="FLAT") circleVerts = IntProperty(default=16) bevelAdded = BoolProperty(default=False) bevelShowRender = BoolProperty(default=True) bevelShowViewport = BoolProperty(default=True) bevelShowEditmode = BoolProperty(default=True) bevelWidth = FloatProperty(default=0.01) bevelSegments = IntProperty(default=1) bevelProfile = FloatProperty(default=0.7) internalSupports = StringProperty(default="NONE") latticeStep = IntProperty(default=4) latticeHeight = IntProperty(default=1) alternateXY = BoolProperty(default=1) colThickness = IntProperty(default=2) colStep = IntProperty(default=2) insidenessRayCastDir = StringProperty(default="HIGH_EFFICIENCY") useNormals = BoolProperty(default=False) verifyExposure = BoolProperty(default=False) calcInternals = BoolProperty(default=True) useLocalOrient = BoolProperty(default=False) instanceBricks = BoolProperty(default=True) BFMCache = StringProperty(default="") modelCreated = BoolProperty(default=False) numAnimatedFrames = IntProperty(default=0) framesToAnimate = IntProperty(default=0) modelCreatedOnFrame = IntProperty(default=-1)
gpl-3.0
8,693,281,229,719,090,000
35.674514
170
0.634395
false
3.951367
false
false
false
xclxxl414/rqalpha
rqalpha/__main__.py
1
14210
# -*- coding: utf-8 -*- # # Copyright 2017 Ricequant, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import errno import sys import os import shutil import six import click from importlib import import_module from rqalpha.utils.click_helper import Date from rqalpha.utils.config import parse_config, dump_config CONTEXT_SETTINGS = { 'default_map': { 'run': { } } } @click.group(context_settings=CONTEXT_SETTINGS) @click.option('-v', '--verbose', count=True) @click.help_option('-h', '--help') @click.pass_context def cli(ctx, verbose): ctx.obj["VERBOSE"] = verbose def inject_mod_commands(): from rqalpha.utils.config import get_mod_conf from rqalpha.mod import SYSTEM_MOD_LIST from rqalpha.utils.package_helper import import_mod mod_config = get_mod_conf() for mod_name, config in six.iteritems(mod_config['mod']): if 'lib' in config: lib_name = config["lib"] else: lib_name = "rqalpha_mod_{}".format(mod_name) if not config['enabled']: continue try: if mod_name in SYSTEM_MOD_LIST: # inject system mod import_mod("rqalpha.mod." + lib_name) else: # inject third part mod import_mod(lib_name) except Exception as e: pass def entry_point(): inject_mod_commands() cli(obj={}) @cli.command() @click.option('-d', '--data-bundle-path', default=os.path.expanduser('~/.rqalpha'), type=click.Path(file_okay=False)) @click.option('--locale', 'locale', type=click.STRING, default="zh_Hans_CN") def update_bundle(data_bundle_path, locale): """ Sync Data Bundle """ from rqalpha import main main.update_bundle(data_bundle_path, locale) @cli.command() @click.help_option('-h', '--help') # -- Base Configuration @click.option('-d', '--data-bundle-path', 'base__data_bundle_path', type=click.Path(exists=True)) @click.option('-f', '--strategy-file', 'base__strategy_file', type=click.Path(exists=True)) @click.option('-s', '--start-date', 'base__start_date', type=Date()) @click.option('-e', '--end-date', 'base__end_date', type=Date()) @click.option('-bm', '--benchmark', 'base__benchmark', type=click.STRING, default=None) @click.option('-mm', '--margin-multiplier', 'base__margin_multiplier', type=click.FLOAT) @click.option('-a', '--account', 'base__accounts', nargs=2, multiple=True, help="set account type with starting cash") @click.option('--position', 'base__init_positions', type=click.STRING, help="set init position") @click.option('-fq', '--frequency', 'base__frequency', type=click.Choice(['1d', '1m', 'tick'])) @click.option('-rt', '--run-type', 'base__run_type', type=click.Choice(['b', 'p', 'r']), default="b") @click.option('-rp', '--round-price', 'base__round_price', is_flag=True) @click.option('-mk', '--market', 'base__market', type=click.Choice(['cn', 'hk']), default=None) @click.option('--resume', 'base__resume_mode', is_flag=True) @click.option('--source-code', 'base__source_code') # -- Extra Configuration @click.option('-l', '--log-level', 'extra__log_level', type=click.Choice(['verbose', 'debug', 'info', 'error', 'none'])) @click.option('--disable-user-system-log', 'extra__user_system_log_disabled', is_flag=True, help='disable user system log stdout') @click.option('--disable-user-log', 'extra__user_log_disabled', is_flag=True, help='disable user log stdout') @click.option('--logger', 'extra__logger', nargs=2, multiple=True, help='config logger, e.g. --logger system_log debug') @click.option('--locale', 'extra__locale', type=click.Choice(['cn', 'en']), default="cn") @click.option('--extra-vars', 'extra__context_vars', type=click.STRING, help="override context vars") @click.option("--enable-profiler", "extra__enable_profiler", is_flag=True, help="add line profiler to profile your strategy") @click.option('--config', 'config_path', type=click.STRING, help="config file path") # -- Mod Configuration @click.option('-mc', '--mod-config', 'mod_configs', nargs=2, multiple=True, type=click.STRING, help="mod extra config") def run(**kwargs): """ Start to run a strategy """ config_path = kwargs.get('config_path', None) if config_path is not None: config_path = os.path.abspath(config_path) kwargs.pop('config_path') if not kwargs.get('base__securities', None): kwargs.pop('base__securities', None) from rqalpha import main source_code = kwargs.get("base__source_code") cfg = parse_config(kwargs, config_path=config_path, click_type=True, source_code=source_code) source_code = cfg.base.source_code results = main.run(cfg, source_code=source_code) # store results into ipython when running in ipython from rqalpha.utils import is_run_from_ipython if results is not None and is_run_from_ipython(): import IPython from rqalpha.utils import RqAttrDict ipy = IPython.get_ipython() report = results.get("sys_analyser", {}) ipy.user_global_ns["results"] = results ipy.user_global_ns["report"] = RqAttrDict(report) if results is None: sys.exit(1) @cli.command() @click.option('-d', '--directory', default="./", type=click.Path(), required=True) def examples(directory): """ Generate example strategies to target folder """ source_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "examples") try: shutil.copytree(source_dir, os.path.join(directory, "examples")) except OSError as e: if e.errno == errno.EEXIST: six.print_("Folder examples is exists.") @cli.command() @click.option('-v', '--verbose', is_flag=True) def version(**kwargs): """ Output Version Info """ from rqalpha import version_info six.print_("Current Version: ", version_info) @cli.command() @click.option('-d', '--directory', default="./", type=click.Path(), required=True) def generate_config(directory): """ Generate default config file """ default_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "config.yml") target_config_path = os.path.abspath(os.path.join(directory, 'config.yml')) shutil.copy(default_config, target_config_path) six.print_("Config file has been generated in", target_config_path) # For Mod Cli @cli.command(context_settings=dict( ignore_unknown_options=True, )) @click.help_option('-h', '--help') @click.argument('cmd', nargs=1, type=click.Choice(['list', 'enable', 'disable', 'install', 'uninstall'])) @click.argument('params', nargs=-1) def mod(cmd, params): """ Mod management command rqalpha mod list \n rqalpha mod install xxx \n rqalpha mod uninstall xxx \n rqalpha mod enable xxx \n rqalpha mod disable xxx \n """ def list(params): """ List all mod configuration """ from tabulate import tabulate from rqalpha.utils.config import get_mod_conf mod_config = get_mod_conf() table = [] for mod_name, mod in six.iteritems(mod_config['mod']): table.append([ mod_name, ("enabled" if mod['enabled'] else "disabled") ]) headers = [ "name", "status" ] six.print_(tabulate(table, headers=headers, tablefmt="psql")) six.print_("You can use `rqalpha mod list/install/uninstall/enable/disable` to manage your mods") def install(params): """ Install third-party Mod """ try: from pip._internal import main as pip_main from pip._internal.commands.install import InstallCommand except ImportError: from pip import main as pip_main from pip.commands.install import InstallCommand params = [param for param in params] options, mod_list = InstallCommand().parse_args(params) mod_list = [mod_name for mod_name in mod_list if mod_name != "."] params = ["install"] + params for mod_name in mod_list: mod_name_index = params.index(mod_name) if mod_name.startswith("rqalpha_mod_sys_"): six.print_('System Mod can not be installed or uninstalled') return if "rqalpha_mod_" in mod_name: lib_name = mod_name else: lib_name = "rqalpha_mod_" + mod_name params[mod_name_index] = lib_name # Install Mod installed_result = pip_main(params) # Export config from rqalpha.utils.config import load_yaml, user_mod_conf_path user_conf = load_yaml(user_mod_conf_path()) if os.path.exists(user_mod_conf_path()) else {'mod': {}} if installed_result == 0: # 如果为0,则说明安装成功 if len(mod_list) == 0: """ 主要是方便 `pip install -e .` 这种方式 本地调试 Mod 使用,需要满足以下条件: 1. `rqalpha mod install -e .` 命令是在对应 自定义 Mod 的根目录下 2. 该 Mod 必须包含 `setup.py` 文件(否则也不能正常的 `pip install -e .` 来安装) 3. 该 Mod 包名必须按照 RQAlpha 的规范来命名,具体规则如下 * 必须以 `rqalpha-mod-` 来开头,比如 `rqalpha-mod-xxx-yyy` * 对应import的库名必须要 `rqalpha_mod_` 来开头,并且需要和包名后半部分一致,但是 `-` 需要替换为 `_`, 比如 `rqalpha_mod_xxx_yyy` """ mod_name = _detect_package_name_from_dir(params) mod_name = mod_name.replace("-", "_").replace("rqalpha_mod_", "") mod_list.append(mod_name) for mod_name in mod_list: if "rqalpha_mod_" in mod_name: mod_name = mod_name.replace("rqalpha_mod_", "") if "==" in mod_name: mod_name = mod_name.split('==')[0] user_conf['mod'][mod_name] = {} user_conf['mod'][mod_name]['enabled'] = False dump_config(user_mod_conf_path(), user_conf) return installed_result def uninstall(params): """ Uninstall third-party Mod """ try: from pip._internal import main as pip_main from pip._internal.commands.uninstall import UninstallCommand except ImportError: # be compatible with pip < 10.0 from pip import main as pip_main from pip.commands.uninstall import UninstallCommand params = [param for param in params] options, mod_list = UninstallCommand().parse_args(params) params = ["uninstall"] + params for mod_name in mod_list: mod_name_index = params.index(mod_name) if mod_name.startswith("rqalpha_mod_sys_"): six.print_('System Mod can not be installed or uninstalled') return if "rqalpha_mod_" in mod_name: lib_name = mod_name else: lib_name = "rqalpha_mod_" + mod_name params[mod_name_index] = lib_name # Uninstall Mod uninstalled_result = pip_main(params) # Remove Mod Config from rqalpha.utils.config import user_mod_conf_path, load_yaml user_conf = load_yaml(user_mod_conf_path()) if os.path.exists(user_mod_conf_path()) else {'mod': {}} for mod_name in mod_list: if "rqalpha_mod_" in mod_name: mod_name = mod_name.replace("rqalpha_mod_", "") del user_conf['mod'][mod_name] dump_config(user_mod_conf_path(), user_conf) return uninstalled_result def enable(params): """ enable mod """ mod_name = params[0] if "rqalpha_mod_" in mod_name: mod_name = mod_name.replace("rqalpha_mod_", "") # check whether is installed module_name = "rqalpha_mod_" + mod_name if module_name.startswith("rqalpha_mod_sys_"): module_name = "rqalpha.mod." + module_name try: import_module(module_name) except ImportError: installed_result = install([module_name]) if installed_result != 0: return from rqalpha.utils.config import user_mod_conf_path, load_yaml user_conf = load_yaml(user_mod_conf_path()) if os.path.exists(user_mod_conf_path()) else {'mod': {}} try: user_conf['mod'][mod_name]['enabled'] = True except KeyError: user_conf['mod'][mod_name] = {'enabled': True} dump_config(user_mod_conf_path(), user_conf) def disable(params): """ disable mod """ mod_name = params[0] if "rqalpha_mod_" in mod_name: mod_name = mod_name.replace("rqalpha_mod_", "") from rqalpha.utils.config import user_mod_conf_path, load_yaml user_conf = load_yaml(user_mod_conf_path()) if os.path.exists(user_mod_conf_path()) else {'mod': {}} try: user_conf['mod'][mod_name]['enabled'] = False except KeyError: user_conf['mod'][mod_name] = {'enabled': False} dump_config(user_mod_conf_path(), user_conf) locals()[cmd](params) def _detect_package_name_from_dir(params): setup_path = os.path.join(os.path.abspath(params[-1]), 'setup.py') if not os.path.exists(setup_path): return None return os.path.split(os.path.dirname(setup_path))[1] if __name__ == '__main__': entry_point()
apache-2.0
1,797,748,913,422,962,200
34.845758
130
0.602266
false
3.486872
true
false
false
kim135797531/opencog-python-blending
opencog_b/python/blending/util/blending_util.py
1
1884
# coding=utf-8 __author__ = 'DongMin Kim' from opencog.type_constructors import * # Choose atoms which are connected to specific atom. def get_incoming_nodes(a, target): ret = [] xget_target_link = a.xget_atoms_by_target_atom(types.Link, target) for link in xget_target_link: xget_target_link_node = a.xget_outgoing(link.h) for node in xget_target_link_node: if node.h != target.h: ret.append(node) return ret def get_weighted_tv(atoms): """ Make new TruthValue by evaluate weighted average of exist link's TruthValue. This is implement code of this idea written by Ben Goertzel: https://groups.google.com/forum/#!topic/opencog/fa5c4yE8YdU :param list(EqualLinkKey) atoms: List of EqualLinkKey which are expected to make weighted average TruthValue from theirs. :rtype TruthValue: New truth value. """ if len(atoms) < 2: raise UserWarning( "Weighted TruthValue can't be evaluated with small size." ) mean_sum = 0 weighted_strength_sum = 0 confidence_sum = 0 link_count = 0 for atom in atoms: weighted_strength_sum += (atom.tv.confidence * atom.tv.mean) confidence_sum += atom.tv.confidence link_count += 1 try: new_strength = weighted_strength_sum / confidence_sum except ZeroDivisionError: # This is arithmetic mean, maybe given atoms doesn't have TruthValue. for atom in atoms: mean_sum += atom.tv.mean new_strength = mean_sum / link_count # TODO: Currently, confidence value for new blended node is just # average of old value. # 충돌값 보정을 단순 평균이 아닌 적절한 이유를 가진 값으로 바꿔야 한다. new_confidence = confidence_sum / link_count return TruthValue(new_strength, new_confidence)
agpl-3.0
70,699,895,936,959,990
28.451613
77
0.652245
false
3.254902
false
false
false
elysium001/zamboni
sites/s3dev/settings_base.py
1
5495
"""private_base will be populated from puppet and placed in this directory""" import logging import os import dj_database_url from mkt.settings import (CACHE_PREFIX, ES_INDEXES, KNOWN_PROXIES, LOGGING, HOSTNAME) from .. import splitstrip import private_base as private ALLOWED_HOSTS = ['.allizom.org', '.mozflare.net'] ENGAGE_ROBOTS = False EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = private.EMAIL_HOST DEBUG = False TEMPLATE_DEBUG = DEBUG DEBUG_PROPAGATE_EXCEPTIONS = False SESSION_COOKIE_SECURE = True ADMINS = () DATABASES = {} DATABASES['default'] = dj_database_url.parse(private.DATABASES_DEFAULT_URL) DATABASES['default']['ENGINE'] = 'django.db.backends.mysql' DATABASES['default']['OPTIONS'] = {'init_command': 'SET storage_engine=InnoDB'} DATABASES['default']['ATOMIC_REQUESTS'] = True DATABASES['default']['CONN_MAX_AGE'] = 5 * 60 # 5m for persistent connections. DATABASES['slave'] = dj_database_url.parse(private.DATABASES_SLAVE_URL) DATABASES['slave']['ENGINE'] = 'django.db.backends.mysql' DATABASES['slave']['OPTIONS'] = {'init_command': 'SET storage_engine=InnoDB'} DATABASES['slave']['sa_pool_key'] = 'slave' DATABASES['slave']['ATOMIC_REQUESTS'] = True DATABASES['slave']['CONN_MAX_AGE'] = 5 * 60 # 5m for persistent connections. SERVICES_DATABASE = dj_database_url.parse(private.SERVICES_DATABASE_URL) SLAVE_DATABASES = ['slave'] CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': splitstrip(private.CACHES_DEFAULT_LOCATION), 'TIMEOUT': 500, 'KEY_PREFIX': CACHE_PREFIX, } } SECRET_KEY = private.SECRET_KEY LOG_LEVEL = logging.DEBUG # Celery BROKER_URL = private.BROKER_URL CELERY_ALWAYS_EAGER = False CELERY_IGNORE_RESULT = True CELERY_DISABLE_RATE_LIMITS = True CELERYD_PREFETCH_MULTIPLIER = 1 NETAPP_STORAGE = private.NETAPP_STORAGE_ROOT + '/shared_storage' GUARDED_ADDONS_PATH = private.NETAPP_STORAGE_ROOT + '/guarded-addons' UPLOADS_PATH = NETAPP_STORAGE + '/uploads' ADDON_ICONS_PATH = UPLOADS_PATH + '/addon_icons' WEBSITE_ICONS_PATH = UPLOADS_PATH + '/website_icons' FEATURED_APP_BG_PATH = UPLOADS_PATH + '/featured_app_background' FEED_COLLECTION_BG_PATH = UPLOADS_PATH + '/feed_collection_background' FEED_SHELF_BG_PATH = UPLOADS_PATH + '/feed_shelf_background' IMAGEASSETS_PATH = UPLOADS_PATH + '/imageassets' REVIEWER_ATTACHMENTS_PATH = UPLOADS_PATH + '/reviewer_attachment' PREVIEWS_PATH = UPLOADS_PATH + '/previews' WEBAPP_PROMO_IMG_PATH = UPLOADS_PATH + '/webapp_promo_imgs' WEBSITE_PROMO_IMG_PATH = UPLOADS_PATH + '/website_promo_imgs' SIGNED_APPS_PATH = NETAPP_STORAGE + '/signed_apps' SIGNED_APPS_REVIEWER_PATH = NETAPP_STORAGE + '/signed_apps_reviewer' PREVIEW_THUMBNAIL_PATH = PREVIEWS_PATH + '/thumbs/%s/%d.png' PREVIEW_FULL_PATH = PREVIEWS_PATH + '/full/%s/%d.%s' EXTENSIONS_PATH = NETAPP_STORAGE + '/extensions' SIGNED_EXTENSIONS_PATH = NETAPP_STORAGE + '/signed-extensions' LOGGING['loggers'].update({ 'amqp': {'level': logging.WARNING}, 'raven': {'level': logging.WARNING}, 'requests': {'level': logging.WARNING}, 'z.addons': {'level': logging.DEBUG}, 'z.elasticsearch': {'level': logging.DEBUG}, 'z.pool': {'level': logging.ERROR}, 'z.task': {'level': logging.DEBUG}, 'z.users': {'level': logging.DEBUG}, }) TMP_PATH = os.path.join(NETAPP_STORAGE, 'tmp') ADDONS_PATH = private.NETAPP_STORAGE_ROOT + '/files' SPIDERMONKEY = '/usr/bin/tracemonkey' csp = 'csp.middleware.CSPMiddleware' RESPONSYS_ID = private.RESPONSYS_ID CRONJOB_LOCK_PREFIX = 'mkt-s3dev' ES_DEFAULT_NUM_REPLICAS = 2 ES_HOSTS = splitstrip(private.ES_HOSTS) ES_URLS = ['http://%s' % h for h in ES_HOSTS] ES_INDEXES = dict((k, '%s_s3dev' % v) for k, v in ES_INDEXES.items()) STATSD_HOST = private.STATSD_HOST STATSD_PORT = private.STATSD_PORT STATSD_PREFIX = private.STATSD_PREFIX CEF_PRODUCT = STATSD_PREFIX ES_TIMEOUT = 60 EXPOSE_VALIDATOR_TRACEBACKS = False KNOWN_PROXIES += ['10.2.83.105', '10.2.83.106', '10.2.83.107', '10.8.83.200', '10.8.83.201', '10.8.83.202', '10.8.83.203', '10.8.83.204', '10.8.83.210', '10.8.83.211', '10.8.83.212', '10.8.83.213', '10.8.83.214', '10.8.83.215', '10.8.83.251', '10.8.83.252', '10.8.83.253', ] NEW_FEATURES = True CLEANCSS_BIN = 'cleancss' LESS_BIN = 'lessc' STYLUS_BIN = 'stylus' UGLIFY_BIN = 'uglifyjs' CELERYD_TASK_SOFT_TIME_LIMIT = 540 VALIDATOR_TIMEOUT = 180 LESS_PREPROCESS = True XSENDFILE = True ALLOW_SELF_REVIEWS = True GOOGLE_ANALYTICS_CREDENTIALS = private.GOOGLE_ANALYTICS_CREDENTIALS GOOGLE_API_CREDENTIALS = private.GOOGLE_API_CREDENTIALS MONOLITH_SERVER = 'https://monolith-dev.allizom.org' GEOIP_URL = 'https://geo-dev-marketplace.allizom.org' AWS_ACCESS_KEY_ID = private.AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY = private.AWS_SECRET_ACCESS_KEY AWS_STORAGE_BUCKET_NAME = private.AWS_STORAGE_BUCKET_NAME RAISE_ON_SIGNAL_ERROR = True API_THROTTLE = False NEWRELIC_ENABLED_LIST = ['dev1.addons.phx1.mozilla.com', 'dev2.addons.phx1.mozilla.com'] NEWRELIC_ENABLE = HOSTNAME in NEWRELIC_ENABLED_LIST AES_KEYS = private.AES_KEYS TASK_USER_ID = 4757633 SERVE_TMP_PATH = False
bsd-3-clause
6,948,503,791,888,337,000
28.86413
79
0.66697
false
2.949544
false
false
false
rackerlabs/qonos
qonos/openstack/common/rpc/dispatcher.py
1
5310
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Code for rpc message dispatching. Messages that come in have a version number associated with them. RPC API version numbers are in the form: Major.Minor For a given message with version X.Y, the receiver must be marked as able to handle messages of version A.B, where: A = X B >= Y The Major version number would be incremented for an almost completely new API. The Minor version number would be incremented for backwards compatible changes to an existing API. A backwards compatible change could be something like adding a new method, adding an argument to an existing method (but not requiring it), or changing the type for an existing argument (but still handling the old type as well). The conversion over to a versioned API must be done on both the client side and server side of the API at the same time. However, as the code stands today, there can be both versioned and unversioned APIs implemented in the same code base. EXAMPLES ======== Nova was the first project to use versioned rpc APIs. Consider the compute rpc API as an example. The client side is in nova/compute/rpcapi.py and the server side is in nova/compute/manager.py. Example 1) Adding a new method. ------------------------------- Adding a new method is a backwards compatible change. It should be added to nova/compute/manager.py, and RPC_API_VERSION should be bumped from X.Y to X.Y+1. On the client side, the new method in nova/compute/rpcapi.py should have a specific version specified to indicate the minimum API version that must be implemented for the method to be supported. For example:: def get_host_uptime(self, ctxt, host): topic = _compute_topic(self.topic, ctxt, host, None) return self.call(ctxt, self.make_msg('get_host_uptime'), topic, version='1.1') In this case, version '1.1' is the first version that supported the get_host_uptime() method. Example 2) Adding a new parameter. ---------------------------------- Adding a new parameter to an rpc method can be made backwards compatible. The RPC_API_VERSION on the server side (nova/compute/manager.py) should be bumped. The implementation of the method must not expect the parameter to be present.:: def some_remote_method(self, arg1, arg2, newarg=None): # The code needs to deal with newarg=None for cases # where an older client sends a message without it. pass On the client side, the same changes should be made as in example 1. The minimum version that supports the new parameter should be specified. """ from qonos.openstack.common.rpc import common as rpc_common class RpcDispatcher(object): """Dispatch rpc messages according to the requested API version. This class can be used as the top level 'manager' for a service. It contains a list of underlying managers that have an API_VERSION attribute. """ def __init__(self, callbacks): """Initialize the rpc dispatcher. :param callbacks: List of proxy objects that are an instance of a class with rpc methods exposed. Each proxy object should have an RPC_API_VERSION attribute. """ self.callbacks = callbacks super(RpcDispatcher, self).__init__() def dispatch(self, ctxt, version, method, **kwargs): """Dispatch a message based on a requested version. :param ctxt: The request context :param version: The requested API version from the incoming message :param method: The method requested to be called by the incoming message. :param kwargs: A dict of keyword arguments to be passed to the method. :returns: Whatever is returned by the underlying method that gets called. """ if not version: version = '1.0' had_compatible = False for proxyobj in self.callbacks: if hasattr(proxyobj, 'RPC_API_VERSION'): rpc_api_version = proxyobj.RPC_API_VERSION else: rpc_api_version = '1.0' is_compatible = rpc_common.version_is_compatible(rpc_api_version, version) had_compatible = had_compatible or is_compatible if not hasattr(proxyobj, method): continue if is_compatible: return getattr(proxyobj, method)(ctxt, **kwargs) if had_compatible: raise AttributeError("No such RPC function '%s'" % method) else: raise rpc_common.UnsupportedRpcVersion(version=version)
apache-2.0
3,698,796,998,904,787,500
37.478261
79
0.673446
false
4.366776
false
false
false
Mirantis/disk_perf_test_tool
wally/test_run_class.py
1
1980
from typing import List, Callable, Any, Dict, Optional, Set from concurrent.futures import ThreadPoolExecutor from cephlib.istorage import IStorage from cephlib.node import NodeInfo, IRPCNode from cephlib.ssh import ConnCreds from cephlib.storage_selectors import DevRolesConfig from .openstack_api import OSCreds, OSConnection from .config import Config from .result_classes import IWallyStorage class TestRun: """Test run information""" def __init__(self, config: Config, storage: IStorage, rstorage: IWallyStorage) -> None: # NodesInfo list self.nodes_info: Dict[str, NodeInfo] = {} self.ceph_master_node: Optional[IRPCNode] = None self.ceph_extra_args: Optional[str] = None # Nodes list self.nodes: List[IRPCNode] = [] self.build_meta: Dict[str,Any] = {} self.clear_calls_stack: List[Callable[['TestRun'], None]] = [] # openstack credentials self.os_creds: Optional[OSCreds] = None # type: ignore self.os_connection: Optional[OSConnection] = None # type: ignore self.rpc_code: bytes = None # type: ignore self.default_rpc_plugins: Dict[str, bytes] = None # type: ignore self.storage = storage self.rstorage = rstorage self.config = config self.sensors_run_on: Set[str] = set() self.os_spawned_nodes_ids: List[int] = None # type: ignore self.devs_locator: DevRolesConfig = [] def get_pool(self): return ThreadPoolExecutor(self.config.get('worker_pool_sz', 32)) def merge_node(self, creds: ConnCreds, roles: Set[str], **params) -> NodeInfo: info = NodeInfo(creds, roles, params) nid = info.node_id if nid in self.nodes_info: self.nodes_info[nid].roles.update(info.roles) self.nodes_info[nid].params.update(info.params) return self.nodes_info[nid] else: self.nodes_info[nid] = info return info
apache-2.0
7,912,155,741,855,254,000
35
91
0.64798
false
3.626374
true
false
false
vmahuli/contrail-controller
src/opserver/partition_handler.py
1
28794
#!/usr/bin/python from gevent import monkey monkey.patch_all() import logging import gevent from gevent.coros import BoundedSemaphore from kafka import KafkaClient, KeyedProducer, SimpleConsumer, common from uveserver import UVEServer import os import json import copy import traceback import uuid import struct import socket import discoveryclient.client as client from sandesh_common.vns.constants import ALARM_PARTITION_SERVICE_NAME from pysandesh.util import UTCTimestampUsec import select import redis from collections import namedtuple PartInfo = namedtuple("PartInfo",["ip_address","instance_id","acq_time","port"]) def sse_pack(d): """Pack data in SSE format""" buffer = '' for k in ['event','data']: if k in d.keys(): buffer += '%s: %s\n' % (k, d[k]) return buffer + '\n' class UveCacheProcessor(gevent.Greenlet): def __init__(self, logger, q, partitions): gevent.Greenlet.__init__(self) self._logger = logger self._q = q self._partkeys = {} for partno in range(0,partitions): self._partkeys[partno] = set() self._uvedb = {} def get_uve(self, key, filters=None, is_alarm=False): failures = False rsp = {} try: filters = filters or {} tfilter = filters.get('cfilt') ackfilter = filters.get('ackfilt') if is_alarm: tfilter = tfilter or {} # When returning only alarms, ignore non-alarm cfilt for k in tfilter.keys(): if k != "UVEAlarms": del tfilter[k] if len(tfilter) == 0: tfilter["UVEAlarms"] = set(["alarms"]) barekey = key.split(":",1)[1] table = key.split(":",1)[0] if table not in self._uvedb: return failures, rsp if barekey not in self._uvedb[table]: return failures, rsp for tkey,tval in self._uvedb[table][barekey].iteritems(): afilter_list = set() if tfilter is not None: if tkey not in tfilter: continue else: afilter_list = tfilter[tkey] if not tval: continue for akey, aval in tval.iteritems(): if len(afilter_list): if akey not in afilter_list: continue if ackfilter is not None and \ tkey == "UVEAlarms" and akey == "alarms": alarms = [] for alarm in aval: ack = "false" if "ack" in alarm: if alarm["ack"]: ack = "true" else: ack = "false" if ack == ackfilter: alarms.append(alarm) if not len(alarms): continue else: if not tkey in rsp: rsp[tkey] = {} rsp[tkey][akey] = alarms else: if not tkey in rsp: rsp[tkey] = {} rsp[tkey][akey] = aval except Exception as ex: template = "Exception {0} in uve cache proc. Arguments:\n{1!r}" messag = template.format(type(ex).__name__, ex.args) self._logger.error("%s : traceback %s" % \ (messag, traceback.format_exc())) return failures, rsp def _run(self): for telem in self._q: elem = telem['data'] if telem['event'] == 'clear': # remove all keys of this partition partno = elem['partition'] for key in self._partkeys[partno]: barekey = key.split(":",1)[1] table = key.split(":",1)[0] del self._uvedb[table][barekey] self._partkeys[partno].remove("%s:%s" % \ (table, barekey)) elif telem['event'] == 'sync' or telem['event'] == 'update': partno = elem['partition'] self._partkeys[partno].add(elem['key']) barekey = elem['key'].split(":",1)[1] table = elem['key'].split(":",1)[0] if table not in self._uvedb: self._uvedb[table] = {} if barekey not in self._uvedb[table]: self._uvedb[table][barekey] = {} if elem['type'] is None: # delete the entire UVE self._partkeys[partno].remove("%s:%s" % \ (table, barekey)) del self._uvedb[table][barekey] else: typ = elem['type'] if typ not in self._uvedb[table][barekey]: self._uvedb[table][barekey][typ] = None if elem['value'] is None: # remove one type of this UVE del self._uvedb[table][barekey][typ] else: self._uvedb[table][barekey][typ] = elem['value'] elif telem['event'] == 'stop': break else: pass class UveStreamPart(gevent.Greenlet): def __init__(self, partno, logger, q, pi, rpass, sse): gevent.Greenlet.__init__(self) self._logger = logger self._q = q self._pi = pi self._partno = partno self._rpass = rpass self._sse = sse def syncpart(self, redish): inst = self._pi.instance_id part = self._partno keys = list(redish.smembers("AGPARTKEYS:%s:%d" % (inst, part))) ppe = redish.pipeline() for key in keys: ppe.hgetall("AGPARTVALUES:%s:%d:%s" % (inst, part, key)) pperes = ppe.execute() idx=0 for res in pperes: for tk,tv in res.iteritems(): dt = {'partition':self._partno, 'key':keys[idx], 'type':tk, 'value':json.loads(tv)} if self._sse: msg = {'event': 'sync', 'data':json.dumps(dt)} self._q.put(sse_pack(msg)) else: msg = {'event': 'sync', 'data':dt} self._q.put(msg) idx += 1 def _run(self): lredis = None pb = None while True: try: lredis = redis.StrictRedis( host=self._pi.ip_address, port=self._pi.port, password=self._rpass, db=2) pb = lredis.pubsub() inst = self._pi.instance_id part = self._partno pb.subscribe('AGPARTPUB:%s:%d' % (inst, part)) self.syncpart(lredis) for message in pb.listen(): if message["type"] != "message": continue dataline = message["data"] try: elems = json.loads(dataline) except: self._logger.error("AggUVE Parsing failed: %s" % str(message)) continue else: self._logger.info("AggUVE loading: %s" % str(elems)) ppe = lredis.pipeline() for elem in elems: # This UVE was deleted if elem["type"] is None: ppe.exists("AGPARTVALUES:%s:%d:%s" % \ (inst, part, elem["key"])) else: ppe.hget("AGPARTVALUES:%s:%d:%s" % \ (inst, part, elem["key"]), elem["type"]) pperes = ppe.execute() idx = 0 for elem in elems: if elem["type"] is None: dt = {'partition':part, 'key':elem["key"], 'type':None} else: vjson = pperes[idx] if vjson is None: vdata = None else: vdata = json.loads(vjson) dt = {'partition':part, 'key':elem["key"], 'type':elem["type"], 'value':vdata} if self._sse: msg = {'event': 'update', 'data':json.dumps(dt)} self._q.put(sse_pack(msg)) else: msg = {'event': 'update', 'data':dt} self._q.put(msg) idx += 1 except gevent.GreenletExit: break except Exception as ex: template = "Exception {0} in uve stream proc. Arguments:\n{1!r}" messag = template.format(type(ex).__name__, ex.args) self._logger.error("%s : traceback %s" % \ (messag, traceback.format_exc())) lredis = None if pb is not None: pb.close() pb = None gevent.sleep(2) return None class UveStreamer(gevent.Greenlet): def __init__(self, logger, q, rfile, agp_cb, partitions, rpass): gevent.Greenlet.__init__(self) self._logger = logger self._q = q self._rfile = rfile self._agp_cb = agp_cb self._agp = {} self._parts = {} self._partitions = partitions self._rpass = rpass self._sse = True if self._rfile is None: self._sse = False def _run(self): inputs = [ self._rfile ] outputs = [ ] if self._sse: msg = {'event': 'init', 'data':\ json.dumps({'partitions':self._partitions})} self._q.put(sse_pack(msg)) else: msg = {'event': 'init', 'data':\ {'partitions':self._partitions}} self._q.put(msg) while True: try: if self._rfile is not None: readable, writable, exceptional = \ select.select(inputs, outputs, inputs, 1) if (readable or writable or exceptional): break else: gevent.sleep(1) newagp = self._agp_cb() set_new, set_old = set(newagp.keys()), set(self._agp.keys()) intersect = set_new.intersection(set_old) # deleted parts for elem in set_old - intersect: self.partition_stop(elem) # new parts for elem in set_new - intersect: self.partition_start(elem, newagp[elem]) # changed parts for elem in intersect: if self._agp[elem] != newagp[elem]: self.partition_stop(elem) self.partition_start(elem, newagp[elem]) self._agp = newagp except gevent.GreenletExit: break for part, pi in self._agp.iteritems(): self.partition_stop(part) if self._sse: msg = {'event': 'stop', 'data':json.dumps(None)} self._q.put(sse_pack(msg)) else: msg = {'event': 'stop', 'data':None} self._q.put(msg) def partition_start(self, partno, pi): self._logger.error("Starting agguve part %d using %s" %( partno, pi)) if self._sse: msg = {'event': 'clear', 'data':\ json.dumps({'partition':partno, 'acq_time':pi.acq_time})} self._q.put(sse_pack(msg)) else: msg = {'event': 'clear', 'data':\ {'partition':partno, 'acq_time':pi.acq_time}} self._q.put(msg) self._parts[partno] = UveStreamPart(partno, self._logger, self._q, pi, self._rpass, self._sse) self._parts[partno].start() def partition_stop(self, partno): self._logger.error("Stopping agguve part %d" % partno) self._parts[partno].kill() self._parts[partno].get() del self._parts[partno] class PartitionHandler(gevent.Greenlet): def __init__(self, brokers, group, topic, logger, limit): gevent.Greenlet.__init__(self) self._brokers = brokers self._group = group self._topic = topic self._logger = logger self._limit = limit self._uvedb = {} self._partoffset = 0 self._kfk = None def msg_handler(self, mlist): self._logger.info("%s Reading %s" % (self._topic, str(mlist))) return True def _run(self): pcount = 0 while True: try: self._logger.error("New KafkaClient %s" % self._topic) self._kfk = KafkaClient(self._brokers , "kc-" + self._topic) try: consumer = SimpleConsumer(self._kfk, self._group, self._topic, buffer_size = 4096*4, max_buffer_size=4096*32) #except: except Exception as ex: template = "Consumer Failure {0} occured. Arguments:\n{1!r}" messag = template.format(type(ex).__name__, ex.args) self._logger.error("Error: %s trace %s" % \ (messag, traceback.format_exc())) raise RuntimeError(messag) self._logger.error("Starting %s" % self._topic) # Find the offset of the last message that has been queued consumer.seek(-1,2) try: mi = consumer.get_message(timeout=0.1) consumer.commit() except common.OffsetOutOfRangeError: mi = None #import pdb; pdb.set_trace() self._logger.info("Last Queued for %s is %s" % \ (self._topic,str(mi))) # start reading from last previously processed message if mi != None: consumer.seek(0,1) else: consumer.seek(0,0) if self._limit: raise gevent.GreenletExit while True: try: mlist = consumer.get_messages(10,timeout=0.5) if not self.msg_handler(mlist): raise gevent.GreenletExit consumer.commit() pcount += len(mlist) except TypeError as ex: self._logger.error("Type Error: %s trace %s" % \ (str(ex.args), traceback.format_exc())) gevent.sleep(0.1) except common.FailedPayloadsError as ex: self._logger.error("Payload Error: %s" % str(ex.args)) gevent.sleep(0.1) except gevent.GreenletExit: break except AssertionError as ex: self._partoffset = ex break except Exception as ex: template = "An exception of type {0} occured. Arguments:\n{1!r}" messag = template.format(type(ex).__name__, ex.args) self._logger.error("%s : traceback %s" % \ (messag, traceback.format_exc())) self.stop_partition() gevent.sleep(2) self._logger.error("Stopping %s pcount %d" % (self._topic, pcount)) partdb = self.stop_partition() return self._partoffset, partdb class UveStreamProc(PartitionHandler): # Arguments: # # brokers : broker list for kafka bootstrap # partition : partition number # uve_topic : Topic to consume # logger : logging object to use # callback : Callback function for reporting the set of the UVEs # that may have changed for a given notification # rsc : Callback function to check on collector status # and get sync contents for new collectors # aginst : instance_id of alarmgen # rport : redis server port # disc : discovery client to publish to def __init__(self, brokers, partition, uve_topic, logger, callback, host_ip, rsc, aginst, rport, disc = None): super(UveStreamProc, self).__init__(brokers, "workers", uve_topic, logger, False) self._uvedb = {} self._uvein = {} self._callback = callback self._partno = partition self._host_ip = host_ip self._ip_code, = struct.unpack('>I', socket.inet_pton( socket.AF_INET, host_ip)) self.disc_rset = set() self._resource_cb = rsc self._aginst = aginst self._disc = disc self._acq_time = UTCTimestampUsec() self._rport = rport def acq_time(self): return self._acq_time def resource_check(self, msgs): ''' This function compares the known collectors with the list from discovery, and syncs UVE keys accordingly ''' newset , coll_delete, chg_res = self._resource_cb(self._partno, self.disc_rset, msgs) for coll in coll_delete: self._logger.error("Part %d lost collector %s" % (self._partno, coll)) self.stop_partition(coll) if len(chg_res): self.start_partition(chg_res) self.disc_rset = newset if self._disc: data = { 'instance-id' : self._aginst, 'partition' : str(self._partno), 'ip-address': self._host_ip, 'acq-time': str(self._acq_time), 'port':str(self._rport)} self._disc.publish(ALARM_PARTITION_SERVICE_NAME, data) def stop_partition(self, kcoll=None): clist = [] if not kcoll: clist = self._uvedb.keys() # If all collectors are being cleared, clear resoures too self.disc_rset = set() if self._disc: # TODO: Unpublish instead of setting acq-time to 0 data = { 'instance-id' : self._aginst, 'partition' : str(self._partno), 'ip-address': self._host_ip, 'acq-time': "0", 'port':str(self._rport)} self._disc.publish(ALARM_PARTITION_SERVICE_NAME, data) else: clist = [kcoll] self._logger.error("Stopping part %d collectors %s" % \ (self._partno,clist)) partdb = {} chg = {} for coll in clist: partdb[coll] = {} for gen in self._uvedb[coll].keys(): partdb[coll][gen] = {} for tab in self._uvedb[coll][gen].keys(): for rkey in self._uvedb[coll][gen][tab].keys(): uk = tab + ":" + rkey chg[uk] = None partdb[coll][gen][uk] = \ set(self._uvedb[coll][gen][tab][rkey].keys()) del self._uvedb[coll] self._logger.error("Stopping part %d UVEs %s" % \ (self._partno,str(chg.keys()))) self._callback(self._partno, chg) return partdb def start_partition(self, cbdb): ''' This function loads the initial UVE database. for the partition ''' self._logger.error("Starting part %d collectors %s" % \ (self._partno, str(cbdb.keys()))) uves = {} for kcoll,coll in cbdb.iteritems(): self._uvedb[kcoll] = {} for kgen,gen in coll.iteritems(): self._uvedb[kcoll][kgen] = {} for kk in gen.keys(): tabl = kk.split(":",1) tab = tabl[0] rkey = tabl[1] if not tab in self._uvedb[kcoll][kgen]: self._uvedb[kcoll][kgen][tab] = {} self._uvedb[kcoll][kgen][tab][rkey] = {} uves[kk] = {} for typ, contents in gen[kk].iteritems(): self._uvedb[kcoll][kgen][tab][rkey][typ] = {} self._uvedb[kcoll][kgen][tab][rkey][typ]["c"] = 0 self._uvedb[kcoll][kgen][tab][rkey][typ]["u"] = \ uuid.uuid1(self._ip_code) uves[kk][typ] = contents self._logger.error("Starting part %d UVEs %s" % \ (self._partno, str(uves.keys()))) self._callback(self._partno, uves) def contents(self): return self._uvedb def stats(self): ''' Return the UVE incoming stats collected over the last time period for this partition Also, the stats should be cleared to prepare for the next period of collection. ''' ret_in = copy.deepcopy(self._uvein) self._uvein = {} return ret_in def msg_handler(self, mlist): self.resource_check(mlist) for mm in mlist: if mm is None: continue self._logger.debug("%s Reading offset %d" % \ (self._topic, mm.offset)) if not self.msg_handler_single(mm): self._logger.info("%s could not handle %s" % \ (self._topic, str(mm))) return False return True def msg_handler_single(self, om): self._partoffset = om.offset chg = {} try: uv = json.loads(om.message.value) coll = uv["coll"] gen = uv["gen"] if not self._uvedb.has_key(coll): # This partition is not synced yet. # Ignore this message self._logger.debug("%s Ignoring UVE %s" % (self._topic, str(om))) return True if not self._uvedb[coll].has_key(gen): self._uvedb[coll][gen] = {} if (uv["message"] == "UVEUpdate"): tabl = uv["key"].split(":",1) tab = tabl[0] rkey = tabl[1] if tab not in self._uvedb[coll][gen]: self._uvedb[coll][gen][tab] = {} if not rkey in self._uvedb[coll][gen][tab]: self._uvedb[coll][gen][tab][rkey] = {} removed = False # uv["type"] and uv["value"] can be decoded as follows: # uv["type"] can be one of the following: # - None # All Types under this UVE are deleted # uv["value"] will not be present # (this option is only for agg UVE updates) # - "<Struct>" # uv["value"] refers to this struct # uv["value"] can be one of the following: # - None # This Type has been deleted. # - {} # The Type has a value, which is # not available in this message. # (this option is only for raw UVE updates) # - {<Value>} # The Value of the Type # (this option is only for agg UVE updates) if uv["type"] is None: # TODO: Handling of delete UVE case return False if uv["value"] is None: if uv["type"] in self._uvedb[coll][gen][tab][rkey]: del self._uvedb[coll][gen][tab][rkey][uv["type"]] if not len(self._uvedb[coll][gen][tab][rkey]): del self._uvedb[coll][gen][tab][rkey] removed = True if not removed: if uv["type"] in self._uvedb[coll][gen][tab][rkey]: self._uvedb[coll][gen][tab][rkey][uv["type"]]["c"] +=1 else: self._uvedb[coll][gen][tab][rkey][uv["type"]] = {} self._uvedb[coll][gen][tab][rkey][uv["type"]]["c"] = 1 self._uvedb[coll][gen][tab][rkey][uv["type"]]["u"] = \ uuid.uuid1(self._ip_code) chg[uv["key"]] = { uv["type"] : uv["value"] } # Record stats on the input UVE Notifications if not self._uvein.has_key(tab): self._uvein[tab] = {} if not self._uvein[tab].has_key(coll): self._uvein[tab][coll] = {} if not self._uvein[tab][coll].has_key(gen): self._uvein[tab][coll][gen] = {} if not self._uvein[tab][coll][gen].has_key(uv["type"]): self._uvein[tab][coll][gen][uv["type"]] = 1 else: self._uvein[tab][coll][gen][uv["type"]] += 1 else: # Record stats on UVE Keys being processed for tab in self._uvedb[coll][gen].keys(): for rkey in self._uvedb[coll][gen][tab].keys(): uk = tab + ":" + rkey # when a generator is delelted, we need to # notify for *ALL* its UVEs chg[uk] = None del self._uvedb[coll][gen] except Exception as ex: template = "An exception of type {0} in uve proc . Arguments:\n{1!r}" messag = template.format(type(ex).__name__, ex.args) self._logger.info("%s" % messag) return False else: self._callback(self._partno, chg) return True if __name__ == '__main__': logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') workers = {} brokers = "localhost:9092,localhost:9093,localhost:9094" group = "workers" kafka = KafkaClient(brokers,str(os.getpid())) cons = SimpleConsumer(kafka, group, "ctrl") cons.provide_partition_info() print "Starting control" end_ready = False while end_ready == False: try: while True: part, mmm = cons.get_message(timeout=None) mm = mmm.message print "Consumed ctrl " + str(mm) if mm.value == "start": if workers.has_key(mm.key): print "Dup partition %s" % mm.key raise ValueError else: ph = UveStreamProc(brokers, int(mm.key), "uve-" + mm.key, "alarm-x" + mm.key, logging) ph.start() workers[int(mm.key)] = ph elif mm.value == "stop": #import pdb; pdb.set_trace() if workers.has_key(int(mm.key)): ph = workers[int(mm.key)] gevent.kill(ph) res,db = ph.get() print "Returned " + str(res) print "State :" for k,v in db.iteritems(): print "%s -> %s" % (k,str(v)) del workers[int(mm.key)] else: end_ready = True cons.commit() gevent.sleep(2) break except TypeError: gevent.sleep(0.1) except common.FailedPayloadsError as ex: print "Payload Error: " + str(ex.args) gevent.sleep(0.1) lw=[] for key, value in workers.iteritems(): gevent.kill(value) lw.append(value) gevent.joinall(lw) print "Ending Consumers"
apache-2.0
-5,221,414,559,799,287,000
38.661157
129
0.44992
false
4.194319
false
false
false
edesky/text_validator
lib/validate.py
1
1509
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import argparse import json import math parser = argparse.ArgumentParser() parser.add_argument("--text", required=True, help="Input text") parser.add_argument("--short", action='store_true') args = parser.parse_args() input_text = args.text.decode('utf8') VALID_CHARS = u'qwertzuiopasdfghjklyxcvbnm1234567890QWERTZUIOPASDFGHJKLYXCVBNM ?:.,;-=/+ěščřžýáíéĚŠČŘŽÝÁÍÉůúŇ' def chars_score(text): known_cnt = 0 for char in text: if char in VALID_CHARS: known_cnt += 1 return float(known_cnt)/max(len(text), 1) def length_score(text): cnt = 0 for char in text: if char in VALID_CHARS: cnt += 1 return min(math.log(max(cnt, 1), 1000), 1.0) # TODO: add another functions here # def xyz_score(text): # text magic here # return 0.5 def compute(scores): total = 0 cnt = 0 for score in scores: cnt += 1 total = (total * (cnt-1) + score['value']) / cnt; return {'score': total, 'parts': scores} scores = [] scores.append({'name': 'chars_score', 'value': chars_score(input_text)}) scores.append({'name': 'length_score', 'value': length_score(input_text)}) # TODO: add another functions here # scores.append({'name': 'xyz_score', 'value': xyz_score(args.text)}) total_score = compute(scores) if args.short: print(total_score['score']) else: print(json.dumps(total_score, sort_keys=True, indent=4))
mit
4,563,589,001,996,884,000
25.571429
110
0.649866
false
2.95825
false
false
false
Alberto-Beralix/Beralix
i386-squashfs-root/usr/share/system-config-printer/errordialogs.py
1
3111
#!/usr/bin/python ## system-config-printer ## Copyright (C) 2006, 2007, 2008, 2010 Red Hat, Inc. ## Authors: ## Florian Festi <ffesti@redhat.com> ## Tim Waugh <twaugh@redhat.com> ## 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 2 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 cups import gtk from gettext import gettext as _ def show_dialog (title, text, type, parent=None): dialog = gtk.MessageDialog (parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, type, gtk.BUTTONS_OK, title) dialog.format_secondary_text (text) dialog.run () dialog.destroy () def show_info_dialog (title, text, parent=None): return show_dialog (title, text, gtk.MESSAGE_INFO, parent=parent) def show_error_dialog (title, text, parent=None): return show_dialog (title, text, gtk.MESSAGE_ERROR, parent=parent) def show_IPP_Error(exception, message, parent=None): if exception == 0: # In this case, the user has canceled an authentication dialog. return elif exception == cups.IPP_SERVICE_UNAVAILABLE: # In this case, the user has canceled a retry dialog. return else: title = _("CUPS server error") text = (_("There was an error during the CUPS " "operation: '%s'.")) % message show_error_dialog (title, text, parent) def show_HTTP_Error(status, parent=None): if (status == cups.HTTP_UNAUTHORIZED or status == cups.HTTP_FORBIDDEN): title = _('Not authorized') text = (_('The password may be incorrect, or the ' 'server may be configured to deny ' 'remote administration.')) else: title = _('CUPS server error') if status == cups.HTTP_BAD_REQUEST: msg = _("Bad request") elif status == cups.HTTP_NOT_FOUND: msg = _("Not found") elif status == cups.HTTP_REQUEST_TIMEOUT: msg = _("Request timeout") elif status == cups.HTTP_UPGRADE_REQUIRED: msg = _("Upgrade required") elif status == cups.HTTP_SERVER_ERROR: msg = _("Server error") elif status == -1: msg = _("Not connected") else: msg = _("status %s") % status text = _("There was an HTTP error: %s.") % msg show_error_dialog (title, text, parent)
gpl-3.0
8,152,813,570,208,546,000
35.6
82
0.6072
false
3.998715
false
false
false
drelu/SAGA-Hadoop
hadoop1/launcher.py
1
2591
#!/usr/bin/env python import time import saga import os, sys import subprocess import pdb import logging logging.basicConfig(level=logging.ERROR) def main(): try: # create a job service for Futuregrid's 'india' PBS cluster js = saga.job.Service("pbs+ssh://india") #js = saga.job.Service("fork://localhost") # describe our job jd = saga.job.Description() # resource requirements jd.total_cpu_count = 16 # environment, executable & arguments executable = os.path.join(os.getcwd(), "bootstrap_hadoop.py") logging.debug("Run %s"%executable) jd.executable = executable jd.arguments = [] # output options jd.output = "hadoop_job.stdout" jd.error = "hadoop_job.stderr" jd.working_directory=os.getcwd() # create the job (state: New) myjob = js.create_job(jd) print "Starting Hadoop bootstrap job...\n" # run the job (submit the job to PBS) myjob.run() jobid = myjob.get_id() print "**** Job ID : %s" % (jobid) print "**** Job State : %s" % (myjob.get_state()) while True: state = myjob.get_state() if state=="Running": if os.path.exists("work/started"): get_hadoop_config_data(str(jobid)) break time.sleep(3) except Exception, ex: print "An error occured: %s" % (str(ex)) def get_hadoop_config_data(jobid): pbs_id = jobid[jobid.find("-")+2:len(jobid)-1] nodes = subprocess.check_output(["qstat", "-f", pbs_id]) hosts = "empty" for i in nodes.split("\n"): if i.find("exec_host")>0: hosts = i[i.find("=")+1:].strip() hadoop_home=os.path.join(os.getcwd(), "work/hadoop-1.0.0") print "HADOOP installation directory: %s"%hadoop_home print "Allocated Resources for Hadoop cluster: " + hosts print "HDFS Web Interface: http://%s:50070"% hosts[:hosts.find("/")] print "\nTo use Hadoop set HADOOP_CONF_DIR: " print "export HADOOP_CONF_DIR=%s"%(os.path.join(os.getcwd(), "work", get_most_current_job(), "conf")) print "%s/bin/hadoop dfsadmin -report"%hadoop_home print "" def get_most_current_job(): dir = "work" files = os.listdir(dir) max = None for i in files: if i.startswith("hadoop-conf"): t = os.path.getctime(os.path.join(dir,i)) if max == None or t>max[0]: max = (t, i) return max[1] if __name__ == "__main__": main()
apache-2.0
944,839,436,700,455,200
29.482353
106
0.564261
false
3.351876
false
false
false
heilaaks/snippy
tests/lib/helper.py
1
7104
# -*- coding: utf-8 -*- # # SPDX-License-Identifier: AGPL-3.0-or-later # # snippy - software development and maintenance notes manager. # Copyright 2017-2020 Heikki J. Laaksonen <laaksonen.heikki.j@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """helper: Generic helpers testing.""" from __future__ import print_function import io import os.path import re import sys import json import pkg_resources from jsonschema import Draft7Validator, RefResolver class Helper(object): """Generic helpers testing. This class intentionally copies some of the implementation from the production code. The purpose is to avoid dependencies in this module to be able to import this module anywhere. """ EXPORT_TIME = '2018-02-02T02:02:02.000001+00:00' IMPORT_TIME = '2018-03-02T02:02:02.000001+00:00' EXPORT_TEMPLATE = '2017-10-14T19:56:31.000001+00:00' DB_SQLITE = 'sqlite' DB_POSTGRESQL = 'postgresql' DB_COCKROACHDB = 'cockroachdb' DB_IN_MEMORY = 'in-memory' STORAGES = (DB_SQLITE, DB_POSTGRESQL, DB_COCKROACHDB, DB_IN_MEMORY) COLOR_OK = '\033[32m' COLOR_END = '\033[0m' # All resource attributes that can be sent in HTTP request. REQUEST_ATTRIBUTES = ( 'data', 'brief', 'description', 'name', 'groups', 'tags', 'links', 'source', 'versions', 'languages', 'filename' ) RE_MATCH_ANSI_ESCAPE_SEQUENCES = re.compile(r''' \x1b[^m]*m # Match all ANSI escape sequences. ''', re.VERBOSE) RE_MATCH_LEADING_WHITEPSACES = re.compile(r''' \n\s+ # Match newline and all leading whitespaces after it. ''', re.VERBOSE) @classmethod def read_template(cls, filename): """Get default content template in text format. The returned template must be in the same format where external editor like vi gets the default template. This means that all the tags are removed and the group tag is replaced with 'default' group. Args: filename (str): Template filename as stored in data/templates. Returns: str: Empty template in the same format as for external editor. """ template = cls._read_resource('data/templates', filename) template = re.sub(r''' <groups> # Match groups tag. ''', 'default', template, flags=re.VERBOSE) template = re.sub(r''' [<]\S+[>] # Match any tag in the template. ''', '', template, flags=re.VERBOSE) # In case of the solution template, there is a <data> tag that leaves # empty fist line. Since all templates start from the first line, the # whitespaces can be removed from left of the string. template = template.lstrip() return template @classmethod def read_completion(cls, filename): """Get shell completion script. Args filename (str): Name of the shell completion file. """ return cls._read_resource('data/completion', filename) @staticmethod def remove_ansi(message): """Remove all ANSI escape codes from given string. Args: message (str): Message which ANSI escape codes are removed. Returns: str: Same message but without ANSI escape sequences. """ return Helper.RE_MATCH_ANSI_ESCAPE_SEQUENCES.sub('', message) @classmethod def get_schema_validator(cls): """Get JSON schema validator for REST API response. Returns: obj: Jsonschema draft7 validator. """ response_resource = json.loads(cls._read_resource('data/server/openapi/schema', 'responseresource.json')) response_collection_get = json.loads(cls._read_resource('data/server/openapi/schema', 'responsecollectionget.json')) response_collection_post = json.loads(cls._read_resource('data/server/openapi/schema', 'responsecollectionpost.json')) response_groups = json.loads(cls._read_resource('data/server/openapi/schema', 'responsegroups.json')) response_tags = json.loads(cls._read_resource('data/server/openapi/schema', 'responsetags.json')) response_errors = json.loads(cls._read_resource('data/server/openapi/schema', 'responseerrors.json')) response_hello = json.loads(cls._read_resource('data/server/openapi/schema', 'responsehello.json')) schema = { 'oneOf': [ response_collection_get, response_collection_post, response_groups, response_tags, response_errors, response_hello, response_resource ] } filepath = pkg_resources.resource_filename('snippy', 'data/server/openapi/schema/') if not os.path.isdir(filepath): print('NOK: cannot run test because server api response schema base uri is not accessible: {}'.format(filepath)) sys.exit(1) server_schema_base_uri = 'file:' + filepath Draft7Validator.check_schema(schema) resolver = RefResolver(base_uri=server_schema_base_uri, referrer=schema) validator = Draft7Validator(schema, resolver=resolver, format_checker=None) return validator @staticmethod def _read_resource(path, filename): """Read resource file. Args: path (str): Relative path under snippy project. filename (str): Resource filename. Returns: str: File read into a string. """ filename = os.path.join(pkg_resources.resource_filename('snippy', path), filename) if not os.path.isfile(filename): print('NOK: cannot run tests because snippy resource file is not accessible: {}'.format(filename)) sys.exit(1) resource_file = '' with io.open(filename, encoding='utf-8') as infile: resource_file = infile.read() return resource_file class Classproperty(object): # pylint: disable=too-few-public-methods """Implement classproperty. Implement decorator that mimics object property. See [1] for more details. [1] https://stackoverflow.com/a/3203659 """ def __init__(self, getter): self._getter = getter def __get__(self, _, owner): """Get property of a class.""" return self._getter(owner)
agpl-3.0
-3,998,784,855,587,372,000
32.668246
126
0.634713
false
4.047863
false
false
false
leshchevds/ganeti
lib/ssh.py
1
43027
# # # Copyright (C) 2006, 2007, 2010, 2011 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Module encapsulating ssh functionality. """ import logging import os import shutil import tempfile from collections import namedtuple from functools import partial from ganeti import utils from ganeti import errors from ganeti import constants from ganeti import netutils from ganeti import pathutils from ganeti import vcluster from ganeti import compat from ganeti import serializer from ganeti import ssconf def GetUserFiles(user, mkdir=False, dircheck=True, kind=constants.SSHK_DSA, _homedir_fn=None): """Return the paths of a user's SSH files. @type user: string @param user: Username @type mkdir: bool @param mkdir: Whether to create ".ssh" directory if it doesn't exist @type dircheck: bool @param dircheck: Whether to check if ".ssh" directory exists @type kind: string @param kind: One of L{constants.SSHK_ALL} @rtype: tuple; (string, string, string) @return: Tuple containing three file system paths; the private SSH key file, the public SSH key file and the user's C{authorized_keys} file @raise errors.OpExecError: When home directory of the user can not be determined @raise errors.OpExecError: Regardless of the C{mkdir} parameters, this exception is raised if C{~$user/.ssh} is not a directory and C{dircheck} is set to C{True} """ if _homedir_fn is None: _homedir_fn = utils.GetHomeDir user_dir = _homedir_fn(user) if not user_dir: raise errors.OpExecError("Cannot resolve home of user '%s'" % user) if kind == constants.SSHK_DSA: suffix = "dsa" elif kind == constants.SSHK_RSA: suffix = "rsa" elif kind == constants.SSHK_ECDSA: suffix = "ecdsa" else: raise errors.ProgrammerError("Unknown SSH key kind '%s'" % kind) ssh_dir = utils.PathJoin(user_dir, ".ssh") if mkdir: utils.EnsureDirs([(ssh_dir, constants.SECURE_DIR_MODE)]) elif dircheck and not os.path.isdir(ssh_dir): raise errors.OpExecError("Path %s is not a directory" % ssh_dir) return [utils.PathJoin(ssh_dir, base) for base in ["id_%s" % suffix, "id_%s.pub" % suffix, "authorized_keys"]] def GetAllUserFiles(user, mkdir=False, dircheck=True, _homedir_fn=None): """Wrapper over L{GetUserFiles} to retrieve files for all SSH key types. See L{GetUserFiles} for details. @rtype: tuple; (string, dict with string as key, tuple of (string, string) as value) """ helper = compat.partial(GetUserFiles, user, mkdir=mkdir, dircheck=dircheck, _homedir_fn=_homedir_fn) result = [(kind, helper(kind=kind)) for kind in constants.SSHK_ALL] authorized_keys = [i for (_, (_, _, i)) in result] assert len(frozenset(authorized_keys)) == 1, \ "Different paths for authorized_keys were returned" return (authorized_keys[0], dict((kind, (privkey, pubkey)) for (kind, (privkey, pubkey, _)) in result)) def _SplitSshKey(key): """Splits a line for SSH's C{authorized_keys} file. If the line has no options (e.g. no C{command="..."}), only the significant parts, the key type and its hash, are used. Otherwise the whole line is used (split at whitespace). @type key: string @param key: Key line @rtype: tuple """ parts = key.split() if parts and parts[0] in constants.SSHAK_ALL: # If the key has no options in front of it, we only want the significant # fields return (False, parts[:2]) else: # Can't properly split the line, so use everything return (True, parts) def AddAuthorizedKeys(file_obj, keys): """Adds a list of SSH public key to an authorized_keys file. @type file_obj: str or file handle @param file_obj: path to authorized_keys file @type keys: list of str @param keys: list of strings containing keys """ key_field_list = [(key, _SplitSshKey(key)) for key in keys] if isinstance(file_obj, basestring): f = open(file_obj, "a+") else: f = file_obj try: nl = True for line in f: # Ignore whitespace changes line_key = _SplitSshKey(line) key_field_list[:] = [(key, split_key) for (key, split_key) in key_field_list if split_key != line_key] nl = line.endswith("\n") else: if not nl: f.write("\n") for (key, _) in key_field_list: f.write(key.rstrip("\r\n")) f.write("\n") f.flush() finally: f.close() def HasAuthorizedKey(file_obj, key): """Check if a particular key is in the 'authorized_keys' file. @type file_obj: str or file handle @param file_obj: path to authorized_keys file @type key: str @param key: string containing key """ key_fields = _SplitSshKey(key) if isinstance(file_obj, basestring): f = open(file_obj, "r") else: f = file_obj try: for line in f: # Ignore whitespace changes line_key = _SplitSshKey(line) if line_key == key_fields: return True finally: f.close() return False def CheckForMultipleKeys(file_obj, node_names): """Check if there is at most one key per host in 'authorized_keys' file. @type file_obj: str or file handle @param file_obj: path to authorized_keys file @type node_names: list of str @param node_names: list of names of nodes of the cluster @returns: a dictionary with hostnames which occur more than once """ if isinstance(file_obj, basestring): f = open(file_obj, "r") else: f = file_obj occurrences = {} try: index = 0 for line in f: index += 1 if line.startswith("#"): continue chunks = line.split() # find the chunk with user@hostname user_hostname = [chunk.strip() for chunk in chunks if "@" in chunk][0] if not user_hostname in occurrences: occurrences[user_hostname] = [] occurrences[user_hostname].append(index) finally: f.close() bad_occurrences = {} for user_hostname, occ in occurrences.items(): _, hostname = user_hostname.split("@") if hostname in node_names and len(occ) > 1: bad_occurrences[user_hostname] = occ return bad_occurrences def AddAuthorizedKey(file_obj, key): """Adds an SSH public key to an authorized_keys file. @type file_obj: str or file handle @param file_obj: path to authorized_keys file @type key: str @param key: string containing key """ AddAuthorizedKeys(file_obj, [key]) def RemoveAuthorizedKeys(file_name, keys): """Removes public SSH keys from an authorized_keys file. @type file_name: str @param file_name: path to authorized_keys file @type keys: list of str @param keys: list of strings containing keys """ key_field_list = [_SplitSshKey(key) for key in keys] fd, tmpname = tempfile.mkstemp(dir=os.path.dirname(file_name)) try: out = os.fdopen(fd, "w") try: f = open(file_name, "r") try: for line in f: # Ignore whitespace changes while comparing lines if _SplitSshKey(line) not in key_field_list: out.write(line) out.flush() os.rename(tmpname, file_name) finally: f.close() finally: out.close() except: utils.RemoveFile(tmpname) raise def RemoveAuthorizedKey(file_name, key): """Removes an SSH public key from an authorized_keys file. @type file_name: str @param file_name: path to authorized_keys file @type key: str @param key: string containing key """ RemoveAuthorizedKeys(file_name, [key]) def _AddPublicKeyProcessLine(new_uuid, new_key, line_uuid, line_key, found): """Processes one line of the public key file when adding a key. This is a sub function that can be called within the C{_ManipulatePublicKeyFile} function. It processes one line of the public key file, checks if this line contains the key to add already and if so, notes the occurrence in the return value. @type new_uuid: string @param new_uuid: the node UUID of the node whose key is added @type new_key: string @param new_key: the SSH key to be added @type line_uuid: the UUID of the node whose line in the public key file is processed in this function call @param line_key: the SSH key of the node whose line in the public key file is processed in this function call @type found: boolean @param found: whether or not the (UUID, key) pair of the node whose key is being added was found in the public key file already. @rtype: (boolean, string) @return: a possibly updated value of C{found} and the processed line """ if line_uuid == new_uuid and line_key == new_key: logging.debug("SSH key of node '%s' already in key file.", new_uuid) found = True return (found, "%s %s\n" % (line_uuid, line_key)) def _AddPublicKeyElse(new_uuid, new_key): """Adds a new SSH key to the key file if it did not exist already. This is an auxiliary function for C{_ManipulatePublicKeyFile} which is carried out when a new key is added to the public key file and after processing the whole file, we found out that the key does not exist in the file yet but needs to be appended at the end. @type new_uuid: string @param new_uuid: the UUID of the node whose key is added @type new_key: string @param new_key: the SSH key to be added @rtype: string @return: a new line to be added to the file """ return "%s %s\n" % (new_uuid, new_key) def _RemovePublicKeyProcessLine( target_uuid, _target_key, line_uuid, line_key, found): """Processes a line in the public key file when aiming for removing a key. This is an auxiliary function for C{_ManipulatePublicKeyFile} when we are removing a key from the public key file. This particular function only checks if the current line contains the UUID of the node in question and writes the line to the temporary file otherwise. @type target_uuid: string @param target_uuid: UUID of the node whose key is being removed @type _target_key: string @param _target_key: SSH key of the node (not used) @type line_uuid: string @param line_uuid: UUID of the node whose line is processed in this call @type line_key: string @param line_key: SSH key of the nodes whose line is processed in this call @type found: boolean @param found: whether or not the UUID was already found. @rtype: (boolean, string) @return: a tuple, indicating if the target line was found and the processed line; the line is 'None', if the original line is removed """ if line_uuid != target_uuid: return (found, "%s %s\n" % (line_uuid, line_key)) else: return (True, None) def _RemovePublicKeyElse( target_uuid, _target_key): """Logs when we tried to remove a key that does not exist. This is an auxiliary function for C{_ManipulatePublicKeyFile} which is run after we have processed the complete public key file and did not find the key to be removed. @type target_uuid: string @param target_uuid: the UUID of the node whose key was supposed to be removed @type _target_key: string @param _target_key: the key of the node which was supposed to be removed (not used) @rtype: string @return: in this case, always None """ logging.debug("Trying to remove key of node '%s' which is not in list" " of public keys.", target_uuid) return None def _ReplaceNameByUuidProcessLine( node_name, _key, line_identifier, line_key, found, node_uuid=None): """Replaces a node's name with its UUID on a matching line in the key file. This is an auxiliary function for C{_ManipulatePublicKeyFile} which processes a line of the ganeti public key file. If the line in question matches the node's name, the name will be replaced by the node's UUID. @type node_name: string @param node_name: name of the node to be replaced by the UUID @type _key: string @param _key: SSH key of the node (not used) @type line_identifier: string @param line_identifier: an identifier of a node in a line of the public key file. This can be either a node name or a node UUID, depending on if it got replaced already or not. @type line_key: string @param line_key: SSH key of the node whose line is processed @type found: boolean @param found: whether or not the line matches the node's name @type node_uuid: string @param node_uuid: the node's UUID which will replace the node name @rtype: (boolean, string) @return: a tuple indicating whether the target line was found and the processed line """ if node_name == line_identifier: return (True, "%s %s\n" % (node_uuid, line_key)) else: return (found, "%s %s\n" % (line_identifier, line_key)) def _ReplaceNameByUuidElse( node_uuid, node_name, _key): """Logs a debug message when we try to replace a key that is not there. This is an implementation of the auxiliary C{process_else_fn} function for the C{_ManipulatePubKeyFile} function when we use it to replace a line in the public key file that is indexed by the node's name instead of the node's UUID. @type node_uuid: string @param node_uuid: the node's UUID @type node_name: string @param node_name: the node's UUID @type _key: string (not used) @param _key: the node's SSH key (not used) @rtype: string @return: in this case, always None """ logging.debug("Trying to replace node name '%s' with UUID '%s', but" " no line with that name was found.", node_name, node_uuid) return None def _ParseKeyLine(line, error_fn): """Parses a line of the public key file. @type line: string @param line: line of the public key file @type error_fn: function @param error_fn: function to process error messages @rtype: tuple (string, string) @return: a tuple containing the UUID of the node and a string containing the SSH key and possible more parameters for the key """ if len(line.rstrip()) == 0: return (None, None) chunks = line.split(" ") if len(chunks) < 2: raise error_fn("Error parsing public SSH key file. Line: '%s'" % line) uuid = chunks[0] key = " ".join(chunks[1:]).rstrip() return (uuid, key) def _ManipulatePubKeyFile(target_identifier, target_key, key_file=pathutils.SSH_PUB_KEYS, error_fn=errors.ProgrammerError, process_line_fn=None, process_else_fn=None): """Manipulates the list of public SSH keys of the cluster. This is a general function to manipulate the public key file. It needs two auxiliary functions C{process_line_fn} and C{process_else_fn} to work. Generally, the public key file is processed as follows: 1) The function processes each line of the original ganeti public key file, applies the C{process_line_fn} function on it, which returns a possibly manipulated line and an indicator whether the line in question was found. If a line is returned, it is added to a list of lines for later writing to the file. 2) If all lines are processed and the 'found' variable is False, the seconds auxiliary function C{process_else_fn} is called to possibly add more lines to the list of lines. 3) Finally, the list of lines is assembled to a string and written atomically to the public key file, thereby overriding it. If the public key file does not exist, we create it. This is necessary for a smooth transition after an upgrade. @type target_identifier: str @param target_identifier: identifier of the node whose key is added; in most cases this is the node's UUID, but in some it is the node's host name @type target_key: str @param target_key: string containing a public SSH key (a complete line possibly including more parameters than just the key) @type key_file: str @param key_file: filename of the file of public node keys (optional parameter for testing) @type error_fn: function @param error_fn: Function that returns an exception, used to customize exception types depending on the calling context @type process_line_fn: function @param process_line_fn: function to process one line of the public key file @type process_else_fn: function @param process_else_fn: function to be called if no line of the key file matches the target uuid """ assert process_else_fn is not None assert process_line_fn is not None old_lines = [] f_orig = None if os.path.exists(key_file): try: f_orig = open(key_file, "r") old_lines = f_orig.readlines() finally: f_orig.close() else: try: f_orig = open(key_file, "w") f_orig.close() except IOError as e: raise errors.SshUpdateError("Cannot create public key file: %s" % e) found = False new_lines = [] for line in old_lines: (uuid, key) = _ParseKeyLine(line, error_fn) if not uuid: continue (new_found, new_line) = process_line_fn(target_identifier, target_key, uuid, key, found) if new_found: found = True if new_line is not None: new_lines.append(new_line) if not found: new_line = process_else_fn(target_identifier, target_key) if new_line is not None: new_lines.append(new_line) new_file_content = "".join(new_lines) utils.WriteFile(key_file, data=new_file_content) def AddPublicKey(new_uuid, new_key, key_file=pathutils.SSH_PUB_KEYS, error_fn=errors.ProgrammerError): """Adds a new key to the list of public keys. @see: _ManipulatePubKeyFile for parameter descriptions. """ _ManipulatePubKeyFile(new_uuid, new_key, key_file=key_file, process_line_fn=_AddPublicKeyProcessLine, process_else_fn=_AddPublicKeyElse, error_fn=error_fn) def RemovePublicKey(target_uuid, key_file=pathutils.SSH_PUB_KEYS, error_fn=errors.ProgrammerError): """Removes a key from the list of public keys. @see: _ManipulatePubKeyFile for parameter descriptions. """ _ManipulatePubKeyFile(target_uuid, None, key_file=key_file, process_line_fn=_RemovePublicKeyProcessLine, process_else_fn=_RemovePublicKeyElse, error_fn=error_fn) def ReplaceNameByUuid(node_uuid, node_name, key_file=pathutils.SSH_PUB_KEYS, error_fn=errors.ProgrammerError): """Replaces a host name with the node's corresponding UUID. When a node is added to the cluster, we don't know it's UUID yet. So first its SSH key gets added to the public key file and in a second step, the node's name gets replaced with the node's UUID as soon as we know the UUID. @type node_uuid: string @param node_uuid: the node's UUID to replace the node's name @type node_name: string @param node_name: the node's name to be replaced by the node's UUID @see: _ManipulatePubKeyFile for the other parameter descriptions. """ process_line_fn = partial(_ReplaceNameByUuidProcessLine, node_uuid=node_uuid) process_else_fn = partial(_ReplaceNameByUuidElse, node_uuid=node_uuid) _ManipulatePubKeyFile(node_name, None, key_file=key_file, process_line_fn=process_line_fn, process_else_fn=process_else_fn, error_fn=error_fn) def ClearPubKeyFile(key_file=pathutils.SSH_PUB_KEYS, mode=0600): """Resets the content of the public key file. """ utils.WriteFile(key_file, data="", mode=mode) def OverridePubKeyFile(key_map, key_file=pathutils.SSH_PUB_KEYS): """Overrides the public key file with a list of given keys. @type key_map: dict from str to list of str @param key_map: dictionary mapping uuids to lists of SSH keys """ new_lines = [] for (uuid, keys) in key_map.items(): for key in keys: new_lines.append("%s %s\n" % (uuid, key)) new_file_content = "".join(new_lines) utils.WriteFile(key_file, data=new_file_content) def QueryPubKeyFile(target_uuids, key_file=pathutils.SSH_PUB_KEYS, error_fn=errors.ProgrammerError): """Retrieves a map of keys for the requested node UUIDs. @type target_uuids: str or list of str @param target_uuids: UUID of the node to retrieve the key for or a list of UUIDs of nodes to retrieve the keys for @type key_file: str @param key_file: filename of the file of public node keys (optional parameter for testing) @type error_fn: function @param error_fn: Function that returns an exception, used to customize exception types depending on the calling context @rtype: dict mapping strings to list of strings @return: dictionary mapping node uuids to their ssh keys """ all_keys = target_uuids is None if isinstance(target_uuids, str): target_uuids = [target_uuids] result = {} f = open(key_file, "r") try: for line in f: (uuid, key) = _ParseKeyLine(line, error_fn) if not uuid: continue if all_keys or (uuid in target_uuids): if uuid not in result: result[uuid] = [] result[uuid].append(key) finally: f.close() return result def InitSSHSetup(key_type, key_bits, error_fn=errors.OpPrereqError, _homedir_fn=None, _suffix=""): """Setup the SSH configuration for the node. This generates a dsa keypair for root, adds the pub key to the permitted hosts and adds the hostkey to its own known hosts. @param key_type: the type of SSH keypair to be generated @param key_bits: the key length, in bits, to be used """ priv_key, _, auth_keys = GetUserFiles(constants.SSH_LOGIN_USER, kind=key_type, mkdir=True, _homedir_fn=_homedir_fn) new_priv_key_name = priv_key + _suffix new_pub_key_name = priv_key + _suffix + ".pub" for name in new_priv_key_name, new_pub_key_name: if os.path.exists(name): utils.CreateBackup(name) utils.RemoveFile(name) result = utils.RunCmd(["ssh-keygen", "-b", str(key_bits), "-t", key_type, "-f", new_priv_key_name, "-q", "-N", ""]) if result.failed: raise error_fn("Could not generate ssh keypair, error %s" % result.output) AddAuthorizedKey(auth_keys, utils.ReadFile(new_pub_key_name)) def InitPubKeyFile(master_uuid, key_type, key_file=pathutils.SSH_PUB_KEYS): """Creates the public key file and adds the master node's SSH key. @type master_uuid: str @param master_uuid: the master node's UUID @type key_type: one of L{constants.SSHK_ALL} @param key_type: the type of ssh key to be used @type key_file: str @param key_file: name of the file containing the public keys """ _, pub_key, _ = GetUserFiles(constants.SSH_LOGIN_USER, kind=key_type) ClearPubKeyFile(key_file=key_file) key = utils.ReadFile(pub_key) AddPublicKey(master_uuid, key, key_file=key_file) class SshRunner: """Wrapper for SSH commands. """ def __init__(self, cluster_name): """Initializes this class. @type cluster_name: str @param cluster_name: name of the cluster """ self.cluster_name = cluster_name family = ssconf.SimpleStore().GetPrimaryIPFamily() self.ipv6 = (family == netutils.IP6Address.family) def _BuildSshOptions(self, batch, ask_key, use_cluster_key, strict_host_check, private_key=None, quiet=True, port=None): """Builds a list with needed SSH options. @param batch: same as ssh's batch option @param ask_key: allows ssh to ask for key confirmation; this parameter conflicts with the batch one @param use_cluster_key: if True, use the cluster name as the HostKeyAlias name @param strict_host_check: this makes the host key checking strict @param private_key: use this private key instead of the default @param quiet: whether to enable -q to ssh @param port: the SSH port to use, or None to use the default @rtype: list @return: the list of options ready to use in L{utils.process.RunCmd} """ options = [ "-oEscapeChar=none", "-oHashKnownHosts=no", "-oGlobalKnownHostsFile=%s" % pathutils.SSH_KNOWN_HOSTS_FILE, "-oUserKnownHostsFile=/dev/null", "-oCheckHostIp=no", ] if use_cluster_key: options.append("-oHostKeyAlias=%s" % self.cluster_name) if quiet: options.append("-q") if private_key: options.append("-i%s" % private_key) if port: options.append("-oPort=%d" % port) # TODO: Too many boolean options, maybe convert them to more descriptive # constants. # Note: ask_key conflicts with batch mode if batch: if ask_key: raise errors.ProgrammerError("SSH call requested conflicting options") options.append("-oBatchMode=yes") if strict_host_check: options.append("-oStrictHostKeyChecking=yes") else: options.append("-oStrictHostKeyChecking=no") else: # non-batch mode if ask_key: options.append("-oStrictHostKeyChecking=ask") elif strict_host_check: options.append("-oStrictHostKeyChecking=yes") else: options.append("-oStrictHostKeyChecking=no") if self.ipv6: options.append("-6") else: options.append("-4") return options def BuildCmd(self, hostname, user, command, batch=True, ask_key=False, tty=False, use_cluster_key=True, strict_host_check=True, private_key=None, quiet=True, port=None): """Build an ssh command to execute a command on a remote node. @param hostname: the target host, string @param user: user to auth as @param command: the command @param batch: if true, ssh will run in batch mode with no prompting @param ask_key: if true, ssh will run with StrictHostKeyChecking=ask, so that we can connect to an unknown host (not valid in batch mode) @param use_cluster_key: whether to expect and use the cluster-global SSH key @param strict_host_check: whether to check the host's SSH key at all @param private_key: use this private key instead of the default @param quiet: whether to enable -q to ssh @param port: the SSH port on which the node's daemon is running @return: the ssh call to run 'command' on the remote host. """ argv = [constants.SSH] argv.extend(self._BuildSshOptions(batch, ask_key, use_cluster_key, strict_host_check, private_key, quiet=quiet, port=port)) if tty: argv.extend(["-t", "-t"]) argv.append("%s@%s" % (user, hostname)) # Insert variables for virtual nodes argv.extend("export %s=%s;" % (utils.ShellQuote(name), utils.ShellQuote(value)) for (name, value) in vcluster.EnvironmentForHost(hostname).items()) argv.append(command) return argv def Run(self, *args, **kwargs): """Runs a command on a remote node. This method has the same return value as `utils.RunCmd()`, which it uses to launch ssh. Args: see SshRunner.BuildCmd. @rtype: L{utils.process.RunResult} @return: the result as from L{utils.process.RunCmd()} """ return utils.RunCmd(self.BuildCmd(*args, **kwargs)) def CopyFileToNode(self, node, port, filename): """Copy a file to another node with scp. @param node: node in the cluster @param filename: absolute pathname of a local file @rtype: boolean @return: the success of the operation """ if not os.path.isabs(filename): logging.error("File %s must be an absolute path", filename) return False if not os.path.isfile(filename): logging.error("File %s does not exist", filename) return False command = [constants.SCP, "-p"] command.extend(self._BuildSshOptions(True, False, True, True, port=port)) command.append(filename) if netutils.IP6Address.IsValid(node): node = netutils.FormatAddress((node, None)) command.append("%s:%s" % (node, vcluster.ExchangeNodeRoot(node, filename))) result = utils.RunCmd(command) if result.failed: logging.error("Copy to node %s failed (%s) error '%s'," " command was '%s'", node, result.fail_reason, result.output, result.cmd) return not result.failed def VerifyNodeHostname(self, node, ssh_port): """Verify hostname consistency via SSH. This functions connects via ssh to a node and compares the hostname reported by the node to the name with have (the one that we connected to). This is used to detect problems in ssh known_hosts files (conflicting known hosts) and inconsistencies between dns/hosts entries and local machine names @param node: nodename of a host to check; can be short or full qualified hostname @param ssh_port: the port of a SSH daemon running on the node @return: (success, detail), where: - success: True/False - detail: string with details """ cmd = ("if test -z \"$GANETI_HOSTNAME\"; then" " hostname --fqdn;" "else" " echo \"$GANETI_HOSTNAME\";" "fi") retval = self.Run(node, constants.SSH_LOGIN_USER, cmd, quiet=False, port=ssh_port) if retval.failed: msg = "ssh problem" output = retval.output if output: msg += ": %s" % output else: msg += ": %s (no output)" % retval.fail_reason logging.error("Command %s failed: %s", retval.cmd, msg) return False, msg remotehostname = retval.stdout.strip() if not remotehostname or remotehostname != node: if node.startswith(remotehostname + "."): msg = "hostname not FQDN" else: msg = "hostname mismatch" return False, ("%s: expected %s but got %s" % (msg, node, remotehostname)) return True, "host matches" def WriteKnownHostsFile(cfg, file_name): """Writes the cluster-wide equally known_hosts file. """ data = "" if cfg.GetRsaHostKey(): data += "%s ssh-rsa %s\n" % (cfg.GetClusterName(), cfg.GetRsaHostKey()) if cfg.GetDsaHostKey(): data += "%s ssh-dss %s\n" % (cfg.GetClusterName(), cfg.GetDsaHostKey()) utils.WriteFile(file_name, mode=0600, data=data) def _EnsureCorrectGanetiVersion(cmd): """Ensured the correct Ganeti version before running a command via SSH. Before a command is run on a node via SSH, it makes sense in some situations to ensure that this node is indeed running the correct version of Ganeti like the rest of the cluster. @type cmd: string @param cmd: string @rtype: list of strings @return: a list of commands with the newly added ones at the beginning """ logging.debug("Ensure correct Ganeti version: %s", cmd) version = constants.DIR_VERSION all_cmds = [["test", "-d", os.path.join(pathutils.PKGLIBDIR, version)]] if constants.HAS_GNU_LN: all_cmds.extend([["ln", "-s", "-f", "-T", os.path.join(pathutils.PKGLIBDIR, version), os.path.join(pathutils.SYSCONFDIR, "ganeti/lib")], ["ln", "-s", "-f", "-T", os.path.join(pathutils.SHAREDIR, version), os.path.join(pathutils.SYSCONFDIR, "ganeti/share")]]) else: all_cmds.extend([["rm", "-f", os.path.join(pathutils.SYSCONFDIR, "ganeti/lib")], ["ln", "-s", "-f", os.path.join(pathutils.PKGLIBDIR, version), os.path.join(pathutils.SYSCONFDIR, "ganeti/lib")], ["rm", "-f", os.path.join(pathutils.SYSCONFDIR, "ganeti/share")], ["ln", "-s", "-f", os.path.join(pathutils.SHAREDIR, version), os.path.join(pathutils.SYSCONFDIR, "ganeti/share")]]) all_cmds.append(cmd) return all_cmds def RunSshCmdWithStdin(cluster_name, node, basecmd, port, data, debug=False, verbose=False, use_cluster_key=False, ask_key=False, strict_host_check=False, ensure_version=False): """Runs a command on a remote machine via SSH and provides input in stdin. @type cluster_name: string @param cluster_name: Cluster name @type node: string @param node: Node name @type basecmd: string @param basecmd: Base command (path on the remote machine) @type port: int @param port: The SSH port of the remote machine or None for the default @param data: JSON-serializable input data for script (passed to stdin) @type debug: bool @param debug: Enable debug output @type verbose: bool @param verbose: Enable verbose output @type use_cluster_key: bool @param use_cluster_key: See L{ssh.SshRunner.BuildCmd} @type ask_key: bool @param ask_key: See L{ssh.SshRunner.BuildCmd} @type strict_host_check: bool @param strict_host_check: See L{ssh.SshRunner.BuildCmd} """ cmd = [basecmd] # Pass --debug/--verbose to the external script if set on our invocation if debug: cmd.append("--debug") if verbose: cmd.append("--verbose") if ensure_version: all_cmds = _EnsureCorrectGanetiVersion(cmd) else: all_cmds = [cmd] if port is None: port = netutils.GetDaemonPort(constants.SSH) srun = SshRunner(cluster_name) scmd = srun.BuildCmd(node, constants.SSH_LOGIN_USER, utils.ShellQuoteArgs( utils.ShellCombineCommands(all_cmds)), batch=False, ask_key=ask_key, quiet=False, strict_host_check=strict_host_check, use_cluster_key=use_cluster_key, port=port) tempfh = tempfile.TemporaryFile() try: tempfh.write(serializer.DumpJson(data)) tempfh.seek(0) result = utils.RunCmd(scmd, interactive=True, input_fd=tempfh) finally: tempfh.close() if result.failed: raise errors.OpExecError("Command '%s' failed: %s" % (result.cmd, result.fail_reason)) def ReadRemoteSshPubKey(pub_key_file, node, cluster_name, port, ask_key, strict_host_check): """Fetches a public SSH key from a node via SSH. @type pub_key_file: string @param pub_key_file: a tuple consisting of the file name of the public DSA key """ ssh_runner = SshRunner(cluster_name) cmd = ["cat", pub_key_file] ssh_cmd = ssh_runner.BuildCmd(node, constants.SSH_LOGIN_USER, utils.ShellQuoteArgs(cmd), batch=False, ask_key=ask_key, quiet=False, strict_host_check=strict_host_check, use_cluster_key=False, port=port) result = utils.RunCmd(ssh_cmd) if result.failed: raise errors.OpPrereqError("Could not fetch a public SSH key (%s) from node" " '%s': ran command '%s', failure reason: '%s'." % (pub_key_file, node, cmd, result.fail_reason), errors.ECODE_INVAL) return result.stdout def GetSshKeyFilenames(key_type, suffix=""): """Get filenames of the SSH key pair of the given type. @type key_type: string @param key_type: type of SSH key, must be element of C{constants.SSHK_ALL} @type suffix: string @param suffix: optional suffix for the key filenames @rtype: tuple of (string, string) @returns: a tuple containing the name of the private key file and the public key file. """ if key_type not in constants.SSHK_ALL: raise errors.SshUpdateError("Unsupported key type '%s'. Supported key types" " are: %s." % (key_type, constants.SSHK_ALL)) (_, root_keyfiles) = \ GetAllUserFiles(constants.SSH_LOGIN_USER, mkdir=False, dircheck=False) if not key_type in root_keyfiles.keys(): raise errors.SshUpdateError("No keyfile for key type '%s' available." % key_type) key_filenames = root_keyfiles[key_type] if suffix: key_filenames = [_ComputeKeyFilePathWithSuffix(key_filename, suffix) for key_filename in key_filenames] return key_filenames def GetSshPubKeyFilename(key_type, suffix=""): """Get filename of the public SSH key of the given type. @type key_type: string @param key_type: type of SSH key, must be element of C{constants.SSHK_ALL} @type suffix: string @param suffix: optional suffix for the key filenames @rtype: string @returns: file name of the public key file """ return GetSshKeyFilenames(key_type, suffix=suffix)[1] def _ComputeKeyFilePathWithSuffix(key_filepath, suffix): """Converts the given key filename to a key filename with a suffix. @type key_filepath: string @param key_filepath: path of the key file @type suffix: string @param suffix: suffix to be appended to the basename of the file """ path = os.path.dirname(key_filepath) ext = os.path.splitext(os.path.basename(key_filepath))[1] basename = os.path.splitext(os.path.basename(key_filepath))[0] return os.path.join(path, basename + suffix + ext) def ReplaceSshKeys(src_key_type, dest_key_type, src_key_suffix="", dest_key_suffix=""): """Replaces an SSH key pair by another SSH key pair. Note that both parts, the private and the public key, are replaced. @type src_key_type: string @param src_key_type: key type of key pair that is replacing the other key pair @type dest_key_type: string @param dest_key_type: key type of the key pair that is being replaced by the source key pair @type src_key_suffix: string @param src_key_suffix: optional suffix of the key files of the source key pair @type dest_key_suffix: string @param dest_key_suffix: optional suffix of the keey files of the destination key pair """ (src_priv_filename, src_pub_filename) = GetSshKeyFilenames( src_key_type, suffix=src_key_suffix) (dest_priv_filename, dest_pub_filename) = GetSshKeyFilenames( dest_key_type, suffix=dest_key_suffix) if not (os.path.exists(src_priv_filename) and os.path.exists(src_pub_filename)): raise errors.SshUpdateError( "At least one of the source key files is missing: %s", ", ".join([src_priv_filename, src_pub_filename])) for dest_file in [dest_priv_filename, dest_pub_filename]: if os.path.exists(dest_file): utils.CreateBackup(dest_file) utils.RemoveFile(dest_file) shutil.move(src_priv_filename, dest_priv_filename) shutil.move(src_pub_filename, dest_pub_filename) def ReadLocalSshPubKeys(key_types, suffix=""): """Reads the local root user SSH key. @type key_types: list of string @param key_types: types of SSH keys. Must be subset of constants.SSHK_ALL. If 'None' or [], all available keys are returned. @type suffix: string @param suffix: optional suffix to be attached to key names when reading them. Used for temporary key files. @rtype: list of string @return: list of public keys """ fetch_key_types = [] if key_types: fetch_key_types += key_types else: fetch_key_types = constants.SSHK_ALL (_, root_keyfiles) = \ GetAllUserFiles(constants.SSH_LOGIN_USER, mkdir=False, dircheck=False) result_keys = [] for (public_key_type, (_, public_key_file)) in root_keyfiles.items(): if public_key_type not in fetch_key_types: continue public_key_dir = os.path.dirname(public_key_file) public_key_filename = "" if suffix: public_key_filename = \ os.path.splitext(os.path.basename(public_key_file))[0] \ + suffix + ".pub" else: public_key_filename = public_key_file public_key_path = os.path.join(public_key_dir, public_key_filename) if not os.path.exists(public_key_path): raise errors.SshUpdateError("Cannot find SSH public key of type '%s'." % public_key_type) else: key = utils.ReadFile(public_key_path) result_keys.append(key) return result_keys # Update gnt-cluster.rst when changing which combinations are valid. KeyBitInfo = namedtuple('KeyBitInfo', ['default', 'validation_fn']) SSH_KEY_VALID_BITS = { constants.SSHK_DSA: KeyBitInfo(1024, lambda b: b == 1024), constants.SSHK_RSA: KeyBitInfo(2048, lambda b: b >= 768), constants.SSHK_ECDSA: KeyBitInfo(384, lambda b: b in [256, 384, 521]), } def DetermineKeyBits(key_type, key_bits, old_key_type, old_key_bits): """Checks the key bits to be used for a given key type, or provides defaults. @type key_type: one of L{constants.SSHK_ALL} @param key_type: The key type to use. @type key_bits: positive int or None @param key_bits: The number of bits to use, if supplied by user. @type old_key_type: one of L{constants.SSHK_ALL} or None @param old_key_type: The previously used key type, if any. @type old_key_bits: positive int or None @param old_key_bits: The previously used number of bits, if any. @rtype: positive int @return: The number of bits to use. """ if key_bits is None: if old_key_type is not None and old_key_type == key_type: key_bits = old_key_bits else: key_bits = SSH_KEY_VALID_BITS[key_type].default if not SSH_KEY_VALID_BITS[key_type].validation_fn(key_bits): raise errors.OpPrereqError("Invalid key type and bit size combination:" " %s with %s bits" % (key_type, key_bits), errors.ECODE_INVAL) return key_bits
bsd-2-clause
-2,877,672,071,644,923,400
32.432012
80
0.659144
false
3.685712
false
false
false
vwflow/raws-python
raws_json/__init__.py
1
28752
#!/usr/bin/python # -*- coding: utf-8 -*- # # This is a modified version of '__init__.py' (version 1.1.1), part of the 'atom' module # from the gdata-python-client project (http://code.google.com/p/gdata-python-client/) by Google Inc. # Copyright (C) 2006, 2007, 2008 Google Inc. # # It has been modified to support json formatted data instead of atom. # Copyright (C) 2012 rambla.eu # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.import os __author__ = 'api.jscudder (Jeffrey Scudder)' """JsonService provides CRUD ops. in line with the Atom Publishing Protocol. JsonService: Encapsulates the ability to perform insert, update and delete operations with the Atom Publishing Protocol on which GData is based. An instance can perform query, insertion, deletion, and update. HttpRequest: Function that performs a GET, POST, PUT, or DELETE HTTP request to the specified end point. An JsonService object or a subclass can be used to specify information about the request. """ import os import httplib import urllib import re import base64 import socket URL_REGEX = re.compile('http(s)?\://([\w\.-]*)(\:(\d+))?(/.*)?') class JsonService(object): """Performs Atom Publishing Protocol CRUD operations. The JsonService contains methods to perform HTTP CRUD operations. """ # Default values for members -> disabled, also works without them # port = 80 # ssl = False # If debug is True, the HTTPConnection will display debug information debug = False def __init__(self, server=None, additional_headers=None): """Creates a new JsonService client. Args: server: string (optional) The start of a URL for the server to which all operations should be directed. Example: 'www.google.com' additional_headers: dict (optional) Any additional HTTP headers which should be included with CRUD operations. """ self.server = server self.additional_headers = additional_headers or {} self.additional_headers['User-Agent'] = 'Python Google Data Client Lib' def _ProcessUrl(self, url, for_proxy=False): """Processes a passed URL. If the URL does not begin with https?, then the default value for self.server is used""" return ProcessUrl(self, url, for_proxy=for_proxy) def UseBasicAuth(self, username, password, for_proxy=False): """Sets an Authenticaiton: Basic HTTP header containing plaintext. The username and password are base64 encoded and added to an HTTP header which will be included in each request. Note that your username and password are sent in plaintext. Args: username: str password: str """ UseBasicAuth(self, username, password, for_proxy=for_proxy) def PrepareConnection(self, full_uri): """Opens a connection to the server based on the full URI. Examines the target URI and the proxy settings, which are set as environment variables, to open a connection with the server. This connection is used to make an HTTP request. Args: full_uri: str Which is the target relative (lacks protocol and host) or absolute URL to be opened. Example: 'https://www.google.com/accounts/ClientLogin' or 'base/feeds/snippets' where the server is set to www.google.com. Returns: A tuple containing the httplib.HTTPConnection and the full_uri for the request. """ return PrepareConnection(self, full_uri) # Alias the old name for the above method to preserve backwards # compatibility. _PrepareConnection = PrepareConnection # CRUD operations def Get(self, uri, extra_headers=None, url_params=None, escape_params=True): """Query the APP server with the given URI The uri is the portion of the URI after the server value (server example: 'www.google.com'). Example use: To perform a query against Google Base, set the server to 'base.google.com' and set the uri to '/base/feeds/...', where ... is your query. For example, to find snippets for all digital cameras uri should be set to: '/base/feeds/snippets?bq=digital+camera' Args: uri: string The query in the form of a URI. Example: '/base/feeds/snippets?bq=digital+camera'. extra_headers: dicty (optional) Extra HTTP headers to be included in the GET request. These headers are in addition to those stored in the client's additional_headers property. The client automatically sets the Content-Type and Authorization headers. url_params: dict (optional) Additional URL parameters to be included in the query. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: httplib.HTTPResponse The server's response to the GET request. """ extra_headers.update({'Accept': 'application/json', 'Content-Type': 'application/json'}) return HttpRequest(self, 'GET', None, uri, extra_headers=extra_headers, url_params=url_params, escape_params=escape_params) def Post(self, data, uri, extra_headers=None, url_params=None, escape_params=True, content_type='application/atom+xml'): """Insert data into an APP server at the given URI. Args: data: string, ElementTree._Element, or something with a __str__ method The XML to be sent to the uri. uri: string The location (feed) to which the data should be inserted. Example: '/base/feeds/items'. extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: httplib.HTTPResponse Server's response to the POST request. """ extra_headers.update({'Accept': 'application/json'}) return HttpRequest(self, 'POST', data, uri, extra_headers=extra_headers, url_params=url_params, escape_params=escape_params, content_type=content_type) def Put(self, data, uri, extra_headers=None, url_params=None, escape_params=True, content_type='application/atom+xml'): """Updates an entry at the given URI. Args: data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The XML containing the updated data. uri: string A URI indicating entry to which the update will be applied. Example: '/base/feeds/items/ITEM-ID' extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: httplib.HTTPResponse Server's response to the PUT request. """ extra_headers.update({'Accept': 'application/json'}) return HttpRequest(self, 'PUT', data, uri, extra_headers=extra_headers, url_params=url_params, escape_params=escape_params, content_type=content_type) def Delete(self, uri, extra_headers=None, url_params=None, escape_params=True): """Deletes the entry at the given URI. Args: uri: string The URI of the entry to be deleted. Example: '/base/feeds/items/ITEM-ID' extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type and Authorization headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: httplib.HTTPResponse Server's response to the DELETE request. """ return HttpRequest(self, 'DELETE', None, uri, extra_headers=extra_headers, url_params=url_params, escape_params=escape_params) def Head(self, uri, extra_headers=None, url_params=None, escape_params=True): """Send a HEAD request to the APP server with the given URI The uri is the portion of the URI after the server value (server example: 'www.google.com'). Example use: To perform a query against Google Base, set the server to 'base.google.com' and set the uri to '/base/feeds/...', where ... is your query. For example, to find snippets for all digital cameras uri should be set to: '/base/feeds/snippets?bq=digital+camera' Args: uri: string The query in the form of a URI. Example: '/base/feeds/snippets?bq=digital+camera'. extra_headers: dicty (optional) Extra HTTP headers to be included in the GET request. These headers are in addition to those stored in the client's additional_headers property. The client automatically sets the Content-Type and Authorization headers. url_params: dict (optional) Additional URL parameters to be included in the query. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: httplib.HTTPResponse The server's response to the GET request. """ return HttpRequest(self, 'HEAD', None, uri, extra_headers=extra_headers, url_params=url_params, escape_params=escape_params) def HttpRequest(service, operation, data, uri, extra_headers=None, url_params=None, escape_params=True, content_type='application/atom+xml'): """Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE. Usage example, perform and HTTP GET on http://www.google.com/: import atom.service client = atom.service.JsonService() http_response = client.Get('http://www.google.com/') or you could set the client.server to 'www.google.com' and use the following: client.server = 'www.google.com' http_response = client.Get('/') Args: service: atom.JsonService object which contains some of the parameters needed to make the request. The following members are used to construct the HTTP call: server (str), additional_headers (dict), port (int), and ssl (bool). operation: str The HTTP operation to be performed. This is usually one of 'GET', 'POST', 'PUT', or 'DELETE' data: ElementTree, filestream, list of parts, or other object which can be converted to a string. Should be set to None when performing a GET or PUT. If data is a file-like object which can be read, this method will read a chunk of 100K bytes at a time and send them. If the data is a list of parts to be sent, each part will be evaluated and sent. uri: The beginning of the URL to which the request should be sent. Examples: '/', '/base/feeds/snippets', '/m8/feeds/contacts/default/base' extra_headers: dict of strings. HTTP headers which should be sent in the request. These headers are in addition to those stored in service.additional_headers. url_params: dict of strings. Key value pairs to be added to the URL as URL parameters. For example {'foo':'bar', 'test':'param'} will become ?foo=bar&test=param. escape_params: bool default True. If true, the keys and values in url_params will be URL escaped when the form is constructed (Special characters converted to %XX form.) content_type: str The MIME type for the data being sent. Defaults to 'application/atom+xml', this is only used if data is set. """ full_uri = BuildUri(uri, url_params, escape_params) (connection, full_uri) = PrepareConnection(service, full_uri) if extra_headers is None: extra_headers = {} # Turn on debug mode if the debug member is set. if service.debug: connection.debuglevel = 1 connection.putrequest(operation, full_uri) # If the list of headers does not include a Content-Length, attempt to # calculate it based on the data object. if (data and not service.additional_headers.has_key('Content-Length') and not extra_headers.has_key('Content-Length')): content_length = __CalculateDataLength(data) if content_length: extra_headers['Content-Length'] = str(content_length) else: extra_headers['Content-Length'] = "0" if content_type: extra_headers['Content-Type'] = content_type # Send the HTTP headers. if isinstance(service.additional_headers, dict): for header in service.additional_headers: connection.putheader(header, service.additional_headers[header]) if isinstance(extra_headers, dict): for header in extra_headers: connection.putheader(header, extra_headers[header]) connection.endheaders() # If there is data, send it in the request. if data: if isinstance(data, list): for data_part in data: __SendDataPart(data_part, connection) else: __SendDataPart(data, connection) # Return the HTTP Response from the server. return connection.getresponse() def __SendDataPart(data, connection): if isinstance(data, str): connection.send(data) return elif isinstance(data, unicode): # unicode string must be converted into 8-bit string version (otherwise httplib will raise UnicodeDecodeError) connection.send(data.encode('utf-8')) return # NEXT SECTION COMMENTED OUT, replace by json.decode() if desired # elif ElementTree.iselement(data): # connection.send(ElementTree.tostring(data)) # return # Check to see if data is a file-like object that has a read method. elif hasattr(data, 'read'): # Read the file and send it a chunk at a time. while 1: binarydata = data.read(100000) if binarydata == '': break connection.send(binarydata) return else: # The data object was not a file. # Try to convert to a string and send the data. connection.send(str(data)) return def __CalculateDataLength(data): """Attempts to determine the length of the data to send. This method will respond with a length only if the data is a string or and ElementTree element. Args: data: object If this is not a string or ElementTree element this funtion will return None. """ if isinstance(data, str): return len(data) elif isinstance(data, unicode): return len(data.decode('utf-8')) elif isinstance(data, list): return None # elif ElementTree.iselement(data): # return len(ElementTree.tostring(data)) elif hasattr(data, 'read'): # If this is a file-like object, don't try to guess the length. return None else: return len(str(data)) def PrepareConnection(service, full_uri): """Opens a connection to the server based on the full URI. Examines the target URI and the proxy settings, which are set as environment variables, to open a connection with the server. This connection is used to make an HTTP request. Args: service: atom.JsonService or a subclass. It must have a server string which represents the server host to which the request should be made. It may also have a dictionary of additional_headers to send in the HTTP request. full_uri: str Which is the target relative (lacks protocol and host) or absolute URL to be opened. Example: 'https://www.google.com/accounts/ClientLogin' or 'base/feeds/snippets' where the server is set to www.google.com. Returns: A tuple containing the httplib.HTTPConnection and the full_uri for the request. """ (server, port, ssl, partial_uri) = ProcessUrl(service, full_uri) if ssl: # destination is https proxy = os.environ.get('https_proxy') if proxy: (p_server, p_port, p_ssl, p_uri) = ProcessUrl(service, proxy, True) proxy_username = os.environ.get('proxy-username') if not proxy_username: proxy_username = os.environ.get('proxy_username') proxy_password = os.environ.get('proxy-password') if not proxy_password: proxy_password = os.environ.get('proxy_password') if proxy_username: user_auth = base64.encodestring('%s:%s' % (proxy_username, proxy_password)) proxy_authorization = ('Proxy-authorization: Basic %s\r\n' % ( user_auth.strip())) else: proxy_authorization = '' proxy_connect = 'CONNECT %s:%s HTTP/1.0\r\n' % (server, port) user_agent = 'User-Agent: %s\r\n' % ( service.additional_headers['User-Agent']) proxy_pieces = (proxy_connect + proxy_authorization + user_agent + '\r\n') #now connect, very simple recv and error checking p_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) p_sock.connect((p_server,p_port)) p_sock.sendall(proxy_pieces) response = '' # Wait for the full response. while response.find("\r\n\r\n") == -1: response += p_sock.recv(8192) p_status=response.split()[1] if p_status!=str(200): raise 'Error status=',str(p_status) # Trivial setup for ssl socket. ssl = socket.ssl(p_sock, None, None) fake_sock = httplib.FakeSocket(p_sock, ssl) # Initalize httplib and replace with the proxy socket. connection = httplib.HTTPConnection(server) connection.sock=fake_sock full_uri = partial_uri else: connection = httplib.HTTPSConnection(server, port) full_uri = partial_uri else: # destination is http proxy = os.environ.get('http_proxy') if proxy: (p_server, p_port, p_ssl, p_uri) = ProcessUrl(service.server, proxy, True) proxy_username = os.environ.get('proxy-username') if not proxy_username: proxy_username = os.environ.get('proxy_username') proxy_password = os.environ.get('proxy-password') if not proxy_password: proxy_password = os.environ.get('proxy_password') if proxy_username: UseBasicAuth(service, proxy_username, proxy_password, True) connection = httplib.HTTPConnection(p_server, p_port) if not full_uri.startswith("http://"): if full_uri.startswith("/"): full_uri = "http://%s%s" % (service.server, full_uri) else: full_uri = "http://%s/%s" % (service.server, full_uri) else: connection = httplib.HTTPConnection(server, port) full_uri = partial_uri return (connection, full_uri) def UseBasicAuth(service, username, password, for_proxy=False): """Sets an Authenticaiton: Basic HTTP header containing plaintext. The username and password are base64 encoded and added to an HTTP header which will be included in each request. Note that your username and password are sent in plaintext. The auth header is added to the additional_headers dictionary in the service object. Args: service: atom.JsonService or a subclass which has an additional_headers dict as a member. username: str password: str """ base_64_string = base64.encodestring('%s:%s' % (username, password)) base_64_string = base_64_string.strip() if for_proxy: header_name = 'Proxy-Authorization' else: header_name = 'Authorization' service.additional_headers[header_name] = 'Basic %s' % (base_64_string,) def ProcessUrl(service, url, for_proxy=False): """Processes a passed URL. If the URL does not begin with https?, then the default value for server is used""" server = None port = 80 ssl = False if hasattr(service, 'server'): server = service.server else: server = service if not for_proxy: if hasattr(service, 'port'): port = service.port if hasattr(service, 'ssl'): ssl = service.ssl uri = url m = URL_REGEX.match(url) if m is None: return (server, port, ssl, uri) else: if m.group(1) is not None: port = 443 ssl = True if m.group(3) is None: server = m.group(2) else: server = m.group(2) port = int(m.group(4)) if m.group(5) is not None: uri = m.group(5) else: uri = '/' return (server, port, ssl, uri) def DictionaryToParamList(url_parameters, escape_params=True): """Convert a dictionary of URL arguments into a URL parameter string. Args: url_parameters: The dictionaty of key-value pairs which will be converted into URL parameters. For example, {'dry-run': 'true', 'foo': 'bar'} will become ['dry-run=true', 'foo=bar']. Returns: A list which contains a string for each key-value pair. The strings are ready to be incorporated into a URL by using '&'.join([] + parameter_list) """ # Choose which function to use when modifying the query and parameters. # Use quote_plus when escape_params is true. transform_op = [str, urllib.quote_plus][bool(escape_params)] # Create a list of tuples containing the escaped version of the # parameter-value pairs. parameter_tuples = [(transform_op(param), transform_op(value)) for param, value in (url_parameters or {}).items()] # Turn parameter-value tuples into a list of strings in the form # 'PARAMETER=VALUE'. return ['='.join(x) for x in parameter_tuples] def BuildUri(uri, url_params=None, escape_params=True): """Converts a uri string and a collection of parameters into a URI. Args: uri: string url_params: dict (optional) escape_params: boolean (optional) uri: string The start of the desired URI. This string can alrady contain URL parameters. Examples: '/base/feeds/snippets', '/base/feeds/snippets?bq=digital+camera' url_parameters: dict (optional) Additional URL parameters to be included in the query. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: string The URI consisting of the escaped URL parameters appended to the initial uri string. """ # Prepare URL parameters for inclusion into the GET request. parameter_list = DictionaryToParamList(url_params, escape_params) # Append the URL parameters to the URL. if parameter_list: if uri.find('?') != -1: # If there are already URL parameters in the uri string, add the # parameters after a new & character. full_uri = '&'.join([uri] + parameter_list) else: # The uri string did not have any URL parameters (no ? character) # so put a ? between the uri and URL parameters. full_uri = '%s%s' % (uri, '?%s' % ('&'.join([] + parameter_list))) else: full_uri = uri return full_uri class MediaSource(object): """Raws Entries can refer to media sources, so this class provides a place to store references to these objects along with some metadata. """ def __init__(self, file_handle=None, content_type=None, content_length=None, file_path=None, file_name=None, svr_filename = None): """Creates an object of type MediaSource. Args: file_handle: A file handle pointing to the file to be encapsulated in the MediaSource content_type: string The MIME type of the file. Required if a file_handle is given. content_length: int The size of the file. Required if a file_handle is given. file_path: string (optional) A full path name to the file. Used in place of a file_handle. file_name: string The name of the file without any path information. Required if a file_handle is given. """ self.file_handle = file_handle self.content_type = content_type self.content_length = content_length self.file_name = file_name self.svr_filename = svr_filename self.file_path = file_path if (file_handle is None and file_path is not None): self.setFile(file_path, content_type) if not self.svr_filename: self.svr_filename = self.file_name def setFile(self, file_name, content_type): """A helper function which can create a file handle from a given filename and set the content type and length all at once. Args: file_name: string The path and file name to the file containing the media content_type: string A MIME type representing the type of the media """ self.file_handle = open(file_name, 'rb') self.content_type = content_type self.content_length = os.path.getsize(file_name) self.file_name = os.path.basename(file_name) def writeFile(self, file_path): # can not write if no path and handle if not file_path or not self.file_handle: return False self.file_path = file_path fd = open(file_path, 'wb') fd.write(self.file_handle.read()) fd.close() return True
apache-2.0
4,799,143,421,886,727,000
40.015692
116
0.643399
false
4.255773
false
false
false
google/google-ctf
2019/finals/web-gphotos-finals/app/gallery/middleware.py
1
1230
# Copyright 2019 Google LLC # # 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 # # https://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. from django.utils.text import slugify import hashlib import os class UserMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): user_id = request.COOKIES.get('user') if not user_id: user_id = hashlib.md5(os.urandom(16)).hexdigest() else: user_id = slugify(user_id) user_dir = os.path.join('media', user_id) if not os.path.exists(user_dir): os.makedirs(user_dir) os.makedirs(os.path.join(user_dir, 'thumbs')) request.user_id = user_id response = self.get_response(request) response.set_cookie('user', user_id) return response
apache-2.0
8,556,968,117,111,451,000
28.285714
74
0.704065
false
3.649852
false
false
false
UKPLab/emnlp2017-claim-identification
src/main/python/process_data_se_WithDevel.py
1
4976
import cPickle import numpy as np import pandas as pd import re import sys from collections import defaultdict def build_data_cv(data_folder, cv=10, clean_string=True): """ Loads data. """ revs = [] pos_file = data_folder[0] # train file neg_file = data_folder[1] # test file devel_file = data_folder[2] vocab = defaultdict(float) for (mysplit,myfile) in [(0,pos_file),(1,neg_file),(2,devel_file)]: with open(myfile, "rb") as f: for line in f: rev = [] strippedLine = line.strip() try: lline,label = strippedLine.split("\t") except ValueError: lline = "" label = strippedLine rev.append(lline.strip()) if clean_string: orig_rev = clean_str(" ".join(rev)) else: orig_rev = " ".join(rev).lower() words = set(orig_rev.split()) for word in words: vocab[word] += 1 datum = {"y":int(label), "text": orig_rev, "num_words": len(orig_rev.split()), "split": mysplit} revs.append(datum) #print revs return revs, vocab def get_W(word_vecs, k=300): """ Get word matrix. W[i] is the vector for word indexed by i """ vocab_size = len(word_vecs) word_idx_map = dict() W = np.zeros(shape=(vocab_size+1, k), dtype='float32') W[0] = np.zeros(k, dtype='float32') i = 1 for word in word_vecs: W[i] = word_vecs[word] word_idx_map[word] = i i += 1 return W, word_idx_map def load_bin_vec(fname, vocab): """ Loads 300x1 word vecs from Google (Mikolov) word2vec """ word_vecs = {} with open(fname, "rb") as f: header = f.readline() vocab_size, layer1_size = map(int, header.split()) binary_len = np.dtype('float32').itemsize * layer1_size for line in xrange(vocab_size): word = [] while True: ch = f.read(1) if ch == ' ': word = ''.join(word) break if ch != '\n': word.append(ch) if word in vocab: word_vecs[word] = np.fromstring(f.read(binary_len), dtype='float32') else: f.read(binary_len) return word_vecs def add_unknown_words(word_vecs, vocab, min_df=1, k=300): """ For words that occur in at least min_df documents, create a separate word vector. 0.25 is chosen so the unknown vectors have (approximately) same variance as pre-trained ones """ for word in vocab: if word not in word_vecs and vocab[word] >= min_df: word_vecs[word] = np.random.uniform(-0.25,0.25,k) def clean_str(string, TREC=False): """ Tokenization/string cleaning for all datasets except for SST. Every dataset is lower cased except for TREC """ string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string) string = re.sub(r"\'s", " \'s", string) string = re.sub(r"\'ve", " \'ve", string) string = re.sub(r"n\'t", " n\'t", string) string = re.sub(r"\'re", " \'re", string) string = re.sub(r"\'d", " \'d", string) string = re.sub(r"\'ll", " \'ll", string) string = re.sub(r",", " , ", string) string = re.sub(r"!", " ! ", string) string = re.sub(r"\(", " \( ", string) string = re.sub(r"\)", " \) ", string) string = re.sub(r"\?", " \? ", string) string = re.sub(r"\s{2,}", " ", string) return string.strip() if TREC else string.strip().lower() def clean_str_sst(string): """ Tokenization/string cleaning for the SST dataset """ string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string) string = re.sub(r"\s{2,}", " ", string) return string.strip().lower() if __name__=="__main__": w2v_file = sys.argv[1] trainFile = sys.argv[2] testFile = sys.argv[3] develFile = sys.argv[4] saveFile = sys.argv[5] data_folder = [trainFile,testFile,develFile] print "loading data...", revs, vocab = build_data_cv(data_folder, cv=10, clean_string=True) max_l = np.max(pd.DataFrame(revs)["num_words"]) print "data loaded!" print "number of sentences: " + str(len(revs)) print "vocab size: " + str(len(vocab)) print "max sentence length: " + str(max_l) print "loading word2vec vectors...", sys.stdout.flush() w2v = load_bin_vec(w2v_file, vocab) print "word2vec loaded!" print "num words already in word2vec: " + str(len(w2v)) add_unknown_words(w2v, vocab) W, word_idx_map = get_W(w2v) rand_vecs = {} add_unknown_words(rand_vecs, vocab) W2, _ = get_W(rand_vecs) cPickle.dump([revs, W, W2, word_idx_map, vocab], open(saveFile, "wb")) print "dataset created!" #sys.exit(1) # SE
apache-2.0
-3,612,380,496,805,541,400
32.85034
96
0.530748
false
3.275839
false
false
false
bcgov/gwells
app/backend/gwells/views/bulk.py
1
18358
""" 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 math import logging from decimal import Decimal from rest_framework.views import APIView from rest_framework import status from rest_framework.response import Response from drf_yasg.utils import swagger_auto_schema from django.db import transaction from django.utils import timezone from django.contrib.gis.geos import Point from aquifers.constants import AQUIFER_ID_FOR_UNCORRELATED_WELLS from aquifers.models import Aquifer, VerticalAquiferExtent, VerticalAquiferExtentsHistory from wells.models import Well from gwells.models.bulk import BulkWellAquiferCorrelationHistory from gwells.permissions import ( HasBulkWellAquiferCorrelationUploadRole, HasBulkVerticalAquiferExtentsUploadRole ) logger = logging.getLogger(__name__) class BulkWellAquiferCorrelation(APIView): """ Changes multiple aquifers well correlations all at once """ permission_classes = (HasBulkWellAquiferCorrelationUploadRole, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.change_log = [] self.create_date = timezone.now() self.unknown_well_tag_numbers = set() self.unknown_aquifer_ids = set() self.wells_outside_aquifer = dict() self.no_geom_aquifers = set() self.retired_aquifers = set() self.unpublished_aquifers = set() self.unpublished_wells = set() @swagger_auto_schema(auto_schema=None) @transaction.atomic def post(self, request, **kwargs): aquifers = request.data changes = {} wells_to_update = [] # check for a ?commit querystring parameter for this /bulk API # this flag will actually perform the bulk_update() on the DB # without it will just check for errors and return the changes # that would have been made update_db = 'commit' in request.GET incoming_well_tag_numbers = {wtn for aquifer in aquifers for wtn in aquifer['wellTagNumbers']} incoming_aquifer_ids = {aquifer['aquiferId'] for aquifer in aquifers} existing_wells = self.lookup_existing_wells(incoming_well_tag_numbers) existing_aquifers = self.lookup_existing_aquifers(incoming_aquifer_ids) if self.has_errors(): return self.return_errors({}) for aquifer in aquifers: aquifer_id = int(aquifer['aquiferId']) well_tag_numbers = aquifer['wellTagNumbers'] # capture errors about any unknown aquifers aquifer = existing_aquifers[aquifer_id] wells = [well for wtn, well in existing_wells.items() if wtn in well_tag_numbers] # now figure out what has changed for each well for well in wells: well_tag_number = well.well_tag_number existing_aquifer_id = well.aquifer_id if well.aquifer_id else None # We need to skip aquifer 1143 as it is the aquifer without geom that wells are # assigned to when they are not correlated at the time of interpretation. if aquifer_id != AQUIFER_ID_FOR_UNCORRELATED_WELLS: # If the correlation is changing — check if the well is inside the aquifer self.check_well_in_aquifer(well, aquifer) if existing_aquifer_id == aquifer_id: # this well correlation is unchanged change = { 'action': 'same' } else: if existing_aquifer_id is None: # No existing aquifer for this well? Must be a new correlation self.append_to_change_log(well_tag_number, aquifer_id, None) change = { 'action': 'new', 'aquiferId': aquifer_id } wells_to_update.append(well) elif existing_aquifer_id != aquifer_id: # existing ids don't match - must be a change self.append_to_change_log(well_tag_number, aquifer_id, existing_aquifer_id) change = { 'action': 'update', 'existingAquiferId': existing_aquifer_id, 'newAquiferId': aquifer_id } wells_to_update.append(well) if change: changes[well_tag_number] = change if update_db: # change all well's to point to the new aquifer for well in wells: well.aquifer = aquifer if update_db: # no errors then updated the DB (if ?commit is passed in) self.update_wells(wells_to_update) elif self.has_warnings(): return self.return_errors(changes) # no errors then we return the changes that were (or could be) performed http_status = status.HTTP_200_OK if update_db else status.HTTP_202_ACCEPTED return Response(changes, status=http_status) def has_errors(self): has_errors = ( len(self.unknown_well_tag_numbers) > 0 or len(self.unknown_aquifer_ids) > 0 ) return has_errors def has_warnings(self): has_warnings = ( len(self.wells_outside_aquifer) > 0 or len(self.no_geom_aquifers) > 0 or len(self.unpublished_wells) > 0 or len(self.unpublished_aquifers) > 0 or len(self.retired_aquifers) > 0 ) return has_warnings def lookup_existing_wells(self, well_tag_numbers): wells = Well.objects.filter(pk__in=well_tag_numbers) keyed_wells = {well.well_tag_number: well for well in wells} known_well_tag_numbers = set(keyed_wells.keys()) self.unknown_well_tag_numbers = well_tag_numbers - known_well_tag_numbers self.unpublished_wells = [well.well_tag_number for well in wells if well.well_publication_status_id != 'Published'] return keyed_wells def lookup_existing_aquifers(self, aquifer_ids): aquifers = Aquifer.objects.filter(pk__in=aquifer_ids).defer('geom') # we are not using geom keyed_aquifers = {aquifer.aquifer_id: aquifer for aquifer in aquifers} known_aquifer_ids = set(keyed_aquifers.keys()) self.unknown_aquifer_ids = aquifer_ids - known_aquifer_ids self.retired_aquifers = [a.aquifer_id for a in aquifers if a.status_retired] self.unpublished_aquifers = [a.aquifer_id for a in aquifers if not a.status_published] return keyed_aquifers def check_well_in_aquifer(self, well, aquifer): if aquifer.geom is None: self.no_geom_aquifers.add(aquifer.aquifer_id) return None if aquifer.geom_simplified is None: raise Exception(f"Aquifer {aquifer.aquifer_id} has no geom_simplified") # Expand simplified polygon by ~1000m in WGS-84 (srid 4326) aquifer_geom = aquifer.geom_simplified.buffer(0.01) if not aquifer_geom.contains(well.geom): well_3005_geom = well.geom.transform(3005, clone=True) distance = aquifer.geom.distance(well_3005_geom) # NOTE: 3005 projection's `.distance()` returns almost-meters self.wells_outside_aquifer[well.well_tag_number] = {'distance': distance, 'units': 'meters'} return False return True def return_errors(self, changes): # roll back the transaction as the bulk_update could have run for one # aquifer but errored on another. Best to abort the whole thing and warn the user transaction.set_rollback(True) errors = { 'unknownAquifers': self.unknown_aquifer_ids, 'unknownWells': self.unknown_well_tag_numbers, 'wellsNotInAquifer': self.wells_outside_aquifer, 'aquiferHasNoGeom': self.no_geom_aquifers, 'retiredAquifers': self.retired_aquifers, 'unpublishedAquifers': self.unpublished_aquifers, 'unpublishedWells': self.unpublished_wells, 'changes': changes # always return the list of changes even if there are unknowns } return Response(errors, status=status.HTTP_400_BAD_REQUEST) def update_wells(self, wells): logger.info("Bulk updating %d wells", len(wells)) # bulk update using efficient SQL for any well aquifer correlations that have changed Well.objects.bulk_update(wells, ['aquifer']) # save the BulkWellAquiferCorrelation records BulkWellAquiferCorrelationHistory.objects.bulk_create(self.change_log) def append_to_change_log(self, well_tag_number, to_aquifer_id, from_aquifer_id): bulk_history_item = BulkWellAquiferCorrelationHistory( well_id=well_tag_number, update_to_aquifer_id=to_aquifer_id, update_from_aquifer_id=from_aquifer_id, create_user=self.request.user.profile.username, create_date=self.create_date ) self.change_log.append(bulk_history_item) class BulkVerticalAquiferExtents(APIView): """ Changes multiple vertical aquifer extents all at once """ permission_classes = (HasBulkVerticalAquiferExtentsUploadRole, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.conflicts = [] self.change_log = [] self.create_date = timezone.now() self.unknown_well_tag_numbers = set() self.unknown_aquifer_ids = set() @swagger_auto_schema(auto_schema=None) @transaction.atomic def post(self, request, **kwargs): vertical_aquifer_extents = request.data new_vae_models = [] # check for a ?commit querystring parameter for this /bulk API # this flag will actually perform the bulk_update() on the DB # without it will just check for errors and return the changes # that would have been made update_db = 'commit' in request.GET # create a dict of the extents keyed by well_tag_number incoming_vae_data = self.as_wells(vertical_aquifer_extents) incoming_well_tag_numbers = incoming_vae_data.keys() existing_wells = self.lookup_existing_wells(incoming_well_tag_numbers) incoming_aquifer_ids = set(row['aquiferId'] for row in vertical_aquifer_extents) existing_aquifers = self.lookup_existing_aquifers(incoming_aquifer_ids) if len(self.unknown_well_tag_numbers) > 0 or len(self.unknown_aquifer_ids) > 0: return self.return_errors() # loop through every well in this bulk update for well_tag_number, data in incoming_vae_data.items(): well = existing_wells[well_tag_number] existing_data = VerticalAquiferExtent.objects \ .filter(well_id=well_tag_number) \ .order_by('start')[:] existing_aquifer_ids = [item.aquifer_id for item in existing_data] extents = [{'start': item.start, 'end': item.end} for item in existing_data] # record the current extents at this well so we know the complete state at this time for existing_vae in existing_data: self.append_to_history_log(existing_vae) # loop through all incoming extents and see if they overlap with any existing or new extents max_depth = float('-inf') data.sort(key=lambda item: item['fromDepth']) for vae in data: aquifer_id = vae['aquiferId'] from_depth = Decimal(format(vae['fromDepth'], '.2f')) if vae['fromDepth'] is not None else None to_depth = Decimal(format(vae['toDepth'], '.2f')) if vae['toDepth'] is not None else Decimal('Infinity') if aquifer_id in existing_aquifer_ids: self.add_conflict(vae, 'Aquifer %s already defined for well' % aquifer_id) continue if from_depth < 0: self.add_conflict(vae, 'From depth can not be less then zero') continue if to_depth < 0: self.add_conflict(vae, 'To depth can not be less then zero') continue if to_depth < from_depth: self.add_conflict(vae, 'From depth must be below to depth') continue aquifer = existing_aquifers[aquifer_id] if self.check_extent_overlaps(from_depth, to_depth, extents): self.add_conflict(vae, 'Overlaps with an existing vertical aquifer extent') continue if from_depth < max_depth: self.add_conflict(vae, 'Overlaps with another vertical aquifer extent in the CSV') continue max_depth = to_depth if update_db: vae_model = self.build_vertical_aquifer_extent_model(well, aquifer, from_depth, to_depth) new_vae_models.append(vae_model) self.append_to_history_log(vae_model) # if there are any unknown aquifers or wells then we want to return errors if len(self.conflicts) > 0: return self.return_errors() if update_db: # no errors then updated the DB (if ?commit is passed in) self.create_vertical_aquifer_extents(new_vae_models) # no errors then we return the changes that were (or could be) performed http_status = status.HTTP_200_OK if update_db else status.HTTP_202_ACCEPTED return Response({}, status=http_status) def as_wells(self, vertical_aquifer_extents): """ Returns extents as a dict keyed by well_tag_number """ wells = {} for record in vertical_aquifer_extents: wells.setdefault(record['wellTagNumber'], []).append(record) return wells def lookup_existing_wells(self, well_tag_numbers): """ Returns a dict keyed by well_tag_number of existing wells """ wells = Well.objects.filter(pk__in=well_tag_numbers) keyed_wells = {well.well_tag_number: well for well in wells} known_well_tag_numbers = set(keyed_wells.keys()) self.unknown_well_tag_numbers = well_tag_numbers - known_well_tag_numbers return keyed_wells def lookup_existing_aquifers(self, aquifer_ids): """ Returns a dict keyed by aquifer_id of existing aquifers """ aquifers = Aquifer.objects.filter(pk__in=aquifer_ids) keyed_aquifers = {aquifer.aquifer_id: aquifer for aquifer in aquifers} known_aquifer_ids = set(keyed_aquifers.keys()) self.unknown_aquifer_ids = aquifer_ids - known_aquifer_ids return keyed_aquifers def add_conflict(self, data, msg): """ Logs a conflict to be returned as a list of conflicts """ self.conflicts.append({ **data, 'message': msg, }) def build_vertical_aquifer_extent_model(self, well, aquifer, from_depth, to_depth): """ A new VerticalAquiferExtentModel which uses the well's geom """ if well.geom: longitude = well.geom.x latitude = well.geom.y point = Point(-abs(float(longitude)), float(latitude), srid=4326) return VerticalAquiferExtent( well=well, aquifer=aquifer, geom=point, start=from_depth, end=None if math.isinf(to_depth) else to_depth, create_user=self.request.user.profile.username, create_date=self.create_date ) def check_extent_overlaps(self, from_depth, to_depth, existing_extents): """ Checks an extent against a list of existing extents """ if len(existing_extents) == 0: return False max_depth = float('-inf') for extent in existing_extents: start = extent['start'] end = extent['end'] if extent['end'] is not None else Decimal('Infinity') if from_depth >= max_depth and to_depth <= start: return False max_depth = end return from_depth < max_depth # check the bottom of all extents def return_errors(self): # roll back the transaction as the bulk_update could have run for one # aquifer but errored on another. Best to abort the whole thing and warn the user transaction.set_rollback(True) errors = { 'unknownAquifers': self.unknown_aquifer_ids, 'unknownWells': self.unknown_well_tag_numbers, 'conflicts': self.conflicts } return Response(errors, status=status.HTTP_400_BAD_REQUEST) def create_vertical_aquifer_extents(self, models): """ Creates all the vertical aquifer extents and history log items all at once """ logger.info("Bulk updating %d VerticalAquiferExtents", len(models)) # bulk update using efficient SQL for any well aquifer correlations that have changed VerticalAquiferExtent.objects.bulk_create(models) # save the BulkWellAquiferCorrelation records VerticalAquiferExtentsHistory.objects.bulk_create(self.change_log) def append_to_history_log(self, model): """ Adds a vertical aquifer extent's data to the history log """ bulk_history_item = VerticalAquiferExtentsHistory( well_tag_number=model.well_id, aquifer_id=model.aquifer_id, geom=model.geom, start=model.start, end=model.end, create_user=self.request.user.profile.username, create_date=self.create_date ) self.change_log.append(bulk_history_item)
apache-2.0
-6,203,309,790,408,724,000
41.787879
123
0.620288
false
3.633413
false
false
false
live-clones/dolfin-adjoint
tests_dolfin/optimization_scalar/optimization_scalar.py
1
1880
from __future__ import print_function from dolfin import * from dolfin_adjoint import * import sys dolfin.set_log_level(ERROR) n = 10 mesh = UnitIntervalMesh(n) V = FunctionSpace(mesh, "CG", 2) ic = project(Expression("sin(2*pi*x[0])", degree=1), V) u = ic.copy(deepcopy=True) def main(nu): u_next = Function(V) v = TestFunction(V) timestep = Constant(1.0/n, name="Timestep") F = ((u_next - u)/timestep*v + u_next*u_next.dx(0)*v + nu*u_next.dx(0)*v.dx(0))*dx bc = DirichletBC(V, 0.0, "on_boundary") t = 0.0 end = 0.1 while (t <= end): solve(F == 0, u_next, bc) u.assign(u_next) t += float(timestep) adj_inc_timestep() def eval_cb(j, m): print("j = %f, m = %f." % (j, float(m))) def derivative_cb(j, dj, m): print("j = %f, dj = %f, m = %f." % (j, dj, float(m))) def replay_cb(var, data, m): #print "Got data for variable %s at m = %f." % (var, float(m)) pass if __name__ == "__main__": nu = Constant(0.0001, name="Nu") # Run the forward model once to have the annotation main(nu) J = Functional(inner(u, u)*dx*dt[FINISH_TIME]) # Run the optimisation reduced_functional = ReducedFunctional(J, ConstantControl("Nu"), eval_cb_post= eval_cb, derivative_cb_post=derivative_cb, replay_cb=replay_cb, scale=2.0) try: nu_opt = minimize(reduced_functional, 'SLSQP') tol = 1e-4 if reduced_functional(nu_opt) > tol: print('Test failed: Optimised functional value exceeds tolerance: ', reduced_functional(nu_opt), ' > ', tol, '.') sys.exit(1) except ImportError: info_red("No suitable scipy version found. Aborting test.")
lgpl-3.0
-1,891,839,056,240,876,000
27.923077
125
0.534574
false
3.122924
false
false
false
Eternali/synk
synk-pre/synk-pre.py
1
5279
''' Synk - Sublime Text Plugin ''' import os import socket import sublime import sublime_plugin from threading import Thread, Timer # variables for storing user defined settings settings_filename = "synk_pre.sublime-settings" enabled_field = "enabled" server_ips_field = "project_server_ips" # NOTE: add feature to have more than one server later uplink_ports_field = "uplink_ports" downlink_ports_field = "downlink_ports" all_files_field = "synk_all_files" current_file_field = "synk_current_file" delay_field = "delay_in_seconds" # Object for connecting to the server class ServerConnection(object): def __init__(self, attempts=5): self.settings = sublime.load_settings(settings_filename) self.delay = self.settings.get(delay_field) self.server = self.settings.get(server_ips_field) self.up_port = self.settings.get(uplink_ports_field) self.down_port = self.settings.get(downlink_ports_field) self.current_file = self.settings.get(current_file_field) self.upsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.downsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.file_locked = False for a in range(attempts): try: self.upsock.connect((self.server, self.up_port)) self.downsock.connect((self.server, self.down_port)) return except: continue sublime.status_message("An error occured while attempting to connect to the server.") def recv_data(conn): received = "" while True: data = conn.recv(4096) received += data.decode("utf-8") if len(data) <= 4096: break return received def write_file(fname, data, mode="w"): with open(fname, mode) as f: for line in data: f.write(line + '\n') def push_changes(self, filename=self.current_file, attempts=30): for a in attempts: if not self.file_locked: self.file_locked = True data = self.current_file + '\n' + view.substr(sublime.Region(0, view.size())) self.upsock.send(data.encode("utf-8")) self.file_locked = False break def get_changes(self): #change_thread = Thread(target=self.get_changes_thread) #change_thread.start() Timer(self.delay, self.get_changes_thread).start() def get_changes_thread(self): while True: self.recved_data = self.recv_data(self.downsock) if len(self.recv_data) and not self.file_locked and not view.is_loading(): self.file_locked = True self.write_file(self.current_file, self.recved_data) self.file_locked = False class SynkPreListener(sublime_plugin.EventListener): save_queue = [] @staticmethod def generate_backup_filename(filename): dirname, basename = [os.path.dirname(filename), os.path.basename(filename).split('.')] if len(basename) > 1: basename.insert(-1, 'bak') else: basename.append('bak') return dirname + '/' + '.'.join(basename) def on_modified(self, view): settings = sublime.load_settings(settings_filename) if not (view.file_name() and view.is_dirty()): return delay = settings.get(delay_field) all_files = settings.get(all_files_field) current_file = settings.get(current_file_field) if not all_files and current_file != view.file_name(): return def callback(): settings = sublime.load_settings(settings_filename) current_file = settings.get(current_file_field) if view.is_dirty() and not view.is_loading(): view.run_command("save") serv_conn.push_changes(filename=current_file) else: content = view.substr(sublime.Region(0, view.size())) try: with open(SynkPreListener.generate_backup_filename(view.filename()), 'w', encoding="utf-8") as f: f.write(content) except Exception as e: sublime.status_message(str(e)) raise e class SynkPreCommand(sublime_plugin.TextCommand): def run(self, **kwargs): enable = kwargs.get("enable", None) all_files = kwargs.get("all_files", False) settings = sublime.load_settings(settings_filename) if enable is None: enable = not settings.get(enabled_field) if not enable: message = "Autosynk is turned off." filename = settings.get(current_file_field) settings.set(enabled_field, enable) settings.set(all_files_field, all_files) filename = sublime.Window.active_view(sublime.active_window()).file_name() settings.set(current_file_field, filename) if enable: message = "Autosynk is turned on." if not all_files: message += " for: " + os.path.basename(filename) serv_conn = ServerConnection() global serv_conn serv_conn.get_changes() sublime.status_message(message)
gpl-3.0
-5,355,001,853,979,260,000
33.730263
113
0.602387
false
3.867399
false
false
false
PostTenebrasLab/DrinkingBuddyServer
drinkingBuddyDB_declarative.py
1
3467
#!/usr/bin/python3 import os import sys from sqlalchemy import Column, ForeignKey, Integer, String, DateTime, Boolean from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine from marshmallow import Schema, fields from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow Base = declarative_base() class Category(Base): __tablename__ = 'categories' id = Column(Integer, primary_key=True) name = Column(String(50), nullable=False) class Terminal(Base): __tablename__ = 'terminals' id = Column(Integer, primary_key=True) name = Column(String(50), nullable=False) key = Column(String(64), nullable=False) class Functionality(Base): __tablename__ = 'functionalities' id = Column(Integer, primary_key=True) category_id = Column(Integer, ForeignKey('categories.id')) category = relationship(Category) terminal_id = Column(Integer, ForeignKey('terminals.id')) terminal = relationship(Terminal) class Item(Base): __tablename__ = 'items' id = Column(Integer, primary_key=True) name = Column(String(50), nullable=False) quantity = Column(Integer) minquantity = Column(Integer) price = Column(Integer) barcode = Column(String(32), nullable=True) pictureURL = Column(String(512), nullable=True) category_id = Column(Integer, ForeignKey('categories.id')) category = relationship(Category) class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(50)) balance = Column(Integer) type = Column(Integer) class Card(Base): __tablename__ = 'cards' id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('users.id')) user = relationship(User) class Locker(Base): __tablename__ = 'locker' id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('users.id')) user = relationship(User) class Transaction(Base): __tablename__ = 'transactions' id = Column(Integer, primary_key=True) date = Column(DateTime) value = Column(Integer) user_id = Column(Integer, ForeignKey('users.id')) user = relationship(User) class TransactionItem(Base): __tablename__ = 'transaction_items' id = Column(Integer, primary_key=True) date = Column(DateTime) quantity = Column(Integer) price_per_item = Column(Integer) canceled = Column(Boolean, default=False) canceled_date = Column(DateTime) element_id = Column(Integer, ForeignKey('items.id')) element = relationship(Item) transaction_id = Column(Integer, ForeignKey('transactions.id')) transaction = relationship(Transaction) class UserSchema(Schema): class Meta: fields = ("id", "name", "balance") class ItemSchema(Schema): class Meta: fields = ("id", "name") class TransactionItemSchema(Schema): element = fields.Nested(ItemSchema) class Meta: fields = ("id", "date", "value", "element_id", "element") class TransactionSchema(Schema): user = fields.Nested(UserSchema) transactionItems = fields.Nested(TransactionItemSchema, many=True) class Meta: fields = ("id", "date", "value", "user_id", "user", "transactionItems") # Create Database # engine = create_engine("sqlite:///db.db", echo=True) # Base.metadata.create_all(engine)
mit
974,896,659,334,482,000
27.418033
87
0.677531
false
3.847947
false
false
false
ifzing/ceilometer-extended-monitor
network/lbaas.py
1
2469
# -*- encoding: utf-8 -*- from ceilometer.openstack.common import log from ceilometer.openstack.common import timeutils from ceilometer.central import plugin from ceilometer import sample from ceilometer import neutron_client class LbaasInBytesPollster(plugin.CentralPollster): LOG = log.getLogger(__name__ + '.LBaaS') def _get_lb_in_bytes(self): in_bytes = [] nt = neutron_client.Client() for pool in nt._list_pools(): bytes = nt._get_lb_in_bytes(pool['id']) in_bytes.append({'id': pool['id'], 'bytes': bytes}) return in_bytes def _iter_pool_stats(self, cache): if 'in_bytes' not in cache: cache['in_bytes'] = list(self._get_lb_in_bytes()) return iter(cache['in_bytes']) def get_samples(self, manager, cache): for pool in self._iter_pool_stats(cache): self.LOG.info("LBAAS POOL: %s" % pool['id']) yield sample.Sample( name='network.lb.in.bytes', type=sample.TYPE_CUMULATIVE, unit='byte', volume=pool['bytes'], user_id=None, project_id=None, resource_id=pool['id'], timestamp=timeutils.utcnow().isoformat(), resource_metadata={}) class LbaasOutBytesPollster(plugin.CentralPollster): LOG = log.getLogger(__name__ + '.LBaaS') def _get_lb_out_bytes(self): in_bytes = [] nt = neutron_client.Client() for pool in nt._list_pools(): bytes = nt._get_lb_out_bytes(pool['id']) in_bytes.append({'id': pool['id'], 'bytes': bytes}) return in_bytes def _iter_pool_stats(self, cache): if 'out_bytes' not in cache: cache['out_bytes'] = list(self._get_lb_out_bytes()) return iter(cache['out_bytes']) def get_samples(self, manager, cache): for pool in self._iter_pool_stats(cache): self.LOG.info("LBAAS POOL: %s" % pool['id']) yield sample.Sample( name='network.lb.out.bytes', type=sample.TYPE_CUMULATIVE, unit='byte', volume=pool['bytes'], user_id=None, project_id=None, resource_id=pool['id'], timestamp=timeutils.utcnow().isoformat(), resource_metadata={})
apache-2.0
8,639,770,541,434,874,000
31.486842
63
0.534629
false
3.882075
false
false
false
bromjiri/Presto
predictor/predictor_new.py
1
8137
import settings import pandas as pd import numpy as np import os from datetime import datetime from datetime import timedelta import predictor.predictor_classifier as cls import predictor.predictor_statistic as stat import random import nltk class Stock: def __init__(self, subject): input_file = settings.PREDICTOR_STOCK + "/" + subject + ".csv" self.stock_df = pd.read_csv(input_file, sep=',', index_col='Date') def create_dict(self, from_date, to_date): self.stock_ser = self.stock_df['Diff'].loc[from_date:to_date] # binning self.stock_ser = self.stock_ser.apply(binning_none) self.stock_dict = self.stock_ser.dropna().astype(int).to_dict() def get_dict(self): return self.stock_dict def get_stock_dates(self): return self.stock_ser.index.values class Sent: def __init__(self, subject, source): input_file = settings.PREDICTOR_SENTIMENT + "/" + source + "/" + source + "-sent-" + subject + ".csv" self.sent_df = pd.read_csv(input_file, sep=',', index_col='Date') def get_weekend(self, col_name, stock_dates): weekend_df = np.round(self.sent_df, 2) aggreg = 0 days = 1 for idx, row in weekend_df.iterrows(): value = row[col_name] date = pd.to_datetime(idx) date_plus = date + timedelta(days=1) if str(date_plus.date()) not in stock_dates: # print("weekend") value += aggreg aggreg = value days += 1 else: total = value + aggreg mean = total / days aggreg = 0 days = 1 weekend_df.set_value(idx, col_name, mean) # print(date.date(), row[col_name], value) return np.round(weekend_df[col_name].diff().loc[stock_dates], 2) def create_dict(self, precision, method, from_date, to_date, stock_dates, binning): sentiment_col = "Sent" + precision sent_ser = self.sent_df[sentiment_col] if method == "Natural": sent_ser = sent_ser.diff().loc[from_date:to_date] elif method == "Friday": sent_ser = sent_ser.loc[stock_dates].diff() elif method == "Sunday": sent_ser = sent_ser.diff().loc[stock_dates] elif method == "Weekend": sent_ser = self.get_weekend(sentiment_col, stock_dates) # binning std_dev1 = sent_ser.std() / 4 std_dev2 = sent_ser.std() if binning == 'none': sent_ser_new = sent_ser.apply(binning_none) elif binning == 'low': sent_ser_new = sent_ser.apply(binning_low, args=(std_dev1,)) else: sent_ser_new = sent_ser.apply(binning_high, args=(std_dev1, std_dev2,)) # print(pd.concat([sent_ser, sent_ser_new], axis=1)) self.sent_dict = sent_ser_new.dropna().astype(int).to_dict() self.key_list = sorted(self.sent_dict.keys()) def get_dict(self): return self.sent_dict def get_features(self, key): index = self.key_list.index(key) features = dict() features['d1'] = self.sent_dict[self.key_list[index-3]] features['d2'] = self.sent_dict[self.key_list[index-2]] features['d3'] = self.sent_dict[self.key_list[index-1]] return features def binning_none(row): if row > 0: return 4 elif row < 0: return 0 else: return row def binning_low(row, std_dev1): if row > std_dev1: return 4 elif row < std_dev1 and row > -std_dev1: return 2 elif row < -std_dev1: return 0 else: return row def binning_high(row, std_dev1, std_dev2): if row > std_dev2: return 4 elif row < std_dev2 and row > std_dev1: return 3 elif row < std_dev1 and row > -std_dev1: return 2 elif row < -std_dev1 and row > -std_dev2: return 1 elif row < -std_dev2: return 0 else: return row def run_one(source, subject, precision, method, from_date, to_date, binning, filename_nltk, filename_skl): # stock dataframe stock = Stock(subject) stock.create_dict(from_date, to_date) stock_dict = stock.get_dict() # print(sorted(stock_dict.items())) indexes = ["djia", "snp", "nasdaq"] # if subject in indexes: # subject = "the" # sentiment dataframe sent = Sent(subject, source) sent.create_dict(precision, method, from_date, to_date, stock.get_stock_dates(), binning) # print(sorted(sent.get_dict().items())) # features features_list = list() for key in sorted(stock_dict)[3:]: features = sent.get_features(key) features_list.append([features, stock_dict[key]]) # print([key, sorted(features.items()), stock_dict[key]]) features_list_pos = list() features_list_neg = list() for feature in features_list: if feature[1] == 0: features_list_neg.append(feature) else: features_list_pos.append(feature) statistic = stat.Statistic(source, subject, precision, method, binning) # print(len(features_list), len(features_list_pos), len(features_list_neg)) max_half = min(len(features_list_pos), len(features_list_neg)) train_border = int(max_half * 4 / 5) # print(train_border, max_half) # exit() cycles = 50 for x in range(0, cycles): random.shuffle(features_list_pos) random.shuffle(features_list_neg) # random.shuffle(features_list) trainfeats = features_list_pos[:train_border] + features_list_neg[:train_border] testfeats = features_list_pos[train_border:max_half] + features_list_neg[train_border:max_half] # print(len(trainfeats), len(testfeats)) # trainfeats = features_list[:170] # testfeats = features_list[170:] nlt_output, skl_output = cls.train(trainfeats, testfeats, nlt=nltk_run, skl=sklearn_run) # print(nlt_output['most1']) # exit() if nltk_run: statistic.add_nltk(nlt_output) if sklearn_run: statistic.add_skl(skl_output) if nltk_run: statistic.mean_nltk(cycles) statistic.print_nltk() # statistic.write_nltk(filename_nltk) if sklearn_run: statistic.mean_skl(cycles) statistic.print_skl() statistic.print_stddev() # statistic.write_skl(filename_skl) nltk_run = True sklearn_run = True from_date = '2016-11-01' to_date = '2017-08-31' source = "stwits-comb" binnings = ['none', 'low', 'high'] # subjects = ["snp", "djia", "nasdaq"] subjects = ["djia", "snp", "nasdaq"] # subjects = ["microsoft"] precisions = ["0.6", "0.8", "1.0"] # precisions = ["0.6"] methods = ["Friday", "Natural", "Weekend", "Sunday"] # methods = ["Friday"] for subject in subjects: folder = settings.PREDICTOR_PREDICTION + '/' + source + '/' + subject + '/' os.makedirs(folder, exist_ok=True) filename_nltk = folder + source + '-prediction-' + subject + "-nltk.csv" filename_skl = folder + source + '-prediction-' + subject + "-skl.csv" # if nltk_run: # open(filename_nltk, 'w').close() # # if sklearn_run: # open(filename_skl, 'w').close() for method in methods: # if nltk_run: # f = open(filename_nltk, 'a') # f.write(source + ", " + subject + ", " + method + ", NLTK\n") # f.write("precision, binning, accuracy, pos_prec, neg_prec, pos_rec, neg_rec, d1, d2, d3\n") # f.close() # # if sklearn_run: # f = open(filename_skl, 'a') # f.write(source + ", " + subject + ", " + method + ", SKL\n") # f.write("precision, binning, mnb, bnb, lr, lsvc, nsvc, voted\n") # f.close() for precision in precisions: for binning in binnings: # print(source, subject, precision, method) run_one(source, subject, precision, method, from_date, to_date, binning, filename_nltk, filename_skl)
mit
-6,080,565,351,509,108,000
28.915441
117
0.577731
false
3.313111
false
false
false
imgos/asterisk-scripts
script/googlecontacts.py
1
2701
#!/usr/bin/python3 """Get Google Contacts Usage: google_contacts.py [--noauth_local_webserver] Options: --noauth_local_webserver passed on to google auth """ import docopt import httplib2 import subprocess import unidecode from apiclient import discovery from argparse import Namespace from oauth2client import client from oauth2client import tools from oauth2client.file import Storage ### APPLICATION_NAME = "Asterisk DB Updater" # If modifying these scopes, delete your previously saved credentials SCOPES = [ "https://www.googleapis.com/auth/contacts.readonly", "https://www.googleapis.com/auth/people.readonly", ] OAUTH_CONFIG_FILE = "/etc/asterisk-scripts/asterisk_client_secrets.json" OAUTH_TOKEN_FILE = "/etc/asterisk-scripts/asterisk_script_tokens.json" ### def get_credentials(flags): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. :param flags: oauth flags :return: the obtained credentials """ store = Storage(OAUTH_TOKEN_FILE) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(OAUTH_CONFIG_FILE, SCOPES) flow.user_agent = APPLICATION_NAME credentials = tools.run_flow(flow, store, flags) print(f"Storing credentials to: {OAUTH_TOKEN_FILE}") return credentials def main(): """Update asterisk db from google contacts""" opts = docopt.docopt(__doc__) flags = Namespace( auth_host_name="localhost", auth_host_port=[8080, 8090], logging_level="ERROR", noauth_local_webserver=opts["--noauth_local_webserver"], ) credentials = get_credentials(flags) http = credentials.authorize(httplib2.Http()) if opts["--noauth_local_webserver"]: return service = discovery.build("people", "v1", http=http) contacts_response = ( service.people() .connections() .list( resourceName="people/me", personFields="names,phoneNumbers", sortOrder="LAST_NAME_ASCENDING", ) .execute() ) for i, contact in enumerate(contacts_response["connections"]): display_name = ( contact["names"][0]["displayName"] if len(contact["names"]) > 0 else "Unknown" ) for phone in contact["phoneNumbers"]: ast_cmd = f'database put cidname {phone["canonicalForm"]} "{display_name}"' subprocess.run(["asterisk", "-rx", unidecode.unidecode(ast_cmd)]) if __name__ == "__main__": main()
mit
-8,137,995,456,563,472,000
26.561224
87
0.654202
false
3.920174
false
false
false
dingmingliu/quanttrade
bt/core.py
1
37660
""" Contains the core building blocks of the framework. """ import math from copy import deepcopy import pandas as pd import numpy as np import cython as cy class Node(object): """ The Node is the main building block in bt's tree structure design. Both StrategyBase and SecurityBase inherit Node. It contains the core functionality of a tree node. Args: * name (str): The Node name * parent (Node): The parent Node * children (dict, list): A collection of children. If dict, the format is {name: child}, if list then list of children. Attributes: * name (str): Node name * parent (Node): Node parent * root (Node): Root node of the tree (topmost node) * children (dict): Node's children * now (datetime): Used when backtesting to store current date * stale (bool): Flag used to determine if Node is stale and need updating * prices (TimeSeries): Prices of the Node. Prices for a security will be the security's price, for a strategy it will be an index that reflects the value of the strategy over time. * price (float): last price * value (float): last value * weight (float): weight in parent * full_name (str): Name including parents' names * members (list): Current Node + node's children """ _price = cy.declare(cy.double) _value = cy.declare(cy.double) _weight = cy.declare(cy.double) _issec = cy.declare(cy.bint) _has_strat_children = cy.declare(cy.bint) def __init__(self, name, parent=None, children=None): self.name = name # strategy children helpers self._has_strat_children = False self._strat_children = [] # if children is not None, we assume that we want to limit the # available children space to the provided list. if children is not None: if isinstance(children, list): # if all strings - just save as universe_filter if all(isinstance(x, str) for x in children): self._universe_tickers = children # empty dict - don't want to uselessly create # tons of children when they might not be needed children = {} else: # this will be case if we pass in children # (say a bunch of sub-strategies) tmp = {} ut = [] for c in children: if type(c) == str: tmp[c] = SecurityBase(c) ut.append(c) else: # deepcopy object for possible later reuse tmp[c.name] = deepcopy(c) # if strategy, turn on flag and add name to list # strategy children have special treatment if isinstance(c, StrategyBase): self._has_strat_children = True self._strat_children.append(c.name) # if not strategy, then we will want to add this to # universe_tickers to filter on setup else: ut.append(c.name) children = tmp # we want to keep whole universe in this case # so set to None self._universe_tickers = ut if parent is None: self.parent = self self.root = self else: self.parent = parent self.root = parent.root parent._add_child(self) # default children if children is None: children = {} self._universe_tickers = None self.children = children self._childrenv = children.values() for c in self._childrenv: c.parent = self c.root = self.root # set default value for now self.now = 0 # make sure root has stale flag # used to avoid unncessary update # sometimes we change values in the tree and we know that we will need # to update if another node tries to access a given value (say weight). # This avoid calling the update until it is actually needed. self.root.stale = False # helper vars self._price = 0 self._value = 0 self._weight = 0 # is security flag - used to avoid updating 0 pos securities self._issec = False def __getitem__(self, key): return self.children[key] @property def prices(self): """ A TimeSeries of the Node's price. """ # can optimize depending on type - # securities don't need to check stale to # return latest prices, whereas strategies do... raise NotImplementedError() @property def price(self): """ Current price of the Node """ # can optimize depending on type - # securities don't need to check stale to # return latest prices, whereas strategies do... raise NotImplementedError() @property def value(self): """ Current value of the Node """ if self.root.stale: self.root.update(self.root.now, None) return self._value @property def weight(self): """ Current weight of the Node (with respect to the parent). """ if self.root.stale: self.root.update(self.root.now, None) return self._weight def setup(self, dates): """ Setup method used to initialize a Node with a set of dates. """ raise NotImplementedError() def _add_child(self, child): child.parent = self child.root = self.root if self.children is None: self.children = {child.name: child} else: self.children[child.name] = child self._childrenv = self.children.values() def update(self, date, data=None, inow=None): """ Update Node with latest date, and optionally some data. """ raise NotImplementedError() def adjust(self, amount, update=True, isflow=True): """ Adjust Node value by amount. """ raise NotImplementedError() def allocate(self, amount, update=True): """ Allocate capital to Node. """ raise NotImplementedError() @property def members(self): """ Node members. Members include current node as well as Node's children. """ res = [self] for c in self.children.values(): res.extend(c.members) return res @property def full_name(self): if self.parent == self: return self.name else: return '%s>%s' % (self.parent.full_name, self.name) class StrategyBase(Node): """ Strategy Node. Used to define strategy logic within a tree. A Strategy's role is to allocate capital to it's children based on a function. Args: * name (str): Strategy name * children (dict, list): A collection of children. If dict, the format is {name: child}, if list then list of children. Children can be any type of Node. * parent (Node): The parent Node Attributes: * name (str): Strategy name * parent (Strategy): Strategy parent * root (Strategy): Root node of the tree (topmost node) * children (dict): Strategy's children * now (datetime): Used when backtesting to store current date * stale (bool): Flag used to determine if Strategy is stale and need updating * prices (TimeSeries): Prices of the Strategy - basically an index that reflects the value of the strategy over time. * price (float): last price * value (float): last value * weight (float): weight in parent * full_name (str): Name including parents' names * members (list): Current Strategy + strategy's children * commission_fn (fn(quantity, price)): A function used to determine the commission (transaction fee) amount. Could be used to model slippage (implementation shortfall). Note that often fees are symmetric for buy and sell and absolute value of quantity should be used for calculation. * capital (float): Capital amount in Strategy - cash * universe (DataFrame): Data universe available at the current time. Universe contains the data passed in when creating a Backtest. Use this data to determine strategy logic. """ _capital = cy.declare(cy.double) _net_flows = cy.declare(cy.double) _last_value = cy.declare(cy.double) _last_price = cy.declare(cy.double) _last_fee = cy.declare(cy.double) _paper_trade = cy.declare(cy.bint) bankrupt = cy.declare(cy.bint) def __init__(self, name, children=None, parent=None): Node.__init__(self, name, children=children, parent=parent) self._capital = 0 self._weight = 1 self._value = 0 self._price = 100 # helper vars self._net_flows = 0 self._last_value = 0 self._last_price = 100 self._last_fee = 0 # default commission function self.commission_fn = self._dflt_comm_fn self._paper_trade = False self._positions = None self.bankrupt = False @property def price(self): """ Current price. """ if self.root.stale: self.root.update(self.now, None) return self._price @property def prices(self): """ TimeSeries of prices. """ if self.root.stale: self.root.update(self.now, None) return self._prices.ix[:self.now] @property def values(self): """ TimeSeries of values. """ if self.root.stale: self.root.update(self.now, None) return self._values.ix[:self.now] @property def capital(self): """ Current capital - amount of unallocated capital left in strategy. """ # no stale check needed return self._capital @property def cash(self): """ TimeSeries of unallocated capital. """ # no stale check needed return self._cash @property def fees(self): """ TimeSeries of fees. """ # no stale check needed return self._fees @property def universe(self): """ Data universe available at the current time. Universe contains the data passed in when creating a Backtest. Use this data to determine strategy logic. """ # avoid windowing every time # if calling and on same date return # cached value if self.now == self._last_chk: return self._funiverse else: self._last_chk = self.now self._funiverse = self._universe.ix[:self.now] return self._funiverse @property def positions(self): """ TimeSeries of positions. """ # if accessing and stale - update first if self.root.stale: self.root.update(self.root.now, None) if self._positions is not None: return self._positions else: vals = pd.DataFrame({x.name: x.positions for x in self.members if isinstance(x, SecurityBase)}) self._positions = vals return vals def setup(self, universe): """ Setup strategy with universe. This will speed up future calculations and updates. """ # save full universe in case we need it self._original_data = universe # determine if needs paper trading # and setup if so if self is not self.parent: self._paper_trade = True self._paper_amount = 1000000 paper = deepcopy(self) paper.parent = paper paper.root = paper paper._paper_trade = False paper.setup(self._original_data) paper.adjust(self._paper_amount) self._paper = paper # setup universe funiverse = universe if self._universe_tickers is not None: # if we have universe_tickers defined, limit universe to # those tickers valid_filter = list(set(universe.columns) .intersection(self._universe_tickers)) funiverse = universe[valid_filter].copy() # if we have strat children, we will need to create their columns # in the new universe if self._has_strat_children: for c in self._strat_children: funiverse[c] = np.nan # must create to avoid pandas warning funiverse = pd.DataFrame(funiverse) self._universe = funiverse # holds filtered universe self._funiverse = funiverse self._last_chk = None # We're not bankrupt yet self.bankrupt = False # setup internal data self.data = pd.DataFrame(index=funiverse.index, columns=['price', 'value', 'cash', 'fees'], data=0.0) self._prices = self.data['price'] self._values = self.data['value'] self._cash = self.data['cash'] self._fees = self.data['fees'] # setup children as well - use original universe here - don't want to # pollute with potential strategy children in funiverse if self.children is not None: [c.setup(universe) for c in self._childrenv] @cy.locals(newpt=cy.bint, val=cy.double, ret=cy.double) def update(self, date, data=None, inow=None): """ Update strategy. Updates prices, values, weight, etc. """ # resolve stale state self.root.stale = False # update helpers on date change # also set newpt flag newpt = False if self.now == 0: newpt = True elif date != self.now: self._net_flows = 0 self._last_price = self._price self._last_value = self._value self._last_fee = 0.0 newpt = True # update now self.now = date if inow is None: if self.now == 0: inow = 0 else: inow = self.data.index.get_loc(date) # update children if any and calculate value val = self._capital # default if no children if self.children is not None: for c in self._childrenv: # avoid useless update call if c._issec and not c._needupdate: continue c.update(date, data, inow) val += c.value if self.root == self: if (val < 0) and not self.bankrupt: # Declare a bankruptcy self.bankrupt = True self.flatten() # update data if this value is different or # if now has changed - avoid all this if not since it # won't change if newpt or self._value != val: self._value = val self._values.values[inow] = val try: ret = self._value / (self._last_value + self._net_flows) - 1 except ZeroDivisionError: if self._value == 0: ret = 0 else: raise ZeroDivisionError( 'Could not update %s. Last value ' 'was %s and net flows were %s. Current' 'value is %s. Therefore, ' 'we are dividing by zero to obtain the return ' 'for the period.' % (self.name, self._last_value, self._net_flows, self._value)) self._price = self._last_price * (1 + ret) self._prices.values[inow] = self._price # update children weights if self.children is not None: for c in self._childrenv: # avoid useless update call if c._issec and not c._needupdate: continue try: c._weight = c.value / val except ZeroDivisionError: c._weight = 0.0 # if we have strategy children, we will need to update them in universe if self._has_strat_children: for c in self._strat_children: # TODO: optimize ".loc" here as well self._universe.loc[date, c] = self.children[c].price # Cash should track the unallocated capital at the end of the day, so # we should update it every time we call "update". # Same for fees self._cash.values[inow] = self._capital self._fees.values[inow] = self._last_fee # update paper trade if necessary if newpt and self._paper_trade: self._paper.update(date) self._paper.run() self._paper.update(date) # update price self._price = self._paper.price self._prices.values[inow] = self._price @cy.locals(amount=cy.double, update=cy.bint, flow=cy.bint, fees=cy.double) def adjust(self, amount, update=True, flow=True, fee=0.0): """ Adjust capital - used to inject capital to a Strategy. This injection of capital will have no effect on the children. Args: * amount (float): Amount to adjust by. * update (bool): Force update? * flow (bool): Is this adjustment a flow? Basically a flow will have an impact on the price index. Examples of flows are commissions. """ # adjust capital self._capital += amount self._last_fee += fee # if flow - increment net_flows - this will not affect # performance. Commissions and other fees are not flows since # they have a performance impact if flow: self._net_flows += amount if update: # indicates that data is now stale and must # be updated before access self.root.stale = True @cy.locals(amount=cy.double, update=cy.bint) def allocate(self, amount, child=None, update=True): """ Allocate capital to Strategy. By default, capital is allocated recursively down the children, proportionally to the children's weights. If a child is specified, capital will be allocated to that specific child. Allocation also have a side-effect. They will deduct the same amount from the parent's "account" to offset the allocation. If there is remaining capital after allocation, it will remain in Strategy. Args: * amount (float): Amount to allocate. * child (str): If specified, allocation will be directed to child only. Specified by name. * update (bool): Force update. """ # allocate to child if child is not None: if child not in self.children: c = SecurityBase(child) c.setup(self._universe) # update to bring up to speed c.update(self.now) # add child to tree self._add_child(c) # allocate to child self.children[child].allocate(amount) # allocate to self else: # adjust parent's capital # no need to update now - avoids repetition if self.parent == self: self.parent.adjust(-amount, update=False, flow=True) else: # do NOT set as flow - parent will be another strategy # and therefore should not incur flow self.parent.adjust(-amount, update=False, flow=False) # adjust self's capital self.adjust(amount, update=False, flow=True) # push allocation down to children if any # use _weight to avoid triggering an update if self.children is not None: [c.allocate(amount * c._weight, update=False) for c in self._childrenv] # mark as stale if update requested if update: self.root.stale = True @cy.locals(delta=cy.double, weight=cy.double, base=cy.double) def rebalance(self, weight, child, base=np.nan, update=True): """ Rebalance a child to a given weight. This is a helper method to simplify code logic. This method is used when we want to se the weight of a particular child to a set amount. It is similar to allocate, but it calculates the appropriate allocation based on the current weight. Args: * weight (float): The target weight. Usually between -1.0 and 1.0. * child (str): child to allocate to - specified by name. * base (float): If specified, this is the base amount all weight delta calculations will be based off of. This is useful when we determine a set of weights and want to rebalance each child given these new weights. However, as we iterate through each child and call this method, the base (which is by default the current value) will change. Therefore, we can set this base to the original value before the iteration to ensure the proper allocations are made. * update (bool): Force update? """ # if weight is 0 - we want to close child if weight == 0: if child in self.children: return self.close(child) else: return # if no base specified use self's value if np.isnan(base): base = self.value # else make sure we have child if child not in self.children: c = SecurityBase(child) c.setup(self._universe) # update child to bring up to speed c.update(self.now) self._add_child(c) # allocate to child # figure out weight delta c = self.children[child] delta = weight - c.weight c.allocate(delta * base) def close(self, child): """ Close a child position - alias for rebalance(0, child). This will also flatten (close out all) the child's children. Args: * child (str): Child, specified by name. """ c = self.children[child] # flatten if children not None if c.children is not None and len(c.children) != 0: c.flatten() c.allocate(-c.value) def flatten(self): """ Close all child positions. """ # go right to base alloc [c.allocate(-c.value) for c in self._childrenv if c.value != 0] def run(self): """ This is the main logic method. Override this method to provide some algorithm to execute on each date change. This method is called by backtester. """ pass def set_commissions(self, fn): """ Set commission (transaction fee) function. Args: fn (fn(quantity, price)): Function used to determine commission amount. """ self.commission_fn = fn for c in self._childrenv: if isinstance(c, StrategyBase): c.set_commissions(fn) @cy.locals(q=cy.double, p=cy.double) def _dflt_comm_fn(self, q, p): return max(1, abs(q) * 0.01) class SecurityBase(Node): """ Security Node. Used to define a security within a tree. A Security's has no children. It simply models an asset that can be bought or sold. Args: * name (str): Security name * multiplier (float): security multiplier - typically used for derivatives. Attributes: * name (str): Security name * parent (Security): Security parent * root (Security): Root node of the tree (topmost node) * now (datetime): Used when backtesting to store current date * stale (bool): Flag used to determine if Security is stale and need updating * prices (TimeSeries): Security prices. * price (float): last price * value (float): last value - basically position * price * multiplier * weight (float): weight in parent * full_name (str): Name including parents' names * members (list): Current Security + strategy's children * position (float): Current position (quantity). """ _last_pos = cy.declare(cy.double) _position = cy.declare(cy.double) multiplier = cy.declare(cy.double) _prices_set = cy.declare(cy.bint) _needupdate = cy.declare(cy.bint) @cy.locals(multiplier=cy.double) def __init__(self, name, multiplier=1): Node.__init__(self, name, parent=None, children=None) self._value = 0 self._price = 0 self._weight = 0 self._position = 0 self.multiplier = multiplier # opt self._last_pos = 0 self._issec = True self._needupdate = True @property def price(self): """ Current price. """ # if accessing and stale - update first if self._needupdate or self.now != self.parent.now: self.update(self.root.now) return self._price @property def prices(self): """ TimeSeries of prices. """ # if accessing and stale - update first if self._needupdate or self.now != self.parent.now: self.update(self.root.now) return self._prices.ix[:self.now] @property def values(self): """ TimeSeries of values. """ # if accessing and stale - update first if self._needupdate or self.now != self.parent.now: self.update(self.root.now) if self.root.stale: self.root.update(self.root.now, None) return self._values.ix[:self.now] @property def position(self): """ Current position """ # no stale check needed return self._position @property def positions(self): """ TimeSeries of positions. """ # if accessing and stale - update first if self._needupdate: self.update(self.root.now) if self.root.stale: self.root.update(self.root.now, None) return self._positions.ix[:self.now] def setup(self, universe): """ Setup Security with universe. Speeds up future runs. Args: * universe (DataFrame): DataFrame of prices with security's name as one of the columns. """ # if we already have all the prices, we will store them to speed up # future udpates try: prices = universe[self.name] except KeyError: prices = None # setup internal data if prices is not None: self._prices = prices self.data = pd.DataFrame(index=universe.index, columns=['value', 'position'], data=0.0) self._prices_set = True else: self.data = pd.DataFrame(index=universe.index, columns=['price', 'value', 'position']) self._prices = self.data['price'] self._prices_set = False self._values = self.data['value'] self._positions = self.data['position'] @cy.locals(prc=cy.double) def update(self, date, data=None, inow=None): """ Update security with a given date and optionally, some data. This will update price, value, weight, etc. """ # filter for internal calls when position has not changed - nothing to # do. Internal calls (stale root calls) have None data. Also want to # make sure date has not changed, because then we do indeed want to # update. if date == self.now and self._last_pos == self._position: return if inow is None: if date == 0: inow = 0 else: inow = self.data.index.get_loc(date) # date change - update price if date != self.now: # update now self.now = date if self._prices_set: self._price = self._prices.values[inow] # traditional data update elif data is not None: prc = data[self.name] self._price = prc self._prices.values[inow] = prc self._positions.values[inow] = self._position self._last_pos = self._position self._value = self._position * self._price * self.multiplier self._values.values[inow] = self._value if self._weight == 0 and self._position == 0: self._needupdate = False @cy.locals(amount=cy.double, update=cy.bint, q=cy.double, outlay=cy.double) def allocate(self, amount, update=True): """ This allocates capital to the Security. This is the method used to buy/sell the security. A given amount of shares will be determined on the current price, a commisison will be calculated based on the parent's commission fn, and any remaining capital will be passed back up to parent as an adjustment. Args: * amount (float): Amount of adjustment. * update (bool): Force update? """ # will need to update if this has been idle for a while... # update if needupdate or if now is stale # fetch parent's now since our now is stale if self._needupdate or self.now != self.parent.now: self.update(self.parent.now) # ignore 0 alloc # Note that if the price of security has dropped to zero, then it should # never be selected by SelectAll, SelectN etc. I.e. we should not open # the position at zero price. At the same time, we are able to close # it at zero price, because at that point amount=0. # Note also that we don't erase the position in an asset which price has # dropped to zero (though the weight will indeed be = 0) if amount == 0: return if self.parent is self or self.parent is None: raise Exception( 'Cannot allocate capital to a parentless security') if self._price == 0 or np.isnan(self._price): raise Exception( 'Cannot allocate capital to ' '%s because price is 0 or nan as of %s' % (self.name, self.parent.now)) # buy/sell # determine quantity - must also factor in commission # closing out? if amount == -self._value: q = -self._position else: if (self._position > 0) or ((self._position == 0) and (amount > 0)): # if we're going long or changing long position q = math.floor(amount / (self._price * self.multiplier)) else: # if we're going short or changing short position q = math.ceil(amount / (self._price * self.multiplier)) # if q is 0 nothing to do if q == 0 or np.isnan(q): return # this security will need an update, even if pos is 0 (for example if # we close the positions, value and pos is 0, but still need to do that # last update) self._needupdate = True # adjust position & value self._position += q # calculate proper adjustment for parent # parent passed down amount so we want to pass # -outlay back up to parent to adjust for capital # used outlay, fee = self.outlay(q) # call parent self.parent.adjust(-outlay, update=update, flow=False, fee=fee) @cy.locals(q=cy.double, p=cy.double) def commission(self, q, p): """ Calculates the commission (transaction fee) based on quantity and price. Uses the parent's commission_fn. Args: * q (float): quantity * p (float): price """ return self.parent.commission_fn(q, p) @cy.locals(q=cy.double) def outlay(self, q): """ Determines the complete cash outlay (including commission) necessary given a quantity q. Second returning parameter is a commission itself. Args: * q (float): quantity """ fee = self.commission(q, self._price * self.multiplier) full_outlay = q * self._price * self.multiplier + fee return full_outlay, fee def run(self): """ Does nothing - securities have nothing to do on run. """ pass class Algo(object): """ Algos are used to modularize strategy logic so that strategy logic becomes modular, composable, more testable and less error prone. Basically, the Algo should follow the unix philosophy - do one thing well. In practice, algos are simply a function that receives one argument, the Strategy (refered to as target) and are expected to return a bool. When some state preservation is necessary between calls, the Algo object can be used (this object). The __call___ method should be implemented and logic defined therein to mimic a function call. A simple function may also be used if no state preservation is neceesary. Args: * name (str): Algo name """ def __init__(self, name=None): self._name = name @property def name(self): """ Algo name. """ if self._name is None: self._name = self.__class__.__name__ return self._name def __call__(self, target): raise NotImplementedError("%s not implemented!" % self.name) class AlgoStack(Algo): """ An AlgoStack derives from Algo runs multiple Algos until a failure is encountered. The purpose of an AlgoStack is to group a logic set of Algos together. Each Algo in the stack is run. Execution stops if one Algo returns False. Args: * algos (list): List of algos. """ def __init__(self, *algos): super(AlgoStack, self).__init__() self.algos = algos self.check_run_always = any(hasattr(x, 'run_always') for x in self.algos) def __call__(self, target): # normal runing mode if not self.check_run_always: for algo in self.algos: if not algo(target): return False return True # run mode when at least one algo has a run_always attribute else: # store result in res # allows continuation to check for and run # algos that have run_always set to True res = True for algo in self.algos: if res: res = algo(target) elif hasattr(algo, 'run_always'): if algo.run_always: algo(target) return res class Strategy(StrategyBase): """ Strategy expands on the StrategyBase and incorporates Algos. Basically, a Strategy is built by passing in a set of algos. These algos will be placed in an Algo stack and the run function will call the stack. Furthermore, two class attributes are created to pass data between algos. perm for permanent data, temp for temporary data. Args: * name (str): Strategy name * algos (list): List of Algos to be passed into an AlgoStack * children (dict, list): Children - useful when you want to create strategies of strategies Attributes: * stack (AlgoStack): The stack * temp (dict): A dict containing temporary data - cleared on each call to run. This can be used to pass info to other algos. * perm (dict): Permanent data used to pass info from one algo to another. Not cleared on each pass. """ def __init__(self, name, algos=[], children=None): super(Strategy, self).__init__(name, children=children) self.stack = AlgoStack(*algos) self.temp = {} self.perm = {} def run(self): # clear out temp data self.temp = {} # run algo stack self.stack(self) # run children for c in self.children.values(): c.run()
apache-2.0
-3,770,879,272,697,670,000
32.151408
80
0.553877
false
4.469499
false
false
false
adamkovics/atmosphere
atmosphere/gas_opacity.py
1
8280
""" Add gas opacities to model based on the composition and vertical structure. """ import numpy as np import logging logger = logging.getLogger() def interpolate_kc(p, T, kc, verbose=False): """Linearly interpolate k-coefficients at a particular pressure and temperature, using the input k-coefficent grid, kc. The standard structure of k-coefficient data array is: [wavelengths,pressures,temperatures,g-nodes] where the g-node are the Legendre-Gauss quadrature nodes or "g-ordinate". Returned array of coefficients corresponds to: [wavelengths,g-nodes] """ pressures = np.array(kc['pressures']) temperatures = np.array(kc['temperatures']) ind_p = np.where(pressures < p) ind_T = np.where(temperatures < T) i = (np.max(ind_p) if np.size(ind_p) else np.array(0)).clip(0,len(pressures)-2) j = (np.max(ind_T) if np.size(ind_T) else np.array(0)).clip(0,len(temperatures)-2) L11 = np.log(kc['kc'][:,i,j,:]) L12 = np.log(kc['kc'][:,i+1,j,:]) L21 = np.log(kc['kc'][:,i,j+1,:]) L22 = np.log(kc['kc'][:,i+1,j+1,:]) L1T = L11 + (L12-L11)*(T-temperatures[j])/(temperatures[j+1]-temperatures[j]) L2T = L21 + (L22-L21)*(T-temperatures[j])/(temperatures[j+1]-temperatures[j]) LPT = L1T + (L2T-L1T)*((np.log(p)-np.log(pressures[i]))/ (np.log(pressures[i+1])-np.log(pressures[i]))) kc_interp = np.exp(LPT) return kc_interp def append_kc_to_layers(model, kc, species): """Set k-coefficients for each layer by interpolating to appropriate temperature and pressure and update the data structure for the amtosphere.""" kc_shape = (model['nlay'], model['nlam'], kc['ng']) model['layers'].update({'kc':{species:np.ndarray(kc_shape), 'ng':kc['ng'], 'g':kc['g'], 'w':kc['w'], }}) for i in range(model['nlay']): model['layers']['kc'][species][i,:,:] = interpolate_kc(model['layers']['p'][i], model['layers']['T'][i], kc) return # There are additional k-coefficients for C2H2, C2H6, and CO. # These are currently calculated on the VIMS grid as they are applicable in # roughly the 2.7--3um wavelength region that is inacccessible from the ground. # # Here we revise the gas opacity in the model to include multiple k-coefficient files. # # It is a reasonable estimate to sum k-coefficients after interpolating each onto the # same pressure and temperature, however, a minimal amount of error-checking should confirm # that the same wavelength grid and g-ordinates are being used. # # Overview of revisions to the code: # # (1) Generalization of the set_methane() to other species. # (2) Error-checking for wavelength (and P,T) grid # (3) back-compatibility for set_methane() method. # (4) Some thought to CH3D abundance variability. # def set_methane(model, kc_file, CH3D_scale=None, verbose=False): """Set methane opacities in atmosphere structure, model, by interpolatating k-coefficents from the specied kc_file, using the temperatures and pressures for each layer. """ if CH3D_scale: if len(kc_file) != 2: logger.debug('two k-coefficient files needed for set_methane_opacity()') return None kc = np.load(kc_file[0]).item() kc_CH3D = np.load(kc_file[1]).item() kc['kc'] = kc['kc']+CH3D_scale*kc_CH3D['kc'] model.update({'wavelength':kc['wavelength']['mu'], 'nlam':kc['wavelength']['nlam'], }) append_kc_to_layers(model, kc, 'CH4') tau_CH4 = model['layers']['kc']['CH4'] * np.reshape(model['layers']['N_CH4'], (model['nlay'],1,1)) if 'tau' not in model['layers']: model['layers'].update({'tau':{}}) model['layers']['tau'].update({'CH4':tau_CH4}) return if kc_file.endswith('.npy'): kc = np.load(kc_file).item() model.update({'wavelength':kc['wavelength']['mu'], 'nlam':kc['wavelength']['nlam'], }) append_kc_to_layers(model, kc, 'CH4') tau_CH4 = model['layers']['kc']['CH4'] * np.reshape(model['layers']['N_CH4'], (model['nlay'],1,1)) if 'tau' not in model['layers']: model['layers'].update({'tau':{}}) model['layers']['tau'].update({'CH4':tau_CH4}) return if kc_file.endswith('.fits'): import pyfits hdu = pyfits.open(kc_file) kc = {'kc': hdu[0].data, 'pressures':hdu[2].data['pressures'], 'temperatures':hdu[3].data['temperatures'], 'g': hdu[4].data['g'], 'w': hdu[5].data['w'], 'ng': hdu[0].header['NG'], } model.update({'wavelength':hdu[1].data['wavelength'], 'nlam':len(hdu[1].data['wavelength']), }) hdu.close() append_kc_to_layers(model, kc, 'CH4') tau_CH4 = model['layers']['kc']['CH4'] * np.reshape(model['layers']['N_CH4'], (model['nlay'],1,1)) if 'tau' not in model['layers']: model['layers'].update({'tau':{}}) model['layers']['tau'].update({'CH4':tau_CH4}) return def print_atmosphere_details(model): logger.debug('model dictionary data structure:') for item in model.keys(): logger.debug("{0:7s} - type: {2} - shape: {1}".format( item, np.shape(model[item]), type(model[item]))) logger.debug("\natmosphere['layers'] dictionary data structure:") for item in model['layers'].keys(): logger.debug("{0:7s} - type: {2} - shape: {1}".format( item, np.shape(model['layers'][item]), type(model['layers'][item]))) def set_cia(model, scale=4.0, show_figure=False): """Append collision-induced-absorption opacity for N2-N2 and H2-N2 (in the near-IR) to the atmosphere data structure, model.""" import pyfits import os fits = pyfits.open(os.path.join(os.getenv('RTDATAPATH'), 'gas_opacity/CIA/N2_N2.fits')) k_N2N2 = fits[0].data fits.close() fits = pyfits.open(os.path.join(os.getenv('RTDATAPATH'), 'gas_opacity/CIA/H2_N2.fits')) k_H2N2 = fits[0].data fits.close() if 'wavelength' not in model.keys(): logger.warning('Set wavelength scale first (e.g., with CH4 opacity.)') return None tau_H2N2 = np.empty((model['nlay'],model['nlam'])) tau_N2N2 = np.empty((model['nlay'],model['nlam'])) layers = model['layers'] N0 = 2.686e19 # Loschmidt number for i in range(model['nlay']): k_H2N2_interp = np.interp(model['wavelength'], (1e4/k_H2N2[::-1,0]), scale*k_H2N2[::-1,1],) k_N2N2_interp = np.interp(model['wavelength'], (1e4/k_N2N2[::-1,0]), scale*k_N2N2[::-1,1],) tau_H2N2[i,:] = k_H2N2_interp*layers['kmamg'][i] * \ layers['n'][i]/N0 * \ layers['m_N2'][i]*layers['m_H2'] tau_N2N2[i,:] = k_N2N2_interp*layers['kmamg'][i] * \ layers['n'][i]/N0 * \ layers['m_N2'][i]*layers['m_N2'][i] layers['tau'].update({'H2_N2':tau_H2N2, 'N2_N2':tau_N2N2,}) if show_figure: fig, ax = subplots(figsize=(16,4)) ax.plot(k_H2N2[:,0], k_H2N2[:,1], 'k', drawstyle='steps-mid') ax.set_xlabel('wavenumber (cm$^{-1}$)') ax.set_ylabel(r'km$^{-1}$ amagat$^{-2}$') ax.set_xlim(4000,5000) fig, ax = subplots(figsize=(16,4)) ax.plot(k_N2N2[:,0], k_N2N2[:,1], 'k', drawstyle='steps-mid') ax.set_xlabel('wavenumber (cm$^{-1}$)') ax.set_ylabel(r'km$^{-1}$ amagat$^{-2}$') ax.set_xlim(4000,5000) ;
gpl-2.0
4,651,276,065,316,480,000
39.004831
91
0.533333
false
3.189522
false
false
false
ArcherSys/ArcherSys
node_modules/npm/node_modules/node-gyp/gyp/buildbot/buildbot_run.py
1
18134
<<<<<<< HEAD <<<<<<< HEAD #!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Argument-less script to select what to run on the buildbots.""" import os import shutil import subprocess import sys if sys.platform in ['win32', 'cygwin']: EXE_SUFFIX = '.exe' else: EXE_SUFFIX = '' BUILDBOT_DIR = os.path.dirname(os.path.abspath(__file__)) TRUNK_DIR = os.path.dirname(BUILDBOT_DIR) ROOT_DIR = os.path.dirname(TRUNK_DIR) ANDROID_DIR = os.path.join(ROOT_DIR, 'android') CMAKE_DIR = os.path.join(ROOT_DIR, 'cmake') CMAKE_BIN_DIR = os.path.join(CMAKE_DIR, 'bin') OUT_DIR = os.path.join(TRUNK_DIR, 'out') def CallSubProcess(*args, **kwargs): """Wrapper around subprocess.call which treats errors as build exceptions.""" retcode = subprocess.call(*args, **kwargs) if retcode != 0: print '@@@STEP_EXCEPTION@@@' sys.exit(1) def PrepareCmake(): """Build CMake 2.8.8 since the version in Precise is 2.8.7.""" if os.environ['BUILDBOT_CLOBBER'] == '1': print '@@@BUILD_STEP Clobber CMake checkout@@@' shutil.rmtree(CMAKE_DIR) # We always build CMake 2.8.8, so no need to do anything # if the directory already exists. if os.path.isdir(CMAKE_DIR): return print '@@@BUILD_STEP Initialize CMake checkout@@@' os.mkdir(CMAKE_DIR) CallSubProcess(['git', 'config', '--global', 'user.name', 'trybot']) CallSubProcess(['git', 'config', '--global', 'user.email', 'chrome-bot@google.com']) CallSubProcess(['git', 'config', '--global', 'color.ui', 'false']) print '@@@BUILD_STEP Sync CMake@@@' CallSubProcess( ['git', 'clone', '--depth', '1', '--single-branch', '--branch', 'v2.8.8', '--', 'git://cmake.org/cmake.git', CMAKE_DIR], cwd=CMAKE_DIR) print '@@@BUILD_STEP Build CMake@@@' CallSubProcess( ['/bin/bash', 'bootstrap', '--prefix=%s' % CMAKE_DIR], cwd=CMAKE_DIR) CallSubProcess( ['make', 'cmake'], cwd=CMAKE_DIR) def PrepareAndroidTree(): """Prepare an Android tree to run 'android' format tests.""" if os.environ['BUILDBOT_CLOBBER'] == '1': print '@@@BUILD_STEP Clobber Android checkout@@@' shutil.rmtree(ANDROID_DIR) # The release of Android we use is static, so there's no need to do anything # if the directory already exists. if os.path.isdir(ANDROID_DIR): return print '@@@BUILD_STEP Initialize Android checkout@@@' os.mkdir(ANDROID_DIR) CallSubProcess(['git', 'config', '--global', 'user.name', 'trybot']) CallSubProcess(['git', 'config', '--global', 'user.email', 'chrome-bot@google.com']) CallSubProcess(['git', 'config', '--global', 'color.ui', 'false']) CallSubProcess( ['repo', 'init', '-u', 'https://android.googlesource.com/platform/manifest', '-b', 'android-4.2.1_r1', '-g', 'all,-notdefault,-device,-darwin,-mips,-x86'], cwd=ANDROID_DIR) print '@@@BUILD_STEP Sync Android@@@' CallSubProcess(['repo', 'sync', '-j4'], cwd=ANDROID_DIR) print '@@@BUILD_STEP Build Android@@@' CallSubProcess( ['/bin/bash', '-c', 'source build/envsetup.sh && lunch full-eng && make -j4'], cwd=ANDROID_DIR) def GypTestFormat(title, format=None, msvs_version=None): """Run the gyp tests for a given format, emitting annotator tags. See annotator docs at: https://sites.google.com/a/chromium.org/dev/developers/testing/chromium-build-infrastructure/buildbot-annotations Args: format: gyp format to test. Returns: 0 for sucesss, 1 for failure. """ if not format: format = title print '@@@BUILD_STEP ' + title + '@@@' sys.stdout.flush() env = os.environ.copy() if msvs_version: env['GYP_MSVS_VERSION'] = msvs_version command = ' '.join( [sys.executable, 'trunk/gyptest.py', '--all', '--passed', '--format', format, '--path', CMAKE_BIN_DIR, '--chdir', 'trunk']) if format == 'android': # gyptest needs the environment setup from envsetup/lunch in order to build # using the 'android' backend, so this is done in a single shell. retcode = subprocess.call( ['/bin/bash', '-c', 'source build/envsetup.sh && lunch full-eng && cd %s && %s' % (ROOT_DIR, command)], cwd=ANDROID_DIR, env=env) else: retcode = subprocess.call(command, cwd=ROOT_DIR, env=env, shell=True) if retcode: # Emit failure tag, and keep going. print '@@@STEP_FAILURE@@@' return 1 return 0 def GypBuild(): # Dump out/ directory. print '@@@BUILD_STEP cleanup@@@' print 'Removing %s...' % OUT_DIR shutil.rmtree(OUT_DIR, ignore_errors=True) print 'Done.' retcode = 0 # The Android gyp bot runs on linux so this must be tested first. if os.environ['BUILDBOT_BUILDERNAME'] == 'gyp-android': PrepareAndroidTree() retcode += GypTestFormat('android') elif sys.platform.startswith('linux'): retcode += GypTestFormat('ninja') retcode += GypTestFormat('make') PrepareCmake() retcode += GypTestFormat('cmake') elif sys.platform == 'darwin': retcode += GypTestFormat('ninja') retcode += GypTestFormat('xcode') retcode += GypTestFormat('make') elif sys.platform == 'win32': retcode += GypTestFormat('ninja') if os.environ['BUILDBOT_BUILDERNAME'] == 'gyp-win64': retcode += GypTestFormat('msvs-2010', format='msvs', msvs_version='2010') retcode += GypTestFormat('msvs-2012', format='msvs', msvs_version='2012') else: raise Exception('Unknown platform') if retcode: # TODO(bradnelson): once the annotator supports a postscript (section for # after the build proper that could be used for cumulative failures), # use that instead of this. This isolates the final return value so # that it isn't misattributed to the last stage. print '@@@BUILD_STEP failures@@@' sys.exit(retcode) if __name__ == '__main__': GypBuild() ======= #!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Argument-less script to select what to run on the buildbots.""" import os import shutil import subprocess import sys if sys.platform in ['win32', 'cygwin']: EXE_SUFFIX = '.exe' else: EXE_SUFFIX = '' BUILDBOT_DIR = os.path.dirname(os.path.abspath(__file__)) TRUNK_DIR = os.path.dirname(BUILDBOT_DIR) ROOT_DIR = os.path.dirname(TRUNK_DIR) ANDROID_DIR = os.path.join(ROOT_DIR, 'android') CMAKE_DIR = os.path.join(ROOT_DIR, 'cmake') CMAKE_BIN_DIR = os.path.join(CMAKE_DIR, 'bin') OUT_DIR = os.path.join(TRUNK_DIR, 'out') def CallSubProcess(*args, **kwargs): """Wrapper around subprocess.call which treats errors as build exceptions.""" retcode = subprocess.call(*args, **kwargs) if retcode != 0: print '@@@STEP_EXCEPTION@@@' sys.exit(1) def PrepareCmake(): """Build CMake 2.8.8 since the version in Precise is 2.8.7.""" if os.environ['BUILDBOT_CLOBBER'] == '1': print '@@@BUILD_STEP Clobber CMake checkout@@@' shutil.rmtree(CMAKE_DIR) # We always build CMake 2.8.8, so no need to do anything # if the directory already exists. if os.path.isdir(CMAKE_DIR): return print '@@@BUILD_STEP Initialize CMake checkout@@@' os.mkdir(CMAKE_DIR) CallSubProcess(['git', 'config', '--global', 'user.name', 'trybot']) CallSubProcess(['git', 'config', '--global', 'user.email', 'chrome-bot@google.com']) CallSubProcess(['git', 'config', '--global', 'color.ui', 'false']) print '@@@BUILD_STEP Sync CMake@@@' CallSubProcess( ['git', 'clone', '--depth', '1', '--single-branch', '--branch', 'v2.8.8', '--', 'git://cmake.org/cmake.git', CMAKE_DIR], cwd=CMAKE_DIR) print '@@@BUILD_STEP Build CMake@@@' CallSubProcess( ['/bin/bash', 'bootstrap', '--prefix=%s' % CMAKE_DIR], cwd=CMAKE_DIR) CallSubProcess( ['make', 'cmake'], cwd=CMAKE_DIR) def PrepareAndroidTree(): """Prepare an Android tree to run 'android' format tests.""" if os.environ['BUILDBOT_CLOBBER'] == '1': print '@@@BUILD_STEP Clobber Android checkout@@@' shutil.rmtree(ANDROID_DIR) # The release of Android we use is static, so there's no need to do anything # if the directory already exists. if os.path.isdir(ANDROID_DIR): return print '@@@BUILD_STEP Initialize Android checkout@@@' os.mkdir(ANDROID_DIR) CallSubProcess(['git', 'config', '--global', 'user.name', 'trybot']) CallSubProcess(['git', 'config', '--global', 'user.email', 'chrome-bot@google.com']) CallSubProcess(['git', 'config', '--global', 'color.ui', 'false']) CallSubProcess( ['repo', 'init', '-u', 'https://android.googlesource.com/platform/manifest', '-b', 'android-4.2.1_r1', '-g', 'all,-notdefault,-device,-darwin,-mips,-x86'], cwd=ANDROID_DIR) print '@@@BUILD_STEP Sync Android@@@' CallSubProcess(['repo', 'sync', '-j4'], cwd=ANDROID_DIR) print '@@@BUILD_STEP Build Android@@@' CallSubProcess( ['/bin/bash', '-c', 'source build/envsetup.sh && lunch full-eng && make -j4'], cwd=ANDROID_DIR) def GypTestFormat(title, format=None, msvs_version=None): """Run the gyp tests for a given format, emitting annotator tags. See annotator docs at: https://sites.google.com/a/chromium.org/dev/developers/testing/chromium-build-infrastructure/buildbot-annotations Args: format: gyp format to test. Returns: 0 for sucesss, 1 for failure. """ if not format: format = title print '@@@BUILD_STEP ' + title + '@@@' sys.stdout.flush() env = os.environ.copy() if msvs_version: env['GYP_MSVS_VERSION'] = msvs_version command = ' '.join( [sys.executable, 'trunk/gyptest.py', '--all', '--passed', '--format', format, '--path', CMAKE_BIN_DIR, '--chdir', 'trunk']) if format == 'android': # gyptest needs the environment setup from envsetup/lunch in order to build # using the 'android' backend, so this is done in a single shell. retcode = subprocess.call( ['/bin/bash', '-c', 'source build/envsetup.sh && lunch full-eng && cd %s && %s' % (ROOT_DIR, command)], cwd=ANDROID_DIR, env=env) else: retcode = subprocess.call(command, cwd=ROOT_DIR, env=env, shell=True) if retcode: # Emit failure tag, and keep going. print '@@@STEP_FAILURE@@@' return 1 return 0 def GypBuild(): # Dump out/ directory. print '@@@BUILD_STEP cleanup@@@' print 'Removing %s...' % OUT_DIR shutil.rmtree(OUT_DIR, ignore_errors=True) print 'Done.' retcode = 0 # The Android gyp bot runs on linux so this must be tested first. if os.environ['BUILDBOT_BUILDERNAME'] == 'gyp-android': PrepareAndroidTree() retcode += GypTestFormat('android') elif sys.platform.startswith('linux'): retcode += GypTestFormat('ninja') retcode += GypTestFormat('make') PrepareCmake() retcode += GypTestFormat('cmake') elif sys.platform == 'darwin': retcode += GypTestFormat('ninja') retcode += GypTestFormat('xcode') retcode += GypTestFormat('make') elif sys.platform == 'win32': retcode += GypTestFormat('ninja') if os.environ['BUILDBOT_BUILDERNAME'] == 'gyp-win64': retcode += GypTestFormat('msvs-2010', format='msvs', msvs_version='2010') retcode += GypTestFormat('msvs-2012', format='msvs', msvs_version='2012') else: raise Exception('Unknown platform') if retcode: # TODO(bradnelson): once the annotator supports a postscript (section for # after the build proper that could be used for cumulative failures), # use that instead of this. This isolates the final return value so # that it isn't misattributed to the last stage. print '@@@BUILD_STEP failures@@@' sys.exit(retcode) if __name__ == '__main__': GypBuild() >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= #!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Argument-less script to select what to run on the buildbots.""" import os import shutil import subprocess import sys if sys.platform in ['win32', 'cygwin']: EXE_SUFFIX = '.exe' else: EXE_SUFFIX = '' BUILDBOT_DIR = os.path.dirname(os.path.abspath(__file__)) TRUNK_DIR = os.path.dirname(BUILDBOT_DIR) ROOT_DIR = os.path.dirname(TRUNK_DIR) ANDROID_DIR = os.path.join(ROOT_DIR, 'android') CMAKE_DIR = os.path.join(ROOT_DIR, 'cmake') CMAKE_BIN_DIR = os.path.join(CMAKE_DIR, 'bin') OUT_DIR = os.path.join(TRUNK_DIR, 'out') def CallSubProcess(*args, **kwargs): """Wrapper around subprocess.call which treats errors as build exceptions.""" retcode = subprocess.call(*args, **kwargs) if retcode != 0: print '@@@STEP_EXCEPTION@@@' sys.exit(1) def PrepareCmake(): """Build CMake 2.8.8 since the version in Precise is 2.8.7.""" if os.environ['BUILDBOT_CLOBBER'] == '1': print '@@@BUILD_STEP Clobber CMake checkout@@@' shutil.rmtree(CMAKE_DIR) # We always build CMake 2.8.8, so no need to do anything # if the directory already exists. if os.path.isdir(CMAKE_DIR): return print '@@@BUILD_STEP Initialize CMake checkout@@@' os.mkdir(CMAKE_DIR) CallSubProcess(['git', 'config', '--global', 'user.name', 'trybot']) CallSubProcess(['git', 'config', '--global', 'user.email', 'chrome-bot@google.com']) CallSubProcess(['git', 'config', '--global', 'color.ui', 'false']) print '@@@BUILD_STEP Sync CMake@@@' CallSubProcess( ['git', 'clone', '--depth', '1', '--single-branch', '--branch', 'v2.8.8', '--', 'git://cmake.org/cmake.git', CMAKE_DIR], cwd=CMAKE_DIR) print '@@@BUILD_STEP Build CMake@@@' CallSubProcess( ['/bin/bash', 'bootstrap', '--prefix=%s' % CMAKE_DIR], cwd=CMAKE_DIR) CallSubProcess( ['make', 'cmake'], cwd=CMAKE_DIR) def PrepareAndroidTree(): """Prepare an Android tree to run 'android' format tests.""" if os.environ['BUILDBOT_CLOBBER'] == '1': print '@@@BUILD_STEP Clobber Android checkout@@@' shutil.rmtree(ANDROID_DIR) # The release of Android we use is static, so there's no need to do anything # if the directory already exists. if os.path.isdir(ANDROID_DIR): return print '@@@BUILD_STEP Initialize Android checkout@@@' os.mkdir(ANDROID_DIR) CallSubProcess(['git', 'config', '--global', 'user.name', 'trybot']) CallSubProcess(['git', 'config', '--global', 'user.email', 'chrome-bot@google.com']) CallSubProcess(['git', 'config', '--global', 'color.ui', 'false']) CallSubProcess( ['repo', 'init', '-u', 'https://android.googlesource.com/platform/manifest', '-b', 'android-4.2.1_r1', '-g', 'all,-notdefault,-device,-darwin,-mips,-x86'], cwd=ANDROID_DIR) print '@@@BUILD_STEP Sync Android@@@' CallSubProcess(['repo', 'sync', '-j4'], cwd=ANDROID_DIR) print '@@@BUILD_STEP Build Android@@@' CallSubProcess( ['/bin/bash', '-c', 'source build/envsetup.sh && lunch full-eng && make -j4'], cwd=ANDROID_DIR) def GypTestFormat(title, format=None, msvs_version=None): """Run the gyp tests for a given format, emitting annotator tags. See annotator docs at: https://sites.google.com/a/chromium.org/dev/developers/testing/chromium-build-infrastructure/buildbot-annotations Args: format: gyp format to test. Returns: 0 for sucesss, 1 for failure. """ if not format: format = title print '@@@BUILD_STEP ' + title + '@@@' sys.stdout.flush() env = os.environ.copy() if msvs_version: env['GYP_MSVS_VERSION'] = msvs_version command = ' '.join( [sys.executable, 'trunk/gyptest.py', '--all', '--passed', '--format', format, '--path', CMAKE_BIN_DIR, '--chdir', 'trunk']) if format == 'android': # gyptest needs the environment setup from envsetup/lunch in order to build # using the 'android' backend, so this is done in a single shell. retcode = subprocess.call( ['/bin/bash', '-c', 'source build/envsetup.sh && lunch full-eng && cd %s && %s' % (ROOT_DIR, command)], cwd=ANDROID_DIR, env=env) else: retcode = subprocess.call(command, cwd=ROOT_DIR, env=env, shell=True) if retcode: # Emit failure tag, and keep going. print '@@@STEP_FAILURE@@@' return 1 return 0 def GypBuild(): # Dump out/ directory. print '@@@BUILD_STEP cleanup@@@' print 'Removing %s...' % OUT_DIR shutil.rmtree(OUT_DIR, ignore_errors=True) print 'Done.' retcode = 0 # The Android gyp bot runs on linux so this must be tested first. if os.environ['BUILDBOT_BUILDERNAME'] == 'gyp-android': PrepareAndroidTree() retcode += GypTestFormat('android') elif sys.platform.startswith('linux'): retcode += GypTestFormat('ninja') retcode += GypTestFormat('make') PrepareCmake() retcode += GypTestFormat('cmake') elif sys.platform == 'darwin': retcode += GypTestFormat('ninja') retcode += GypTestFormat('xcode') retcode += GypTestFormat('make') elif sys.platform == 'win32': retcode += GypTestFormat('ninja') if os.environ['BUILDBOT_BUILDERNAME'] == 'gyp-win64': retcode += GypTestFormat('msvs-2010', format='msvs', msvs_version='2010') retcode += GypTestFormat('msvs-2012', format='msvs', msvs_version='2012') else: raise Exception('Unknown platform') if retcode: # TODO(bradnelson): once the annotator supports a postscript (section for # after the build proper that could be used for cumulative failures), # use that instead of this. This isolates the final return value so # that it isn't misattributed to the last stage. print '@@@BUILD_STEP failures@@@' sys.exit(retcode) if __name__ == '__main__': GypBuild() >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
mit
4,987,594,992,532,851,000
30.482639
117
0.635657
false
3.427977
true
false
false