commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
0
2.94k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
444
message
stringlengths
16
3.45k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43.2k
prompt
stringlengths
17
4.58k
response
stringlengths
1
4.43k
prompt_tagged
stringlengths
58
4.62k
response_tagged
stringlengths
1
4.43k
text
stringlengths
132
7.29k
text_tagged
stringlengths
173
7.33k
12906fd952bb03a98411ccf51f1ab40e6f580e3a
surveil/tests/api/controllers/v1/test_hello.py
surveil/tests/api/controllers/v1/test_hello.py
# Copyright 2014 - Savoir-Faire Linux 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 surveil.tests.api import functionalTest class TestRootController(functionalTest.FunctionalTest): def test_get(self): response = self.app.get('/v1/hello') assert response.body == b"Hello World!" assert response.status_int == 200
# Copyright 2014 - Savoir-Faire Linux 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 surveil.tests.api import functionalTest class TestRootController(functionalTest.FunctionalTest): def test_get(self): response = self.app.get('/v1/hello') self.assertEqual(response.body, b"Hello World!") assert response.status_int == 200
Use self.assertEqual instead of assert
Use self.assertEqual instead of assert Change-Id: Icae26d907eec2c4ab9f430c69491a96bd549c45a
Python
apache-2.0
stackforge/surveil,openstack/surveil,openstack/surveil,stackforge/surveil
# Copyright 2014 - Savoir-Faire Linux 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 surveil.tests.api import functionalTest class TestRootController(functionalTest.FunctionalTest): def test_get(self): response = self.app.get('/v1/hello') assert response.body == b"Hello World!" assert response.status_int == 200 Use self.assertEqual instead of assert Change-Id: Icae26d907eec2c4ab9f430c69491a96bd549c45a
# Copyright 2014 - Savoir-Faire Linux 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 surveil.tests.api import functionalTest class TestRootController(functionalTest.FunctionalTest): def test_get(self): response = self.app.get('/v1/hello') self.assertEqual(response.body, b"Hello World!") assert response.status_int == 200
<commit_before># Copyright 2014 - Savoir-Faire Linux 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 surveil.tests.api import functionalTest class TestRootController(functionalTest.FunctionalTest): def test_get(self): response = self.app.get('/v1/hello') assert response.body == b"Hello World!" assert response.status_int == 200 <commit_msg>Use self.assertEqual instead of assert Change-Id: Icae26d907eec2c4ab9f430c69491a96bd549c45a<commit_after>
# Copyright 2014 - Savoir-Faire Linux 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 surveil.tests.api import functionalTest class TestRootController(functionalTest.FunctionalTest): def test_get(self): response = self.app.get('/v1/hello') self.assertEqual(response.body, b"Hello World!") assert response.status_int == 200
# Copyright 2014 - Savoir-Faire Linux 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 surveil.tests.api import functionalTest class TestRootController(functionalTest.FunctionalTest): def test_get(self): response = self.app.get('/v1/hello') assert response.body == b"Hello World!" assert response.status_int == 200 Use self.assertEqual instead of assert Change-Id: Icae26d907eec2c4ab9f430c69491a96bd549c45a# Copyright 2014 - Savoir-Faire Linux 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 surveil.tests.api import functionalTest class TestRootController(functionalTest.FunctionalTest): def test_get(self): response = self.app.get('/v1/hello') self.assertEqual(response.body, b"Hello World!") assert response.status_int == 200
<commit_before># Copyright 2014 - Savoir-Faire Linux 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 surveil.tests.api import functionalTest class TestRootController(functionalTest.FunctionalTest): def test_get(self): response = self.app.get('/v1/hello') assert response.body == b"Hello World!" assert response.status_int == 200 <commit_msg>Use self.assertEqual instead of assert Change-Id: Icae26d907eec2c4ab9f430c69491a96bd549c45a<commit_after># Copyright 2014 - Savoir-Faire Linux 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 surveil.tests.api import functionalTest class TestRootController(functionalTest.FunctionalTest): def test_get(self): response = self.app.get('/v1/hello') self.assertEqual(response.body, b"Hello World!") assert response.status_int == 200
2ad6b7b57b20e75c5a98cb64d11b74e536057906
diary/forms.py
diary/forms.py
from django import forms import cube.diary.models class DiaryIdeaForm(forms.ModelForm): class Meta(object): model = cube.diary.models.DiaryIdea class EventForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Event # Ensure soft wrapping is set for textareas: widgets = { 'copy': forms.Textarea(attrs={'wrap':'soft'}), 'copy_summary': forms.Textarea(attrs={'wrap':'soft'}), 'terms': forms.Textarea(attrs={'wrap':'soft'}), 'notes': forms.Textarea(attrs={'wrap':'soft'}), } class ShowingForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by') class NewShowingForm(forms.ModelForm): # Same as Showing, but without the role field class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by', 'roles')
from django import forms import cube.diary.models class DiaryIdeaForm(forms.ModelForm): class Meta(object): model = cube.diary.models.DiaryIdea class EventForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Event # Ensure soft wrapping is set for textareas: widgets = { 'copy': forms.Textarea(attrs={'wrap':'soft'}), 'copy_summary': forms.Textarea(attrs={'wrap':'soft'}), 'terms': forms.Textarea(attrs={'wrap':'soft'}), 'notes': forms.Textarea(attrs={'wrap':'soft'}), } class ShowingForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by') class NewShowingForm(forms.ModelForm): # Same as Showing, but without the role field class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'roles')
Set booked_by for cloned/additional showings
Set booked_by for cloned/additional showings
Python
agpl-3.0
BenMotz/cubetoolkit,BenMotz/cubetoolkit,BenMotz/cubetoolkit,BenMotz/cubetoolkit
from django import forms import cube.diary.models class DiaryIdeaForm(forms.ModelForm): class Meta(object): model = cube.diary.models.DiaryIdea class EventForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Event # Ensure soft wrapping is set for textareas: widgets = { 'copy': forms.Textarea(attrs={'wrap':'soft'}), 'copy_summary': forms.Textarea(attrs={'wrap':'soft'}), 'terms': forms.Textarea(attrs={'wrap':'soft'}), 'notes': forms.Textarea(attrs={'wrap':'soft'}), } class ShowingForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by') class NewShowingForm(forms.ModelForm): # Same as Showing, but without the role field class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by', 'roles') Set booked_by for cloned/additional showings
from django import forms import cube.diary.models class DiaryIdeaForm(forms.ModelForm): class Meta(object): model = cube.diary.models.DiaryIdea class EventForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Event # Ensure soft wrapping is set for textareas: widgets = { 'copy': forms.Textarea(attrs={'wrap':'soft'}), 'copy_summary': forms.Textarea(attrs={'wrap':'soft'}), 'terms': forms.Textarea(attrs={'wrap':'soft'}), 'notes': forms.Textarea(attrs={'wrap':'soft'}), } class ShowingForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by') class NewShowingForm(forms.ModelForm): # Same as Showing, but without the role field class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'roles')
<commit_before>from django import forms import cube.diary.models class DiaryIdeaForm(forms.ModelForm): class Meta(object): model = cube.diary.models.DiaryIdea class EventForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Event # Ensure soft wrapping is set for textareas: widgets = { 'copy': forms.Textarea(attrs={'wrap':'soft'}), 'copy_summary': forms.Textarea(attrs={'wrap':'soft'}), 'terms': forms.Textarea(attrs={'wrap':'soft'}), 'notes': forms.Textarea(attrs={'wrap':'soft'}), } class ShowingForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by') class NewShowingForm(forms.ModelForm): # Same as Showing, but without the role field class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by', 'roles') <commit_msg>Set booked_by for cloned/additional showings<commit_after>
from django import forms import cube.diary.models class DiaryIdeaForm(forms.ModelForm): class Meta(object): model = cube.diary.models.DiaryIdea class EventForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Event # Ensure soft wrapping is set for textareas: widgets = { 'copy': forms.Textarea(attrs={'wrap':'soft'}), 'copy_summary': forms.Textarea(attrs={'wrap':'soft'}), 'terms': forms.Textarea(attrs={'wrap':'soft'}), 'notes': forms.Textarea(attrs={'wrap':'soft'}), } class ShowingForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by') class NewShowingForm(forms.ModelForm): # Same as Showing, but without the role field class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'roles')
from django import forms import cube.diary.models class DiaryIdeaForm(forms.ModelForm): class Meta(object): model = cube.diary.models.DiaryIdea class EventForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Event # Ensure soft wrapping is set for textareas: widgets = { 'copy': forms.Textarea(attrs={'wrap':'soft'}), 'copy_summary': forms.Textarea(attrs={'wrap':'soft'}), 'terms': forms.Textarea(attrs={'wrap':'soft'}), 'notes': forms.Textarea(attrs={'wrap':'soft'}), } class ShowingForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by') class NewShowingForm(forms.ModelForm): # Same as Showing, but without the role field class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by', 'roles') Set booked_by for cloned/additional showingsfrom django import forms import cube.diary.models class DiaryIdeaForm(forms.ModelForm): class Meta(object): model = cube.diary.models.DiaryIdea class EventForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Event # Ensure soft wrapping is set for textareas: widgets = { 'copy': forms.Textarea(attrs={'wrap':'soft'}), 'copy_summary': forms.Textarea(attrs={'wrap':'soft'}), 'terms': forms.Textarea(attrs={'wrap':'soft'}), 'notes': forms.Textarea(attrs={'wrap':'soft'}), } class ShowingForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by') class NewShowingForm(forms.ModelForm): # Same as Showing, but without the role field class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'roles')
<commit_before>from django import forms import cube.diary.models class DiaryIdeaForm(forms.ModelForm): class Meta(object): model = cube.diary.models.DiaryIdea class EventForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Event # Ensure soft wrapping is set for textareas: widgets = { 'copy': forms.Textarea(attrs={'wrap':'soft'}), 'copy_summary': forms.Textarea(attrs={'wrap':'soft'}), 'terms': forms.Textarea(attrs={'wrap':'soft'}), 'notes': forms.Textarea(attrs={'wrap':'soft'}), } class ShowingForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by') class NewShowingForm(forms.ModelForm): # Same as Showing, but without the role field class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by', 'roles') <commit_msg>Set booked_by for cloned/additional showings<commit_after>from django import forms import cube.diary.models class DiaryIdeaForm(forms.ModelForm): class Meta(object): model = cube.diary.models.DiaryIdea class EventForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Event # Ensure soft wrapping is set for textareas: widgets = { 'copy': forms.Textarea(attrs={'wrap':'soft'}), 'copy_summary': forms.Textarea(attrs={'wrap':'soft'}), 'terms': forms.Textarea(attrs={'wrap':'soft'}), 'notes': forms.Textarea(attrs={'wrap':'soft'}), } class ShowingForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by') class NewShowingForm(forms.ModelForm): # Same as Showing, but without the role field class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'roles')
75157b852ae174359d1665658d99852bfeca07c3
reportlab/rl_config.py
reportlab/rl_config.py
#copyright ReportLab Inc. 2000-2001 #see license.txt for license details #history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/rl_config.py?cvsroot=reportlab #$Header: /tmp/reportlab/reportlab/rl_config.py,v 1.3 2001/04/05 09:30:11 rgbecker Exp $ import sys from reportlab.lib import pagesizes shapeChecking = 1 defaultEncoding = 'WinAnsiEncoding' # 'WinAnsi' or 'MacRoman' defaultPageSize=pagesizes.A4 #check in reportlab/lib/pagesizes for other possibilities defaultImageCaching = 1 #set to zero to remove those annoying cached images #places to search for Type 1 Font files if sys.platform=='win32': T1SearchPathPath=['c:\\Program Files\\Adobe\\Acrobat 4.0\\Resource\\Font'] else: T1SearchPathPath=[]
#copyright ReportLab Inc. 2000-2001 #see license.txt for license details #history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/rl_config.py?cvsroot=reportlab #$Header: /tmp/reportlab/reportlab/rl_config.py,v 1.4 2001/04/17 18:28:54 rgbecker Exp $ import sys from reportlab.lib import pagesizes shapeChecking = 1 defaultEncoding = 'WinAnsiEncoding' # 'WinAnsi' or 'MacRoman' defaultPageSize=pagesizes.A4 #check in reportlab/lib/pagesizes for other possibilities defaultImageCaching = 1 #set to zero to remove those annoying cached images #places to search for Type 1 Font files if sys.platform=='win32': T1SearchPath=['c:\\Program Files\\Adobe\\Acrobat 4.0\\Resource\\Font'] else: T1SearchPath=[]
Fix typo in T1SearchPath name
Fix typo in T1SearchPath name
Python
bsd-3-clause
makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile
#copyright ReportLab Inc. 2000-2001 #see license.txt for license details #history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/rl_config.py?cvsroot=reportlab #$Header: /tmp/reportlab/reportlab/rl_config.py,v 1.3 2001/04/05 09:30:11 rgbecker Exp $ import sys from reportlab.lib import pagesizes shapeChecking = 1 defaultEncoding = 'WinAnsiEncoding' # 'WinAnsi' or 'MacRoman' defaultPageSize=pagesizes.A4 #check in reportlab/lib/pagesizes for other possibilities defaultImageCaching = 1 #set to zero to remove those annoying cached images #places to search for Type 1 Font files if sys.platform=='win32': T1SearchPathPath=['c:\\Program Files\\Adobe\\Acrobat 4.0\\Resource\\Font'] else: T1SearchPathPath=[] Fix typo in T1SearchPath name
#copyright ReportLab Inc. 2000-2001 #see license.txt for license details #history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/rl_config.py?cvsroot=reportlab #$Header: /tmp/reportlab/reportlab/rl_config.py,v 1.4 2001/04/17 18:28:54 rgbecker Exp $ import sys from reportlab.lib import pagesizes shapeChecking = 1 defaultEncoding = 'WinAnsiEncoding' # 'WinAnsi' or 'MacRoman' defaultPageSize=pagesizes.A4 #check in reportlab/lib/pagesizes for other possibilities defaultImageCaching = 1 #set to zero to remove those annoying cached images #places to search for Type 1 Font files if sys.platform=='win32': T1SearchPath=['c:\\Program Files\\Adobe\\Acrobat 4.0\\Resource\\Font'] else: T1SearchPath=[]
<commit_before>#copyright ReportLab Inc. 2000-2001 #see license.txt for license details #history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/rl_config.py?cvsroot=reportlab #$Header: /tmp/reportlab/reportlab/rl_config.py,v 1.3 2001/04/05 09:30:11 rgbecker Exp $ import sys from reportlab.lib import pagesizes shapeChecking = 1 defaultEncoding = 'WinAnsiEncoding' # 'WinAnsi' or 'MacRoman' defaultPageSize=pagesizes.A4 #check in reportlab/lib/pagesizes for other possibilities defaultImageCaching = 1 #set to zero to remove those annoying cached images #places to search for Type 1 Font files if sys.platform=='win32': T1SearchPathPath=['c:\\Program Files\\Adobe\\Acrobat 4.0\\Resource\\Font'] else: T1SearchPathPath=[] <commit_msg>Fix typo in T1SearchPath name<commit_after>
#copyright ReportLab Inc. 2000-2001 #see license.txt for license details #history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/rl_config.py?cvsroot=reportlab #$Header: /tmp/reportlab/reportlab/rl_config.py,v 1.4 2001/04/17 18:28:54 rgbecker Exp $ import sys from reportlab.lib import pagesizes shapeChecking = 1 defaultEncoding = 'WinAnsiEncoding' # 'WinAnsi' or 'MacRoman' defaultPageSize=pagesizes.A4 #check in reportlab/lib/pagesizes for other possibilities defaultImageCaching = 1 #set to zero to remove those annoying cached images #places to search for Type 1 Font files if sys.platform=='win32': T1SearchPath=['c:\\Program Files\\Adobe\\Acrobat 4.0\\Resource\\Font'] else: T1SearchPath=[]
#copyright ReportLab Inc. 2000-2001 #see license.txt for license details #history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/rl_config.py?cvsroot=reportlab #$Header: /tmp/reportlab/reportlab/rl_config.py,v 1.3 2001/04/05 09:30:11 rgbecker Exp $ import sys from reportlab.lib import pagesizes shapeChecking = 1 defaultEncoding = 'WinAnsiEncoding' # 'WinAnsi' or 'MacRoman' defaultPageSize=pagesizes.A4 #check in reportlab/lib/pagesizes for other possibilities defaultImageCaching = 1 #set to zero to remove those annoying cached images #places to search for Type 1 Font files if sys.platform=='win32': T1SearchPathPath=['c:\\Program Files\\Adobe\\Acrobat 4.0\\Resource\\Font'] else: T1SearchPathPath=[] Fix typo in T1SearchPath name#copyright ReportLab Inc. 2000-2001 #see license.txt for license details #history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/rl_config.py?cvsroot=reportlab #$Header: /tmp/reportlab/reportlab/rl_config.py,v 1.4 2001/04/17 18:28:54 rgbecker Exp $ import sys from reportlab.lib import pagesizes shapeChecking = 1 defaultEncoding = 'WinAnsiEncoding' # 'WinAnsi' or 'MacRoman' defaultPageSize=pagesizes.A4 #check in reportlab/lib/pagesizes for other possibilities defaultImageCaching = 1 #set to zero to remove those annoying cached images #places to search for Type 1 Font files if sys.platform=='win32': T1SearchPath=['c:\\Program Files\\Adobe\\Acrobat 4.0\\Resource\\Font'] else: T1SearchPath=[]
<commit_before>#copyright ReportLab Inc. 2000-2001 #see license.txt for license details #history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/rl_config.py?cvsroot=reportlab #$Header: /tmp/reportlab/reportlab/rl_config.py,v 1.3 2001/04/05 09:30:11 rgbecker Exp $ import sys from reportlab.lib import pagesizes shapeChecking = 1 defaultEncoding = 'WinAnsiEncoding' # 'WinAnsi' or 'MacRoman' defaultPageSize=pagesizes.A4 #check in reportlab/lib/pagesizes for other possibilities defaultImageCaching = 1 #set to zero to remove those annoying cached images #places to search for Type 1 Font files if sys.platform=='win32': T1SearchPathPath=['c:\\Program Files\\Adobe\\Acrobat 4.0\\Resource\\Font'] else: T1SearchPathPath=[] <commit_msg>Fix typo in T1SearchPath name<commit_after>#copyright ReportLab Inc. 2000-2001 #see license.txt for license details #history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/rl_config.py?cvsroot=reportlab #$Header: /tmp/reportlab/reportlab/rl_config.py,v 1.4 2001/04/17 18:28:54 rgbecker Exp $ import sys from reportlab.lib import pagesizes shapeChecking = 1 defaultEncoding = 'WinAnsiEncoding' # 'WinAnsi' or 'MacRoman' defaultPageSize=pagesizes.A4 #check in reportlab/lib/pagesizes for other possibilities defaultImageCaching = 1 #set to zero to remove those annoying cached images #places to search for Type 1 Font files if sys.platform=='win32': T1SearchPath=['c:\\Program Files\\Adobe\\Acrobat 4.0\\Resource\\Font'] else: T1SearchPath=[]
3a711d6005b16fcc6faf19c80f292ad6ef25455c
sqlserver_ado/__init__.py
sqlserver_ado/__init__.py
import os.path VERSION = (1, 0, 0, 'stable') def get_version(): """ Return the version as a string. If this is flagged as a development release and mercurial can be loaded the specifics about the changeset will be appended to the version string. """ if 'dev' in VERSION: try: from mercurial import hg, ui repo_path = os.path.join(os.path.dirname(__file__), '..') repo = hg.repository(ui.ui(), repo_path) ctx = repo['tip'] build_info = 'dev %s %s:%s' % (ctx.branch(), ctx.rev(), str(ctx)) except: # mercurial module missing or repository not found build_info = 'dev-unknown' v = VERSION[:VERSION.index('dev')] + (build_info,) return '.'.join(map(str, v))
import os.path VERSION = (1, 0, 1, 'stable') def get_version(): """ Return the version as a string. If this is flagged as a development release and mercurial can be loaded the specifics about the changeset will be appended to the version string. """ if 'dev' in VERSION: try: from mercurial import hg, ui repo_path = os.path.join(os.path.dirname(__file__), '..') repo = hg.repository(ui.ui(), repo_path) ctx = repo['tip'] build_info = 'dev %s %s:%s' % (ctx.branch(), ctx.rev(), str(ctx)) except: # mercurial module missing or repository not found build_info = 'dev-unknown' v = VERSION[:VERSION.index('dev')] + (build_info,) return '.'.join(map(str, v))
Bump version to 1.0.1 for unit test fix.
Bump version to 1.0.1 for unit test fix.
Python
mit
theoriginalgri/django-mssql,theoriginalgri/django-mssql
import os.path VERSION = (1, 0, 0, 'stable') def get_version(): """ Return the version as a string. If this is flagged as a development release and mercurial can be loaded the specifics about the changeset will be appended to the version string. """ if 'dev' in VERSION: try: from mercurial import hg, ui repo_path = os.path.join(os.path.dirname(__file__), '..') repo = hg.repository(ui.ui(), repo_path) ctx = repo['tip'] build_info = 'dev %s %s:%s' % (ctx.branch(), ctx.rev(), str(ctx)) except: # mercurial module missing or repository not found build_info = 'dev-unknown' v = VERSION[:VERSION.index('dev')] + (build_info,) return '.'.join(map(str, v)) Bump version to 1.0.1 for unit test fix.
import os.path VERSION = (1, 0, 1, 'stable') def get_version(): """ Return the version as a string. If this is flagged as a development release and mercurial can be loaded the specifics about the changeset will be appended to the version string. """ if 'dev' in VERSION: try: from mercurial import hg, ui repo_path = os.path.join(os.path.dirname(__file__), '..') repo = hg.repository(ui.ui(), repo_path) ctx = repo['tip'] build_info = 'dev %s %s:%s' % (ctx.branch(), ctx.rev(), str(ctx)) except: # mercurial module missing or repository not found build_info = 'dev-unknown' v = VERSION[:VERSION.index('dev')] + (build_info,) return '.'.join(map(str, v))
<commit_before>import os.path VERSION = (1, 0, 0, 'stable') def get_version(): """ Return the version as a string. If this is flagged as a development release and mercurial can be loaded the specifics about the changeset will be appended to the version string. """ if 'dev' in VERSION: try: from mercurial import hg, ui repo_path = os.path.join(os.path.dirname(__file__), '..') repo = hg.repository(ui.ui(), repo_path) ctx = repo['tip'] build_info = 'dev %s %s:%s' % (ctx.branch(), ctx.rev(), str(ctx)) except: # mercurial module missing or repository not found build_info = 'dev-unknown' v = VERSION[:VERSION.index('dev')] + (build_info,) return '.'.join(map(str, v)) <commit_msg>Bump version to 1.0.1 for unit test fix.<commit_after>
import os.path VERSION = (1, 0, 1, 'stable') def get_version(): """ Return the version as a string. If this is flagged as a development release and mercurial can be loaded the specifics about the changeset will be appended to the version string. """ if 'dev' in VERSION: try: from mercurial import hg, ui repo_path = os.path.join(os.path.dirname(__file__), '..') repo = hg.repository(ui.ui(), repo_path) ctx = repo['tip'] build_info = 'dev %s %s:%s' % (ctx.branch(), ctx.rev(), str(ctx)) except: # mercurial module missing or repository not found build_info = 'dev-unknown' v = VERSION[:VERSION.index('dev')] + (build_info,) return '.'.join(map(str, v))
import os.path VERSION = (1, 0, 0, 'stable') def get_version(): """ Return the version as a string. If this is flagged as a development release and mercurial can be loaded the specifics about the changeset will be appended to the version string. """ if 'dev' in VERSION: try: from mercurial import hg, ui repo_path = os.path.join(os.path.dirname(__file__), '..') repo = hg.repository(ui.ui(), repo_path) ctx = repo['tip'] build_info = 'dev %s %s:%s' % (ctx.branch(), ctx.rev(), str(ctx)) except: # mercurial module missing or repository not found build_info = 'dev-unknown' v = VERSION[:VERSION.index('dev')] + (build_info,) return '.'.join(map(str, v)) Bump version to 1.0.1 for unit test fix.import os.path VERSION = (1, 0, 1, 'stable') def get_version(): """ Return the version as a string. If this is flagged as a development release and mercurial can be loaded the specifics about the changeset will be appended to the version string. """ if 'dev' in VERSION: try: from mercurial import hg, ui repo_path = os.path.join(os.path.dirname(__file__), '..') repo = hg.repository(ui.ui(), repo_path) ctx = repo['tip'] build_info = 'dev %s %s:%s' % (ctx.branch(), ctx.rev(), str(ctx)) except: # mercurial module missing or repository not found build_info = 'dev-unknown' v = VERSION[:VERSION.index('dev')] + (build_info,) return '.'.join(map(str, v))
<commit_before>import os.path VERSION = (1, 0, 0, 'stable') def get_version(): """ Return the version as a string. If this is flagged as a development release and mercurial can be loaded the specifics about the changeset will be appended to the version string. """ if 'dev' in VERSION: try: from mercurial import hg, ui repo_path = os.path.join(os.path.dirname(__file__), '..') repo = hg.repository(ui.ui(), repo_path) ctx = repo['tip'] build_info = 'dev %s %s:%s' % (ctx.branch(), ctx.rev(), str(ctx)) except: # mercurial module missing or repository not found build_info = 'dev-unknown' v = VERSION[:VERSION.index('dev')] + (build_info,) return '.'.join(map(str, v)) <commit_msg>Bump version to 1.0.1 for unit test fix.<commit_after>import os.path VERSION = (1, 0, 1, 'stable') def get_version(): """ Return the version as a string. If this is flagged as a development release and mercurial can be loaded the specifics about the changeset will be appended to the version string. """ if 'dev' in VERSION: try: from mercurial import hg, ui repo_path = os.path.join(os.path.dirname(__file__), '..') repo = hg.repository(ui.ui(), repo_path) ctx = repo['tip'] build_info = 'dev %s %s:%s' % (ctx.branch(), ctx.rev(), str(ctx)) except: # mercurial module missing or repository not found build_info = 'dev-unknown' v = VERSION[:VERSION.index('dev')] + (build_info,) return '.'.join(map(str, v))
f8677eff328d50e16b51c2802b3f9e168c38534b
user_test.py
user_test.py
#!/usr/bin/env python try: import sympy except ImportError: print("sympy is required") else: if sympy.__version__ < '0.7.5': print("SymPy version 0.7.5 or newer is required. You have", sympy.__version__) if sympy.__version__ != '0.7.5': print("The stable SymPy version 0.7.5 is recommended. You have", sympy.__version__) try: import matplotlib except ImportError: print("matplotlib is required for the plotting section of the tutorial") try: import IPython except ImportError: print("IPython notebook is required.") else: if IPython.__version__ < '2.1.0': print("The latest version of IPython is recommended. You have", IPython.__version__) print("""A fortran and/or C compiler is required for the code generation portion of the tutorial. However, if you do not have one, you should not worry, as it will not be a large part of the tutorial.""")
#!/usr/bin/env python try: import sympy except ImportError: print("sympy is required") else: if sympy.__version__ < '1.0': print("SymPy version 1.0 or newer is required. You have", sympy.__version__) if sympy.__version__ != '1.0': print("The stable SymPy version 1.0 is recommended. You have", sympy.__version__) try: import matplotlib except ImportError: print("matplotlib is required for the plotting section of the tutorial") try: import IPython except ImportError: print("IPython notebook is required.") else: if IPython.__version__ < '4.1.2': print("The latest version of IPython is recommended. You have", IPython.__version__) print("""A fortran and/or C compiler is required for the code generation portion of the tutorial. However, if you do not have one, you should not worry, as it will not be a large part of the tutorial.""")
Update SymPy/IPython version in test script
Update SymPy/IPython version in test script
Python
bsd-3-clause
leosartaj/scipy-2016-tutorial,aktech/scipy-2016-tutorial
#!/usr/bin/env python try: import sympy except ImportError: print("sympy is required") else: if sympy.__version__ < '0.7.5': print("SymPy version 0.7.5 or newer is required. You have", sympy.__version__) if sympy.__version__ != '0.7.5': print("The stable SymPy version 0.7.5 is recommended. You have", sympy.__version__) try: import matplotlib except ImportError: print("matplotlib is required for the plotting section of the tutorial") try: import IPython except ImportError: print("IPython notebook is required.") else: if IPython.__version__ < '2.1.0': print("The latest version of IPython is recommended. You have", IPython.__version__) print("""A fortran and/or C compiler is required for the code generation portion of the tutorial. However, if you do not have one, you should not worry, as it will not be a large part of the tutorial.""") Update SymPy/IPython version in test script
#!/usr/bin/env python try: import sympy except ImportError: print("sympy is required") else: if sympy.__version__ < '1.0': print("SymPy version 1.0 or newer is required. You have", sympy.__version__) if sympy.__version__ != '1.0': print("The stable SymPy version 1.0 is recommended. You have", sympy.__version__) try: import matplotlib except ImportError: print("matplotlib is required for the plotting section of the tutorial") try: import IPython except ImportError: print("IPython notebook is required.") else: if IPython.__version__ < '4.1.2': print("The latest version of IPython is recommended. You have", IPython.__version__) print("""A fortran and/or C compiler is required for the code generation portion of the tutorial. However, if you do not have one, you should not worry, as it will not be a large part of the tutorial.""")
<commit_before>#!/usr/bin/env python try: import sympy except ImportError: print("sympy is required") else: if sympy.__version__ < '0.7.5': print("SymPy version 0.7.5 or newer is required. You have", sympy.__version__) if sympy.__version__ != '0.7.5': print("The stable SymPy version 0.7.5 is recommended. You have", sympy.__version__) try: import matplotlib except ImportError: print("matplotlib is required for the plotting section of the tutorial") try: import IPython except ImportError: print("IPython notebook is required.") else: if IPython.__version__ < '2.1.0': print("The latest version of IPython is recommended. You have", IPython.__version__) print("""A fortran and/or C compiler is required for the code generation portion of the tutorial. However, if you do not have one, you should not worry, as it will not be a large part of the tutorial.""") <commit_msg>Update SymPy/IPython version in test script<commit_after>
#!/usr/bin/env python try: import sympy except ImportError: print("sympy is required") else: if sympy.__version__ < '1.0': print("SymPy version 1.0 or newer is required. You have", sympy.__version__) if sympy.__version__ != '1.0': print("The stable SymPy version 1.0 is recommended. You have", sympy.__version__) try: import matplotlib except ImportError: print("matplotlib is required for the plotting section of the tutorial") try: import IPython except ImportError: print("IPython notebook is required.") else: if IPython.__version__ < '4.1.2': print("The latest version of IPython is recommended. You have", IPython.__version__) print("""A fortran and/or C compiler is required for the code generation portion of the tutorial. However, if you do not have one, you should not worry, as it will not be a large part of the tutorial.""")
#!/usr/bin/env python try: import sympy except ImportError: print("sympy is required") else: if sympy.__version__ < '0.7.5': print("SymPy version 0.7.5 or newer is required. You have", sympy.__version__) if sympy.__version__ != '0.7.5': print("The stable SymPy version 0.7.5 is recommended. You have", sympy.__version__) try: import matplotlib except ImportError: print("matplotlib is required for the plotting section of the tutorial") try: import IPython except ImportError: print("IPython notebook is required.") else: if IPython.__version__ < '2.1.0': print("The latest version of IPython is recommended. You have", IPython.__version__) print("""A fortran and/or C compiler is required for the code generation portion of the tutorial. However, if you do not have one, you should not worry, as it will not be a large part of the tutorial.""") Update SymPy/IPython version in test script#!/usr/bin/env python try: import sympy except ImportError: print("sympy is required") else: if sympy.__version__ < '1.0': print("SymPy version 1.0 or newer is required. You have", sympy.__version__) if sympy.__version__ != '1.0': print("The stable SymPy version 1.0 is recommended. You have", sympy.__version__) try: import matplotlib except ImportError: print("matplotlib is required for the plotting section of the tutorial") try: import IPython except ImportError: print("IPython notebook is required.") else: if IPython.__version__ < '4.1.2': print("The latest version of IPython is recommended. You have", IPython.__version__) print("""A fortran and/or C compiler is required for the code generation portion of the tutorial. However, if you do not have one, you should not worry, as it will not be a large part of the tutorial.""")
<commit_before>#!/usr/bin/env python try: import sympy except ImportError: print("sympy is required") else: if sympy.__version__ < '0.7.5': print("SymPy version 0.7.5 or newer is required. You have", sympy.__version__) if sympy.__version__ != '0.7.5': print("The stable SymPy version 0.7.5 is recommended. You have", sympy.__version__) try: import matplotlib except ImportError: print("matplotlib is required for the plotting section of the tutorial") try: import IPython except ImportError: print("IPython notebook is required.") else: if IPython.__version__ < '2.1.0': print("The latest version of IPython is recommended. You have", IPython.__version__) print("""A fortran and/or C compiler is required for the code generation portion of the tutorial. However, if you do not have one, you should not worry, as it will not be a large part of the tutorial.""") <commit_msg>Update SymPy/IPython version in test script<commit_after>#!/usr/bin/env python try: import sympy except ImportError: print("sympy is required") else: if sympy.__version__ < '1.0': print("SymPy version 1.0 or newer is required. You have", sympy.__version__) if sympy.__version__ != '1.0': print("The stable SymPy version 1.0 is recommended. You have", sympy.__version__) try: import matplotlib except ImportError: print("matplotlib is required for the plotting section of the tutorial") try: import IPython except ImportError: print("IPython notebook is required.") else: if IPython.__version__ < '4.1.2': print("The latest version of IPython is recommended. You have", IPython.__version__) print("""A fortran and/or C compiler is required for the code generation portion of the tutorial. However, if you do not have one, you should not worry, as it will not be a large part of the tutorial.""")
df21a8558f28887b3f38a892e8c7f45c12169764
src/ansible/urls.py
src/ansible/urls.py
from django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileView ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'^$', PlaybookListView.as_view(), name='playbook-list'), url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$', PlaybookFileView.as_view(), name='playbook-file-detail' ), ]
from django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileEditView, PlaybookFileView ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'^$', PlaybookListView.as_view(), name='playbook-list'), url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$', PlaybookFileView.as_view(), name='playbook-file-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/edit$', PlaybookFileEditView.as_view(), name='playbook-file-edit' ), ]
Add PlaybookFile edit view url
Add PlaybookFile edit view url
Python
bsd-3-clause
lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin
from django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileView ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'^$', PlaybookListView.as_view(), name='playbook-list'), url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$', PlaybookFileView.as_view(), name='playbook-file-detail' ), ] Add PlaybookFile edit view url
from django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileEditView, PlaybookFileView ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'^$', PlaybookListView.as_view(), name='playbook-list'), url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$', PlaybookFileView.as_view(), name='playbook-file-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/edit$', PlaybookFileEditView.as_view(), name='playbook-file-edit' ), ]
<commit_before>from django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileView ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'^$', PlaybookListView.as_view(), name='playbook-list'), url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$', PlaybookFileView.as_view(), name='playbook-file-detail' ), ] <commit_msg>Add PlaybookFile edit view url<commit_after>
from django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileEditView, PlaybookFileView ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'^$', PlaybookListView.as_view(), name='playbook-list'), url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$', PlaybookFileView.as_view(), name='playbook-file-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/edit$', PlaybookFileEditView.as_view(), name='playbook-file-edit' ), ]
from django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileView ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'^$', PlaybookListView.as_view(), name='playbook-list'), url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$', PlaybookFileView.as_view(), name='playbook-file-detail' ), ] Add PlaybookFile edit view urlfrom django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileEditView, PlaybookFileView ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'^$', PlaybookListView.as_view(), name='playbook-list'), url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$', PlaybookFileView.as_view(), name='playbook-file-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/edit$', PlaybookFileEditView.as_view(), name='playbook-file-edit' ), ]
<commit_before>from django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileView ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'^$', PlaybookListView.as_view(), name='playbook-list'), url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$', PlaybookFileView.as_view(), name='playbook-file-detail' ), ] <commit_msg>Add PlaybookFile edit view url<commit_after>from django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileEditView, PlaybookFileView ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'^$', PlaybookListView.as_view(), name='playbook-list'), url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$', PlaybookFileView.as_view(), name='playbook-file-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/edit$', PlaybookFileEditView.as_view(), name='playbook-file-edit' ), ]
fdd6f31c582318bbbb1ca8b408a7a3194e5de85a
groundstation/gref.py
groundstation/gref.py
import os class Gref(object): def __init__(self, store, channel, identifier): self.store = store self.channel = channel.replace("/", "_") self.identifier = identifier def node_path(self): node_path = os.path.join(self.store.gref_path(), self.channel, self.identifier) if not os.path.exists(node_path): os.makedirs(node_path) return node_path def write_tip(self, tip, signature): fh = open(self.tip_path(tip), 'r+') fh.seek(0) fh.write(signature) fh.truncate() fh.close() def tip_path(self, tip): return os.path.join(self.node_path(), tip) def __iter__(self): return os.listdir(self.node_path()).__iter__() def remove_tip(self, tip): try: os.unlink(os.path.join(self.tip_path(tip))) except: raise
import os class Gref(object): def __init__(self, store, channel, identifier): self.store = store self.channel = channel.replace("/", "_") self.identifier = identifier def node_path(self): node_path = os.path.join(self.store.gref_path(), self.channel, self.identifier) if not os.path.exists(node_path): os.makedirs(node_path) return node_path def write_tip(self, tip, signature): tip_path = self.tip_path(tip) open(tip_path, 'a').close() fh = open(tip_path, 'r+') fh.seek(0) fh.write(signature) fh.truncate() fh.close() def tip_path(self, tip): return os.path.join(self.node_path(), tip) def __iter__(self): return os.listdir(self.node_path()).__iter__() def remove_tip(self, tip): try: os.unlink(os.path.join(self.tip_path(tip))) except: raise
Fix broken attempts to open r+ non existant files
Fix broken attempts to open r+ non existant files
Python
mit
richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation
import os class Gref(object): def __init__(self, store, channel, identifier): self.store = store self.channel = channel.replace("/", "_") self.identifier = identifier def node_path(self): node_path = os.path.join(self.store.gref_path(), self.channel, self.identifier) if not os.path.exists(node_path): os.makedirs(node_path) return node_path def write_tip(self, tip, signature): fh = open(self.tip_path(tip), 'r+') fh.seek(0) fh.write(signature) fh.truncate() fh.close() def tip_path(self, tip): return os.path.join(self.node_path(), tip) def __iter__(self): return os.listdir(self.node_path()).__iter__() def remove_tip(self, tip): try: os.unlink(os.path.join(self.tip_path(tip))) except: raise Fix broken attempts to open r+ non existant files
import os class Gref(object): def __init__(self, store, channel, identifier): self.store = store self.channel = channel.replace("/", "_") self.identifier = identifier def node_path(self): node_path = os.path.join(self.store.gref_path(), self.channel, self.identifier) if not os.path.exists(node_path): os.makedirs(node_path) return node_path def write_tip(self, tip, signature): tip_path = self.tip_path(tip) open(tip_path, 'a').close() fh = open(tip_path, 'r+') fh.seek(0) fh.write(signature) fh.truncate() fh.close() def tip_path(self, tip): return os.path.join(self.node_path(), tip) def __iter__(self): return os.listdir(self.node_path()).__iter__() def remove_tip(self, tip): try: os.unlink(os.path.join(self.tip_path(tip))) except: raise
<commit_before>import os class Gref(object): def __init__(self, store, channel, identifier): self.store = store self.channel = channel.replace("/", "_") self.identifier = identifier def node_path(self): node_path = os.path.join(self.store.gref_path(), self.channel, self.identifier) if not os.path.exists(node_path): os.makedirs(node_path) return node_path def write_tip(self, tip, signature): fh = open(self.tip_path(tip), 'r+') fh.seek(0) fh.write(signature) fh.truncate() fh.close() def tip_path(self, tip): return os.path.join(self.node_path(), tip) def __iter__(self): return os.listdir(self.node_path()).__iter__() def remove_tip(self, tip): try: os.unlink(os.path.join(self.tip_path(tip))) except: raise <commit_msg>Fix broken attempts to open r+ non existant files<commit_after>
import os class Gref(object): def __init__(self, store, channel, identifier): self.store = store self.channel = channel.replace("/", "_") self.identifier = identifier def node_path(self): node_path = os.path.join(self.store.gref_path(), self.channel, self.identifier) if not os.path.exists(node_path): os.makedirs(node_path) return node_path def write_tip(self, tip, signature): tip_path = self.tip_path(tip) open(tip_path, 'a').close() fh = open(tip_path, 'r+') fh.seek(0) fh.write(signature) fh.truncate() fh.close() def tip_path(self, tip): return os.path.join(self.node_path(), tip) def __iter__(self): return os.listdir(self.node_path()).__iter__() def remove_tip(self, tip): try: os.unlink(os.path.join(self.tip_path(tip))) except: raise
import os class Gref(object): def __init__(self, store, channel, identifier): self.store = store self.channel = channel.replace("/", "_") self.identifier = identifier def node_path(self): node_path = os.path.join(self.store.gref_path(), self.channel, self.identifier) if not os.path.exists(node_path): os.makedirs(node_path) return node_path def write_tip(self, tip, signature): fh = open(self.tip_path(tip), 'r+') fh.seek(0) fh.write(signature) fh.truncate() fh.close() def tip_path(self, tip): return os.path.join(self.node_path(), tip) def __iter__(self): return os.listdir(self.node_path()).__iter__() def remove_tip(self, tip): try: os.unlink(os.path.join(self.tip_path(tip))) except: raise Fix broken attempts to open r+ non existant filesimport os class Gref(object): def __init__(self, store, channel, identifier): self.store = store self.channel = channel.replace("/", "_") self.identifier = identifier def node_path(self): node_path = os.path.join(self.store.gref_path(), self.channel, self.identifier) if not os.path.exists(node_path): os.makedirs(node_path) return node_path def write_tip(self, tip, signature): tip_path = self.tip_path(tip) open(tip_path, 'a').close() fh = open(tip_path, 'r+') fh.seek(0) fh.write(signature) fh.truncate() fh.close() def tip_path(self, tip): return os.path.join(self.node_path(), tip) def __iter__(self): return os.listdir(self.node_path()).__iter__() def remove_tip(self, tip): try: os.unlink(os.path.join(self.tip_path(tip))) except: raise
<commit_before>import os class Gref(object): def __init__(self, store, channel, identifier): self.store = store self.channel = channel.replace("/", "_") self.identifier = identifier def node_path(self): node_path = os.path.join(self.store.gref_path(), self.channel, self.identifier) if not os.path.exists(node_path): os.makedirs(node_path) return node_path def write_tip(self, tip, signature): fh = open(self.tip_path(tip), 'r+') fh.seek(0) fh.write(signature) fh.truncate() fh.close() def tip_path(self, tip): return os.path.join(self.node_path(), tip) def __iter__(self): return os.listdir(self.node_path()).__iter__() def remove_tip(self, tip): try: os.unlink(os.path.join(self.tip_path(tip))) except: raise <commit_msg>Fix broken attempts to open r+ non existant files<commit_after>import os class Gref(object): def __init__(self, store, channel, identifier): self.store = store self.channel = channel.replace("/", "_") self.identifier = identifier def node_path(self): node_path = os.path.join(self.store.gref_path(), self.channel, self.identifier) if not os.path.exists(node_path): os.makedirs(node_path) return node_path def write_tip(self, tip, signature): tip_path = self.tip_path(tip) open(tip_path, 'a').close() fh = open(tip_path, 'r+') fh.seek(0) fh.write(signature) fh.truncate() fh.close() def tip_path(self, tip): return os.path.join(self.node_path(), tip) def __iter__(self): return os.listdir(self.node_path()).__iter__() def remove_tip(self, tip): try: os.unlink(os.path.join(self.tip_path(tip))) except: raise
4304409d6f6028cb5f22edd97b8ecffa197dd9ed
server.py
server.py
import asyncio import logging # https://pypi.python.org/pypi/websockets import websockets clients = set() logging.basicConfig(level=logging.INFO) @asyncio.coroutine def chat(websocket, uri): clients.add(websocket) while True: msg = yield from websocket.recv() if msg is None: return print(msg) for client in clients.copy(): if client is not websocket: try: yield from client.send(msg) except websockets.exceptions.InvalidState: clients.remove(client) start_server = websockets.serve(chat, 'localhost', 8765) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever()
import asyncio import logging # https://pypi.python.org/pypi/websockets import websockets clients = set() logging.basicConfig(level=logging.INFO) @asyncio.coroutine def chat(websocket, uri): clients.add(websocket) while True: msg = yield from websocket.recv() if msg is None: return print(msg) for client in clients.copy(): if client is not websocket: try: yield from client.send(msg) except websockets.exceptions.InvalidState: clients.remove(client) start_server = websockets.serve(chat, 'localhost', 8765) asyncio.Task(start_server) asyncio.get_event_loop().run_forever()
Use Task instead of run_until_complete
Use Task instead of run_until_complete
Python
unlicense
ajdavis/asyncio-chat-example,ajdavis/asyncio-chat-example
import asyncio import logging # https://pypi.python.org/pypi/websockets import websockets clients = set() logging.basicConfig(level=logging.INFO) @asyncio.coroutine def chat(websocket, uri): clients.add(websocket) while True: msg = yield from websocket.recv() if msg is None: return print(msg) for client in clients.copy(): if client is not websocket: try: yield from client.send(msg) except websockets.exceptions.InvalidState: clients.remove(client) start_server = websockets.serve(chat, 'localhost', 8765) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() Use Task instead of run_until_complete
import asyncio import logging # https://pypi.python.org/pypi/websockets import websockets clients = set() logging.basicConfig(level=logging.INFO) @asyncio.coroutine def chat(websocket, uri): clients.add(websocket) while True: msg = yield from websocket.recv() if msg is None: return print(msg) for client in clients.copy(): if client is not websocket: try: yield from client.send(msg) except websockets.exceptions.InvalidState: clients.remove(client) start_server = websockets.serve(chat, 'localhost', 8765) asyncio.Task(start_server) asyncio.get_event_loop().run_forever()
<commit_before>import asyncio import logging # https://pypi.python.org/pypi/websockets import websockets clients = set() logging.basicConfig(level=logging.INFO) @asyncio.coroutine def chat(websocket, uri): clients.add(websocket) while True: msg = yield from websocket.recv() if msg is None: return print(msg) for client in clients.copy(): if client is not websocket: try: yield from client.send(msg) except websockets.exceptions.InvalidState: clients.remove(client) start_server = websockets.serve(chat, 'localhost', 8765) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() <commit_msg>Use Task instead of run_until_complete<commit_after>
import asyncio import logging # https://pypi.python.org/pypi/websockets import websockets clients = set() logging.basicConfig(level=logging.INFO) @asyncio.coroutine def chat(websocket, uri): clients.add(websocket) while True: msg = yield from websocket.recv() if msg is None: return print(msg) for client in clients.copy(): if client is not websocket: try: yield from client.send(msg) except websockets.exceptions.InvalidState: clients.remove(client) start_server = websockets.serve(chat, 'localhost', 8765) asyncio.Task(start_server) asyncio.get_event_loop().run_forever()
import asyncio import logging # https://pypi.python.org/pypi/websockets import websockets clients = set() logging.basicConfig(level=logging.INFO) @asyncio.coroutine def chat(websocket, uri): clients.add(websocket) while True: msg = yield from websocket.recv() if msg is None: return print(msg) for client in clients.copy(): if client is not websocket: try: yield from client.send(msg) except websockets.exceptions.InvalidState: clients.remove(client) start_server = websockets.serve(chat, 'localhost', 8765) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() Use Task instead of run_until_completeimport asyncio import logging # https://pypi.python.org/pypi/websockets import websockets clients = set() logging.basicConfig(level=logging.INFO) @asyncio.coroutine def chat(websocket, uri): clients.add(websocket) while True: msg = yield from websocket.recv() if msg is None: return print(msg) for client in clients.copy(): if client is not websocket: try: yield from client.send(msg) except websockets.exceptions.InvalidState: clients.remove(client) start_server = websockets.serve(chat, 'localhost', 8765) asyncio.Task(start_server) asyncio.get_event_loop().run_forever()
<commit_before>import asyncio import logging # https://pypi.python.org/pypi/websockets import websockets clients = set() logging.basicConfig(level=logging.INFO) @asyncio.coroutine def chat(websocket, uri): clients.add(websocket) while True: msg = yield from websocket.recv() if msg is None: return print(msg) for client in clients.copy(): if client is not websocket: try: yield from client.send(msg) except websockets.exceptions.InvalidState: clients.remove(client) start_server = websockets.serve(chat, 'localhost', 8765) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() <commit_msg>Use Task instead of run_until_complete<commit_after>import asyncio import logging # https://pypi.python.org/pypi/websockets import websockets clients = set() logging.basicConfig(level=logging.INFO) @asyncio.coroutine def chat(websocket, uri): clients.add(websocket) while True: msg = yield from websocket.recv() if msg is None: return print(msg) for client in clients.copy(): if client is not websocket: try: yield from client.send(msg) except websockets.exceptions.InvalidState: clients.remove(client) start_server = websockets.serve(chat, 'localhost', 8765) asyncio.Task(start_server) asyncio.get_event_loop().run_forever()
f18111d1a4227ce43326fd90c645ce09f6a183f7
shared.py
shared.py
import os __VERSION__ = '' __PLUGIN_VERSION__ = '' # Config settings USERNAME = '' SECRET = '' API_KEY = '' DEBUG = False SOCK_DEBUG = False ALERT_ON_MSG = True LOG_TO_CONSOLE = False BASE_DIR = os.path.expanduser(os.path.join('~', 'floobits')) # Shared globals DEFAULT_HOST = 'floobits.com' DEFAULT_PORT = 3448 SECURE = True SHARE_DIR = None COLAB_DIR = '' PROJECT_PATH = '' JOINED_WORKSPACE = False PERMS = [] STALKER_MODE = False SPLIT_MODE = False AUTO_GENERATED_ACCOUNT = False PLUGIN_PATH = None WORKSPACE_WINDOW = None CHAT_VIEW = None CHAT_VIEW_PATH = None TICK_TIME = 100 AGENT = None IGNORE_MODIFIED_EVENTS = False VIEW_TO_HASH = {} FLOORC_PATH = os.path.expanduser(os.path.join('~', '.floorc'))
import os __VERSION__ = '' __PLUGIN_VERSION__ = '' # Config settings USERNAME = '' SECRET = '' API_KEY = '' DEBUG = False SOCK_DEBUG = False ALERT_ON_MSG = True LOG_TO_CONSOLE = False BASE_DIR = os.path.expanduser(os.path.join('~', 'floobits')) # Shared globals DEFAULT_HOST = 'floobits.com' DEFAULT_PORT = 3448 SECURE = True SHARE_DIR = None COLAB_DIR = '' PROJECT_PATH = '' JOINED_WORKSPACE = False PERMS = [] STALKER_MODE = False SPLIT_MODE = False MIRRORED_SAVES = True AUTO_GENERATED_ACCOUNT = False PLUGIN_PATH = None WORKSPACE_WINDOW = None CHAT_VIEW = None CHAT_VIEW_PATH = None TICK_TIME = 100 AGENT = None IGNORE_MODIFIED_EVENTS = False VIEW_TO_HASH = {} FLOORC_PATH = os.path.expanduser(os.path.join('~', '.floorc'))
Add a setting so that people can disable mirrored saves
Add a setting so that people can disable mirrored saves
Python
apache-2.0
Floobits/plugin-common-python,Floobits/flootty
import os __VERSION__ = '' __PLUGIN_VERSION__ = '' # Config settings USERNAME = '' SECRET = '' API_KEY = '' DEBUG = False SOCK_DEBUG = False ALERT_ON_MSG = True LOG_TO_CONSOLE = False BASE_DIR = os.path.expanduser(os.path.join('~', 'floobits')) # Shared globals DEFAULT_HOST = 'floobits.com' DEFAULT_PORT = 3448 SECURE = True SHARE_DIR = None COLAB_DIR = '' PROJECT_PATH = '' JOINED_WORKSPACE = False PERMS = [] STALKER_MODE = False SPLIT_MODE = False AUTO_GENERATED_ACCOUNT = False PLUGIN_PATH = None WORKSPACE_WINDOW = None CHAT_VIEW = None CHAT_VIEW_PATH = None TICK_TIME = 100 AGENT = None IGNORE_MODIFIED_EVENTS = False VIEW_TO_HASH = {} FLOORC_PATH = os.path.expanduser(os.path.join('~', '.floorc')) Add a setting so that people can disable mirrored saves
import os __VERSION__ = '' __PLUGIN_VERSION__ = '' # Config settings USERNAME = '' SECRET = '' API_KEY = '' DEBUG = False SOCK_DEBUG = False ALERT_ON_MSG = True LOG_TO_CONSOLE = False BASE_DIR = os.path.expanduser(os.path.join('~', 'floobits')) # Shared globals DEFAULT_HOST = 'floobits.com' DEFAULT_PORT = 3448 SECURE = True SHARE_DIR = None COLAB_DIR = '' PROJECT_PATH = '' JOINED_WORKSPACE = False PERMS = [] STALKER_MODE = False SPLIT_MODE = False MIRRORED_SAVES = True AUTO_GENERATED_ACCOUNT = False PLUGIN_PATH = None WORKSPACE_WINDOW = None CHAT_VIEW = None CHAT_VIEW_PATH = None TICK_TIME = 100 AGENT = None IGNORE_MODIFIED_EVENTS = False VIEW_TO_HASH = {} FLOORC_PATH = os.path.expanduser(os.path.join('~', '.floorc'))
<commit_before>import os __VERSION__ = '' __PLUGIN_VERSION__ = '' # Config settings USERNAME = '' SECRET = '' API_KEY = '' DEBUG = False SOCK_DEBUG = False ALERT_ON_MSG = True LOG_TO_CONSOLE = False BASE_DIR = os.path.expanduser(os.path.join('~', 'floobits')) # Shared globals DEFAULT_HOST = 'floobits.com' DEFAULT_PORT = 3448 SECURE = True SHARE_DIR = None COLAB_DIR = '' PROJECT_PATH = '' JOINED_WORKSPACE = False PERMS = [] STALKER_MODE = False SPLIT_MODE = False AUTO_GENERATED_ACCOUNT = False PLUGIN_PATH = None WORKSPACE_WINDOW = None CHAT_VIEW = None CHAT_VIEW_PATH = None TICK_TIME = 100 AGENT = None IGNORE_MODIFIED_EVENTS = False VIEW_TO_HASH = {} FLOORC_PATH = os.path.expanduser(os.path.join('~', '.floorc')) <commit_msg>Add a setting so that people can disable mirrored saves<commit_after>
import os __VERSION__ = '' __PLUGIN_VERSION__ = '' # Config settings USERNAME = '' SECRET = '' API_KEY = '' DEBUG = False SOCK_DEBUG = False ALERT_ON_MSG = True LOG_TO_CONSOLE = False BASE_DIR = os.path.expanduser(os.path.join('~', 'floobits')) # Shared globals DEFAULT_HOST = 'floobits.com' DEFAULT_PORT = 3448 SECURE = True SHARE_DIR = None COLAB_DIR = '' PROJECT_PATH = '' JOINED_WORKSPACE = False PERMS = [] STALKER_MODE = False SPLIT_MODE = False MIRRORED_SAVES = True AUTO_GENERATED_ACCOUNT = False PLUGIN_PATH = None WORKSPACE_WINDOW = None CHAT_VIEW = None CHAT_VIEW_PATH = None TICK_TIME = 100 AGENT = None IGNORE_MODIFIED_EVENTS = False VIEW_TO_HASH = {} FLOORC_PATH = os.path.expanduser(os.path.join('~', '.floorc'))
import os __VERSION__ = '' __PLUGIN_VERSION__ = '' # Config settings USERNAME = '' SECRET = '' API_KEY = '' DEBUG = False SOCK_DEBUG = False ALERT_ON_MSG = True LOG_TO_CONSOLE = False BASE_DIR = os.path.expanduser(os.path.join('~', 'floobits')) # Shared globals DEFAULT_HOST = 'floobits.com' DEFAULT_PORT = 3448 SECURE = True SHARE_DIR = None COLAB_DIR = '' PROJECT_PATH = '' JOINED_WORKSPACE = False PERMS = [] STALKER_MODE = False SPLIT_MODE = False AUTO_GENERATED_ACCOUNT = False PLUGIN_PATH = None WORKSPACE_WINDOW = None CHAT_VIEW = None CHAT_VIEW_PATH = None TICK_TIME = 100 AGENT = None IGNORE_MODIFIED_EVENTS = False VIEW_TO_HASH = {} FLOORC_PATH = os.path.expanduser(os.path.join('~', '.floorc')) Add a setting so that people can disable mirrored savesimport os __VERSION__ = '' __PLUGIN_VERSION__ = '' # Config settings USERNAME = '' SECRET = '' API_KEY = '' DEBUG = False SOCK_DEBUG = False ALERT_ON_MSG = True LOG_TO_CONSOLE = False BASE_DIR = os.path.expanduser(os.path.join('~', 'floobits')) # Shared globals DEFAULT_HOST = 'floobits.com' DEFAULT_PORT = 3448 SECURE = True SHARE_DIR = None COLAB_DIR = '' PROJECT_PATH = '' JOINED_WORKSPACE = False PERMS = [] STALKER_MODE = False SPLIT_MODE = False MIRRORED_SAVES = True AUTO_GENERATED_ACCOUNT = False PLUGIN_PATH = None WORKSPACE_WINDOW = None CHAT_VIEW = None CHAT_VIEW_PATH = None TICK_TIME = 100 AGENT = None IGNORE_MODIFIED_EVENTS = False VIEW_TO_HASH = {} FLOORC_PATH = os.path.expanduser(os.path.join('~', '.floorc'))
<commit_before>import os __VERSION__ = '' __PLUGIN_VERSION__ = '' # Config settings USERNAME = '' SECRET = '' API_KEY = '' DEBUG = False SOCK_DEBUG = False ALERT_ON_MSG = True LOG_TO_CONSOLE = False BASE_DIR = os.path.expanduser(os.path.join('~', 'floobits')) # Shared globals DEFAULT_HOST = 'floobits.com' DEFAULT_PORT = 3448 SECURE = True SHARE_DIR = None COLAB_DIR = '' PROJECT_PATH = '' JOINED_WORKSPACE = False PERMS = [] STALKER_MODE = False SPLIT_MODE = False AUTO_GENERATED_ACCOUNT = False PLUGIN_PATH = None WORKSPACE_WINDOW = None CHAT_VIEW = None CHAT_VIEW_PATH = None TICK_TIME = 100 AGENT = None IGNORE_MODIFIED_EVENTS = False VIEW_TO_HASH = {} FLOORC_PATH = os.path.expanduser(os.path.join('~', '.floorc')) <commit_msg>Add a setting so that people can disable mirrored saves<commit_after>import os __VERSION__ = '' __PLUGIN_VERSION__ = '' # Config settings USERNAME = '' SECRET = '' API_KEY = '' DEBUG = False SOCK_DEBUG = False ALERT_ON_MSG = True LOG_TO_CONSOLE = False BASE_DIR = os.path.expanduser(os.path.join('~', 'floobits')) # Shared globals DEFAULT_HOST = 'floobits.com' DEFAULT_PORT = 3448 SECURE = True SHARE_DIR = None COLAB_DIR = '' PROJECT_PATH = '' JOINED_WORKSPACE = False PERMS = [] STALKER_MODE = False SPLIT_MODE = False MIRRORED_SAVES = True AUTO_GENERATED_ACCOUNT = False PLUGIN_PATH = None WORKSPACE_WINDOW = None CHAT_VIEW = None CHAT_VIEW_PATH = None TICK_TIME = 100 AGENT = None IGNORE_MODIFIED_EVENTS = False VIEW_TO_HASH = {} FLOORC_PATH = os.path.expanduser(os.path.join('~', '.floorc'))
301463a99dceceb21ecec933f3a83e55ca37c3b8
wagtail/wagtailimages/api/admin/serializers.py
wagtail/wagtailimages/api/admin/serializers.py
from __future__ import absolute_import, unicode_literals from collections import OrderedDict from rest_framework.fields import Field from ...models import SourceImageIOError from ..v2.serializers import ImageSerializer class ImageRenditionField(Field): """ A field that generates a rendition with the specified filter spec, and serialises details of that rendition. Example: "thumbnail": { "url": "/media/images/myimage.max-165x165.jpg", "width": 165, "height": 100 } If there is an error with the source image. The dict will only contain a single key, "error", indicating this error: "thumbnail": { "error": "SourceImageIOError" } """ def __init__(self, filter_spec, *args, **kwargs): self.filter_spec = filter_spec super(ImageRenditionField, self).__init__(*args, **kwargs) def get_attribute(self, instance): return instance def to_representation(self, image): try: thumbnail = image.get_rendition(self.filter_spec) return OrderedDict([ ('url', thumbnail.url), ('width', thumbnail.width), ('height', thumbnail.height), ]) except SourceImageIOError: return OrderedDict([ ('error', 'SourceImageIOError'), ]) class AdminImageSerializer(ImageSerializer): thumbnail = ImageRenditionField('max-165x165', read_only=True)
from __future__ import absolute_import, unicode_literals from collections import OrderedDict from rest_framework.fields import Field from ...models import SourceImageIOError from ..v2.serializers import ImageSerializer class ImageRenditionField(Field): """ A field that generates a rendition with the specified filter spec, and serialises details of that rendition. Example: "thumbnail": { "url": "/media/images/myimage.max-165x165.jpg", "width": 165, "height": 100 } If there is an error with the source image. The dict will only contain a single key, "error", indicating this error: "thumbnail": { "error": "SourceImageIOError" } """ def __init__(self, filter_spec, *args, **kwargs): self.filter_spec = filter_spec super(ImageRenditionField, self).__init__(*args, **kwargs) def to_representation(self, image): try: thumbnail = image.get_rendition(self.filter_spec) return OrderedDict([ ('url', thumbnail.url), ('width', thumbnail.width), ('height', thumbnail.height), ]) except SourceImageIOError: return OrderedDict([ ('error', 'SourceImageIOError'), ]) class AdminImageSerializer(ImageSerializer): thumbnail = ImageRenditionField('max-165x165', source='*', read_only=True)
Use source keyword argument (instead of overriding get_attribute)
Use source keyword argument (instead of overriding get_attribute) This allows the ImageRenditionField to be used on models that contain an image field.
Python
bsd-3-clause
nealtodd/wagtail,mikedingjan/wagtail,FlipperPA/wagtail,torchbox/wagtail,iansprice/wagtail,jnns/wagtail,wagtail/wagtail,zerolab/wagtail,thenewguy/wagtail,iansprice/wagtail,zerolab/wagtail,rsalmaso/wagtail,gasman/wagtail,timorieber/wagtail,kaedroho/wagtail,mikedingjan/wagtail,torchbox/wagtail,thenewguy/wagtail,zerolab/wagtail,takeflight/wagtail,takeflight/wagtail,gasman/wagtail,rsalmaso/wagtail,nimasmi/wagtail,Toshakins/wagtail,timorieber/wagtail,thenewguy/wagtail,timorieber/wagtail,nimasmi/wagtail,gasman/wagtail,wagtail/wagtail,wagtail/wagtail,mixxorz/wagtail,nealtodd/wagtail,mixxorz/wagtail,zerolab/wagtail,iansprice/wagtail,timorieber/wagtail,jnns/wagtail,gasman/wagtail,nealtodd/wagtail,wagtail/wagtail,iansprice/wagtail,rsalmaso/wagtail,takeflight/wagtail,jnns/wagtail,mixxorz/wagtail,torchbox/wagtail,FlipperPA/wagtail,mixxorz/wagtail,jnns/wagtail,kaedroho/wagtail,Toshakins/wagtail,FlipperPA/wagtail,nimasmi/wagtail,zerolab/wagtail,wagtail/wagtail,nimasmi/wagtail,kaedroho/wagtail,mikedingjan/wagtail,rsalmaso/wagtail,mixxorz/wagtail,thenewguy/wagtail,takeflight/wagtail,kaedroho/wagtail,mikedingjan/wagtail,thenewguy/wagtail,nealtodd/wagtail,rsalmaso/wagtail,gasman/wagtail,FlipperPA/wagtail,Toshakins/wagtail,Toshakins/wagtail,torchbox/wagtail,kaedroho/wagtail
from __future__ import absolute_import, unicode_literals from collections import OrderedDict from rest_framework.fields import Field from ...models import SourceImageIOError from ..v2.serializers import ImageSerializer class ImageRenditionField(Field): """ A field that generates a rendition with the specified filter spec, and serialises details of that rendition. Example: "thumbnail": { "url": "/media/images/myimage.max-165x165.jpg", "width": 165, "height": 100 } If there is an error with the source image. The dict will only contain a single key, "error", indicating this error: "thumbnail": { "error": "SourceImageIOError" } """ def __init__(self, filter_spec, *args, **kwargs): self.filter_spec = filter_spec super(ImageRenditionField, self).__init__(*args, **kwargs) def get_attribute(self, instance): return instance def to_representation(self, image): try: thumbnail = image.get_rendition(self.filter_spec) return OrderedDict([ ('url', thumbnail.url), ('width', thumbnail.width), ('height', thumbnail.height), ]) except SourceImageIOError: return OrderedDict([ ('error', 'SourceImageIOError'), ]) class AdminImageSerializer(ImageSerializer): thumbnail = ImageRenditionField('max-165x165', read_only=True) Use source keyword argument (instead of overriding get_attribute) This allows the ImageRenditionField to be used on models that contain an image field.
from __future__ import absolute_import, unicode_literals from collections import OrderedDict from rest_framework.fields import Field from ...models import SourceImageIOError from ..v2.serializers import ImageSerializer class ImageRenditionField(Field): """ A field that generates a rendition with the specified filter spec, and serialises details of that rendition. Example: "thumbnail": { "url": "/media/images/myimage.max-165x165.jpg", "width": 165, "height": 100 } If there is an error with the source image. The dict will only contain a single key, "error", indicating this error: "thumbnail": { "error": "SourceImageIOError" } """ def __init__(self, filter_spec, *args, **kwargs): self.filter_spec = filter_spec super(ImageRenditionField, self).__init__(*args, **kwargs) def to_representation(self, image): try: thumbnail = image.get_rendition(self.filter_spec) return OrderedDict([ ('url', thumbnail.url), ('width', thumbnail.width), ('height', thumbnail.height), ]) except SourceImageIOError: return OrderedDict([ ('error', 'SourceImageIOError'), ]) class AdminImageSerializer(ImageSerializer): thumbnail = ImageRenditionField('max-165x165', source='*', read_only=True)
<commit_before>from __future__ import absolute_import, unicode_literals from collections import OrderedDict from rest_framework.fields import Field from ...models import SourceImageIOError from ..v2.serializers import ImageSerializer class ImageRenditionField(Field): """ A field that generates a rendition with the specified filter spec, and serialises details of that rendition. Example: "thumbnail": { "url": "/media/images/myimage.max-165x165.jpg", "width": 165, "height": 100 } If there is an error with the source image. The dict will only contain a single key, "error", indicating this error: "thumbnail": { "error": "SourceImageIOError" } """ def __init__(self, filter_spec, *args, **kwargs): self.filter_spec = filter_spec super(ImageRenditionField, self).__init__(*args, **kwargs) def get_attribute(self, instance): return instance def to_representation(self, image): try: thumbnail = image.get_rendition(self.filter_spec) return OrderedDict([ ('url', thumbnail.url), ('width', thumbnail.width), ('height', thumbnail.height), ]) except SourceImageIOError: return OrderedDict([ ('error', 'SourceImageIOError'), ]) class AdminImageSerializer(ImageSerializer): thumbnail = ImageRenditionField('max-165x165', read_only=True) <commit_msg>Use source keyword argument (instead of overriding get_attribute) This allows the ImageRenditionField to be used on models that contain an image field.<commit_after>
from __future__ import absolute_import, unicode_literals from collections import OrderedDict from rest_framework.fields import Field from ...models import SourceImageIOError from ..v2.serializers import ImageSerializer class ImageRenditionField(Field): """ A field that generates a rendition with the specified filter spec, and serialises details of that rendition. Example: "thumbnail": { "url": "/media/images/myimage.max-165x165.jpg", "width": 165, "height": 100 } If there is an error with the source image. The dict will only contain a single key, "error", indicating this error: "thumbnail": { "error": "SourceImageIOError" } """ def __init__(self, filter_spec, *args, **kwargs): self.filter_spec = filter_spec super(ImageRenditionField, self).__init__(*args, **kwargs) def to_representation(self, image): try: thumbnail = image.get_rendition(self.filter_spec) return OrderedDict([ ('url', thumbnail.url), ('width', thumbnail.width), ('height', thumbnail.height), ]) except SourceImageIOError: return OrderedDict([ ('error', 'SourceImageIOError'), ]) class AdminImageSerializer(ImageSerializer): thumbnail = ImageRenditionField('max-165x165', source='*', read_only=True)
from __future__ import absolute_import, unicode_literals from collections import OrderedDict from rest_framework.fields import Field from ...models import SourceImageIOError from ..v2.serializers import ImageSerializer class ImageRenditionField(Field): """ A field that generates a rendition with the specified filter spec, and serialises details of that rendition. Example: "thumbnail": { "url": "/media/images/myimage.max-165x165.jpg", "width": 165, "height": 100 } If there is an error with the source image. The dict will only contain a single key, "error", indicating this error: "thumbnail": { "error": "SourceImageIOError" } """ def __init__(self, filter_spec, *args, **kwargs): self.filter_spec = filter_spec super(ImageRenditionField, self).__init__(*args, **kwargs) def get_attribute(self, instance): return instance def to_representation(self, image): try: thumbnail = image.get_rendition(self.filter_spec) return OrderedDict([ ('url', thumbnail.url), ('width', thumbnail.width), ('height', thumbnail.height), ]) except SourceImageIOError: return OrderedDict([ ('error', 'SourceImageIOError'), ]) class AdminImageSerializer(ImageSerializer): thumbnail = ImageRenditionField('max-165x165', read_only=True) Use source keyword argument (instead of overriding get_attribute) This allows the ImageRenditionField to be used on models that contain an image field.from __future__ import absolute_import, unicode_literals from collections import OrderedDict from rest_framework.fields import Field from ...models import SourceImageIOError from ..v2.serializers import ImageSerializer class ImageRenditionField(Field): """ A field that generates a rendition with the specified filter spec, and serialises details of that rendition. Example: "thumbnail": { "url": "/media/images/myimage.max-165x165.jpg", "width": 165, "height": 100 } If there is an error with the source image. The dict will only contain a single key, "error", indicating this error: "thumbnail": { "error": "SourceImageIOError" } """ def __init__(self, filter_spec, *args, **kwargs): self.filter_spec = filter_spec super(ImageRenditionField, self).__init__(*args, **kwargs) def to_representation(self, image): try: thumbnail = image.get_rendition(self.filter_spec) return OrderedDict([ ('url', thumbnail.url), ('width', thumbnail.width), ('height', thumbnail.height), ]) except SourceImageIOError: return OrderedDict([ ('error', 'SourceImageIOError'), ]) class AdminImageSerializer(ImageSerializer): thumbnail = ImageRenditionField('max-165x165', source='*', read_only=True)
<commit_before>from __future__ import absolute_import, unicode_literals from collections import OrderedDict from rest_framework.fields import Field from ...models import SourceImageIOError from ..v2.serializers import ImageSerializer class ImageRenditionField(Field): """ A field that generates a rendition with the specified filter spec, and serialises details of that rendition. Example: "thumbnail": { "url": "/media/images/myimage.max-165x165.jpg", "width": 165, "height": 100 } If there is an error with the source image. The dict will only contain a single key, "error", indicating this error: "thumbnail": { "error": "SourceImageIOError" } """ def __init__(self, filter_spec, *args, **kwargs): self.filter_spec = filter_spec super(ImageRenditionField, self).__init__(*args, **kwargs) def get_attribute(self, instance): return instance def to_representation(self, image): try: thumbnail = image.get_rendition(self.filter_spec) return OrderedDict([ ('url', thumbnail.url), ('width', thumbnail.width), ('height', thumbnail.height), ]) except SourceImageIOError: return OrderedDict([ ('error', 'SourceImageIOError'), ]) class AdminImageSerializer(ImageSerializer): thumbnail = ImageRenditionField('max-165x165', read_only=True) <commit_msg>Use source keyword argument (instead of overriding get_attribute) This allows the ImageRenditionField to be used on models that contain an image field.<commit_after>from __future__ import absolute_import, unicode_literals from collections import OrderedDict from rest_framework.fields import Field from ...models import SourceImageIOError from ..v2.serializers import ImageSerializer class ImageRenditionField(Field): """ A field that generates a rendition with the specified filter spec, and serialises details of that rendition. Example: "thumbnail": { "url": "/media/images/myimage.max-165x165.jpg", "width": 165, "height": 100 } If there is an error with the source image. The dict will only contain a single key, "error", indicating this error: "thumbnail": { "error": "SourceImageIOError" } """ def __init__(self, filter_spec, *args, **kwargs): self.filter_spec = filter_spec super(ImageRenditionField, self).__init__(*args, **kwargs) def to_representation(self, image): try: thumbnail = image.get_rendition(self.filter_spec) return OrderedDict([ ('url', thumbnail.url), ('width', thumbnail.width), ('height', thumbnail.height), ]) except SourceImageIOError: return OrderedDict([ ('error', 'SourceImageIOError'), ]) class AdminImageSerializer(ImageSerializer): thumbnail = ImageRenditionField('max-165x165', source='*', read_only=True)
e21f17b7d3ee810ce587a67609a53cbe038e5458
src/pubmed.py
src/pubmed.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import httplib #import xml.dom.minidom as minidom #import urllib import time, sys import xml.etree.ElementTree as ET def get_pubmed_abs(pmid): conn = httplib.HTTPConnection("eutils.ncbi.nlm.nih.gov") conn.request("GET", '/entrez/eutils/efetch.fcgi?db=pubmed&id=%s&retmode=xml&rettype=xml' % pmid) r1 = conn.getresponse() #print "Request Status: " + str(r1.status) + " " + str(r1.reason) response = r1.read() #print response[3] abstract = parse_pubmed_xml(response) return abstract, str(r1.status) + ' ' + str(r1.reason) def parse_pubmed_xml(xml): #print xml if xml.strip() == '': print "PMID not found" sys.exit() else: root = ET.fromstring(xml) abstext = root.findall('.//AbstractText') if len(abstext) > 0: abstext = abstext[0].text else: print "Abstract not found" sys.exit() return abstext def main(): print get_pubmed_abs(sys.argv[1]) if __name__ == "__main__": main()
#!/usr/bin/env python # -*- coding: utf-8 -*- import httplib #import xml.dom.minidom as minidom #import urllib import time, sys import xml.etree.ElementTree as ET def get_pubmed_abs(pmid): conn = httplib.HTTPConnection("eutils.ncbi.nlm.nih.gov") conn.request("GET", '/entrez/eutils/efetch.fcgi?db=pubmed&id=%s&retmode=xml&rettype=xml' % pmid) r1 = conn.getresponse() #print "Request Status: " + str(r1.status) + " " + str(r1.reason) response = r1.read() # print response title, abstract = parse_pubmed_xml(response) return title, abstract, str(r1.status) + ' ' + str(r1.reason) def parse_pubmed_xml(xml): #print xml if xml.strip() == '': print "PMID not found" sys.exit() else: root = ET.fromstring(xml) title = root.findall('.//ArticleTitle').text abstext = root.findall('.//AbstractText') if len(abstext) > 0: abstext = abstext[0].text else: print "Abstract not found" sys.exit() return title, abstext def main(): print get_pubmed_abs(sys.argv[1]) if __name__ == "__main__": main()
Return Pubmed title and abstract
Return Pubmed title and abstract
Python
mit
AndreLamurias/IBEnt,AndreLamurias/IBRel,AndreLamurias/IBEnt,AndreLamurias/IBRel
#!/usr/bin/env python # -*- coding: utf-8 -*- import httplib #import xml.dom.minidom as minidom #import urllib import time, sys import xml.etree.ElementTree as ET def get_pubmed_abs(pmid): conn = httplib.HTTPConnection("eutils.ncbi.nlm.nih.gov") conn.request("GET", '/entrez/eutils/efetch.fcgi?db=pubmed&id=%s&retmode=xml&rettype=xml' % pmid) r1 = conn.getresponse() #print "Request Status: " + str(r1.status) + " " + str(r1.reason) response = r1.read() #print response[3] abstract = parse_pubmed_xml(response) return abstract, str(r1.status) + ' ' + str(r1.reason) def parse_pubmed_xml(xml): #print xml if xml.strip() == '': print "PMID not found" sys.exit() else: root = ET.fromstring(xml) abstext = root.findall('.//AbstractText') if len(abstext) > 0: abstext = abstext[0].text else: print "Abstract not found" sys.exit() return abstext def main(): print get_pubmed_abs(sys.argv[1]) if __name__ == "__main__": main() Return Pubmed title and abstract
#!/usr/bin/env python # -*- coding: utf-8 -*- import httplib #import xml.dom.minidom as minidom #import urllib import time, sys import xml.etree.ElementTree as ET def get_pubmed_abs(pmid): conn = httplib.HTTPConnection("eutils.ncbi.nlm.nih.gov") conn.request("GET", '/entrez/eutils/efetch.fcgi?db=pubmed&id=%s&retmode=xml&rettype=xml' % pmid) r1 = conn.getresponse() #print "Request Status: " + str(r1.status) + " " + str(r1.reason) response = r1.read() # print response title, abstract = parse_pubmed_xml(response) return title, abstract, str(r1.status) + ' ' + str(r1.reason) def parse_pubmed_xml(xml): #print xml if xml.strip() == '': print "PMID not found" sys.exit() else: root = ET.fromstring(xml) title = root.findall('.//ArticleTitle').text abstext = root.findall('.//AbstractText') if len(abstext) > 0: abstext = abstext[0].text else: print "Abstract not found" sys.exit() return title, abstext def main(): print get_pubmed_abs(sys.argv[1]) if __name__ == "__main__": main()
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import httplib #import xml.dom.minidom as minidom #import urllib import time, sys import xml.etree.ElementTree as ET def get_pubmed_abs(pmid): conn = httplib.HTTPConnection("eutils.ncbi.nlm.nih.gov") conn.request("GET", '/entrez/eutils/efetch.fcgi?db=pubmed&id=%s&retmode=xml&rettype=xml' % pmid) r1 = conn.getresponse() #print "Request Status: " + str(r1.status) + " " + str(r1.reason) response = r1.read() #print response[3] abstract = parse_pubmed_xml(response) return abstract, str(r1.status) + ' ' + str(r1.reason) def parse_pubmed_xml(xml): #print xml if xml.strip() == '': print "PMID not found" sys.exit() else: root = ET.fromstring(xml) abstext = root.findall('.//AbstractText') if len(abstext) > 0: abstext = abstext[0].text else: print "Abstract not found" sys.exit() return abstext def main(): print get_pubmed_abs(sys.argv[1]) if __name__ == "__main__": main() <commit_msg>Return Pubmed title and abstract<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- import httplib #import xml.dom.minidom as minidom #import urllib import time, sys import xml.etree.ElementTree as ET def get_pubmed_abs(pmid): conn = httplib.HTTPConnection("eutils.ncbi.nlm.nih.gov") conn.request("GET", '/entrez/eutils/efetch.fcgi?db=pubmed&id=%s&retmode=xml&rettype=xml' % pmid) r1 = conn.getresponse() #print "Request Status: " + str(r1.status) + " " + str(r1.reason) response = r1.read() # print response title, abstract = parse_pubmed_xml(response) return title, abstract, str(r1.status) + ' ' + str(r1.reason) def parse_pubmed_xml(xml): #print xml if xml.strip() == '': print "PMID not found" sys.exit() else: root = ET.fromstring(xml) title = root.findall('.//ArticleTitle').text abstext = root.findall('.//AbstractText') if len(abstext) > 0: abstext = abstext[0].text else: print "Abstract not found" sys.exit() return title, abstext def main(): print get_pubmed_abs(sys.argv[1]) if __name__ == "__main__": main()
#!/usr/bin/env python # -*- coding: utf-8 -*- import httplib #import xml.dom.minidom as minidom #import urllib import time, sys import xml.etree.ElementTree as ET def get_pubmed_abs(pmid): conn = httplib.HTTPConnection("eutils.ncbi.nlm.nih.gov") conn.request("GET", '/entrez/eutils/efetch.fcgi?db=pubmed&id=%s&retmode=xml&rettype=xml' % pmid) r1 = conn.getresponse() #print "Request Status: " + str(r1.status) + " " + str(r1.reason) response = r1.read() #print response[3] abstract = parse_pubmed_xml(response) return abstract, str(r1.status) + ' ' + str(r1.reason) def parse_pubmed_xml(xml): #print xml if xml.strip() == '': print "PMID not found" sys.exit() else: root = ET.fromstring(xml) abstext = root.findall('.//AbstractText') if len(abstext) > 0: abstext = abstext[0].text else: print "Abstract not found" sys.exit() return abstext def main(): print get_pubmed_abs(sys.argv[1]) if __name__ == "__main__": main() Return Pubmed title and abstract#!/usr/bin/env python # -*- coding: utf-8 -*- import httplib #import xml.dom.minidom as minidom #import urllib import time, sys import xml.etree.ElementTree as ET def get_pubmed_abs(pmid): conn = httplib.HTTPConnection("eutils.ncbi.nlm.nih.gov") conn.request("GET", '/entrez/eutils/efetch.fcgi?db=pubmed&id=%s&retmode=xml&rettype=xml' % pmid) r1 = conn.getresponse() #print "Request Status: " + str(r1.status) + " " + str(r1.reason) response = r1.read() # print response title, abstract = parse_pubmed_xml(response) return title, abstract, str(r1.status) + ' ' + str(r1.reason) def parse_pubmed_xml(xml): #print xml if xml.strip() == '': print "PMID not found" sys.exit() else: root = ET.fromstring(xml) title = root.findall('.//ArticleTitle').text abstext = root.findall('.//AbstractText') if len(abstext) > 0: abstext = abstext[0].text else: print "Abstract not found" sys.exit() return title, abstext def main(): print get_pubmed_abs(sys.argv[1]) if __name__ == "__main__": main()
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import httplib #import xml.dom.minidom as minidom #import urllib import time, sys import xml.etree.ElementTree as ET def get_pubmed_abs(pmid): conn = httplib.HTTPConnection("eutils.ncbi.nlm.nih.gov") conn.request("GET", '/entrez/eutils/efetch.fcgi?db=pubmed&id=%s&retmode=xml&rettype=xml' % pmid) r1 = conn.getresponse() #print "Request Status: " + str(r1.status) + " " + str(r1.reason) response = r1.read() #print response[3] abstract = parse_pubmed_xml(response) return abstract, str(r1.status) + ' ' + str(r1.reason) def parse_pubmed_xml(xml): #print xml if xml.strip() == '': print "PMID not found" sys.exit() else: root = ET.fromstring(xml) abstext = root.findall('.//AbstractText') if len(abstext) > 0: abstext = abstext[0].text else: print "Abstract not found" sys.exit() return abstext def main(): print get_pubmed_abs(sys.argv[1]) if __name__ == "__main__": main() <commit_msg>Return Pubmed title and abstract<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- import httplib #import xml.dom.minidom as minidom #import urllib import time, sys import xml.etree.ElementTree as ET def get_pubmed_abs(pmid): conn = httplib.HTTPConnection("eutils.ncbi.nlm.nih.gov") conn.request("GET", '/entrez/eutils/efetch.fcgi?db=pubmed&id=%s&retmode=xml&rettype=xml' % pmid) r1 = conn.getresponse() #print "Request Status: " + str(r1.status) + " " + str(r1.reason) response = r1.read() # print response title, abstract = parse_pubmed_xml(response) return title, abstract, str(r1.status) + ' ' + str(r1.reason) def parse_pubmed_xml(xml): #print xml if xml.strip() == '': print "PMID not found" sys.exit() else: root = ET.fromstring(xml) title = root.findall('.//ArticleTitle').text abstext = root.findall('.//AbstractText') if len(abstext) > 0: abstext = abstext[0].text else: print "Abstract not found" sys.exit() return title, abstext def main(): print get_pubmed_abs(sys.argv[1]) if __name__ == "__main__": main()
969bc09c515f208738da67ebf77ef543ab358613
leonardo_agenda/__init__.py
leonardo_agenda/__init__.py
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ default_app_config = 'leonardo_agenda.Config' LEONARDO_OPTGROUP = 'Events' LEONARDO_APPS = [ 'leonardo_agenda', 'elephantagenda', 'elephantagenda.backends.agenda' ] LEONARDO_WIDGETS = [ 'leonardo_agenda.models.EventsWidget' ] LEONARDO_PLUGINS = [ ('leonardo_agenda.apps.events', _('Events'), ), ] LEONARDO_ABSOLUTE_URL_OVERRIDES = { 'agenda.event': 'leonardo_agenda.overrides.event' } class Config(AppConfig): name = 'leonardo_agenda' verbose_name = "leonardo-agenda" def ready(self): from ckeditor_uploader.widgets import CKEditorUploadingWidget from elephantagenda.backends.agenda import models models.EventAdminForm._meta.widgets.update({ 'description': CKEditorUploadingWidget(), 'short_description': CKEditorUploadingWidget() }) try: from ckeditor_uploader.widgets import CKEditorUploadingWidget from elephantagenda.backends.agenda import models models.EventAdminForm._meta.widgets[ 'description'] = CKEditorUploadingWidget() except Exception as e: raise e
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ default_app_config = 'leonardo_agenda.Config' LEONARDO_OPTGROUP = 'Events' LEONARDO_APPS = [ 'leonardo_agenda', 'elephantagenda', 'elephantagenda.backends.agenda' ] LEONARDO_WIDGETS = [ 'leonardo_agenda.models.EventsWidget' ] LEONARDO_PLUGINS = [ ('leonardo_agenda.apps.events', _('Events'), ), ] LEONARDO_ABSOLUTE_URL_OVERRIDES = { 'agenda.event': 'leonardo_agenda.overrides.event' } class Config(AppConfig): name = 'leonardo_agenda' verbose_name = "leonardo-agenda" def ready(self): try: from leonardo.utils import get_htmltext_widget from elephantagenda.backends.agenda import models models.EventAdminForm._meta.widgets.update({ 'description': get_htmltext_widget, 'short_description': get_htmltext_widget }) except: pass
Use leonardo helper for declare html text widget.
Use leonardo helper for declare html text widget.
Python
bsd-3-clause
leonardo-modules/leonardo-agenda,leonardo-modules/leonardo-agenda,leonardo-modules/leonardo-agenda
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ default_app_config = 'leonardo_agenda.Config' LEONARDO_OPTGROUP = 'Events' LEONARDO_APPS = [ 'leonardo_agenda', 'elephantagenda', 'elephantagenda.backends.agenda' ] LEONARDO_WIDGETS = [ 'leonardo_agenda.models.EventsWidget' ] LEONARDO_PLUGINS = [ ('leonardo_agenda.apps.events', _('Events'), ), ] LEONARDO_ABSOLUTE_URL_OVERRIDES = { 'agenda.event': 'leonardo_agenda.overrides.event' } class Config(AppConfig): name = 'leonardo_agenda' verbose_name = "leonardo-agenda" def ready(self): from ckeditor_uploader.widgets import CKEditorUploadingWidget from elephantagenda.backends.agenda import models models.EventAdminForm._meta.widgets.update({ 'description': CKEditorUploadingWidget(), 'short_description': CKEditorUploadingWidget() }) try: from ckeditor_uploader.widgets import CKEditorUploadingWidget from elephantagenda.backends.agenda import models models.EventAdminForm._meta.widgets[ 'description'] = CKEditorUploadingWidget() except Exception as e: raise e Use leonardo helper for declare html text widget.
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ default_app_config = 'leonardo_agenda.Config' LEONARDO_OPTGROUP = 'Events' LEONARDO_APPS = [ 'leonardo_agenda', 'elephantagenda', 'elephantagenda.backends.agenda' ] LEONARDO_WIDGETS = [ 'leonardo_agenda.models.EventsWidget' ] LEONARDO_PLUGINS = [ ('leonardo_agenda.apps.events', _('Events'), ), ] LEONARDO_ABSOLUTE_URL_OVERRIDES = { 'agenda.event': 'leonardo_agenda.overrides.event' } class Config(AppConfig): name = 'leonardo_agenda' verbose_name = "leonardo-agenda" def ready(self): try: from leonardo.utils import get_htmltext_widget from elephantagenda.backends.agenda import models models.EventAdminForm._meta.widgets.update({ 'description': get_htmltext_widget, 'short_description': get_htmltext_widget }) except: pass
<commit_before> from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ default_app_config = 'leonardo_agenda.Config' LEONARDO_OPTGROUP = 'Events' LEONARDO_APPS = [ 'leonardo_agenda', 'elephantagenda', 'elephantagenda.backends.agenda' ] LEONARDO_WIDGETS = [ 'leonardo_agenda.models.EventsWidget' ] LEONARDO_PLUGINS = [ ('leonardo_agenda.apps.events', _('Events'), ), ] LEONARDO_ABSOLUTE_URL_OVERRIDES = { 'agenda.event': 'leonardo_agenda.overrides.event' } class Config(AppConfig): name = 'leonardo_agenda' verbose_name = "leonardo-agenda" def ready(self): from ckeditor_uploader.widgets import CKEditorUploadingWidget from elephantagenda.backends.agenda import models models.EventAdminForm._meta.widgets.update({ 'description': CKEditorUploadingWidget(), 'short_description': CKEditorUploadingWidget() }) try: from ckeditor_uploader.widgets import CKEditorUploadingWidget from elephantagenda.backends.agenda import models models.EventAdminForm._meta.widgets[ 'description'] = CKEditorUploadingWidget() except Exception as e: raise e <commit_msg>Use leonardo helper for declare html text widget.<commit_after>
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ default_app_config = 'leonardo_agenda.Config' LEONARDO_OPTGROUP = 'Events' LEONARDO_APPS = [ 'leonardo_agenda', 'elephantagenda', 'elephantagenda.backends.agenda' ] LEONARDO_WIDGETS = [ 'leonardo_agenda.models.EventsWidget' ] LEONARDO_PLUGINS = [ ('leonardo_agenda.apps.events', _('Events'), ), ] LEONARDO_ABSOLUTE_URL_OVERRIDES = { 'agenda.event': 'leonardo_agenda.overrides.event' } class Config(AppConfig): name = 'leonardo_agenda' verbose_name = "leonardo-agenda" def ready(self): try: from leonardo.utils import get_htmltext_widget from elephantagenda.backends.agenda import models models.EventAdminForm._meta.widgets.update({ 'description': get_htmltext_widget, 'short_description': get_htmltext_widget }) except: pass
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ default_app_config = 'leonardo_agenda.Config' LEONARDO_OPTGROUP = 'Events' LEONARDO_APPS = [ 'leonardo_agenda', 'elephantagenda', 'elephantagenda.backends.agenda' ] LEONARDO_WIDGETS = [ 'leonardo_agenda.models.EventsWidget' ] LEONARDO_PLUGINS = [ ('leonardo_agenda.apps.events', _('Events'), ), ] LEONARDO_ABSOLUTE_URL_OVERRIDES = { 'agenda.event': 'leonardo_agenda.overrides.event' } class Config(AppConfig): name = 'leonardo_agenda' verbose_name = "leonardo-agenda" def ready(self): from ckeditor_uploader.widgets import CKEditorUploadingWidget from elephantagenda.backends.agenda import models models.EventAdminForm._meta.widgets.update({ 'description': CKEditorUploadingWidget(), 'short_description': CKEditorUploadingWidget() }) try: from ckeditor_uploader.widgets import CKEditorUploadingWidget from elephantagenda.backends.agenda import models models.EventAdminForm._meta.widgets[ 'description'] = CKEditorUploadingWidget() except Exception as e: raise e Use leonardo helper for declare html text widget. from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ default_app_config = 'leonardo_agenda.Config' LEONARDO_OPTGROUP = 'Events' LEONARDO_APPS = [ 'leonardo_agenda', 'elephantagenda', 'elephantagenda.backends.agenda' ] LEONARDO_WIDGETS = [ 'leonardo_agenda.models.EventsWidget' ] LEONARDO_PLUGINS = [ ('leonardo_agenda.apps.events', _('Events'), ), ] LEONARDO_ABSOLUTE_URL_OVERRIDES = { 'agenda.event': 'leonardo_agenda.overrides.event' } class Config(AppConfig): name = 'leonardo_agenda' verbose_name = "leonardo-agenda" def ready(self): try: from leonardo.utils import get_htmltext_widget from elephantagenda.backends.agenda import models models.EventAdminForm._meta.widgets.update({ 'description': get_htmltext_widget, 'short_description': get_htmltext_widget }) except: pass
<commit_before> from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ default_app_config = 'leonardo_agenda.Config' LEONARDO_OPTGROUP = 'Events' LEONARDO_APPS = [ 'leonardo_agenda', 'elephantagenda', 'elephantagenda.backends.agenda' ] LEONARDO_WIDGETS = [ 'leonardo_agenda.models.EventsWidget' ] LEONARDO_PLUGINS = [ ('leonardo_agenda.apps.events', _('Events'), ), ] LEONARDO_ABSOLUTE_URL_OVERRIDES = { 'agenda.event': 'leonardo_agenda.overrides.event' } class Config(AppConfig): name = 'leonardo_agenda' verbose_name = "leonardo-agenda" def ready(self): from ckeditor_uploader.widgets import CKEditorUploadingWidget from elephantagenda.backends.agenda import models models.EventAdminForm._meta.widgets.update({ 'description': CKEditorUploadingWidget(), 'short_description': CKEditorUploadingWidget() }) try: from ckeditor_uploader.widgets import CKEditorUploadingWidget from elephantagenda.backends.agenda import models models.EventAdminForm._meta.widgets[ 'description'] = CKEditorUploadingWidget() except Exception as e: raise e <commit_msg>Use leonardo helper for declare html text widget.<commit_after> from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ default_app_config = 'leonardo_agenda.Config' LEONARDO_OPTGROUP = 'Events' LEONARDO_APPS = [ 'leonardo_agenda', 'elephantagenda', 'elephantagenda.backends.agenda' ] LEONARDO_WIDGETS = [ 'leonardo_agenda.models.EventsWidget' ] LEONARDO_PLUGINS = [ ('leonardo_agenda.apps.events', _('Events'), ), ] LEONARDO_ABSOLUTE_URL_OVERRIDES = { 'agenda.event': 'leonardo_agenda.overrides.event' } class Config(AppConfig): name = 'leonardo_agenda' verbose_name = "leonardo-agenda" def ready(self): try: from leonardo.utils import get_htmltext_widget from elephantagenda.backends.agenda import models models.EventAdminForm._meta.widgets.update({ 'description': get_htmltext_widget, 'short_description': get_htmltext_widget }) except: pass
06cf113cc45e7eaa8ab63e2791c2f2a0990ac946
EasyEuler/data.py
EasyEuler/data.py
import json import os from jinja2 import Environment, FileSystemLoader BASE_PATH = os.path.abspath(os.path.dirname(__file__)) DATA_PATH = os.path.join(BASE_PATH, 'data') TEMPLATE_PATH = os.path.join(BASE_PATH, 'templates') CONFIG_PATH = os.path.join(BASE_PATH, 'config.json') templates = Environment(loader=FileSystemLoader(TEMPLATE_PATH)) with open(CONFIG_PATH) as f: config = json.load(f) with open('%s/problems.json' % DATA_PATH) as f: problems = json.load(f)
import collections import json import os from jinja2 import Environment, FileSystemLoader BASE_PATH = os.path.abspath(os.path.dirname(__file__)) DATA_PATH = os.path.join(BASE_PATH, 'data') TEMPLATE_PATH = os.path.join(BASE_PATH, 'templates') CONFIG_PATH = os.path.join(BASE_PATH, 'config.json') with open('%s/problems.json' % DATA_PATH) as f: problems = json.load(f) class ConfigurationDictionary(collections.MutableMapping): def __init__(self, config_paths): self.config = {} for config_path in config_paths: if os.path.exists(config_path): with open(config_path) as f: self.config = self.update(self.config, json.load(f)) def update(self, config, updates): for key, value in updates.items(): if isinstance(value, collections.Mapping): updated = self.update(config.get(key, {}), value) config[key] = updated else: config[key] = value return config def __getitem__(self, key): return self.config[key] def __setitem__(self, key, value): self.config[key] = value def __delitem__(self, key): del self.config[key] def __iter__(self): return iter(self.config) def __len__(self): return len(self.config) home = os.environ.get('HOME') xdg_config_home = os.environ.get('XDG_CONFIG_HOME', os.path.join(home, '.config')) xdg_config_dirs = os.environ.get('XDG_CONFIG_DIRS', '/etc/xdg') config_dirs = [xdg_config_home] + xdg_config_dirs.split(':') config_paths = [os.path.join(config_dir, 'EasyEuler/config.json') for config_dir in config_dirs if os.path.isabs(config_dir)] template_paths = [os.path.join(config_dir, 'EasyEuler/templates') for config_dir in config_dirs if os.path.isabs(config_dir)] config_paths.append(CONFIG_PATH) template_paths.append(TEMPLATE_PATH) config = ConfigurationDictionary(reversed(config_paths)) templates = Environment(loader=FileSystemLoader(reversed(template_paths)))
Add support for XDG spec configuration
Add support for XDG spec configuration
Python
mit
Encrylize/EasyEuler
import json import os from jinja2 import Environment, FileSystemLoader BASE_PATH = os.path.abspath(os.path.dirname(__file__)) DATA_PATH = os.path.join(BASE_PATH, 'data') TEMPLATE_PATH = os.path.join(BASE_PATH, 'templates') CONFIG_PATH = os.path.join(BASE_PATH, 'config.json') templates = Environment(loader=FileSystemLoader(TEMPLATE_PATH)) with open(CONFIG_PATH) as f: config = json.load(f) with open('%s/problems.json' % DATA_PATH) as f: problems = json.load(f) Add support for XDG spec configuration
import collections import json import os from jinja2 import Environment, FileSystemLoader BASE_PATH = os.path.abspath(os.path.dirname(__file__)) DATA_PATH = os.path.join(BASE_PATH, 'data') TEMPLATE_PATH = os.path.join(BASE_PATH, 'templates') CONFIG_PATH = os.path.join(BASE_PATH, 'config.json') with open('%s/problems.json' % DATA_PATH) as f: problems = json.load(f) class ConfigurationDictionary(collections.MutableMapping): def __init__(self, config_paths): self.config = {} for config_path in config_paths: if os.path.exists(config_path): with open(config_path) as f: self.config = self.update(self.config, json.load(f)) def update(self, config, updates): for key, value in updates.items(): if isinstance(value, collections.Mapping): updated = self.update(config.get(key, {}), value) config[key] = updated else: config[key] = value return config def __getitem__(self, key): return self.config[key] def __setitem__(self, key, value): self.config[key] = value def __delitem__(self, key): del self.config[key] def __iter__(self): return iter(self.config) def __len__(self): return len(self.config) home = os.environ.get('HOME') xdg_config_home = os.environ.get('XDG_CONFIG_HOME', os.path.join(home, '.config')) xdg_config_dirs = os.environ.get('XDG_CONFIG_DIRS', '/etc/xdg') config_dirs = [xdg_config_home] + xdg_config_dirs.split(':') config_paths = [os.path.join(config_dir, 'EasyEuler/config.json') for config_dir in config_dirs if os.path.isabs(config_dir)] template_paths = [os.path.join(config_dir, 'EasyEuler/templates') for config_dir in config_dirs if os.path.isabs(config_dir)] config_paths.append(CONFIG_PATH) template_paths.append(TEMPLATE_PATH) config = ConfigurationDictionary(reversed(config_paths)) templates = Environment(loader=FileSystemLoader(reversed(template_paths)))
<commit_before>import json import os from jinja2 import Environment, FileSystemLoader BASE_PATH = os.path.abspath(os.path.dirname(__file__)) DATA_PATH = os.path.join(BASE_PATH, 'data') TEMPLATE_PATH = os.path.join(BASE_PATH, 'templates') CONFIG_PATH = os.path.join(BASE_PATH, 'config.json') templates = Environment(loader=FileSystemLoader(TEMPLATE_PATH)) with open(CONFIG_PATH) as f: config = json.load(f) with open('%s/problems.json' % DATA_PATH) as f: problems = json.load(f) <commit_msg>Add support for XDG spec configuration<commit_after>
import collections import json import os from jinja2 import Environment, FileSystemLoader BASE_PATH = os.path.abspath(os.path.dirname(__file__)) DATA_PATH = os.path.join(BASE_PATH, 'data') TEMPLATE_PATH = os.path.join(BASE_PATH, 'templates') CONFIG_PATH = os.path.join(BASE_PATH, 'config.json') with open('%s/problems.json' % DATA_PATH) as f: problems = json.load(f) class ConfigurationDictionary(collections.MutableMapping): def __init__(self, config_paths): self.config = {} for config_path in config_paths: if os.path.exists(config_path): with open(config_path) as f: self.config = self.update(self.config, json.load(f)) def update(self, config, updates): for key, value in updates.items(): if isinstance(value, collections.Mapping): updated = self.update(config.get(key, {}), value) config[key] = updated else: config[key] = value return config def __getitem__(self, key): return self.config[key] def __setitem__(self, key, value): self.config[key] = value def __delitem__(self, key): del self.config[key] def __iter__(self): return iter(self.config) def __len__(self): return len(self.config) home = os.environ.get('HOME') xdg_config_home = os.environ.get('XDG_CONFIG_HOME', os.path.join(home, '.config')) xdg_config_dirs = os.environ.get('XDG_CONFIG_DIRS', '/etc/xdg') config_dirs = [xdg_config_home] + xdg_config_dirs.split(':') config_paths = [os.path.join(config_dir, 'EasyEuler/config.json') for config_dir in config_dirs if os.path.isabs(config_dir)] template_paths = [os.path.join(config_dir, 'EasyEuler/templates') for config_dir in config_dirs if os.path.isabs(config_dir)] config_paths.append(CONFIG_PATH) template_paths.append(TEMPLATE_PATH) config = ConfigurationDictionary(reversed(config_paths)) templates = Environment(loader=FileSystemLoader(reversed(template_paths)))
import json import os from jinja2 import Environment, FileSystemLoader BASE_PATH = os.path.abspath(os.path.dirname(__file__)) DATA_PATH = os.path.join(BASE_PATH, 'data') TEMPLATE_PATH = os.path.join(BASE_PATH, 'templates') CONFIG_PATH = os.path.join(BASE_PATH, 'config.json') templates = Environment(loader=FileSystemLoader(TEMPLATE_PATH)) with open(CONFIG_PATH) as f: config = json.load(f) with open('%s/problems.json' % DATA_PATH) as f: problems = json.load(f) Add support for XDG spec configurationimport collections import json import os from jinja2 import Environment, FileSystemLoader BASE_PATH = os.path.abspath(os.path.dirname(__file__)) DATA_PATH = os.path.join(BASE_PATH, 'data') TEMPLATE_PATH = os.path.join(BASE_PATH, 'templates') CONFIG_PATH = os.path.join(BASE_PATH, 'config.json') with open('%s/problems.json' % DATA_PATH) as f: problems = json.load(f) class ConfigurationDictionary(collections.MutableMapping): def __init__(self, config_paths): self.config = {} for config_path in config_paths: if os.path.exists(config_path): with open(config_path) as f: self.config = self.update(self.config, json.load(f)) def update(self, config, updates): for key, value in updates.items(): if isinstance(value, collections.Mapping): updated = self.update(config.get(key, {}), value) config[key] = updated else: config[key] = value return config def __getitem__(self, key): return self.config[key] def __setitem__(self, key, value): self.config[key] = value def __delitem__(self, key): del self.config[key] def __iter__(self): return iter(self.config) def __len__(self): return len(self.config) home = os.environ.get('HOME') xdg_config_home = os.environ.get('XDG_CONFIG_HOME', os.path.join(home, '.config')) xdg_config_dirs = os.environ.get('XDG_CONFIG_DIRS', '/etc/xdg') config_dirs = [xdg_config_home] + xdg_config_dirs.split(':') config_paths = [os.path.join(config_dir, 'EasyEuler/config.json') for config_dir in config_dirs if os.path.isabs(config_dir)] template_paths = [os.path.join(config_dir, 'EasyEuler/templates') for config_dir in config_dirs if os.path.isabs(config_dir)] config_paths.append(CONFIG_PATH) template_paths.append(TEMPLATE_PATH) config = ConfigurationDictionary(reversed(config_paths)) templates = Environment(loader=FileSystemLoader(reversed(template_paths)))
<commit_before>import json import os from jinja2 import Environment, FileSystemLoader BASE_PATH = os.path.abspath(os.path.dirname(__file__)) DATA_PATH = os.path.join(BASE_PATH, 'data') TEMPLATE_PATH = os.path.join(BASE_PATH, 'templates') CONFIG_PATH = os.path.join(BASE_PATH, 'config.json') templates = Environment(loader=FileSystemLoader(TEMPLATE_PATH)) with open(CONFIG_PATH) as f: config = json.load(f) with open('%s/problems.json' % DATA_PATH) as f: problems = json.load(f) <commit_msg>Add support for XDG spec configuration<commit_after>import collections import json import os from jinja2 import Environment, FileSystemLoader BASE_PATH = os.path.abspath(os.path.dirname(__file__)) DATA_PATH = os.path.join(BASE_PATH, 'data') TEMPLATE_PATH = os.path.join(BASE_PATH, 'templates') CONFIG_PATH = os.path.join(BASE_PATH, 'config.json') with open('%s/problems.json' % DATA_PATH) as f: problems = json.load(f) class ConfigurationDictionary(collections.MutableMapping): def __init__(self, config_paths): self.config = {} for config_path in config_paths: if os.path.exists(config_path): with open(config_path) as f: self.config = self.update(self.config, json.load(f)) def update(self, config, updates): for key, value in updates.items(): if isinstance(value, collections.Mapping): updated = self.update(config.get(key, {}), value) config[key] = updated else: config[key] = value return config def __getitem__(self, key): return self.config[key] def __setitem__(self, key, value): self.config[key] = value def __delitem__(self, key): del self.config[key] def __iter__(self): return iter(self.config) def __len__(self): return len(self.config) home = os.environ.get('HOME') xdg_config_home = os.environ.get('XDG_CONFIG_HOME', os.path.join(home, '.config')) xdg_config_dirs = os.environ.get('XDG_CONFIG_DIRS', '/etc/xdg') config_dirs = [xdg_config_home] + xdg_config_dirs.split(':') config_paths = [os.path.join(config_dir, 'EasyEuler/config.json') for config_dir in config_dirs if os.path.isabs(config_dir)] template_paths = [os.path.join(config_dir, 'EasyEuler/templates') for config_dir in config_dirs if os.path.isabs(config_dir)] config_paths.append(CONFIG_PATH) template_paths.append(TEMPLATE_PATH) config = ConfigurationDictionary(reversed(config_paths)) templates = Environment(loader=FileSystemLoader(reversed(template_paths)))
77d491ea43fcd00dcfcee1f0b9c2fdb50dc50c8e
tests/test_models.py
tests/test_models.py
import unittest from datetime import datetime from twofa import create_app, db from twofa.models import User class UserTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') db.create_all() def tearDown(self): db.session.remove() db.drop_all() def test_password_setter(self): pass
import unittest from twofa import create_app, db from twofa.models import User from unittest.mock import patch class UserTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.user = User( 'example@example.com', 'fakepassword', 'Alice', 33, 600112233, 123 ) db.create_all() def tearDown(self): db.session.remove() db.drop_all() def test_has_authy_app(self): # Arrange # Act with patch('twofa.models.authy_user_has_app', return_value=True): has_authy_app = self.user.has_authy_app # Assert self.assertTrue(has_authy_app) def test_hasnt_authy_app(self): # Arrange # Act with patch('twofa.models.authy_user_has_app', return_value=False): has_authy_app = self.user.has_authy_app # Assert self.assertFalse(has_authy_app) def test_password_is_unreadable(self): # Arrange # Act / Assert with self.assertRaises(AttributeError): self.user.password def test_password_setter(self): # Arrange old_password_hash = self.user.password_hash password = 'superpassword' # Act self.user.password = password # Assert self.assertNotEqual(password, self.user.password_hash) self.assertNotEqual(old_password_hash, self.user.password_hash) def test_verify_password(self): # Arrange password = 'anothercoolpassword' unused_password = 'unusedpassword' self.user.password = password # Act ret_good_password = self.user.verify_password(password) ret_bad_password = self.user.verify_password(unused_password) # Assert self.assertTrue(ret_good_password) self.assertFalse(ret_bad_password) def test_send_one_touch_request(self): # Arrange # Act with patch('twofa.models.send_authy_one_touch_request') as fake_send: self.user.send_one_touch_request() # Assert fake_send.assert_called_with(self.user.authy_id, self.user.email)
Add some tests for the model
Add some tests for the model
Python
mit
TwilioDevEd/authy2fa-flask,TwilioDevEd/authy2fa-flask,TwilioDevEd/authy2fa-flask,TwilioDevEd/authy2fa-flask
import unittest from datetime import datetime from twofa import create_app, db from twofa.models import User class UserTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') db.create_all() def tearDown(self): db.session.remove() db.drop_all() def test_password_setter(self): passAdd some tests for the model
import unittest from twofa import create_app, db from twofa.models import User from unittest.mock import patch class UserTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.user = User( 'example@example.com', 'fakepassword', 'Alice', 33, 600112233, 123 ) db.create_all() def tearDown(self): db.session.remove() db.drop_all() def test_has_authy_app(self): # Arrange # Act with patch('twofa.models.authy_user_has_app', return_value=True): has_authy_app = self.user.has_authy_app # Assert self.assertTrue(has_authy_app) def test_hasnt_authy_app(self): # Arrange # Act with patch('twofa.models.authy_user_has_app', return_value=False): has_authy_app = self.user.has_authy_app # Assert self.assertFalse(has_authy_app) def test_password_is_unreadable(self): # Arrange # Act / Assert with self.assertRaises(AttributeError): self.user.password def test_password_setter(self): # Arrange old_password_hash = self.user.password_hash password = 'superpassword' # Act self.user.password = password # Assert self.assertNotEqual(password, self.user.password_hash) self.assertNotEqual(old_password_hash, self.user.password_hash) def test_verify_password(self): # Arrange password = 'anothercoolpassword' unused_password = 'unusedpassword' self.user.password = password # Act ret_good_password = self.user.verify_password(password) ret_bad_password = self.user.verify_password(unused_password) # Assert self.assertTrue(ret_good_password) self.assertFalse(ret_bad_password) def test_send_one_touch_request(self): # Arrange # Act with patch('twofa.models.send_authy_one_touch_request') as fake_send: self.user.send_one_touch_request() # Assert fake_send.assert_called_with(self.user.authy_id, self.user.email)
<commit_before>import unittest from datetime import datetime from twofa import create_app, db from twofa.models import User class UserTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') db.create_all() def tearDown(self): db.session.remove() db.drop_all() def test_password_setter(self): pass<commit_msg>Add some tests for the model<commit_after>
import unittest from twofa import create_app, db from twofa.models import User from unittest.mock import patch class UserTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.user = User( 'example@example.com', 'fakepassword', 'Alice', 33, 600112233, 123 ) db.create_all() def tearDown(self): db.session.remove() db.drop_all() def test_has_authy_app(self): # Arrange # Act with patch('twofa.models.authy_user_has_app', return_value=True): has_authy_app = self.user.has_authy_app # Assert self.assertTrue(has_authy_app) def test_hasnt_authy_app(self): # Arrange # Act with patch('twofa.models.authy_user_has_app', return_value=False): has_authy_app = self.user.has_authy_app # Assert self.assertFalse(has_authy_app) def test_password_is_unreadable(self): # Arrange # Act / Assert with self.assertRaises(AttributeError): self.user.password def test_password_setter(self): # Arrange old_password_hash = self.user.password_hash password = 'superpassword' # Act self.user.password = password # Assert self.assertNotEqual(password, self.user.password_hash) self.assertNotEqual(old_password_hash, self.user.password_hash) def test_verify_password(self): # Arrange password = 'anothercoolpassword' unused_password = 'unusedpassword' self.user.password = password # Act ret_good_password = self.user.verify_password(password) ret_bad_password = self.user.verify_password(unused_password) # Assert self.assertTrue(ret_good_password) self.assertFalse(ret_bad_password) def test_send_one_touch_request(self): # Arrange # Act with patch('twofa.models.send_authy_one_touch_request') as fake_send: self.user.send_one_touch_request() # Assert fake_send.assert_called_with(self.user.authy_id, self.user.email)
import unittest from datetime import datetime from twofa import create_app, db from twofa.models import User class UserTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') db.create_all() def tearDown(self): db.session.remove() db.drop_all() def test_password_setter(self): passAdd some tests for the modelimport unittest from twofa import create_app, db from twofa.models import User from unittest.mock import patch class UserTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.user = User( 'example@example.com', 'fakepassword', 'Alice', 33, 600112233, 123 ) db.create_all() def tearDown(self): db.session.remove() db.drop_all() def test_has_authy_app(self): # Arrange # Act with patch('twofa.models.authy_user_has_app', return_value=True): has_authy_app = self.user.has_authy_app # Assert self.assertTrue(has_authy_app) def test_hasnt_authy_app(self): # Arrange # Act with patch('twofa.models.authy_user_has_app', return_value=False): has_authy_app = self.user.has_authy_app # Assert self.assertFalse(has_authy_app) def test_password_is_unreadable(self): # Arrange # Act / Assert with self.assertRaises(AttributeError): self.user.password def test_password_setter(self): # Arrange old_password_hash = self.user.password_hash password = 'superpassword' # Act self.user.password = password # Assert self.assertNotEqual(password, self.user.password_hash) self.assertNotEqual(old_password_hash, self.user.password_hash) def test_verify_password(self): # Arrange password = 'anothercoolpassword' unused_password = 'unusedpassword' self.user.password = password # Act ret_good_password = self.user.verify_password(password) ret_bad_password = self.user.verify_password(unused_password) # Assert self.assertTrue(ret_good_password) self.assertFalse(ret_bad_password) def test_send_one_touch_request(self): # Arrange # Act with patch('twofa.models.send_authy_one_touch_request') as fake_send: self.user.send_one_touch_request() # Assert fake_send.assert_called_with(self.user.authy_id, self.user.email)
<commit_before>import unittest from datetime import datetime from twofa import create_app, db from twofa.models import User class UserTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') db.create_all() def tearDown(self): db.session.remove() db.drop_all() def test_password_setter(self): pass<commit_msg>Add some tests for the model<commit_after>import unittest from twofa import create_app, db from twofa.models import User from unittest.mock import patch class UserTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.user = User( 'example@example.com', 'fakepassword', 'Alice', 33, 600112233, 123 ) db.create_all() def tearDown(self): db.session.remove() db.drop_all() def test_has_authy_app(self): # Arrange # Act with patch('twofa.models.authy_user_has_app', return_value=True): has_authy_app = self.user.has_authy_app # Assert self.assertTrue(has_authy_app) def test_hasnt_authy_app(self): # Arrange # Act with patch('twofa.models.authy_user_has_app', return_value=False): has_authy_app = self.user.has_authy_app # Assert self.assertFalse(has_authy_app) def test_password_is_unreadable(self): # Arrange # Act / Assert with self.assertRaises(AttributeError): self.user.password def test_password_setter(self): # Arrange old_password_hash = self.user.password_hash password = 'superpassword' # Act self.user.password = password # Assert self.assertNotEqual(password, self.user.password_hash) self.assertNotEqual(old_password_hash, self.user.password_hash) def test_verify_password(self): # Arrange password = 'anothercoolpassword' unused_password = 'unusedpassword' self.user.password = password # Act ret_good_password = self.user.verify_password(password) ret_bad_password = self.user.verify_password(unused_password) # Assert self.assertTrue(ret_good_password) self.assertFalse(ret_bad_password) def test_send_one_touch_request(self): # Arrange # Act with patch('twofa.models.send_authy_one_touch_request') as fake_send: self.user.send_one_touch_request() # Assert fake_send.assert_called_with(self.user.authy_id, self.user.email)
69a763860202c42026b2c7146dcf915e30bc3f9b
misc/utils/LogTools/LogView.py
misc/utils/LogTools/LogView.py
import threading import socket import logging import os import colorama from termcolor import colored from collections import deque markerStack = deque(['']) def colorMessage(message): if 'Info' in message : print(colored(message, 'green')) elif 'Error' in message : print(colored(message, 'red')) elif 'Fatal' in message : print(colored(message, 'red', 'white')) else: print(message) def appendMessageToBuffer(message): markerStack.append(message) if len(markerStack) > MAX_ELEMENTS_IN_QUEUE: markerStack.popleft() def updateView(): for marker in reversed(markerStack): colorMessage(marker) class UdpListener(): def __init__(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(('127.0.0.1', 4242)) self.clients_list = [] def listen(self): while True: msg = self.sock.recv(4096) appendMessageToBuffer(msg) updateView() def start_listening(self): t = threading.Thread(target=self.listen) t.start() if __name__ == "__main__": print 'call' colorama.init() listener = UdpListener() listener.start_listening()
"""Usage: logview [options] Options: -h, --help show this help message -v, --verbose print status messages --ignore=loglevels ignore logs of the specified levels """ import threading import socket import logging import os import colorama import docopt from termcolor import colored from collections import deque markerStack = deque(['']) def colorMessage(message): if 'Info' in message : print(colored(message, 'green')) elif 'Error' in message : print(colored(message, 'red')) elif 'Fatal' in message : print(colored(message, 'red', 'white')) else: print(message) def appendMessageToBuffer(message): markerStack.append(message) if len(markerStack) > MAX_ELEMENTS_IN_QUEUE: markerStack.popleft() def updateView(): for marker in reversed(markerStack): colorMessage(marker) class UdpListener(): def __init__(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(('127.0.0.1', 4242)) self.clients_list = [] def listen(self): while True: msg = self.sock.recv(4096) appendMessageToBuffer(msg) updateView() def start_listening(self): t = threading.Thread(target=self.listen) t.start() if __name__ == "__main__": print 'call' colorama.init() listener = UdpListener() listener.start_listening()
Add docopt - not finished
Add docopt - not finished
Python
mit
xfleckx/BeMoBI,xfleckx/BeMoBI
import threading import socket import logging import os import colorama from termcolor import colored from collections import deque markerStack = deque(['']) def colorMessage(message): if 'Info' in message : print(colored(message, 'green')) elif 'Error' in message : print(colored(message, 'red')) elif 'Fatal' in message : print(colored(message, 'red', 'white')) else: print(message) def appendMessageToBuffer(message): markerStack.append(message) if len(markerStack) > MAX_ELEMENTS_IN_QUEUE: markerStack.popleft() def updateView(): for marker in reversed(markerStack): colorMessage(marker) class UdpListener(): def __init__(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(('127.0.0.1', 4242)) self.clients_list = [] def listen(self): while True: msg = self.sock.recv(4096) appendMessageToBuffer(msg) updateView() def start_listening(self): t = threading.Thread(target=self.listen) t.start() if __name__ == "__main__": print 'call' colorama.init() listener = UdpListener() listener.start_listening() Add docopt - not finished
"""Usage: logview [options] Options: -h, --help show this help message -v, --verbose print status messages --ignore=loglevels ignore logs of the specified levels """ import threading import socket import logging import os import colorama import docopt from termcolor import colored from collections import deque markerStack = deque(['']) def colorMessage(message): if 'Info' in message : print(colored(message, 'green')) elif 'Error' in message : print(colored(message, 'red')) elif 'Fatal' in message : print(colored(message, 'red', 'white')) else: print(message) def appendMessageToBuffer(message): markerStack.append(message) if len(markerStack) > MAX_ELEMENTS_IN_QUEUE: markerStack.popleft() def updateView(): for marker in reversed(markerStack): colorMessage(marker) class UdpListener(): def __init__(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(('127.0.0.1', 4242)) self.clients_list = [] def listen(self): while True: msg = self.sock.recv(4096) appendMessageToBuffer(msg) updateView() def start_listening(self): t = threading.Thread(target=self.listen) t.start() if __name__ == "__main__": print 'call' colorama.init() listener = UdpListener() listener.start_listening()
<commit_before>import threading import socket import logging import os import colorama from termcolor import colored from collections import deque markerStack = deque(['']) def colorMessage(message): if 'Info' in message : print(colored(message, 'green')) elif 'Error' in message : print(colored(message, 'red')) elif 'Fatal' in message : print(colored(message, 'red', 'white')) else: print(message) def appendMessageToBuffer(message): markerStack.append(message) if len(markerStack) > MAX_ELEMENTS_IN_QUEUE: markerStack.popleft() def updateView(): for marker in reversed(markerStack): colorMessage(marker) class UdpListener(): def __init__(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(('127.0.0.1', 4242)) self.clients_list = [] def listen(self): while True: msg = self.sock.recv(4096) appendMessageToBuffer(msg) updateView() def start_listening(self): t = threading.Thread(target=self.listen) t.start() if __name__ == "__main__": print 'call' colorama.init() listener = UdpListener() listener.start_listening() <commit_msg>Add docopt - not finished<commit_after>
"""Usage: logview [options] Options: -h, --help show this help message -v, --verbose print status messages --ignore=loglevels ignore logs of the specified levels """ import threading import socket import logging import os import colorama import docopt from termcolor import colored from collections import deque markerStack = deque(['']) def colorMessage(message): if 'Info' in message : print(colored(message, 'green')) elif 'Error' in message : print(colored(message, 'red')) elif 'Fatal' in message : print(colored(message, 'red', 'white')) else: print(message) def appendMessageToBuffer(message): markerStack.append(message) if len(markerStack) > MAX_ELEMENTS_IN_QUEUE: markerStack.popleft() def updateView(): for marker in reversed(markerStack): colorMessage(marker) class UdpListener(): def __init__(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(('127.0.0.1', 4242)) self.clients_list = [] def listen(self): while True: msg = self.sock.recv(4096) appendMessageToBuffer(msg) updateView() def start_listening(self): t = threading.Thread(target=self.listen) t.start() if __name__ == "__main__": print 'call' colorama.init() listener = UdpListener() listener.start_listening()
import threading import socket import logging import os import colorama from termcolor import colored from collections import deque markerStack = deque(['']) def colorMessage(message): if 'Info' in message : print(colored(message, 'green')) elif 'Error' in message : print(colored(message, 'red')) elif 'Fatal' in message : print(colored(message, 'red', 'white')) else: print(message) def appendMessageToBuffer(message): markerStack.append(message) if len(markerStack) > MAX_ELEMENTS_IN_QUEUE: markerStack.popleft() def updateView(): for marker in reversed(markerStack): colorMessage(marker) class UdpListener(): def __init__(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(('127.0.0.1', 4242)) self.clients_list = [] def listen(self): while True: msg = self.sock.recv(4096) appendMessageToBuffer(msg) updateView() def start_listening(self): t = threading.Thread(target=self.listen) t.start() if __name__ == "__main__": print 'call' colorama.init() listener = UdpListener() listener.start_listening() Add docopt - not finished"""Usage: logview [options] Options: -h, --help show this help message -v, --verbose print status messages --ignore=loglevels ignore logs of the specified levels """ import threading import socket import logging import os import colorama import docopt from termcolor import colored from collections import deque markerStack = deque(['']) def colorMessage(message): if 'Info' in message : print(colored(message, 'green')) elif 'Error' in message : print(colored(message, 'red')) elif 'Fatal' in message : print(colored(message, 'red', 'white')) else: print(message) def appendMessageToBuffer(message): markerStack.append(message) if len(markerStack) > MAX_ELEMENTS_IN_QUEUE: markerStack.popleft() def updateView(): for marker in reversed(markerStack): colorMessage(marker) class UdpListener(): def __init__(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(('127.0.0.1', 4242)) self.clients_list = [] def listen(self): while True: msg = self.sock.recv(4096) appendMessageToBuffer(msg) updateView() def start_listening(self): t = threading.Thread(target=self.listen) t.start() if __name__ == "__main__": print 'call' colorama.init() listener = UdpListener() listener.start_listening()
<commit_before>import threading import socket import logging import os import colorama from termcolor import colored from collections import deque markerStack = deque(['']) def colorMessage(message): if 'Info' in message : print(colored(message, 'green')) elif 'Error' in message : print(colored(message, 'red')) elif 'Fatal' in message : print(colored(message, 'red', 'white')) else: print(message) def appendMessageToBuffer(message): markerStack.append(message) if len(markerStack) > MAX_ELEMENTS_IN_QUEUE: markerStack.popleft() def updateView(): for marker in reversed(markerStack): colorMessage(marker) class UdpListener(): def __init__(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(('127.0.0.1', 4242)) self.clients_list = [] def listen(self): while True: msg = self.sock.recv(4096) appendMessageToBuffer(msg) updateView() def start_listening(self): t = threading.Thread(target=self.listen) t.start() if __name__ == "__main__": print 'call' colorama.init() listener = UdpListener() listener.start_listening() <commit_msg>Add docopt - not finished<commit_after>"""Usage: logview [options] Options: -h, --help show this help message -v, --verbose print status messages --ignore=loglevels ignore logs of the specified levels """ import threading import socket import logging import os import colorama import docopt from termcolor import colored from collections import deque markerStack = deque(['']) def colorMessage(message): if 'Info' in message : print(colored(message, 'green')) elif 'Error' in message : print(colored(message, 'red')) elif 'Fatal' in message : print(colored(message, 'red', 'white')) else: print(message) def appendMessageToBuffer(message): markerStack.append(message) if len(markerStack) > MAX_ELEMENTS_IN_QUEUE: markerStack.popleft() def updateView(): for marker in reversed(markerStack): colorMessage(marker) class UdpListener(): def __init__(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(('127.0.0.1', 4242)) self.clients_list = [] def listen(self): while True: msg = self.sock.recv(4096) appendMessageToBuffer(msg) updateView() def start_listening(self): t = threading.Thread(target=self.listen) t.start() if __name__ == "__main__": print 'call' colorama.init() listener = UdpListener() listener.start_listening()
0547675bc4530681181005d1f502a43baf7deb56
napalm_ios/__init__.py
napalm_ios/__init__.py
# Copyright 2016 Dravetech AB. All rights reserved. # # The contents of this file are 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. """napalm_ios package.""" import pkg_resources from napalm_ios.ios import IOSDriver try: __version__ = pkg_resources.get_distribution('napalm-ios').version except pkg_resources.DistributionNotFound: __version__ = "Not installed" __all__ = ['IOSDriver']
# Copyright 2016 Dravetech AB. All rights reserved. # # The contents of this file are 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. """napalm_ios package.""" import pkg_resources from napalm_ios.ios import IOSDriver try: __version__ = pkg_resources.get_distribution('napalm-ios').version except pkg_resources.DistributionNotFound: __version__ = "Not installed" __all__ = ['IOSDriver'] # intentionally introduce a pylama error to make sure it fails the unit tests...................................
Verify fails travis-ci due to pylama (just a test
Verify fails travis-ci due to pylama (just a test
Python
apache-2.0
spotify/napalm,napalm-automation/napalm-ios,napalm-automation/napalm,spotify/napalm
# Copyright 2016 Dravetech AB. All rights reserved. # # The contents of this file are 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. """napalm_ios package.""" import pkg_resources from napalm_ios.ios import IOSDriver try: __version__ = pkg_resources.get_distribution('napalm-ios').version except pkg_resources.DistributionNotFound: __version__ = "Not installed" __all__ = ['IOSDriver'] Verify fails travis-ci due to pylama (just a test
# Copyright 2016 Dravetech AB. All rights reserved. # # The contents of this file are 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. """napalm_ios package.""" import pkg_resources from napalm_ios.ios import IOSDriver try: __version__ = pkg_resources.get_distribution('napalm-ios').version except pkg_resources.DistributionNotFound: __version__ = "Not installed" __all__ = ['IOSDriver'] # intentionally introduce a pylama error to make sure it fails the unit tests...................................
<commit_before># Copyright 2016 Dravetech AB. All rights reserved. # # The contents of this file are 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. """napalm_ios package.""" import pkg_resources from napalm_ios.ios import IOSDriver try: __version__ = pkg_resources.get_distribution('napalm-ios').version except pkg_resources.DistributionNotFound: __version__ = "Not installed" __all__ = ['IOSDriver'] <commit_msg>Verify fails travis-ci due to pylama (just a test<commit_after>
# Copyright 2016 Dravetech AB. All rights reserved. # # The contents of this file are 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. """napalm_ios package.""" import pkg_resources from napalm_ios.ios import IOSDriver try: __version__ = pkg_resources.get_distribution('napalm-ios').version except pkg_resources.DistributionNotFound: __version__ = "Not installed" __all__ = ['IOSDriver'] # intentionally introduce a pylama error to make sure it fails the unit tests...................................
# Copyright 2016 Dravetech AB. All rights reserved. # # The contents of this file are 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. """napalm_ios package.""" import pkg_resources from napalm_ios.ios import IOSDriver try: __version__ = pkg_resources.get_distribution('napalm-ios').version except pkg_resources.DistributionNotFound: __version__ = "Not installed" __all__ = ['IOSDriver'] Verify fails travis-ci due to pylama (just a test# Copyright 2016 Dravetech AB. All rights reserved. # # The contents of this file are 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. """napalm_ios package.""" import pkg_resources from napalm_ios.ios import IOSDriver try: __version__ = pkg_resources.get_distribution('napalm-ios').version except pkg_resources.DistributionNotFound: __version__ = "Not installed" __all__ = ['IOSDriver'] # intentionally introduce a pylama error to make sure it fails the unit tests...................................
<commit_before># Copyright 2016 Dravetech AB. All rights reserved. # # The contents of this file are 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. """napalm_ios package.""" import pkg_resources from napalm_ios.ios import IOSDriver try: __version__ = pkg_resources.get_distribution('napalm-ios').version except pkg_resources.DistributionNotFound: __version__ = "Not installed" __all__ = ['IOSDriver'] <commit_msg>Verify fails travis-ci due to pylama (just a test<commit_after># Copyright 2016 Dravetech AB. All rights reserved. # # The contents of this file are 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. """napalm_ios package.""" import pkg_resources from napalm_ios.ios import IOSDriver try: __version__ = pkg_resources.get_distribution('napalm-ios').version except pkg_resources.DistributionNotFound: __version__ = "Not installed" __all__ = ['IOSDriver'] # intentionally introduce a pylama error to make sure it fails the unit tests...................................
8378b474fca360696adc8a7c11439ac78912fab4
tools/test_filter.py
tools/test_filter.py
{ 'bslstl_iteratorutil': [ {'OS': 'SunOS'} ], 'bslstl_unorderedmultiset': [ {'OS': 'SunOS'} ], 'bsls_atomic' : [ {'case': 7, 'HOST': 'VM', 'policy': 'skip' }, {'case': 8, 'HOST': 'VM', 'policy': 'skip' }, ], 'bsls_stopwatch' : [ {'case': 6, 'HOST': 'VM', 'policy': 'skip' } ], }
{ 'bsls_atomic' : [ {'case': 7, 'HOST': 'VM', 'policy': 'skip' }, {'case': 8, 'HOST': 'VM', 'policy': 'skip' }, ], 'bsls_stopwatch' : [ {'case': 6, 'HOST': 'VM', 'policy': 'skip' } ], }
Remove test driver exceptions for bslstl_iteratorutil and bslstl_unorderedmultiset on Sun
Remove test driver exceptions for bslstl_iteratorutil and bslstl_unorderedmultiset on Sun
Python
apache-2.0
mversche/bde,gbleaney/Allocator-Benchmarks,abeels/bde,RMGiroux/bde-allocator-benchmarks,bowlofstew/bde,abeels/bde,che2/bde,saxena84/bde,minhlongdo/bde,jmptrader/bde,che2/bde,dharesign/bde,bloomberg/bde-allocator-benchmarks,bloomberg/bde-allocator-benchmarks,apaprocki/bde,jmptrader/bde,osubboo/bde,bloomberg/bde-allocator-benchmarks,mversche/bde,dharesign/bde,bloomberg/bde,osubboo/bde,che2/bde,bloomberg/bde,frutiger/bde,RMGiroux/bde-allocator-benchmarks,bowlofstew/bde,frutiger/bde,minhlongdo/bde,abeels/bde,dbremner/bde,apaprocki/bde,mversche/bde,bowlofstew/bde,bloomberg/bde,jmptrader/bde,osubboo/bde,idispatch/bde,apaprocki/bde,dbremner/bde,idispatch/bde,dharesign/bde,apaprocki/bde,apaprocki/bde,RMGiroux/bde-allocator-benchmarks,gbleaney/Allocator-Benchmarks,frutiger/bde,RMGiroux/bde-allocator-benchmarks,frutiger/bde,bloomberg/bde,gbleaney/Allocator-Benchmarks,dbremner/bde,mversche/bde,bowlofstew/bde,osubboo/bde,bloomberg/bde-allocator-benchmarks,saxena84/bde,jmptrader/bde,bloomberg/bde-allocator-benchmarks,abeels/bde,che2/bde,bloomberg/bde,saxena84/bde,dharesign/bde,idispatch/bde,abeels/bde,idispatch/bde,gbleaney/Allocator-Benchmarks,abeels/bde,minhlongdo/bde,dbremner/bde,RMGiroux/bde-allocator-benchmarks,saxena84/bde,minhlongdo/bde
{ 'bslstl_iteratorutil': [ {'OS': 'SunOS'} ], 'bslstl_unorderedmultiset': [ {'OS': 'SunOS'} ], 'bsls_atomic' : [ {'case': 7, 'HOST': 'VM', 'policy': 'skip' }, {'case': 8, 'HOST': 'VM', 'policy': 'skip' }, ], 'bsls_stopwatch' : [ {'case': 6, 'HOST': 'VM', 'policy': 'skip' } ], } Remove test driver exceptions for bslstl_iteratorutil and bslstl_unorderedmultiset on Sun
{ 'bsls_atomic' : [ {'case': 7, 'HOST': 'VM', 'policy': 'skip' }, {'case': 8, 'HOST': 'VM', 'policy': 'skip' }, ], 'bsls_stopwatch' : [ {'case': 6, 'HOST': 'VM', 'policy': 'skip' } ], }
<commit_before>{ 'bslstl_iteratorutil': [ {'OS': 'SunOS'} ], 'bslstl_unorderedmultiset': [ {'OS': 'SunOS'} ], 'bsls_atomic' : [ {'case': 7, 'HOST': 'VM', 'policy': 'skip' }, {'case': 8, 'HOST': 'VM', 'policy': 'skip' }, ], 'bsls_stopwatch' : [ {'case': 6, 'HOST': 'VM', 'policy': 'skip' } ], } <commit_msg>Remove test driver exceptions for bslstl_iteratorutil and bslstl_unorderedmultiset on Sun<commit_after>
{ 'bsls_atomic' : [ {'case': 7, 'HOST': 'VM', 'policy': 'skip' }, {'case': 8, 'HOST': 'VM', 'policy': 'skip' }, ], 'bsls_stopwatch' : [ {'case': 6, 'HOST': 'VM', 'policy': 'skip' } ], }
{ 'bslstl_iteratorutil': [ {'OS': 'SunOS'} ], 'bslstl_unorderedmultiset': [ {'OS': 'SunOS'} ], 'bsls_atomic' : [ {'case': 7, 'HOST': 'VM', 'policy': 'skip' }, {'case': 8, 'HOST': 'VM', 'policy': 'skip' }, ], 'bsls_stopwatch' : [ {'case': 6, 'HOST': 'VM', 'policy': 'skip' } ], } Remove test driver exceptions for bslstl_iteratorutil and bslstl_unorderedmultiset on Sun{ 'bsls_atomic' : [ {'case': 7, 'HOST': 'VM', 'policy': 'skip' }, {'case': 8, 'HOST': 'VM', 'policy': 'skip' }, ], 'bsls_stopwatch' : [ {'case': 6, 'HOST': 'VM', 'policy': 'skip' } ], }
<commit_before>{ 'bslstl_iteratorutil': [ {'OS': 'SunOS'} ], 'bslstl_unorderedmultiset': [ {'OS': 'SunOS'} ], 'bsls_atomic' : [ {'case': 7, 'HOST': 'VM', 'policy': 'skip' }, {'case': 8, 'HOST': 'VM', 'policy': 'skip' }, ], 'bsls_stopwatch' : [ {'case': 6, 'HOST': 'VM', 'policy': 'skip' } ], } <commit_msg>Remove test driver exceptions for bslstl_iteratorutil and bslstl_unorderedmultiset on Sun<commit_after>{ 'bsls_atomic' : [ {'case': 7, 'HOST': 'VM', 'policy': 'skip' }, {'case': 8, 'HOST': 'VM', 'policy': 'skip' }, ], 'bsls_stopwatch' : [ {'case': 6, 'HOST': 'VM', 'policy': 'skip' } ], }
0d8c37cb0ebdc88c11be60e856677ac090aeea49
users/views.py
users/views.py
import json import logging from django.http import HttpResponse from django.views.generic import View from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt logger = logging.getLogger(__name__) class CSRFExemptMixin(object): @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): logger.debug("CSRFExemptMixin: dispatch method") return super(CSRFExemptMixin, self).dispatch(*args, **kwargs) class UserAddLocationView(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): logger.debug(request.POST) lat = request.POST.get('lat', '') lon = request.POST.get('lon', '') logger.debug("Latitude: {0} and longitude: {1}".format(lat, lon)) # adds the lation object into the session request.session['location'] = {'lat': lat, 'lon': lon} data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json') class UserRemoveLocation(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): if 'location' in request.session: del request.session['location'] data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json')
import json import logging from django.http import HttpResponse from django.views.generic import View from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt logger = logging.getLogger(__name__) class CSRFExemptMixin(object): @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): logger.debug("CSRFExemptMixin: dispatch method") return super(CSRFExemptMixin, self).dispatch(*args, **kwargs) class UserAddLocationView(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): logger.debug(request.POST) lat = request.POST.get('lat', '') lon = request.POST.get('lon', '') logger.debug("Latitude: {0} and longitude: {1}".format(lat, lon)) # adds the lation object into the session request.session['location'] = {'lat': lat, 'lon': lon} request.session.set_expiry(300) data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json') class UserRemoveLocation(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): if 'location' in request.session: del request.session['location'] data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json')
Add expiration value of 5m to the session.
Add expiration value of 5m to the session.
Python
bsd-3-clause
codefordurham/food-inspector,codefordurham/Durham-Restaurants,codefordurham/Durham-Restaurants,codefordurham/food-inspector,codefordurham/food-inspector,codefordurham/Durham-Restaurants,codefordurham/food-inspector,codefordurham/Durham-Restaurants
import json import logging from django.http import HttpResponse from django.views.generic import View from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt logger = logging.getLogger(__name__) class CSRFExemptMixin(object): @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): logger.debug("CSRFExemptMixin: dispatch method") return super(CSRFExemptMixin, self).dispatch(*args, **kwargs) class UserAddLocationView(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): logger.debug(request.POST) lat = request.POST.get('lat', '') lon = request.POST.get('lon', '') logger.debug("Latitude: {0} and longitude: {1}".format(lat, lon)) # adds the lation object into the session request.session['location'] = {'lat': lat, 'lon': lon} data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json') class UserRemoveLocation(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): if 'location' in request.session: del request.session['location'] data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json') Add expiration value of 5m to the session.
import json import logging from django.http import HttpResponse from django.views.generic import View from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt logger = logging.getLogger(__name__) class CSRFExemptMixin(object): @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): logger.debug("CSRFExemptMixin: dispatch method") return super(CSRFExemptMixin, self).dispatch(*args, **kwargs) class UserAddLocationView(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): logger.debug(request.POST) lat = request.POST.get('lat', '') lon = request.POST.get('lon', '') logger.debug("Latitude: {0} and longitude: {1}".format(lat, lon)) # adds the lation object into the session request.session['location'] = {'lat': lat, 'lon': lon} request.session.set_expiry(300) data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json') class UserRemoveLocation(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): if 'location' in request.session: del request.session['location'] data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json')
<commit_before>import json import logging from django.http import HttpResponse from django.views.generic import View from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt logger = logging.getLogger(__name__) class CSRFExemptMixin(object): @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): logger.debug("CSRFExemptMixin: dispatch method") return super(CSRFExemptMixin, self).dispatch(*args, **kwargs) class UserAddLocationView(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): logger.debug(request.POST) lat = request.POST.get('lat', '') lon = request.POST.get('lon', '') logger.debug("Latitude: {0} and longitude: {1}".format(lat, lon)) # adds the lation object into the session request.session['location'] = {'lat': lat, 'lon': lon} data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json') class UserRemoveLocation(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): if 'location' in request.session: del request.session['location'] data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json') <commit_msg>Add expiration value of 5m to the session.<commit_after>
import json import logging from django.http import HttpResponse from django.views.generic import View from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt logger = logging.getLogger(__name__) class CSRFExemptMixin(object): @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): logger.debug("CSRFExemptMixin: dispatch method") return super(CSRFExemptMixin, self).dispatch(*args, **kwargs) class UserAddLocationView(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): logger.debug(request.POST) lat = request.POST.get('lat', '') lon = request.POST.get('lon', '') logger.debug("Latitude: {0} and longitude: {1}".format(lat, lon)) # adds the lation object into the session request.session['location'] = {'lat': lat, 'lon': lon} request.session.set_expiry(300) data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json') class UserRemoveLocation(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): if 'location' in request.session: del request.session['location'] data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json')
import json import logging from django.http import HttpResponse from django.views.generic import View from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt logger = logging.getLogger(__name__) class CSRFExemptMixin(object): @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): logger.debug("CSRFExemptMixin: dispatch method") return super(CSRFExemptMixin, self).dispatch(*args, **kwargs) class UserAddLocationView(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): logger.debug(request.POST) lat = request.POST.get('lat', '') lon = request.POST.get('lon', '') logger.debug("Latitude: {0} and longitude: {1}".format(lat, lon)) # adds the lation object into the session request.session['location'] = {'lat': lat, 'lon': lon} data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json') class UserRemoveLocation(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): if 'location' in request.session: del request.session['location'] data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json') Add expiration value of 5m to the session.import json import logging from django.http import HttpResponse from django.views.generic import View from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt logger = logging.getLogger(__name__) class CSRFExemptMixin(object): @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): logger.debug("CSRFExemptMixin: dispatch method") return super(CSRFExemptMixin, self).dispatch(*args, **kwargs) class UserAddLocationView(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): logger.debug(request.POST) lat = request.POST.get('lat', '') lon = request.POST.get('lon', '') logger.debug("Latitude: {0} and longitude: {1}".format(lat, lon)) # adds the lation object into the session request.session['location'] = {'lat': lat, 'lon': lon} request.session.set_expiry(300) data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json') class UserRemoveLocation(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): if 'location' in request.session: del request.session['location'] data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json')
<commit_before>import json import logging from django.http import HttpResponse from django.views.generic import View from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt logger = logging.getLogger(__name__) class CSRFExemptMixin(object): @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): logger.debug("CSRFExemptMixin: dispatch method") return super(CSRFExemptMixin, self).dispatch(*args, **kwargs) class UserAddLocationView(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): logger.debug(request.POST) lat = request.POST.get('lat', '') lon = request.POST.get('lon', '') logger.debug("Latitude: {0} and longitude: {1}".format(lat, lon)) # adds the lation object into the session request.session['location'] = {'lat': lat, 'lon': lon} data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json') class UserRemoveLocation(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): if 'location' in request.session: del request.session['location'] data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json') <commit_msg>Add expiration value of 5m to the session.<commit_after>import json import logging from django.http import HttpResponse from django.views.generic import View from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt logger = logging.getLogger(__name__) class CSRFExemptMixin(object): @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): logger.debug("CSRFExemptMixin: dispatch method") return super(CSRFExemptMixin, self).dispatch(*args, **kwargs) class UserAddLocationView(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): logger.debug(request.POST) lat = request.POST.get('lat', '') lon = request.POST.get('lon', '') logger.debug("Latitude: {0} and longitude: {1}".format(lat, lon)) # adds the lation object into the session request.session['location'] = {'lat': lat, 'lon': lon} request.session.set_expiry(300) data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json') class UserRemoveLocation(CSRFExemptMixin, View): def post(self, request, *args, **kwargs): if 'location' in request.session: del request.session['location'] data = json.dumps({'status': 'success'}) return HttpResponse(data, 'application/json')
16b3cc9be877710c80146a439b74d46987859771
ui_devel/discover.py
ui_devel/discover.py
from django.conf import settings from django.utils.importlib import import_module class InvalidTemplateFixture(Exception): pass # holds all the fixtures template_fixtures = {} def get_template_fixtures(): """ Return the list of all available template fixtures. Caches the result for faster access. Code modified from django/template/base.py/get_templatetags_modules() """ global template_fixtures if not template_fixtures: _template_fixtures = {} # Populate list once per process. Mutate the local list first, and # then assign it to the global name to ensure there are no cases where # two threads try to populate it simultaneously. for app_module in list(settings.INSTALLED_APPS): try: templatefixture_module = '%s.templatefixtures' % app_module mod = import_module(templatefixture_module) try: fixtures = mod.fixtures # TODO: validate fixtures structure _template_fixtures.update(fixtures) except AttributeError: raise InvalidTemplateFixture('Template fixture module %s ' 'does not have a variable' 'named "fixtures"' % templatefixture_module) except ValueError: raise InvalidTemplateFixture('%s.fixture should be a ' 'dictionary' % templatefixture_module) except ImportError as e: #print app_module, e continue template_fixtures = _template_fixtures return template_fixtures
from django.conf import settings from importlib import import_module class InvalidTemplateFixture(Exception): pass # holds all the fixtures template_fixtures = {} def get_template_fixtures(): """ Return the list of all available template fixtures. Caches the result for faster access. Code modified from django/template/base.py/get_templatetags_modules() """ global template_fixtures if not template_fixtures: _template_fixtures = {} # Populate list once per process. Mutate the local list first, and # then assign it to the global name to ensure there are no cases where # two threads try to populate it simultaneously. for app_module in list(settings.INSTALLED_APPS): try: templatefixture_module = '%s.templatefixtures' % app_module mod = import_module(templatefixture_module) try: fixtures = mod.fixtures # TODO: validate fixtures structure _template_fixtures.update(fixtures) except AttributeError: raise InvalidTemplateFixture('Template fixture module %s ' 'does not have a variable' 'named "fixtures"' % templatefixture_module) except ValueError: raise InvalidTemplateFixture('%s.fixture should be a ' 'dictionary' % templatefixture_module) except ImportError as e: #print app_module, e continue template_fixtures = _template_fixtures return template_fixtures
Use Python importlib instead of sjango.utils.importlib
Use Python importlib instead of sjango.utils.importlib
Python
bsd-3-clause
alexkasina/django-ui-devel,atul-bhouraskar/django-ui-devel,atul-bhouraskar/django-ui-devel,alexkasina/django-ui-devel
from django.conf import settings from django.utils.importlib import import_module class InvalidTemplateFixture(Exception): pass # holds all the fixtures template_fixtures = {} def get_template_fixtures(): """ Return the list of all available template fixtures. Caches the result for faster access. Code modified from django/template/base.py/get_templatetags_modules() """ global template_fixtures if not template_fixtures: _template_fixtures = {} # Populate list once per process. Mutate the local list first, and # then assign it to the global name to ensure there are no cases where # two threads try to populate it simultaneously. for app_module in list(settings.INSTALLED_APPS): try: templatefixture_module = '%s.templatefixtures' % app_module mod = import_module(templatefixture_module) try: fixtures = mod.fixtures # TODO: validate fixtures structure _template_fixtures.update(fixtures) except AttributeError: raise InvalidTemplateFixture('Template fixture module %s ' 'does not have a variable' 'named "fixtures"' % templatefixture_module) except ValueError: raise InvalidTemplateFixture('%s.fixture should be a ' 'dictionary' % templatefixture_module) except ImportError as e: #print app_module, e continue template_fixtures = _template_fixtures return template_fixtures Use Python importlib instead of sjango.utils.importlib
from django.conf import settings from importlib import import_module class InvalidTemplateFixture(Exception): pass # holds all the fixtures template_fixtures = {} def get_template_fixtures(): """ Return the list of all available template fixtures. Caches the result for faster access. Code modified from django/template/base.py/get_templatetags_modules() """ global template_fixtures if not template_fixtures: _template_fixtures = {} # Populate list once per process. Mutate the local list first, and # then assign it to the global name to ensure there are no cases where # two threads try to populate it simultaneously. for app_module in list(settings.INSTALLED_APPS): try: templatefixture_module = '%s.templatefixtures' % app_module mod = import_module(templatefixture_module) try: fixtures = mod.fixtures # TODO: validate fixtures structure _template_fixtures.update(fixtures) except AttributeError: raise InvalidTemplateFixture('Template fixture module %s ' 'does not have a variable' 'named "fixtures"' % templatefixture_module) except ValueError: raise InvalidTemplateFixture('%s.fixture should be a ' 'dictionary' % templatefixture_module) except ImportError as e: #print app_module, e continue template_fixtures = _template_fixtures return template_fixtures
<commit_before>from django.conf import settings from django.utils.importlib import import_module class InvalidTemplateFixture(Exception): pass # holds all the fixtures template_fixtures = {} def get_template_fixtures(): """ Return the list of all available template fixtures. Caches the result for faster access. Code modified from django/template/base.py/get_templatetags_modules() """ global template_fixtures if not template_fixtures: _template_fixtures = {} # Populate list once per process. Mutate the local list first, and # then assign it to the global name to ensure there are no cases where # two threads try to populate it simultaneously. for app_module in list(settings.INSTALLED_APPS): try: templatefixture_module = '%s.templatefixtures' % app_module mod = import_module(templatefixture_module) try: fixtures = mod.fixtures # TODO: validate fixtures structure _template_fixtures.update(fixtures) except AttributeError: raise InvalidTemplateFixture('Template fixture module %s ' 'does not have a variable' 'named "fixtures"' % templatefixture_module) except ValueError: raise InvalidTemplateFixture('%s.fixture should be a ' 'dictionary' % templatefixture_module) except ImportError as e: #print app_module, e continue template_fixtures = _template_fixtures return template_fixtures <commit_msg>Use Python importlib instead of sjango.utils.importlib<commit_after>
from django.conf import settings from importlib import import_module class InvalidTemplateFixture(Exception): pass # holds all the fixtures template_fixtures = {} def get_template_fixtures(): """ Return the list of all available template fixtures. Caches the result for faster access. Code modified from django/template/base.py/get_templatetags_modules() """ global template_fixtures if not template_fixtures: _template_fixtures = {} # Populate list once per process. Mutate the local list first, and # then assign it to the global name to ensure there are no cases where # two threads try to populate it simultaneously. for app_module in list(settings.INSTALLED_APPS): try: templatefixture_module = '%s.templatefixtures' % app_module mod = import_module(templatefixture_module) try: fixtures = mod.fixtures # TODO: validate fixtures structure _template_fixtures.update(fixtures) except AttributeError: raise InvalidTemplateFixture('Template fixture module %s ' 'does not have a variable' 'named "fixtures"' % templatefixture_module) except ValueError: raise InvalidTemplateFixture('%s.fixture should be a ' 'dictionary' % templatefixture_module) except ImportError as e: #print app_module, e continue template_fixtures = _template_fixtures return template_fixtures
from django.conf import settings from django.utils.importlib import import_module class InvalidTemplateFixture(Exception): pass # holds all the fixtures template_fixtures = {} def get_template_fixtures(): """ Return the list of all available template fixtures. Caches the result for faster access. Code modified from django/template/base.py/get_templatetags_modules() """ global template_fixtures if not template_fixtures: _template_fixtures = {} # Populate list once per process. Mutate the local list first, and # then assign it to the global name to ensure there are no cases where # two threads try to populate it simultaneously. for app_module in list(settings.INSTALLED_APPS): try: templatefixture_module = '%s.templatefixtures' % app_module mod = import_module(templatefixture_module) try: fixtures = mod.fixtures # TODO: validate fixtures structure _template_fixtures.update(fixtures) except AttributeError: raise InvalidTemplateFixture('Template fixture module %s ' 'does not have a variable' 'named "fixtures"' % templatefixture_module) except ValueError: raise InvalidTemplateFixture('%s.fixture should be a ' 'dictionary' % templatefixture_module) except ImportError as e: #print app_module, e continue template_fixtures = _template_fixtures return template_fixtures Use Python importlib instead of sjango.utils.importlibfrom django.conf import settings from importlib import import_module class InvalidTemplateFixture(Exception): pass # holds all the fixtures template_fixtures = {} def get_template_fixtures(): """ Return the list of all available template fixtures. Caches the result for faster access. Code modified from django/template/base.py/get_templatetags_modules() """ global template_fixtures if not template_fixtures: _template_fixtures = {} # Populate list once per process. Mutate the local list first, and # then assign it to the global name to ensure there are no cases where # two threads try to populate it simultaneously. for app_module in list(settings.INSTALLED_APPS): try: templatefixture_module = '%s.templatefixtures' % app_module mod = import_module(templatefixture_module) try: fixtures = mod.fixtures # TODO: validate fixtures structure _template_fixtures.update(fixtures) except AttributeError: raise InvalidTemplateFixture('Template fixture module %s ' 'does not have a variable' 'named "fixtures"' % templatefixture_module) except ValueError: raise InvalidTemplateFixture('%s.fixture should be a ' 'dictionary' % templatefixture_module) except ImportError as e: #print app_module, e continue template_fixtures = _template_fixtures return template_fixtures
<commit_before>from django.conf import settings from django.utils.importlib import import_module class InvalidTemplateFixture(Exception): pass # holds all the fixtures template_fixtures = {} def get_template_fixtures(): """ Return the list of all available template fixtures. Caches the result for faster access. Code modified from django/template/base.py/get_templatetags_modules() """ global template_fixtures if not template_fixtures: _template_fixtures = {} # Populate list once per process. Mutate the local list first, and # then assign it to the global name to ensure there are no cases where # two threads try to populate it simultaneously. for app_module in list(settings.INSTALLED_APPS): try: templatefixture_module = '%s.templatefixtures' % app_module mod = import_module(templatefixture_module) try: fixtures = mod.fixtures # TODO: validate fixtures structure _template_fixtures.update(fixtures) except AttributeError: raise InvalidTemplateFixture('Template fixture module %s ' 'does not have a variable' 'named "fixtures"' % templatefixture_module) except ValueError: raise InvalidTemplateFixture('%s.fixture should be a ' 'dictionary' % templatefixture_module) except ImportError as e: #print app_module, e continue template_fixtures = _template_fixtures return template_fixtures <commit_msg>Use Python importlib instead of sjango.utils.importlib<commit_after>from django.conf import settings from importlib import import_module class InvalidTemplateFixture(Exception): pass # holds all the fixtures template_fixtures = {} def get_template_fixtures(): """ Return the list of all available template fixtures. Caches the result for faster access. Code modified from django/template/base.py/get_templatetags_modules() """ global template_fixtures if not template_fixtures: _template_fixtures = {} # Populate list once per process. Mutate the local list first, and # then assign it to the global name to ensure there are no cases where # two threads try to populate it simultaneously. for app_module in list(settings.INSTALLED_APPS): try: templatefixture_module = '%s.templatefixtures' % app_module mod = import_module(templatefixture_module) try: fixtures = mod.fixtures # TODO: validate fixtures structure _template_fixtures.update(fixtures) except AttributeError: raise InvalidTemplateFixture('Template fixture module %s ' 'does not have a variable' 'named "fixtures"' % templatefixture_module) except ValueError: raise InvalidTemplateFixture('%s.fixture should be a ' 'dictionary' % templatefixture_module) except ImportError as e: #print app_module, e continue template_fixtures = _template_fixtures return template_fixtures
826251dc100914bf644f09acafba0f01d168a797
mysite/haystack_configuration.py
mysite/haystack_configuration.py
################ We could, import haystack, but what's the point? #import haystack ################# The docs suggest we do this: #haystack.autodiscover() ################# but we will NOT because this causes explosions in the sky. ################# We should talk to the Haystack folks. It seems that they have ################# already run into mod_wsgi woes before; here's a new one for them. # Note that when you want to re-generate the XML file that is the Solr configuration, # you may need to uncomment the above. That's fine, just do not send code that calls # haystack.autodiscover() to the git repository, and CERTAINTLY don't send it to the # production server. # Sorry to be vague. Ask me if you have questions! # -- Asheesh 2010-02-09.
### The docs suggest we do this: import haystack haystack.autodiscover()
Use haystack.autodiscover() again, in the hopes it no longer breaks the world
Use haystack.autodiscover() again, in the hopes it no longer breaks the world
Python
agpl-3.0
SnappleCap/oh-mainline,vipul-sharma20/oh-mainline,mzdaniel/oh-mainline,nirmeshk/oh-mainline,moijes12/oh-mainline,openhatch/oh-mainline,Changaco/oh-mainline,mzdaniel/oh-mainline,mzdaniel/oh-mainline,mzdaniel/oh-mainline,sudheesh001/oh-mainline,Changaco/oh-mainline,moijes12/oh-mainline,sudheesh001/oh-mainline,nirmeshk/oh-mainline,openhatch/oh-mainline,moijes12/oh-mainline,openhatch/oh-mainline,Changaco/oh-mainline,willingc/oh-mainline,sudheesh001/oh-mainline,moijes12/oh-mainline,eeshangarg/oh-mainline,waseem18/oh-mainline,SnappleCap/oh-mainline,mzdaniel/oh-mainline,mzdaniel/oh-mainline,campbe13/openhatch,sudheesh001/oh-mainline,vipul-sharma20/oh-mainline,willingc/oh-mainline,ojengwa/oh-mainline,Changaco/oh-mainline,ehashman/oh-mainline,ojengwa/oh-mainline,heeraj123/oh-mainline,waseem18/oh-mainline,campbe13/openhatch,heeraj123/oh-mainline,campbe13/openhatch,waseem18/oh-mainline,onceuponatimeforever/oh-mainline,sudheesh001/oh-mainline,onceuponatimeforever/oh-mainline,campbe13/openhatch,moijes12/oh-mainline,onceuponatimeforever/oh-mainline,vipul-sharma20/oh-mainline,mzdaniel/oh-mainline,openhatch/oh-mainline,ehashman/oh-mainline,ojengwa/oh-mainline,Changaco/oh-mainline,heeraj123/oh-mainline,ojengwa/oh-mainline,SnappleCap/oh-mainline,nirmeshk/oh-mainline,SnappleCap/oh-mainline,vipul-sharma20/oh-mainline,waseem18/oh-mainline,willingc/oh-mainline,ehashman/oh-mainline,willingc/oh-mainline,heeraj123/oh-mainline,vipul-sharma20/oh-mainline,waseem18/oh-mainline,campbe13/openhatch,nirmeshk/oh-mainline,eeshangarg/oh-mainline,openhatch/oh-mainline,onceuponatimeforever/oh-mainline,ehashman/oh-mainline,eeshangarg/oh-mainline,heeraj123/oh-mainline,willingc/oh-mainline,ojengwa/oh-mainline,ehashman/oh-mainline,nirmeshk/oh-mainline,onceuponatimeforever/oh-mainline,eeshangarg/oh-mainline,eeshangarg/oh-mainline,SnappleCap/oh-mainline
################ We could, import haystack, but what's the point? #import haystack ################# The docs suggest we do this: #haystack.autodiscover() ################# but we will NOT because this causes explosions in the sky. ################# We should talk to the Haystack folks. It seems that they have ################# already run into mod_wsgi woes before; here's a new one for them. # Note that when you want to re-generate the XML file that is the Solr configuration, # you may need to uncomment the above. That's fine, just do not send code that calls # haystack.autodiscover() to the git repository, and CERTAINTLY don't send it to the # production server. # Sorry to be vague. Ask me if you have questions! # -- Asheesh 2010-02-09. Use haystack.autodiscover() again, in the hopes it no longer breaks the world
### The docs suggest we do this: import haystack haystack.autodiscover()
<commit_before>################ We could, import haystack, but what's the point? #import haystack ################# The docs suggest we do this: #haystack.autodiscover() ################# but we will NOT because this causes explosions in the sky. ################# We should talk to the Haystack folks. It seems that they have ################# already run into mod_wsgi woes before; here's a new one for them. # Note that when you want to re-generate the XML file that is the Solr configuration, # you may need to uncomment the above. That's fine, just do not send code that calls # haystack.autodiscover() to the git repository, and CERTAINTLY don't send it to the # production server. # Sorry to be vague. Ask me if you have questions! # -- Asheesh 2010-02-09. <commit_msg>Use haystack.autodiscover() again, in the hopes it no longer breaks the world<commit_after>
### The docs suggest we do this: import haystack haystack.autodiscover()
################ We could, import haystack, but what's the point? #import haystack ################# The docs suggest we do this: #haystack.autodiscover() ################# but we will NOT because this causes explosions in the sky. ################# We should talk to the Haystack folks. It seems that they have ################# already run into mod_wsgi woes before; here's a new one for them. # Note that when you want to re-generate the XML file that is the Solr configuration, # you may need to uncomment the above. That's fine, just do not send code that calls # haystack.autodiscover() to the git repository, and CERTAINTLY don't send it to the # production server. # Sorry to be vague. Ask me if you have questions! # -- Asheesh 2010-02-09. Use haystack.autodiscover() again, in the hopes it no longer breaks the world### The docs suggest we do this: import haystack haystack.autodiscover()
<commit_before>################ We could, import haystack, but what's the point? #import haystack ################# The docs suggest we do this: #haystack.autodiscover() ################# but we will NOT because this causes explosions in the sky. ################# We should talk to the Haystack folks. It seems that they have ################# already run into mod_wsgi woes before; here's a new one for them. # Note that when you want to re-generate the XML file that is the Solr configuration, # you may need to uncomment the above. That's fine, just do not send code that calls # haystack.autodiscover() to the git repository, and CERTAINTLY don't send it to the # production server. # Sorry to be vague. Ask me if you have questions! # -- Asheesh 2010-02-09. <commit_msg>Use haystack.autodiscover() again, in the hopes it no longer breaks the world<commit_after>### The docs suggest we do this: import haystack haystack.autodiscover()
3e42af8ac949032d8dc2c4bc181a64fc2fbed651
downstream_node/models.py
downstream_node/models.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from sqlalchemy import Table
#!/usr/bin/env python # -*- coding: utf-8 -*- from downstream_node.startup import db class Files(db.Model): __tablename__ = 'files' id = db.Column(db.Integer(), primary_key=True, autoincrement=True) filepath = db.Column('filepath', db.String()) class Challenges(db.Model): __tablename__ = 'challenges' id = db.Column(db.Integer(), primary_key=True, autoincrement=True) filepath = db.Column(db.ForeignKey('files.filepath')) block = db.Column('block', db.String()) seed = db.Column('seed', db.String()) response = db.Column('response', db.String(), nullable=True)
Add model stuff into DB
Add model stuff into DB
Python
mit
Storj/downstream-node,Storj/downstream-node
#!/usr/bin/env python # -*- coding: utf-8 -*- from sqlalchemy import TableAdd model stuff into DB
#!/usr/bin/env python # -*- coding: utf-8 -*- from downstream_node.startup import db class Files(db.Model): __tablename__ = 'files' id = db.Column(db.Integer(), primary_key=True, autoincrement=True) filepath = db.Column('filepath', db.String()) class Challenges(db.Model): __tablename__ = 'challenges' id = db.Column(db.Integer(), primary_key=True, autoincrement=True) filepath = db.Column(db.ForeignKey('files.filepath')) block = db.Column('block', db.String()) seed = db.Column('seed', db.String()) response = db.Column('response', db.String(), nullable=True)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from sqlalchemy import Table<commit_msg>Add model stuff into DB<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- from downstream_node.startup import db class Files(db.Model): __tablename__ = 'files' id = db.Column(db.Integer(), primary_key=True, autoincrement=True) filepath = db.Column('filepath', db.String()) class Challenges(db.Model): __tablename__ = 'challenges' id = db.Column(db.Integer(), primary_key=True, autoincrement=True) filepath = db.Column(db.ForeignKey('files.filepath')) block = db.Column('block', db.String()) seed = db.Column('seed', db.String()) response = db.Column('response', db.String(), nullable=True)
#!/usr/bin/env python # -*- coding: utf-8 -*- from sqlalchemy import TableAdd model stuff into DB#!/usr/bin/env python # -*- coding: utf-8 -*- from downstream_node.startup import db class Files(db.Model): __tablename__ = 'files' id = db.Column(db.Integer(), primary_key=True, autoincrement=True) filepath = db.Column('filepath', db.String()) class Challenges(db.Model): __tablename__ = 'challenges' id = db.Column(db.Integer(), primary_key=True, autoincrement=True) filepath = db.Column(db.ForeignKey('files.filepath')) block = db.Column('block', db.String()) seed = db.Column('seed', db.String()) response = db.Column('response', db.String(), nullable=True)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from sqlalchemy import Table<commit_msg>Add model stuff into DB<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- from downstream_node.startup import db class Files(db.Model): __tablename__ = 'files' id = db.Column(db.Integer(), primary_key=True, autoincrement=True) filepath = db.Column('filepath', db.String()) class Challenges(db.Model): __tablename__ = 'challenges' id = db.Column(db.Integer(), primary_key=True, autoincrement=True) filepath = db.Column(db.ForeignKey('files.filepath')) block = db.Column('block', db.String()) seed = db.Column('seed', db.String()) response = db.Column('response', db.String(), nullable=True)
599e2328ba0ab4f5fa467a363e35b8c99392ad3c
elvis/utils.py
elvis/utils.py
from datetime import datetime, timedelta import pytz DATE_PREFIX = '/Date(' DATE_SUFFIX = ')/' ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn') def decode_elvis_timestamp(timestamp: str): """Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible""" str_timestamp = str(timestamp).strip() if str_timestamp.startswith(DATE_PREFIX) and str_timestamp.endswith(DATE_SUFFIX): milliseconds = str_timestamp[len(DATE_PREFIX):-len(DATE_SUFFIX)] timezone_offset = 0 try: if "+" in milliseconds: timezone_offset_string = milliseconds[milliseconds.index("+")+1:] milliseconds = milliseconds[:milliseconds.index("+")] if len(timezone_offset_string) == 4: timezone_offset = int(timezone_offset_string[:2])*60+int(timezone_offset_string[2:]) seconds = int(milliseconds) / 1000 except ValueError: return timestamp # Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn) return datetime.fromtimestamp(seconds).astimezone( ELVIS_TIMEZONE ) + timedelta(minutes=timezone_offset) return timestamp
from datetime import datetime import pytz DATE_PREFIX = '/Date(' DATE_SUFFIX = ')/' ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn') UTC = pytz.timezone('UTC') def decode_elvis_timestamp(timestamp: str): """Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible""" str_timestamp = str(timestamp).strip() if str_timestamp.startswith(DATE_PREFIX) and str_timestamp.endswith(DATE_SUFFIX): milliseconds = str_timestamp[len(DATE_PREFIX):-len(DATE_SUFFIX)] timezone_offset = 0 try: if "+" in milliseconds: timezone_offset_string = milliseconds[milliseconds.index("+")+1:] milliseconds = milliseconds[:milliseconds.index("+")] if len(timezone_offset_string) == 4: timezone_offset = int(timezone_offset_string[:2])*60+int(timezone_offset_string[2:]) seconds = int(milliseconds) / 1000 except ValueError: return timestamp # Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn) return ELVIS_TIMEZONE.localize(datetime.fromtimestamp(seconds).astimezone( pytz.FixedOffset(-timezone_offset) ).replace(tzinfo=None)) return timestamp
Fix date parsing having wrong offset
Fix date parsing having wrong offset
Python
bsd-2-clause
thorgate/python-lvis
from datetime import datetime, timedelta import pytz DATE_PREFIX = '/Date(' DATE_SUFFIX = ')/' ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn') def decode_elvis_timestamp(timestamp: str): """Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible""" str_timestamp = str(timestamp).strip() if str_timestamp.startswith(DATE_PREFIX) and str_timestamp.endswith(DATE_SUFFIX): milliseconds = str_timestamp[len(DATE_PREFIX):-len(DATE_SUFFIX)] timezone_offset = 0 try: if "+" in milliseconds: timezone_offset_string = milliseconds[milliseconds.index("+")+1:] milliseconds = milliseconds[:milliseconds.index("+")] if len(timezone_offset_string) == 4: timezone_offset = int(timezone_offset_string[:2])*60+int(timezone_offset_string[2:]) seconds = int(milliseconds) / 1000 except ValueError: return timestamp # Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn) return datetime.fromtimestamp(seconds).astimezone( ELVIS_TIMEZONE ) + timedelta(minutes=timezone_offset) return timestamp Fix date parsing having wrong offset
from datetime import datetime import pytz DATE_PREFIX = '/Date(' DATE_SUFFIX = ')/' ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn') UTC = pytz.timezone('UTC') def decode_elvis_timestamp(timestamp: str): """Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible""" str_timestamp = str(timestamp).strip() if str_timestamp.startswith(DATE_PREFIX) and str_timestamp.endswith(DATE_SUFFIX): milliseconds = str_timestamp[len(DATE_PREFIX):-len(DATE_SUFFIX)] timezone_offset = 0 try: if "+" in milliseconds: timezone_offset_string = milliseconds[milliseconds.index("+")+1:] milliseconds = milliseconds[:milliseconds.index("+")] if len(timezone_offset_string) == 4: timezone_offset = int(timezone_offset_string[:2])*60+int(timezone_offset_string[2:]) seconds = int(milliseconds) / 1000 except ValueError: return timestamp # Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn) return ELVIS_TIMEZONE.localize(datetime.fromtimestamp(seconds).astimezone( pytz.FixedOffset(-timezone_offset) ).replace(tzinfo=None)) return timestamp
<commit_before>from datetime import datetime, timedelta import pytz DATE_PREFIX = '/Date(' DATE_SUFFIX = ')/' ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn') def decode_elvis_timestamp(timestamp: str): """Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible""" str_timestamp = str(timestamp).strip() if str_timestamp.startswith(DATE_PREFIX) and str_timestamp.endswith(DATE_SUFFIX): milliseconds = str_timestamp[len(DATE_PREFIX):-len(DATE_SUFFIX)] timezone_offset = 0 try: if "+" in milliseconds: timezone_offset_string = milliseconds[milliseconds.index("+")+1:] milliseconds = milliseconds[:milliseconds.index("+")] if len(timezone_offset_string) == 4: timezone_offset = int(timezone_offset_string[:2])*60+int(timezone_offset_string[2:]) seconds = int(milliseconds) / 1000 except ValueError: return timestamp # Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn) return datetime.fromtimestamp(seconds).astimezone( ELVIS_TIMEZONE ) + timedelta(minutes=timezone_offset) return timestamp <commit_msg>Fix date parsing having wrong offset<commit_after>
from datetime import datetime import pytz DATE_PREFIX = '/Date(' DATE_SUFFIX = ')/' ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn') UTC = pytz.timezone('UTC') def decode_elvis_timestamp(timestamp: str): """Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible""" str_timestamp = str(timestamp).strip() if str_timestamp.startswith(DATE_PREFIX) and str_timestamp.endswith(DATE_SUFFIX): milliseconds = str_timestamp[len(DATE_PREFIX):-len(DATE_SUFFIX)] timezone_offset = 0 try: if "+" in milliseconds: timezone_offset_string = milliseconds[milliseconds.index("+")+1:] milliseconds = milliseconds[:milliseconds.index("+")] if len(timezone_offset_string) == 4: timezone_offset = int(timezone_offset_string[:2])*60+int(timezone_offset_string[2:]) seconds = int(milliseconds) / 1000 except ValueError: return timestamp # Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn) return ELVIS_TIMEZONE.localize(datetime.fromtimestamp(seconds).astimezone( pytz.FixedOffset(-timezone_offset) ).replace(tzinfo=None)) return timestamp
from datetime import datetime, timedelta import pytz DATE_PREFIX = '/Date(' DATE_SUFFIX = ')/' ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn') def decode_elvis_timestamp(timestamp: str): """Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible""" str_timestamp = str(timestamp).strip() if str_timestamp.startswith(DATE_PREFIX) and str_timestamp.endswith(DATE_SUFFIX): milliseconds = str_timestamp[len(DATE_PREFIX):-len(DATE_SUFFIX)] timezone_offset = 0 try: if "+" in milliseconds: timezone_offset_string = milliseconds[milliseconds.index("+")+1:] milliseconds = milliseconds[:milliseconds.index("+")] if len(timezone_offset_string) == 4: timezone_offset = int(timezone_offset_string[:2])*60+int(timezone_offset_string[2:]) seconds = int(milliseconds) / 1000 except ValueError: return timestamp # Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn) return datetime.fromtimestamp(seconds).astimezone( ELVIS_TIMEZONE ) + timedelta(minutes=timezone_offset) return timestamp Fix date parsing having wrong offsetfrom datetime import datetime import pytz DATE_PREFIX = '/Date(' DATE_SUFFIX = ')/' ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn') UTC = pytz.timezone('UTC') def decode_elvis_timestamp(timestamp: str): """Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible""" str_timestamp = str(timestamp).strip() if str_timestamp.startswith(DATE_PREFIX) and str_timestamp.endswith(DATE_SUFFIX): milliseconds = str_timestamp[len(DATE_PREFIX):-len(DATE_SUFFIX)] timezone_offset = 0 try: if "+" in milliseconds: timezone_offset_string = milliseconds[milliseconds.index("+")+1:] milliseconds = milliseconds[:milliseconds.index("+")] if len(timezone_offset_string) == 4: timezone_offset = int(timezone_offset_string[:2])*60+int(timezone_offset_string[2:]) seconds = int(milliseconds) / 1000 except ValueError: return timestamp # Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn) return ELVIS_TIMEZONE.localize(datetime.fromtimestamp(seconds).astimezone( pytz.FixedOffset(-timezone_offset) ).replace(tzinfo=None)) return timestamp
<commit_before>from datetime import datetime, timedelta import pytz DATE_PREFIX = '/Date(' DATE_SUFFIX = ')/' ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn') def decode_elvis_timestamp(timestamp: str): """Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible""" str_timestamp = str(timestamp).strip() if str_timestamp.startswith(DATE_PREFIX) and str_timestamp.endswith(DATE_SUFFIX): milliseconds = str_timestamp[len(DATE_PREFIX):-len(DATE_SUFFIX)] timezone_offset = 0 try: if "+" in milliseconds: timezone_offset_string = milliseconds[milliseconds.index("+")+1:] milliseconds = milliseconds[:milliseconds.index("+")] if len(timezone_offset_string) == 4: timezone_offset = int(timezone_offset_string[:2])*60+int(timezone_offset_string[2:]) seconds = int(milliseconds) / 1000 except ValueError: return timestamp # Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn) return datetime.fromtimestamp(seconds).astimezone( ELVIS_TIMEZONE ) + timedelta(minutes=timezone_offset) return timestamp <commit_msg>Fix date parsing having wrong offset<commit_after>from datetime import datetime import pytz DATE_PREFIX = '/Date(' DATE_SUFFIX = ')/' ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn') UTC = pytz.timezone('UTC') def decode_elvis_timestamp(timestamp: str): """Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible""" str_timestamp = str(timestamp).strip() if str_timestamp.startswith(DATE_PREFIX) and str_timestamp.endswith(DATE_SUFFIX): milliseconds = str_timestamp[len(DATE_PREFIX):-len(DATE_SUFFIX)] timezone_offset = 0 try: if "+" in milliseconds: timezone_offset_string = milliseconds[milliseconds.index("+")+1:] milliseconds = milliseconds[:milliseconds.index("+")] if len(timezone_offset_string) == 4: timezone_offset = int(timezone_offset_string[:2])*60+int(timezone_offset_string[2:]) seconds = int(milliseconds) / 1000 except ValueError: return timestamp # Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn) return ELVIS_TIMEZONE.localize(datetime.fromtimestamp(seconds).astimezone( pytz.FixedOffset(-timezone_offset) ).replace(tzinfo=None)) return timestamp
80326d96a8137c1d285d3c24eda15039e03dedfe
opps/contrib/logging/models.py
opps/contrib/logging/models.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from opps.core.models import NotUserPublishable class Logging(NotUserPublishable): user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True) application = models.CharField( _(u"Application"), max_length=75, null=True, blank=True, db_index=True) action = models.CharField( _(u"Action"), max_length=50, null=True, blank=True, db_index=True) text = models.TextField( _(u"Text"), null=True, blank=True, ) def save(self, *args, **kwargs): self.published = True super(Logging, self).save(*args, **kwargs)
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from opps.core.models import NotUserPublishable class Logging(NotUserPublishable): user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, ) application = models.CharField( _(u"Application"), max_length=75, null=True, blank=True, db_index=True) action = models.CharField( _(u"Action"), max_length=50, null=True, blank=True, db_index=True) text = models.TextField( _(u"Text"), null=True, blank=True, db_index=True) def save(self, *args, **kwargs): self.published = True super(Logging, self).save(*args, **kwargs)
Add index in text field on Logging
Add index in text field on Logging
Python
mit
opps/opps,williamroot/opps,opps/opps,williamroot/opps,YACOWS/opps,opps/opps,jeanmask/opps,jeanmask/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,williamroot/opps,opps/opps
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from opps.core.models import NotUserPublishable class Logging(NotUserPublishable): user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True) application = models.CharField( _(u"Application"), max_length=75, null=True, blank=True, db_index=True) action = models.CharField( _(u"Action"), max_length=50, null=True, blank=True, db_index=True) text = models.TextField( _(u"Text"), null=True, blank=True, ) def save(self, *args, **kwargs): self.published = True super(Logging, self).save(*args, **kwargs) Add index in text field on Logging
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from opps.core.models import NotUserPublishable class Logging(NotUserPublishable): user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, ) application = models.CharField( _(u"Application"), max_length=75, null=True, blank=True, db_index=True) action = models.CharField( _(u"Action"), max_length=50, null=True, blank=True, db_index=True) text = models.TextField( _(u"Text"), null=True, blank=True, db_index=True) def save(self, *args, **kwargs): self.published = True super(Logging, self).save(*args, **kwargs)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from opps.core.models import NotUserPublishable class Logging(NotUserPublishable): user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True) application = models.CharField( _(u"Application"), max_length=75, null=True, blank=True, db_index=True) action = models.CharField( _(u"Action"), max_length=50, null=True, blank=True, db_index=True) text = models.TextField( _(u"Text"), null=True, blank=True, ) def save(self, *args, **kwargs): self.published = True super(Logging, self).save(*args, **kwargs) <commit_msg>Add index in text field on Logging<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from opps.core.models import NotUserPublishable class Logging(NotUserPublishable): user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, ) application = models.CharField( _(u"Application"), max_length=75, null=True, blank=True, db_index=True) action = models.CharField( _(u"Action"), max_length=50, null=True, blank=True, db_index=True) text = models.TextField( _(u"Text"), null=True, blank=True, db_index=True) def save(self, *args, **kwargs): self.published = True super(Logging, self).save(*args, **kwargs)
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from opps.core.models import NotUserPublishable class Logging(NotUserPublishable): user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True) application = models.CharField( _(u"Application"), max_length=75, null=True, blank=True, db_index=True) action = models.CharField( _(u"Action"), max_length=50, null=True, blank=True, db_index=True) text = models.TextField( _(u"Text"), null=True, blank=True, ) def save(self, *args, **kwargs): self.published = True super(Logging, self).save(*args, **kwargs) Add index in text field on Logging#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from opps.core.models import NotUserPublishable class Logging(NotUserPublishable): user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, ) application = models.CharField( _(u"Application"), max_length=75, null=True, blank=True, db_index=True) action = models.CharField( _(u"Action"), max_length=50, null=True, blank=True, db_index=True) text = models.TextField( _(u"Text"), null=True, blank=True, db_index=True) def save(self, *args, **kwargs): self.published = True super(Logging, self).save(*args, **kwargs)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from opps.core.models import NotUserPublishable class Logging(NotUserPublishable): user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True) application = models.CharField( _(u"Application"), max_length=75, null=True, blank=True, db_index=True) action = models.CharField( _(u"Action"), max_length=50, null=True, blank=True, db_index=True) text = models.TextField( _(u"Text"), null=True, blank=True, ) def save(self, *args, **kwargs): self.published = True super(Logging, self).save(*args, **kwargs) <commit_msg>Add index in text field on Logging<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from opps.core.models import NotUserPublishable class Logging(NotUserPublishable): user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, ) application = models.CharField( _(u"Application"), max_length=75, null=True, blank=True, db_index=True) action = models.CharField( _(u"Action"), max_length=50, null=True, blank=True, db_index=True) text = models.TextField( _(u"Text"), null=True, blank=True, db_index=True) def save(self, *args, **kwargs): self.published = True super(Logging, self).save(*args, **kwargs)
00c87d7b169119c8d9e5972d47ec9293870f313f
gui.py
gui.py
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="Text Playing Game") self.set_border_width(10) self.set_size_request(500, 400) win = MainWindow() win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main()
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="Text Playing Game") self.set_border_width(10) self.set_size_request(400, 350) box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=20) box.set_homogeneous(False) vboxUp = Gtk.Box(spacing=20) vboxUp.set_homogeneous(False) vboxBot = Gtk.Box(spacing=20) vboxBot.set_homogeneous(False) hboxLeft = Gtk.Box(spacing=20) hboxLeft.set_homogeneous(False) hboxRight = Gtk.Box(spacing=20) hboxRight.set_homogeneous(False) box.pack_start(vboxUp, True, True, 0) box.pack_start(vboxBot, True, True, 0) vboxBot.pack_start(hboxLeft, True, True, 0) vboxBot.pack_start(hboxRight, True, True, 0) label = Gtk.Label() label.set_text("What is your name brave soul?") label.set_justify(Gtk.Justification.FILL) vboxUp.pack_start(label, True, True, 0) self.entry = Gtk.Entry() hboxLeft.pack_start(self.entry, True, True, 0) self.button = Gtk.Button(label="Next") self.button.connect("clicked", self.button_clicked) hboxRight.pack_start(self.button, True, True, 0) self.add(box) def button_clicked(self, widget): print("Hello") win = MainWindow() win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main()
Set up beginning template - definitely requires changes
Set up beginning template - definitely requires changes
Python
mit
Giovanni21M/Text-Playing-Game
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="Text Playing Game") self.set_border_width(10) self.set_size_request(500, 400) win = MainWindow() win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main() Set up beginning template - definitely requires changes
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="Text Playing Game") self.set_border_width(10) self.set_size_request(400, 350) box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=20) box.set_homogeneous(False) vboxUp = Gtk.Box(spacing=20) vboxUp.set_homogeneous(False) vboxBot = Gtk.Box(spacing=20) vboxBot.set_homogeneous(False) hboxLeft = Gtk.Box(spacing=20) hboxLeft.set_homogeneous(False) hboxRight = Gtk.Box(spacing=20) hboxRight.set_homogeneous(False) box.pack_start(vboxUp, True, True, 0) box.pack_start(vboxBot, True, True, 0) vboxBot.pack_start(hboxLeft, True, True, 0) vboxBot.pack_start(hboxRight, True, True, 0) label = Gtk.Label() label.set_text("What is your name brave soul?") label.set_justify(Gtk.Justification.FILL) vboxUp.pack_start(label, True, True, 0) self.entry = Gtk.Entry() hboxLeft.pack_start(self.entry, True, True, 0) self.button = Gtk.Button(label="Next") self.button.connect("clicked", self.button_clicked) hboxRight.pack_start(self.button, True, True, 0) self.add(box) def button_clicked(self, widget): print("Hello") win = MainWindow() win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main()
<commit_before>import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="Text Playing Game") self.set_border_width(10) self.set_size_request(500, 400) win = MainWindow() win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main() <commit_msg>Set up beginning template - definitely requires changes<commit_after>
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="Text Playing Game") self.set_border_width(10) self.set_size_request(400, 350) box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=20) box.set_homogeneous(False) vboxUp = Gtk.Box(spacing=20) vboxUp.set_homogeneous(False) vboxBot = Gtk.Box(spacing=20) vboxBot.set_homogeneous(False) hboxLeft = Gtk.Box(spacing=20) hboxLeft.set_homogeneous(False) hboxRight = Gtk.Box(spacing=20) hboxRight.set_homogeneous(False) box.pack_start(vboxUp, True, True, 0) box.pack_start(vboxBot, True, True, 0) vboxBot.pack_start(hboxLeft, True, True, 0) vboxBot.pack_start(hboxRight, True, True, 0) label = Gtk.Label() label.set_text("What is your name brave soul?") label.set_justify(Gtk.Justification.FILL) vboxUp.pack_start(label, True, True, 0) self.entry = Gtk.Entry() hboxLeft.pack_start(self.entry, True, True, 0) self.button = Gtk.Button(label="Next") self.button.connect("clicked", self.button_clicked) hboxRight.pack_start(self.button, True, True, 0) self.add(box) def button_clicked(self, widget): print("Hello") win = MainWindow() win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main()
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="Text Playing Game") self.set_border_width(10) self.set_size_request(500, 400) win = MainWindow() win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main() Set up beginning template - definitely requires changesimport gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="Text Playing Game") self.set_border_width(10) self.set_size_request(400, 350) box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=20) box.set_homogeneous(False) vboxUp = Gtk.Box(spacing=20) vboxUp.set_homogeneous(False) vboxBot = Gtk.Box(spacing=20) vboxBot.set_homogeneous(False) hboxLeft = Gtk.Box(spacing=20) hboxLeft.set_homogeneous(False) hboxRight = Gtk.Box(spacing=20) hboxRight.set_homogeneous(False) box.pack_start(vboxUp, True, True, 0) box.pack_start(vboxBot, True, True, 0) vboxBot.pack_start(hboxLeft, True, True, 0) vboxBot.pack_start(hboxRight, True, True, 0) label = Gtk.Label() label.set_text("What is your name brave soul?") label.set_justify(Gtk.Justification.FILL) vboxUp.pack_start(label, True, True, 0) self.entry = Gtk.Entry() hboxLeft.pack_start(self.entry, True, True, 0) self.button = Gtk.Button(label="Next") self.button.connect("clicked", self.button_clicked) hboxRight.pack_start(self.button, True, True, 0) self.add(box) def button_clicked(self, widget): print("Hello") win = MainWindow() win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main()
<commit_before>import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="Text Playing Game") self.set_border_width(10) self.set_size_request(500, 400) win = MainWindow() win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main() <commit_msg>Set up beginning template - definitely requires changes<commit_after>import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="Text Playing Game") self.set_border_width(10) self.set_size_request(400, 350) box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=20) box.set_homogeneous(False) vboxUp = Gtk.Box(spacing=20) vboxUp.set_homogeneous(False) vboxBot = Gtk.Box(spacing=20) vboxBot.set_homogeneous(False) hboxLeft = Gtk.Box(spacing=20) hboxLeft.set_homogeneous(False) hboxRight = Gtk.Box(spacing=20) hboxRight.set_homogeneous(False) box.pack_start(vboxUp, True, True, 0) box.pack_start(vboxBot, True, True, 0) vboxBot.pack_start(hboxLeft, True, True, 0) vboxBot.pack_start(hboxRight, True, True, 0) label = Gtk.Label() label.set_text("What is your name brave soul?") label.set_justify(Gtk.Justification.FILL) vboxUp.pack_start(label, True, True, 0) self.entry = Gtk.Entry() hboxLeft.pack_start(self.entry, True, True, 0) self.button = Gtk.Button(label="Next") self.button.connect("clicked", self.button_clicked) hboxRight.pack_start(self.button, True, True, 0) self.add(box) def button_clicked(self, widget): print("Hello") win = MainWindow() win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main()
1079550f0742a446c1b64e6080a40e06ffa6a30d
nova/policies/instance_actions.py
nova/policies/instance_actions.py
# Copyright 2016 Cloudbase Solutions Srl # 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 oslo_policy import policy from nova.policies import base BASE_POLICY_NAME = 'os_compute_api:os-instance-actions' POLICY_ROOT = 'os_compute_api:os-instance-actions:%s' instance_actions_policies = [ policy.RuleDefault( name=POLICY_ROOT % 'events', check_str=base.RULE_ADMIN_API), policy.RuleDefault( name=BASE_POLICY_NAME, check_str=base.RULE_ADMIN_OR_OWNER), ] def list_rules(): return instance_actions_policies
# Copyright 2016 Cloudbase Solutions Srl # 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 nova.policies import base BASE_POLICY_NAME = 'os_compute_api:os-instance-actions' POLICY_ROOT = 'os_compute_api:os-instance-actions:%s' instance_actions_policies = [ base.create_rule_default( POLICY_ROOT % 'events', base.RULE_ADMIN_API, """Add events details in action details for a server. This check is performed only after the check os_compute_api:os-instance-actions passes""", [ { 'method': 'GET', 'path': '/servers/{server_id}/os-instance-actions/{request_id}' } ]), base.create_rule_default( BASE_POLICY_NAME, base.RULE_ADMIN_OR_OWNER, """List actions and show action details for a server.""", [ { 'method': 'GET', 'path': '/servers/{server_id}/os-instance-actions' }, { 'method': 'GET', 'path': '/servers/{server_id}/os-instance-actions/{request_id}' } ]), ] def list_rules(): return instance_actions_policies
Add policy description for instance actions
Add policy description for instance actions This commit adds policy doc for instance actions policies. Partial implement blueprint policy-docs Change-Id: Id336b660fb687d096cd55bf8758dc408c45f9382
Python
apache-2.0
gooddata/openstack-nova,vmturbo/nova,rahulunair/nova,rajalokan/nova,klmitch/nova,openstack/nova,openstack/nova,vmturbo/nova,mikalstill/nova,mahak/nova,klmitch/nova,openstack/nova,mikalstill/nova,vmturbo/nova,mahak/nova,phenoxim/nova,mikalstill/nova,klmitch/nova,gooddata/openstack-nova,Juniper/nova,gooddata/openstack-nova,klmitch/nova,jianghuaw/nova,Juniper/nova,Juniper/nova,phenoxim/nova,rajalokan/nova,vmturbo/nova,mahak/nova,rahulunair/nova,jianghuaw/nova,jianghuaw/nova,rajalokan/nova,Juniper/nova,jianghuaw/nova,rajalokan/nova,rahulunair/nova,gooddata/openstack-nova
# Copyright 2016 Cloudbase Solutions Srl # 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 oslo_policy import policy from nova.policies import base BASE_POLICY_NAME = 'os_compute_api:os-instance-actions' POLICY_ROOT = 'os_compute_api:os-instance-actions:%s' instance_actions_policies = [ policy.RuleDefault( name=POLICY_ROOT % 'events', check_str=base.RULE_ADMIN_API), policy.RuleDefault( name=BASE_POLICY_NAME, check_str=base.RULE_ADMIN_OR_OWNER), ] def list_rules(): return instance_actions_policies Add policy description for instance actions This commit adds policy doc for instance actions policies. Partial implement blueprint policy-docs Change-Id: Id336b660fb687d096cd55bf8758dc408c45f9382
# Copyright 2016 Cloudbase Solutions Srl # 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 nova.policies import base BASE_POLICY_NAME = 'os_compute_api:os-instance-actions' POLICY_ROOT = 'os_compute_api:os-instance-actions:%s' instance_actions_policies = [ base.create_rule_default( POLICY_ROOT % 'events', base.RULE_ADMIN_API, """Add events details in action details for a server. This check is performed only after the check os_compute_api:os-instance-actions passes""", [ { 'method': 'GET', 'path': '/servers/{server_id}/os-instance-actions/{request_id}' } ]), base.create_rule_default( BASE_POLICY_NAME, base.RULE_ADMIN_OR_OWNER, """List actions and show action details for a server.""", [ { 'method': 'GET', 'path': '/servers/{server_id}/os-instance-actions' }, { 'method': 'GET', 'path': '/servers/{server_id}/os-instance-actions/{request_id}' } ]), ] def list_rules(): return instance_actions_policies
<commit_before># Copyright 2016 Cloudbase Solutions Srl # 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 oslo_policy import policy from nova.policies import base BASE_POLICY_NAME = 'os_compute_api:os-instance-actions' POLICY_ROOT = 'os_compute_api:os-instance-actions:%s' instance_actions_policies = [ policy.RuleDefault( name=POLICY_ROOT % 'events', check_str=base.RULE_ADMIN_API), policy.RuleDefault( name=BASE_POLICY_NAME, check_str=base.RULE_ADMIN_OR_OWNER), ] def list_rules(): return instance_actions_policies <commit_msg>Add policy description for instance actions This commit adds policy doc for instance actions policies. Partial implement blueprint policy-docs Change-Id: Id336b660fb687d096cd55bf8758dc408c45f9382<commit_after>
# Copyright 2016 Cloudbase Solutions Srl # 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 nova.policies import base BASE_POLICY_NAME = 'os_compute_api:os-instance-actions' POLICY_ROOT = 'os_compute_api:os-instance-actions:%s' instance_actions_policies = [ base.create_rule_default( POLICY_ROOT % 'events', base.RULE_ADMIN_API, """Add events details in action details for a server. This check is performed only after the check os_compute_api:os-instance-actions passes""", [ { 'method': 'GET', 'path': '/servers/{server_id}/os-instance-actions/{request_id}' } ]), base.create_rule_default( BASE_POLICY_NAME, base.RULE_ADMIN_OR_OWNER, """List actions and show action details for a server.""", [ { 'method': 'GET', 'path': '/servers/{server_id}/os-instance-actions' }, { 'method': 'GET', 'path': '/servers/{server_id}/os-instance-actions/{request_id}' } ]), ] def list_rules(): return instance_actions_policies
# Copyright 2016 Cloudbase Solutions Srl # 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 oslo_policy import policy from nova.policies import base BASE_POLICY_NAME = 'os_compute_api:os-instance-actions' POLICY_ROOT = 'os_compute_api:os-instance-actions:%s' instance_actions_policies = [ policy.RuleDefault( name=POLICY_ROOT % 'events', check_str=base.RULE_ADMIN_API), policy.RuleDefault( name=BASE_POLICY_NAME, check_str=base.RULE_ADMIN_OR_OWNER), ] def list_rules(): return instance_actions_policies Add policy description for instance actions This commit adds policy doc for instance actions policies. Partial implement blueprint policy-docs Change-Id: Id336b660fb687d096cd55bf8758dc408c45f9382# Copyright 2016 Cloudbase Solutions Srl # 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 nova.policies import base BASE_POLICY_NAME = 'os_compute_api:os-instance-actions' POLICY_ROOT = 'os_compute_api:os-instance-actions:%s' instance_actions_policies = [ base.create_rule_default( POLICY_ROOT % 'events', base.RULE_ADMIN_API, """Add events details in action details for a server. This check is performed only after the check os_compute_api:os-instance-actions passes""", [ { 'method': 'GET', 'path': '/servers/{server_id}/os-instance-actions/{request_id}' } ]), base.create_rule_default( BASE_POLICY_NAME, base.RULE_ADMIN_OR_OWNER, """List actions and show action details for a server.""", [ { 'method': 'GET', 'path': '/servers/{server_id}/os-instance-actions' }, { 'method': 'GET', 'path': '/servers/{server_id}/os-instance-actions/{request_id}' } ]), ] def list_rules(): return instance_actions_policies
<commit_before># Copyright 2016 Cloudbase Solutions Srl # 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 oslo_policy import policy from nova.policies import base BASE_POLICY_NAME = 'os_compute_api:os-instance-actions' POLICY_ROOT = 'os_compute_api:os-instance-actions:%s' instance_actions_policies = [ policy.RuleDefault( name=POLICY_ROOT % 'events', check_str=base.RULE_ADMIN_API), policy.RuleDefault( name=BASE_POLICY_NAME, check_str=base.RULE_ADMIN_OR_OWNER), ] def list_rules(): return instance_actions_policies <commit_msg>Add policy description for instance actions This commit adds policy doc for instance actions policies. Partial implement blueprint policy-docs Change-Id: Id336b660fb687d096cd55bf8758dc408c45f9382<commit_after># Copyright 2016 Cloudbase Solutions Srl # 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 nova.policies import base BASE_POLICY_NAME = 'os_compute_api:os-instance-actions' POLICY_ROOT = 'os_compute_api:os-instance-actions:%s' instance_actions_policies = [ base.create_rule_default( POLICY_ROOT % 'events', base.RULE_ADMIN_API, """Add events details in action details for a server. This check is performed only after the check os_compute_api:os-instance-actions passes""", [ { 'method': 'GET', 'path': '/servers/{server_id}/os-instance-actions/{request_id}' } ]), base.create_rule_default( BASE_POLICY_NAME, base.RULE_ADMIN_OR_OWNER, """List actions and show action details for a server.""", [ { 'method': 'GET', 'path': '/servers/{server_id}/os-instance-actions' }, { 'method': 'GET', 'path': '/servers/{server_id}/os-instance-actions/{request_id}' } ]), ] def list_rules(): return instance_actions_policies
720996b538862220a3b6c822beff52840e53aaac
seleniumbase/config/proxy_list.py
seleniumbase/config/proxy_list.py
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://www.us-proxy.org/ * https://hidemy.name/en/proxy-list/ """ PROXY_LIST = { "example1": "134.209.128.61:3128", # (Example) - set your own proxy here "example2": "165.227.83.185:3128", # (Example) - set your own proxy here "example3": "82.200.233.4:3128", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://bit.ly/36GtZa1 * https://www.us-proxy.org/ * https://hidemy.name/en/proxy-list/ * http://free-proxy.cz/en/proxylist/country/all/https/ping/all """ PROXY_LIST = { "example1": "152.26.66.140:3128", # (Example) - set your own proxy here "example2": "64.235.204.107:8080", # (Example) - set your own proxy here "example3": "82.200.233.4:3128", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
Update the sample proxy list
Update the sample proxy list
Python
mit
mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://www.us-proxy.org/ * https://hidemy.name/en/proxy-list/ """ PROXY_LIST = { "example1": "134.209.128.61:3128", # (Example) - set your own proxy here "example2": "165.227.83.185:3128", # (Example) - set your own proxy here "example3": "82.200.233.4:3128", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, } Update the sample proxy list
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://bit.ly/36GtZa1 * https://www.us-proxy.org/ * https://hidemy.name/en/proxy-list/ * http://free-proxy.cz/en/proxylist/country/all/https/ping/all """ PROXY_LIST = { "example1": "152.26.66.140:3128", # (Example) - set your own proxy here "example2": "64.235.204.107:8080", # (Example) - set your own proxy here "example3": "82.200.233.4:3128", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
<commit_before>""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://www.us-proxy.org/ * https://hidemy.name/en/proxy-list/ """ PROXY_LIST = { "example1": "134.209.128.61:3128", # (Example) - set your own proxy here "example2": "165.227.83.185:3128", # (Example) - set your own proxy here "example3": "82.200.233.4:3128", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, } <commit_msg>Update the sample proxy list<commit_after>
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://bit.ly/36GtZa1 * https://www.us-proxy.org/ * https://hidemy.name/en/proxy-list/ * http://free-proxy.cz/en/proxylist/country/all/https/ping/all """ PROXY_LIST = { "example1": "152.26.66.140:3128", # (Example) - set your own proxy here "example2": "64.235.204.107:8080", # (Example) - set your own proxy here "example3": "82.200.233.4:3128", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://www.us-proxy.org/ * https://hidemy.name/en/proxy-list/ """ PROXY_LIST = { "example1": "134.209.128.61:3128", # (Example) - set your own proxy here "example2": "165.227.83.185:3128", # (Example) - set your own proxy here "example3": "82.200.233.4:3128", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, } Update the sample proxy list""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://bit.ly/36GtZa1 * https://www.us-proxy.org/ * https://hidemy.name/en/proxy-list/ * http://free-proxy.cz/en/proxylist/country/all/https/ping/all """ PROXY_LIST = { "example1": "152.26.66.140:3128", # (Example) - set your own proxy here "example2": "64.235.204.107:8080", # (Example) - set your own proxy here "example3": "82.200.233.4:3128", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
<commit_before>""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://www.us-proxy.org/ * https://hidemy.name/en/proxy-list/ """ PROXY_LIST = { "example1": "134.209.128.61:3128", # (Example) - set your own proxy here "example2": "165.227.83.185:3128", # (Example) - set your own proxy here "example3": "82.200.233.4:3128", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, } <commit_msg>Update the sample proxy list<commit_after>""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://bit.ly/36GtZa1 * https://www.us-proxy.org/ * https://hidemy.name/en/proxy-list/ * http://free-proxy.cz/en/proxylist/country/all/https/ping/all """ PROXY_LIST = { "example1": "152.26.66.140:3128", # (Example) - set your own proxy here "example2": "64.235.204.107:8080", # (Example) - set your own proxy here "example3": "82.200.233.4:3128", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
5c9100b40ce5d99368ace789f8545be10ec9db71
providers/tasks/gog.py
providers/tasks/gog.py
""" Compare GOG games to the Lutris library """ import os from celery import task from celery.utils.log import get_task_logger from django.conf import settings from providers.gog import load_games_from_gogdb, match_from_gogdb LOGGER = get_task_logger(__name__) @task def load_gog_games(): """Task to load GOG games from a GOGDB dump""" file_path = os.path.join(settings.GOG_CACHE_PATH, "gogdb.json") if not os.path.exists(file_path): LOGGER.error("No file present at %s", file_path) return None return load_games_from_gogdb(file_path) @task def match_gog_games(): """Match GOG games with Lutris games""" return match_from_gogdb(create_missing=True)
""" Compare GOG games to the Lutris library """ import os from celery import task from celery.utils.log import get_task_logger from django.conf import settings from providers.gog import load_games_from_gogdb, match_from_gogdb from common.models import save_action_log LOGGER = get_task_logger(__name__) @task def load_gog_games(): """Task to load GOG games from a GOGDB dump""" file_path = os.path.join(settings.GOG_CACHE_PATH, "gogdb.json") if not os.path.exists(file_path): LOGGER.error("No file present at %s", file_path) return None stats = load_games_from_gogdb(file_path) save_action_log("load_gog_games", stats) return stats @task def match_gog_games(): """Match GOG games with Lutris games""" stats = match_from_gogdb(create_missing=True) save_action_log("match_gog_games", stats) return stats
Add stats logging for GOG tasks
Add stats logging for GOG tasks
Python
agpl-3.0
lutris/website,lutris/website,lutris/website,lutris/website
""" Compare GOG games to the Lutris library """ import os from celery import task from celery.utils.log import get_task_logger from django.conf import settings from providers.gog import load_games_from_gogdb, match_from_gogdb LOGGER = get_task_logger(__name__) @task def load_gog_games(): """Task to load GOG games from a GOGDB dump""" file_path = os.path.join(settings.GOG_CACHE_PATH, "gogdb.json") if not os.path.exists(file_path): LOGGER.error("No file present at %s", file_path) return None return load_games_from_gogdb(file_path) @task def match_gog_games(): """Match GOG games with Lutris games""" return match_from_gogdb(create_missing=True) Add stats logging for GOG tasks
""" Compare GOG games to the Lutris library """ import os from celery import task from celery.utils.log import get_task_logger from django.conf import settings from providers.gog import load_games_from_gogdb, match_from_gogdb from common.models import save_action_log LOGGER = get_task_logger(__name__) @task def load_gog_games(): """Task to load GOG games from a GOGDB dump""" file_path = os.path.join(settings.GOG_CACHE_PATH, "gogdb.json") if not os.path.exists(file_path): LOGGER.error("No file present at %s", file_path) return None stats = load_games_from_gogdb(file_path) save_action_log("load_gog_games", stats) return stats @task def match_gog_games(): """Match GOG games with Lutris games""" stats = match_from_gogdb(create_missing=True) save_action_log("match_gog_games", stats) return stats
<commit_before>""" Compare GOG games to the Lutris library """ import os from celery import task from celery.utils.log import get_task_logger from django.conf import settings from providers.gog import load_games_from_gogdb, match_from_gogdb LOGGER = get_task_logger(__name__) @task def load_gog_games(): """Task to load GOG games from a GOGDB dump""" file_path = os.path.join(settings.GOG_CACHE_PATH, "gogdb.json") if not os.path.exists(file_path): LOGGER.error("No file present at %s", file_path) return None return load_games_from_gogdb(file_path) @task def match_gog_games(): """Match GOG games with Lutris games""" return match_from_gogdb(create_missing=True) <commit_msg>Add stats logging for GOG tasks<commit_after>
""" Compare GOG games to the Lutris library """ import os from celery import task from celery.utils.log import get_task_logger from django.conf import settings from providers.gog import load_games_from_gogdb, match_from_gogdb from common.models import save_action_log LOGGER = get_task_logger(__name__) @task def load_gog_games(): """Task to load GOG games from a GOGDB dump""" file_path = os.path.join(settings.GOG_CACHE_PATH, "gogdb.json") if not os.path.exists(file_path): LOGGER.error("No file present at %s", file_path) return None stats = load_games_from_gogdb(file_path) save_action_log("load_gog_games", stats) return stats @task def match_gog_games(): """Match GOG games with Lutris games""" stats = match_from_gogdb(create_missing=True) save_action_log("match_gog_games", stats) return stats
""" Compare GOG games to the Lutris library """ import os from celery import task from celery.utils.log import get_task_logger from django.conf import settings from providers.gog import load_games_from_gogdb, match_from_gogdb LOGGER = get_task_logger(__name__) @task def load_gog_games(): """Task to load GOG games from a GOGDB dump""" file_path = os.path.join(settings.GOG_CACHE_PATH, "gogdb.json") if not os.path.exists(file_path): LOGGER.error("No file present at %s", file_path) return None return load_games_from_gogdb(file_path) @task def match_gog_games(): """Match GOG games with Lutris games""" return match_from_gogdb(create_missing=True) Add stats logging for GOG tasks""" Compare GOG games to the Lutris library """ import os from celery import task from celery.utils.log import get_task_logger from django.conf import settings from providers.gog import load_games_from_gogdb, match_from_gogdb from common.models import save_action_log LOGGER = get_task_logger(__name__) @task def load_gog_games(): """Task to load GOG games from a GOGDB dump""" file_path = os.path.join(settings.GOG_CACHE_PATH, "gogdb.json") if not os.path.exists(file_path): LOGGER.error("No file present at %s", file_path) return None stats = load_games_from_gogdb(file_path) save_action_log("load_gog_games", stats) return stats @task def match_gog_games(): """Match GOG games with Lutris games""" stats = match_from_gogdb(create_missing=True) save_action_log("match_gog_games", stats) return stats
<commit_before>""" Compare GOG games to the Lutris library """ import os from celery import task from celery.utils.log import get_task_logger from django.conf import settings from providers.gog import load_games_from_gogdb, match_from_gogdb LOGGER = get_task_logger(__name__) @task def load_gog_games(): """Task to load GOG games from a GOGDB dump""" file_path = os.path.join(settings.GOG_CACHE_PATH, "gogdb.json") if not os.path.exists(file_path): LOGGER.error("No file present at %s", file_path) return None return load_games_from_gogdb(file_path) @task def match_gog_games(): """Match GOG games with Lutris games""" return match_from_gogdb(create_missing=True) <commit_msg>Add stats logging for GOG tasks<commit_after>""" Compare GOG games to the Lutris library """ import os from celery import task from celery.utils.log import get_task_logger from django.conf import settings from providers.gog import load_games_from_gogdb, match_from_gogdb from common.models import save_action_log LOGGER = get_task_logger(__name__) @task def load_gog_games(): """Task to load GOG games from a GOGDB dump""" file_path = os.path.join(settings.GOG_CACHE_PATH, "gogdb.json") if not os.path.exists(file_path): LOGGER.error("No file present at %s", file_path) return None stats = load_games_from_gogdb(file_path) save_action_log("load_gog_games", stats) return stats @task def match_gog_games(): """Match GOG games with Lutris games""" stats = match_from_gogdb(create_missing=True) save_action_log("match_gog_games", stats) return stats
65e76bb4d4d2731046d90ef874fdf17e324f1dc3
tests/test_localstorage.py
tests/test_localstorage.py
import pytest from roomcontrol.utils.localstorage import LocalStorage TEST_FILE = """ [kind1] a=1 b=2 [kind]] c=3 """ @pytest.fixture def ls(tmpdir): p = tmpdir.join('test_localstorage.in') p.write(TEST_FILE) obj = LocalStorage(str(p)) return obj def test_set_corresponds_to_get(ls): ls.set('kind2', 'd', '4') assert ls.get('kind2', 'd') == '4' def test_set_all_corresponds_to_get_all(ls): data = {'e': '5', 'f': '6'} ls.set_all('kind3', data) assert ls.get_all('kind3') == data
import pytest from roomcontrol.utils.localstorage import LocalStorage TEST_FILE = """ [kind1] a=1 b=2 [kind2] c=3 """ @pytest.fixture def ls(tmpdir): p = tmpdir.join('test_localstorage.in') p.write(TEST_FILE) obj = LocalStorage(str(p)) return obj def test_set_corresponds_to_get(ls): ls.set('kind2', 'd', '4') assert ls.get('kind2', 'd') == '4' def test_set_all_corresponds_to_get_all(ls): data = {'e': '5', 'f': '6'} ls.set_all('kind3', data) assert ls.get_all('kind3') == data
Fix typo in localstorage test
Fix typo in localstorage test
Python
mit
miguelfrde/roomcontrol_backend
import pytest from roomcontrol.utils.localstorage import LocalStorage TEST_FILE = """ [kind1] a=1 b=2 [kind]] c=3 """ @pytest.fixture def ls(tmpdir): p = tmpdir.join('test_localstorage.in') p.write(TEST_FILE) obj = LocalStorage(str(p)) return obj def test_set_corresponds_to_get(ls): ls.set('kind2', 'd', '4') assert ls.get('kind2', 'd') == '4' def test_set_all_corresponds_to_get_all(ls): data = {'e': '5', 'f': '6'} ls.set_all('kind3', data) assert ls.get_all('kind3') == data Fix typo in localstorage test
import pytest from roomcontrol.utils.localstorage import LocalStorage TEST_FILE = """ [kind1] a=1 b=2 [kind2] c=3 """ @pytest.fixture def ls(tmpdir): p = tmpdir.join('test_localstorage.in') p.write(TEST_FILE) obj = LocalStorage(str(p)) return obj def test_set_corresponds_to_get(ls): ls.set('kind2', 'd', '4') assert ls.get('kind2', 'd') == '4' def test_set_all_corresponds_to_get_all(ls): data = {'e': '5', 'f': '6'} ls.set_all('kind3', data) assert ls.get_all('kind3') == data
<commit_before>import pytest from roomcontrol.utils.localstorage import LocalStorage TEST_FILE = """ [kind1] a=1 b=2 [kind]] c=3 """ @pytest.fixture def ls(tmpdir): p = tmpdir.join('test_localstorage.in') p.write(TEST_FILE) obj = LocalStorage(str(p)) return obj def test_set_corresponds_to_get(ls): ls.set('kind2', 'd', '4') assert ls.get('kind2', 'd') == '4' def test_set_all_corresponds_to_get_all(ls): data = {'e': '5', 'f': '6'} ls.set_all('kind3', data) assert ls.get_all('kind3') == data <commit_msg>Fix typo in localstorage test<commit_after>
import pytest from roomcontrol.utils.localstorage import LocalStorage TEST_FILE = """ [kind1] a=1 b=2 [kind2] c=3 """ @pytest.fixture def ls(tmpdir): p = tmpdir.join('test_localstorage.in') p.write(TEST_FILE) obj = LocalStorage(str(p)) return obj def test_set_corresponds_to_get(ls): ls.set('kind2', 'd', '4') assert ls.get('kind2', 'd') == '4' def test_set_all_corresponds_to_get_all(ls): data = {'e': '5', 'f': '6'} ls.set_all('kind3', data) assert ls.get_all('kind3') == data
import pytest from roomcontrol.utils.localstorage import LocalStorage TEST_FILE = """ [kind1] a=1 b=2 [kind]] c=3 """ @pytest.fixture def ls(tmpdir): p = tmpdir.join('test_localstorage.in') p.write(TEST_FILE) obj = LocalStorage(str(p)) return obj def test_set_corresponds_to_get(ls): ls.set('kind2', 'd', '4') assert ls.get('kind2', 'd') == '4' def test_set_all_corresponds_to_get_all(ls): data = {'e': '5', 'f': '6'} ls.set_all('kind3', data) assert ls.get_all('kind3') == data Fix typo in localstorage testimport pytest from roomcontrol.utils.localstorage import LocalStorage TEST_FILE = """ [kind1] a=1 b=2 [kind2] c=3 """ @pytest.fixture def ls(tmpdir): p = tmpdir.join('test_localstorage.in') p.write(TEST_FILE) obj = LocalStorage(str(p)) return obj def test_set_corresponds_to_get(ls): ls.set('kind2', 'd', '4') assert ls.get('kind2', 'd') == '4' def test_set_all_corresponds_to_get_all(ls): data = {'e': '5', 'f': '6'} ls.set_all('kind3', data) assert ls.get_all('kind3') == data
<commit_before>import pytest from roomcontrol.utils.localstorage import LocalStorage TEST_FILE = """ [kind1] a=1 b=2 [kind]] c=3 """ @pytest.fixture def ls(tmpdir): p = tmpdir.join('test_localstorage.in') p.write(TEST_FILE) obj = LocalStorage(str(p)) return obj def test_set_corresponds_to_get(ls): ls.set('kind2', 'd', '4') assert ls.get('kind2', 'd') == '4' def test_set_all_corresponds_to_get_all(ls): data = {'e': '5', 'f': '6'} ls.set_all('kind3', data) assert ls.get_all('kind3') == data <commit_msg>Fix typo in localstorage test<commit_after>import pytest from roomcontrol.utils.localstorage import LocalStorage TEST_FILE = """ [kind1] a=1 b=2 [kind2] c=3 """ @pytest.fixture def ls(tmpdir): p = tmpdir.join('test_localstorage.in') p.write(TEST_FILE) obj = LocalStorage(str(p)) return obj def test_set_corresponds_to_get(ls): ls.set('kind2', 'd', '4') assert ls.get('kind2', 'd') == '4' def test_set_all_corresponds_to_get_all(ls): data = {'e': '5', 'f': '6'} ls.set_all('kind3', data) assert ls.get_all('kind3') == data
5ff2a8655caa66369733d7c151f36737217498f8
scoring_engine/db.py
scoring_engine/db.py
import bcrypt from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from scoring_engine.config import config isolation_level = "READ COMMITTED" if 'sqlite' in config.db_uri: # sqlite db does not support transaction based statements # so we have to manually set it to something else isolation_level = "READ UNCOMMITTED" engine = create_engine(config.db_uri, isolation_level=isolation_level) session = scoped_session(sessionmaker(bind=engine)) db_salt = bcrypt.gensalt()
import bcrypt from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from scoring_engine.config import config isolation_level = "READ COMMITTED" if 'sqlite' in config.db_uri: # sqlite db does not support transaction based statements # so we have to manually set it to something else isolation_level = "READ UNCOMMITTED" engine = create_engine(config.db_uri, isolation_level=isolation_level) session = scoped_session(sessionmaker(bind=engine)) db_salt = bcrypt.gensalt() # This is a monkey patch so that we # don't need to commit before every query # We got weird results in the web ui when we didn't # have this def query_monkeypatch(classname): session.commit() return session.orig_query(classname) session.orig_query = session.query session.query = query_monkeypatch
Add monkeypatch for session query problems
Add monkeypatch for session query problems
Python
mit
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
import bcrypt from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from scoring_engine.config import config isolation_level = "READ COMMITTED" if 'sqlite' in config.db_uri: # sqlite db does not support transaction based statements # so we have to manually set it to something else isolation_level = "READ UNCOMMITTED" engine = create_engine(config.db_uri, isolation_level=isolation_level) session = scoped_session(sessionmaker(bind=engine)) db_salt = bcrypt.gensalt() Add monkeypatch for session query problems
import bcrypt from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from scoring_engine.config import config isolation_level = "READ COMMITTED" if 'sqlite' in config.db_uri: # sqlite db does not support transaction based statements # so we have to manually set it to something else isolation_level = "READ UNCOMMITTED" engine = create_engine(config.db_uri, isolation_level=isolation_level) session = scoped_session(sessionmaker(bind=engine)) db_salt = bcrypt.gensalt() # This is a monkey patch so that we # don't need to commit before every query # We got weird results in the web ui when we didn't # have this def query_monkeypatch(classname): session.commit() return session.orig_query(classname) session.orig_query = session.query session.query = query_monkeypatch
<commit_before>import bcrypt from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from scoring_engine.config import config isolation_level = "READ COMMITTED" if 'sqlite' in config.db_uri: # sqlite db does not support transaction based statements # so we have to manually set it to something else isolation_level = "READ UNCOMMITTED" engine = create_engine(config.db_uri, isolation_level=isolation_level) session = scoped_session(sessionmaker(bind=engine)) db_salt = bcrypt.gensalt() <commit_msg>Add monkeypatch for session query problems<commit_after>
import bcrypt from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from scoring_engine.config import config isolation_level = "READ COMMITTED" if 'sqlite' in config.db_uri: # sqlite db does not support transaction based statements # so we have to manually set it to something else isolation_level = "READ UNCOMMITTED" engine = create_engine(config.db_uri, isolation_level=isolation_level) session = scoped_session(sessionmaker(bind=engine)) db_salt = bcrypt.gensalt() # This is a monkey patch so that we # don't need to commit before every query # We got weird results in the web ui when we didn't # have this def query_monkeypatch(classname): session.commit() return session.orig_query(classname) session.orig_query = session.query session.query = query_monkeypatch
import bcrypt from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from scoring_engine.config import config isolation_level = "READ COMMITTED" if 'sqlite' in config.db_uri: # sqlite db does not support transaction based statements # so we have to manually set it to something else isolation_level = "READ UNCOMMITTED" engine = create_engine(config.db_uri, isolation_level=isolation_level) session = scoped_session(sessionmaker(bind=engine)) db_salt = bcrypt.gensalt() Add monkeypatch for session query problemsimport bcrypt from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from scoring_engine.config import config isolation_level = "READ COMMITTED" if 'sqlite' in config.db_uri: # sqlite db does not support transaction based statements # so we have to manually set it to something else isolation_level = "READ UNCOMMITTED" engine = create_engine(config.db_uri, isolation_level=isolation_level) session = scoped_session(sessionmaker(bind=engine)) db_salt = bcrypt.gensalt() # This is a monkey patch so that we # don't need to commit before every query # We got weird results in the web ui when we didn't # have this def query_monkeypatch(classname): session.commit() return session.orig_query(classname) session.orig_query = session.query session.query = query_monkeypatch
<commit_before>import bcrypt from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from scoring_engine.config import config isolation_level = "READ COMMITTED" if 'sqlite' in config.db_uri: # sqlite db does not support transaction based statements # so we have to manually set it to something else isolation_level = "READ UNCOMMITTED" engine = create_engine(config.db_uri, isolation_level=isolation_level) session = scoped_session(sessionmaker(bind=engine)) db_salt = bcrypt.gensalt() <commit_msg>Add monkeypatch for session query problems<commit_after>import bcrypt from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from scoring_engine.config import config isolation_level = "READ COMMITTED" if 'sqlite' in config.db_uri: # sqlite db does not support transaction based statements # so we have to manually set it to something else isolation_level = "READ UNCOMMITTED" engine = create_engine(config.db_uri, isolation_level=isolation_level) session = scoped_session(sessionmaker(bind=engine)) db_salt = bcrypt.gensalt() # This is a monkey patch so that we # don't need to commit before every query # We got weird results in the web ui when we didn't # have this def query_monkeypatch(classname): session.commit() return session.orig_query(classname) session.orig_query = session.query session.query = query_monkeypatch
6c929f04559698a5988aaa3b03d42a03c091fc57
pyes/tests/pyestest.py
pyes/tests/pyestest.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500). """ import unittest from pyes import ES, file_to_attachment from pyes.exceptions import NotFoundException from pprint import pprint import os class ESTestCase(unittest.TestCase): def setUp(self): self.conn = ES('127.0.0.1:9200') try: self.conn.delete_index("test-index") except NotFoundException: pass def tearDown(self): try: self.conn.delete_index("test-index") except NotFoundException: pass def assertResultContains(self, result, expected): for (key, value) in expected.items(): self.assertEquals(value, result[key]) def dump(self, result): """ dump to stdout the result """ pprint(result) main = unittest.main
#!/usr/bin/python # -*- coding: utf-8 -*- """ Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500). """ import unittest from pyes import ES, file_to_attachment from pyes.exceptions import NotFoundException from pprint import pprint import os class ESTestCase(unittest.TestCase): def setUp(self): self.conn = ES('127.0.0.1:9200') try: self.conn.delete_index("test-index") except NotFoundException: pass def tearDown(self): try: self.conn.delete_index("test-index") except NotFoundException: pass def assertResultContains(self, result, expected): for (key, value) in expected.items(): self.assertEquals(value, result[key]) def checkRaises(self, excClass, callableObj, *args, **kwargs): """Assert that calling callableObj with *args and **kwargs raises an exception of type excClass, and return the exception object so that further tests on it can be performed. """ try: callableObj(*args, **kwargs) except excClass, e: return e else: raise self.failureException, \ "Expected exception %s not raised" % excClass def dump(self, result): """ dump to stdout the result """ pprint(result) main = unittest.main
Add a checkRaises method to check that an exception is raised, but also return it for futher tests.
Add a checkRaises method to check that an exception is raised, but also return it for futher tests.
Python
bsd-3-clause
mouadino/pyes,Fiedzia/pyes,haiwen/pyes,HackLinux/pyes,haiwen/pyes,Fiedzia/pyes,Fiedzia/pyes,aparo/pyes,aparo/pyes,haiwen/pyes,rookdev/pyes,HackLinux/pyes,jayzeng/pyes,HackLinux/pyes,mavarick/pyes,mavarick/pyes,rookdev/pyes,mavarick/pyes,jayzeng/pyes,mouadino/pyes,aparo/pyes,jayzeng/pyes
#!/usr/bin/python # -*- coding: utf-8 -*- """ Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500). """ import unittest from pyes import ES, file_to_attachment from pyes.exceptions import NotFoundException from pprint import pprint import os class ESTestCase(unittest.TestCase): def setUp(self): self.conn = ES('127.0.0.1:9200') try: self.conn.delete_index("test-index") except NotFoundException: pass def tearDown(self): try: self.conn.delete_index("test-index") except NotFoundException: pass def assertResultContains(self, result, expected): for (key, value) in expected.items(): self.assertEquals(value, result[key]) def dump(self, result): """ dump to stdout the result """ pprint(result) main = unittest.mainAdd a checkRaises method to check that an exception is raised, but also return it for futher tests.
#!/usr/bin/python # -*- coding: utf-8 -*- """ Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500). """ import unittest from pyes import ES, file_to_attachment from pyes.exceptions import NotFoundException from pprint import pprint import os class ESTestCase(unittest.TestCase): def setUp(self): self.conn = ES('127.0.0.1:9200') try: self.conn.delete_index("test-index") except NotFoundException: pass def tearDown(self): try: self.conn.delete_index("test-index") except NotFoundException: pass def assertResultContains(self, result, expected): for (key, value) in expected.items(): self.assertEquals(value, result[key]) def checkRaises(self, excClass, callableObj, *args, **kwargs): """Assert that calling callableObj with *args and **kwargs raises an exception of type excClass, and return the exception object so that further tests on it can be performed. """ try: callableObj(*args, **kwargs) except excClass, e: return e else: raise self.failureException, \ "Expected exception %s not raised" % excClass def dump(self, result): """ dump to stdout the result """ pprint(result) main = unittest.main
<commit_before>#!/usr/bin/python # -*- coding: utf-8 -*- """ Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500). """ import unittest from pyes import ES, file_to_attachment from pyes.exceptions import NotFoundException from pprint import pprint import os class ESTestCase(unittest.TestCase): def setUp(self): self.conn = ES('127.0.0.1:9200') try: self.conn.delete_index("test-index") except NotFoundException: pass def tearDown(self): try: self.conn.delete_index("test-index") except NotFoundException: pass def assertResultContains(self, result, expected): for (key, value) in expected.items(): self.assertEquals(value, result[key]) def dump(self, result): """ dump to stdout the result """ pprint(result) main = unittest.main<commit_msg>Add a checkRaises method to check that an exception is raised, but also return it for futher tests.<commit_after>
#!/usr/bin/python # -*- coding: utf-8 -*- """ Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500). """ import unittest from pyes import ES, file_to_attachment from pyes.exceptions import NotFoundException from pprint import pprint import os class ESTestCase(unittest.TestCase): def setUp(self): self.conn = ES('127.0.0.1:9200') try: self.conn.delete_index("test-index") except NotFoundException: pass def tearDown(self): try: self.conn.delete_index("test-index") except NotFoundException: pass def assertResultContains(self, result, expected): for (key, value) in expected.items(): self.assertEquals(value, result[key]) def checkRaises(self, excClass, callableObj, *args, **kwargs): """Assert that calling callableObj with *args and **kwargs raises an exception of type excClass, and return the exception object so that further tests on it can be performed. """ try: callableObj(*args, **kwargs) except excClass, e: return e else: raise self.failureException, \ "Expected exception %s not raised" % excClass def dump(self, result): """ dump to stdout the result """ pprint(result) main = unittest.main
#!/usr/bin/python # -*- coding: utf-8 -*- """ Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500). """ import unittest from pyes import ES, file_to_attachment from pyes.exceptions import NotFoundException from pprint import pprint import os class ESTestCase(unittest.TestCase): def setUp(self): self.conn = ES('127.0.0.1:9200') try: self.conn.delete_index("test-index") except NotFoundException: pass def tearDown(self): try: self.conn.delete_index("test-index") except NotFoundException: pass def assertResultContains(self, result, expected): for (key, value) in expected.items(): self.assertEquals(value, result[key]) def dump(self, result): """ dump to stdout the result """ pprint(result) main = unittest.mainAdd a checkRaises method to check that an exception is raised, but also return it for futher tests.#!/usr/bin/python # -*- coding: utf-8 -*- """ Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500). """ import unittest from pyes import ES, file_to_attachment from pyes.exceptions import NotFoundException from pprint import pprint import os class ESTestCase(unittest.TestCase): def setUp(self): self.conn = ES('127.0.0.1:9200') try: self.conn.delete_index("test-index") except NotFoundException: pass def tearDown(self): try: self.conn.delete_index("test-index") except NotFoundException: pass def assertResultContains(self, result, expected): for (key, value) in expected.items(): self.assertEquals(value, result[key]) def checkRaises(self, excClass, callableObj, *args, **kwargs): """Assert that calling callableObj with *args and **kwargs raises an exception of type excClass, and return the exception object so that further tests on it can be performed. """ try: callableObj(*args, **kwargs) except excClass, e: return e else: raise self.failureException, \ "Expected exception %s not raised" % excClass def dump(self, result): """ dump to stdout the result """ pprint(result) main = unittest.main
<commit_before>#!/usr/bin/python # -*- coding: utf-8 -*- """ Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500). """ import unittest from pyes import ES, file_to_attachment from pyes.exceptions import NotFoundException from pprint import pprint import os class ESTestCase(unittest.TestCase): def setUp(self): self.conn = ES('127.0.0.1:9200') try: self.conn.delete_index("test-index") except NotFoundException: pass def tearDown(self): try: self.conn.delete_index("test-index") except NotFoundException: pass def assertResultContains(self, result, expected): for (key, value) in expected.items(): self.assertEquals(value, result[key]) def dump(self, result): """ dump to stdout the result """ pprint(result) main = unittest.main<commit_msg>Add a checkRaises method to check that an exception is raised, but also return it for futher tests.<commit_after>#!/usr/bin/python # -*- coding: utf-8 -*- """ Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500). """ import unittest from pyes import ES, file_to_attachment from pyes.exceptions import NotFoundException from pprint import pprint import os class ESTestCase(unittest.TestCase): def setUp(self): self.conn = ES('127.0.0.1:9200') try: self.conn.delete_index("test-index") except NotFoundException: pass def tearDown(self): try: self.conn.delete_index("test-index") except NotFoundException: pass def assertResultContains(self, result, expected): for (key, value) in expected.items(): self.assertEquals(value, result[key]) def checkRaises(self, excClass, callableObj, *args, **kwargs): """Assert that calling callableObj with *args and **kwargs raises an exception of type excClass, and return the exception object so that further tests on it can be performed. """ try: callableObj(*args, **kwargs) except excClass, e: return e else: raise self.failureException, \ "Expected exception %s not raised" % excClass def dump(self, result): """ dump to stdout the result """ pprint(result) main = unittest.main
95f89ab590555bd4cc6c92b6b24883a27b323d2a
tests/test_methods.py
tests/test_methods.py
from apiritif import http from unittest import TestCase class TestRequests(TestCase): def test_get(self): http.get('http://blazedemo.com/?tag=get') def test_post(self): http.post('http://blazedemo.com/?tag=post') def test_put(self): http.put('http://blazedemo.com/?tag=put') def test_patch(self): http.patch('http://blazedemo.com/?tag=patch') def test_head(self): http.head('http://blazedemo.com/?tag=head') def test_delete(self): http.delete('http://blazedemo.com/?tag=delete') def test_options(self): http.options('http://blazedemo.com/echo.php?echo=options') def test_connect(self): target = http.target('http://blazedemo.com/', auto_assert_ok=False) target.connect('/echo.php?echo=connect')
from apiritif import http from unittest import TestCase class TestHTTPMethods(TestCase): def test_get(self): http.get('http://blazedemo.com/?tag=get') def test_post(self): http.post('http://blazedemo.com/?tag=post') def test_put(self): http.put('http://blazedemo.com/?tag=put') def test_patch(self): http.patch('http://blazedemo.com/?tag=patch') def test_head(self): http.head('http://blazedemo.com/?tag=head') def test_delete(self): http.delete('http://blazedemo.com/?tag=delete') def test_options(self): http.options('http://blazedemo.com/echo.php?echo=options') class TestTargetMethods(TestCase): def setUp(self): self.target = http.target('http://blazedemo.com', auto_assert_ok=False) def test_get(self): self.target.get('/echo.php?echo=get').assert_ok() def test_post(self): self.target.post('/echo.php?echo=post').assert_ok() def test_put(self): self.target.put('/echo.php?echo=put').assert_ok() def test_patch(self): self.target.patch('/echo.php?echo=patch').assert_ok() def test_delete(self): self.target.delete('/echo.php?echo=delete').assert_ok() def test_head(self): self.target.head('/echo.php?echo=head').assert_ok() def test_options(self): self.target.options('/echo.php?echo=options').assert_ok() def test_connect(self): self.target.connect('/echo.php?echo=connect')
Add a lot more tests
Add a lot more tests
Python
apache-2.0
Blazemeter/apiritif,Blazemeter/apiritif
from apiritif import http from unittest import TestCase class TestRequests(TestCase): def test_get(self): http.get('http://blazedemo.com/?tag=get') def test_post(self): http.post('http://blazedemo.com/?tag=post') def test_put(self): http.put('http://blazedemo.com/?tag=put') def test_patch(self): http.patch('http://blazedemo.com/?tag=patch') def test_head(self): http.head('http://blazedemo.com/?tag=head') def test_delete(self): http.delete('http://blazedemo.com/?tag=delete') def test_options(self): http.options('http://blazedemo.com/echo.php?echo=options') def test_connect(self): target = http.target('http://blazedemo.com/', auto_assert_ok=False) target.connect('/echo.php?echo=connect') Add a lot more tests
from apiritif import http from unittest import TestCase class TestHTTPMethods(TestCase): def test_get(self): http.get('http://blazedemo.com/?tag=get') def test_post(self): http.post('http://blazedemo.com/?tag=post') def test_put(self): http.put('http://blazedemo.com/?tag=put') def test_patch(self): http.patch('http://blazedemo.com/?tag=patch') def test_head(self): http.head('http://blazedemo.com/?tag=head') def test_delete(self): http.delete('http://blazedemo.com/?tag=delete') def test_options(self): http.options('http://blazedemo.com/echo.php?echo=options') class TestTargetMethods(TestCase): def setUp(self): self.target = http.target('http://blazedemo.com', auto_assert_ok=False) def test_get(self): self.target.get('/echo.php?echo=get').assert_ok() def test_post(self): self.target.post('/echo.php?echo=post').assert_ok() def test_put(self): self.target.put('/echo.php?echo=put').assert_ok() def test_patch(self): self.target.patch('/echo.php?echo=patch').assert_ok() def test_delete(self): self.target.delete('/echo.php?echo=delete').assert_ok() def test_head(self): self.target.head('/echo.php?echo=head').assert_ok() def test_options(self): self.target.options('/echo.php?echo=options').assert_ok() def test_connect(self): self.target.connect('/echo.php?echo=connect')
<commit_before>from apiritif import http from unittest import TestCase class TestRequests(TestCase): def test_get(self): http.get('http://blazedemo.com/?tag=get') def test_post(self): http.post('http://blazedemo.com/?tag=post') def test_put(self): http.put('http://blazedemo.com/?tag=put') def test_patch(self): http.patch('http://blazedemo.com/?tag=patch') def test_head(self): http.head('http://blazedemo.com/?tag=head') def test_delete(self): http.delete('http://blazedemo.com/?tag=delete') def test_options(self): http.options('http://blazedemo.com/echo.php?echo=options') def test_connect(self): target = http.target('http://blazedemo.com/', auto_assert_ok=False) target.connect('/echo.php?echo=connect') <commit_msg>Add a lot more tests<commit_after>
from apiritif import http from unittest import TestCase class TestHTTPMethods(TestCase): def test_get(self): http.get('http://blazedemo.com/?tag=get') def test_post(self): http.post('http://blazedemo.com/?tag=post') def test_put(self): http.put('http://blazedemo.com/?tag=put') def test_patch(self): http.patch('http://blazedemo.com/?tag=patch') def test_head(self): http.head('http://blazedemo.com/?tag=head') def test_delete(self): http.delete('http://blazedemo.com/?tag=delete') def test_options(self): http.options('http://blazedemo.com/echo.php?echo=options') class TestTargetMethods(TestCase): def setUp(self): self.target = http.target('http://blazedemo.com', auto_assert_ok=False) def test_get(self): self.target.get('/echo.php?echo=get').assert_ok() def test_post(self): self.target.post('/echo.php?echo=post').assert_ok() def test_put(self): self.target.put('/echo.php?echo=put').assert_ok() def test_patch(self): self.target.patch('/echo.php?echo=patch').assert_ok() def test_delete(self): self.target.delete('/echo.php?echo=delete').assert_ok() def test_head(self): self.target.head('/echo.php?echo=head').assert_ok() def test_options(self): self.target.options('/echo.php?echo=options').assert_ok() def test_connect(self): self.target.connect('/echo.php?echo=connect')
from apiritif import http from unittest import TestCase class TestRequests(TestCase): def test_get(self): http.get('http://blazedemo.com/?tag=get') def test_post(self): http.post('http://blazedemo.com/?tag=post') def test_put(self): http.put('http://blazedemo.com/?tag=put') def test_patch(self): http.patch('http://blazedemo.com/?tag=patch') def test_head(self): http.head('http://blazedemo.com/?tag=head') def test_delete(self): http.delete('http://blazedemo.com/?tag=delete') def test_options(self): http.options('http://blazedemo.com/echo.php?echo=options') def test_connect(self): target = http.target('http://blazedemo.com/', auto_assert_ok=False) target.connect('/echo.php?echo=connect') Add a lot more testsfrom apiritif import http from unittest import TestCase class TestHTTPMethods(TestCase): def test_get(self): http.get('http://blazedemo.com/?tag=get') def test_post(self): http.post('http://blazedemo.com/?tag=post') def test_put(self): http.put('http://blazedemo.com/?tag=put') def test_patch(self): http.patch('http://blazedemo.com/?tag=patch') def test_head(self): http.head('http://blazedemo.com/?tag=head') def test_delete(self): http.delete('http://blazedemo.com/?tag=delete') def test_options(self): http.options('http://blazedemo.com/echo.php?echo=options') class TestTargetMethods(TestCase): def setUp(self): self.target = http.target('http://blazedemo.com', auto_assert_ok=False) def test_get(self): self.target.get('/echo.php?echo=get').assert_ok() def test_post(self): self.target.post('/echo.php?echo=post').assert_ok() def test_put(self): self.target.put('/echo.php?echo=put').assert_ok() def test_patch(self): self.target.patch('/echo.php?echo=patch').assert_ok() def test_delete(self): self.target.delete('/echo.php?echo=delete').assert_ok() def test_head(self): self.target.head('/echo.php?echo=head').assert_ok() def test_options(self): self.target.options('/echo.php?echo=options').assert_ok() def test_connect(self): self.target.connect('/echo.php?echo=connect')
<commit_before>from apiritif import http from unittest import TestCase class TestRequests(TestCase): def test_get(self): http.get('http://blazedemo.com/?tag=get') def test_post(self): http.post('http://blazedemo.com/?tag=post') def test_put(self): http.put('http://blazedemo.com/?tag=put') def test_patch(self): http.patch('http://blazedemo.com/?tag=patch') def test_head(self): http.head('http://blazedemo.com/?tag=head') def test_delete(self): http.delete('http://blazedemo.com/?tag=delete') def test_options(self): http.options('http://blazedemo.com/echo.php?echo=options') def test_connect(self): target = http.target('http://blazedemo.com/', auto_assert_ok=False) target.connect('/echo.php?echo=connect') <commit_msg>Add a lot more tests<commit_after>from apiritif import http from unittest import TestCase class TestHTTPMethods(TestCase): def test_get(self): http.get('http://blazedemo.com/?tag=get') def test_post(self): http.post('http://blazedemo.com/?tag=post') def test_put(self): http.put('http://blazedemo.com/?tag=put') def test_patch(self): http.patch('http://blazedemo.com/?tag=patch') def test_head(self): http.head('http://blazedemo.com/?tag=head') def test_delete(self): http.delete('http://blazedemo.com/?tag=delete') def test_options(self): http.options('http://blazedemo.com/echo.php?echo=options') class TestTargetMethods(TestCase): def setUp(self): self.target = http.target('http://blazedemo.com', auto_assert_ok=False) def test_get(self): self.target.get('/echo.php?echo=get').assert_ok() def test_post(self): self.target.post('/echo.php?echo=post').assert_ok() def test_put(self): self.target.put('/echo.php?echo=put').assert_ok() def test_patch(self): self.target.patch('/echo.php?echo=patch').assert_ok() def test_delete(self): self.target.delete('/echo.php?echo=delete').assert_ok() def test_head(self): self.target.head('/echo.php?echo=head').assert_ok() def test_options(self): self.target.options('/echo.php?echo=options').assert_ok() def test_connect(self): self.target.connect('/echo.php?echo=connect')
301af589415dfa0f074f19a3b234a4613f3e5bad
tools/misc/bin2hex.py
tools/misc/bin2hex.py
#!/usr/bin/env python # # Copyright 2016 Jeff Bush # # 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 sys import binascii with open(sys.argv[1], 'rb') as f: while True: word = f.read(4) if not word: break print(binascii.hexlify(word))
#!/usr/bin/env python # # Copyright 2016 Jeff Bush # # 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 sys import binascii with open(sys.argv[1], 'rb') as f: while True: word = f.read(4) if not word: break print(binascii.hexlify(word).decode())
Fix broken bootloader build on systems that default to python3
Fix broken bootloader build on systems that default to python3 binascii.hexlify was returning a byte array, which python would print with a leading b'. Use decode() method to convert to string. [ci skip]
Python
apache-2.0
jbush001/NyuziProcessor,jbush001/NyuziProcessor,jbush001/NyuziProcessor,jbush001/NyuziProcessor,jbush001/NyuziProcessor,jbush001/NyuziProcessor
#!/usr/bin/env python # # Copyright 2016 Jeff Bush # # 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 sys import binascii with open(sys.argv[1], 'rb') as f: while True: word = f.read(4) if not word: break print(binascii.hexlify(word)) Fix broken bootloader build on systems that default to python3 binascii.hexlify was returning a byte array, which python would print with a leading b'. Use decode() method to convert to string. [ci skip]
#!/usr/bin/env python # # Copyright 2016 Jeff Bush # # 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 sys import binascii with open(sys.argv[1], 'rb') as f: while True: word = f.read(4) if not word: break print(binascii.hexlify(word).decode())
<commit_before>#!/usr/bin/env python # # Copyright 2016 Jeff Bush # # 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 sys import binascii with open(sys.argv[1], 'rb') as f: while True: word = f.read(4) if not word: break print(binascii.hexlify(word)) <commit_msg>Fix broken bootloader build on systems that default to python3 binascii.hexlify was returning a byte array, which python would print with a leading b'. Use decode() method to convert to string. [ci skip]<commit_after>
#!/usr/bin/env python # # Copyright 2016 Jeff Bush # # 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 sys import binascii with open(sys.argv[1], 'rb') as f: while True: word = f.read(4) if not word: break print(binascii.hexlify(word).decode())
#!/usr/bin/env python # # Copyright 2016 Jeff Bush # # 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 sys import binascii with open(sys.argv[1], 'rb') as f: while True: word = f.read(4) if not word: break print(binascii.hexlify(word)) Fix broken bootloader build on systems that default to python3 binascii.hexlify was returning a byte array, which python would print with a leading b'. Use decode() method to convert to string. [ci skip]#!/usr/bin/env python # # Copyright 2016 Jeff Bush # # 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 sys import binascii with open(sys.argv[1], 'rb') as f: while True: word = f.read(4) if not word: break print(binascii.hexlify(word).decode())
<commit_before>#!/usr/bin/env python # # Copyright 2016 Jeff Bush # # 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 sys import binascii with open(sys.argv[1], 'rb') as f: while True: word = f.read(4) if not word: break print(binascii.hexlify(word)) <commit_msg>Fix broken bootloader build on systems that default to python3 binascii.hexlify was returning a byte array, which python would print with a leading b'. Use decode() method to convert to string. [ci skip]<commit_after>#!/usr/bin/env python # # Copyright 2016 Jeff Bush # # 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 sys import binascii with open(sys.argv[1], 'rb') as f: while True: word = f.read(4) if not word: break print(binascii.hexlify(word).decode())
5c8741b8c4fe7ce447fadeeb1707144903728836
tests/builtins/test_sum.py
tests/builtins/test_sum.py
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class SumTests(TranspileTestCase): pass class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["sum"] not_implemented = [ 'test_bytearray', 'test_bytes', 'test_class', 'test_complex', 'test_dict', 'test_frozenset', 'test_set', 'test_str', ]
from unittest import expectedFailure from .. utils import TranspileTestCase, BuiltinFunctionTestCase class SumTests(TranspileTestCase): pass class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["sum"] not_implemented = [ 'test_bytearray', 'test_bytes', 'test_class', 'test_complex', 'test_dict', 'test_frozenset', 'test_set', 'test_str', ] def test_sum_list(self): self.assertCodeExecution(""" print(sum([1, 2, 3, 4, 5, 6, 7])) """) def test_sum_tuple(self): self.assertCodeExecution(""" print(sum((1, 2, 3, 4, 5, 6, 7))) """) def test_sum_iterator(self): self.assertCodeExecution(""" i = iter([1, 2]) print(sum(i)) print(sum(i)) """) @expectedFailure # + not defined on float/float yet. def test_sum_mix_floats_and_ints(self): self.assertCodeExecution(""" print(sum([1, 1.414, 2, 3.14159])) """)
Add extra testcases for `sum`.
Add extra testcases for `sum`.
Python
bsd-3-clause
ASP1234/voc,Felix5721/voc,cflee/voc,cflee/voc,freakboy3742/voc,pombredanne/voc,gEt-rIgHt-jR/voc,pombredanne/voc,gEt-rIgHt-jR/voc,ASP1234/voc,Felix5721/voc,freakboy3742/voc
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class SumTests(TranspileTestCase): pass class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["sum"] not_implemented = [ 'test_bytearray', 'test_bytes', 'test_class', 'test_complex', 'test_dict', 'test_frozenset', 'test_set', 'test_str', ] Add extra testcases for `sum`.
from unittest import expectedFailure from .. utils import TranspileTestCase, BuiltinFunctionTestCase class SumTests(TranspileTestCase): pass class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["sum"] not_implemented = [ 'test_bytearray', 'test_bytes', 'test_class', 'test_complex', 'test_dict', 'test_frozenset', 'test_set', 'test_str', ] def test_sum_list(self): self.assertCodeExecution(""" print(sum([1, 2, 3, 4, 5, 6, 7])) """) def test_sum_tuple(self): self.assertCodeExecution(""" print(sum((1, 2, 3, 4, 5, 6, 7))) """) def test_sum_iterator(self): self.assertCodeExecution(""" i = iter([1, 2]) print(sum(i)) print(sum(i)) """) @expectedFailure # + not defined on float/float yet. def test_sum_mix_floats_and_ints(self): self.assertCodeExecution(""" print(sum([1, 1.414, 2, 3.14159])) """)
<commit_before>from .. utils import TranspileTestCase, BuiltinFunctionTestCase class SumTests(TranspileTestCase): pass class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["sum"] not_implemented = [ 'test_bytearray', 'test_bytes', 'test_class', 'test_complex', 'test_dict', 'test_frozenset', 'test_set', 'test_str', ] <commit_msg>Add extra testcases for `sum`.<commit_after>
from unittest import expectedFailure from .. utils import TranspileTestCase, BuiltinFunctionTestCase class SumTests(TranspileTestCase): pass class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["sum"] not_implemented = [ 'test_bytearray', 'test_bytes', 'test_class', 'test_complex', 'test_dict', 'test_frozenset', 'test_set', 'test_str', ] def test_sum_list(self): self.assertCodeExecution(""" print(sum([1, 2, 3, 4, 5, 6, 7])) """) def test_sum_tuple(self): self.assertCodeExecution(""" print(sum((1, 2, 3, 4, 5, 6, 7))) """) def test_sum_iterator(self): self.assertCodeExecution(""" i = iter([1, 2]) print(sum(i)) print(sum(i)) """) @expectedFailure # + not defined on float/float yet. def test_sum_mix_floats_and_ints(self): self.assertCodeExecution(""" print(sum([1, 1.414, 2, 3.14159])) """)
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class SumTests(TranspileTestCase): pass class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["sum"] not_implemented = [ 'test_bytearray', 'test_bytes', 'test_class', 'test_complex', 'test_dict', 'test_frozenset', 'test_set', 'test_str', ] Add extra testcases for `sum`.from unittest import expectedFailure from .. utils import TranspileTestCase, BuiltinFunctionTestCase class SumTests(TranspileTestCase): pass class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["sum"] not_implemented = [ 'test_bytearray', 'test_bytes', 'test_class', 'test_complex', 'test_dict', 'test_frozenset', 'test_set', 'test_str', ] def test_sum_list(self): self.assertCodeExecution(""" print(sum([1, 2, 3, 4, 5, 6, 7])) """) def test_sum_tuple(self): self.assertCodeExecution(""" print(sum((1, 2, 3, 4, 5, 6, 7))) """) def test_sum_iterator(self): self.assertCodeExecution(""" i = iter([1, 2]) print(sum(i)) print(sum(i)) """) @expectedFailure # + not defined on float/float yet. def test_sum_mix_floats_and_ints(self): self.assertCodeExecution(""" print(sum([1, 1.414, 2, 3.14159])) """)
<commit_before>from .. utils import TranspileTestCase, BuiltinFunctionTestCase class SumTests(TranspileTestCase): pass class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["sum"] not_implemented = [ 'test_bytearray', 'test_bytes', 'test_class', 'test_complex', 'test_dict', 'test_frozenset', 'test_set', 'test_str', ] <commit_msg>Add extra testcases for `sum`.<commit_after>from unittest import expectedFailure from .. utils import TranspileTestCase, BuiltinFunctionTestCase class SumTests(TranspileTestCase): pass class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["sum"] not_implemented = [ 'test_bytearray', 'test_bytes', 'test_class', 'test_complex', 'test_dict', 'test_frozenset', 'test_set', 'test_str', ] def test_sum_list(self): self.assertCodeExecution(""" print(sum([1, 2, 3, 4, 5, 6, 7])) """) def test_sum_tuple(self): self.assertCodeExecution(""" print(sum((1, 2, 3, 4, 5, 6, 7))) """) def test_sum_iterator(self): self.assertCodeExecution(""" i = iter([1, 2]) print(sum(i)) print(sum(i)) """) @expectedFailure # + not defined on float/float yet. def test_sum_mix_floats_and_ints(self): self.assertCodeExecution(""" print(sum([1, 1.414, 2, 3.14159])) """)
0d5e5bb3eec9a4603b7e0899c296042e09c80911
gatekeeper/app.py
gatekeeper/app.py
#!/usr/bin/env python3 import bot as chat_bot from intercom import Intercom import logging from facerecognition import FaceRecognition import nodered import subprocess from sys import platform icom = Intercom() facerec = FaceRecognition() doorBellServer = nodered.NodeRedDoorbellServerThread(icom) doorBellServer.start() if platform == "linux" or platform == "linux2": # linux subprocess.call(["pulseaudio", "-D"]) def onBellPressed(): if chat_bot.chat_id is None: logging.warning('Bell is pressed but we have no user in the chat') chat_bot.verify_image(chat_bot.updater, icom.takePicture()) def onTakeSnap(): pic = icom.takePicture() chat_bot.uploadSnap(chat_bot.updater, pic) icom.registerOnBellPressedCallback(onBellPressed) chat_bot.registerOnSnapButtonCallback(onTakeSnap) chat_bot.run_bot()
#!/usr/bin/env python3 import bot as chat_bot from intercom import Intercom import logging from facerecognition import FaceRecognition import nodered import subprocess from sys import platform icom = Intercom() facerec = FaceRecognition() doorBellServer = nodered.NodeRedDoorbellServerThread(icom) doorBellServer.start() if platform == "linux" or platform == "linux2": # linux print("Starting PulseAudio") subprocess.call(["pulseaudio", "-D"]) def onBellPressed(): if chat_bot.chat_id is None: logging.warning('Bell is pressed but we have no user in the chat') chat_bot.verify_image(chat_bot.updater, icom.takePicture()) def onTakeSnap(): pic = icom.takePicture() chat_bot.uploadSnap(chat_bot.updater, pic) icom.registerOnBellPressedCallback(onBellPressed) chat_bot.registerOnSnapButtonCallback(onTakeSnap) chat_bot.run_bot()
Add a print when running pulseaudio
Add a print when running pulseaudio
Python
mit
git-commit/iot-gatekeeper,git-commit/iot-gatekeeper
#!/usr/bin/env python3 import bot as chat_bot from intercom import Intercom import logging from facerecognition import FaceRecognition import nodered import subprocess from sys import platform icom = Intercom() facerec = FaceRecognition() doorBellServer = nodered.NodeRedDoorbellServerThread(icom) doorBellServer.start() if platform == "linux" or platform == "linux2": # linux subprocess.call(["pulseaudio", "-D"]) def onBellPressed(): if chat_bot.chat_id is None: logging.warning('Bell is pressed but we have no user in the chat') chat_bot.verify_image(chat_bot.updater, icom.takePicture()) def onTakeSnap(): pic = icom.takePicture() chat_bot.uploadSnap(chat_bot.updater, pic) icom.registerOnBellPressedCallback(onBellPressed) chat_bot.registerOnSnapButtonCallback(onTakeSnap) chat_bot.run_bot() Add a print when running pulseaudio
#!/usr/bin/env python3 import bot as chat_bot from intercom import Intercom import logging from facerecognition import FaceRecognition import nodered import subprocess from sys import platform icom = Intercom() facerec = FaceRecognition() doorBellServer = nodered.NodeRedDoorbellServerThread(icom) doorBellServer.start() if platform == "linux" or platform == "linux2": # linux print("Starting PulseAudio") subprocess.call(["pulseaudio", "-D"]) def onBellPressed(): if chat_bot.chat_id is None: logging.warning('Bell is pressed but we have no user in the chat') chat_bot.verify_image(chat_bot.updater, icom.takePicture()) def onTakeSnap(): pic = icom.takePicture() chat_bot.uploadSnap(chat_bot.updater, pic) icom.registerOnBellPressedCallback(onBellPressed) chat_bot.registerOnSnapButtonCallback(onTakeSnap) chat_bot.run_bot()
<commit_before>#!/usr/bin/env python3 import bot as chat_bot from intercom import Intercom import logging from facerecognition import FaceRecognition import nodered import subprocess from sys import platform icom = Intercom() facerec = FaceRecognition() doorBellServer = nodered.NodeRedDoorbellServerThread(icom) doorBellServer.start() if platform == "linux" or platform == "linux2": # linux subprocess.call(["pulseaudio", "-D"]) def onBellPressed(): if chat_bot.chat_id is None: logging.warning('Bell is pressed but we have no user in the chat') chat_bot.verify_image(chat_bot.updater, icom.takePicture()) def onTakeSnap(): pic = icom.takePicture() chat_bot.uploadSnap(chat_bot.updater, pic) icom.registerOnBellPressedCallback(onBellPressed) chat_bot.registerOnSnapButtonCallback(onTakeSnap) chat_bot.run_bot() <commit_msg>Add a print when running pulseaudio<commit_after>
#!/usr/bin/env python3 import bot as chat_bot from intercom import Intercom import logging from facerecognition import FaceRecognition import nodered import subprocess from sys import platform icom = Intercom() facerec = FaceRecognition() doorBellServer = nodered.NodeRedDoorbellServerThread(icom) doorBellServer.start() if platform == "linux" or platform == "linux2": # linux print("Starting PulseAudio") subprocess.call(["pulseaudio", "-D"]) def onBellPressed(): if chat_bot.chat_id is None: logging.warning('Bell is pressed but we have no user in the chat') chat_bot.verify_image(chat_bot.updater, icom.takePicture()) def onTakeSnap(): pic = icom.takePicture() chat_bot.uploadSnap(chat_bot.updater, pic) icom.registerOnBellPressedCallback(onBellPressed) chat_bot.registerOnSnapButtonCallback(onTakeSnap) chat_bot.run_bot()
#!/usr/bin/env python3 import bot as chat_bot from intercom import Intercom import logging from facerecognition import FaceRecognition import nodered import subprocess from sys import platform icom = Intercom() facerec = FaceRecognition() doorBellServer = nodered.NodeRedDoorbellServerThread(icom) doorBellServer.start() if platform == "linux" or platform == "linux2": # linux subprocess.call(["pulseaudio", "-D"]) def onBellPressed(): if chat_bot.chat_id is None: logging.warning('Bell is pressed but we have no user in the chat') chat_bot.verify_image(chat_bot.updater, icom.takePicture()) def onTakeSnap(): pic = icom.takePicture() chat_bot.uploadSnap(chat_bot.updater, pic) icom.registerOnBellPressedCallback(onBellPressed) chat_bot.registerOnSnapButtonCallback(onTakeSnap) chat_bot.run_bot() Add a print when running pulseaudio#!/usr/bin/env python3 import bot as chat_bot from intercom import Intercom import logging from facerecognition import FaceRecognition import nodered import subprocess from sys import platform icom = Intercom() facerec = FaceRecognition() doorBellServer = nodered.NodeRedDoorbellServerThread(icom) doorBellServer.start() if platform == "linux" or platform == "linux2": # linux print("Starting PulseAudio") subprocess.call(["pulseaudio", "-D"]) def onBellPressed(): if chat_bot.chat_id is None: logging.warning('Bell is pressed but we have no user in the chat') chat_bot.verify_image(chat_bot.updater, icom.takePicture()) def onTakeSnap(): pic = icom.takePicture() chat_bot.uploadSnap(chat_bot.updater, pic) icom.registerOnBellPressedCallback(onBellPressed) chat_bot.registerOnSnapButtonCallback(onTakeSnap) chat_bot.run_bot()
<commit_before>#!/usr/bin/env python3 import bot as chat_bot from intercom import Intercom import logging from facerecognition import FaceRecognition import nodered import subprocess from sys import platform icom = Intercom() facerec = FaceRecognition() doorBellServer = nodered.NodeRedDoorbellServerThread(icom) doorBellServer.start() if platform == "linux" or platform == "linux2": # linux subprocess.call(["pulseaudio", "-D"]) def onBellPressed(): if chat_bot.chat_id is None: logging.warning('Bell is pressed but we have no user in the chat') chat_bot.verify_image(chat_bot.updater, icom.takePicture()) def onTakeSnap(): pic = icom.takePicture() chat_bot.uploadSnap(chat_bot.updater, pic) icom.registerOnBellPressedCallback(onBellPressed) chat_bot.registerOnSnapButtonCallback(onTakeSnap) chat_bot.run_bot() <commit_msg>Add a print when running pulseaudio<commit_after>#!/usr/bin/env python3 import bot as chat_bot from intercom import Intercom import logging from facerecognition import FaceRecognition import nodered import subprocess from sys import platform icom = Intercom() facerec = FaceRecognition() doorBellServer = nodered.NodeRedDoorbellServerThread(icom) doorBellServer.start() if platform == "linux" or platform == "linux2": # linux print("Starting PulseAudio") subprocess.call(["pulseaudio", "-D"]) def onBellPressed(): if chat_bot.chat_id is None: logging.warning('Bell is pressed but we have no user in the chat') chat_bot.verify_image(chat_bot.updater, icom.takePicture()) def onTakeSnap(): pic = icom.takePicture() chat_bot.uploadSnap(chat_bot.updater, pic) icom.registerOnBellPressedCallback(onBellPressed) chat_bot.registerOnSnapButtonCallback(onTakeSnap) chat_bot.run_bot()
758227a735c914ace87e6648e95cecc445fe4e68
lab/provider/files.py
lab/provider/files.py
import os import io import errno from xdg import BaseDirectory from .common import ProviderError class Record(object): def __init__(self, *path): data_dir = BaseDirectory.save_data_path('lab', 'v1', *path[:-1]) self.path = os.path.join(data_dir, path[-1]) try: with io.open(self.path, 'r') as fp: self.data = fp.read() except IOError as e: if e.errno == errno.ENOENT: self.data = None else: raise ProviderError(e) def push(self, data): with io.open(self.path, 'w', encoding='utf-8') as fp: return fp.write(data) class FileProvider(object): name = 'files' def __init__(self, config): pass def get(self, *path): return Record(*path)
import os import io import errno from xdg import BaseDirectory from .common import ProviderError class Record(object): def __init__(self, *path): data_dir = BaseDirectory.save_data_path('lab', 'v1', *path[:-1]) self.path = os.path.join(data_dir, path[-1]) try: with io.open(self.path, 'r') as fp: self.data = fp.read() except IOError as e: if e.errno == errno.ENOENT: self.data = None else: raise ProviderError(e) def push(self, data): with io.open(self.path, 'w', encoding='utf-8') as fp: return fp.write(data) class FileProvider(object): name = 'files' def __init__(self, config): # We don't support and configuration, so intentionally empty pass def get(self, *path): return Record(*path)
Add comment on FileProvider init
Add comment on FileProvider init I swear I added this prior to merging, somehow slipped through. Sorry
Python
mpl-2.0
sangoma/pytestlab
import os import io import errno from xdg import BaseDirectory from .common import ProviderError class Record(object): def __init__(self, *path): data_dir = BaseDirectory.save_data_path('lab', 'v1', *path[:-1]) self.path = os.path.join(data_dir, path[-1]) try: with io.open(self.path, 'r') as fp: self.data = fp.read() except IOError as e: if e.errno == errno.ENOENT: self.data = None else: raise ProviderError(e) def push(self, data): with io.open(self.path, 'w', encoding='utf-8') as fp: return fp.write(data) class FileProvider(object): name = 'files' def __init__(self, config): pass def get(self, *path): return Record(*path) Add comment on FileProvider init I swear I added this prior to merging, somehow slipped through. Sorry
import os import io import errno from xdg import BaseDirectory from .common import ProviderError class Record(object): def __init__(self, *path): data_dir = BaseDirectory.save_data_path('lab', 'v1', *path[:-1]) self.path = os.path.join(data_dir, path[-1]) try: with io.open(self.path, 'r') as fp: self.data = fp.read() except IOError as e: if e.errno == errno.ENOENT: self.data = None else: raise ProviderError(e) def push(self, data): with io.open(self.path, 'w', encoding='utf-8') as fp: return fp.write(data) class FileProvider(object): name = 'files' def __init__(self, config): # We don't support and configuration, so intentionally empty pass def get(self, *path): return Record(*path)
<commit_before>import os import io import errno from xdg import BaseDirectory from .common import ProviderError class Record(object): def __init__(self, *path): data_dir = BaseDirectory.save_data_path('lab', 'v1', *path[:-1]) self.path = os.path.join(data_dir, path[-1]) try: with io.open(self.path, 'r') as fp: self.data = fp.read() except IOError as e: if e.errno == errno.ENOENT: self.data = None else: raise ProviderError(e) def push(self, data): with io.open(self.path, 'w', encoding='utf-8') as fp: return fp.write(data) class FileProvider(object): name = 'files' def __init__(self, config): pass def get(self, *path): return Record(*path) <commit_msg>Add comment on FileProvider init I swear I added this prior to merging, somehow slipped through. Sorry<commit_after>
import os import io import errno from xdg import BaseDirectory from .common import ProviderError class Record(object): def __init__(self, *path): data_dir = BaseDirectory.save_data_path('lab', 'v1', *path[:-1]) self.path = os.path.join(data_dir, path[-1]) try: with io.open(self.path, 'r') as fp: self.data = fp.read() except IOError as e: if e.errno == errno.ENOENT: self.data = None else: raise ProviderError(e) def push(self, data): with io.open(self.path, 'w', encoding='utf-8') as fp: return fp.write(data) class FileProvider(object): name = 'files' def __init__(self, config): # We don't support and configuration, so intentionally empty pass def get(self, *path): return Record(*path)
import os import io import errno from xdg import BaseDirectory from .common import ProviderError class Record(object): def __init__(self, *path): data_dir = BaseDirectory.save_data_path('lab', 'v1', *path[:-1]) self.path = os.path.join(data_dir, path[-1]) try: with io.open(self.path, 'r') as fp: self.data = fp.read() except IOError as e: if e.errno == errno.ENOENT: self.data = None else: raise ProviderError(e) def push(self, data): with io.open(self.path, 'w', encoding='utf-8') as fp: return fp.write(data) class FileProvider(object): name = 'files' def __init__(self, config): pass def get(self, *path): return Record(*path) Add comment on FileProvider init I swear I added this prior to merging, somehow slipped through. Sorryimport os import io import errno from xdg import BaseDirectory from .common import ProviderError class Record(object): def __init__(self, *path): data_dir = BaseDirectory.save_data_path('lab', 'v1', *path[:-1]) self.path = os.path.join(data_dir, path[-1]) try: with io.open(self.path, 'r') as fp: self.data = fp.read() except IOError as e: if e.errno == errno.ENOENT: self.data = None else: raise ProviderError(e) def push(self, data): with io.open(self.path, 'w', encoding='utf-8') as fp: return fp.write(data) class FileProvider(object): name = 'files' def __init__(self, config): # We don't support and configuration, so intentionally empty pass def get(self, *path): return Record(*path)
<commit_before>import os import io import errno from xdg import BaseDirectory from .common import ProviderError class Record(object): def __init__(self, *path): data_dir = BaseDirectory.save_data_path('lab', 'v1', *path[:-1]) self.path = os.path.join(data_dir, path[-1]) try: with io.open(self.path, 'r') as fp: self.data = fp.read() except IOError as e: if e.errno == errno.ENOENT: self.data = None else: raise ProviderError(e) def push(self, data): with io.open(self.path, 'w', encoding='utf-8') as fp: return fp.write(data) class FileProvider(object): name = 'files' def __init__(self, config): pass def get(self, *path): return Record(*path) <commit_msg>Add comment on FileProvider init I swear I added this prior to merging, somehow slipped through. Sorry<commit_after>import os import io import errno from xdg import BaseDirectory from .common import ProviderError class Record(object): def __init__(self, *path): data_dir = BaseDirectory.save_data_path('lab', 'v1', *path[:-1]) self.path = os.path.join(data_dir, path[-1]) try: with io.open(self.path, 'r') as fp: self.data = fp.read() except IOError as e: if e.errno == errno.ENOENT: self.data = None else: raise ProviderError(e) def push(self, data): with io.open(self.path, 'w', encoding='utf-8') as fp: return fp.write(data) class FileProvider(object): name = 'files' def __init__(self, config): # We don't support and configuration, so intentionally empty pass def get(self, *path): return Record(*path)
28884ff33b913f0613a2b271b428d91066440793
moksha/hub/amqp/__init__.py
moksha/hub/amqp/__init__.py
""" Here is where we configure which AMQP hub implementation we are going to use. """ try: from qpid010 import QpidAMQPHub AMQPHub = QpidAMQPHub except ImportError: print "Unable to import qpid module" class FakeHub(object): pass AMQPHub = FakeHub #from pyamqplib import AMQPLibHub #AMQPHub = AMQPLibHub
""" Here is where we configure which AMQP hub implementation we are going to use. """ import logging log = logging.getLogger(__name__) try: from qpid010 import QpidAMQPHub AMQPHub = QpidAMQPHub except ImportError: log.debug("Unable to import qpid module") class FakeHub(object): pass AMQPHub = FakeHub #from pyamqplib import AMQPLibHub #AMQPHub = AMQPLibHub
Make our python-qpid detection code use the logger, as to not anger mod_wsgi
Make our python-qpid detection code use the logger, as to not anger mod_wsgi
Python
apache-2.0
mokshaproject/moksha,mokshaproject/moksha,lmacken/moksha,mokshaproject/moksha,mokshaproject/moksha,lmacken/moksha,pombredanne/moksha,pombredanne/moksha,ralphbean/moksha,ralphbean/moksha,lmacken/moksha,pombredanne/moksha,ralphbean/moksha,pombredanne/moksha
""" Here is where we configure which AMQP hub implementation we are going to use. """ try: from qpid010 import QpidAMQPHub AMQPHub = QpidAMQPHub except ImportError: print "Unable to import qpid module" class FakeHub(object): pass AMQPHub = FakeHub #from pyamqplib import AMQPLibHub #AMQPHub = AMQPLibHub Make our python-qpid detection code use the logger, as to not anger mod_wsgi
""" Here is where we configure which AMQP hub implementation we are going to use. """ import logging log = logging.getLogger(__name__) try: from qpid010 import QpidAMQPHub AMQPHub = QpidAMQPHub except ImportError: log.debug("Unable to import qpid module") class FakeHub(object): pass AMQPHub = FakeHub #from pyamqplib import AMQPLibHub #AMQPHub = AMQPLibHub
<commit_before>""" Here is where we configure which AMQP hub implementation we are going to use. """ try: from qpid010 import QpidAMQPHub AMQPHub = QpidAMQPHub except ImportError: print "Unable to import qpid module" class FakeHub(object): pass AMQPHub = FakeHub #from pyamqplib import AMQPLibHub #AMQPHub = AMQPLibHub <commit_msg>Make our python-qpid detection code use the logger, as to not anger mod_wsgi<commit_after>
""" Here is where we configure which AMQP hub implementation we are going to use. """ import logging log = logging.getLogger(__name__) try: from qpid010 import QpidAMQPHub AMQPHub = QpidAMQPHub except ImportError: log.debug("Unable to import qpid module") class FakeHub(object): pass AMQPHub = FakeHub #from pyamqplib import AMQPLibHub #AMQPHub = AMQPLibHub
""" Here is where we configure which AMQP hub implementation we are going to use. """ try: from qpid010 import QpidAMQPHub AMQPHub = QpidAMQPHub except ImportError: print "Unable to import qpid module" class FakeHub(object): pass AMQPHub = FakeHub #from pyamqplib import AMQPLibHub #AMQPHub = AMQPLibHub Make our python-qpid detection code use the logger, as to not anger mod_wsgi""" Here is where we configure which AMQP hub implementation we are going to use. """ import logging log = logging.getLogger(__name__) try: from qpid010 import QpidAMQPHub AMQPHub = QpidAMQPHub except ImportError: log.debug("Unable to import qpid module") class FakeHub(object): pass AMQPHub = FakeHub #from pyamqplib import AMQPLibHub #AMQPHub = AMQPLibHub
<commit_before>""" Here is where we configure which AMQP hub implementation we are going to use. """ try: from qpid010 import QpidAMQPHub AMQPHub = QpidAMQPHub except ImportError: print "Unable to import qpid module" class FakeHub(object): pass AMQPHub = FakeHub #from pyamqplib import AMQPLibHub #AMQPHub = AMQPLibHub <commit_msg>Make our python-qpid detection code use the logger, as to not anger mod_wsgi<commit_after>""" Here is where we configure which AMQP hub implementation we are going to use. """ import logging log = logging.getLogger(__name__) try: from qpid010 import QpidAMQPHub AMQPHub = QpidAMQPHub except ImportError: log.debug("Unable to import qpid module") class FakeHub(object): pass AMQPHub = FakeHub #from pyamqplib import AMQPLibHub #AMQPHub = AMQPLibHub
806fcd76941efe6971709509623876d5181c1f8d
mopidy_subsonic/__init__.py
mopidy_subsonic/__init__.py
from __future__ import unicode_literals import os from mopidy import ext, config __version__ = '0.2' class SubsonicExtension(ext.Extension): dist_name = 'Mopidy-Subsonic' ext_name = 'subsonic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(SubsonicExtension, self).get_config_schema() schema['hostname'] = config.Hostname() schema['port'] = config.Port() schema['username'] = config.String() schema['password'] = config.Secret() schema['ssl'] = config.Boolean() return schema def get_backend_classes(self): from .actor import SubsonicBackend return [SubsonicBackend]
from __future__ import unicode_literals import os from mopidy import ext, config __version__ = '0.2' class SubsonicExtension(ext.Extension): dist_name = 'Mopidy-Subsonic' ext_name = 'subsonic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(SubsonicExtension, self).get_config_schema() schema['hostname'] = config.Hostname() schema['port'] = config.Port() schema['username'] = config.String() schema['password'] = config.Secret() schema['ssl'] = config.Boolean() return schema def setup(self, registry): from .actor import SubsonicBackend registry.add('backend', SubsonicBackend)
Use new extension setup() API
Use new extension setup() API
Python
mit
rattboi/mopidy-subsonic
from __future__ import unicode_literals import os from mopidy import ext, config __version__ = '0.2' class SubsonicExtension(ext.Extension): dist_name = 'Mopidy-Subsonic' ext_name = 'subsonic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(SubsonicExtension, self).get_config_schema() schema['hostname'] = config.Hostname() schema['port'] = config.Port() schema['username'] = config.String() schema['password'] = config.Secret() schema['ssl'] = config.Boolean() return schema def get_backend_classes(self): from .actor import SubsonicBackend return [SubsonicBackend] Use new extension setup() API
from __future__ import unicode_literals import os from mopidy import ext, config __version__ = '0.2' class SubsonicExtension(ext.Extension): dist_name = 'Mopidy-Subsonic' ext_name = 'subsonic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(SubsonicExtension, self).get_config_schema() schema['hostname'] = config.Hostname() schema['port'] = config.Port() schema['username'] = config.String() schema['password'] = config.Secret() schema['ssl'] = config.Boolean() return schema def setup(self, registry): from .actor import SubsonicBackend registry.add('backend', SubsonicBackend)
<commit_before>from __future__ import unicode_literals import os from mopidy import ext, config __version__ = '0.2' class SubsonicExtension(ext.Extension): dist_name = 'Mopidy-Subsonic' ext_name = 'subsonic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(SubsonicExtension, self).get_config_schema() schema['hostname'] = config.Hostname() schema['port'] = config.Port() schema['username'] = config.String() schema['password'] = config.Secret() schema['ssl'] = config.Boolean() return schema def get_backend_classes(self): from .actor import SubsonicBackend return [SubsonicBackend] <commit_msg>Use new extension setup() API<commit_after>
from __future__ import unicode_literals import os from mopidy import ext, config __version__ = '0.2' class SubsonicExtension(ext.Extension): dist_name = 'Mopidy-Subsonic' ext_name = 'subsonic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(SubsonicExtension, self).get_config_schema() schema['hostname'] = config.Hostname() schema['port'] = config.Port() schema['username'] = config.String() schema['password'] = config.Secret() schema['ssl'] = config.Boolean() return schema def setup(self, registry): from .actor import SubsonicBackend registry.add('backend', SubsonicBackend)
from __future__ import unicode_literals import os from mopidy import ext, config __version__ = '0.2' class SubsonicExtension(ext.Extension): dist_name = 'Mopidy-Subsonic' ext_name = 'subsonic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(SubsonicExtension, self).get_config_schema() schema['hostname'] = config.Hostname() schema['port'] = config.Port() schema['username'] = config.String() schema['password'] = config.Secret() schema['ssl'] = config.Boolean() return schema def get_backend_classes(self): from .actor import SubsonicBackend return [SubsonicBackend] Use new extension setup() APIfrom __future__ import unicode_literals import os from mopidy import ext, config __version__ = '0.2' class SubsonicExtension(ext.Extension): dist_name = 'Mopidy-Subsonic' ext_name = 'subsonic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(SubsonicExtension, self).get_config_schema() schema['hostname'] = config.Hostname() schema['port'] = config.Port() schema['username'] = config.String() schema['password'] = config.Secret() schema['ssl'] = config.Boolean() return schema def setup(self, registry): from .actor import SubsonicBackend registry.add('backend', SubsonicBackend)
<commit_before>from __future__ import unicode_literals import os from mopidy import ext, config __version__ = '0.2' class SubsonicExtension(ext.Extension): dist_name = 'Mopidy-Subsonic' ext_name = 'subsonic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(SubsonicExtension, self).get_config_schema() schema['hostname'] = config.Hostname() schema['port'] = config.Port() schema['username'] = config.String() schema['password'] = config.Secret() schema['ssl'] = config.Boolean() return schema def get_backend_classes(self): from .actor import SubsonicBackend return [SubsonicBackend] <commit_msg>Use new extension setup() API<commit_after>from __future__ import unicode_literals import os from mopidy import ext, config __version__ = '0.2' class SubsonicExtension(ext.Extension): dist_name = 'Mopidy-Subsonic' ext_name = 'subsonic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(SubsonicExtension, self).get_config_schema() schema['hostname'] = config.Hostname() schema['port'] = config.Port() schema['username'] = config.String() schema['password'] = config.Secret() schema['ssl'] = config.Boolean() return schema def setup(self, registry): from .actor import SubsonicBackend registry.add('backend', SubsonicBackend)
08e4669d7ac743c152c552edf0617caa1d4934ad
tests/settings-djcelery.py
tests/settings-djcelery.py
__doc__ = """Minimal django settings to run manage.py test command""" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': __name__, 'ATOMIC': True } } BROKER_BACKEND = 'memory' ROOT_URLCONF = 'tests.urls' INSTALLED_APPS = ('djcelery_transactions', 'test' ) SECRET_KEY = "django_tests_secret_key" TIME_ZONE = 'America/New_York' LANGUAGE_CODE = 'en-us' ADMIN_MEDIA_PREFIX = '/static/admin/' STATICFILES_DIRS = () TEST_RUNNER = 'djcelery.contrib.test_runner.CeleryTestSuiteRunner'
__doc__ = """Minimal django settings to run manage.py test command""" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': __name__ } } BROKER_BACKEND = 'memory' ROOT_URLCONF = 'tests.urls' INSTALLED_APPS = ('djcelery_transactions', 'test' ) SECRET_KEY = "django_tests_secret_key" TIME_ZONE = 'America/New_York' LANGUAGE_CODE = 'en-us' ADMIN_MEDIA_PREFIX = '/static/admin/' STATICFILES_DIRS = () TEST_RUNNER = 'djcelery.contrib.test_runner.CeleryTestSuiteRunner'
Make both test settings more similar
Make both test settings more similar
Python
bsd-2-clause
roverdotcom/django-celery-transactions,stored/django-celery-transactions,fellowshipofone/django-celery-transactions
__doc__ = """Minimal django settings to run manage.py test command""" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': __name__, 'ATOMIC': True } } BROKER_BACKEND = 'memory' ROOT_URLCONF = 'tests.urls' INSTALLED_APPS = ('djcelery_transactions', 'test' ) SECRET_KEY = "django_tests_secret_key" TIME_ZONE = 'America/New_York' LANGUAGE_CODE = 'en-us' ADMIN_MEDIA_PREFIX = '/static/admin/' STATICFILES_DIRS = () TEST_RUNNER = 'djcelery.contrib.test_runner.CeleryTestSuiteRunner'Make both test settings more similar
__doc__ = """Minimal django settings to run manage.py test command""" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': __name__ } } BROKER_BACKEND = 'memory' ROOT_URLCONF = 'tests.urls' INSTALLED_APPS = ('djcelery_transactions', 'test' ) SECRET_KEY = "django_tests_secret_key" TIME_ZONE = 'America/New_York' LANGUAGE_CODE = 'en-us' ADMIN_MEDIA_PREFIX = '/static/admin/' STATICFILES_DIRS = () TEST_RUNNER = 'djcelery.contrib.test_runner.CeleryTestSuiteRunner'
<commit_before>__doc__ = """Minimal django settings to run manage.py test command""" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': __name__, 'ATOMIC': True } } BROKER_BACKEND = 'memory' ROOT_URLCONF = 'tests.urls' INSTALLED_APPS = ('djcelery_transactions', 'test' ) SECRET_KEY = "django_tests_secret_key" TIME_ZONE = 'America/New_York' LANGUAGE_CODE = 'en-us' ADMIN_MEDIA_PREFIX = '/static/admin/' STATICFILES_DIRS = () TEST_RUNNER = 'djcelery.contrib.test_runner.CeleryTestSuiteRunner'<commit_msg>Make both test settings more similar<commit_after>
__doc__ = """Minimal django settings to run manage.py test command""" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': __name__ } } BROKER_BACKEND = 'memory' ROOT_URLCONF = 'tests.urls' INSTALLED_APPS = ('djcelery_transactions', 'test' ) SECRET_KEY = "django_tests_secret_key" TIME_ZONE = 'America/New_York' LANGUAGE_CODE = 'en-us' ADMIN_MEDIA_PREFIX = '/static/admin/' STATICFILES_DIRS = () TEST_RUNNER = 'djcelery.contrib.test_runner.CeleryTestSuiteRunner'
__doc__ = """Minimal django settings to run manage.py test command""" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': __name__, 'ATOMIC': True } } BROKER_BACKEND = 'memory' ROOT_URLCONF = 'tests.urls' INSTALLED_APPS = ('djcelery_transactions', 'test' ) SECRET_KEY = "django_tests_secret_key" TIME_ZONE = 'America/New_York' LANGUAGE_CODE = 'en-us' ADMIN_MEDIA_PREFIX = '/static/admin/' STATICFILES_DIRS = () TEST_RUNNER = 'djcelery.contrib.test_runner.CeleryTestSuiteRunner'Make both test settings more similar__doc__ = """Minimal django settings to run manage.py test command""" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': __name__ } } BROKER_BACKEND = 'memory' ROOT_URLCONF = 'tests.urls' INSTALLED_APPS = ('djcelery_transactions', 'test' ) SECRET_KEY = "django_tests_secret_key" TIME_ZONE = 'America/New_York' LANGUAGE_CODE = 'en-us' ADMIN_MEDIA_PREFIX = '/static/admin/' STATICFILES_DIRS = () TEST_RUNNER = 'djcelery.contrib.test_runner.CeleryTestSuiteRunner'
<commit_before>__doc__ = """Minimal django settings to run manage.py test command""" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': __name__, 'ATOMIC': True } } BROKER_BACKEND = 'memory' ROOT_URLCONF = 'tests.urls' INSTALLED_APPS = ('djcelery_transactions', 'test' ) SECRET_KEY = "django_tests_secret_key" TIME_ZONE = 'America/New_York' LANGUAGE_CODE = 'en-us' ADMIN_MEDIA_PREFIX = '/static/admin/' STATICFILES_DIRS = () TEST_RUNNER = 'djcelery.contrib.test_runner.CeleryTestSuiteRunner'<commit_msg>Make both test settings more similar<commit_after>__doc__ = """Minimal django settings to run manage.py test command""" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': __name__ } } BROKER_BACKEND = 'memory' ROOT_URLCONF = 'tests.urls' INSTALLED_APPS = ('djcelery_transactions', 'test' ) SECRET_KEY = "django_tests_secret_key" TIME_ZONE = 'America/New_York' LANGUAGE_CODE = 'en-us' ADMIN_MEDIA_PREFIX = '/static/admin/' STATICFILES_DIRS = () TEST_RUNNER = 'djcelery.contrib.test_runner.CeleryTestSuiteRunner'
86036942f32b629e7d3ccc5307be6b3e03ae4053
tests/test_content_type.py
tests/test_content_type.py
import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) requestWithQueryParam = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert FormParser is negotiation.select_parser( requestWithQueryParam, parsers) requestWithoutQueryParam = Request( factory.post('/', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert None is negotiation.select_parser( requestWithoutQueryParam, parsers)
import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) requestWithQueryParam = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert FormParser is negotiation.select_parser( requestWithQueryParam, parsers) requestWithoutQueryParam = Request( factory.post('/', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert None is negotiation.select_parser( requestWithoutQueryParam, parsers) def test_limited_overrides(): """ The content type shouldn't be overridden if the header is something other than 'text/plain', or missing entirely. """ from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) req = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/somethingelse')) assert negotiation.select_parser(req, parsers) is None
Test that not all content types are overridden
Test that not all content types are overridden
Python
mit
hzdg/drf-url-content-type-override
import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) requestWithQueryParam = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert FormParser is negotiation.select_parser( requestWithQueryParam, parsers) requestWithoutQueryParam = Request( factory.post('/', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert None is negotiation.select_parser( requestWithoutQueryParam, parsers) Test that not all content types are overridden
import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) requestWithQueryParam = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert FormParser is negotiation.select_parser( requestWithQueryParam, parsers) requestWithoutQueryParam = Request( factory.post('/', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert None is negotiation.select_parser( requestWithoutQueryParam, parsers) def test_limited_overrides(): """ The content type shouldn't be overridden if the header is something other than 'text/plain', or missing entirely. """ from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) req = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/somethingelse')) assert negotiation.select_parser(req, parsers) is None
<commit_before>import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) requestWithQueryParam = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert FormParser is negotiation.select_parser( requestWithQueryParam, parsers) requestWithoutQueryParam = Request( factory.post('/', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert None is negotiation.select_parser( requestWithoutQueryParam, parsers) <commit_msg>Test that not all content types are overridden<commit_after>
import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) requestWithQueryParam = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert FormParser is negotiation.select_parser( requestWithQueryParam, parsers) requestWithoutQueryParam = Request( factory.post('/', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert None is negotiation.select_parser( requestWithoutQueryParam, parsers) def test_limited_overrides(): """ The content type shouldn't be overridden if the header is something other than 'text/plain', or missing entirely. """ from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) req = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/somethingelse')) assert negotiation.select_parser(req, parsers) is None
import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) requestWithQueryParam = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert FormParser is negotiation.select_parser( requestWithQueryParam, parsers) requestWithoutQueryParam = Request( factory.post('/', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert None is negotiation.select_parser( requestWithoutQueryParam, parsers) Test that not all content types are overriddenimport pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) requestWithQueryParam = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert FormParser is negotiation.select_parser( requestWithQueryParam, parsers) requestWithoutQueryParam = Request( factory.post('/', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert None is negotiation.select_parser( requestWithoutQueryParam, parsers) def test_limited_overrides(): """ The content type shouldn't be overridden if the header is something other than 'text/plain', or missing entirely. """ from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) req = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/somethingelse')) assert negotiation.select_parser(req, parsers) is None
<commit_before>import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) requestWithQueryParam = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert FormParser is negotiation.select_parser( requestWithQueryParam, parsers) requestWithoutQueryParam = Request( factory.post('/', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert None is negotiation.select_parser( requestWithoutQueryParam, parsers) <commit_msg>Test that not all content types are overridden<commit_after>import pytest from rest_framework.request import Request from rest_framework.test import APIRequestFactory from rest_framework.parsers import JSONParser, FormParser, MultiPartParser factory = APIRequestFactory() def test_content_type_override_query(): from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) requestWithQueryParam = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert FormParser is negotiation.select_parser( requestWithQueryParam, parsers) requestWithoutQueryParam = Request( factory.post('/', {'email': 'mmmmmm@test.com'}, content_type='text/plain')) assert None is negotiation.select_parser( requestWithoutQueryParam, parsers) def test_limited_overrides(): """ The content type shouldn't be overridden if the header is something other than 'text/plain', or missing entirely. """ from rest_url_override_content_negotiation import \ URLOverrideContentNegotiation negotiation = URLOverrideContentNegotiation() parsers = (JSONParser, FormParser, MultiPartParser) req = Request( factory.post('/?content_type=application/x-www-form-urlencoded', {'email': 'mmmmmm@test.com'}, content_type='text/somethingelse')) assert negotiation.select_parser(req, parsers) is None
d37c1dca5ffe0508b0944b811a2a65daf8717bea
tests/test_garner_dates.py
tests/test_garner_dates.py
"""Test garner.dates.""" from __future__ import absolute_import from .check import Check from proselint.checks.garner import dates class TestCheck(Check): """Test class for garner.dates.""" __test__ = True def test_50s_hyphenation(self): """Find uneeded hyphen in 50's.""" text = """The 50's were swell.""" errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 1 def test_50_Cent_hyphenation(self): """Don't flag 50's when it refers to 50 Cent's manager.""" text = """ Dr. Dre suggested to 50's manager that he look into signing Eminem to the G-Unit record label. """ errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 0 def test_dash_and_from(self): """Test garner.check_dash_and_from.""" text = """From 1999-2002, Sally served as chair of the committee.""" errors = dates.check_dash_and_from(text) print errors assert len(errors) == 1
"""Test garner.dates.""" from __future__ import absolute_import from .check import Check from proselint.checks.garner import dates class TestCheck(Check): """Test class for garner.dates.""" __test__ = True def test_50s_hyphenation(self): """Find uneeded hyphen in 50's.""" text = """The 50's were swell.""" errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 1 def test_50_Cent_hyphenation(self): """Don't flag 50's when it refers to 50 Cent's manager.""" text = """ Dr. Dre suggested to 50's manager that he look into signing Eminem to the G-Unit record label. """ errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 0 def test_dash_and_from(self): """Test garner.check_dash_and_from.""" text = """From 1999-2002, Sally served as chair of the committee.""" errors = dates.check_dash_and_from(text) print(errors) assert len(errors) == 1
Fix bug in print statement
Fix bug in print statement
Python
bsd-3-clause
jstewmon/proselint,amperser/proselint,amperser/proselint,jstewmon/proselint,amperser/proselint,jstewmon/proselint,amperser/proselint,amperser/proselint
"""Test garner.dates.""" from __future__ import absolute_import from .check import Check from proselint.checks.garner import dates class TestCheck(Check): """Test class for garner.dates.""" __test__ = True def test_50s_hyphenation(self): """Find uneeded hyphen in 50's.""" text = """The 50's were swell.""" errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 1 def test_50_Cent_hyphenation(self): """Don't flag 50's when it refers to 50 Cent's manager.""" text = """ Dr. Dre suggested to 50's manager that he look into signing Eminem to the G-Unit record label. """ errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 0 def test_dash_and_from(self): """Test garner.check_dash_and_from.""" text = """From 1999-2002, Sally served as chair of the committee.""" errors = dates.check_dash_and_from(text) print errors assert len(errors) == 1 Fix bug in print statement
"""Test garner.dates.""" from __future__ import absolute_import from .check import Check from proselint.checks.garner import dates class TestCheck(Check): """Test class for garner.dates.""" __test__ = True def test_50s_hyphenation(self): """Find uneeded hyphen in 50's.""" text = """The 50's were swell.""" errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 1 def test_50_Cent_hyphenation(self): """Don't flag 50's when it refers to 50 Cent's manager.""" text = """ Dr. Dre suggested to 50's manager that he look into signing Eminem to the G-Unit record label. """ errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 0 def test_dash_and_from(self): """Test garner.check_dash_and_from.""" text = """From 1999-2002, Sally served as chair of the committee.""" errors = dates.check_dash_and_from(text) print(errors) assert len(errors) == 1
<commit_before>"""Test garner.dates.""" from __future__ import absolute_import from .check import Check from proselint.checks.garner import dates class TestCheck(Check): """Test class for garner.dates.""" __test__ = True def test_50s_hyphenation(self): """Find uneeded hyphen in 50's.""" text = """The 50's were swell.""" errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 1 def test_50_Cent_hyphenation(self): """Don't flag 50's when it refers to 50 Cent's manager.""" text = """ Dr. Dre suggested to 50's manager that he look into signing Eminem to the G-Unit record label. """ errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 0 def test_dash_and_from(self): """Test garner.check_dash_and_from.""" text = """From 1999-2002, Sally served as chair of the committee.""" errors = dates.check_dash_and_from(text) print errors assert len(errors) == 1 <commit_msg>Fix bug in print statement<commit_after>
"""Test garner.dates.""" from __future__ import absolute_import from .check import Check from proselint.checks.garner import dates class TestCheck(Check): """Test class for garner.dates.""" __test__ = True def test_50s_hyphenation(self): """Find uneeded hyphen in 50's.""" text = """The 50's were swell.""" errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 1 def test_50_Cent_hyphenation(self): """Don't flag 50's when it refers to 50 Cent's manager.""" text = """ Dr. Dre suggested to 50's manager that he look into signing Eminem to the G-Unit record label. """ errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 0 def test_dash_and_from(self): """Test garner.check_dash_and_from.""" text = """From 1999-2002, Sally served as chair of the committee.""" errors = dates.check_dash_and_from(text) print(errors) assert len(errors) == 1
"""Test garner.dates.""" from __future__ import absolute_import from .check import Check from proselint.checks.garner import dates class TestCheck(Check): """Test class for garner.dates.""" __test__ = True def test_50s_hyphenation(self): """Find uneeded hyphen in 50's.""" text = """The 50's were swell.""" errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 1 def test_50_Cent_hyphenation(self): """Don't flag 50's when it refers to 50 Cent's manager.""" text = """ Dr. Dre suggested to 50's manager that he look into signing Eminem to the G-Unit record label. """ errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 0 def test_dash_and_from(self): """Test garner.check_dash_and_from.""" text = """From 1999-2002, Sally served as chair of the committee.""" errors = dates.check_dash_and_from(text) print errors assert len(errors) == 1 Fix bug in print statement"""Test garner.dates.""" from __future__ import absolute_import from .check import Check from proselint.checks.garner import dates class TestCheck(Check): """Test class for garner.dates.""" __test__ = True def test_50s_hyphenation(self): """Find uneeded hyphen in 50's.""" text = """The 50's were swell.""" errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 1 def test_50_Cent_hyphenation(self): """Don't flag 50's when it refers to 50 Cent's manager.""" text = """ Dr. Dre suggested to 50's manager that he look into signing Eminem to the G-Unit record label. """ errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 0 def test_dash_and_from(self): """Test garner.check_dash_and_from.""" text = """From 1999-2002, Sally served as chair of the committee.""" errors = dates.check_dash_and_from(text) print(errors) assert len(errors) == 1
<commit_before>"""Test garner.dates.""" from __future__ import absolute_import from .check import Check from proselint.checks.garner import dates class TestCheck(Check): """Test class for garner.dates.""" __test__ = True def test_50s_hyphenation(self): """Find uneeded hyphen in 50's.""" text = """The 50's were swell.""" errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 1 def test_50_Cent_hyphenation(self): """Don't flag 50's when it refers to 50 Cent's manager.""" text = """ Dr. Dre suggested to 50's manager that he look into signing Eminem to the G-Unit record label. """ errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 0 def test_dash_and_from(self): """Test garner.check_dash_and_from.""" text = """From 1999-2002, Sally served as chair of the committee.""" errors = dates.check_dash_and_from(text) print errors assert len(errors) == 1 <commit_msg>Fix bug in print statement<commit_after>"""Test garner.dates.""" from __future__ import absolute_import from .check import Check from proselint.checks.garner import dates class TestCheck(Check): """Test class for garner.dates.""" __test__ = True def test_50s_hyphenation(self): """Find uneeded hyphen in 50's.""" text = """The 50's were swell.""" errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 1 def test_50_Cent_hyphenation(self): """Don't flag 50's when it refers to 50 Cent's manager.""" text = """ Dr. Dre suggested to 50's manager that he look into signing Eminem to the G-Unit record label. """ errors = dates.check_decade_apostrophes_short(text) assert len(errors) == 0 def test_dash_and_from(self): """Test garner.check_dash_and_from.""" text = """From 1999-2002, Sally served as chair of the committee.""" errors = dates.check_dash_and_from(text) print(errors) assert len(errors) == 1
dd35907f9164cd8f75babb1b5b9b6ff9711628fb
djangopeople/djangopeople/management/commands/fix_counts.py
djangopeople/djangopeople/management/commands/fix_counts.py
from django.core.management.base import NoArgsCommand from ...models import Country, Region class Command(NoArgsCommand): """ Countries and regions keep a denormalized count of people that gets out of sync during migrate. This updates it. """ def handle_noargs(self, **options): for qs in (Country.objects.all(), Region.objects.all()): for geo in qs: qs.model.objects.filter(pk=geo.pk).update( num_people=geo.djangoperson_set.count(), )
from django.core.management.base import BaseCommand from ...models import Country, Region class Command(BaseCommand): """ Countries and regions keep a denormalized count of people that gets out of sync during migrate. This updates it. """ def handle(self, **options): for qs in (Country.objects.all(), Region.objects.all()): for geo in qs: qs.model.objects.filter(pk=geo.pk).update( num_people=geo.djangoperson_set.count(), )
Remove usage of deprecated NoArgsCommand
Remove usage of deprecated NoArgsCommand
Python
mit
brutasse/djangopeople,django/djangopeople,django/djangopeople,django/djangopeople,brutasse/djangopeople,brutasse/djangopeople,brutasse/djangopeople
from django.core.management.base import NoArgsCommand from ...models import Country, Region class Command(NoArgsCommand): """ Countries and regions keep a denormalized count of people that gets out of sync during migrate. This updates it. """ def handle_noargs(self, **options): for qs in (Country.objects.all(), Region.objects.all()): for geo in qs: qs.model.objects.filter(pk=geo.pk).update( num_people=geo.djangoperson_set.count(), ) Remove usage of deprecated NoArgsCommand
from django.core.management.base import BaseCommand from ...models import Country, Region class Command(BaseCommand): """ Countries and regions keep a denormalized count of people that gets out of sync during migrate. This updates it. """ def handle(self, **options): for qs in (Country.objects.all(), Region.objects.all()): for geo in qs: qs.model.objects.filter(pk=geo.pk).update( num_people=geo.djangoperson_set.count(), )
<commit_before>from django.core.management.base import NoArgsCommand from ...models import Country, Region class Command(NoArgsCommand): """ Countries and regions keep a denormalized count of people that gets out of sync during migrate. This updates it. """ def handle_noargs(self, **options): for qs in (Country.objects.all(), Region.objects.all()): for geo in qs: qs.model.objects.filter(pk=geo.pk).update( num_people=geo.djangoperson_set.count(), ) <commit_msg>Remove usage of deprecated NoArgsCommand<commit_after>
from django.core.management.base import BaseCommand from ...models import Country, Region class Command(BaseCommand): """ Countries and regions keep a denormalized count of people that gets out of sync during migrate. This updates it. """ def handle(self, **options): for qs in (Country.objects.all(), Region.objects.all()): for geo in qs: qs.model.objects.filter(pk=geo.pk).update( num_people=geo.djangoperson_set.count(), )
from django.core.management.base import NoArgsCommand from ...models import Country, Region class Command(NoArgsCommand): """ Countries and regions keep a denormalized count of people that gets out of sync during migrate. This updates it. """ def handle_noargs(self, **options): for qs in (Country.objects.all(), Region.objects.all()): for geo in qs: qs.model.objects.filter(pk=geo.pk).update( num_people=geo.djangoperson_set.count(), ) Remove usage of deprecated NoArgsCommandfrom django.core.management.base import BaseCommand from ...models import Country, Region class Command(BaseCommand): """ Countries and regions keep a denormalized count of people that gets out of sync during migrate. This updates it. """ def handle(self, **options): for qs in (Country.objects.all(), Region.objects.all()): for geo in qs: qs.model.objects.filter(pk=geo.pk).update( num_people=geo.djangoperson_set.count(), )
<commit_before>from django.core.management.base import NoArgsCommand from ...models import Country, Region class Command(NoArgsCommand): """ Countries and regions keep a denormalized count of people that gets out of sync during migrate. This updates it. """ def handle_noargs(self, **options): for qs in (Country.objects.all(), Region.objects.all()): for geo in qs: qs.model.objects.filter(pk=geo.pk).update( num_people=geo.djangoperson_set.count(), ) <commit_msg>Remove usage of deprecated NoArgsCommand<commit_after>from django.core.management.base import BaseCommand from ...models import Country, Region class Command(BaseCommand): """ Countries and regions keep a denormalized count of people that gets out of sync during migrate. This updates it. """ def handle(self, **options): for qs in (Country.objects.all(), Region.objects.all()): for geo in qs: qs.model.objects.filter(pk=geo.pk).update( num_people=geo.djangoperson_set.count(), )
5aa55190bae3657e09f6c2fbdedb9ab71210fad5
cocktails/drinks/models.py
cocktails/drinks/models.py
from django.db import models # Create your models here. class Ingredient(models.Model): name = models.CharField(max_length=100) abv = models.FloatField() type = models.CharField(max_length=25) def __str__(self): return self.name class Admin: list_display = ('name') class Meta: ordering = ['id'] class IngredientLine(models.Model): ing = models.ForeignKey(Ingredient, on_delete=models.CASCADE, default=1) amt = models.FloatField(default=0) def __str__(self): return "{} ounces of {}".format(str(self.amt), self.ing.name) class Drink(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey('auth.User', related_name='drinks') ings = models.ManyToManyField(IngredientLine) instructions = models.TextField() def __str__(self): return self.name
from django.db import models # Create your models here. class Ingredient(models.Model): name = models.CharField(max_length=100) abv = models.FloatField() type = models.CharField(max_length=25) def __str__(self): return self.name class Admin: list_display = ('name') class Meta: ordering = ['id'] class IngredientLine(models.Model): ing = models.ForeignKey(Ingredient, on_delete=models.CASCADE, default=1) amt = models.FloatField(default=0) def __str__(self): if self.amt == 0: return self.ing.name return "{} ounces of {}".format(str(self.amt), self.ing.name) class Drink(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey('auth.User', related_name='drinks') ings = models.ManyToManyField(IngredientLine) instructions = models.TextField() def __str__(self): return self.name
Remove 0.0 from ings line
Remove 0.0 from ings line
Python
mit
jake-jake-jake/cocktails,jake-jake-jake/cocktails,jake-jake-jake/cocktails,jake-jake-jake/cocktails
from django.db import models # Create your models here. class Ingredient(models.Model): name = models.CharField(max_length=100) abv = models.FloatField() type = models.CharField(max_length=25) def __str__(self): return self.name class Admin: list_display = ('name') class Meta: ordering = ['id'] class IngredientLine(models.Model): ing = models.ForeignKey(Ingredient, on_delete=models.CASCADE, default=1) amt = models.FloatField(default=0) def __str__(self): return "{} ounces of {}".format(str(self.amt), self.ing.name) class Drink(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey('auth.User', related_name='drinks') ings = models.ManyToManyField(IngredientLine) instructions = models.TextField() def __str__(self): return self.name Remove 0.0 from ings line
from django.db import models # Create your models here. class Ingredient(models.Model): name = models.CharField(max_length=100) abv = models.FloatField() type = models.CharField(max_length=25) def __str__(self): return self.name class Admin: list_display = ('name') class Meta: ordering = ['id'] class IngredientLine(models.Model): ing = models.ForeignKey(Ingredient, on_delete=models.CASCADE, default=1) amt = models.FloatField(default=0) def __str__(self): if self.amt == 0: return self.ing.name return "{} ounces of {}".format(str(self.amt), self.ing.name) class Drink(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey('auth.User', related_name='drinks') ings = models.ManyToManyField(IngredientLine) instructions = models.TextField() def __str__(self): return self.name
<commit_before>from django.db import models # Create your models here. class Ingredient(models.Model): name = models.CharField(max_length=100) abv = models.FloatField() type = models.CharField(max_length=25) def __str__(self): return self.name class Admin: list_display = ('name') class Meta: ordering = ['id'] class IngredientLine(models.Model): ing = models.ForeignKey(Ingredient, on_delete=models.CASCADE, default=1) amt = models.FloatField(default=0) def __str__(self): return "{} ounces of {}".format(str(self.amt), self.ing.name) class Drink(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey('auth.User', related_name='drinks') ings = models.ManyToManyField(IngredientLine) instructions = models.TextField() def __str__(self): return self.name <commit_msg>Remove 0.0 from ings line<commit_after>
from django.db import models # Create your models here. class Ingredient(models.Model): name = models.CharField(max_length=100) abv = models.FloatField() type = models.CharField(max_length=25) def __str__(self): return self.name class Admin: list_display = ('name') class Meta: ordering = ['id'] class IngredientLine(models.Model): ing = models.ForeignKey(Ingredient, on_delete=models.CASCADE, default=1) amt = models.FloatField(default=0) def __str__(self): if self.amt == 0: return self.ing.name return "{} ounces of {}".format(str(self.amt), self.ing.name) class Drink(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey('auth.User', related_name='drinks') ings = models.ManyToManyField(IngredientLine) instructions = models.TextField() def __str__(self): return self.name
from django.db import models # Create your models here. class Ingredient(models.Model): name = models.CharField(max_length=100) abv = models.FloatField() type = models.CharField(max_length=25) def __str__(self): return self.name class Admin: list_display = ('name') class Meta: ordering = ['id'] class IngredientLine(models.Model): ing = models.ForeignKey(Ingredient, on_delete=models.CASCADE, default=1) amt = models.FloatField(default=0) def __str__(self): return "{} ounces of {}".format(str(self.amt), self.ing.name) class Drink(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey('auth.User', related_name='drinks') ings = models.ManyToManyField(IngredientLine) instructions = models.TextField() def __str__(self): return self.name Remove 0.0 from ings linefrom django.db import models # Create your models here. class Ingredient(models.Model): name = models.CharField(max_length=100) abv = models.FloatField() type = models.CharField(max_length=25) def __str__(self): return self.name class Admin: list_display = ('name') class Meta: ordering = ['id'] class IngredientLine(models.Model): ing = models.ForeignKey(Ingredient, on_delete=models.CASCADE, default=1) amt = models.FloatField(default=0) def __str__(self): if self.amt == 0: return self.ing.name return "{} ounces of {}".format(str(self.amt), self.ing.name) class Drink(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey('auth.User', related_name='drinks') ings = models.ManyToManyField(IngredientLine) instructions = models.TextField() def __str__(self): return self.name
<commit_before>from django.db import models # Create your models here. class Ingredient(models.Model): name = models.CharField(max_length=100) abv = models.FloatField() type = models.CharField(max_length=25) def __str__(self): return self.name class Admin: list_display = ('name') class Meta: ordering = ['id'] class IngredientLine(models.Model): ing = models.ForeignKey(Ingredient, on_delete=models.CASCADE, default=1) amt = models.FloatField(default=0) def __str__(self): return "{} ounces of {}".format(str(self.amt), self.ing.name) class Drink(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey('auth.User', related_name='drinks') ings = models.ManyToManyField(IngredientLine) instructions = models.TextField() def __str__(self): return self.name <commit_msg>Remove 0.0 from ings line<commit_after>from django.db import models # Create your models here. class Ingredient(models.Model): name = models.CharField(max_length=100) abv = models.FloatField() type = models.CharField(max_length=25) def __str__(self): return self.name class Admin: list_display = ('name') class Meta: ordering = ['id'] class IngredientLine(models.Model): ing = models.ForeignKey(Ingredient, on_delete=models.CASCADE, default=1) amt = models.FloatField(default=0) def __str__(self): if self.amt == 0: return self.ing.name return "{} ounces of {}".format(str(self.amt), self.ing.name) class Drink(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey('auth.User', related_name='drinks') ings = models.ManyToManyField(IngredientLine) instructions = models.TextField() def __str__(self): return self.name
bcd5ea69815405508d7f862754f910fe381172b9
responsive/context_processors.py
responsive/context_processors.py
from django.core.exceptions import ImproperlyConfigured from .conf import settings from .utils import Device def device(request): responsive_middleware = 'responsive.middleware.ResponsiveMiddleware' if responsive_middleware not in settings.MIDDLEWARE_CLASSES: raise ImproperlyConfigured( "responsive context_processors requires the responsive middleware to " "be installed. Edit your MIDDLEWARE_CLASSES setting to insert" "the 'responsive.middleware.ResponsiveMiddleware'") device_obj = getattr(request, settings.RESPONSIVE_VARIABLE_NAME, None) if not device_obj: device_obj = Device() return { settings.RESPONSIVE_VARIABLE_NAME: device_obj }
from django.core.exceptions import ImproperlyConfigured from .conf import settings from .utils import Device def device(request): responsive_middleware = 'responsive.middleware.ResponsiveMiddleware' if responsive_middleware not in settings.MIDDLEWARE_CLASSES: raise ImproperlyConfigured( "You must enable the 'ResponsiveMiddleware'. Edit your " "MIDDLEWARE_CLASSES setting to insert" "the 'responsive.middleware.ResponsiveMiddleware'") device_obj = getattr(request, settings.RESPONSIVE_VARIABLE_NAME, None) if not device_obj: device_obj = Device() return { settings.RESPONSIVE_VARIABLE_NAME: device_obj }
Update message for missing ResponsiveMiddleware
Update message for missing ResponsiveMiddleware
Python
bsd-3-clause
mishbahr/django-responsive2,mishbahr/django-responsive2
from django.core.exceptions import ImproperlyConfigured from .conf import settings from .utils import Device def device(request): responsive_middleware = 'responsive.middleware.ResponsiveMiddleware' if responsive_middleware not in settings.MIDDLEWARE_CLASSES: raise ImproperlyConfigured( "responsive context_processors requires the responsive middleware to " "be installed. Edit your MIDDLEWARE_CLASSES setting to insert" "the 'responsive.middleware.ResponsiveMiddleware'") device_obj = getattr(request, settings.RESPONSIVE_VARIABLE_NAME, None) if not device_obj: device_obj = Device() return { settings.RESPONSIVE_VARIABLE_NAME: device_obj } Update message for missing ResponsiveMiddleware
from django.core.exceptions import ImproperlyConfigured from .conf import settings from .utils import Device def device(request): responsive_middleware = 'responsive.middleware.ResponsiveMiddleware' if responsive_middleware not in settings.MIDDLEWARE_CLASSES: raise ImproperlyConfigured( "You must enable the 'ResponsiveMiddleware'. Edit your " "MIDDLEWARE_CLASSES setting to insert" "the 'responsive.middleware.ResponsiveMiddleware'") device_obj = getattr(request, settings.RESPONSIVE_VARIABLE_NAME, None) if not device_obj: device_obj = Device() return { settings.RESPONSIVE_VARIABLE_NAME: device_obj }
<commit_before>from django.core.exceptions import ImproperlyConfigured from .conf import settings from .utils import Device def device(request): responsive_middleware = 'responsive.middleware.ResponsiveMiddleware' if responsive_middleware not in settings.MIDDLEWARE_CLASSES: raise ImproperlyConfigured( "responsive context_processors requires the responsive middleware to " "be installed. Edit your MIDDLEWARE_CLASSES setting to insert" "the 'responsive.middleware.ResponsiveMiddleware'") device_obj = getattr(request, settings.RESPONSIVE_VARIABLE_NAME, None) if not device_obj: device_obj = Device() return { settings.RESPONSIVE_VARIABLE_NAME: device_obj } <commit_msg>Update message for missing ResponsiveMiddleware<commit_after>
from django.core.exceptions import ImproperlyConfigured from .conf import settings from .utils import Device def device(request): responsive_middleware = 'responsive.middleware.ResponsiveMiddleware' if responsive_middleware not in settings.MIDDLEWARE_CLASSES: raise ImproperlyConfigured( "You must enable the 'ResponsiveMiddleware'. Edit your " "MIDDLEWARE_CLASSES setting to insert" "the 'responsive.middleware.ResponsiveMiddleware'") device_obj = getattr(request, settings.RESPONSIVE_VARIABLE_NAME, None) if not device_obj: device_obj = Device() return { settings.RESPONSIVE_VARIABLE_NAME: device_obj }
from django.core.exceptions import ImproperlyConfigured from .conf import settings from .utils import Device def device(request): responsive_middleware = 'responsive.middleware.ResponsiveMiddleware' if responsive_middleware not in settings.MIDDLEWARE_CLASSES: raise ImproperlyConfigured( "responsive context_processors requires the responsive middleware to " "be installed. Edit your MIDDLEWARE_CLASSES setting to insert" "the 'responsive.middleware.ResponsiveMiddleware'") device_obj = getattr(request, settings.RESPONSIVE_VARIABLE_NAME, None) if not device_obj: device_obj = Device() return { settings.RESPONSIVE_VARIABLE_NAME: device_obj } Update message for missing ResponsiveMiddlewarefrom django.core.exceptions import ImproperlyConfigured from .conf import settings from .utils import Device def device(request): responsive_middleware = 'responsive.middleware.ResponsiveMiddleware' if responsive_middleware not in settings.MIDDLEWARE_CLASSES: raise ImproperlyConfigured( "You must enable the 'ResponsiveMiddleware'. Edit your " "MIDDLEWARE_CLASSES setting to insert" "the 'responsive.middleware.ResponsiveMiddleware'") device_obj = getattr(request, settings.RESPONSIVE_VARIABLE_NAME, None) if not device_obj: device_obj = Device() return { settings.RESPONSIVE_VARIABLE_NAME: device_obj }
<commit_before>from django.core.exceptions import ImproperlyConfigured from .conf import settings from .utils import Device def device(request): responsive_middleware = 'responsive.middleware.ResponsiveMiddleware' if responsive_middleware not in settings.MIDDLEWARE_CLASSES: raise ImproperlyConfigured( "responsive context_processors requires the responsive middleware to " "be installed. Edit your MIDDLEWARE_CLASSES setting to insert" "the 'responsive.middleware.ResponsiveMiddleware'") device_obj = getattr(request, settings.RESPONSIVE_VARIABLE_NAME, None) if not device_obj: device_obj = Device() return { settings.RESPONSIVE_VARIABLE_NAME: device_obj } <commit_msg>Update message for missing ResponsiveMiddleware<commit_after>from django.core.exceptions import ImproperlyConfigured from .conf import settings from .utils import Device def device(request): responsive_middleware = 'responsive.middleware.ResponsiveMiddleware' if responsive_middleware not in settings.MIDDLEWARE_CLASSES: raise ImproperlyConfigured( "You must enable the 'ResponsiveMiddleware'. Edit your " "MIDDLEWARE_CLASSES setting to insert" "the 'responsive.middleware.ResponsiveMiddleware'") device_obj = getattr(request, settings.RESPONSIVE_VARIABLE_NAME, None) if not device_obj: device_obj = Device() return { settings.RESPONSIVE_VARIABLE_NAME: device_obj }
77e78827237b1d3dfcb173075970377d17db4627
formly/utils/views.py
formly/utils/views.py
from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.urls import reverse from django.utils.decorators import method_decorator from django.views.generic import DeleteView def cbv_decorator(decorator): def _decorator(cls): cls.dispatch = method_decorator(decorator)(cls.dispatch) return cls return _decorator @cbv_decorator(login_required) class BaseDeleteView(DeleteView): success_url_name = "" pk_obj_name = "" def get_object(self, queryset=None): obj = super(BaseDeleteView, self).get_object(queryset=queryset) if not self.request.user.has_perm("formly.delete_object", obj=obj): raise PermissionDenied() return obj def get_template_names(self): names = super(BaseDeleteView, self).get_template_names() return [ name.replace("formly/", "formly/design/") for name in names ] def get_success_url(self): kwargs = {} if self.pk_obj_name: kwargs["pk"] = getattr(self.object, self.pk_obj_name).pk return reverse(self.success_url_name, kwargs=kwargs)
from django.contrib.auth.mixins import LoginRequiredMixin from django.core.exceptions import PermissionDenied from django.urls import reverse from django.views.generic import DeleteView class BaseDeleteView(LoginRequiredMixin, DeleteView): success_url_name = "" pk_obj_name = "" def get_object(self, queryset=None): obj = super(BaseDeleteView, self).get_object(queryset=queryset) if not self.request.user.has_perm("formly.delete_object", obj=obj): raise PermissionDenied() return obj def get_template_names(self): names = super(BaseDeleteView, self).get_template_names() return [ name.replace("formly/", "formly/design/") for name in names ] def get_success_url(self): kwargs = {} if self.pk_obj_name: kwargs["pk"] = getattr(self.object, self.pk_obj_name).pk return reverse(self.success_url_name, kwargs=kwargs)
Use modern login required mixin
Use modern login required mixin
Python
bsd-3-clause
eldarion/formly,eldarion/formly
from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.urls import reverse from django.utils.decorators import method_decorator from django.views.generic import DeleteView def cbv_decorator(decorator): def _decorator(cls): cls.dispatch = method_decorator(decorator)(cls.dispatch) return cls return _decorator @cbv_decorator(login_required) class BaseDeleteView(DeleteView): success_url_name = "" pk_obj_name = "" def get_object(self, queryset=None): obj = super(BaseDeleteView, self).get_object(queryset=queryset) if not self.request.user.has_perm("formly.delete_object", obj=obj): raise PermissionDenied() return obj def get_template_names(self): names = super(BaseDeleteView, self).get_template_names() return [ name.replace("formly/", "formly/design/") for name in names ] def get_success_url(self): kwargs = {} if self.pk_obj_name: kwargs["pk"] = getattr(self.object, self.pk_obj_name).pk return reverse(self.success_url_name, kwargs=kwargs) Use modern login required mixin
from django.contrib.auth.mixins import LoginRequiredMixin from django.core.exceptions import PermissionDenied from django.urls import reverse from django.views.generic import DeleteView class BaseDeleteView(LoginRequiredMixin, DeleteView): success_url_name = "" pk_obj_name = "" def get_object(self, queryset=None): obj = super(BaseDeleteView, self).get_object(queryset=queryset) if not self.request.user.has_perm("formly.delete_object", obj=obj): raise PermissionDenied() return obj def get_template_names(self): names = super(BaseDeleteView, self).get_template_names() return [ name.replace("formly/", "formly/design/") for name in names ] def get_success_url(self): kwargs = {} if self.pk_obj_name: kwargs["pk"] = getattr(self.object, self.pk_obj_name).pk return reverse(self.success_url_name, kwargs=kwargs)
<commit_before>from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.urls import reverse from django.utils.decorators import method_decorator from django.views.generic import DeleteView def cbv_decorator(decorator): def _decorator(cls): cls.dispatch = method_decorator(decorator)(cls.dispatch) return cls return _decorator @cbv_decorator(login_required) class BaseDeleteView(DeleteView): success_url_name = "" pk_obj_name = "" def get_object(self, queryset=None): obj = super(BaseDeleteView, self).get_object(queryset=queryset) if not self.request.user.has_perm("formly.delete_object", obj=obj): raise PermissionDenied() return obj def get_template_names(self): names = super(BaseDeleteView, self).get_template_names() return [ name.replace("formly/", "formly/design/") for name in names ] def get_success_url(self): kwargs = {} if self.pk_obj_name: kwargs["pk"] = getattr(self.object, self.pk_obj_name).pk return reverse(self.success_url_name, kwargs=kwargs) <commit_msg>Use modern login required mixin<commit_after>
from django.contrib.auth.mixins import LoginRequiredMixin from django.core.exceptions import PermissionDenied from django.urls import reverse from django.views.generic import DeleteView class BaseDeleteView(LoginRequiredMixin, DeleteView): success_url_name = "" pk_obj_name = "" def get_object(self, queryset=None): obj = super(BaseDeleteView, self).get_object(queryset=queryset) if not self.request.user.has_perm("formly.delete_object", obj=obj): raise PermissionDenied() return obj def get_template_names(self): names = super(BaseDeleteView, self).get_template_names() return [ name.replace("formly/", "formly/design/") for name in names ] def get_success_url(self): kwargs = {} if self.pk_obj_name: kwargs["pk"] = getattr(self.object, self.pk_obj_name).pk return reverse(self.success_url_name, kwargs=kwargs)
from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.urls import reverse from django.utils.decorators import method_decorator from django.views.generic import DeleteView def cbv_decorator(decorator): def _decorator(cls): cls.dispatch = method_decorator(decorator)(cls.dispatch) return cls return _decorator @cbv_decorator(login_required) class BaseDeleteView(DeleteView): success_url_name = "" pk_obj_name = "" def get_object(self, queryset=None): obj = super(BaseDeleteView, self).get_object(queryset=queryset) if not self.request.user.has_perm("formly.delete_object", obj=obj): raise PermissionDenied() return obj def get_template_names(self): names = super(BaseDeleteView, self).get_template_names() return [ name.replace("formly/", "formly/design/") for name in names ] def get_success_url(self): kwargs = {} if self.pk_obj_name: kwargs["pk"] = getattr(self.object, self.pk_obj_name).pk return reverse(self.success_url_name, kwargs=kwargs) Use modern login required mixinfrom django.contrib.auth.mixins import LoginRequiredMixin from django.core.exceptions import PermissionDenied from django.urls import reverse from django.views.generic import DeleteView class BaseDeleteView(LoginRequiredMixin, DeleteView): success_url_name = "" pk_obj_name = "" def get_object(self, queryset=None): obj = super(BaseDeleteView, self).get_object(queryset=queryset) if not self.request.user.has_perm("formly.delete_object", obj=obj): raise PermissionDenied() return obj def get_template_names(self): names = super(BaseDeleteView, self).get_template_names() return [ name.replace("formly/", "formly/design/") for name in names ] def get_success_url(self): kwargs = {} if self.pk_obj_name: kwargs["pk"] = getattr(self.object, self.pk_obj_name).pk return reverse(self.success_url_name, kwargs=kwargs)
<commit_before>from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.urls import reverse from django.utils.decorators import method_decorator from django.views.generic import DeleteView def cbv_decorator(decorator): def _decorator(cls): cls.dispatch = method_decorator(decorator)(cls.dispatch) return cls return _decorator @cbv_decorator(login_required) class BaseDeleteView(DeleteView): success_url_name = "" pk_obj_name = "" def get_object(self, queryset=None): obj = super(BaseDeleteView, self).get_object(queryset=queryset) if not self.request.user.has_perm("formly.delete_object", obj=obj): raise PermissionDenied() return obj def get_template_names(self): names = super(BaseDeleteView, self).get_template_names() return [ name.replace("formly/", "formly/design/") for name in names ] def get_success_url(self): kwargs = {} if self.pk_obj_name: kwargs["pk"] = getattr(self.object, self.pk_obj_name).pk return reverse(self.success_url_name, kwargs=kwargs) <commit_msg>Use modern login required mixin<commit_after>from django.contrib.auth.mixins import LoginRequiredMixin from django.core.exceptions import PermissionDenied from django.urls import reverse from django.views.generic import DeleteView class BaseDeleteView(LoginRequiredMixin, DeleteView): success_url_name = "" pk_obj_name = "" def get_object(self, queryset=None): obj = super(BaseDeleteView, self).get_object(queryset=queryset) if not self.request.user.has_perm("formly.delete_object", obj=obj): raise PermissionDenied() return obj def get_template_names(self): names = super(BaseDeleteView, self).get_template_names() return [ name.replace("formly/", "formly/design/") for name in names ] def get_success_url(self): kwargs = {} if self.pk_obj_name: kwargs["pk"] = getattr(self.object, self.pk_obj_name).pk return reverse(self.success_url_name, kwargs=kwargs)
9294f54822d9c73b27cd225fa318c3119a999e4a
pylearn2/training_algorithms/training_algorithm.py
pylearn2/training_algorithms/training_algorithm.py
class TrainingAlgorithm(object): """ An abstract superclass that defines the interface of training algorithms. """ def setup(self, model): """ Initialize the given training algorithm. Parameters ---------- model : object Object that implements the Model interface defined in `pylearn2.models`. Notes ----- Called by the training script prior to any calls involving data. This is a good place to compile theano functions for doing learning. """ self.model = model def train(self, dataset): """ Performs some amount of training, generally one "epoch" of online learning Parameters ---------- dataset : object Object implementing the dataset interface defined in `pylearn2.datasets.dataset.Dataset`. Returns ------- status : bool `True` if the algorithm wishes to continue for another epoch. `False` if the algorithm has converged. """ raise NotImplementedError()
class TrainingAlgorithm(object): """ An abstract superclass that defines the interface of training algorithms. """ def setup(self, model, dataset): """ Initialize the given training algorithm. Parameters ---------- model : object Object that implements the Model interface defined in `pylearn2.models`. dataset : object Object that implements the Dataset interface defined in `pylearn2.datasets`. Notes ----- Called by the training script prior to any calls involving data. This is a good place to compile theano functions for doing learning. """ self.model = model def train(self, dataset): """ Performs some amount of training, generally one "epoch" of online learning Parameters ---------- dataset : object Object implementing the dataset interface defined in `pylearn2.datasets.dataset.Dataset`. Returns ------- status : bool `True` if the algorithm wishes to continue for another epoch. `False` if the algorithm has converged. """ raise NotImplementedError()
Make TrainingAlgorithm interface to respect reality.
Make TrainingAlgorithm interface to respect reality.
Python
bsd-3-clause
TNick/pylearn2,caidongyun/pylearn2,alexjc/pylearn2,cosmoharrigan/pylearn2,mclaughlin6464/pylearn2,alexjc/pylearn2,abergeron/pylearn2,kastnerkyle/pylearn2,chrish42/pylearn,pombredanne/pylearn2,JesseLivezey/pylearn2,lamblin/pylearn2,kose-y/pylearn2,msingh172/pylearn2,se4u/pylearn2,lancezlin/pylearn2,w1kke/pylearn2,fulmicoton/pylearn2,ddboline/pylearn2,mkraemer67/pylearn2,shiquanwang/pylearn2,CIFASIS/pylearn2,CIFASIS/pylearn2,Refefer/pylearn2,bartvm/pylearn2,lunyang/pylearn2,kastnerkyle/pylearn2,junbochen/pylearn2,jeremyfix/pylearn2,junbochen/pylearn2,msingh172/pylearn2,aalmah/pylearn2,lancezlin/pylearn2,sandeepkbhat/pylearn2,goodfeli/pylearn2,cosmoharrigan/pylearn2,hantek/pylearn2,lunyang/pylearn2,bartvm/pylearn2,mclaughlin6464/pylearn2,chrish42/pylearn,daemonmaker/pylearn2,JesseLivezey/plankton,Refefer/pylearn2,lamblin/pylearn2,ddboline/pylearn2,skearnes/pylearn2,KennethPierce/pylearnk,pkainz/pylearn2,w1kke/pylearn2,cosmoharrigan/pylearn2,daemonmaker/pylearn2,kose-y/pylearn2,w1kke/pylearn2,chrish42/pylearn,matrogers/pylearn2,se4u/pylearn2,fyffyt/pylearn2,lunyang/pylearn2,goodfeli/pylearn2,w1kke/pylearn2,ddboline/pylearn2,fyffyt/pylearn2,kastnerkyle/pylearn2,matrogers/pylearn2,fyffyt/pylearn2,TNick/pylearn2,fulmicoton/pylearn2,lamblin/pylearn2,aalmah/pylearn2,Refefer/pylearn2,jeremyfix/pylearn2,hyqneuron/pylearn2-maxsom,fishcorn/pylearn2,woozzu/pylearn2,JesseLivezey/pylearn2,skearnes/pylearn2,daemonmaker/pylearn2,theoryno3/pylearn2,junbochen/pylearn2,pombredanne/pylearn2,daemonmaker/pylearn2,woozzu/pylearn2,KennethPierce/pylearnk,se4u/pylearn2,pkainz/pylearn2,bartvm/pylearn2,KennethPierce/pylearnk,jeremyfix/pylearn2,nouiz/pylearn2,JesseLivezey/plankton,msingh172/pylearn2,alexjc/pylearn2,aalmah/pylearn2,lamblin/pylearn2,ashhher3/pylearn2,CIFASIS/pylearn2,lunyang/pylearn2,mkraemer67/pylearn2,se4u/pylearn2,cosmoharrigan/pylearn2,pombredanne/pylearn2,hantek/pylearn2,nouiz/pylearn2,hyqneuron/pylearn2-maxsom,goodfeli/pylearn2,lisa-lab/pylearn2,lisa-lab/pylearn2,kose-y/pylearn2,abergeron/pylearn2,fulmicoton/pylearn2,mkraemer67/pylearn2,nouiz/pylearn2,KennethPierce/pylearnk,bartvm/pylearn2,JesseLivezey/pylearn2,sandeepkbhat/pylearn2,fyffyt/pylearn2,abergeron/pylearn2,fulmicoton/pylearn2,abergeron/pylearn2,woozzu/pylearn2,shiquanwang/pylearn2,woozzu/pylearn2,hyqneuron/pylearn2-maxsom,ashhher3/pylearn2,jamessergeant/pylearn2,theoryno3/pylearn2,fishcorn/pylearn2,jamessergeant/pylearn2,mkraemer67/pylearn2,lancezlin/pylearn2,mclaughlin6464/pylearn2,hantek/pylearn2,Refefer/pylearn2,fishcorn/pylearn2,JesseLivezey/pylearn2,jamessergeant/pylearn2,JesseLivezey/plankton,skearnes/pylearn2,jamessergeant/pylearn2,sandeepkbhat/pylearn2,jeremyfix/pylearn2,caidongyun/pylearn2,shiquanwang/pylearn2,TNick/pylearn2,JesseLivezey/plankton,pombredanne/pylearn2,nouiz/pylearn2,theoryno3/pylearn2,caidongyun/pylearn2,lisa-lab/pylearn2,hantek/pylearn2,junbochen/pylearn2,pkainz/pylearn2,ddboline/pylearn2,caidongyun/pylearn2,mclaughlin6464/pylearn2,hyqneuron/pylearn2-maxsom,ashhher3/pylearn2,theoryno3/pylearn2,sandeepkbhat/pylearn2,ashhher3/pylearn2,kastnerkyle/pylearn2,kose-y/pylearn2,pkainz/pylearn2,shiquanwang/pylearn2,skearnes/pylearn2,matrogers/pylearn2,chrish42/pylearn,msingh172/pylearn2,fishcorn/pylearn2,aalmah/pylearn2,lisa-lab/pylearn2,matrogers/pylearn2,TNick/pylearn2,goodfeli/pylearn2,CIFASIS/pylearn2,alexjc/pylearn2,lancezlin/pylearn2
class TrainingAlgorithm(object): """ An abstract superclass that defines the interface of training algorithms. """ def setup(self, model): """ Initialize the given training algorithm. Parameters ---------- model : object Object that implements the Model interface defined in `pylearn2.models`. Notes ----- Called by the training script prior to any calls involving data. This is a good place to compile theano functions for doing learning. """ self.model = model def train(self, dataset): """ Performs some amount of training, generally one "epoch" of online learning Parameters ---------- dataset : object Object implementing the dataset interface defined in `pylearn2.datasets.dataset.Dataset`. Returns ------- status : bool `True` if the algorithm wishes to continue for another epoch. `False` if the algorithm has converged. """ raise NotImplementedError() Make TrainingAlgorithm interface to respect reality.
class TrainingAlgorithm(object): """ An abstract superclass that defines the interface of training algorithms. """ def setup(self, model, dataset): """ Initialize the given training algorithm. Parameters ---------- model : object Object that implements the Model interface defined in `pylearn2.models`. dataset : object Object that implements the Dataset interface defined in `pylearn2.datasets`. Notes ----- Called by the training script prior to any calls involving data. This is a good place to compile theano functions for doing learning. """ self.model = model def train(self, dataset): """ Performs some amount of training, generally one "epoch" of online learning Parameters ---------- dataset : object Object implementing the dataset interface defined in `pylearn2.datasets.dataset.Dataset`. Returns ------- status : bool `True` if the algorithm wishes to continue for another epoch. `False` if the algorithm has converged. """ raise NotImplementedError()
<commit_before>class TrainingAlgorithm(object): """ An abstract superclass that defines the interface of training algorithms. """ def setup(self, model): """ Initialize the given training algorithm. Parameters ---------- model : object Object that implements the Model interface defined in `pylearn2.models`. Notes ----- Called by the training script prior to any calls involving data. This is a good place to compile theano functions for doing learning. """ self.model = model def train(self, dataset): """ Performs some amount of training, generally one "epoch" of online learning Parameters ---------- dataset : object Object implementing the dataset interface defined in `pylearn2.datasets.dataset.Dataset`. Returns ------- status : bool `True` if the algorithm wishes to continue for another epoch. `False` if the algorithm has converged. """ raise NotImplementedError() <commit_msg>Make TrainingAlgorithm interface to respect reality.<commit_after>
class TrainingAlgorithm(object): """ An abstract superclass that defines the interface of training algorithms. """ def setup(self, model, dataset): """ Initialize the given training algorithm. Parameters ---------- model : object Object that implements the Model interface defined in `pylearn2.models`. dataset : object Object that implements the Dataset interface defined in `pylearn2.datasets`. Notes ----- Called by the training script prior to any calls involving data. This is a good place to compile theano functions for doing learning. """ self.model = model def train(self, dataset): """ Performs some amount of training, generally one "epoch" of online learning Parameters ---------- dataset : object Object implementing the dataset interface defined in `pylearn2.datasets.dataset.Dataset`. Returns ------- status : bool `True` if the algorithm wishes to continue for another epoch. `False` if the algorithm has converged. """ raise NotImplementedError()
class TrainingAlgorithm(object): """ An abstract superclass that defines the interface of training algorithms. """ def setup(self, model): """ Initialize the given training algorithm. Parameters ---------- model : object Object that implements the Model interface defined in `pylearn2.models`. Notes ----- Called by the training script prior to any calls involving data. This is a good place to compile theano functions for doing learning. """ self.model = model def train(self, dataset): """ Performs some amount of training, generally one "epoch" of online learning Parameters ---------- dataset : object Object implementing the dataset interface defined in `pylearn2.datasets.dataset.Dataset`. Returns ------- status : bool `True` if the algorithm wishes to continue for another epoch. `False` if the algorithm has converged. """ raise NotImplementedError() Make TrainingAlgorithm interface to respect reality.class TrainingAlgorithm(object): """ An abstract superclass that defines the interface of training algorithms. """ def setup(self, model, dataset): """ Initialize the given training algorithm. Parameters ---------- model : object Object that implements the Model interface defined in `pylearn2.models`. dataset : object Object that implements the Dataset interface defined in `pylearn2.datasets`. Notes ----- Called by the training script prior to any calls involving data. This is a good place to compile theano functions for doing learning. """ self.model = model def train(self, dataset): """ Performs some amount of training, generally one "epoch" of online learning Parameters ---------- dataset : object Object implementing the dataset interface defined in `pylearn2.datasets.dataset.Dataset`. Returns ------- status : bool `True` if the algorithm wishes to continue for another epoch. `False` if the algorithm has converged. """ raise NotImplementedError()
<commit_before>class TrainingAlgorithm(object): """ An abstract superclass that defines the interface of training algorithms. """ def setup(self, model): """ Initialize the given training algorithm. Parameters ---------- model : object Object that implements the Model interface defined in `pylearn2.models`. Notes ----- Called by the training script prior to any calls involving data. This is a good place to compile theano functions for doing learning. """ self.model = model def train(self, dataset): """ Performs some amount of training, generally one "epoch" of online learning Parameters ---------- dataset : object Object implementing the dataset interface defined in `pylearn2.datasets.dataset.Dataset`. Returns ------- status : bool `True` if the algorithm wishes to continue for another epoch. `False` if the algorithm has converged. """ raise NotImplementedError() <commit_msg>Make TrainingAlgorithm interface to respect reality.<commit_after>class TrainingAlgorithm(object): """ An abstract superclass that defines the interface of training algorithms. """ def setup(self, model, dataset): """ Initialize the given training algorithm. Parameters ---------- model : object Object that implements the Model interface defined in `pylearn2.models`. dataset : object Object that implements the Dataset interface defined in `pylearn2.datasets`. Notes ----- Called by the training script prior to any calls involving data. This is a good place to compile theano functions for doing learning. """ self.model = model def train(self, dataset): """ Performs some amount of training, generally one "epoch" of online learning Parameters ---------- dataset : object Object implementing the dataset interface defined in `pylearn2.datasets.dataset.Dataset`. Returns ------- status : bool `True` if the algorithm wishes to continue for another epoch. `False` if the algorithm has converged. """ raise NotImplementedError()
98ed31aa995bfdf08b2b069c00ecc0d0b0b29b90
twitter/endpoints_v1_1.py
twitter/endpoints_v1_1.py
""" API Mapping for Twitter API 1.1 """ mapping_table = { 'content_type': 'application/json', 'path_prefix': '/1.1', 'search_tweets' : { 'path': '/search/tweets.json', 'valid_params': ['q'] }, }
""" API Mapping for Twitter API 1.1 """ mapping_table = { 'content_type': 'application/json', 'path_prefix': '/1.1', 'search_tweets' : { 'path': '/search/tweets.json', 'valid_params': ['q'], }, 'show_status' : { 'path': '/statuses/show.json', 'valid_params': ['id'], }, }
Add method to show a status by id.
Add method to show a status by id.
Python
mit
alexcchan/twitter
""" API Mapping for Twitter API 1.1 """ mapping_table = { 'content_type': 'application/json', 'path_prefix': '/1.1', 'search_tweets' : { 'path': '/search/tweets.json', 'valid_params': ['q'] }, } Add method to show a status by id.
""" API Mapping for Twitter API 1.1 """ mapping_table = { 'content_type': 'application/json', 'path_prefix': '/1.1', 'search_tweets' : { 'path': '/search/tweets.json', 'valid_params': ['q'], }, 'show_status' : { 'path': '/statuses/show.json', 'valid_params': ['id'], }, }
<commit_before>""" API Mapping for Twitter API 1.1 """ mapping_table = { 'content_type': 'application/json', 'path_prefix': '/1.1', 'search_tweets' : { 'path': '/search/tweets.json', 'valid_params': ['q'] }, } <commit_msg>Add method to show a status by id.<commit_after>
""" API Mapping for Twitter API 1.1 """ mapping_table = { 'content_type': 'application/json', 'path_prefix': '/1.1', 'search_tweets' : { 'path': '/search/tweets.json', 'valid_params': ['q'], }, 'show_status' : { 'path': '/statuses/show.json', 'valid_params': ['id'], }, }
""" API Mapping for Twitter API 1.1 """ mapping_table = { 'content_type': 'application/json', 'path_prefix': '/1.1', 'search_tweets' : { 'path': '/search/tweets.json', 'valid_params': ['q'] }, } Add method to show a status by id.""" API Mapping for Twitter API 1.1 """ mapping_table = { 'content_type': 'application/json', 'path_prefix': '/1.1', 'search_tweets' : { 'path': '/search/tweets.json', 'valid_params': ['q'], }, 'show_status' : { 'path': '/statuses/show.json', 'valid_params': ['id'], }, }
<commit_before>""" API Mapping for Twitter API 1.1 """ mapping_table = { 'content_type': 'application/json', 'path_prefix': '/1.1', 'search_tweets' : { 'path': '/search/tweets.json', 'valid_params': ['q'] }, } <commit_msg>Add method to show a status by id.<commit_after>""" API Mapping for Twitter API 1.1 """ mapping_table = { 'content_type': 'application/json', 'path_prefix': '/1.1', 'search_tweets' : { 'path': '/search/tweets.json', 'valid_params': ['q'], }, 'show_status' : { 'path': '/statuses/show.json', 'valid_params': ['id'], }, }
5383db76e043057217dfbebd2dd484f5b6418260
app/models.py
app/models.py
from app import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) posts = db.relationship('Post', backref='author', lazy='dynamic') def __repr__(self): return '<User %r>' % (self.name) class Post(db.Model): id = db.Column(db.Integer, primary_key = True) body = db.Column(db.String(140)) timestamp = db.Column(db.DateTime) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __repr__(self): return '<Post %r>' % (self.body)
from app import db # Define char limits allowed in names and passwords user_limits = {'name': 16, 'email': 50} # Define char limits allowed in titles and bodies of posts post_limits = {'title': 1000, 'body': 30000} # of pages page_limits = {'title': 1000, 'body': 75000} class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(user_limits['name']), index=True, unique=True) email = db.Column(db.String(user_limits['email']), index=True, unique=True) posts = db.relationship('Post', backref='author', lazy='dynamic') def __repr__(self): return '<User %r>' % (self.name) class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(post_limits['title'])) body = db.Column(db.String(post_limits['body'])) timestamp = db.Column(db.DateTime) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __repr__(self): return '<Post %r>' % (self.body) class Page(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(post_limits['title'])) body = db.Column(db.String(post_limits['body'])) timestamp = db.Column(db.DateTime) def __repr__(self): return '<Page %r>' % (self.body)
Add Page class and restructure hard-coded character limits
Add Page class and restructure hard-coded character limits
Python
agpl-3.0
lasa/website,lasa/website,lasa/website
from app import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) posts = db.relationship('Post', backref='author', lazy='dynamic') def __repr__(self): return '<User %r>' % (self.name) class Post(db.Model): id = db.Column(db.Integer, primary_key = True) body = db.Column(db.String(140)) timestamp = db.Column(db.DateTime) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __repr__(self): return '<Post %r>' % (self.body) Add Page class and restructure hard-coded character limits
from app import db # Define char limits allowed in names and passwords user_limits = {'name': 16, 'email': 50} # Define char limits allowed in titles and bodies of posts post_limits = {'title': 1000, 'body': 30000} # of pages page_limits = {'title': 1000, 'body': 75000} class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(user_limits['name']), index=True, unique=True) email = db.Column(db.String(user_limits['email']), index=True, unique=True) posts = db.relationship('Post', backref='author', lazy='dynamic') def __repr__(self): return '<User %r>' % (self.name) class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(post_limits['title'])) body = db.Column(db.String(post_limits['body'])) timestamp = db.Column(db.DateTime) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __repr__(self): return '<Post %r>' % (self.body) class Page(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(post_limits['title'])) body = db.Column(db.String(post_limits['body'])) timestamp = db.Column(db.DateTime) def __repr__(self): return '<Page %r>' % (self.body)
<commit_before>from app import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) posts = db.relationship('Post', backref='author', lazy='dynamic') def __repr__(self): return '<User %r>' % (self.name) class Post(db.Model): id = db.Column(db.Integer, primary_key = True) body = db.Column(db.String(140)) timestamp = db.Column(db.DateTime) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __repr__(self): return '<Post %r>' % (self.body) <commit_msg>Add Page class and restructure hard-coded character limits<commit_after>
from app import db # Define char limits allowed in names and passwords user_limits = {'name': 16, 'email': 50} # Define char limits allowed in titles and bodies of posts post_limits = {'title': 1000, 'body': 30000} # of pages page_limits = {'title': 1000, 'body': 75000} class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(user_limits['name']), index=True, unique=True) email = db.Column(db.String(user_limits['email']), index=True, unique=True) posts = db.relationship('Post', backref='author', lazy='dynamic') def __repr__(self): return '<User %r>' % (self.name) class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(post_limits['title'])) body = db.Column(db.String(post_limits['body'])) timestamp = db.Column(db.DateTime) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __repr__(self): return '<Post %r>' % (self.body) class Page(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(post_limits['title'])) body = db.Column(db.String(post_limits['body'])) timestamp = db.Column(db.DateTime) def __repr__(self): return '<Page %r>' % (self.body)
from app import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) posts = db.relationship('Post', backref='author', lazy='dynamic') def __repr__(self): return '<User %r>' % (self.name) class Post(db.Model): id = db.Column(db.Integer, primary_key = True) body = db.Column(db.String(140)) timestamp = db.Column(db.DateTime) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __repr__(self): return '<Post %r>' % (self.body) Add Page class and restructure hard-coded character limitsfrom app import db # Define char limits allowed in names and passwords user_limits = {'name': 16, 'email': 50} # Define char limits allowed in titles and bodies of posts post_limits = {'title': 1000, 'body': 30000} # of pages page_limits = {'title': 1000, 'body': 75000} class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(user_limits['name']), index=True, unique=True) email = db.Column(db.String(user_limits['email']), index=True, unique=True) posts = db.relationship('Post', backref='author', lazy='dynamic') def __repr__(self): return '<User %r>' % (self.name) class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(post_limits['title'])) body = db.Column(db.String(post_limits['body'])) timestamp = db.Column(db.DateTime) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __repr__(self): return '<Post %r>' % (self.body) class Page(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(post_limits['title'])) body = db.Column(db.String(post_limits['body'])) timestamp = db.Column(db.DateTime) def __repr__(self): return '<Page %r>' % (self.body)
<commit_before>from app import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) posts = db.relationship('Post', backref='author', lazy='dynamic') def __repr__(self): return '<User %r>' % (self.name) class Post(db.Model): id = db.Column(db.Integer, primary_key = True) body = db.Column(db.String(140)) timestamp = db.Column(db.DateTime) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __repr__(self): return '<Post %r>' % (self.body) <commit_msg>Add Page class and restructure hard-coded character limits<commit_after>from app import db # Define char limits allowed in names and passwords user_limits = {'name': 16, 'email': 50} # Define char limits allowed in titles and bodies of posts post_limits = {'title': 1000, 'body': 30000} # of pages page_limits = {'title': 1000, 'body': 75000} class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(user_limits['name']), index=True, unique=True) email = db.Column(db.String(user_limits['email']), index=True, unique=True) posts = db.relationship('Post', backref='author', lazy='dynamic') def __repr__(self): return '<User %r>' % (self.name) class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(post_limits['title'])) body = db.Column(db.String(post_limits['body'])) timestamp = db.Column(db.DateTime) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __repr__(self): return '<Post %r>' % (self.body) class Page(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(post_limits['title'])) body = db.Column(db.String(post_limits['body'])) timestamp = db.Column(db.DateTime) def __repr__(self): return '<Page %r>' % (self.body)
2d1290b7a4ba750611a23fe38b7d028f2f0db030
txircd/modules/cmd_user.py
txircd/modules/cmd_user.py
from twisted.words.protocols import irc from txircd.modbase import Command import string class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0][:12]) if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "USER": UserCommand() } } def cleanup(self): del self.ircd.commands["USER"]
from twisted.words.protocols import irc from txircd.modbase import Command import string class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":You may not reregister") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0][:12]) if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "USER": UserCommand() } } def cleanup(self): del self.ircd.commands["USER"]
Fix message with 462 numeric
Fix message with 462 numeric
Python
bsd-3-clause
ElementalAlchemist/txircd,DesertBus/txircd,Heufneutje/txircd
from twisted.words.protocols import irc from txircd.modbase import Command import string class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0][:12]) if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "USER": UserCommand() } } def cleanup(self): del self.ircd.commands["USER"]Fix message with 462 numeric
from twisted.words.protocols import irc from txircd.modbase import Command import string class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":You may not reregister") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0][:12]) if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "USER": UserCommand() } } def cleanup(self): del self.ircd.commands["USER"]
<commit_before>from twisted.words.protocols import irc from txircd.modbase import Command import string class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0][:12]) if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "USER": UserCommand() } } def cleanup(self): del self.ircd.commands["USER"]<commit_msg>Fix message with 462 numeric<commit_after>
from twisted.words.protocols import irc from txircd.modbase import Command import string class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":You may not reregister") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0][:12]) if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "USER": UserCommand() } } def cleanup(self): del self.ircd.commands["USER"]
from twisted.words.protocols import irc from txircd.modbase import Command import string class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0][:12]) if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "USER": UserCommand() } } def cleanup(self): del self.ircd.commands["USER"]Fix message with 462 numericfrom twisted.words.protocols import irc from txircd.modbase import Command import string class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":You may not reregister") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0][:12]) if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "USER": UserCommand() } } def cleanup(self): del self.ircd.commands["USER"]
<commit_before>from twisted.words.protocols import irc from txircd.modbase import Command import string class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0][:12]) if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "USER": UserCommand() } } def cleanup(self): del self.ircd.commands["USER"]<commit_msg>Fix message with 462 numeric<commit_after>from twisted.words.protocols import irc from txircd.modbase import Command import string class UserCommand(Command): def onUse(self, user, data): if not user.username: user.registered -= 1 user.username = data["ident"] user.realname = data["gecos"] if user.registered == 0: user.register() def processParams(self, user, params): if user.registered == 0: user.sendMessage(irc.ERR_ALREADYREGISTRED, ":You may not reregister") return {} if params and len(params) < 4: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters") return {} ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0][:12]) if not ident: user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid") return {} return { "user": user, "ident": ident, "gecos": params[3] } class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "commands": { "USER": UserCommand() } } def cleanup(self): del self.ircd.commands["USER"]
201d8d532b907d97823c2dbf61fdd6e75b8eb615
form_designer/contrib/cms_plugins/form_designer_form/cms_plugins.py
form_designer/contrib/cms_plugins/form_designer_form/cms_plugins.py
from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDesignerPlugin(CMSPluginBase): model = CMSFormDefinition module = _('Form Designer') name = _('Form') admin_preview = False render_template = False def render(self, context, instance, placeholder): if instance.form_definition.form_template_name: self.render_template = instance.form_definition.form_template_name else: self.render_template = settings.DEFAULT_FORM_TEMPLATE # Redirection does not work with CMS plugin, hence disable: return process_form(context['request'], instance.form_definition, context, disable_redirection=True, push_messages=False) plugin_pool.register_plugin(FormDesignerPlugin)
from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDesignerPlugin(CMSPluginBase): model = CMSFormDefinition module = _('Form Designer') name = _('Form') admin_preview = False render_template = False cache = False # New in version 3.0. see http://django-cms.readthedocs.org/en/latest/advanced/caching.html def render(self, context, instance, placeholder): if instance.form_definition.form_template_name: self.render_template = instance.form_definition.form_template_name else: self.render_template = settings.DEFAULT_FORM_TEMPLATE # Redirection does not work with CMS plugin, hence disable: return process_form(context['request'], instance.form_definition, context, disable_redirection=True, push_messages=False) plugin_pool.register_plugin(FormDesignerPlugin)
Disable caching for CMS plugin.
Disable caching for CMS plugin. CSRF tokens may get cached otherwise. This is for compatibility with Django CMS 3.0+.
Python
bsd-3-clause
andersinno/django-form-designer-ai,andersinno/django-form-designer,kcsry/django-form-designer,andersinno/django-form-designer,kcsry/django-form-designer,andersinno/django-form-designer-ai
from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDesignerPlugin(CMSPluginBase): model = CMSFormDefinition module = _('Form Designer') name = _('Form') admin_preview = False render_template = False def render(self, context, instance, placeholder): if instance.form_definition.form_template_name: self.render_template = instance.form_definition.form_template_name else: self.render_template = settings.DEFAULT_FORM_TEMPLATE # Redirection does not work with CMS plugin, hence disable: return process_form(context['request'], instance.form_definition, context, disable_redirection=True, push_messages=False) plugin_pool.register_plugin(FormDesignerPlugin) Disable caching for CMS plugin. CSRF tokens may get cached otherwise. This is for compatibility with Django CMS 3.0+.
from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDesignerPlugin(CMSPluginBase): model = CMSFormDefinition module = _('Form Designer') name = _('Form') admin_preview = False render_template = False cache = False # New in version 3.0. see http://django-cms.readthedocs.org/en/latest/advanced/caching.html def render(self, context, instance, placeholder): if instance.form_definition.form_template_name: self.render_template = instance.form_definition.form_template_name else: self.render_template = settings.DEFAULT_FORM_TEMPLATE # Redirection does not work with CMS plugin, hence disable: return process_form(context['request'], instance.form_definition, context, disable_redirection=True, push_messages=False) plugin_pool.register_plugin(FormDesignerPlugin)
<commit_before>from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDesignerPlugin(CMSPluginBase): model = CMSFormDefinition module = _('Form Designer') name = _('Form') admin_preview = False render_template = False def render(self, context, instance, placeholder): if instance.form_definition.form_template_name: self.render_template = instance.form_definition.form_template_name else: self.render_template = settings.DEFAULT_FORM_TEMPLATE # Redirection does not work with CMS plugin, hence disable: return process_form(context['request'], instance.form_definition, context, disable_redirection=True, push_messages=False) plugin_pool.register_plugin(FormDesignerPlugin) <commit_msg>Disable caching for CMS plugin. CSRF tokens may get cached otherwise. This is for compatibility with Django CMS 3.0+.<commit_after>
from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDesignerPlugin(CMSPluginBase): model = CMSFormDefinition module = _('Form Designer') name = _('Form') admin_preview = False render_template = False cache = False # New in version 3.0. see http://django-cms.readthedocs.org/en/latest/advanced/caching.html def render(self, context, instance, placeholder): if instance.form_definition.form_template_name: self.render_template = instance.form_definition.form_template_name else: self.render_template = settings.DEFAULT_FORM_TEMPLATE # Redirection does not work with CMS plugin, hence disable: return process_form(context['request'], instance.form_definition, context, disable_redirection=True, push_messages=False) plugin_pool.register_plugin(FormDesignerPlugin)
from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDesignerPlugin(CMSPluginBase): model = CMSFormDefinition module = _('Form Designer') name = _('Form') admin_preview = False render_template = False def render(self, context, instance, placeholder): if instance.form_definition.form_template_name: self.render_template = instance.form_definition.form_template_name else: self.render_template = settings.DEFAULT_FORM_TEMPLATE # Redirection does not work with CMS plugin, hence disable: return process_form(context['request'], instance.form_definition, context, disable_redirection=True, push_messages=False) plugin_pool.register_plugin(FormDesignerPlugin) Disable caching for CMS plugin. CSRF tokens may get cached otherwise. This is for compatibility with Django CMS 3.0+.from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDesignerPlugin(CMSPluginBase): model = CMSFormDefinition module = _('Form Designer') name = _('Form') admin_preview = False render_template = False cache = False # New in version 3.0. see http://django-cms.readthedocs.org/en/latest/advanced/caching.html def render(self, context, instance, placeholder): if instance.form_definition.form_template_name: self.render_template = instance.form_definition.form_template_name else: self.render_template = settings.DEFAULT_FORM_TEMPLATE # Redirection does not work with CMS plugin, hence disable: return process_form(context['request'], instance.form_definition, context, disable_redirection=True, push_messages=False) plugin_pool.register_plugin(FormDesignerPlugin)
<commit_before>from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDesignerPlugin(CMSPluginBase): model = CMSFormDefinition module = _('Form Designer') name = _('Form') admin_preview = False render_template = False def render(self, context, instance, placeholder): if instance.form_definition.form_template_name: self.render_template = instance.form_definition.form_template_name else: self.render_template = settings.DEFAULT_FORM_TEMPLATE # Redirection does not work with CMS plugin, hence disable: return process_form(context['request'], instance.form_definition, context, disable_redirection=True, push_messages=False) plugin_pool.register_plugin(FormDesignerPlugin) <commit_msg>Disable caching for CMS plugin. CSRF tokens may get cached otherwise. This is for compatibility with Django CMS 3.0+.<commit_after>from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDesignerPlugin(CMSPluginBase): model = CMSFormDefinition module = _('Form Designer') name = _('Form') admin_preview = False render_template = False cache = False # New in version 3.0. see http://django-cms.readthedocs.org/en/latest/advanced/caching.html def render(self, context, instance, placeholder): if instance.form_definition.form_template_name: self.render_template = instance.form_definition.form_template_name else: self.render_template = settings.DEFAULT_FORM_TEMPLATE # Redirection does not work with CMS plugin, hence disable: return process_form(context['request'], instance.form_definition, context, disable_redirection=True, push_messages=False) plugin_pool.register_plugin(FormDesignerPlugin)
d030e9bfaf8cd4f83d0db7728f4f546c48bd8934
harness/ext/SciKit.py
harness/ext/SciKit.py
# coding: utf-8 # A jinja extension for the harness # In[9]: try: from .base import HarnessExtension except: from base import HarnessExtension import pandas, sklearn.model_selection as model_selection from toolz.curried import first # In[11]: get_ipython().magic('pinfo2 model_selection.ShuffleSplit') # In[10]: class SciKitExtension(HarnessExtension): alias = 'sklearn' def keywords(self, dataframe): return { 'X': lambda: dataframe.values, 'y': lambda: dataframe.index.get_level_values(dataframe.feature_level) if dataframe.feature_level else None, } def pipe(self, dataframe, attr): self.module_ = dataframe.estimator return super().pipe(dataframe, attr) def callback(self, dataframe, value): if value is dataframe.estimator: return dataframe if isinstance(value, pandas.np.ndarray): return dataframe.__class__( value, index=dataframe.index, feature_level=dataframe.feature_level, ) if isinstance(value, pandas.CategoricalIndex): # new dataframe value = dataframe.set_index(value, append=True) value.index = value.index.reorder_levels([-1, *range( len(dataframe.index.levels) if hasattr(dataframe.index, 'levels') else 1 )]) return value
# coding: utf-8 # A jinja extension for the harness # In[9]: try: from .base import HarnessExtension except: from base import HarnessExtension import pandas, sklearn.model_selection as model_selection from toolz.curried import first # In[10]: class SciKitExtension(HarnessExtension): alias = 'sklearn' def keywords(self, dataframe): return { 'X': lambda: dataframe.values, 'y': lambda: dataframe.index.get_level_values(dataframe.feature_level) if dataframe.feature_level else None, } def pipe(self, dataframe, attr): self.module_ = dataframe.estimator return super().pipe(dataframe, attr) def callback(self, dataframe, value): if value is dataframe.estimator: return dataframe if isinstance(value, pandas.np.ndarray): return dataframe.__class__( value, index=dataframe.index, feature_level=dataframe.feature_level, ) if isinstance(value, pandas.CategoricalIndex): # new dataframe value = dataframe.set_index(value, append=True) value.index = value.index.reorder_levels([-1, *range( len(dataframe.index.levels) if hasattr(dataframe.index, 'levels') else 1 )]) return value
Fix error message in the scikitlearn extension.
Fix error message in the scikitlearn extension.
Python
bsd-3-clause
tonyfast/tidy-harness,tonyfast/tidy-harness
# coding: utf-8 # A jinja extension for the harness # In[9]: try: from .base import HarnessExtension except: from base import HarnessExtension import pandas, sklearn.model_selection as model_selection from toolz.curried import first # In[11]: get_ipython().magic('pinfo2 model_selection.ShuffleSplit') # In[10]: class SciKitExtension(HarnessExtension): alias = 'sklearn' def keywords(self, dataframe): return { 'X': lambda: dataframe.values, 'y': lambda: dataframe.index.get_level_values(dataframe.feature_level) if dataframe.feature_level else None, } def pipe(self, dataframe, attr): self.module_ = dataframe.estimator return super().pipe(dataframe, attr) def callback(self, dataframe, value): if value is dataframe.estimator: return dataframe if isinstance(value, pandas.np.ndarray): return dataframe.__class__( value, index=dataframe.index, feature_level=dataframe.feature_level, ) if isinstance(value, pandas.CategoricalIndex): # new dataframe value = dataframe.set_index(value, append=True) value.index = value.index.reorder_levels([-1, *range( len(dataframe.index.levels) if hasattr(dataframe.index, 'levels') else 1 )]) return value Fix error message in the scikitlearn extension.
# coding: utf-8 # A jinja extension for the harness # In[9]: try: from .base import HarnessExtension except: from base import HarnessExtension import pandas, sklearn.model_selection as model_selection from toolz.curried import first # In[10]: class SciKitExtension(HarnessExtension): alias = 'sklearn' def keywords(self, dataframe): return { 'X': lambda: dataframe.values, 'y': lambda: dataframe.index.get_level_values(dataframe.feature_level) if dataframe.feature_level else None, } def pipe(self, dataframe, attr): self.module_ = dataframe.estimator return super().pipe(dataframe, attr) def callback(self, dataframe, value): if value is dataframe.estimator: return dataframe if isinstance(value, pandas.np.ndarray): return dataframe.__class__( value, index=dataframe.index, feature_level=dataframe.feature_level, ) if isinstance(value, pandas.CategoricalIndex): # new dataframe value = dataframe.set_index(value, append=True) value.index = value.index.reorder_levels([-1, *range( len(dataframe.index.levels) if hasattr(dataframe.index, 'levels') else 1 )]) return value
<commit_before> # coding: utf-8 # A jinja extension for the harness # In[9]: try: from .base import HarnessExtension except: from base import HarnessExtension import pandas, sklearn.model_selection as model_selection from toolz.curried import first # In[11]: get_ipython().magic('pinfo2 model_selection.ShuffleSplit') # In[10]: class SciKitExtension(HarnessExtension): alias = 'sklearn' def keywords(self, dataframe): return { 'X': lambda: dataframe.values, 'y': lambda: dataframe.index.get_level_values(dataframe.feature_level) if dataframe.feature_level else None, } def pipe(self, dataframe, attr): self.module_ = dataframe.estimator return super().pipe(dataframe, attr) def callback(self, dataframe, value): if value is dataframe.estimator: return dataframe if isinstance(value, pandas.np.ndarray): return dataframe.__class__( value, index=dataframe.index, feature_level=dataframe.feature_level, ) if isinstance(value, pandas.CategoricalIndex): # new dataframe value = dataframe.set_index(value, append=True) value.index = value.index.reorder_levels([-1, *range( len(dataframe.index.levels) if hasattr(dataframe.index, 'levels') else 1 )]) return value <commit_msg>Fix error message in the scikitlearn extension.<commit_after>
# coding: utf-8 # A jinja extension for the harness # In[9]: try: from .base import HarnessExtension except: from base import HarnessExtension import pandas, sklearn.model_selection as model_selection from toolz.curried import first # In[10]: class SciKitExtension(HarnessExtension): alias = 'sklearn' def keywords(self, dataframe): return { 'X': lambda: dataframe.values, 'y': lambda: dataframe.index.get_level_values(dataframe.feature_level) if dataframe.feature_level else None, } def pipe(self, dataframe, attr): self.module_ = dataframe.estimator return super().pipe(dataframe, attr) def callback(self, dataframe, value): if value is dataframe.estimator: return dataframe if isinstance(value, pandas.np.ndarray): return dataframe.__class__( value, index=dataframe.index, feature_level=dataframe.feature_level, ) if isinstance(value, pandas.CategoricalIndex): # new dataframe value = dataframe.set_index(value, append=True) value.index = value.index.reorder_levels([-1, *range( len(dataframe.index.levels) if hasattr(dataframe.index, 'levels') else 1 )]) return value
# coding: utf-8 # A jinja extension for the harness # In[9]: try: from .base import HarnessExtension except: from base import HarnessExtension import pandas, sklearn.model_selection as model_selection from toolz.curried import first # In[11]: get_ipython().magic('pinfo2 model_selection.ShuffleSplit') # In[10]: class SciKitExtension(HarnessExtension): alias = 'sklearn' def keywords(self, dataframe): return { 'X': lambda: dataframe.values, 'y': lambda: dataframe.index.get_level_values(dataframe.feature_level) if dataframe.feature_level else None, } def pipe(self, dataframe, attr): self.module_ = dataframe.estimator return super().pipe(dataframe, attr) def callback(self, dataframe, value): if value is dataframe.estimator: return dataframe if isinstance(value, pandas.np.ndarray): return dataframe.__class__( value, index=dataframe.index, feature_level=dataframe.feature_level, ) if isinstance(value, pandas.CategoricalIndex): # new dataframe value = dataframe.set_index(value, append=True) value.index = value.index.reorder_levels([-1, *range( len(dataframe.index.levels) if hasattr(dataframe.index, 'levels') else 1 )]) return value Fix error message in the scikitlearn extension. # coding: utf-8 # A jinja extension for the harness # In[9]: try: from .base import HarnessExtension except: from base import HarnessExtension import pandas, sklearn.model_selection as model_selection from toolz.curried import first # In[10]: class SciKitExtension(HarnessExtension): alias = 'sklearn' def keywords(self, dataframe): return { 'X': lambda: dataframe.values, 'y': lambda: dataframe.index.get_level_values(dataframe.feature_level) if dataframe.feature_level else None, } def pipe(self, dataframe, attr): self.module_ = dataframe.estimator return super().pipe(dataframe, attr) def callback(self, dataframe, value): if value is dataframe.estimator: return dataframe if isinstance(value, pandas.np.ndarray): return dataframe.__class__( value, index=dataframe.index, feature_level=dataframe.feature_level, ) if isinstance(value, pandas.CategoricalIndex): # new dataframe value = dataframe.set_index(value, append=True) value.index = value.index.reorder_levels([-1, *range( len(dataframe.index.levels) if hasattr(dataframe.index, 'levels') else 1 )]) return value
<commit_before> # coding: utf-8 # A jinja extension for the harness # In[9]: try: from .base import HarnessExtension except: from base import HarnessExtension import pandas, sklearn.model_selection as model_selection from toolz.curried import first # In[11]: get_ipython().magic('pinfo2 model_selection.ShuffleSplit') # In[10]: class SciKitExtension(HarnessExtension): alias = 'sklearn' def keywords(self, dataframe): return { 'X': lambda: dataframe.values, 'y': lambda: dataframe.index.get_level_values(dataframe.feature_level) if dataframe.feature_level else None, } def pipe(self, dataframe, attr): self.module_ = dataframe.estimator return super().pipe(dataframe, attr) def callback(self, dataframe, value): if value is dataframe.estimator: return dataframe if isinstance(value, pandas.np.ndarray): return dataframe.__class__( value, index=dataframe.index, feature_level=dataframe.feature_level, ) if isinstance(value, pandas.CategoricalIndex): # new dataframe value = dataframe.set_index(value, append=True) value.index = value.index.reorder_levels([-1, *range( len(dataframe.index.levels) if hasattr(dataframe.index, 'levels') else 1 )]) return value <commit_msg>Fix error message in the scikitlearn extension.<commit_after> # coding: utf-8 # A jinja extension for the harness # In[9]: try: from .base import HarnessExtension except: from base import HarnessExtension import pandas, sklearn.model_selection as model_selection from toolz.curried import first # In[10]: class SciKitExtension(HarnessExtension): alias = 'sklearn' def keywords(self, dataframe): return { 'X': lambda: dataframe.values, 'y': lambda: dataframe.index.get_level_values(dataframe.feature_level) if dataframe.feature_level else None, } def pipe(self, dataframe, attr): self.module_ = dataframe.estimator return super().pipe(dataframe, attr) def callback(self, dataframe, value): if value is dataframe.estimator: return dataframe if isinstance(value, pandas.np.ndarray): return dataframe.__class__( value, index=dataframe.index, feature_level=dataframe.feature_level, ) if isinstance(value, pandas.CategoricalIndex): # new dataframe value = dataframe.set_index(value, append=True) value.index = value.index.reorder_levels([-1, *range( len(dataframe.index.levels) if hasattr(dataframe.index, 'levels') else 1 )]) return value
44e21fa7504a4650eb2db0036a66ecf7b0ab5e5d
d_parser/helpers/re_set.py
d_parser/helpers/re_set.py
# re_set.py # Module for generating regex rules # r1 import re class Ree: float = None number = None page_number = None extract_int = None @staticmethod def init(): Ree._is_float() Ree._is_number() Ree._is_page_number('') Ree._extract_int_compile() @staticmethod def _is_page_number(page_param): Ree.page_number = re.compile('(?P<param>{})=(?P<page>\d+)'.format(page_param)) @staticmethod def _is_float(price_sep=',.'): Ree.float = re.compile('(?P<price>-?\d+([{}]\d+)?)'.format(price_sep)) @staticmethod def _is_number(): Ree.number = re.compile('^\d+$') @staticmethod def _extract_int_compile(): Ree.extract_int = re.compile('^.*?(?P<int>\d+).+$')
# re_set.py # Module for generating regex rules # r1 import re class Ree: float = None number = None page_number = None extract_int = None extract_float = None @staticmethod def init(): Ree._is_float() Ree._is_number() Ree._is_page_number('') Ree._extract_int_compile() Ree._extract_float_compile() @staticmethod def _is_page_number(page_param): Ree.page_number = re.compile('(?P<param>{})=(?P<page>\d+)'.format(page_param)) @staticmethod def _is_float(sep=',.'): Ree.float = re.compile('(?P<float>-?\d+([{}]\d+)?)'.format(sep)) @staticmethod def _is_number(): Ree.number = re.compile('^-?\d+$') @staticmethod def _extract_int_compile(): Ree.extract_int = re.compile('^.*?(?P<int>-?\d+).*$') @staticmethod def _extract_float_compile(sep=',.'): Ree.extract_float = re.compile('^.*?(?P<float>-?\d+([{}]\d+)?).*$'.format(sep))
Add float extractor, fix extractors rules
Add float extractor, fix extractors rules
Python
mit
Holovin/D_GrabDemo
# re_set.py # Module for generating regex rules # r1 import re class Ree: float = None number = None page_number = None extract_int = None @staticmethod def init(): Ree._is_float() Ree._is_number() Ree._is_page_number('') Ree._extract_int_compile() @staticmethod def _is_page_number(page_param): Ree.page_number = re.compile('(?P<param>{})=(?P<page>\d+)'.format(page_param)) @staticmethod def _is_float(price_sep=',.'): Ree.float = re.compile('(?P<price>-?\d+([{}]\d+)?)'.format(price_sep)) @staticmethod def _is_number(): Ree.number = re.compile('^\d+$') @staticmethod def _extract_int_compile(): Ree.extract_int = re.compile('^.*?(?P<int>\d+).+$') Add float extractor, fix extractors rules
# re_set.py # Module for generating regex rules # r1 import re class Ree: float = None number = None page_number = None extract_int = None extract_float = None @staticmethod def init(): Ree._is_float() Ree._is_number() Ree._is_page_number('') Ree._extract_int_compile() Ree._extract_float_compile() @staticmethod def _is_page_number(page_param): Ree.page_number = re.compile('(?P<param>{})=(?P<page>\d+)'.format(page_param)) @staticmethod def _is_float(sep=',.'): Ree.float = re.compile('(?P<float>-?\d+([{}]\d+)?)'.format(sep)) @staticmethod def _is_number(): Ree.number = re.compile('^-?\d+$') @staticmethod def _extract_int_compile(): Ree.extract_int = re.compile('^.*?(?P<int>-?\d+).*$') @staticmethod def _extract_float_compile(sep=',.'): Ree.extract_float = re.compile('^.*?(?P<float>-?\d+([{}]\d+)?).*$'.format(sep))
<commit_before># re_set.py # Module for generating regex rules # r1 import re class Ree: float = None number = None page_number = None extract_int = None @staticmethod def init(): Ree._is_float() Ree._is_number() Ree._is_page_number('') Ree._extract_int_compile() @staticmethod def _is_page_number(page_param): Ree.page_number = re.compile('(?P<param>{})=(?P<page>\d+)'.format(page_param)) @staticmethod def _is_float(price_sep=',.'): Ree.float = re.compile('(?P<price>-?\d+([{}]\d+)?)'.format(price_sep)) @staticmethod def _is_number(): Ree.number = re.compile('^\d+$') @staticmethod def _extract_int_compile(): Ree.extract_int = re.compile('^.*?(?P<int>\d+).+$') <commit_msg>Add float extractor, fix extractors rules<commit_after>
# re_set.py # Module for generating regex rules # r1 import re class Ree: float = None number = None page_number = None extract_int = None extract_float = None @staticmethod def init(): Ree._is_float() Ree._is_number() Ree._is_page_number('') Ree._extract_int_compile() Ree._extract_float_compile() @staticmethod def _is_page_number(page_param): Ree.page_number = re.compile('(?P<param>{})=(?P<page>\d+)'.format(page_param)) @staticmethod def _is_float(sep=',.'): Ree.float = re.compile('(?P<float>-?\d+([{}]\d+)?)'.format(sep)) @staticmethod def _is_number(): Ree.number = re.compile('^-?\d+$') @staticmethod def _extract_int_compile(): Ree.extract_int = re.compile('^.*?(?P<int>-?\d+).*$') @staticmethod def _extract_float_compile(sep=',.'): Ree.extract_float = re.compile('^.*?(?P<float>-?\d+([{}]\d+)?).*$'.format(sep))
# re_set.py # Module for generating regex rules # r1 import re class Ree: float = None number = None page_number = None extract_int = None @staticmethod def init(): Ree._is_float() Ree._is_number() Ree._is_page_number('') Ree._extract_int_compile() @staticmethod def _is_page_number(page_param): Ree.page_number = re.compile('(?P<param>{})=(?P<page>\d+)'.format(page_param)) @staticmethod def _is_float(price_sep=',.'): Ree.float = re.compile('(?P<price>-?\d+([{}]\d+)?)'.format(price_sep)) @staticmethod def _is_number(): Ree.number = re.compile('^\d+$') @staticmethod def _extract_int_compile(): Ree.extract_int = re.compile('^.*?(?P<int>\d+).+$') Add float extractor, fix extractors rules# re_set.py # Module for generating regex rules # r1 import re class Ree: float = None number = None page_number = None extract_int = None extract_float = None @staticmethod def init(): Ree._is_float() Ree._is_number() Ree._is_page_number('') Ree._extract_int_compile() Ree._extract_float_compile() @staticmethod def _is_page_number(page_param): Ree.page_number = re.compile('(?P<param>{})=(?P<page>\d+)'.format(page_param)) @staticmethod def _is_float(sep=',.'): Ree.float = re.compile('(?P<float>-?\d+([{}]\d+)?)'.format(sep)) @staticmethod def _is_number(): Ree.number = re.compile('^-?\d+$') @staticmethod def _extract_int_compile(): Ree.extract_int = re.compile('^.*?(?P<int>-?\d+).*$') @staticmethod def _extract_float_compile(sep=',.'): Ree.extract_float = re.compile('^.*?(?P<float>-?\d+([{}]\d+)?).*$'.format(sep))
<commit_before># re_set.py # Module for generating regex rules # r1 import re class Ree: float = None number = None page_number = None extract_int = None @staticmethod def init(): Ree._is_float() Ree._is_number() Ree._is_page_number('') Ree._extract_int_compile() @staticmethod def _is_page_number(page_param): Ree.page_number = re.compile('(?P<param>{})=(?P<page>\d+)'.format(page_param)) @staticmethod def _is_float(price_sep=',.'): Ree.float = re.compile('(?P<price>-?\d+([{}]\d+)?)'.format(price_sep)) @staticmethod def _is_number(): Ree.number = re.compile('^\d+$') @staticmethod def _extract_int_compile(): Ree.extract_int = re.compile('^.*?(?P<int>\d+).+$') <commit_msg>Add float extractor, fix extractors rules<commit_after># re_set.py # Module for generating regex rules # r1 import re class Ree: float = None number = None page_number = None extract_int = None extract_float = None @staticmethod def init(): Ree._is_float() Ree._is_number() Ree._is_page_number('') Ree._extract_int_compile() Ree._extract_float_compile() @staticmethod def _is_page_number(page_param): Ree.page_number = re.compile('(?P<param>{})=(?P<page>\d+)'.format(page_param)) @staticmethod def _is_float(sep=',.'): Ree.float = re.compile('(?P<float>-?\d+([{}]\d+)?)'.format(sep)) @staticmethod def _is_number(): Ree.number = re.compile('^-?\d+$') @staticmethod def _extract_int_compile(): Ree.extract_int = re.compile('^.*?(?P<int>-?\d+).*$') @staticmethod def _extract_float_compile(sep=',.'): Ree.extract_float = re.compile('^.*?(?P<float>-?\d+([{}]\d+)?).*$'.format(sep))
18e056339492c8dde9ae53aafa9d53d16d3bb455
src/mcedit2/editortools/select_block.py
src/mcedit2/editortools/select_block.py
""" select block """ from __future__ import absolute_import, division, print_function, unicode_literals import logging from PySide import QtGui from mcedit2.editortools import EditorTool from mcedit2.util.load_ui import load_ui log = logging.getLogger(__name__) class SelectBlockCommand(QtGui.QUndoCommand): def __init__(self, tool, mousePos, *args, **kwargs): QtGui.QUndoCommand.__init__(self, *args, **kwargs) self.setText("Select Block") self.mousePos = mousePos self.tool = tool def undo(self): self.tool.setMousePos(self.ray) def redo(self): self.previousPos = self.tool.mousePos self.tool.setMousePos(self.mousePos) class SelectBlockTool(EditorTool): name = "Select Block" iconName = "edit_block" selectionRay = None currentEntity = None def __init__(self, editorSession, *args, **kwargs): """ :type editorSession: EditorSession """ super(SelectBlockTool, self).__init__(editorSession, *args, **kwargs) self.createToolWidget() self.mousePos = None def createToolWidget(self): self.toolWidget = load_ui("editortools/select_block.ui") def mousePress(self, event): command = SelectBlockCommand(self, event.blockPosition) self.editorSession.pushCommand(command) def setMousePos(self, pos): self.mousePos = pos self.editorSession.inspectBlock(pos)
""" select block """ from __future__ import absolute_import, division, print_function, unicode_literals import logging from PySide import QtGui from mcedit2.editortools import EditorTool from mcedit2.util.load_ui import load_ui log = logging.getLogger(__name__) class SelectBlockTool(EditorTool): name = "Select Block" iconName = "edit_block" selectionRay = None currentEntity = None def __init__(self, editorSession, *args, **kwargs): """ :type editorSession: EditorSession """ super(SelectBlockTool, self).__init__(editorSession, *args, **kwargs) self.createToolWidget() self.mousePos = None def createToolWidget(self): self.toolWidget = load_ui("editortools/select_block.ui") def mousePress(self, event): self.setMousePos(event.blockPosition) def setMousePos(self, pos): self.mousePos = pos self.editorSession.inspectBlock(pos)
Select Block is no longer undoable
Select Block is no longer undoable
Python
bsd-3-clause
vorburger/mcedit2,vorburger/mcedit2,Rubisk/mcedit2,Rubisk/mcedit2
""" select block """ from __future__ import absolute_import, division, print_function, unicode_literals import logging from PySide import QtGui from mcedit2.editortools import EditorTool from mcedit2.util.load_ui import load_ui log = logging.getLogger(__name__) class SelectBlockCommand(QtGui.QUndoCommand): def __init__(self, tool, mousePos, *args, **kwargs): QtGui.QUndoCommand.__init__(self, *args, **kwargs) self.setText("Select Block") self.mousePos = mousePos self.tool = tool def undo(self): self.tool.setMousePos(self.ray) def redo(self): self.previousPos = self.tool.mousePos self.tool.setMousePos(self.mousePos) class SelectBlockTool(EditorTool): name = "Select Block" iconName = "edit_block" selectionRay = None currentEntity = None def __init__(self, editorSession, *args, **kwargs): """ :type editorSession: EditorSession """ super(SelectBlockTool, self).__init__(editorSession, *args, **kwargs) self.createToolWidget() self.mousePos = None def createToolWidget(self): self.toolWidget = load_ui("editortools/select_block.ui") def mousePress(self, event): command = SelectBlockCommand(self, event.blockPosition) self.editorSession.pushCommand(command) def setMousePos(self, pos): self.mousePos = pos self.editorSession.inspectBlock(pos) Select Block is no longer undoable
""" select block """ from __future__ import absolute_import, division, print_function, unicode_literals import logging from PySide import QtGui from mcedit2.editortools import EditorTool from mcedit2.util.load_ui import load_ui log = logging.getLogger(__name__) class SelectBlockTool(EditorTool): name = "Select Block" iconName = "edit_block" selectionRay = None currentEntity = None def __init__(self, editorSession, *args, **kwargs): """ :type editorSession: EditorSession """ super(SelectBlockTool, self).__init__(editorSession, *args, **kwargs) self.createToolWidget() self.mousePos = None def createToolWidget(self): self.toolWidget = load_ui("editortools/select_block.ui") def mousePress(self, event): self.setMousePos(event.blockPosition) def setMousePos(self, pos): self.mousePos = pos self.editorSession.inspectBlock(pos)
<commit_before>""" select block """ from __future__ import absolute_import, division, print_function, unicode_literals import logging from PySide import QtGui from mcedit2.editortools import EditorTool from mcedit2.util.load_ui import load_ui log = logging.getLogger(__name__) class SelectBlockCommand(QtGui.QUndoCommand): def __init__(self, tool, mousePos, *args, **kwargs): QtGui.QUndoCommand.__init__(self, *args, **kwargs) self.setText("Select Block") self.mousePos = mousePos self.tool = tool def undo(self): self.tool.setMousePos(self.ray) def redo(self): self.previousPos = self.tool.mousePos self.tool.setMousePos(self.mousePos) class SelectBlockTool(EditorTool): name = "Select Block" iconName = "edit_block" selectionRay = None currentEntity = None def __init__(self, editorSession, *args, **kwargs): """ :type editorSession: EditorSession """ super(SelectBlockTool, self).__init__(editorSession, *args, **kwargs) self.createToolWidget() self.mousePos = None def createToolWidget(self): self.toolWidget = load_ui("editortools/select_block.ui") def mousePress(self, event): command = SelectBlockCommand(self, event.blockPosition) self.editorSession.pushCommand(command) def setMousePos(self, pos): self.mousePos = pos self.editorSession.inspectBlock(pos) <commit_msg>Select Block is no longer undoable<commit_after>
""" select block """ from __future__ import absolute_import, division, print_function, unicode_literals import logging from PySide import QtGui from mcedit2.editortools import EditorTool from mcedit2.util.load_ui import load_ui log = logging.getLogger(__name__) class SelectBlockTool(EditorTool): name = "Select Block" iconName = "edit_block" selectionRay = None currentEntity = None def __init__(self, editorSession, *args, **kwargs): """ :type editorSession: EditorSession """ super(SelectBlockTool, self).__init__(editorSession, *args, **kwargs) self.createToolWidget() self.mousePos = None def createToolWidget(self): self.toolWidget = load_ui("editortools/select_block.ui") def mousePress(self, event): self.setMousePos(event.blockPosition) def setMousePos(self, pos): self.mousePos = pos self.editorSession.inspectBlock(pos)
""" select block """ from __future__ import absolute_import, division, print_function, unicode_literals import logging from PySide import QtGui from mcedit2.editortools import EditorTool from mcedit2.util.load_ui import load_ui log = logging.getLogger(__name__) class SelectBlockCommand(QtGui.QUndoCommand): def __init__(self, tool, mousePos, *args, **kwargs): QtGui.QUndoCommand.__init__(self, *args, **kwargs) self.setText("Select Block") self.mousePos = mousePos self.tool = tool def undo(self): self.tool.setMousePos(self.ray) def redo(self): self.previousPos = self.tool.mousePos self.tool.setMousePos(self.mousePos) class SelectBlockTool(EditorTool): name = "Select Block" iconName = "edit_block" selectionRay = None currentEntity = None def __init__(self, editorSession, *args, **kwargs): """ :type editorSession: EditorSession """ super(SelectBlockTool, self).__init__(editorSession, *args, **kwargs) self.createToolWidget() self.mousePos = None def createToolWidget(self): self.toolWidget = load_ui("editortools/select_block.ui") def mousePress(self, event): command = SelectBlockCommand(self, event.blockPosition) self.editorSession.pushCommand(command) def setMousePos(self, pos): self.mousePos = pos self.editorSession.inspectBlock(pos) Select Block is no longer undoable""" select block """ from __future__ import absolute_import, division, print_function, unicode_literals import logging from PySide import QtGui from mcedit2.editortools import EditorTool from mcedit2.util.load_ui import load_ui log = logging.getLogger(__name__) class SelectBlockTool(EditorTool): name = "Select Block" iconName = "edit_block" selectionRay = None currentEntity = None def __init__(self, editorSession, *args, **kwargs): """ :type editorSession: EditorSession """ super(SelectBlockTool, self).__init__(editorSession, *args, **kwargs) self.createToolWidget() self.mousePos = None def createToolWidget(self): self.toolWidget = load_ui("editortools/select_block.ui") def mousePress(self, event): self.setMousePos(event.blockPosition) def setMousePos(self, pos): self.mousePos = pos self.editorSession.inspectBlock(pos)
<commit_before>""" select block """ from __future__ import absolute_import, division, print_function, unicode_literals import logging from PySide import QtGui from mcedit2.editortools import EditorTool from mcedit2.util.load_ui import load_ui log = logging.getLogger(__name__) class SelectBlockCommand(QtGui.QUndoCommand): def __init__(self, tool, mousePos, *args, **kwargs): QtGui.QUndoCommand.__init__(self, *args, **kwargs) self.setText("Select Block") self.mousePos = mousePos self.tool = tool def undo(self): self.tool.setMousePos(self.ray) def redo(self): self.previousPos = self.tool.mousePos self.tool.setMousePos(self.mousePos) class SelectBlockTool(EditorTool): name = "Select Block" iconName = "edit_block" selectionRay = None currentEntity = None def __init__(self, editorSession, *args, **kwargs): """ :type editorSession: EditorSession """ super(SelectBlockTool, self).__init__(editorSession, *args, **kwargs) self.createToolWidget() self.mousePos = None def createToolWidget(self): self.toolWidget = load_ui("editortools/select_block.ui") def mousePress(self, event): command = SelectBlockCommand(self, event.blockPosition) self.editorSession.pushCommand(command) def setMousePos(self, pos): self.mousePos = pos self.editorSession.inspectBlock(pos) <commit_msg>Select Block is no longer undoable<commit_after>""" select block """ from __future__ import absolute_import, division, print_function, unicode_literals import logging from PySide import QtGui from mcedit2.editortools import EditorTool from mcedit2.util.load_ui import load_ui log = logging.getLogger(__name__) class SelectBlockTool(EditorTool): name = "Select Block" iconName = "edit_block" selectionRay = None currentEntity = None def __init__(self, editorSession, *args, **kwargs): """ :type editorSession: EditorSession """ super(SelectBlockTool, self).__init__(editorSession, *args, **kwargs) self.createToolWidget() self.mousePos = None def createToolWidget(self): self.toolWidget = load_ui("editortools/select_block.ui") def mousePress(self, event): self.setMousePos(event.blockPosition) def setMousePos(self, pos): self.mousePos = pos self.editorSession.inspectBlock(pos)
75922744effcd1748a9d16887c771149a2026e20
mfr/ext/pdf/render.py
mfr/ext/pdf/render.py
"""PDF renderer module.""" from mfr.core import RenderResult import PyPDF2 import urllib def is_valid(fp): """Tests file pointer for validity :return: True if fp is a valid pdf, False if not """ try: PyPDF2.PdfFileReader(fp) return True except PyPDF2.utils.PdfReadError: return False def render_pdf(fp, src=None): """A simple pdf renderer. :param fp: File pointer :param src: Path to file :return: A RenderResult object containing html content and js assets for pdf rendering """ src = src or fp.name url_encoded_src = urllib.quote_plus(src) if is_valid(fp): content = ( '<iframe src="/static/mfr/pdf/web/viewer.html?file={src}" width="100%" height="600px"></iframe>' ).format(src = url_encoded_src) return RenderResult(content) else: return RenderResult("This is not a valid pdf file")
"""PDF renderer module.""" from mfr.core import RenderResult import PyPDF2 import urllib import mfr def is_valid(fp): """Tests file pointer for validity :return: True if fp is a valid pdf, False if not """ try: PyPDF2.PdfFileReader(fp) return True except PyPDF2.utils.PdfReadError: return False def render_pdf(fp, src=None): """A simple pdf renderer. :param fp: File pointer :param src: Path to file :return: A RenderResult object containing html content and js assets for pdf rendering """ src = src or fp.name url_encoded_src = urllib.quote_plus(src) assets_uri_base = '{0}/pdf'.format(mfr.config['ASSETS_URL']) if is_valid(fp): content = ( '<iframe src="{base}/web/viewer.html?file={src}" width="100%" height="600px"></iframe>' ).format(src=url_encoded_src, base=assets_uri_base) return RenderResult(content) else: return RenderResult("This is not a valid pdf file")
Change path to mfr directory
Change path to mfr directory
Python
apache-2.0
AddisonSchiller/modular-file-renderer,Johnetordoff/modular-file-renderer,rdhyee/modular-file-renderer,mfraezz/modular-file-renderer,TomBaxter/modular-file-renderer,icereval/modular-file-renderer,CenterForOpenScience/modular-file-renderer,mfraezz/modular-file-renderer,mfraezz/modular-file-renderer,Johnetordoff/modular-file-renderer,TomBaxter/modular-file-renderer,rdhyee/modular-file-renderer,felliott/modular-file-renderer,rdhyee/modular-file-renderer,AddisonSchiller/modular-file-renderer,haoyuchen1992/modular-file-renderer,CenterForOpenScience/modular-file-renderer,mfraezz/modular-file-renderer,icereval/modular-file-renderer,Johnetordoff/modular-file-renderer,CenterForOpenScience/modular-file-renderer,haoyuchen1992/modular-file-renderer,felliott/modular-file-renderer,haoyuchen1992/modular-file-renderer,Johnetordoff/modular-file-renderer,icereval/modular-file-renderer,rdhyee/modular-file-renderer,AddisonSchiller/modular-file-renderer,TomBaxter/modular-file-renderer,TomBaxter/modular-file-renderer,AddisonSchiller/modular-file-renderer,felliott/modular-file-renderer,felliott/modular-file-renderer,CenterForOpenScience/modular-file-renderer,haoyuchen1992/modular-file-renderer
"""PDF renderer module.""" from mfr.core import RenderResult import PyPDF2 import urllib def is_valid(fp): """Tests file pointer for validity :return: True if fp is a valid pdf, False if not """ try: PyPDF2.PdfFileReader(fp) return True except PyPDF2.utils.PdfReadError: return False def render_pdf(fp, src=None): """A simple pdf renderer. :param fp: File pointer :param src: Path to file :return: A RenderResult object containing html content and js assets for pdf rendering """ src = src or fp.name url_encoded_src = urllib.quote_plus(src) if is_valid(fp): content = ( '<iframe src="/static/mfr/pdf/web/viewer.html?file={src}" width="100%" height="600px"></iframe>' ).format(src = url_encoded_src) return RenderResult(content) else: return RenderResult("This is not a valid pdf file") Change path to mfr directory
"""PDF renderer module.""" from mfr.core import RenderResult import PyPDF2 import urllib import mfr def is_valid(fp): """Tests file pointer for validity :return: True if fp is a valid pdf, False if not """ try: PyPDF2.PdfFileReader(fp) return True except PyPDF2.utils.PdfReadError: return False def render_pdf(fp, src=None): """A simple pdf renderer. :param fp: File pointer :param src: Path to file :return: A RenderResult object containing html content and js assets for pdf rendering """ src = src or fp.name url_encoded_src = urllib.quote_plus(src) assets_uri_base = '{0}/pdf'.format(mfr.config['ASSETS_URL']) if is_valid(fp): content = ( '<iframe src="{base}/web/viewer.html?file={src}" width="100%" height="600px"></iframe>' ).format(src=url_encoded_src, base=assets_uri_base) return RenderResult(content) else: return RenderResult("This is not a valid pdf file")
<commit_before>"""PDF renderer module.""" from mfr.core import RenderResult import PyPDF2 import urllib def is_valid(fp): """Tests file pointer for validity :return: True if fp is a valid pdf, False if not """ try: PyPDF2.PdfFileReader(fp) return True except PyPDF2.utils.PdfReadError: return False def render_pdf(fp, src=None): """A simple pdf renderer. :param fp: File pointer :param src: Path to file :return: A RenderResult object containing html content and js assets for pdf rendering """ src = src or fp.name url_encoded_src = urllib.quote_plus(src) if is_valid(fp): content = ( '<iframe src="/static/mfr/pdf/web/viewer.html?file={src}" width="100%" height="600px"></iframe>' ).format(src = url_encoded_src) return RenderResult(content) else: return RenderResult("This is not a valid pdf file") <commit_msg>Change path to mfr directory<commit_after>
"""PDF renderer module.""" from mfr.core import RenderResult import PyPDF2 import urllib import mfr def is_valid(fp): """Tests file pointer for validity :return: True if fp is a valid pdf, False if not """ try: PyPDF2.PdfFileReader(fp) return True except PyPDF2.utils.PdfReadError: return False def render_pdf(fp, src=None): """A simple pdf renderer. :param fp: File pointer :param src: Path to file :return: A RenderResult object containing html content and js assets for pdf rendering """ src = src or fp.name url_encoded_src = urllib.quote_plus(src) assets_uri_base = '{0}/pdf'.format(mfr.config['ASSETS_URL']) if is_valid(fp): content = ( '<iframe src="{base}/web/viewer.html?file={src}" width="100%" height="600px"></iframe>' ).format(src=url_encoded_src, base=assets_uri_base) return RenderResult(content) else: return RenderResult("This is not a valid pdf file")
"""PDF renderer module.""" from mfr.core import RenderResult import PyPDF2 import urllib def is_valid(fp): """Tests file pointer for validity :return: True if fp is a valid pdf, False if not """ try: PyPDF2.PdfFileReader(fp) return True except PyPDF2.utils.PdfReadError: return False def render_pdf(fp, src=None): """A simple pdf renderer. :param fp: File pointer :param src: Path to file :return: A RenderResult object containing html content and js assets for pdf rendering """ src = src or fp.name url_encoded_src = urllib.quote_plus(src) if is_valid(fp): content = ( '<iframe src="/static/mfr/pdf/web/viewer.html?file={src}" width="100%" height="600px"></iframe>' ).format(src = url_encoded_src) return RenderResult(content) else: return RenderResult("This is not a valid pdf file") Change path to mfr directory"""PDF renderer module.""" from mfr.core import RenderResult import PyPDF2 import urllib import mfr def is_valid(fp): """Tests file pointer for validity :return: True if fp is a valid pdf, False if not """ try: PyPDF2.PdfFileReader(fp) return True except PyPDF2.utils.PdfReadError: return False def render_pdf(fp, src=None): """A simple pdf renderer. :param fp: File pointer :param src: Path to file :return: A RenderResult object containing html content and js assets for pdf rendering """ src = src or fp.name url_encoded_src = urllib.quote_plus(src) assets_uri_base = '{0}/pdf'.format(mfr.config['ASSETS_URL']) if is_valid(fp): content = ( '<iframe src="{base}/web/viewer.html?file={src}" width="100%" height="600px"></iframe>' ).format(src=url_encoded_src, base=assets_uri_base) return RenderResult(content) else: return RenderResult("This is not a valid pdf file")
<commit_before>"""PDF renderer module.""" from mfr.core import RenderResult import PyPDF2 import urllib def is_valid(fp): """Tests file pointer for validity :return: True if fp is a valid pdf, False if not """ try: PyPDF2.PdfFileReader(fp) return True except PyPDF2.utils.PdfReadError: return False def render_pdf(fp, src=None): """A simple pdf renderer. :param fp: File pointer :param src: Path to file :return: A RenderResult object containing html content and js assets for pdf rendering """ src = src or fp.name url_encoded_src = urllib.quote_plus(src) if is_valid(fp): content = ( '<iframe src="/static/mfr/pdf/web/viewer.html?file={src}" width="100%" height="600px"></iframe>' ).format(src = url_encoded_src) return RenderResult(content) else: return RenderResult("This is not a valid pdf file") <commit_msg>Change path to mfr directory<commit_after>"""PDF renderer module.""" from mfr.core import RenderResult import PyPDF2 import urllib import mfr def is_valid(fp): """Tests file pointer for validity :return: True if fp is a valid pdf, False if not """ try: PyPDF2.PdfFileReader(fp) return True except PyPDF2.utils.PdfReadError: return False def render_pdf(fp, src=None): """A simple pdf renderer. :param fp: File pointer :param src: Path to file :return: A RenderResult object containing html content and js assets for pdf rendering """ src = src or fp.name url_encoded_src = urllib.quote_plus(src) assets_uri_base = '{0}/pdf'.format(mfr.config['ASSETS_URL']) if is_valid(fp): content = ( '<iframe src="{base}/web/viewer.html?file={src}" width="100%" height="600px"></iframe>' ).format(src=url_encoded_src, base=assets_uri_base) return RenderResult(content) else: return RenderResult("This is not a valid pdf file")
e5f22a2e59a44535cde1a3a41ccae4eee440bbf2
mica/report/tests/test_write_report.py
mica/report/tests/test_write_report.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst import tempfile import os import shutil import pytest from .. import report try: import Ska.DBI with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db: assert db.conn._is_connected == 1 HAS_SYBASE_ACCESS = True except: HAS_SYBASE_ACCESS = False @pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access') def test_write_reports(): """ Make a report and database """ tempdir = tempfile.mkdtemp() # Get a temporary file, but then delete it, because report.py will only # make a new table if the supplied file doesn't exist fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3') os.unlink(fn) report.REPORT_ROOT = tempdir report.REPORT_SERVER = fn for obsid in [20001, 15175, 54778]: report.main(obsid) os.unlink(fn) shutil.rmtree(tempdir)
# Licensed under a 3-clause BSD style license - see LICENSE.rst import tempfile import os import shutil import pytest from .. import report try: import Ska.DBI with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db: assert db.conn._is_connected == 1 HAS_SYBASE_ACCESS = True except: HAS_SYBASE_ACCESS = False HAS_SC_ARCHIVE = os.path.exists(report.starcheck.FILES['data_root']) @pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access') @pytest.mark.skipif('not HAS_SC_ARCHIVE', reason='Report test requires mica starcheck archive') def test_write_reports(): """ Make a report and database """ tempdir = tempfile.mkdtemp() # Get a temporary file, but then delete it, because report.py will only # make a new table if the supplied file doesn't exist fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3') os.unlink(fn) report.REPORT_ROOT = tempdir report.REPORT_SERVER = fn for obsid in [20001, 15175, 54778]: report.main(obsid) os.unlink(fn) shutil.rmtree(tempdir)
Add one more test skip on mica.report
Add one more test skip on mica.report
Python
bsd-3-clause
sot/mica,sot/mica
# Licensed under a 3-clause BSD style license - see LICENSE.rst import tempfile import os import shutil import pytest from .. import report try: import Ska.DBI with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db: assert db.conn._is_connected == 1 HAS_SYBASE_ACCESS = True except: HAS_SYBASE_ACCESS = False @pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access') def test_write_reports(): """ Make a report and database """ tempdir = tempfile.mkdtemp() # Get a temporary file, but then delete it, because report.py will only # make a new table if the supplied file doesn't exist fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3') os.unlink(fn) report.REPORT_ROOT = tempdir report.REPORT_SERVER = fn for obsid in [20001, 15175, 54778]: report.main(obsid) os.unlink(fn) shutil.rmtree(tempdir) Add one more test skip on mica.report
# Licensed under a 3-clause BSD style license - see LICENSE.rst import tempfile import os import shutil import pytest from .. import report try: import Ska.DBI with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db: assert db.conn._is_connected == 1 HAS_SYBASE_ACCESS = True except: HAS_SYBASE_ACCESS = False HAS_SC_ARCHIVE = os.path.exists(report.starcheck.FILES['data_root']) @pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access') @pytest.mark.skipif('not HAS_SC_ARCHIVE', reason='Report test requires mica starcheck archive') def test_write_reports(): """ Make a report and database """ tempdir = tempfile.mkdtemp() # Get a temporary file, but then delete it, because report.py will only # make a new table if the supplied file doesn't exist fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3') os.unlink(fn) report.REPORT_ROOT = tempdir report.REPORT_SERVER = fn for obsid in [20001, 15175, 54778]: report.main(obsid) os.unlink(fn) shutil.rmtree(tempdir)
<commit_before># Licensed under a 3-clause BSD style license - see LICENSE.rst import tempfile import os import shutil import pytest from .. import report try: import Ska.DBI with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db: assert db.conn._is_connected == 1 HAS_SYBASE_ACCESS = True except: HAS_SYBASE_ACCESS = False @pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access') def test_write_reports(): """ Make a report and database """ tempdir = tempfile.mkdtemp() # Get a temporary file, but then delete it, because report.py will only # make a new table if the supplied file doesn't exist fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3') os.unlink(fn) report.REPORT_ROOT = tempdir report.REPORT_SERVER = fn for obsid in [20001, 15175, 54778]: report.main(obsid) os.unlink(fn) shutil.rmtree(tempdir) <commit_msg>Add one more test skip on mica.report<commit_after>
# Licensed under a 3-clause BSD style license - see LICENSE.rst import tempfile import os import shutil import pytest from .. import report try: import Ska.DBI with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db: assert db.conn._is_connected == 1 HAS_SYBASE_ACCESS = True except: HAS_SYBASE_ACCESS = False HAS_SC_ARCHIVE = os.path.exists(report.starcheck.FILES['data_root']) @pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access') @pytest.mark.skipif('not HAS_SC_ARCHIVE', reason='Report test requires mica starcheck archive') def test_write_reports(): """ Make a report and database """ tempdir = tempfile.mkdtemp() # Get a temporary file, but then delete it, because report.py will only # make a new table if the supplied file doesn't exist fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3') os.unlink(fn) report.REPORT_ROOT = tempdir report.REPORT_SERVER = fn for obsid in [20001, 15175, 54778]: report.main(obsid) os.unlink(fn) shutil.rmtree(tempdir)
# Licensed under a 3-clause BSD style license - see LICENSE.rst import tempfile import os import shutil import pytest from .. import report try: import Ska.DBI with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db: assert db.conn._is_connected == 1 HAS_SYBASE_ACCESS = True except: HAS_SYBASE_ACCESS = False @pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access') def test_write_reports(): """ Make a report and database """ tempdir = tempfile.mkdtemp() # Get a temporary file, but then delete it, because report.py will only # make a new table if the supplied file doesn't exist fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3') os.unlink(fn) report.REPORT_ROOT = tempdir report.REPORT_SERVER = fn for obsid in [20001, 15175, 54778]: report.main(obsid) os.unlink(fn) shutil.rmtree(tempdir) Add one more test skip on mica.report# Licensed under a 3-clause BSD style license - see LICENSE.rst import tempfile import os import shutil import pytest from .. import report try: import Ska.DBI with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db: assert db.conn._is_connected == 1 HAS_SYBASE_ACCESS = True except: HAS_SYBASE_ACCESS = False HAS_SC_ARCHIVE = os.path.exists(report.starcheck.FILES['data_root']) @pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access') @pytest.mark.skipif('not HAS_SC_ARCHIVE', reason='Report test requires mica starcheck archive') def test_write_reports(): """ Make a report and database """ tempdir = tempfile.mkdtemp() # Get a temporary file, but then delete it, because report.py will only # make a new table if the supplied file doesn't exist fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3') os.unlink(fn) report.REPORT_ROOT = tempdir report.REPORT_SERVER = fn for obsid in [20001, 15175, 54778]: report.main(obsid) os.unlink(fn) shutil.rmtree(tempdir)
<commit_before># Licensed under a 3-clause BSD style license - see LICENSE.rst import tempfile import os import shutil import pytest from .. import report try: import Ska.DBI with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db: assert db.conn._is_connected == 1 HAS_SYBASE_ACCESS = True except: HAS_SYBASE_ACCESS = False @pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access') def test_write_reports(): """ Make a report and database """ tempdir = tempfile.mkdtemp() # Get a temporary file, but then delete it, because report.py will only # make a new table if the supplied file doesn't exist fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3') os.unlink(fn) report.REPORT_ROOT = tempdir report.REPORT_SERVER = fn for obsid in [20001, 15175, 54778]: report.main(obsid) os.unlink(fn) shutil.rmtree(tempdir) <commit_msg>Add one more test skip on mica.report<commit_after># Licensed under a 3-clause BSD style license - see LICENSE.rst import tempfile import os import shutil import pytest from .. import report try: import Ska.DBI with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db: assert db.conn._is_connected == 1 HAS_SYBASE_ACCESS = True except: HAS_SYBASE_ACCESS = False HAS_SC_ARCHIVE = os.path.exists(report.starcheck.FILES['data_root']) @pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access') @pytest.mark.skipif('not HAS_SC_ARCHIVE', reason='Report test requires mica starcheck archive') def test_write_reports(): """ Make a report and database """ tempdir = tempfile.mkdtemp() # Get a temporary file, but then delete it, because report.py will only # make a new table if the supplied file doesn't exist fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3') os.unlink(fn) report.REPORT_ROOT = tempdir report.REPORT_SERVER = fn for obsid in [20001, 15175, 54778]: report.main(obsid) os.unlink(fn) shutil.rmtree(tempdir)
638dda46a63f1c98f674febe170df55fe36cea5e
tests/test_timestepping.py
tests/test_timestepping.py
import numpy as np from sympy import Eq import pytest from devito.interfaces import TimeData from devito.stencilkernel import StencilKernel @pytest.fixture def a(shape=(11, 11)): """Forward time data object, unrolled (save=True)""" return TimeData(name='a', shape=shape, time_order=1, time_dim=6, save=True) def test_forward(a, nt=5): a.data[0, :] = 1. eqn = Eq(a.forward, a + 1.) StencilKernel(eqn, dle=None, dse=None)() for i in range(nt): assert np.allclose(a.data[i, :], 1. + i, rtol=1.e-12)
import numpy as np from sympy import Eq import pytest from devito.interfaces import Backward, Forward, TimeData from devito.stencilkernel import StencilKernel @pytest.fixture def a(shape=(11, 11)): """Forward time data object, unrolled (save=True)""" return TimeData(name='a', shape=shape, time_order=1, time_dim=6, save=True) @pytest.fixture def b(shape=(11, 11)): """Backward time data object, unrolled (save=True)""" return TimeData(name='b', shape=shape, time_order=1, time_dim=6, save=True) def test_forward(a, nt=5): a.data[0, :] = 1. eqn = Eq(a.forward, a + 1.) StencilKernel(eqn, dle=None, dse=None)() for i in range(nt): assert np.allclose(a.data[i, :], 1. + i, rtol=1.e-12) def test_backward(b, nt=5): b.data[nt, :] = 6. eqn = Eq(b.backward, b - 1.) StencilKernel(eqn, dle=None, dse=None, time_axis=Backward)(time=nt) for i in range(nt + 1): assert np.allclose(b.data[i, :], 1. + i, rtol=1.e-12)
Add explicit test for reverse timestepping
TimeData: Add explicit test for reverse timestepping
Python
mit
opesci/devito,opesci/devito
import numpy as np from sympy import Eq import pytest from devito.interfaces import TimeData from devito.stencilkernel import StencilKernel @pytest.fixture def a(shape=(11, 11)): """Forward time data object, unrolled (save=True)""" return TimeData(name='a', shape=shape, time_order=1, time_dim=6, save=True) def test_forward(a, nt=5): a.data[0, :] = 1. eqn = Eq(a.forward, a + 1.) StencilKernel(eqn, dle=None, dse=None)() for i in range(nt): assert np.allclose(a.data[i, :], 1. + i, rtol=1.e-12) TimeData: Add explicit test for reverse timestepping
import numpy as np from sympy import Eq import pytest from devito.interfaces import Backward, Forward, TimeData from devito.stencilkernel import StencilKernel @pytest.fixture def a(shape=(11, 11)): """Forward time data object, unrolled (save=True)""" return TimeData(name='a', shape=shape, time_order=1, time_dim=6, save=True) @pytest.fixture def b(shape=(11, 11)): """Backward time data object, unrolled (save=True)""" return TimeData(name='b', shape=shape, time_order=1, time_dim=6, save=True) def test_forward(a, nt=5): a.data[0, :] = 1. eqn = Eq(a.forward, a + 1.) StencilKernel(eqn, dle=None, dse=None)() for i in range(nt): assert np.allclose(a.data[i, :], 1. + i, rtol=1.e-12) def test_backward(b, nt=5): b.data[nt, :] = 6. eqn = Eq(b.backward, b - 1.) StencilKernel(eqn, dle=None, dse=None, time_axis=Backward)(time=nt) for i in range(nt + 1): assert np.allclose(b.data[i, :], 1. + i, rtol=1.e-12)
<commit_before>import numpy as np from sympy import Eq import pytest from devito.interfaces import TimeData from devito.stencilkernel import StencilKernel @pytest.fixture def a(shape=(11, 11)): """Forward time data object, unrolled (save=True)""" return TimeData(name='a', shape=shape, time_order=1, time_dim=6, save=True) def test_forward(a, nt=5): a.data[0, :] = 1. eqn = Eq(a.forward, a + 1.) StencilKernel(eqn, dle=None, dse=None)() for i in range(nt): assert np.allclose(a.data[i, :], 1. + i, rtol=1.e-12) <commit_msg>TimeData: Add explicit test for reverse timestepping<commit_after>
import numpy as np from sympy import Eq import pytest from devito.interfaces import Backward, Forward, TimeData from devito.stencilkernel import StencilKernel @pytest.fixture def a(shape=(11, 11)): """Forward time data object, unrolled (save=True)""" return TimeData(name='a', shape=shape, time_order=1, time_dim=6, save=True) @pytest.fixture def b(shape=(11, 11)): """Backward time data object, unrolled (save=True)""" return TimeData(name='b', shape=shape, time_order=1, time_dim=6, save=True) def test_forward(a, nt=5): a.data[0, :] = 1. eqn = Eq(a.forward, a + 1.) StencilKernel(eqn, dle=None, dse=None)() for i in range(nt): assert np.allclose(a.data[i, :], 1. + i, rtol=1.e-12) def test_backward(b, nt=5): b.data[nt, :] = 6. eqn = Eq(b.backward, b - 1.) StencilKernel(eqn, dle=None, dse=None, time_axis=Backward)(time=nt) for i in range(nt + 1): assert np.allclose(b.data[i, :], 1. + i, rtol=1.e-12)
import numpy as np from sympy import Eq import pytest from devito.interfaces import TimeData from devito.stencilkernel import StencilKernel @pytest.fixture def a(shape=(11, 11)): """Forward time data object, unrolled (save=True)""" return TimeData(name='a', shape=shape, time_order=1, time_dim=6, save=True) def test_forward(a, nt=5): a.data[0, :] = 1. eqn = Eq(a.forward, a + 1.) StencilKernel(eqn, dle=None, dse=None)() for i in range(nt): assert np.allclose(a.data[i, :], 1. + i, rtol=1.e-12) TimeData: Add explicit test for reverse timesteppingimport numpy as np from sympy import Eq import pytest from devito.interfaces import Backward, Forward, TimeData from devito.stencilkernel import StencilKernel @pytest.fixture def a(shape=(11, 11)): """Forward time data object, unrolled (save=True)""" return TimeData(name='a', shape=shape, time_order=1, time_dim=6, save=True) @pytest.fixture def b(shape=(11, 11)): """Backward time data object, unrolled (save=True)""" return TimeData(name='b', shape=shape, time_order=1, time_dim=6, save=True) def test_forward(a, nt=5): a.data[0, :] = 1. eqn = Eq(a.forward, a + 1.) StencilKernel(eqn, dle=None, dse=None)() for i in range(nt): assert np.allclose(a.data[i, :], 1. + i, rtol=1.e-12) def test_backward(b, nt=5): b.data[nt, :] = 6. eqn = Eq(b.backward, b - 1.) StencilKernel(eqn, dle=None, dse=None, time_axis=Backward)(time=nt) for i in range(nt + 1): assert np.allclose(b.data[i, :], 1. + i, rtol=1.e-12)
<commit_before>import numpy as np from sympy import Eq import pytest from devito.interfaces import TimeData from devito.stencilkernel import StencilKernel @pytest.fixture def a(shape=(11, 11)): """Forward time data object, unrolled (save=True)""" return TimeData(name='a', shape=shape, time_order=1, time_dim=6, save=True) def test_forward(a, nt=5): a.data[0, :] = 1. eqn = Eq(a.forward, a + 1.) StencilKernel(eqn, dle=None, dse=None)() for i in range(nt): assert np.allclose(a.data[i, :], 1. + i, rtol=1.e-12) <commit_msg>TimeData: Add explicit test for reverse timestepping<commit_after>import numpy as np from sympy import Eq import pytest from devito.interfaces import Backward, Forward, TimeData from devito.stencilkernel import StencilKernel @pytest.fixture def a(shape=(11, 11)): """Forward time data object, unrolled (save=True)""" return TimeData(name='a', shape=shape, time_order=1, time_dim=6, save=True) @pytest.fixture def b(shape=(11, 11)): """Backward time data object, unrolled (save=True)""" return TimeData(name='b', shape=shape, time_order=1, time_dim=6, save=True) def test_forward(a, nt=5): a.data[0, :] = 1. eqn = Eq(a.forward, a + 1.) StencilKernel(eqn, dle=None, dse=None)() for i in range(nt): assert np.allclose(a.data[i, :], 1. + i, rtol=1.e-12) def test_backward(b, nt=5): b.data[nt, :] = 6. eqn = Eq(b.backward, b - 1.) StencilKernel(eqn, dle=None, dse=None, time_axis=Backward)(time=nt) for i in range(nt + 1): assert np.allclose(b.data[i, :], 1. + i, rtol=1.e-12)
1eea70f8f378477b216b608aaa93e524a900cdf8
tests/unit/test_stencil.py
tests/unit/test_stencil.py
# -*- coding: utf-8 -*- import unittest import stencil from stencil import Token class ModuleTestCase(unittest.TestCase): """Test cases for the stencil module.""" @staticmethod def test_tokenise(): """Test stencil.tokenise() function.""" it_token = stencil.tokenise('abc {{ x }} xyz') token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == 'abc ' token = next(it_token) assert isinstance(token, Token) assert token.type == 'var' assert token.content == 'x' token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == ' xyz'
# -*- coding: utf-8 -*- import unittest import stencil from stencil import Token class ModuleTestCase(unittest.TestCase): """Test cases for the stencil module.""" @staticmethod def test_tokenise(): """Test stencil.tokenise() function.""" it_token = stencil.tokenise('abc {{ x }} xyz') token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == 'abc ' token = next(it_token) assert isinstance(token, Token) assert token.type == 'var' assert token.content == 'x' token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == ' xyz' class ContextTestCase(unittest.TestCase): def test_push(self): ctx = stencil.Context({'a': 1}) self.assertEqual(ctx['a'], 1) self.assertIsNone(ctx['None']) with ctx.push(a=2): self.assertEqual(ctx['a'], 2) self.assertEqual(ctx['a'], 1)
Add simple context push test
Add simple context push test
Python
mit
funkybob/stencil,funkybob/stencil
# -*- coding: utf-8 -*- import unittest import stencil from stencil import Token class ModuleTestCase(unittest.TestCase): """Test cases for the stencil module.""" @staticmethod def test_tokenise(): """Test stencil.tokenise() function.""" it_token = stencil.tokenise('abc {{ x }} xyz') token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == 'abc ' token = next(it_token) assert isinstance(token, Token) assert token.type == 'var' assert token.content == 'x' token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == ' xyz' Add simple context push test
# -*- coding: utf-8 -*- import unittest import stencil from stencil import Token class ModuleTestCase(unittest.TestCase): """Test cases for the stencil module.""" @staticmethod def test_tokenise(): """Test stencil.tokenise() function.""" it_token = stencil.tokenise('abc {{ x }} xyz') token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == 'abc ' token = next(it_token) assert isinstance(token, Token) assert token.type == 'var' assert token.content == 'x' token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == ' xyz' class ContextTestCase(unittest.TestCase): def test_push(self): ctx = stencil.Context({'a': 1}) self.assertEqual(ctx['a'], 1) self.assertIsNone(ctx['None']) with ctx.push(a=2): self.assertEqual(ctx['a'], 2) self.assertEqual(ctx['a'], 1)
<commit_before># -*- coding: utf-8 -*- import unittest import stencil from stencil import Token class ModuleTestCase(unittest.TestCase): """Test cases for the stencil module.""" @staticmethod def test_tokenise(): """Test stencil.tokenise() function.""" it_token = stencil.tokenise('abc {{ x }} xyz') token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == 'abc ' token = next(it_token) assert isinstance(token, Token) assert token.type == 'var' assert token.content == 'x' token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == ' xyz' <commit_msg>Add simple context push test<commit_after>
# -*- coding: utf-8 -*- import unittest import stencil from stencil import Token class ModuleTestCase(unittest.TestCase): """Test cases for the stencil module.""" @staticmethod def test_tokenise(): """Test stencil.tokenise() function.""" it_token = stencil.tokenise('abc {{ x }} xyz') token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == 'abc ' token = next(it_token) assert isinstance(token, Token) assert token.type == 'var' assert token.content == 'x' token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == ' xyz' class ContextTestCase(unittest.TestCase): def test_push(self): ctx = stencil.Context({'a': 1}) self.assertEqual(ctx['a'], 1) self.assertIsNone(ctx['None']) with ctx.push(a=2): self.assertEqual(ctx['a'], 2) self.assertEqual(ctx['a'], 1)
# -*- coding: utf-8 -*- import unittest import stencil from stencil import Token class ModuleTestCase(unittest.TestCase): """Test cases for the stencil module.""" @staticmethod def test_tokenise(): """Test stencil.tokenise() function.""" it_token = stencil.tokenise('abc {{ x }} xyz') token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == 'abc ' token = next(it_token) assert isinstance(token, Token) assert token.type == 'var' assert token.content == 'x' token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == ' xyz' Add simple context push test# -*- coding: utf-8 -*- import unittest import stencil from stencil import Token class ModuleTestCase(unittest.TestCase): """Test cases for the stencil module.""" @staticmethod def test_tokenise(): """Test stencil.tokenise() function.""" it_token = stencil.tokenise('abc {{ x }} xyz') token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == 'abc ' token = next(it_token) assert isinstance(token, Token) assert token.type == 'var' assert token.content == 'x' token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == ' xyz' class ContextTestCase(unittest.TestCase): def test_push(self): ctx = stencil.Context({'a': 1}) self.assertEqual(ctx['a'], 1) self.assertIsNone(ctx['None']) with ctx.push(a=2): self.assertEqual(ctx['a'], 2) self.assertEqual(ctx['a'], 1)
<commit_before># -*- coding: utf-8 -*- import unittest import stencil from stencil import Token class ModuleTestCase(unittest.TestCase): """Test cases for the stencil module.""" @staticmethod def test_tokenise(): """Test stencil.tokenise() function.""" it_token = stencil.tokenise('abc {{ x }} xyz') token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == 'abc ' token = next(it_token) assert isinstance(token, Token) assert token.type == 'var' assert token.content == 'x' token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == ' xyz' <commit_msg>Add simple context push test<commit_after># -*- coding: utf-8 -*- import unittest import stencil from stencil import Token class ModuleTestCase(unittest.TestCase): """Test cases for the stencil module.""" @staticmethod def test_tokenise(): """Test stencil.tokenise() function.""" it_token = stencil.tokenise('abc {{ x }} xyz') token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == 'abc ' token = next(it_token) assert isinstance(token, Token) assert token.type == 'var' assert token.content == 'x' token = next(it_token) assert isinstance(token, Token) assert token.type == 'text' assert token.content == ' xyz' class ContextTestCase(unittest.TestCase): def test_push(self): ctx = stencil.Context({'a': 1}) self.assertEqual(ctx['a'], 1) self.assertIsNone(ctx['None']) with ctx.push(a=2): self.assertEqual(ctx['a'], 2) self.assertEqual(ctx['a'], 1)
f5c2f39892d3ec10bf00a5df661b3d6bb3a30399
web_paullaroid/__init__.py
web_paullaroid/__init__.py
from pyramid.config import Configurator def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('pyramid_chameleon') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.scan() return config.make_wsgi_app()
from pyramid.config import Configurator def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('pyramid_chameleon') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('event', '/{event}/') config.add_route('image', '/{event}/{image}/') config.scan() return config.make_wsgi_app()
Add event and image route
Add event and image route
Python
mit
mips-lab/web_paullaroid,mips-lab/web_paullaroid,mips-lab/web_paullaroid
from pyramid.config import Configurator def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('pyramid_chameleon') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.scan() return config.make_wsgi_app() Add event and image route
from pyramid.config import Configurator def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('pyramid_chameleon') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('event', '/{event}/') config.add_route('image', '/{event}/{image}/') config.scan() return config.make_wsgi_app()
<commit_before>from pyramid.config import Configurator def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('pyramid_chameleon') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.scan() return config.make_wsgi_app() <commit_msg>Add event and image route<commit_after>
from pyramid.config import Configurator def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('pyramid_chameleon') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('event', '/{event}/') config.add_route('image', '/{event}/{image}/') config.scan() return config.make_wsgi_app()
from pyramid.config import Configurator def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('pyramid_chameleon') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.scan() return config.make_wsgi_app() Add event and image routefrom pyramid.config import Configurator def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('pyramid_chameleon') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('event', '/{event}/') config.add_route('image', '/{event}/{image}/') config.scan() return config.make_wsgi_app()
<commit_before>from pyramid.config import Configurator def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('pyramid_chameleon') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.scan() return config.make_wsgi_app() <commit_msg>Add event and image route<commit_after>from pyramid.config import Configurator def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('pyramid_chameleon') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('event', '/{event}/') config.add_route('image', '/{event}/{image}/') config.scan() return config.make_wsgi_app()
4b1ab446ffb396b6ddec8fa593c4225d5878363a
deflect/management/commands/checkurls.py
deflect/management/commands/checkurls.py
from django.core.management.base import NoArgsCommand from django.core.urlresolvers import reverse import requests from deflect.models import ShortURL class Command(NoArgsCommand): help = "Validate short URL redirect targets" def handle_noargs(self, *args, **options): for url in ShortURL.objects.all(): try: url.check_status() except requests.exceptions.RequestException as e: print self.error_text(url, e) def error_text(self, url, exception): """ """ return """ Bad redirect target: {key} {target} returns {error} Edit this URL: {edit} """.format(key=url.key, target=url.long_url, error=exception, edit=reverse('admin:deflect_shorturl_change', args=(url.id,)))
from django.core.management.base import NoArgsCommand from django.core.urlresolvers import reverse import requests from deflect.models import ShortURL class Command(NoArgsCommand): help = "Validate short URL redirect targets" def handle_noargs(self, *args, **options): for url in ShortURL.objects.all(): try: url.check_status() except requests.exceptions.RequestException as e: print self.bad_redirect_text(url, e) def bad_redirect_text(self, url, exception): """ Return informational text for a URL that raised an exception. """ return """ Redirect {key} with target {target} returns {error} Edit this short URL: {edit} """.format(key=url.key, target=url.long_url, error=exception, edit=reverse('admin:deflect_shorturl_change', args=(url.id,)))
Modify text for management command message
Modify text for management command message
Python
bsd-3-clause
jbittel/django-deflect
from django.core.management.base import NoArgsCommand from django.core.urlresolvers import reverse import requests from deflect.models import ShortURL class Command(NoArgsCommand): help = "Validate short URL redirect targets" def handle_noargs(self, *args, **options): for url in ShortURL.objects.all(): try: url.check_status() except requests.exceptions.RequestException as e: print self.error_text(url, e) def error_text(self, url, exception): """ """ return """ Bad redirect target: {key} {target} returns {error} Edit this URL: {edit} """.format(key=url.key, target=url.long_url, error=exception, edit=reverse('admin:deflect_shorturl_change', args=(url.id,))) Modify text for management command message
from django.core.management.base import NoArgsCommand from django.core.urlresolvers import reverse import requests from deflect.models import ShortURL class Command(NoArgsCommand): help = "Validate short URL redirect targets" def handle_noargs(self, *args, **options): for url in ShortURL.objects.all(): try: url.check_status() except requests.exceptions.RequestException as e: print self.bad_redirect_text(url, e) def bad_redirect_text(self, url, exception): """ Return informational text for a URL that raised an exception. """ return """ Redirect {key} with target {target} returns {error} Edit this short URL: {edit} """.format(key=url.key, target=url.long_url, error=exception, edit=reverse('admin:deflect_shorturl_change', args=(url.id,)))
<commit_before>from django.core.management.base import NoArgsCommand from django.core.urlresolvers import reverse import requests from deflect.models import ShortURL class Command(NoArgsCommand): help = "Validate short URL redirect targets" def handle_noargs(self, *args, **options): for url in ShortURL.objects.all(): try: url.check_status() except requests.exceptions.RequestException as e: print self.error_text(url, e) def error_text(self, url, exception): """ """ return """ Bad redirect target: {key} {target} returns {error} Edit this URL: {edit} """.format(key=url.key, target=url.long_url, error=exception, edit=reverse('admin:deflect_shorturl_change', args=(url.id,))) <commit_msg>Modify text for management command message<commit_after>
from django.core.management.base import NoArgsCommand from django.core.urlresolvers import reverse import requests from deflect.models import ShortURL class Command(NoArgsCommand): help = "Validate short URL redirect targets" def handle_noargs(self, *args, **options): for url in ShortURL.objects.all(): try: url.check_status() except requests.exceptions.RequestException as e: print self.bad_redirect_text(url, e) def bad_redirect_text(self, url, exception): """ Return informational text for a URL that raised an exception. """ return """ Redirect {key} with target {target} returns {error} Edit this short URL: {edit} """.format(key=url.key, target=url.long_url, error=exception, edit=reverse('admin:deflect_shorturl_change', args=(url.id,)))
from django.core.management.base import NoArgsCommand from django.core.urlresolvers import reverse import requests from deflect.models import ShortURL class Command(NoArgsCommand): help = "Validate short URL redirect targets" def handle_noargs(self, *args, **options): for url in ShortURL.objects.all(): try: url.check_status() except requests.exceptions.RequestException as e: print self.error_text(url, e) def error_text(self, url, exception): """ """ return """ Bad redirect target: {key} {target} returns {error} Edit this URL: {edit} """.format(key=url.key, target=url.long_url, error=exception, edit=reverse('admin:deflect_shorturl_change', args=(url.id,))) Modify text for management command messagefrom django.core.management.base import NoArgsCommand from django.core.urlresolvers import reverse import requests from deflect.models import ShortURL class Command(NoArgsCommand): help = "Validate short URL redirect targets" def handle_noargs(self, *args, **options): for url in ShortURL.objects.all(): try: url.check_status() except requests.exceptions.RequestException as e: print self.bad_redirect_text(url, e) def bad_redirect_text(self, url, exception): """ Return informational text for a URL that raised an exception. """ return """ Redirect {key} with target {target} returns {error} Edit this short URL: {edit} """.format(key=url.key, target=url.long_url, error=exception, edit=reverse('admin:deflect_shorturl_change', args=(url.id,)))
<commit_before>from django.core.management.base import NoArgsCommand from django.core.urlresolvers import reverse import requests from deflect.models import ShortURL class Command(NoArgsCommand): help = "Validate short URL redirect targets" def handle_noargs(self, *args, **options): for url in ShortURL.objects.all(): try: url.check_status() except requests.exceptions.RequestException as e: print self.error_text(url, e) def error_text(self, url, exception): """ """ return """ Bad redirect target: {key} {target} returns {error} Edit this URL: {edit} """.format(key=url.key, target=url.long_url, error=exception, edit=reverse('admin:deflect_shorturl_change', args=(url.id,))) <commit_msg>Modify text for management command message<commit_after>from django.core.management.base import NoArgsCommand from django.core.urlresolvers import reverse import requests from deflect.models import ShortURL class Command(NoArgsCommand): help = "Validate short URL redirect targets" def handle_noargs(self, *args, **options): for url in ShortURL.objects.all(): try: url.check_status() except requests.exceptions.RequestException as e: print self.bad_redirect_text(url, e) def bad_redirect_text(self, url, exception): """ Return informational text for a URL that raised an exception. """ return """ Redirect {key} with target {target} returns {error} Edit this short URL: {edit} """.format(key=url.key, target=url.long_url, error=exception, edit=reverse('admin:deflect_shorturl_change', args=(url.id,)))
31d0278bb7eb40e108af1ad455275c86aa462390
src/helpers/utils.py
src/helpers/utils.py
from __future__ import unicode_literals from config import settings import os import re import string import pytz def clear_screen(): # Clear screen os.system(['clear', 'cls'][os.name == 'nt']) def print_obj(obj): for attr, val in obj.__dict__.iteritems(): print "{0}: {1}".format(attr, val) def convert_to_snake_case(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() def parse_int(text): digits = ''.join([c for c in text if c.isdigit()]) if digits.isdigit(): return int(digits) return None def as_client_tz(dt): return dt.astimezone(pytz.timezone(settings.CLIENT_TZ)) def make_data_updates_string(data_changes): updates = "" if data_changes: for key in data_changes: title = key.replace("_", " ").capitalize() old_val = data_changes[key]['old'] new_val = data_changes[key]['new'] updates += "\n{0}: {1} => {2}".format(title, old_val, new_val) return updates def delta_minutes(now, before): delta_datetime = now - before minutes_ago = int(delta_datetime.total_seconds() / 60) return minutes_ago
from __future__ import unicode_literals from config import settings import os import re import string import pytz def clear_screen(): # Clear screen os.system(['clear', 'cls'][os.name == 'nt']) def print_obj(obj): for attr, val in obj.__dict__.iteritems(): print "{0}: {1}".format(attr, val) def convert_to_snake_case(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() def parse_int(text): digits = ''.join([c for c in text if c.isdigit()]) if digits.isdigit(): return int(digits) return None def as_client_tz(dt): return dt.astimezone(pytz.timezone(settings.CLIENT_TZ)) def make_data_updates_string(data_changes): updates = "" if data_changes: for key in data_changes: title = key.replace("_", " ").capitalize() old_val = data_changes[key]['old'] new_val = data_changes[key]['new'] if new_val: updates += "\n{0}: {1} => {2}".format(title, old_val, new_val) return updates def delta_minutes(now, before): delta_datetime = now - before minutes_ago = int(delta_datetime.total_seconds() / 60) return minutes_ago
Add data change to updates string only if new value is not None in order to preserve scraped data, that user decided to hide.
Add data change to updates string only if new value is not None in order to preserve scraped data, that user decided to hide.
Python
mit
lesh1k/VKStalk
from __future__ import unicode_literals from config import settings import os import re import string import pytz def clear_screen(): # Clear screen os.system(['clear', 'cls'][os.name == 'nt']) def print_obj(obj): for attr, val in obj.__dict__.iteritems(): print "{0}: {1}".format(attr, val) def convert_to_snake_case(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() def parse_int(text): digits = ''.join([c for c in text if c.isdigit()]) if digits.isdigit(): return int(digits) return None def as_client_tz(dt): return dt.astimezone(pytz.timezone(settings.CLIENT_TZ)) def make_data_updates_string(data_changes): updates = "" if data_changes: for key in data_changes: title = key.replace("_", " ").capitalize() old_val = data_changes[key]['old'] new_val = data_changes[key]['new'] updates += "\n{0}: {1} => {2}".format(title, old_val, new_val) return updates def delta_minutes(now, before): delta_datetime = now - before minutes_ago = int(delta_datetime.total_seconds() / 60) return minutes_ago Add data change to updates string only if new value is not None in order to preserve scraped data, that user decided to hide.
from __future__ import unicode_literals from config import settings import os import re import string import pytz def clear_screen(): # Clear screen os.system(['clear', 'cls'][os.name == 'nt']) def print_obj(obj): for attr, val in obj.__dict__.iteritems(): print "{0}: {1}".format(attr, val) def convert_to_snake_case(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() def parse_int(text): digits = ''.join([c for c in text if c.isdigit()]) if digits.isdigit(): return int(digits) return None def as_client_tz(dt): return dt.astimezone(pytz.timezone(settings.CLIENT_TZ)) def make_data_updates_string(data_changes): updates = "" if data_changes: for key in data_changes: title = key.replace("_", " ").capitalize() old_val = data_changes[key]['old'] new_val = data_changes[key]['new'] if new_val: updates += "\n{0}: {1} => {2}".format(title, old_val, new_val) return updates def delta_minutes(now, before): delta_datetime = now - before minutes_ago = int(delta_datetime.total_seconds() / 60) return minutes_ago
<commit_before>from __future__ import unicode_literals from config import settings import os import re import string import pytz def clear_screen(): # Clear screen os.system(['clear', 'cls'][os.name == 'nt']) def print_obj(obj): for attr, val in obj.__dict__.iteritems(): print "{0}: {1}".format(attr, val) def convert_to_snake_case(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() def parse_int(text): digits = ''.join([c for c in text if c.isdigit()]) if digits.isdigit(): return int(digits) return None def as_client_tz(dt): return dt.astimezone(pytz.timezone(settings.CLIENT_TZ)) def make_data_updates_string(data_changes): updates = "" if data_changes: for key in data_changes: title = key.replace("_", " ").capitalize() old_val = data_changes[key]['old'] new_val = data_changes[key]['new'] updates += "\n{0}: {1} => {2}".format(title, old_val, new_val) return updates def delta_minutes(now, before): delta_datetime = now - before minutes_ago = int(delta_datetime.total_seconds() / 60) return minutes_ago <commit_msg>Add data change to updates string only if new value is not None in order to preserve scraped data, that user decided to hide.<commit_after>
from __future__ import unicode_literals from config import settings import os import re import string import pytz def clear_screen(): # Clear screen os.system(['clear', 'cls'][os.name == 'nt']) def print_obj(obj): for attr, val in obj.__dict__.iteritems(): print "{0}: {1}".format(attr, val) def convert_to_snake_case(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() def parse_int(text): digits = ''.join([c for c in text if c.isdigit()]) if digits.isdigit(): return int(digits) return None def as_client_tz(dt): return dt.astimezone(pytz.timezone(settings.CLIENT_TZ)) def make_data_updates_string(data_changes): updates = "" if data_changes: for key in data_changes: title = key.replace("_", " ").capitalize() old_val = data_changes[key]['old'] new_val = data_changes[key]['new'] if new_val: updates += "\n{0}: {1} => {2}".format(title, old_val, new_val) return updates def delta_minutes(now, before): delta_datetime = now - before minutes_ago = int(delta_datetime.total_seconds() / 60) return minutes_ago
from __future__ import unicode_literals from config import settings import os import re import string import pytz def clear_screen(): # Clear screen os.system(['clear', 'cls'][os.name == 'nt']) def print_obj(obj): for attr, val in obj.__dict__.iteritems(): print "{0}: {1}".format(attr, val) def convert_to_snake_case(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() def parse_int(text): digits = ''.join([c for c in text if c.isdigit()]) if digits.isdigit(): return int(digits) return None def as_client_tz(dt): return dt.astimezone(pytz.timezone(settings.CLIENT_TZ)) def make_data_updates_string(data_changes): updates = "" if data_changes: for key in data_changes: title = key.replace("_", " ").capitalize() old_val = data_changes[key]['old'] new_val = data_changes[key]['new'] updates += "\n{0}: {1} => {2}".format(title, old_val, new_val) return updates def delta_minutes(now, before): delta_datetime = now - before minutes_ago = int(delta_datetime.total_seconds() / 60) return minutes_ago Add data change to updates string only if new value is not None in order to preserve scraped data, that user decided to hide.from __future__ import unicode_literals from config import settings import os import re import string import pytz def clear_screen(): # Clear screen os.system(['clear', 'cls'][os.name == 'nt']) def print_obj(obj): for attr, val in obj.__dict__.iteritems(): print "{0}: {1}".format(attr, val) def convert_to_snake_case(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() def parse_int(text): digits = ''.join([c for c in text if c.isdigit()]) if digits.isdigit(): return int(digits) return None def as_client_tz(dt): return dt.astimezone(pytz.timezone(settings.CLIENT_TZ)) def make_data_updates_string(data_changes): updates = "" if data_changes: for key in data_changes: title = key.replace("_", " ").capitalize() old_val = data_changes[key]['old'] new_val = data_changes[key]['new'] if new_val: updates += "\n{0}: {1} => {2}".format(title, old_val, new_val) return updates def delta_minutes(now, before): delta_datetime = now - before minutes_ago = int(delta_datetime.total_seconds() / 60) return minutes_ago
<commit_before>from __future__ import unicode_literals from config import settings import os import re import string import pytz def clear_screen(): # Clear screen os.system(['clear', 'cls'][os.name == 'nt']) def print_obj(obj): for attr, val in obj.__dict__.iteritems(): print "{0}: {1}".format(attr, val) def convert_to_snake_case(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() def parse_int(text): digits = ''.join([c for c in text if c.isdigit()]) if digits.isdigit(): return int(digits) return None def as_client_tz(dt): return dt.astimezone(pytz.timezone(settings.CLIENT_TZ)) def make_data_updates_string(data_changes): updates = "" if data_changes: for key in data_changes: title = key.replace("_", " ").capitalize() old_val = data_changes[key]['old'] new_val = data_changes[key]['new'] updates += "\n{0}: {1} => {2}".format(title, old_val, new_val) return updates def delta_minutes(now, before): delta_datetime = now - before minutes_ago = int(delta_datetime.total_seconds() / 60) return minutes_ago <commit_msg>Add data change to updates string only if new value is not None in order to preserve scraped data, that user decided to hide.<commit_after>from __future__ import unicode_literals from config import settings import os import re import string import pytz def clear_screen(): # Clear screen os.system(['clear', 'cls'][os.name == 'nt']) def print_obj(obj): for attr, val in obj.__dict__.iteritems(): print "{0}: {1}".format(attr, val) def convert_to_snake_case(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() def parse_int(text): digits = ''.join([c for c in text if c.isdigit()]) if digits.isdigit(): return int(digits) return None def as_client_tz(dt): return dt.astimezone(pytz.timezone(settings.CLIENT_TZ)) def make_data_updates_string(data_changes): updates = "" if data_changes: for key in data_changes: title = key.replace("_", " ").capitalize() old_val = data_changes[key]['old'] new_val = data_changes[key]['new'] if new_val: updates += "\n{0}: {1} => {2}".format(title, old_val, new_val) return updates def delta_minutes(now, before): delta_datetime = now - before minutes_ago = int(delta_datetime.total_seconds() / 60) return minutes_ago
aab722e1072fe5857ee1f4dbe699676ac3c2c061
sparts/tasks/periodic.py
sparts/tasks/periodic.py
from ..vtask import VTask import time from ..sparts import option class PeriodicTask(VTask): INTERVAL = None interval = option('interval', type=float, metavar='SECONDS', default=lambda cls: cls.INTERVAL, help='How often this task should run [%(default)s] (s)') def initTask(self): super(PeriodicTask, self).initTask() assert self.getTaskOption('interval') is not None def _runloop(self): while not self.service._stop: end_time = time.time() + self.interval self.execute() while not self.service._stop: tn = time.time() to_sleep = end_time - tn if to_sleep <= 0: break time.sleep(min(0.1, to_sleep)) def execute(self, context=None): self.logger.debug('execute')
from ..vtask import VTask import time from ..sparts import option from threading import Event class PeriodicTask(VTask): INTERVAL = None interval = option('interval', type=float, metavar='SECONDS', default=lambda cls: cls.INTERVAL, help='How often this task should run [%(default)s] (s)') def initTask(self): super(PeriodicTask, self).initTask() assert self.getTaskOption('interval') is not None self.stop_event = Event() def stop(self): self.stop_event.set() super(PeriodicTask, self).stop() def _runloop(self): while not self.service._stop: t0 = time.time() self.execute() to_sleep = time.time() - (t0 + self.interval) if to_sleep > 0: if self.stop_event.wait(to_sleep): return def execute(self, context=None): self.logger.debug('execute')
Use threading.Event() to stop PeriodicTasks
Use threading.Event() to stop PeriodicTasks This is a lot more cpu efficient and results in less tasks swapping randomly.
Python
bsd-3-clause
fmoo/sparts,pshuff/sparts,bboozzoo/sparts,djipko/sparts,facebook/sparts,facebook/sparts,djipko/sparts,fmoo/sparts,pshuff/sparts,bboozzoo/sparts
from ..vtask import VTask import time from ..sparts import option class PeriodicTask(VTask): INTERVAL = None interval = option('interval', type=float, metavar='SECONDS', default=lambda cls: cls.INTERVAL, help='How often this task should run [%(default)s] (s)') def initTask(self): super(PeriodicTask, self).initTask() assert self.getTaskOption('interval') is not None def _runloop(self): while not self.service._stop: end_time = time.time() + self.interval self.execute() while not self.service._stop: tn = time.time() to_sleep = end_time - tn if to_sleep <= 0: break time.sleep(min(0.1, to_sleep)) def execute(self, context=None): self.logger.debug('execute') Use threading.Event() to stop PeriodicTasks This is a lot more cpu efficient and results in less tasks swapping randomly.
from ..vtask import VTask import time from ..sparts import option from threading import Event class PeriodicTask(VTask): INTERVAL = None interval = option('interval', type=float, metavar='SECONDS', default=lambda cls: cls.INTERVAL, help='How often this task should run [%(default)s] (s)') def initTask(self): super(PeriodicTask, self).initTask() assert self.getTaskOption('interval') is not None self.stop_event = Event() def stop(self): self.stop_event.set() super(PeriodicTask, self).stop() def _runloop(self): while not self.service._stop: t0 = time.time() self.execute() to_sleep = time.time() - (t0 + self.interval) if to_sleep > 0: if self.stop_event.wait(to_sleep): return def execute(self, context=None): self.logger.debug('execute')
<commit_before>from ..vtask import VTask import time from ..sparts import option class PeriodicTask(VTask): INTERVAL = None interval = option('interval', type=float, metavar='SECONDS', default=lambda cls: cls.INTERVAL, help='How often this task should run [%(default)s] (s)') def initTask(self): super(PeriodicTask, self).initTask() assert self.getTaskOption('interval') is not None def _runloop(self): while not self.service._stop: end_time = time.time() + self.interval self.execute() while not self.service._stop: tn = time.time() to_sleep = end_time - tn if to_sleep <= 0: break time.sleep(min(0.1, to_sleep)) def execute(self, context=None): self.logger.debug('execute') <commit_msg>Use threading.Event() to stop PeriodicTasks This is a lot more cpu efficient and results in less tasks swapping randomly.<commit_after>
from ..vtask import VTask import time from ..sparts import option from threading import Event class PeriodicTask(VTask): INTERVAL = None interval = option('interval', type=float, metavar='SECONDS', default=lambda cls: cls.INTERVAL, help='How often this task should run [%(default)s] (s)') def initTask(self): super(PeriodicTask, self).initTask() assert self.getTaskOption('interval') is not None self.stop_event = Event() def stop(self): self.stop_event.set() super(PeriodicTask, self).stop() def _runloop(self): while not self.service._stop: t0 = time.time() self.execute() to_sleep = time.time() - (t0 + self.interval) if to_sleep > 0: if self.stop_event.wait(to_sleep): return def execute(self, context=None): self.logger.debug('execute')
from ..vtask import VTask import time from ..sparts import option class PeriodicTask(VTask): INTERVAL = None interval = option('interval', type=float, metavar='SECONDS', default=lambda cls: cls.INTERVAL, help='How often this task should run [%(default)s] (s)') def initTask(self): super(PeriodicTask, self).initTask() assert self.getTaskOption('interval') is not None def _runloop(self): while not self.service._stop: end_time = time.time() + self.interval self.execute() while not self.service._stop: tn = time.time() to_sleep = end_time - tn if to_sleep <= 0: break time.sleep(min(0.1, to_sleep)) def execute(self, context=None): self.logger.debug('execute') Use threading.Event() to stop PeriodicTasks This is a lot more cpu efficient and results in less tasks swapping randomly.from ..vtask import VTask import time from ..sparts import option from threading import Event class PeriodicTask(VTask): INTERVAL = None interval = option('interval', type=float, metavar='SECONDS', default=lambda cls: cls.INTERVAL, help='How often this task should run [%(default)s] (s)') def initTask(self): super(PeriodicTask, self).initTask() assert self.getTaskOption('interval') is not None self.stop_event = Event() def stop(self): self.stop_event.set() super(PeriodicTask, self).stop() def _runloop(self): while not self.service._stop: t0 = time.time() self.execute() to_sleep = time.time() - (t0 + self.interval) if to_sleep > 0: if self.stop_event.wait(to_sleep): return def execute(self, context=None): self.logger.debug('execute')
<commit_before>from ..vtask import VTask import time from ..sparts import option class PeriodicTask(VTask): INTERVAL = None interval = option('interval', type=float, metavar='SECONDS', default=lambda cls: cls.INTERVAL, help='How often this task should run [%(default)s] (s)') def initTask(self): super(PeriodicTask, self).initTask() assert self.getTaskOption('interval') is not None def _runloop(self): while not self.service._stop: end_time = time.time() + self.interval self.execute() while not self.service._stop: tn = time.time() to_sleep = end_time - tn if to_sleep <= 0: break time.sleep(min(0.1, to_sleep)) def execute(self, context=None): self.logger.debug('execute') <commit_msg>Use threading.Event() to stop PeriodicTasks This is a lot more cpu efficient and results in less tasks swapping randomly.<commit_after>from ..vtask import VTask import time from ..sparts import option from threading import Event class PeriodicTask(VTask): INTERVAL = None interval = option('interval', type=float, metavar='SECONDS', default=lambda cls: cls.INTERVAL, help='How often this task should run [%(default)s] (s)') def initTask(self): super(PeriodicTask, self).initTask() assert self.getTaskOption('interval') is not None self.stop_event = Event() def stop(self): self.stop_event.set() super(PeriodicTask, self).stop() def _runloop(self): while not self.service._stop: t0 = time.time() self.execute() to_sleep = time.time() - (t0 + self.interval) if to_sleep > 0: if self.stop_event.wait(to_sleep): return def execute(self, context=None): self.logger.debug('execute')
e81155d845ec2455d5a673e06d614f7086ebd2e0
todo_file_generator/test/test_remove_file_more_than_a_week.py
todo_file_generator/test/test_remove_file_more_than_a_week.py
"""test_remove_file_more_than_a_week.py: Creates an todo file with title name as current date""" import os import time def get_files(): files_array = [] for file in os.listdir("files/"): if file.endswith(".todo"): files_array.append(file) return files_array # todo: fix file duration def test_should_return_file_duration(): files_directory = 'files/' file_list = get_files() one_week = time.time() - 604800 for file in file_list: file_path = files_directory + file file_stat = os.stat(file_path) mtime = file_stat.st_mtime if mtime > one_week: print('Remove ' + file + ' at the age of ' + mtime) def main(): test_should_return_file_duration() if __name__ == '__main__': main()
"""test_remove_file_more_than_a_week.py: Moves files to archive than a more than a week""" import os import time def get_files(): files_array = [] files_directory = 'files/' extension = 'todo' for file in os.listdir(files_directory): if file.endswith(extension): files_array.append(file) return files_array def move_file(source, target): os.rename(source, target) def test_should_return_file_duration(): files_directory = 'files/' archive_directory = 'archive/' date_format = '%Y-%m-%d %H:%M:%S' one_week = time.time() - 604800 file_list = get_files() for file in file_list: file_path = files_directory + file file_stat = os.stat(file_path) mtime = file_stat.st_mtime file_creation_time = time.strftime(date_format, time.localtime(mtime)) if mtime < one_week: print('Moving {} | Creation date: [{}]'.format(file, file_creation_time)) target_path = files_directory + archive_directory + file move_file(file_path, target_path) def main(): test_should_return_file_duration() if __name__ == '__main__': main()
Move files to archive test case
Move files to archive test case
Python
mit
prajesh-ananthan/Tools
"""test_remove_file_more_than_a_week.py: Creates an todo file with title name as current date""" import os import time def get_files(): files_array = [] for file in os.listdir("files/"): if file.endswith(".todo"): files_array.append(file) return files_array # todo: fix file duration def test_should_return_file_duration(): files_directory = 'files/' file_list = get_files() one_week = time.time() - 604800 for file in file_list: file_path = files_directory + file file_stat = os.stat(file_path) mtime = file_stat.st_mtime if mtime > one_week: print('Remove ' + file + ' at the age of ' + mtime) def main(): test_should_return_file_duration() if __name__ == '__main__': main() Move files to archive test case
"""test_remove_file_more_than_a_week.py: Moves files to archive than a more than a week""" import os import time def get_files(): files_array = [] files_directory = 'files/' extension = 'todo' for file in os.listdir(files_directory): if file.endswith(extension): files_array.append(file) return files_array def move_file(source, target): os.rename(source, target) def test_should_return_file_duration(): files_directory = 'files/' archive_directory = 'archive/' date_format = '%Y-%m-%d %H:%M:%S' one_week = time.time() - 604800 file_list = get_files() for file in file_list: file_path = files_directory + file file_stat = os.stat(file_path) mtime = file_stat.st_mtime file_creation_time = time.strftime(date_format, time.localtime(mtime)) if mtime < one_week: print('Moving {} | Creation date: [{}]'.format(file, file_creation_time)) target_path = files_directory + archive_directory + file move_file(file_path, target_path) def main(): test_should_return_file_duration() if __name__ == '__main__': main()
<commit_before>"""test_remove_file_more_than_a_week.py: Creates an todo file with title name as current date""" import os import time def get_files(): files_array = [] for file in os.listdir("files/"): if file.endswith(".todo"): files_array.append(file) return files_array # todo: fix file duration def test_should_return_file_duration(): files_directory = 'files/' file_list = get_files() one_week = time.time() - 604800 for file in file_list: file_path = files_directory + file file_stat = os.stat(file_path) mtime = file_stat.st_mtime if mtime > one_week: print('Remove ' + file + ' at the age of ' + mtime) def main(): test_should_return_file_duration() if __name__ == '__main__': main() <commit_msg>Move files to archive test case<commit_after>
"""test_remove_file_more_than_a_week.py: Moves files to archive than a more than a week""" import os import time def get_files(): files_array = [] files_directory = 'files/' extension = 'todo' for file in os.listdir(files_directory): if file.endswith(extension): files_array.append(file) return files_array def move_file(source, target): os.rename(source, target) def test_should_return_file_duration(): files_directory = 'files/' archive_directory = 'archive/' date_format = '%Y-%m-%d %H:%M:%S' one_week = time.time() - 604800 file_list = get_files() for file in file_list: file_path = files_directory + file file_stat = os.stat(file_path) mtime = file_stat.st_mtime file_creation_time = time.strftime(date_format, time.localtime(mtime)) if mtime < one_week: print('Moving {} | Creation date: [{}]'.format(file, file_creation_time)) target_path = files_directory + archive_directory + file move_file(file_path, target_path) def main(): test_should_return_file_duration() if __name__ == '__main__': main()
"""test_remove_file_more_than_a_week.py: Creates an todo file with title name as current date""" import os import time def get_files(): files_array = [] for file in os.listdir("files/"): if file.endswith(".todo"): files_array.append(file) return files_array # todo: fix file duration def test_should_return_file_duration(): files_directory = 'files/' file_list = get_files() one_week = time.time() - 604800 for file in file_list: file_path = files_directory + file file_stat = os.stat(file_path) mtime = file_stat.st_mtime if mtime > one_week: print('Remove ' + file + ' at the age of ' + mtime) def main(): test_should_return_file_duration() if __name__ == '__main__': main() Move files to archive test case"""test_remove_file_more_than_a_week.py: Moves files to archive than a more than a week""" import os import time def get_files(): files_array = [] files_directory = 'files/' extension = 'todo' for file in os.listdir(files_directory): if file.endswith(extension): files_array.append(file) return files_array def move_file(source, target): os.rename(source, target) def test_should_return_file_duration(): files_directory = 'files/' archive_directory = 'archive/' date_format = '%Y-%m-%d %H:%M:%S' one_week = time.time() - 604800 file_list = get_files() for file in file_list: file_path = files_directory + file file_stat = os.stat(file_path) mtime = file_stat.st_mtime file_creation_time = time.strftime(date_format, time.localtime(mtime)) if mtime < one_week: print('Moving {} | Creation date: [{}]'.format(file, file_creation_time)) target_path = files_directory + archive_directory + file move_file(file_path, target_path) def main(): test_should_return_file_duration() if __name__ == '__main__': main()
<commit_before>"""test_remove_file_more_than_a_week.py: Creates an todo file with title name as current date""" import os import time def get_files(): files_array = [] for file in os.listdir("files/"): if file.endswith(".todo"): files_array.append(file) return files_array # todo: fix file duration def test_should_return_file_duration(): files_directory = 'files/' file_list = get_files() one_week = time.time() - 604800 for file in file_list: file_path = files_directory + file file_stat = os.stat(file_path) mtime = file_stat.st_mtime if mtime > one_week: print('Remove ' + file + ' at the age of ' + mtime) def main(): test_should_return_file_duration() if __name__ == '__main__': main() <commit_msg>Move files to archive test case<commit_after>"""test_remove_file_more_than_a_week.py: Moves files to archive than a more than a week""" import os import time def get_files(): files_array = [] files_directory = 'files/' extension = 'todo' for file in os.listdir(files_directory): if file.endswith(extension): files_array.append(file) return files_array def move_file(source, target): os.rename(source, target) def test_should_return_file_duration(): files_directory = 'files/' archive_directory = 'archive/' date_format = '%Y-%m-%d %H:%M:%S' one_week = time.time() - 604800 file_list = get_files() for file in file_list: file_path = files_directory + file file_stat = os.stat(file_path) mtime = file_stat.st_mtime file_creation_time = time.strftime(date_format, time.localtime(mtime)) if mtime < one_week: print('Moving {} | Creation date: [{}]'.format(file, file_creation_time)) target_path = files_directory + archive_directory + file move_file(file_path, target_path) def main(): test_should_return_file_duration() if __name__ == '__main__': main()
8e6532b9e3d47948f6d1a37b74e54c91a8cdc0b4
examples/translations/japanese_test_1.py
examples/translations/japanese_test_1.py
# Japanese Language Test from seleniumbase.translate.japanese import セレニウムテストケース # noqa class 私のテストクラス(セレニウムテストケース): def test_例1(self): self.を開く("https://ja.wikipedia.org/wiki/") self.テキストを確認する("ウィキペディア") self.要素を確認する('[title*="メインページに移動する"]') self.JS入力('input[name="search"]', "アニメ") self.クリックして("#searchform button") self.テキストを確認する("アニメ", "#firstHeading") self.JS入力('input[name="search"]', "寿司") self.クリックして("#searchform button") self.テキストを確認する("寿司", "#firstHeading") self.要素を確認する('img[alt="握り寿司"]') self.JS入力("#searchInput", "レゴランド・ジャパン") self.クリックして("#searchform button") self.要素を確認する('img[alt*="LEGOLAND JAPAN"]') self.リンクテキストを確認する("名古屋城") self.リンクテキストをクリックします("テーマパーク") self.テキストを確認する("テーマパーク", "#firstHeading")
# Japanese Language Test from seleniumbase.translate.japanese import セレニウムテストケース # noqa class 私のテストクラス(セレニウムテストケース): def test_例1(self): self.を開く("https://ja.wikipedia.org/wiki/") self.テキストを確認する("ウィキペディア") self.要素を確認する('[title*="ウィキペディアへようこそ"]') self.JS入力('input[name="search"]', "アニメ") self.クリックして("#searchform button") self.テキストを確認する("アニメ", "#firstHeading") self.JS入力('input[name="search"]', "寿司") self.クリックして("#searchform button") self.テキストを確認する("寿司", "#firstHeading") self.要素を確認する('img[alt="握り寿司"]') self.JS入力("#searchInput", "レゴランド・ジャパン") self.クリックして("#searchform button") self.要素を確認する('img[alt*="LEGOLAND JAPAN"]') self.リンクテキストを確認する("名古屋城") self.リンクテキストをクリックします("テーマパーク") self.テキストを確認する("テーマパーク", "#firstHeading")
Update the Japanese example test
Update the Japanese example test
Python
mit
seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase
# Japanese Language Test from seleniumbase.translate.japanese import セレニウムテストケース # noqa class 私のテストクラス(セレニウムテストケース): def test_例1(self): self.を開く("https://ja.wikipedia.org/wiki/") self.テキストを確認する("ウィキペディア") self.要素を確認する('[title*="メインページに移動する"]') self.JS入力('input[name="search"]', "アニメ") self.クリックして("#searchform button") self.テキストを確認する("アニメ", "#firstHeading") self.JS入力('input[name="search"]', "寿司") self.クリックして("#searchform button") self.テキストを確認する("寿司", "#firstHeading") self.要素を確認する('img[alt="握り寿司"]') self.JS入力("#searchInput", "レゴランド・ジャパン") self.クリックして("#searchform button") self.要素を確認する('img[alt*="LEGOLAND JAPAN"]') self.リンクテキストを確認する("名古屋城") self.リンクテキストをクリックします("テーマパーク") self.テキストを確認する("テーマパーク", "#firstHeading") Update the Japanese example test
# Japanese Language Test from seleniumbase.translate.japanese import セレニウムテストケース # noqa class 私のテストクラス(セレニウムテストケース): def test_例1(self): self.を開く("https://ja.wikipedia.org/wiki/") self.テキストを確認する("ウィキペディア") self.要素を確認する('[title*="ウィキペディアへようこそ"]') self.JS入力('input[name="search"]', "アニメ") self.クリックして("#searchform button") self.テキストを確認する("アニメ", "#firstHeading") self.JS入力('input[name="search"]', "寿司") self.クリックして("#searchform button") self.テキストを確認する("寿司", "#firstHeading") self.要素を確認する('img[alt="握り寿司"]') self.JS入力("#searchInput", "レゴランド・ジャパン") self.クリックして("#searchform button") self.要素を確認する('img[alt*="LEGOLAND JAPAN"]') self.リンクテキストを確認する("名古屋城") self.リンクテキストをクリックします("テーマパーク") self.テキストを確認する("テーマパーク", "#firstHeading")
<commit_before># Japanese Language Test from seleniumbase.translate.japanese import セレニウムテストケース # noqa class 私のテストクラス(セレニウムテストケース): def test_例1(self): self.を開く("https://ja.wikipedia.org/wiki/") self.テキストを確認する("ウィキペディア") self.要素を確認する('[title*="メインページに移動する"]') self.JS入力('input[name="search"]', "アニメ") self.クリックして("#searchform button") self.テキストを確認する("アニメ", "#firstHeading") self.JS入力('input[name="search"]', "寿司") self.クリックして("#searchform button") self.テキストを確認する("寿司", "#firstHeading") self.要素を確認する('img[alt="握り寿司"]') self.JS入力("#searchInput", "レゴランド・ジャパン") self.クリックして("#searchform button") self.要素を確認する('img[alt*="LEGOLAND JAPAN"]') self.リンクテキストを確認する("名古屋城") self.リンクテキストをクリックします("テーマパーク") self.テキストを確認する("テーマパーク", "#firstHeading") <commit_msg>Update the Japanese example test<commit_after>
# Japanese Language Test from seleniumbase.translate.japanese import セレニウムテストケース # noqa class 私のテストクラス(セレニウムテストケース): def test_例1(self): self.を開く("https://ja.wikipedia.org/wiki/") self.テキストを確認する("ウィキペディア") self.要素を確認する('[title*="ウィキペディアへようこそ"]') self.JS入力('input[name="search"]', "アニメ") self.クリックして("#searchform button") self.テキストを確認する("アニメ", "#firstHeading") self.JS入力('input[name="search"]', "寿司") self.クリックして("#searchform button") self.テキストを確認する("寿司", "#firstHeading") self.要素を確認する('img[alt="握り寿司"]') self.JS入力("#searchInput", "レゴランド・ジャパン") self.クリックして("#searchform button") self.要素を確認する('img[alt*="LEGOLAND JAPAN"]') self.リンクテキストを確認する("名古屋城") self.リンクテキストをクリックします("テーマパーク") self.テキストを確認する("テーマパーク", "#firstHeading")
# Japanese Language Test from seleniumbase.translate.japanese import セレニウムテストケース # noqa class 私のテストクラス(セレニウムテストケース): def test_例1(self): self.を開く("https://ja.wikipedia.org/wiki/") self.テキストを確認する("ウィキペディア") self.要素を確認する('[title*="メインページに移動する"]') self.JS入力('input[name="search"]', "アニメ") self.クリックして("#searchform button") self.テキストを確認する("アニメ", "#firstHeading") self.JS入力('input[name="search"]', "寿司") self.クリックして("#searchform button") self.テキストを確認する("寿司", "#firstHeading") self.要素を確認する('img[alt="握り寿司"]') self.JS入力("#searchInput", "レゴランド・ジャパン") self.クリックして("#searchform button") self.要素を確認する('img[alt*="LEGOLAND JAPAN"]') self.リンクテキストを確認する("名古屋城") self.リンクテキストをクリックします("テーマパーク") self.テキストを確認する("テーマパーク", "#firstHeading") Update the Japanese example test# Japanese Language Test from seleniumbase.translate.japanese import セレニウムテストケース # noqa class 私のテストクラス(セレニウムテストケース): def test_例1(self): self.を開く("https://ja.wikipedia.org/wiki/") self.テキストを確認する("ウィキペディア") self.要素を確認する('[title*="ウィキペディアへようこそ"]') self.JS入力('input[name="search"]', "アニメ") self.クリックして("#searchform button") self.テキストを確認する("アニメ", "#firstHeading") self.JS入力('input[name="search"]', "寿司") self.クリックして("#searchform button") self.テキストを確認する("寿司", "#firstHeading") self.要素を確認する('img[alt="握り寿司"]') self.JS入力("#searchInput", "レゴランド・ジャパン") self.クリックして("#searchform button") self.要素を確認する('img[alt*="LEGOLAND JAPAN"]') self.リンクテキストを確認する("名古屋城") self.リンクテキストをクリックします("テーマパーク") self.テキストを確認する("テーマパーク", "#firstHeading")
<commit_before># Japanese Language Test from seleniumbase.translate.japanese import セレニウムテストケース # noqa class 私のテストクラス(セレニウムテストケース): def test_例1(self): self.を開く("https://ja.wikipedia.org/wiki/") self.テキストを確認する("ウィキペディア") self.要素を確認する('[title*="メインページに移動する"]') self.JS入力('input[name="search"]', "アニメ") self.クリックして("#searchform button") self.テキストを確認する("アニメ", "#firstHeading") self.JS入力('input[name="search"]', "寿司") self.クリックして("#searchform button") self.テキストを確認する("寿司", "#firstHeading") self.要素を確認する('img[alt="握り寿司"]') self.JS入力("#searchInput", "レゴランド・ジャパン") self.クリックして("#searchform button") self.要素を確認する('img[alt*="LEGOLAND JAPAN"]') self.リンクテキストを確認する("名古屋城") self.リンクテキストをクリックします("テーマパーク") self.テキストを確認する("テーマパーク", "#firstHeading") <commit_msg>Update the Japanese example test<commit_after># Japanese Language Test from seleniumbase.translate.japanese import セレニウムテストケース # noqa class 私のテストクラス(セレニウムテストケース): def test_例1(self): self.を開く("https://ja.wikipedia.org/wiki/") self.テキストを確認する("ウィキペディア") self.要素を確認する('[title*="ウィキペディアへようこそ"]') self.JS入力('input[name="search"]', "アニメ") self.クリックして("#searchform button") self.テキストを確認する("アニメ", "#firstHeading") self.JS入力('input[name="search"]', "寿司") self.クリックして("#searchform button") self.テキストを確認する("寿司", "#firstHeading") self.要素を確認する('img[alt="握り寿司"]') self.JS入力("#searchInput", "レゴランド・ジャパン") self.クリックして("#searchform button") self.要素を確認する('img[alt*="LEGOLAND JAPAN"]') self.リンクテキストを確認する("名古屋城") self.リンクテキストをクリックします("テーマパーク") self.テキストを確認する("テーマパーク", "#firstHeading")
a6935b78a8411fafe05543d928449a98ba89c4be
Orange/tests/test_sparse_table.py
Orange/tests/test_sparse_table.py
import unittest import numpy as np from scipy.sparse import csr_matrix, lil_matrix from Orange import data from Orange.tests import test_table as tabletests class InterfaceTest(tabletests.InterfaceTest): def setUp(self): super().setUp() self.table = data.Table.from_numpy( self.domain, csr_matrix(self.table.X), csr_matrix(self.table.Y), ) def test_append_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_insert_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_delete_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_clear(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_row_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_value_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment()
import unittest import numpy as np from scipy.sparse import csr_matrix, lil_matrix from Orange import data from Orange.tests import test_table as tabletests class InterfaceTest(tabletests.InterfaceTest): def setUp(self): super().setUp() self.table = data.Table.from_numpy( self.domain, csr_matrix(self.table.X), csr_matrix(self.table.Y), ) def test_append_rows(self): with self.assertRaises(ValueError): super().test_append_rows() def test_insert_rows(self): with self.assertRaises(ValueError): super().test_insert_rows() def test_delete_rows(self): with self.assertRaises(ValueError): super().test_delete_rows() def test_clear(self): with self.assertRaises(ValueError): super().test_clear() def test_row_assignment(self): with self.assertRaises(ValueError): super().test_row_assignment() def test_value_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment()
Call same methods on parent class.
Call same methods on parent class.
Python
bsd-2-clause
marinkaz/orange3,kwikadi/orange3,kwikadi/orange3,qPCR4vir/orange3,qPCR4vir/orange3,marinkaz/orange3,qusp/orange3,marinkaz/orange3,qusp/orange3,cheral/orange3,qPCR4vir/orange3,marinkaz/orange3,cheral/orange3,cheral/orange3,cheral/orange3,qPCR4vir/orange3,kwikadi/orange3,cheral/orange3,qusp/orange3,marinkaz/orange3,marinkaz/orange3,qPCR4vir/orange3,cheral/orange3,kwikadi/orange3,qPCR4vir/orange3,kwikadi/orange3,qusp/orange3,kwikadi/orange3
import unittest import numpy as np from scipy.sparse import csr_matrix, lil_matrix from Orange import data from Orange.tests import test_table as tabletests class InterfaceTest(tabletests.InterfaceTest): def setUp(self): super().setUp() self.table = data.Table.from_numpy( self.domain, csr_matrix(self.table.X), csr_matrix(self.table.Y), ) def test_append_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_insert_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_delete_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_clear(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_row_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_value_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment() Call same methods on parent class.
import unittest import numpy as np from scipy.sparse import csr_matrix, lil_matrix from Orange import data from Orange.tests import test_table as tabletests class InterfaceTest(tabletests.InterfaceTest): def setUp(self): super().setUp() self.table = data.Table.from_numpy( self.domain, csr_matrix(self.table.X), csr_matrix(self.table.Y), ) def test_append_rows(self): with self.assertRaises(ValueError): super().test_append_rows() def test_insert_rows(self): with self.assertRaises(ValueError): super().test_insert_rows() def test_delete_rows(self): with self.assertRaises(ValueError): super().test_delete_rows() def test_clear(self): with self.assertRaises(ValueError): super().test_clear() def test_row_assignment(self): with self.assertRaises(ValueError): super().test_row_assignment() def test_value_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment()
<commit_before>import unittest import numpy as np from scipy.sparse import csr_matrix, lil_matrix from Orange import data from Orange.tests import test_table as tabletests class InterfaceTest(tabletests.InterfaceTest): def setUp(self): super().setUp() self.table = data.Table.from_numpy( self.domain, csr_matrix(self.table.X), csr_matrix(self.table.Y), ) def test_append_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_insert_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_delete_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_clear(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_row_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_value_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment() <commit_msg>Call same methods on parent class.<commit_after>
import unittest import numpy as np from scipy.sparse import csr_matrix, lil_matrix from Orange import data from Orange.tests import test_table as tabletests class InterfaceTest(tabletests.InterfaceTest): def setUp(self): super().setUp() self.table = data.Table.from_numpy( self.domain, csr_matrix(self.table.X), csr_matrix(self.table.Y), ) def test_append_rows(self): with self.assertRaises(ValueError): super().test_append_rows() def test_insert_rows(self): with self.assertRaises(ValueError): super().test_insert_rows() def test_delete_rows(self): with self.assertRaises(ValueError): super().test_delete_rows() def test_clear(self): with self.assertRaises(ValueError): super().test_clear() def test_row_assignment(self): with self.assertRaises(ValueError): super().test_row_assignment() def test_value_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment()
import unittest import numpy as np from scipy.sparse import csr_matrix, lil_matrix from Orange import data from Orange.tests import test_table as tabletests class InterfaceTest(tabletests.InterfaceTest): def setUp(self): super().setUp() self.table = data.Table.from_numpy( self.domain, csr_matrix(self.table.X), csr_matrix(self.table.Y), ) def test_append_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_insert_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_delete_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_clear(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_row_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_value_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment() Call same methods on parent class.import unittest import numpy as np from scipy.sparse import csr_matrix, lil_matrix from Orange import data from Orange.tests import test_table as tabletests class InterfaceTest(tabletests.InterfaceTest): def setUp(self): super().setUp() self.table = data.Table.from_numpy( self.domain, csr_matrix(self.table.X), csr_matrix(self.table.Y), ) def test_append_rows(self): with self.assertRaises(ValueError): super().test_append_rows() def test_insert_rows(self): with self.assertRaises(ValueError): super().test_insert_rows() def test_delete_rows(self): with self.assertRaises(ValueError): super().test_delete_rows() def test_clear(self): with self.assertRaises(ValueError): super().test_clear() def test_row_assignment(self): with self.assertRaises(ValueError): super().test_row_assignment() def test_value_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment()
<commit_before>import unittest import numpy as np from scipy.sparse import csr_matrix, lil_matrix from Orange import data from Orange.tests import test_table as tabletests class InterfaceTest(tabletests.InterfaceTest): def setUp(self): super().setUp() self.table = data.Table.from_numpy( self.domain, csr_matrix(self.table.X), csr_matrix(self.table.Y), ) def test_append_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_insert_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_delete_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_clear(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_row_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_value_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment() <commit_msg>Call same methods on parent class.<commit_after>import unittest import numpy as np from scipy.sparse import csr_matrix, lil_matrix from Orange import data from Orange.tests import test_table as tabletests class InterfaceTest(tabletests.InterfaceTest): def setUp(self): super().setUp() self.table = data.Table.from_numpy( self.domain, csr_matrix(self.table.X), csr_matrix(self.table.Y), ) def test_append_rows(self): with self.assertRaises(ValueError): super().test_append_rows() def test_insert_rows(self): with self.assertRaises(ValueError): super().test_insert_rows() def test_delete_rows(self): with self.assertRaises(ValueError): super().test_delete_rows() def test_clear(self): with self.assertRaises(ValueError): super().test_clear() def test_row_assignment(self): with self.assertRaises(ValueError): super().test_row_assignment() def test_value_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment()
d2e9289167b538fe5ef83edcbfce3d5f023de088
lib/core/countpage.py
lib/core/countpage.py
#!/usr/bin/env python ''' Copyright (c) 2016 anti-XSS developers ''' class CountPage(object): __number = 0 def __init__(self, number=0): self.__number = number def setNumber(self, number): self.__number = number def getNumber(self): return self.__number def incNumber(self): self.__number += 1
#!/usr/bin/env python ''' Copyright (c) 2016 anti-XSS developers ''' class CountPage(object): number = 0 def __init__(self, number=0): self.number = number def setNumber(self, number): self.number = number def getNumber(self): return self.number def incNumber(self): self.number += 1
Modify CountPage to a public class
Modify CountPage to a public class
Python
mit
lewangbtcc/anti-XSS,lewangbtcc/anti-XSS
#!/usr/bin/env python ''' Copyright (c) 2016 anti-XSS developers ''' class CountPage(object): __number = 0 def __init__(self, number=0): self.__number = number def setNumber(self, number): self.__number = number def getNumber(self): return self.__number def incNumber(self): self.__number += 1 Modify CountPage to a public class
#!/usr/bin/env python ''' Copyright (c) 2016 anti-XSS developers ''' class CountPage(object): number = 0 def __init__(self, number=0): self.number = number def setNumber(self, number): self.number = number def getNumber(self): return self.number def incNumber(self): self.number += 1
<commit_before>#!/usr/bin/env python ''' Copyright (c) 2016 anti-XSS developers ''' class CountPage(object): __number = 0 def __init__(self, number=0): self.__number = number def setNumber(self, number): self.__number = number def getNumber(self): return self.__number def incNumber(self): self.__number += 1 <commit_msg>Modify CountPage to a public class<commit_after>
#!/usr/bin/env python ''' Copyright (c) 2016 anti-XSS developers ''' class CountPage(object): number = 0 def __init__(self, number=0): self.number = number def setNumber(self, number): self.number = number def getNumber(self): return self.number def incNumber(self): self.number += 1
#!/usr/bin/env python ''' Copyright (c) 2016 anti-XSS developers ''' class CountPage(object): __number = 0 def __init__(self, number=0): self.__number = number def setNumber(self, number): self.__number = number def getNumber(self): return self.__number def incNumber(self): self.__number += 1 Modify CountPage to a public class#!/usr/bin/env python ''' Copyright (c) 2016 anti-XSS developers ''' class CountPage(object): number = 0 def __init__(self, number=0): self.number = number def setNumber(self, number): self.number = number def getNumber(self): return self.number def incNumber(self): self.number += 1
<commit_before>#!/usr/bin/env python ''' Copyright (c) 2016 anti-XSS developers ''' class CountPage(object): __number = 0 def __init__(self, number=0): self.__number = number def setNumber(self, number): self.__number = number def getNumber(self): return self.__number def incNumber(self): self.__number += 1 <commit_msg>Modify CountPage to a public class<commit_after>#!/usr/bin/env python ''' Copyright (c) 2016 anti-XSS developers ''' class CountPage(object): number = 0 def __init__(self, number=0): self.number = number def setNumber(self, number): self.number = number def getNumber(self): return self.number def incNumber(self): self.number += 1
27e7a2a429367b52ae7eff6b1b4aaf9adc212813
JasmineCoffeeScriptDetectFileType.py
JasmineCoffeeScriptDetectFileType.py
import sublime, sublime_plugin import os class JasmineCoffeeScriptDetectFileTypeCommand(sublime_plugin.EventListener): """ Detects current file type if the file's extension isn't conclusive """ """ Modified for Ruby on Rails and Sublime Text 2 """ """ Original pastie here: http://pastie.org/private/kz8gtts0cjcvkec0d4quqa """ def on_load(self, view): filename = view.file_name() if not filename: # buffer has never been saved return name = os.path.basename(filename.lower()) if name.endswith("spec.js.coffee") or name.endswith("spec.coffee"): set_syntax(view, "jasmine-coffeescript", "jasmine-coffeescript/Syntaxes") def set_syntax(view, syntax, path=None): if path is None: path = syntax view.settings().set('syntax', 'Packages/'+ path + '/' + syntax + '.tmLanguage') print("Switched syntax to: " + syntax)
import sublime, sublime_plugin import os class JasmineCoffeeScriptDetectFileTypeCommand(sublime_plugin.EventListener): """ Detects current file type if the file's extension isn't conclusive """ def on_load(self, view): filename = view.file_name() if not filename: # buffer has never been saved return name = os.path.basename(filename.lower()) if name.endswith("spec.js.coffee") or name.endswith("spec.coffee"): set_syntax(view, "jasmine-coffeescript", "jasmine-coffeescript/Syntaxes") def set_syntax(view, syntax, path=None): if path is None: path = syntax view.settings().set('syntax', 'Packages/'+ path + '/' + syntax + '.tmLanguage') print("Switched syntax to: " + syntax)
Remove copied comment from Rspec Syntax detector
Remove copied comment from Rspec Syntax detector
Python
mit
integrum/sublime-text-jasmine-coffeescript
import sublime, sublime_plugin import os class JasmineCoffeeScriptDetectFileTypeCommand(sublime_plugin.EventListener): """ Detects current file type if the file's extension isn't conclusive """ """ Modified for Ruby on Rails and Sublime Text 2 """ """ Original pastie here: http://pastie.org/private/kz8gtts0cjcvkec0d4quqa """ def on_load(self, view): filename = view.file_name() if not filename: # buffer has never been saved return name = os.path.basename(filename.lower()) if name.endswith("spec.js.coffee") or name.endswith("spec.coffee"): set_syntax(view, "jasmine-coffeescript", "jasmine-coffeescript/Syntaxes") def set_syntax(view, syntax, path=None): if path is None: path = syntax view.settings().set('syntax', 'Packages/'+ path + '/' + syntax + '.tmLanguage') print("Switched syntax to: " + syntax) Remove copied comment from Rspec Syntax detector
import sublime, sublime_plugin import os class JasmineCoffeeScriptDetectFileTypeCommand(sublime_plugin.EventListener): """ Detects current file type if the file's extension isn't conclusive """ def on_load(self, view): filename = view.file_name() if not filename: # buffer has never been saved return name = os.path.basename(filename.lower()) if name.endswith("spec.js.coffee") or name.endswith("spec.coffee"): set_syntax(view, "jasmine-coffeescript", "jasmine-coffeescript/Syntaxes") def set_syntax(view, syntax, path=None): if path is None: path = syntax view.settings().set('syntax', 'Packages/'+ path + '/' + syntax + '.tmLanguage') print("Switched syntax to: " + syntax)
<commit_before>import sublime, sublime_plugin import os class JasmineCoffeeScriptDetectFileTypeCommand(sublime_plugin.EventListener): """ Detects current file type if the file's extension isn't conclusive """ """ Modified for Ruby on Rails and Sublime Text 2 """ """ Original pastie here: http://pastie.org/private/kz8gtts0cjcvkec0d4quqa """ def on_load(self, view): filename = view.file_name() if not filename: # buffer has never been saved return name = os.path.basename(filename.lower()) if name.endswith("spec.js.coffee") or name.endswith("spec.coffee"): set_syntax(view, "jasmine-coffeescript", "jasmine-coffeescript/Syntaxes") def set_syntax(view, syntax, path=None): if path is None: path = syntax view.settings().set('syntax', 'Packages/'+ path + '/' + syntax + '.tmLanguage') print("Switched syntax to: " + syntax) <commit_msg>Remove copied comment from Rspec Syntax detector<commit_after>
import sublime, sublime_plugin import os class JasmineCoffeeScriptDetectFileTypeCommand(sublime_plugin.EventListener): """ Detects current file type if the file's extension isn't conclusive """ def on_load(self, view): filename = view.file_name() if not filename: # buffer has never been saved return name = os.path.basename(filename.lower()) if name.endswith("spec.js.coffee") or name.endswith("spec.coffee"): set_syntax(view, "jasmine-coffeescript", "jasmine-coffeescript/Syntaxes") def set_syntax(view, syntax, path=None): if path is None: path = syntax view.settings().set('syntax', 'Packages/'+ path + '/' + syntax + '.tmLanguage') print("Switched syntax to: " + syntax)
import sublime, sublime_plugin import os class JasmineCoffeeScriptDetectFileTypeCommand(sublime_plugin.EventListener): """ Detects current file type if the file's extension isn't conclusive """ """ Modified for Ruby on Rails and Sublime Text 2 """ """ Original pastie here: http://pastie.org/private/kz8gtts0cjcvkec0d4quqa """ def on_load(self, view): filename = view.file_name() if not filename: # buffer has never been saved return name = os.path.basename(filename.lower()) if name.endswith("spec.js.coffee") or name.endswith("spec.coffee"): set_syntax(view, "jasmine-coffeescript", "jasmine-coffeescript/Syntaxes") def set_syntax(view, syntax, path=None): if path is None: path = syntax view.settings().set('syntax', 'Packages/'+ path + '/' + syntax + '.tmLanguage') print("Switched syntax to: " + syntax) Remove copied comment from Rspec Syntax detectorimport sublime, sublime_plugin import os class JasmineCoffeeScriptDetectFileTypeCommand(sublime_plugin.EventListener): """ Detects current file type if the file's extension isn't conclusive """ def on_load(self, view): filename = view.file_name() if not filename: # buffer has never been saved return name = os.path.basename(filename.lower()) if name.endswith("spec.js.coffee") or name.endswith("spec.coffee"): set_syntax(view, "jasmine-coffeescript", "jasmine-coffeescript/Syntaxes") def set_syntax(view, syntax, path=None): if path is None: path = syntax view.settings().set('syntax', 'Packages/'+ path + '/' + syntax + '.tmLanguage') print("Switched syntax to: " + syntax)
<commit_before>import sublime, sublime_plugin import os class JasmineCoffeeScriptDetectFileTypeCommand(sublime_plugin.EventListener): """ Detects current file type if the file's extension isn't conclusive """ """ Modified for Ruby on Rails and Sublime Text 2 """ """ Original pastie here: http://pastie.org/private/kz8gtts0cjcvkec0d4quqa """ def on_load(self, view): filename = view.file_name() if not filename: # buffer has never been saved return name = os.path.basename(filename.lower()) if name.endswith("spec.js.coffee") or name.endswith("spec.coffee"): set_syntax(view, "jasmine-coffeescript", "jasmine-coffeescript/Syntaxes") def set_syntax(view, syntax, path=None): if path is None: path = syntax view.settings().set('syntax', 'Packages/'+ path + '/' + syntax + '.tmLanguage') print("Switched syntax to: " + syntax) <commit_msg>Remove copied comment from Rspec Syntax detector<commit_after>import sublime, sublime_plugin import os class JasmineCoffeeScriptDetectFileTypeCommand(sublime_plugin.EventListener): """ Detects current file type if the file's extension isn't conclusive """ def on_load(self, view): filename = view.file_name() if not filename: # buffer has never been saved return name = os.path.basename(filename.lower()) if name.endswith("spec.js.coffee") or name.endswith("spec.coffee"): set_syntax(view, "jasmine-coffeescript", "jasmine-coffeescript/Syntaxes") def set_syntax(view, syntax, path=None): if path is None: path = syntax view.settings().set('syntax', 'Packages/'+ path + '/' + syntax + '.tmLanguage') print("Switched syntax to: " + syntax)
a35a25732159e4c8b5655755ce31ec4c3e6e7975
dummy_robot/dummy_robot_bringup/launch/dummy_robot_bringup.launch.py
dummy_robot/dummy_robot_bringup/launch/dummy_robot_bringup.launch.py
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch_ros.actions import Node def generate_launch_description(): # TODO(wjwwood): Use a substitution to find share directory once this is implemented in launch urdf = os.path.join(get_package_share_directory('dummy_robot_bringup'), 'launch', 'single_rrbot.urdf') return LaunchDescription([ Node(package='dummy_map_server', node_executable='dummy_map_server', output='screen'), Node(package='robot_state_publisher', node_executable='robot_state_publisher', output='screen', arguments=[urdf]), Node(package='dummy_sensors', node_executable='dummy_joint_states', output='screen'), Node(package='dummy_sensors', node_executable='dummy_laser', output='screen') ])
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from launch import LaunchDescription from launch_ros.actions import Node from launch_ros.substitutions import FindPackageShare def generate_launch_description(): pkg_share = FindPackageShare('dummy_robot_bringup').find('dummy_robot_bringup') urdf_file = os.path.join(pkg_share, 'launch', 'single_rrbot.urdf') with open(urdf_file, 'r') as infp: robot_desc = infp.read() rsp_params = {'robot_description': robot_desc} return LaunchDescription([ Node(package='dummy_map_server', node_executable='dummy_map_server', output='screen'), Node(package='robot_state_publisher', node_executable='robot_state_publisher_node', output='screen', parameters=[rsp_params]), Node(package='dummy_sensors', node_executable='dummy_joint_states', output='screen'), Node(package='dummy_sensors', node_executable='dummy_laser', output='screen') ])
Switch dummy_robot_bringup to use parameter for rsp.
Switch dummy_robot_bringup to use parameter for rsp. Signed-off-by: Chris Lalancette <281cd07d7578d97c83271fbbf2faddb83ab3791c@openrobotics.org>
Python
apache-2.0
ros2/demos,ros2/demos,ros2/demos,ros2/demos
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch_ros.actions import Node def generate_launch_description(): # TODO(wjwwood): Use a substitution to find share directory once this is implemented in launch urdf = os.path.join(get_package_share_directory('dummy_robot_bringup'), 'launch', 'single_rrbot.urdf') return LaunchDescription([ Node(package='dummy_map_server', node_executable='dummy_map_server', output='screen'), Node(package='robot_state_publisher', node_executable='robot_state_publisher', output='screen', arguments=[urdf]), Node(package='dummy_sensors', node_executable='dummy_joint_states', output='screen'), Node(package='dummy_sensors', node_executable='dummy_laser', output='screen') ]) Switch dummy_robot_bringup to use parameter for rsp. Signed-off-by: Chris Lalancette <281cd07d7578d97c83271fbbf2faddb83ab3791c@openrobotics.org>
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from launch import LaunchDescription from launch_ros.actions import Node from launch_ros.substitutions import FindPackageShare def generate_launch_description(): pkg_share = FindPackageShare('dummy_robot_bringup').find('dummy_robot_bringup') urdf_file = os.path.join(pkg_share, 'launch', 'single_rrbot.urdf') with open(urdf_file, 'r') as infp: robot_desc = infp.read() rsp_params = {'robot_description': robot_desc} return LaunchDescription([ Node(package='dummy_map_server', node_executable='dummy_map_server', output='screen'), Node(package='robot_state_publisher', node_executable='robot_state_publisher_node', output='screen', parameters=[rsp_params]), Node(package='dummy_sensors', node_executable='dummy_joint_states', output='screen'), Node(package='dummy_sensors', node_executable='dummy_laser', output='screen') ])
<commit_before># Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch_ros.actions import Node def generate_launch_description(): # TODO(wjwwood): Use a substitution to find share directory once this is implemented in launch urdf = os.path.join(get_package_share_directory('dummy_robot_bringup'), 'launch', 'single_rrbot.urdf') return LaunchDescription([ Node(package='dummy_map_server', node_executable='dummy_map_server', output='screen'), Node(package='robot_state_publisher', node_executable='robot_state_publisher', output='screen', arguments=[urdf]), Node(package='dummy_sensors', node_executable='dummy_joint_states', output='screen'), Node(package='dummy_sensors', node_executable='dummy_laser', output='screen') ]) <commit_msg>Switch dummy_robot_bringup to use parameter for rsp. Signed-off-by: Chris Lalancette <281cd07d7578d97c83271fbbf2faddb83ab3791c@openrobotics.org><commit_after>
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from launch import LaunchDescription from launch_ros.actions import Node from launch_ros.substitutions import FindPackageShare def generate_launch_description(): pkg_share = FindPackageShare('dummy_robot_bringup').find('dummy_robot_bringup') urdf_file = os.path.join(pkg_share, 'launch', 'single_rrbot.urdf') with open(urdf_file, 'r') as infp: robot_desc = infp.read() rsp_params = {'robot_description': robot_desc} return LaunchDescription([ Node(package='dummy_map_server', node_executable='dummy_map_server', output='screen'), Node(package='robot_state_publisher', node_executable='robot_state_publisher_node', output='screen', parameters=[rsp_params]), Node(package='dummy_sensors', node_executable='dummy_joint_states', output='screen'), Node(package='dummy_sensors', node_executable='dummy_laser', output='screen') ])
# Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch_ros.actions import Node def generate_launch_description(): # TODO(wjwwood): Use a substitution to find share directory once this is implemented in launch urdf = os.path.join(get_package_share_directory('dummy_robot_bringup'), 'launch', 'single_rrbot.urdf') return LaunchDescription([ Node(package='dummy_map_server', node_executable='dummy_map_server', output='screen'), Node(package='robot_state_publisher', node_executable='robot_state_publisher', output='screen', arguments=[urdf]), Node(package='dummy_sensors', node_executable='dummy_joint_states', output='screen'), Node(package='dummy_sensors', node_executable='dummy_laser', output='screen') ]) Switch dummy_robot_bringup to use parameter for rsp. Signed-off-by: Chris Lalancette <281cd07d7578d97c83271fbbf2faddb83ab3791c@openrobotics.org># Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from launch import LaunchDescription from launch_ros.actions import Node from launch_ros.substitutions import FindPackageShare def generate_launch_description(): pkg_share = FindPackageShare('dummy_robot_bringup').find('dummy_robot_bringup') urdf_file = os.path.join(pkg_share, 'launch', 'single_rrbot.urdf') with open(urdf_file, 'r') as infp: robot_desc = infp.read() rsp_params = {'robot_description': robot_desc} return LaunchDescription([ Node(package='dummy_map_server', node_executable='dummy_map_server', output='screen'), Node(package='robot_state_publisher', node_executable='robot_state_publisher_node', output='screen', parameters=[rsp_params]), Node(package='dummy_sensors', node_executable='dummy_joint_states', output='screen'), Node(package='dummy_sensors', node_executable='dummy_laser', output='screen') ])
<commit_before># Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch_ros.actions import Node def generate_launch_description(): # TODO(wjwwood): Use a substitution to find share directory once this is implemented in launch urdf = os.path.join(get_package_share_directory('dummy_robot_bringup'), 'launch', 'single_rrbot.urdf') return LaunchDescription([ Node(package='dummy_map_server', node_executable='dummy_map_server', output='screen'), Node(package='robot_state_publisher', node_executable='robot_state_publisher', output='screen', arguments=[urdf]), Node(package='dummy_sensors', node_executable='dummy_joint_states', output='screen'), Node(package='dummy_sensors', node_executable='dummy_laser', output='screen') ]) <commit_msg>Switch dummy_robot_bringup to use parameter for rsp. Signed-off-by: Chris Lalancette <281cd07d7578d97c83271fbbf2faddb83ab3791c@openrobotics.org><commit_after># Copyright 2018 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from launch import LaunchDescription from launch_ros.actions import Node from launch_ros.substitutions import FindPackageShare def generate_launch_description(): pkg_share = FindPackageShare('dummy_robot_bringup').find('dummy_robot_bringup') urdf_file = os.path.join(pkg_share, 'launch', 'single_rrbot.urdf') with open(urdf_file, 'r') as infp: robot_desc = infp.read() rsp_params = {'robot_description': robot_desc} return LaunchDescription([ Node(package='dummy_map_server', node_executable='dummy_map_server', output='screen'), Node(package='robot_state_publisher', node_executable='robot_state_publisher_node', output='screen', parameters=[rsp_params]), Node(package='dummy_sensors', node_executable='dummy_joint_states', output='screen'), Node(package='dummy_sensors', node_executable='dummy_laser', output='screen') ])
1faf32fb45bf69b9486e79ba3aee5c290f9e7ab1
plugins/reversedns.py
plugins/reversedns.py
import logging, interfaces, os, IPy from StringIO import StringIO class Shorewall(interfaces.IOpenMesherPlugin): def __init__(self): self._files = {} def process(self, mesh): logging.debug('Generating DNS config...') self._files = {} rdns = StringIO() for router in mesh.links: for link in mesh.links[router]: if link.isServer(router): ip1 = IPy.IP(str(link.block[1])) ip2 = IPy.IP(str(link.block[2])) #BUG: fqdn might not be populated if just using hostnames. #BUG: Need to allow reversing to alternate domain names if p2p routing block is private #BUG: Need to put iface name in rev dns rdns.write('%s\t\tPTR\t%s.\n' %(ip1.reverseName(), link.server.fqdn)) rdns.write('%s\t\tPTR\t%s.\n' %(ip2.reverseName(), link.client.fqdn)) self._files[router] = {'/etc/mesh-reverse.db': rdns.getvalue()} return True def files(self): """ Return a dictionary of routers containing a dictionary of filenames and contents """ return self._files
import logging, interfaces, os, IPy from StringIO import StringIO class Shorewall(interfaces.IOpenMesherPlugin): def __init__(self): self._files = {} def process(self, mesh): logging.debug('Generating DNS config...') self._files = {} rdns = StringIO() for router in mesh.links: for link in mesh.links[router]: if link.isServer(router): ip1 = IPy.IP(str(link.block[1])) ip2 = IPy.IP(str(link.block[2])) #BUG: fqdn might not be populated if just using hostnames. #BUG: Need to allow reversing to alternate domain names if p2p routing block is private #BUG: Need to put iface name in rev dns rdns.write('%s\t\tPTR\t%s.\n' %(ip1.reverseName(), link.server.fqdn)) rdns.write('%s\t\tPTR\t%s.\n' %(ip2.reverseName(), link.client.fqdn)) self._files[router] = {'/etc/mesh-reverse.db': rdns.getvalue()} return True def files(self): """ Return a dictionary of routers containing a dictionary of filenames and contents """ return self._files
Return DNS data in the correct format
Return DNS data in the correct format
Python
bsd-3-clause
heyaaron/openmesher,darkpixel/openmesher,heyaaron/openmesher,darkpixel/openmesher
import logging, interfaces, os, IPy from StringIO import StringIO class Shorewall(interfaces.IOpenMesherPlugin): def __init__(self): self._files = {} def process(self, mesh): logging.debug('Generating DNS config...') self._files = {} rdns = StringIO() for router in mesh.links: for link in mesh.links[router]: if link.isServer(router): ip1 = IPy.IP(str(link.block[1])) ip2 = IPy.IP(str(link.block[2])) #BUG: fqdn might not be populated if just using hostnames. #BUG: Need to allow reversing to alternate domain names if p2p routing block is private #BUG: Need to put iface name in rev dns rdns.write('%s\t\tPTR\t%s.\n' %(ip1.reverseName(), link.server.fqdn)) rdns.write('%s\t\tPTR\t%s.\n' %(ip2.reverseName(), link.client.fqdn)) self._files[router] = {'/etc/mesh-reverse.db': rdns.getvalue()} return True def files(self): """ Return a dictionary of routers containing a dictionary of filenames and contents """ return self._files Return DNS data in the correct format
import logging, interfaces, os, IPy from StringIO import StringIO class Shorewall(interfaces.IOpenMesherPlugin): def __init__(self): self._files = {} def process(self, mesh): logging.debug('Generating DNS config...') self._files = {} rdns = StringIO() for router in mesh.links: for link in mesh.links[router]: if link.isServer(router): ip1 = IPy.IP(str(link.block[1])) ip2 = IPy.IP(str(link.block[2])) #BUG: fqdn might not be populated if just using hostnames. #BUG: Need to allow reversing to alternate domain names if p2p routing block is private #BUG: Need to put iface name in rev dns rdns.write('%s\t\tPTR\t%s.\n' %(ip1.reverseName(), link.server.fqdn)) rdns.write('%s\t\tPTR\t%s.\n' %(ip2.reverseName(), link.client.fqdn)) self._files[router] = {'/etc/mesh-reverse.db': rdns.getvalue()} return True def files(self): """ Return a dictionary of routers containing a dictionary of filenames and contents """ return self._files
<commit_before>import logging, interfaces, os, IPy from StringIO import StringIO class Shorewall(interfaces.IOpenMesherPlugin): def __init__(self): self._files = {} def process(self, mesh): logging.debug('Generating DNS config...') self._files = {} rdns = StringIO() for router in mesh.links: for link in mesh.links[router]: if link.isServer(router): ip1 = IPy.IP(str(link.block[1])) ip2 = IPy.IP(str(link.block[2])) #BUG: fqdn might not be populated if just using hostnames. #BUG: Need to allow reversing to alternate domain names if p2p routing block is private #BUG: Need to put iface name in rev dns rdns.write('%s\t\tPTR\t%s.\n' %(ip1.reverseName(), link.server.fqdn)) rdns.write('%s\t\tPTR\t%s.\n' %(ip2.reverseName(), link.client.fqdn)) self._files[router] = {'/etc/mesh-reverse.db': rdns.getvalue()} return True def files(self): """ Return a dictionary of routers containing a dictionary of filenames and contents """ return self._files <commit_msg>Return DNS data in the correct format<commit_after>
import logging, interfaces, os, IPy from StringIO import StringIO class Shorewall(interfaces.IOpenMesherPlugin): def __init__(self): self._files = {} def process(self, mesh): logging.debug('Generating DNS config...') self._files = {} rdns = StringIO() for router in mesh.links: for link in mesh.links[router]: if link.isServer(router): ip1 = IPy.IP(str(link.block[1])) ip2 = IPy.IP(str(link.block[2])) #BUG: fqdn might not be populated if just using hostnames. #BUG: Need to allow reversing to alternate domain names if p2p routing block is private #BUG: Need to put iface name in rev dns rdns.write('%s\t\tPTR\t%s.\n' %(ip1.reverseName(), link.server.fqdn)) rdns.write('%s\t\tPTR\t%s.\n' %(ip2.reverseName(), link.client.fqdn)) self._files[router] = {'/etc/mesh-reverse.db': rdns.getvalue()} return True def files(self): """ Return a dictionary of routers containing a dictionary of filenames and contents """ return self._files
import logging, interfaces, os, IPy from StringIO import StringIO class Shorewall(interfaces.IOpenMesherPlugin): def __init__(self): self._files = {} def process(self, mesh): logging.debug('Generating DNS config...') self._files = {} rdns = StringIO() for router in mesh.links: for link in mesh.links[router]: if link.isServer(router): ip1 = IPy.IP(str(link.block[1])) ip2 = IPy.IP(str(link.block[2])) #BUG: fqdn might not be populated if just using hostnames. #BUG: Need to allow reversing to alternate domain names if p2p routing block is private #BUG: Need to put iface name in rev dns rdns.write('%s\t\tPTR\t%s.\n' %(ip1.reverseName(), link.server.fqdn)) rdns.write('%s\t\tPTR\t%s.\n' %(ip2.reverseName(), link.client.fqdn)) self._files[router] = {'/etc/mesh-reverse.db': rdns.getvalue()} return True def files(self): """ Return a dictionary of routers containing a dictionary of filenames and contents """ return self._files Return DNS data in the correct formatimport logging, interfaces, os, IPy from StringIO import StringIO class Shorewall(interfaces.IOpenMesherPlugin): def __init__(self): self._files = {} def process(self, mesh): logging.debug('Generating DNS config...') self._files = {} rdns = StringIO() for router in mesh.links: for link in mesh.links[router]: if link.isServer(router): ip1 = IPy.IP(str(link.block[1])) ip2 = IPy.IP(str(link.block[2])) #BUG: fqdn might not be populated if just using hostnames. #BUG: Need to allow reversing to alternate domain names if p2p routing block is private #BUG: Need to put iface name in rev dns rdns.write('%s\t\tPTR\t%s.\n' %(ip1.reverseName(), link.server.fqdn)) rdns.write('%s\t\tPTR\t%s.\n' %(ip2.reverseName(), link.client.fqdn)) self._files[router] = {'/etc/mesh-reverse.db': rdns.getvalue()} return True def files(self): """ Return a dictionary of routers containing a dictionary of filenames and contents """ return self._files
<commit_before>import logging, interfaces, os, IPy from StringIO import StringIO class Shorewall(interfaces.IOpenMesherPlugin): def __init__(self): self._files = {} def process(self, mesh): logging.debug('Generating DNS config...') self._files = {} rdns = StringIO() for router in mesh.links: for link in mesh.links[router]: if link.isServer(router): ip1 = IPy.IP(str(link.block[1])) ip2 = IPy.IP(str(link.block[2])) #BUG: fqdn might not be populated if just using hostnames. #BUG: Need to allow reversing to alternate domain names if p2p routing block is private #BUG: Need to put iface name in rev dns rdns.write('%s\t\tPTR\t%s.\n' %(ip1.reverseName(), link.server.fqdn)) rdns.write('%s\t\tPTR\t%s.\n' %(ip2.reverseName(), link.client.fqdn)) self._files[router] = {'/etc/mesh-reverse.db': rdns.getvalue()} return True def files(self): """ Return a dictionary of routers containing a dictionary of filenames and contents """ return self._files <commit_msg>Return DNS data in the correct format<commit_after>import logging, interfaces, os, IPy from StringIO import StringIO class Shorewall(interfaces.IOpenMesherPlugin): def __init__(self): self._files = {} def process(self, mesh): logging.debug('Generating DNS config...') self._files = {} rdns = StringIO() for router in mesh.links: for link in mesh.links[router]: if link.isServer(router): ip1 = IPy.IP(str(link.block[1])) ip2 = IPy.IP(str(link.block[2])) #BUG: fqdn might not be populated if just using hostnames. #BUG: Need to allow reversing to alternate domain names if p2p routing block is private #BUG: Need to put iface name in rev dns rdns.write('%s\t\tPTR\t%s.\n' %(ip1.reverseName(), link.server.fqdn)) rdns.write('%s\t\tPTR\t%s.\n' %(ip2.reverseName(), link.client.fqdn)) self._files[router] = {'/etc/mesh-reverse.db': rdns.getvalue()} return True def files(self): """ Return a dictionary of routers containing a dictionary of filenames and contents """ return self._files
123ffcabb6fa783b1524a55dd3dce52ad33a13db
nitrogen/local.py
nitrogen/local.py
import collections from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock from .proxy import Proxy class Local(Local): # Just adding a __dict__ property to the object. def __init__(self): super(Local, self).__init__() object.__setattr__(self, '__storage__', collections.defaultdict(dict)) @property def __dict__(self): return self.__storage__[self.__ident_func__()] def __call__(self, name): return Proxy(lambda: getattr(self, name)) class LocalManager(LocalManager): def local(self): obj = Local() self.locals.append(obj) return obj def stack(self): obj = LocalStack() self.locals.append(obj) return obj class LocalStack(LocalStack): def __call__(self): def _lookup(): rv = self.top if rv is None: raise RuntimeError('object unbound') return rv return Proxy(_lookup) def LocalProxy(local, name=None): if name is None: return Proxy(local) return Proxy(lambda: getattr(local, name))
import collections from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock, get_ident from .proxy import Proxy class Local(Local): # We are extending this class for the only purpose of adding a __dict__ # attribute, so that this will work nearly identically to the builtin # threading.local class. # Not adding any more attributes, but we don't want to actually add a dict. __slots__ = () def __init__(self): super(Local, self).__init__() object.__setattr__(self, '__storage__', collections.defaultdict(dict)) @property def __dict__(self): # The __ident_func__ attribute is added after the 0.6.2 release (at # this point it is still in the development branch). This lets us # work with both versions. try: return self.__storage__[self.__ident_func__()] except AttributeError: return self.__storage__[get_ident()] def __call__(self, name): return Proxy(lambda: getattr(self, name)) class LocalManager(LocalManager): def local(self): obj = Local() self.locals.append(obj) return obj def stack(self): obj = LocalStack() self.locals.append(obj) return obj class LocalStack(LocalStack): def __call__(self): def _lookup(): rv = self.top if rv is None: raise RuntimeError('object unbound') return rv return Proxy(_lookup) def LocalProxy(local, name=None): if name is None: return Proxy(local) return Proxy(lambda: getattr(local, name))
Fix Local class to work with older werkzeug.
Fix Local class to work with older werkzeug.
Python
bsd-3-clause
mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen
import collections from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock from .proxy import Proxy class Local(Local): # Just adding a __dict__ property to the object. def __init__(self): super(Local, self).__init__() object.__setattr__(self, '__storage__', collections.defaultdict(dict)) @property def __dict__(self): return self.__storage__[self.__ident_func__()] def __call__(self, name): return Proxy(lambda: getattr(self, name)) class LocalManager(LocalManager): def local(self): obj = Local() self.locals.append(obj) return obj def stack(self): obj = LocalStack() self.locals.append(obj) return obj class LocalStack(LocalStack): def __call__(self): def _lookup(): rv = self.top if rv is None: raise RuntimeError('object unbound') return rv return Proxy(_lookup) def LocalProxy(local, name=None): if name is None: return Proxy(local) return Proxy(lambda: getattr(local, name))Fix Local class to work with older werkzeug.
import collections from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock, get_ident from .proxy import Proxy class Local(Local): # We are extending this class for the only purpose of adding a __dict__ # attribute, so that this will work nearly identically to the builtin # threading.local class. # Not adding any more attributes, but we don't want to actually add a dict. __slots__ = () def __init__(self): super(Local, self).__init__() object.__setattr__(self, '__storage__', collections.defaultdict(dict)) @property def __dict__(self): # The __ident_func__ attribute is added after the 0.6.2 release (at # this point it is still in the development branch). This lets us # work with both versions. try: return self.__storage__[self.__ident_func__()] except AttributeError: return self.__storage__[get_ident()] def __call__(self, name): return Proxy(lambda: getattr(self, name)) class LocalManager(LocalManager): def local(self): obj = Local() self.locals.append(obj) return obj def stack(self): obj = LocalStack() self.locals.append(obj) return obj class LocalStack(LocalStack): def __call__(self): def _lookup(): rv = self.top if rv is None: raise RuntimeError('object unbound') return rv return Proxy(_lookup) def LocalProxy(local, name=None): if name is None: return Proxy(local) return Proxy(lambda: getattr(local, name))
<commit_before> import collections from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock from .proxy import Proxy class Local(Local): # Just adding a __dict__ property to the object. def __init__(self): super(Local, self).__init__() object.__setattr__(self, '__storage__', collections.defaultdict(dict)) @property def __dict__(self): return self.__storage__[self.__ident_func__()] def __call__(self, name): return Proxy(lambda: getattr(self, name)) class LocalManager(LocalManager): def local(self): obj = Local() self.locals.append(obj) return obj def stack(self): obj = LocalStack() self.locals.append(obj) return obj class LocalStack(LocalStack): def __call__(self): def _lookup(): rv = self.top if rv is None: raise RuntimeError('object unbound') return rv return Proxy(_lookup) def LocalProxy(local, name=None): if name is None: return Proxy(local) return Proxy(lambda: getattr(local, name))<commit_msg>Fix Local class to work with older werkzeug.<commit_after>
import collections from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock, get_ident from .proxy import Proxy class Local(Local): # We are extending this class for the only purpose of adding a __dict__ # attribute, so that this will work nearly identically to the builtin # threading.local class. # Not adding any more attributes, but we don't want to actually add a dict. __slots__ = () def __init__(self): super(Local, self).__init__() object.__setattr__(self, '__storage__', collections.defaultdict(dict)) @property def __dict__(self): # The __ident_func__ attribute is added after the 0.6.2 release (at # this point it is still in the development branch). This lets us # work with both versions. try: return self.__storage__[self.__ident_func__()] except AttributeError: return self.__storage__[get_ident()] def __call__(self, name): return Proxy(lambda: getattr(self, name)) class LocalManager(LocalManager): def local(self): obj = Local() self.locals.append(obj) return obj def stack(self): obj = LocalStack() self.locals.append(obj) return obj class LocalStack(LocalStack): def __call__(self): def _lookup(): rv = self.top if rv is None: raise RuntimeError('object unbound') return rv return Proxy(_lookup) def LocalProxy(local, name=None): if name is None: return Proxy(local) return Proxy(lambda: getattr(local, name))
import collections from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock from .proxy import Proxy class Local(Local): # Just adding a __dict__ property to the object. def __init__(self): super(Local, self).__init__() object.__setattr__(self, '__storage__', collections.defaultdict(dict)) @property def __dict__(self): return self.__storage__[self.__ident_func__()] def __call__(self, name): return Proxy(lambda: getattr(self, name)) class LocalManager(LocalManager): def local(self): obj = Local() self.locals.append(obj) return obj def stack(self): obj = LocalStack() self.locals.append(obj) return obj class LocalStack(LocalStack): def __call__(self): def _lookup(): rv = self.top if rv is None: raise RuntimeError('object unbound') return rv return Proxy(_lookup) def LocalProxy(local, name=None): if name is None: return Proxy(local) return Proxy(lambda: getattr(local, name))Fix Local class to work with older werkzeug. import collections from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock, get_ident from .proxy import Proxy class Local(Local): # We are extending this class for the only purpose of adding a __dict__ # attribute, so that this will work nearly identically to the builtin # threading.local class. # Not adding any more attributes, but we don't want to actually add a dict. __slots__ = () def __init__(self): super(Local, self).__init__() object.__setattr__(self, '__storage__', collections.defaultdict(dict)) @property def __dict__(self): # The __ident_func__ attribute is added after the 0.6.2 release (at # this point it is still in the development branch). This lets us # work with both versions. try: return self.__storage__[self.__ident_func__()] except AttributeError: return self.__storage__[get_ident()] def __call__(self, name): return Proxy(lambda: getattr(self, name)) class LocalManager(LocalManager): def local(self): obj = Local() self.locals.append(obj) return obj def stack(self): obj = LocalStack() self.locals.append(obj) return obj class LocalStack(LocalStack): def __call__(self): def _lookup(): rv = self.top if rv is None: raise RuntimeError('object unbound') return rv return Proxy(_lookup) def LocalProxy(local, name=None): if name is None: return Proxy(local) return Proxy(lambda: getattr(local, name))
<commit_before> import collections from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock from .proxy import Proxy class Local(Local): # Just adding a __dict__ property to the object. def __init__(self): super(Local, self).__init__() object.__setattr__(self, '__storage__', collections.defaultdict(dict)) @property def __dict__(self): return self.__storage__[self.__ident_func__()] def __call__(self, name): return Proxy(lambda: getattr(self, name)) class LocalManager(LocalManager): def local(self): obj = Local() self.locals.append(obj) return obj def stack(self): obj = LocalStack() self.locals.append(obj) return obj class LocalStack(LocalStack): def __call__(self): def _lookup(): rv = self.top if rv is None: raise RuntimeError('object unbound') return rv return Proxy(_lookup) def LocalProxy(local, name=None): if name is None: return Proxy(local) return Proxy(lambda: getattr(local, name))<commit_msg>Fix Local class to work with older werkzeug.<commit_after> import collections from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock, get_ident from .proxy import Proxy class Local(Local): # We are extending this class for the only purpose of adding a __dict__ # attribute, so that this will work nearly identically to the builtin # threading.local class. # Not adding any more attributes, but we don't want to actually add a dict. __slots__ = () def __init__(self): super(Local, self).__init__() object.__setattr__(self, '__storage__', collections.defaultdict(dict)) @property def __dict__(self): # The __ident_func__ attribute is added after the 0.6.2 release (at # this point it is still in the development branch). This lets us # work with both versions. try: return self.__storage__[self.__ident_func__()] except AttributeError: return self.__storage__[get_ident()] def __call__(self, name): return Proxy(lambda: getattr(self, name)) class LocalManager(LocalManager): def local(self): obj = Local() self.locals.append(obj) return obj def stack(self): obj = LocalStack() self.locals.append(obj) return obj class LocalStack(LocalStack): def __call__(self): def _lookup(): rv = self.top if rv is None: raise RuntimeError('object unbound') return rv return Proxy(_lookup) def LocalProxy(local, name=None): if name is None: return Proxy(local) return Proxy(lambda: getattr(local, name))
4adb686fc15dc3dfdb872157df27b534f1ca7f98
tests/QtUiTools/bug_392.py
tests/QtUiTools/bug_392.py
import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'action.ui') result = loader.load(filePath, w) self.assertEqual(type(result.statusbar.actionFoo), QtGui.QAction) if __name__ == '__main__': unittest.main()
import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui, QtDeclarative from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'action.ui') result = loader.load(filePath, w) self.assertEqual(type(result.statusbar.actionFoo), QtGui.QAction) def testCustomWidgets(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'customwidget.ui') result = loader.load(filePath, w) self.assert_(type(result.declarativeView), QtDeclarative.QDeclarativeView) self.assert_(type(result.worldTimeClock), QtGui.QWidget) if __name__ == '__main__': unittest.main()
Extend QUiLoader test to test ui files with custom widgets.
Extend QUiLoader test to test ui files with custom widgets.
Python
lgpl-2.1
PySide/PySide,RobinD42/pyside,M4rtinK/pyside-android,IronManMark20/pyside2,PySide/PySide,RobinD42/pyside,PySide/PySide,RobinD42/pyside,RobinD42/pyside,PySide/PySide,M4rtinK/pyside-android,BadSingleton/pyside2,BadSingleton/pyside2,RobinD42/pyside,enthought/pyside,pankajp/pyside,gbaty/pyside2,M4rtinK/pyside-android,IronManMark20/pyside2,qtproject/pyside-pyside,gbaty/pyside2,M4rtinK/pyside-bb10,PySide/PySide,gbaty/pyside2,pankajp/pyside,pankajp/pyside,M4rtinK/pyside-android,qtproject/pyside-pyside,enthought/pyside,enthought/pyside,M4rtinK/pyside-bb10,IronManMark20/pyside2,pankajp/pyside,M4rtinK/pyside-bb10,RobinD42/pyside,gbaty/pyside2,qtproject/pyside-pyside,M4rtinK/pyside-bb10,BadSingleton/pyside2,gbaty/pyside2,enthought/pyside,pankajp/pyside,IronManMark20/pyside2,M4rtinK/pyside-android,qtproject/pyside-pyside,RobinD42/pyside,qtproject/pyside-pyside,M4rtinK/pyside-bb10,M4rtinK/pyside-android,enthought/pyside,M4rtinK/pyside-bb10,BadSingleton/pyside2,IronManMark20/pyside2,enthought/pyside,BadSingleton/pyside2,enthought/pyside
import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'action.ui') result = loader.load(filePath, w) self.assertEqual(type(result.statusbar.actionFoo), QtGui.QAction) if __name__ == '__main__': unittest.main() Extend QUiLoader test to test ui files with custom widgets.
import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui, QtDeclarative from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'action.ui') result = loader.load(filePath, w) self.assertEqual(type(result.statusbar.actionFoo), QtGui.QAction) def testCustomWidgets(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'customwidget.ui') result = loader.load(filePath, w) self.assert_(type(result.declarativeView), QtDeclarative.QDeclarativeView) self.assert_(type(result.worldTimeClock), QtGui.QWidget) if __name__ == '__main__': unittest.main()
<commit_before>import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'action.ui') result = loader.load(filePath, w) self.assertEqual(type(result.statusbar.actionFoo), QtGui.QAction) if __name__ == '__main__': unittest.main() <commit_msg>Extend QUiLoader test to test ui files with custom widgets.<commit_after>
import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui, QtDeclarative from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'action.ui') result = loader.load(filePath, w) self.assertEqual(type(result.statusbar.actionFoo), QtGui.QAction) def testCustomWidgets(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'customwidget.ui') result = loader.load(filePath, w) self.assert_(type(result.declarativeView), QtDeclarative.QDeclarativeView) self.assert_(type(result.worldTimeClock), QtGui.QWidget) if __name__ == '__main__': unittest.main()
import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'action.ui') result = loader.load(filePath, w) self.assertEqual(type(result.statusbar.actionFoo), QtGui.QAction) if __name__ == '__main__': unittest.main() Extend QUiLoader test to test ui files with custom widgets.import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui, QtDeclarative from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'action.ui') result = loader.load(filePath, w) self.assertEqual(type(result.statusbar.actionFoo), QtGui.QAction) def testCustomWidgets(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'customwidget.ui') result = loader.load(filePath, w) self.assert_(type(result.declarativeView), QtDeclarative.QDeclarativeView) self.assert_(type(result.worldTimeClock), QtGui.QWidget) if __name__ == '__main__': unittest.main()
<commit_before>import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'action.ui') result = loader.load(filePath, w) self.assertEqual(type(result.statusbar.actionFoo), QtGui.QAction) if __name__ == '__main__': unittest.main() <commit_msg>Extend QUiLoader test to test ui files with custom widgets.<commit_after>import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui, QtDeclarative from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'action.ui') result = loader.load(filePath, w) self.assertEqual(type(result.statusbar.actionFoo), QtGui.QAction) def testCustomWidgets(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'customwidget.ui') result = loader.load(filePath, w) self.assert_(type(result.declarativeView), QtDeclarative.QDeclarativeView) self.assert_(type(result.worldTimeClock), QtGui.QWidget) if __name__ == '__main__': unittest.main()
fd8c82855f233d2bc7fba482191de46ab5afef5a
wagtailimportexport/tests/test_views.py
wagtailimportexport/tests/test_views.py
import json import os import tempfile import zipfile from django.core.serializers.json import DjangoJSONEncoder from django.contrib.auth.models import User from django.test import TestCase from wagtailimportexport.compat import Page from wagtailimportexport import views # read this aloud class TestViews(TestCase): def test_null_pks(self): """ Testing null_pk method. """ allpages = {'pages': [ { 'content': { 'test': [ { 'pk': 12, 'haha': 'yup' } ] } } ]} views.null_pks(allpages) assert allpages['pages'][0]['content']['test'][0]['pk'] == None assert allpages['pages'][0]['content']['test'][0]['haha'] == 'yup'
import json import os import tempfile import zipfile from django.core.serializers.json import DjangoJSONEncoder from django.contrib.auth.models import User from django.test import TestCase, Client from wagtailimportexport.compat import Page from django.urls import reverse from wagtailimportexport import views # read this aloud class TestViews(TestCase): def test_null_pks(self): """ Testing null_pk method. """ allpages = {'pages': [ { 'content': { 'test': [ { 'pk': 12, 'haha': 'yup' } ] } } ]} views.null_pks(allpages) assert allpages['pages'][0]['content']['test'][0]['pk'] == None assert allpages['pages'][0]['content']['test'][0]['haha'] == 'yup' class TestForms(TestCase): def setUp(self): self.client = Client() def test_importfile(self): response = self.client.get(reverse('wagtailimportexport_admin:import_from_file')) self.assertNotEqual(response.status_code, 404) def test_exportfile(self): response = self.client.get(reverse('wagtailimportexport_admin:export_to_file')) self.assertNotEqual(response.status_code, 404) def test_duplicate(self): response = self.client.get(reverse('wagtailimportexport_admin:duplicate', args=[1])) self.assertNotEqual(response.status_code, 404) def test_index(self): response = self.client.get(reverse('wagtailimportexport_admin:index')) self.assertNotEqual(response.status_code, 404)
Add tests for wagtailimportexport forms.
Add tests for wagtailimportexport forms.
Python
agpl-3.0
openstax/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,Connexions/openstax-cms,Connexions/openstax-cms
import json import os import tempfile import zipfile from django.core.serializers.json import DjangoJSONEncoder from django.contrib.auth.models import User from django.test import TestCase from wagtailimportexport.compat import Page from wagtailimportexport import views # read this aloud class TestViews(TestCase): def test_null_pks(self): """ Testing null_pk method. """ allpages = {'pages': [ { 'content': { 'test': [ { 'pk': 12, 'haha': 'yup' } ] } } ]} views.null_pks(allpages) assert allpages['pages'][0]['content']['test'][0]['pk'] == None assert allpages['pages'][0]['content']['test'][0]['haha'] == 'yup'Add tests for wagtailimportexport forms.
import json import os import tempfile import zipfile from django.core.serializers.json import DjangoJSONEncoder from django.contrib.auth.models import User from django.test import TestCase, Client from wagtailimportexport.compat import Page from django.urls import reverse from wagtailimportexport import views # read this aloud class TestViews(TestCase): def test_null_pks(self): """ Testing null_pk method. """ allpages = {'pages': [ { 'content': { 'test': [ { 'pk': 12, 'haha': 'yup' } ] } } ]} views.null_pks(allpages) assert allpages['pages'][0]['content']['test'][0]['pk'] == None assert allpages['pages'][0]['content']['test'][0]['haha'] == 'yup' class TestForms(TestCase): def setUp(self): self.client = Client() def test_importfile(self): response = self.client.get(reverse('wagtailimportexport_admin:import_from_file')) self.assertNotEqual(response.status_code, 404) def test_exportfile(self): response = self.client.get(reverse('wagtailimportexport_admin:export_to_file')) self.assertNotEqual(response.status_code, 404) def test_duplicate(self): response = self.client.get(reverse('wagtailimportexport_admin:duplicate', args=[1])) self.assertNotEqual(response.status_code, 404) def test_index(self): response = self.client.get(reverse('wagtailimportexport_admin:index')) self.assertNotEqual(response.status_code, 404)
<commit_before>import json import os import tempfile import zipfile from django.core.serializers.json import DjangoJSONEncoder from django.contrib.auth.models import User from django.test import TestCase from wagtailimportexport.compat import Page from wagtailimportexport import views # read this aloud class TestViews(TestCase): def test_null_pks(self): """ Testing null_pk method. """ allpages = {'pages': [ { 'content': { 'test': [ { 'pk': 12, 'haha': 'yup' } ] } } ]} views.null_pks(allpages) assert allpages['pages'][0]['content']['test'][0]['pk'] == None assert allpages['pages'][0]['content']['test'][0]['haha'] == 'yup'<commit_msg>Add tests for wagtailimportexport forms.<commit_after>
import json import os import tempfile import zipfile from django.core.serializers.json import DjangoJSONEncoder from django.contrib.auth.models import User from django.test import TestCase, Client from wagtailimportexport.compat import Page from django.urls import reverse from wagtailimportexport import views # read this aloud class TestViews(TestCase): def test_null_pks(self): """ Testing null_pk method. """ allpages = {'pages': [ { 'content': { 'test': [ { 'pk': 12, 'haha': 'yup' } ] } } ]} views.null_pks(allpages) assert allpages['pages'][0]['content']['test'][0]['pk'] == None assert allpages['pages'][0]['content']['test'][0]['haha'] == 'yup' class TestForms(TestCase): def setUp(self): self.client = Client() def test_importfile(self): response = self.client.get(reverse('wagtailimportexport_admin:import_from_file')) self.assertNotEqual(response.status_code, 404) def test_exportfile(self): response = self.client.get(reverse('wagtailimportexport_admin:export_to_file')) self.assertNotEqual(response.status_code, 404) def test_duplicate(self): response = self.client.get(reverse('wagtailimportexport_admin:duplicate', args=[1])) self.assertNotEqual(response.status_code, 404) def test_index(self): response = self.client.get(reverse('wagtailimportexport_admin:index')) self.assertNotEqual(response.status_code, 404)
import json import os import tempfile import zipfile from django.core.serializers.json import DjangoJSONEncoder from django.contrib.auth.models import User from django.test import TestCase from wagtailimportexport.compat import Page from wagtailimportexport import views # read this aloud class TestViews(TestCase): def test_null_pks(self): """ Testing null_pk method. """ allpages = {'pages': [ { 'content': { 'test': [ { 'pk': 12, 'haha': 'yup' } ] } } ]} views.null_pks(allpages) assert allpages['pages'][0]['content']['test'][0]['pk'] == None assert allpages['pages'][0]['content']['test'][0]['haha'] == 'yup'Add tests for wagtailimportexport forms.import json import os import tempfile import zipfile from django.core.serializers.json import DjangoJSONEncoder from django.contrib.auth.models import User from django.test import TestCase, Client from wagtailimportexport.compat import Page from django.urls import reverse from wagtailimportexport import views # read this aloud class TestViews(TestCase): def test_null_pks(self): """ Testing null_pk method. """ allpages = {'pages': [ { 'content': { 'test': [ { 'pk': 12, 'haha': 'yup' } ] } } ]} views.null_pks(allpages) assert allpages['pages'][0]['content']['test'][0]['pk'] == None assert allpages['pages'][0]['content']['test'][0]['haha'] == 'yup' class TestForms(TestCase): def setUp(self): self.client = Client() def test_importfile(self): response = self.client.get(reverse('wagtailimportexport_admin:import_from_file')) self.assertNotEqual(response.status_code, 404) def test_exportfile(self): response = self.client.get(reverse('wagtailimportexport_admin:export_to_file')) self.assertNotEqual(response.status_code, 404) def test_duplicate(self): response = self.client.get(reverse('wagtailimportexport_admin:duplicate', args=[1])) self.assertNotEqual(response.status_code, 404) def test_index(self): response = self.client.get(reverse('wagtailimportexport_admin:index')) self.assertNotEqual(response.status_code, 404)
<commit_before>import json import os import tempfile import zipfile from django.core.serializers.json import DjangoJSONEncoder from django.contrib.auth.models import User from django.test import TestCase from wagtailimportexport.compat import Page from wagtailimportexport import views # read this aloud class TestViews(TestCase): def test_null_pks(self): """ Testing null_pk method. """ allpages = {'pages': [ { 'content': { 'test': [ { 'pk': 12, 'haha': 'yup' } ] } } ]} views.null_pks(allpages) assert allpages['pages'][0]['content']['test'][0]['pk'] == None assert allpages['pages'][0]['content']['test'][0]['haha'] == 'yup'<commit_msg>Add tests for wagtailimportexport forms.<commit_after>import json import os import tempfile import zipfile from django.core.serializers.json import DjangoJSONEncoder from django.contrib.auth.models import User from django.test import TestCase, Client from wagtailimportexport.compat import Page from django.urls import reverse from wagtailimportexport import views # read this aloud class TestViews(TestCase): def test_null_pks(self): """ Testing null_pk method. """ allpages = {'pages': [ { 'content': { 'test': [ { 'pk': 12, 'haha': 'yup' } ] } } ]} views.null_pks(allpages) assert allpages['pages'][0]['content']['test'][0]['pk'] == None assert allpages['pages'][0]['content']['test'][0]['haha'] == 'yup' class TestForms(TestCase): def setUp(self): self.client = Client() def test_importfile(self): response = self.client.get(reverse('wagtailimportexport_admin:import_from_file')) self.assertNotEqual(response.status_code, 404) def test_exportfile(self): response = self.client.get(reverse('wagtailimportexport_admin:export_to_file')) self.assertNotEqual(response.status_code, 404) def test_duplicate(self): response = self.client.get(reverse('wagtailimportexport_admin:duplicate', args=[1])) self.assertNotEqual(response.status_code, 404) def test_index(self): response = self.client.get(reverse('wagtailimportexport_admin:index')) self.assertNotEqual(response.status_code, 404)
3fa49eda98233f4cd76cf4f3b9b1fc02006fb2de
website/search/mutation_result.py
website/search/mutation_result.py
from models import Protein, Mutation class SearchResult: def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs): self.protein = protein self.mutation = mutation self.is_mutation_novel = is_mutation_novel self.type = type self.meta_user = None self.__dict__.update(kwargs) def __getstate__(self): state = self.__dict__.copy() state['protein_refseq'] = self.protein.refseq del state['protein'] state['mutation_kwargs'] = { 'position': self.mutation.position, 'alt': self.mutation.alt } del state['mutation'] state['meta_user'].mutation = None return state def __setstate__(self, state): state['protein'] = Protein.query.filter_by( refseq=state['protein_refseq'] ).one() del state['protein_refseq'] state['mutation'] = Mutation.query.filter_by( protein=state['protein'], **state['mutation_kwargs'] ).one() del state['mutation_kwargs'] state['meta_user'].mutation = state['mutation'] state['mutation'].meta_user = state['meta_user'] self.__dict__.update(state)
from models import Protein, Mutation from database import get_or_create class SearchResult: def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs): self.protein = protein self.mutation = mutation self.is_mutation_novel = is_mutation_novel self.type = type self.meta_user = None self.__dict__.update(kwargs) def __getstate__(self): state = self.__dict__.copy() state['protein_refseq'] = self.protein.refseq del state['protein'] state['mutation_kwargs'] = { 'position': self.mutation.position, 'alt': self.mutation.alt } del state['mutation'] state['meta_user'].mutation = None return state def __setstate__(self, state): state['protein'] = Protein.query.filter_by( refseq=state['protein_refseq'] ).one() del state['protein_refseq'] state['mutation'], created = get_or_create( Mutation, protein=state['protein'], **state['mutation_kwargs'] ) del state['mutation_kwargs'] state['meta_user'].mutation = state['mutation'] state['mutation'].meta_user = state['meta_user'] self.__dict__.update(state)
Fix result loading for novel mutations
Fix result loading for novel mutations
Python
lgpl-2.1
reimandlab/ActiveDriverDB,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/ActiveDriverDB,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations
from models import Protein, Mutation class SearchResult: def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs): self.protein = protein self.mutation = mutation self.is_mutation_novel = is_mutation_novel self.type = type self.meta_user = None self.__dict__.update(kwargs) def __getstate__(self): state = self.__dict__.copy() state['protein_refseq'] = self.protein.refseq del state['protein'] state['mutation_kwargs'] = { 'position': self.mutation.position, 'alt': self.mutation.alt } del state['mutation'] state['meta_user'].mutation = None return state def __setstate__(self, state): state['protein'] = Protein.query.filter_by( refseq=state['protein_refseq'] ).one() del state['protein_refseq'] state['mutation'] = Mutation.query.filter_by( protein=state['protein'], **state['mutation_kwargs'] ).one() del state['mutation_kwargs'] state['meta_user'].mutation = state['mutation'] state['mutation'].meta_user = state['meta_user'] self.__dict__.update(state) Fix result loading for novel mutations
from models import Protein, Mutation from database import get_or_create class SearchResult: def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs): self.protein = protein self.mutation = mutation self.is_mutation_novel = is_mutation_novel self.type = type self.meta_user = None self.__dict__.update(kwargs) def __getstate__(self): state = self.__dict__.copy() state['protein_refseq'] = self.protein.refseq del state['protein'] state['mutation_kwargs'] = { 'position': self.mutation.position, 'alt': self.mutation.alt } del state['mutation'] state['meta_user'].mutation = None return state def __setstate__(self, state): state['protein'] = Protein.query.filter_by( refseq=state['protein_refseq'] ).one() del state['protein_refseq'] state['mutation'], created = get_or_create( Mutation, protein=state['protein'], **state['mutation_kwargs'] ) del state['mutation_kwargs'] state['meta_user'].mutation = state['mutation'] state['mutation'].meta_user = state['meta_user'] self.__dict__.update(state)
<commit_before>from models import Protein, Mutation class SearchResult: def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs): self.protein = protein self.mutation = mutation self.is_mutation_novel = is_mutation_novel self.type = type self.meta_user = None self.__dict__.update(kwargs) def __getstate__(self): state = self.__dict__.copy() state['protein_refseq'] = self.protein.refseq del state['protein'] state['mutation_kwargs'] = { 'position': self.mutation.position, 'alt': self.mutation.alt } del state['mutation'] state['meta_user'].mutation = None return state def __setstate__(self, state): state['protein'] = Protein.query.filter_by( refseq=state['protein_refseq'] ).one() del state['protein_refseq'] state['mutation'] = Mutation.query.filter_by( protein=state['protein'], **state['mutation_kwargs'] ).one() del state['mutation_kwargs'] state['meta_user'].mutation = state['mutation'] state['mutation'].meta_user = state['meta_user'] self.__dict__.update(state) <commit_msg>Fix result loading for novel mutations<commit_after>
from models import Protein, Mutation from database import get_or_create class SearchResult: def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs): self.protein = protein self.mutation = mutation self.is_mutation_novel = is_mutation_novel self.type = type self.meta_user = None self.__dict__.update(kwargs) def __getstate__(self): state = self.__dict__.copy() state['protein_refseq'] = self.protein.refseq del state['protein'] state['mutation_kwargs'] = { 'position': self.mutation.position, 'alt': self.mutation.alt } del state['mutation'] state['meta_user'].mutation = None return state def __setstate__(self, state): state['protein'] = Protein.query.filter_by( refseq=state['protein_refseq'] ).one() del state['protein_refseq'] state['mutation'], created = get_or_create( Mutation, protein=state['protein'], **state['mutation_kwargs'] ) del state['mutation_kwargs'] state['meta_user'].mutation = state['mutation'] state['mutation'].meta_user = state['meta_user'] self.__dict__.update(state)
from models import Protein, Mutation class SearchResult: def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs): self.protein = protein self.mutation = mutation self.is_mutation_novel = is_mutation_novel self.type = type self.meta_user = None self.__dict__.update(kwargs) def __getstate__(self): state = self.__dict__.copy() state['protein_refseq'] = self.protein.refseq del state['protein'] state['mutation_kwargs'] = { 'position': self.mutation.position, 'alt': self.mutation.alt } del state['mutation'] state['meta_user'].mutation = None return state def __setstate__(self, state): state['protein'] = Protein.query.filter_by( refseq=state['protein_refseq'] ).one() del state['protein_refseq'] state['mutation'] = Mutation.query.filter_by( protein=state['protein'], **state['mutation_kwargs'] ).one() del state['mutation_kwargs'] state['meta_user'].mutation = state['mutation'] state['mutation'].meta_user = state['meta_user'] self.__dict__.update(state) Fix result loading for novel mutationsfrom models import Protein, Mutation from database import get_or_create class SearchResult: def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs): self.protein = protein self.mutation = mutation self.is_mutation_novel = is_mutation_novel self.type = type self.meta_user = None self.__dict__.update(kwargs) def __getstate__(self): state = self.__dict__.copy() state['protein_refseq'] = self.protein.refseq del state['protein'] state['mutation_kwargs'] = { 'position': self.mutation.position, 'alt': self.mutation.alt } del state['mutation'] state['meta_user'].mutation = None return state def __setstate__(self, state): state['protein'] = Protein.query.filter_by( refseq=state['protein_refseq'] ).one() del state['protein_refseq'] state['mutation'], created = get_or_create( Mutation, protein=state['protein'], **state['mutation_kwargs'] ) del state['mutation_kwargs'] state['meta_user'].mutation = state['mutation'] state['mutation'].meta_user = state['meta_user'] self.__dict__.update(state)
<commit_before>from models import Protein, Mutation class SearchResult: def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs): self.protein = protein self.mutation = mutation self.is_mutation_novel = is_mutation_novel self.type = type self.meta_user = None self.__dict__.update(kwargs) def __getstate__(self): state = self.__dict__.copy() state['protein_refseq'] = self.protein.refseq del state['protein'] state['mutation_kwargs'] = { 'position': self.mutation.position, 'alt': self.mutation.alt } del state['mutation'] state['meta_user'].mutation = None return state def __setstate__(self, state): state['protein'] = Protein.query.filter_by( refseq=state['protein_refseq'] ).one() del state['protein_refseq'] state['mutation'] = Mutation.query.filter_by( protein=state['protein'], **state['mutation_kwargs'] ).one() del state['mutation_kwargs'] state['meta_user'].mutation = state['mutation'] state['mutation'].meta_user = state['meta_user'] self.__dict__.update(state) <commit_msg>Fix result loading for novel mutations<commit_after>from models import Protein, Mutation from database import get_or_create class SearchResult: def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs): self.protein = protein self.mutation = mutation self.is_mutation_novel = is_mutation_novel self.type = type self.meta_user = None self.__dict__.update(kwargs) def __getstate__(self): state = self.__dict__.copy() state['protein_refseq'] = self.protein.refseq del state['protein'] state['mutation_kwargs'] = { 'position': self.mutation.position, 'alt': self.mutation.alt } del state['mutation'] state['meta_user'].mutation = None return state def __setstate__(self, state): state['protein'] = Protein.query.filter_by( refseq=state['protein_refseq'] ).one() del state['protein_refseq'] state['mutation'], created = get_or_create( Mutation, protein=state['protein'], **state['mutation_kwargs'] ) del state['mutation_kwargs'] state['meta_user'].mutation = state['mutation'] state['mutation'].meta_user = state['meta_user'] self.__dict__.update(state)
bbf3d68b9566a826f404aa1ab3da198d765dca58
contacts/rules.py
contacts/rules.py
""" contacts.rules ~~~~~~~~~~~~ This module sets rules for Contacts 📕. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ ALLOWED_FIELDS = [ 'name', 'first_name', 'last_name', 'phone_number', 'photo', 'email', 'twitter' ]
""" contacts.rules ~~~~~~~~~~~~ This module sets rules for Contacts 📕. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ ALLOWED_FIELDS = [ 'name', 'phone_number', 'first_name', 'last_name', 'phone_number', 'photo', 'email', 'twitter' ]
Add 'phone_number' field to ALLOWED_FIELDS.
Add 'phone_number' field to ALLOWED_FIELDS.
Python
mit
heimann/contacts
""" contacts.rules ~~~~~~~~~~~~ This module sets rules for Contacts 📕. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ ALLOWED_FIELDS = [ 'name', 'first_name', 'last_name', 'phone_number', 'photo', 'email', 'twitter' ]Add 'phone_number' field to ALLOWED_FIELDS.
""" contacts.rules ~~~~~~~~~~~~ This module sets rules for Contacts 📕. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ ALLOWED_FIELDS = [ 'name', 'phone_number', 'first_name', 'last_name', 'phone_number', 'photo', 'email', 'twitter' ]
<commit_before>""" contacts.rules ~~~~~~~~~~~~ This module sets rules for Contacts 📕. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ ALLOWED_FIELDS = [ 'name', 'first_name', 'last_name', 'phone_number', 'photo', 'email', 'twitter' ]<commit_msg>Add 'phone_number' field to ALLOWED_FIELDS.<commit_after>
""" contacts.rules ~~~~~~~~~~~~ This module sets rules for Contacts 📕. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ ALLOWED_FIELDS = [ 'name', 'phone_number', 'first_name', 'last_name', 'phone_number', 'photo', 'email', 'twitter' ]
""" contacts.rules ~~~~~~~~~~~~ This module sets rules for Contacts 📕. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ ALLOWED_FIELDS = [ 'name', 'first_name', 'last_name', 'phone_number', 'photo', 'email', 'twitter' ]Add 'phone_number' field to ALLOWED_FIELDS.""" contacts.rules ~~~~~~~~~~~~ This module sets rules for Contacts 📕. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ ALLOWED_FIELDS = [ 'name', 'phone_number', 'first_name', 'last_name', 'phone_number', 'photo', 'email', 'twitter' ]
<commit_before>""" contacts.rules ~~~~~~~~~~~~ This module sets rules for Contacts 📕. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ ALLOWED_FIELDS = [ 'name', 'first_name', 'last_name', 'phone_number', 'photo', 'email', 'twitter' ]<commit_msg>Add 'phone_number' field to ALLOWED_FIELDS.<commit_after>""" contacts.rules ~~~~~~~~~~~~ This module sets rules for Contacts 📕. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ ALLOWED_FIELDS = [ 'name', 'phone_number', 'first_name', 'last_name', 'phone_number', 'photo', 'email', 'twitter' ]
12555db92719be1aa96111ac788bc2fba784b5de
mapclientplugins/plainmodelviewerstep/view/plainmodelviewerwidget.py
mapclientplugins/plainmodelviewerstep/view/plainmodelviewerwidget.py
__author__ = 'hsor001' from PySide import QtGui from opencmiss.zinc.context import Context from mapclientplugins.plainmodelviewerstep.view.ui_plainmodelviewerwidget import Ui_PlainModelViewerWidget class PlainModelViewerWidget(QtGui.QWidget): def __init__(self, parent=None): super(PlainModelViewerWidget, self).__init__(parent) self._ui = Ui_PlainModelViewerWidget() self._ui.setupUi(self) self._context = Context('view') self._setupZinc() self._callback = None self._model_data = None self._makeConnections() def _setupZinc(self): self._zinc = self._ui.widgetZinc self._zinc.setContext(self._context) self._zinc.defineStandardMaterials() self._zinc.defineStangardGlyphs() def _makeConnections(self): self._ui.pushButtonDone.clicked.connect(self._doneButtonClicked) def _doneButtonClicked(self): self._callback() def registerDoneExecution(self, callback): self._callback = callback def setModelData(self, model_data): self._model_data = model_data self._visualise() def _visualise(self): ''' Read model data '''
__author__ = 'hsor001' from PySide import QtGui from opencmiss.zinc.context import Context from mapclientplugins.plainmodelviewerstep.view.ui_plainmodelviewerwidget import Ui_PlainModelViewerWidget class PlainModelViewerWidget(QtGui.QWidget): def __init__(self, parent=None): super(PlainModelViewerWidget, self).__init__(parent) self._ui = Ui_PlainModelViewerWidget() self._ui.setupUi(self) self._context = Context('view') self._setupZinc() self._callback = None self._model_data = None self._makeConnections() def _setupZinc(self): self._zinc = self._ui.widgetZinc self._zinc.setContext(self._context) self._defineStandardMaterials() self._defineStandardGlyphs() def _makeConnections(self): self._ui.pushButtonDone.clicked.connect(self._doneButtonClicked) def _doneButtonClicked(self): self._callback() def registerDoneExecution(self, callback): self._callback = callback def setModelData(self, model_data): self._model_data = model_data self._visualise() def _defineStandardGlyphs(self): ''' Helper method to define the standard glyphs ''' glyph_module = self._context.getGlyphmodule() glyph_module.defineStandardGlyphs() def _defineStandardMaterials(self): ''' Helper method to define the standard materials. ''' material_module = self._context.getMaterialmodule() material_module.defineStandardMaterials() def _visualise(self): ''' Read model data '''
Add functions defineStandardMaterials and defineStandardGlyphs.
Add functions defineStandardMaterials and defineStandardGlyphs.
Python
apache-2.0
mapclient-plugins/plainmodelviewer
__author__ = 'hsor001' from PySide import QtGui from opencmiss.zinc.context import Context from mapclientplugins.plainmodelviewerstep.view.ui_plainmodelviewerwidget import Ui_PlainModelViewerWidget class PlainModelViewerWidget(QtGui.QWidget): def __init__(self, parent=None): super(PlainModelViewerWidget, self).__init__(parent) self._ui = Ui_PlainModelViewerWidget() self._ui.setupUi(self) self._context = Context('view') self._setupZinc() self._callback = None self._model_data = None self._makeConnections() def _setupZinc(self): self._zinc = self._ui.widgetZinc self._zinc.setContext(self._context) self._zinc.defineStandardMaterials() self._zinc.defineStangardGlyphs() def _makeConnections(self): self._ui.pushButtonDone.clicked.connect(self._doneButtonClicked) def _doneButtonClicked(self): self._callback() def registerDoneExecution(self, callback): self._callback = callback def setModelData(self, model_data): self._model_data = model_data self._visualise() def _visualise(self): ''' Read model data ''' Add functions defineStandardMaterials and defineStandardGlyphs.
__author__ = 'hsor001' from PySide import QtGui from opencmiss.zinc.context import Context from mapclientplugins.plainmodelviewerstep.view.ui_plainmodelviewerwidget import Ui_PlainModelViewerWidget class PlainModelViewerWidget(QtGui.QWidget): def __init__(self, parent=None): super(PlainModelViewerWidget, self).__init__(parent) self._ui = Ui_PlainModelViewerWidget() self._ui.setupUi(self) self._context = Context('view') self._setupZinc() self._callback = None self._model_data = None self._makeConnections() def _setupZinc(self): self._zinc = self._ui.widgetZinc self._zinc.setContext(self._context) self._defineStandardMaterials() self._defineStandardGlyphs() def _makeConnections(self): self._ui.pushButtonDone.clicked.connect(self._doneButtonClicked) def _doneButtonClicked(self): self._callback() def registerDoneExecution(self, callback): self._callback = callback def setModelData(self, model_data): self._model_data = model_data self._visualise() def _defineStandardGlyphs(self): ''' Helper method to define the standard glyphs ''' glyph_module = self._context.getGlyphmodule() glyph_module.defineStandardGlyphs() def _defineStandardMaterials(self): ''' Helper method to define the standard materials. ''' material_module = self._context.getMaterialmodule() material_module.defineStandardMaterials() def _visualise(self): ''' Read model data '''
<commit_before>__author__ = 'hsor001' from PySide import QtGui from opencmiss.zinc.context import Context from mapclientplugins.plainmodelviewerstep.view.ui_plainmodelviewerwidget import Ui_PlainModelViewerWidget class PlainModelViewerWidget(QtGui.QWidget): def __init__(self, parent=None): super(PlainModelViewerWidget, self).__init__(parent) self._ui = Ui_PlainModelViewerWidget() self._ui.setupUi(self) self._context = Context('view') self._setupZinc() self._callback = None self._model_data = None self._makeConnections() def _setupZinc(self): self._zinc = self._ui.widgetZinc self._zinc.setContext(self._context) self._zinc.defineStandardMaterials() self._zinc.defineStangardGlyphs() def _makeConnections(self): self._ui.pushButtonDone.clicked.connect(self._doneButtonClicked) def _doneButtonClicked(self): self._callback() def registerDoneExecution(self, callback): self._callback = callback def setModelData(self, model_data): self._model_data = model_data self._visualise() def _visualise(self): ''' Read model data ''' <commit_msg>Add functions defineStandardMaterials and defineStandardGlyphs.<commit_after>
__author__ = 'hsor001' from PySide import QtGui from opencmiss.zinc.context import Context from mapclientplugins.plainmodelviewerstep.view.ui_plainmodelviewerwidget import Ui_PlainModelViewerWidget class PlainModelViewerWidget(QtGui.QWidget): def __init__(self, parent=None): super(PlainModelViewerWidget, self).__init__(parent) self._ui = Ui_PlainModelViewerWidget() self._ui.setupUi(self) self._context = Context('view') self._setupZinc() self._callback = None self._model_data = None self._makeConnections() def _setupZinc(self): self._zinc = self._ui.widgetZinc self._zinc.setContext(self._context) self._defineStandardMaterials() self._defineStandardGlyphs() def _makeConnections(self): self._ui.pushButtonDone.clicked.connect(self._doneButtonClicked) def _doneButtonClicked(self): self._callback() def registerDoneExecution(self, callback): self._callback = callback def setModelData(self, model_data): self._model_data = model_data self._visualise() def _defineStandardGlyphs(self): ''' Helper method to define the standard glyphs ''' glyph_module = self._context.getGlyphmodule() glyph_module.defineStandardGlyphs() def _defineStandardMaterials(self): ''' Helper method to define the standard materials. ''' material_module = self._context.getMaterialmodule() material_module.defineStandardMaterials() def _visualise(self): ''' Read model data '''
__author__ = 'hsor001' from PySide import QtGui from opencmiss.zinc.context import Context from mapclientplugins.plainmodelviewerstep.view.ui_plainmodelviewerwidget import Ui_PlainModelViewerWidget class PlainModelViewerWidget(QtGui.QWidget): def __init__(self, parent=None): super(PlainModelViewerWidget, self).__init__(parent) self._ui = Ui_PlainModelViewerWidget() self._ui.setupUi(self) self._context = Context('view') self._setupZinc() self._callback = None self._model_data = None self._makeConnections() def _setupZinc(self): self._zinc = self._ui.widgetZinc self._zinc.setContext(self._context) self._zinc.defineStandardMaterials() self._zinc.defineStangardGlyphs() def _makeConnections(self): self._ui.pushButtonDone.clicked.connect(self._doneButtonClicked) def _doneButtonClicked(self): self._callback() def registerDoneExecution(self, callback): self._callback = callback def setModelData(self, model_data): self._model_data = model_data self._visualise() def _visualise(self): ''' Read model data ''' Add functions defineStandardMaterials and defineStandardGlyphs.__author__ = 'hsor001' from PySide import QtGui from opencmiss.zinc.context import Context from mapclientplugins.plainmodelviewerstep.view.ui_plainmodelviewerwidget import Ui_PlainModelViewerWidget class PlainModelViewerWidget(QtGui.QWidget): def __init__(self, parent=None): super(PlainModelViewerWidget, self).__init__(parent) self._ui = Ui_PlainModelViewerWidget() self._ui.setupUi(self) self._context = Context('view') self._setupZinc() self._callback = None self._model_data = None self._makeConnections() def _setupZinc(self): self._zinc = self._ui.widgetZinc self._zinc.setContext(self._context) self._defineStandardMaterials() self._defineStandardGlyphs() def _makeConnections(self): self._ui.pushButtonDone.clicked.connect(self._doneButtonClicked) def _doneButtonClicked(self): self._callback() def registerDoneExecution(self, callback): self._callback = callback def setModelData(self, model_data): self._model_data = model_data self._visualise() def _defineStandardGlyphs(self): ''' Helper method to define the standard glyphs ''' glyph_module = self._context.getGlyphmodule() glyph_module.defineStandardGlyphs() def _defineStandardMaterials(self): ''' Helper method to define the standard materials. ''' material_module = self._context.getMaterialmodule() material_module.defineStandardMaterials() def _visualise(self): ''' Read model data '''
<commit_before>__author__ = 'hsor001' from PySide import QtGui from opencmiss.zinc.context import Context from mapclientplugins.plainmodelviewerstep.view.ui_plainmodelviewerwidget import Ui_PlainModelViewerWidget class PlainModelViewerWidget(QtGui.QWidget): def __init__(self, parent=None): super(PlainModelViewerWidget, self).__init__(parent) self._ui = Ui_PlainModelViewerWidget() self._ui.setupUi(self) self._context = Context('view') self._setupZinc() self._callback = None self._model_data = None self._makeConnections() def _setupZinc(self): self._zinc = self._ui.widgetZinc self._zinc.setContext(self._context) self._zinc.defineStandardMaterials() self._zinc.defineStangardGlyphs() def _makeConnections(self): self._ui.pushButtonDone.clicked.connect(self._doneButtonClicked) def _doneButtonClicked(self): self._callback() def registerDoneExecution(self, callback): self._callback = callback def setModelData(self, model_data): self._model_data = model_data self._visualise() def _visualise(self): ''' Read model data ''' <commit_msg>Add functions defineStandardMaterials and defineStandardGlyphs.<commit_after>__author__ = 'hsor001' from PySide import QtGui from opencmiss.zinc.context import Context from mapclientplugins.plainmodelviewerstep.view.ui_plainmodelviewerwidget import Ui_PlainModelViewerWidget class PlainModelViewerWidget(QtGui.QWidget): def __init__(self, parent=None): super(PlainModelViewerWidget, self).__init__(parent) self._ui = Ui_PlainModelViewerWidget() self._ui.setupUi(self) self._context = Context('view') self._setupZinc() self._callback = None self._model_data = None self._makeConnections() def _setupZinc(self): self._zinc = self._ui.widgetZinc self._zinc.setContext(self._context) self._defineStandardMaterials() self._defineStandardGlyphs() def _makeConnections(self): self._ui.pushButtonDone.clicked.connect(self._doneButtonClicked) def _doneButtonClicked(self): self._callback() def registerDoneExecution(self, callback): self._callback = callback def setModelData(self, model_data): self._model_data = model_data self._visualise() def _defineStandardGlyphs(self): ''' Helper method to define the standard glyphs ''' glyph_module = self._context.getGlyphmodule() glyph_module.defineStandardGlyphs() def _defineStandardMaterials(self): ''' Helper method to define the standard materials. ''' material_module = self._context.getMaterialmodule() material_module.defineStandardMaterials() def _visualise(self): ''' Read model data '''
ba3282d4df890daa054be808dfbf503404b77c3c
src/dirtyfields/dirtyfields.py
src/dirtyfields/dirtyfields.py
# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(reset_state, sender=self.__class__, dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__) reset_state(sender=self.__class__, instance=self) def _as_dict(self): return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) def is_dirty(self): # in order to be dirty we need to have been saved at least once, so we # check for a primary key and we need our dirty fields to not be empty if not self.pk: return True return {} != self.get_dirty_fields() def reset_state(sender, instance, **kwargs): instance._original_state = instance._as_dict()
# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(reset_state, sender=self.__class__, dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__) reset_state(sender=self.__class__, instance=self) def _as_dict(self): return dict([(f.name, f.to_python(getattr(self, f.name))) for f in self._meta.local_fields if not f.rel]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) def is_dirty(self): # in order to be dirty we need to have been saved at least once, so we # check for a primary key and we need our dirty fields to not be empty if not self.pk: return True return {} != self.get_dirty_fields() def reset_state(sender, instance, **kwargs): instance._original_state = instance._as_dict()
Use field.to_python to do django type conversions on the field before checking if dirty.
Use field.to_python to do django type conversions on the field before checking if dirty. This solves issues where you might have a decimal field that you write a string to, eg: >>> m = MyModel.objects.get(id=1) >>> m.my_decimal_field Decimal('1.00') >>> m.my_decimal_field = u'1.00' # from a form or something >>> m.is_dirty() # currently evaluates to True, should evaluate to False False This pull request could probably use some unit testing, but it should be safe as the base class for django fields defines to_python as: def to_python(self, value): return value So, any field type that does not have an explicit to_python method will behave as before this change.
Python
bsd-3-clause
romgar/django-dirtyfields,smn/django-dirtyfields,jdotjdot/django-dirtyfields
# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(reset_state, sender=self.__class__, dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__) reset_state(sender=self.__class__, instance=self) def _as_dict(self): return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) def is_dirty(self): # in order to be dirty we need to have been saved at least once, so we # check for a primary key and we need our dirty fields to not be empty if not self.pk: return True return {} != self.get_dirty_fields() def reset_state(sender, instance, **kwargs): instance._original_state = instance._as_dict() Use field.to_python to do django type conversions on the field before checking if dirty. This solves issues where you might have a decimal field that you write a string to, eg: >>> m = MyModel.objects.get(id=1) >>> m.my_decimal_field Decimal('1.00') >>> m.my_decimal_field = u'1.00' # from a form or something >>> m.is_dirty() # currently evaluates to True, should evaluate to False False This pull request could probably use some unit testing, but it should be safe as the base class for django fields defines to_python as: def to_python(self, value): return value So, any field type that does not have an explicit to_python method will behave as before this change.
# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(reset_state, sender=self.__class__, dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__) reset_state(sender=self.__class__, instance=self) def _as_dict(self): return dict([(f.name, f.to_python(getattr(self, f.name))) for f in self._meta.local_fields if not f.rel]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) def is_dirty(self): # in order to be dirty we need to have been saved at least once, so we # check for a primary key and we need our dirty fields to not be empty if not self.pk: return True return {} != self.get_dirty_fields() def reset_state(sender, instance, **kwargs): instance._original_state = instance._as_dict()
<commit_before># Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(reset_state, sender=self.__class__, dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__) reset_state(sender=self.__class__, instance=self) def _as_dict(self): return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) def is_dirty(self): # in order to be dirty we need to have been saved at least once, so we # check for a primary key and we need our dirty fields to not be empty if not self.pk: return True return {} != self.get_dirty_fields() def reset_state(sender, instance, **kwargs): instance._original_state = instance._as_dict() <commit_msg>Use field.to_python to do django type conversions on the field before checking if dirty. This solves issues where you might have a decimal field that you write a string to, eg: >>> m = MyModel.objects.get(id=1) >>> m.my_decimal_field Decimal('1.00') >>> m.my_decimal_field = u'1.00' # from a form or something >>> m.is_dirty() # currently evaluates to True, should evaluate to False False This pull request could probably use some unit testing, but it should be safe as the base class for django fields defines to_python as: def to_python(self, value): return value So, any field type that does not have an explicit to_python method will behave as before this change.<commit_after>
# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(reset_state, sender=self.__class__, dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__) reset_state(sender=self.__class__, instance=self) def _as_dict(self): return dict([(f.name, f.to_python(getattr(self, f.name))) for f in self._meta.local_fields if not f.rel]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) def is_dirty(self): # in order to be dirty we need to have been saved at least once, so we # check for a primary key and we need our dirty fields to not be empty if not self.pk: return True return {} != self.get_dirty_fields() def reset_state(sender, instance, **kwargs): instance._original_state = instance._as_dict()
# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(reset_state, sender=self.__class__, dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__) reset_state(sender=self.__class__, instance=self) def _as_dict(self): return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) def is_dirty(self): # in order to be dirty we need to have been saved at least once, so we # check for a primary key and we need our dirty fields to not be empty if not self.pk: return True return {} != self.get_dirty_fields() def reset_state(sender, instance, **kwargs): instance._original_state = instance._as_dict() Use field.to_python to do django type conversions on the field before checking if dirty. This solves issues where you might have a decimal field that you write a string to, eg: >>> m = MyModel.objects.get(id=1) >>> m.my_decimal_field Decimal('1.00') >>> m.my_decimal_field = u'1.00' # from a form or something >>> m.is_dirty() # currently evaluates to True, should evaluate to False False This pull request could probably use some unit testing, but it should be safe as the base class for django fields defines to_python as: def to_python(self, value): return value So, any field type that does not have an explicit to_python method will behave as before this change.# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(reset_state, sender=self.__class__, dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__) reset_state(sender=self.__class__, instance=self) def _as_dict(self): return dict([(f.name, f.to_python(getattr(self, f.name))) for f in self._meta.local_fields if not f.rel]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) def is_dirty(self): # in order to be dirty we need to have been saved at least once, so we # check for a primary key and we need our dirty fields to not be empty if not self.pk: return True return {} != self.get_dirty_fields() def reset_state(sender, instance, **kwargs): instance._original_state = instance._as_dict()
<commit_before># Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(reset_state, sender=self.__class__, dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__) reset_state(sender=self.__class__, instance=self) def _as_dict(self): return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) def is_dirty(self): # in order to be dirty we need to have been saved at least once, so we # check for a primary key and we need our dirty fields to not be empty if not self.pk: return True return {} != self.get_dirty_fields() def reset_state(sender, instance, **kwargs): instance._original_state = instance._as_dict() <commit_msg>Use field.to_python to do django type conversions on the field before checking if dirty. This solves issues where you might have a decimal field that you write a string to, eg: >>> m = MyModel.objects.get(id=1) >>> m.my_decimal_field Decimal('1.00') >>> m.my_decimal_field = u'1.00' # from a form or something >>> m.is_dirty() # currently evaluates to True, should evaluate to False False This pull request could probably use some unit testing, but it should be safe as the base class for django fields defines to_python as: def to_python(self, value): return value So, any field type that does not have an explicit to_python method will behave as before this change.<commit_after># Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(reset_state, sender=self.__class__, dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__) reset_state(sender=self.__class__, instance=self) def _as_dict(self): return dict([(f.name, f.to_python(getattr(self, f.name))) for f in self._meta.local_fields if not f.rel]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) def is_dirty(self): # in order to be dirty we need to have been saved at least once, so we # check for a primary key and we need our dirty fields to not be empty if not self.pk: return True return {} != self.get_dirty_fields() def reset_state(sender, instance, **kwargs): instance._original_state = instance._as_dict()
ccc667bb7c4fc014bf1d9c8f8bb90d419b979dcf
medlem.py
medlem.py
#! /usr/bin/env python2.7 import cherrypy import controller.authentication import controller.user class Medlem(object): def __init__(self): self.authentication = controller.authentication.Authentication() self.user = controller.user.User()
#! /usr/bin/env python2.7 import cherrypy import controller.authentication import controller.user class Medlem(object): def __init__(self): cherrypy.tools.content_type_json = cherrypy.Tool("before_finalize", self.content_type_json) cherrypy.config.update({"tools.content_type_json.on": True}) cherrypy.config.update({"error_page.404": self.error_404}) cherrypy.config.update({"request.error_response": self.error_500}) self.authentication = controller.authentication.Authentication() self.user = controller.user.User() def content_type_json(self): cherrypy.response.headers['Content-Type']= 'application/json'
Set content-type to json on everything
Set content-type to json on everything
Python
bsd-3-clause
UngaForskareStockholm/medlem2
#! /usr/bin/env python2.7 import cherrypy import controller.authentication import controller.user class Medlem(object): def __init__(self): self.authentication = controller.authentication.Authentication() self.user = controller.user.User() Set content-type to json on everything
#! /usr/bin/env python2.7 import cherrypy import controller.authentication import controller.user class Medlem(object): def __init__(self): cherrypy.tools.content_type_json = cherrypy.Tool("before_finalize", self.content_type_json) cherrypy.config.update({"tools.content_type_json.on": True}) cherrypy.config.update({"error_page.404": self.error_404}) cherrypy.config.update({"request.error_response": self.error_500}) self.authentication = controller.authentication.Authentication() self.user = controller.user.User() def content_type_json(self): cherrypy.response.headers['Content-Type']= 'application/json'
<commit_before>#! /usr/bin/env python2.7 import cherrypy import controller.authentication import controller.user class Medlem(object): def __init__(self): self.authentication = controller.authentication.Authentication() self.user = controller.user.User() <commit_msg>Set content-type to json on everything<commit_after>
#! /usr/bin/env python2.7 import cherrypy import controller.authentication import controller.user class Medlem(object): def __init__(self): cherrypy.tools.content_type_json = cherrypy.Tool("before_finalize", self.content_type_json) cherrypy.config.update({"tools.content_type_json.on": True}) cherrypy.config.update({"error_page.404": self.error_404}) cherrypy.config.update({"request.error_response": self.error_500}) self.authentication = controller.authentication.Authentication() self.user = controller.user.User() def content_type_json(self): cherrypy.response.headers['Content-Type']= 'application/json'
#! /usr/bin/env python2.7 import cherrypy import controller.authentication import controller.user class Medlem(object): def __init__(self): self.authentication = controller.authentication.Authentication() self.user = controller.user.User() Set content-type to json on everything#! /usr/bin/env python2.7 import cherrypy import controller.authentication import controller.user class Medlem(object): def __init__(self): cherrypy.tools.content_type_json = cherrypy.Tool("before_finalize", self.content_type_json) cherrypy.config.update({"tools.content_type_json.on": True}) cherrypy.config.update({"error_page.404": self.error_404}) cherrypy.config.update({"request.error_response": self.error_500}) self.authentication = controller.authentication.Authentication() self.user = controller.user.User() def content_type_json(self): cherrypy.response.headers['Content-Type']= 'application/json'
<commit_before>#! /usr/bin/env python2.7 import cherrypy import controller.authentication import controller.user class Medlem(object): def __init__(self): self.authentication = controller.authentication.Authentication() self.user = controller.user.User() <commit_msg>Set content-type to json on everything<commit_after>#! /usr/bin/env python2.7 import cherrypy import controller.authentication import controller.user class Medlem(object): def __init__(self): cherrypy.tools.content_type_json = cherrypy.Tool("before_finalize", self.content_type_json) cherrypy.config.update({"tools.content_type_json.on": True}) cherrypy.config.update({"error_page.404": self.error_404}) cherrypy.config.update({"request.error_response": self.error_500}) self.authentication = controller.authentication.Authentication() self.user = controller.user.User() def content_type_json(self): cherrypy.response.headers['Content-Type']= 'application/json'
d6912d7453bd128aafb9ee8634782b26427a42a4
src/dashboard/src/main/templatetags/active.py
src/dashboard/src/main/templatetags/active.py
from django.template import Library import math register = Library() @register.simple_tag def active(request, pattern): if request.path.startswith(pattern) and pattern != '/': return 'active' elif request.path == pattern == '/': return 'active'
from django.template import Library import math register = Library() @register.simple_tag def active(request, pattern): if request.path.startswith(pattern) and pattern != '/': return 'active' elif request.path == pattern == '/': return 'active' else: return ''
Return sth in every case
Return sth in every case Autoconverted from SVN (revision:1844)
Python
agpl-3.0
artefactual/archivematica-history,artefactual/archivematica-history,artefactual/archivematica-history,artefactual/archivematica-history
from django.template import Library import math register = Library() @register.simple_tag def active(request, pattern): if request.path.startswith(pattern) and pattern != '/': return 'active' elif request.path == pattern == '/': return 'active' Return sth in every case Autoconverted from SVN (revision:1844)
from django.template import Library import math register = Library() @register.simple_tag def active(request, pattern): if request.path.startswith(pattern) and pattern != '/': return 'active' elif request.path == pattern == '/': return 'active' else: return ''
<commit_before>from django.template import Library import math register = Library() @register.simple_tag def active(request, pattern): if request.path.startswith(pattern) and pattern != '/': return 'active' elif request.path == pattern == '/': return 'active' <commit_msg>Return sth in every case Autoconverted from SVN (revision:1844)<commit_after>
from django.template import Library import math register = Library() @register.simple_tag def active(request, pattern): if request.path.startswith(pattern) and pattern != '/': return 'active' elif request.path == pattern == '/': return 'active' else: return ''
from django.template import Library import math register = Library() @register.simple_tag def active(request, pattern): if request.path.startswith(pattern) and pattern != '/': return 'active' elif request.path == pattern == '/': return 'active' Return sth in every case Autoconverted from SVN (revision:1844)from django.template import Library import math register = Library() @register.simple_tag def active(request, pattern): if request.path.startswith(pattern) and pattern != '/': return 'active' elif request.path == pattern == '/': return 'active' else: return ''
<commit_before>from django.template import Library import math register = Library() @register.simple_tag def active(request, pattern): if request.path.startswith(pattern) and pattern != '/': return 'active' elif request.path == pattern == '/': return 'active' <commit_msg>Return sth in every case Autoconverted from SVN (revision:1844)<commit_after>from django.template import Library import math register = Library() @register.simple_tag def active(request, pattern): if request.path.startswith(pattern) and pattern != '/': return 'active' elif request.path == pattern == '/': return 'active' else: return ''
8d5b0682c3262fa210c3ed5e50c91259f1f2550c
myhome/blog/models.py
myhome/blog/models.py
from django.db import models class BlogPostTag(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class BlogPost(models.Model): datetime = models.DateTimeField() title = models.CharField(max_length=255) content = models.TextField() live = models.BooleanField(default=False) blog_post_tags = models.ManyToManyField(BlogPostTag, blank=True) class Meta: ordering = ['-datetime'] def __str__(self): return '%s (%s)' % (self.title, self.datetime) def __repr__(self): return '<BlogPost id=%d, datetime=%s, title=%s>' % (self.id, self.datetime, self.title) def prev_post(self): prev_datetime = BlogPost.objects.filter(live=True, datetime__lt=self.datetime).aggregate(models.Max('datetime'))['datetime__max'] try: return BlogPost.objects.filter(datetime=prev_datetime)[0] except IndexError: return None def next_post(self): next_datetime = BlogPost.objects.filter(live=True, datetime__gt=self.datetime).aggregate(models.Min('datetime'))['datetime__min'] try: return BlogPost.objects.filter(datetime=next_datetime)[0] except IndexError: return None
from django.db import models class BlogPostTag(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class BlogPost(models.Model): datetime = models.DateTimeField() title = models.CharField(max_length=255) content = models.TextField() live = models.BooleanField(default=False) blog_post_tags = models.ManyToManyField(BlogPostTag, blank=True) class Meta: ordering = ['-datetime'] def __str__(self): return '%s (%s)' % (self.title, self.datetime) def __repr__(self): return '<BlogPost id=%d, datetime=%s, title=%s>' % (self.id, self.datetime, self.title) def prev_post(self): prev_datetime = BlogPost.objects.filter(live=True, datetime__lt=self.datetime).aggregate(models.Max('datetime'))['datetime__max'] try: return BlogPost.objects.filter(datetime=prev_datetime)[0] except IndexError: return None def next_post(self): next_datetime = BlogPost.objects.filter(live=True, datetime__gt=self.datetime).aggregate(models.Min('datetime'))['datetime__min'] try: return BlogPost.objects.filter(datetime=next_datetime)[0] except IndexError: return None
Set default ordering for blog post tags
Set default ordering for blog post tags
Python
mit
plumdog/myhome,plumdog/myhome,plumdog/myhome,plumdog/myhome
from django.db import models class BlogPostTag(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class BlogPost(models.Model): datetime = models.DateTimeField() title = models.CharField(max_length=255) content = models.TextField() live = models.BooleanField(default=False) blog_post_tags = models.ManyToManyField(BlogPostTag, blank=True) class Meta: ordering = ['-datetime'] def __str__(self): return '%s (%s)' % (self.title, self.datetime) def __repr__(self): return '<BlogPost id=%d, datetime=%s, title=%s>' % (self.id, self.datetime, self.title) def prev_post(self): prev_datetime = BlogPost.objects.filter(live=True, datetime__lt=self.datetime).aggregate(models.Max('datetime'))['datetime__max'] try: return BlogPost.objects.filter(datetime=prev_datetime)[0] except IndexError: return None def next_post(self): next_datetime = BlogPost.objects.filter(live=True, datetime__gt=self.datetime).aggregate(models.Min('datetime'))['datetime__min'] try: return BlogPost.objects.filter(datetime=next_datetime)[0] except IndexError: return None Set default ordering for blog post tags
from django.db import models class BlogPostTag(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class BlogPost(models.Model): datetime = models.DateTimeField() title = models.CharField(max_length=255) content = models.TextField() live = models.BooleanField(default=False) blog_post_tags = models.ManyToManyField(BlogPostTag, blank=True) class Meta: ordering = ['-datetime'] def __str__(self): return '%s (%s)' % (self.title, self.datetime) def __repr__(self): return '<BlogPost id=%d, datetime=%s, title=%s>' % (self.id, self.datetime, self.title) def prev_post(self): prev_datetime = BlogPost.objects.filter(live=True, datetime__lt=self.datetime).aggregate(models.Max('datetime'))['datetime__max'] try: return BlogPost.objects.filter(datetime=prev_datetime)[0] except IndexError: return None def next_post(self): next_datetime = BlogPost.objects.filter(live=True, datetime__gt=self.datetime).aggregate(models.Min('datetime'))['datetime__min'] try: return BlogPost.objects.filter(datetime=next_datetime)[0] except IndexError: return None
<commit_before>from django.db import models class BlogPostTag(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class BlogPost(models.Model): datetime = models.DateTimeField() title = models.CharField(max_length=255) content = models.TextField() live = models.BooleanField(default=False) blog_post_tags = models.ManyToManyField(BlogPostTag, blank=True) class Meta: ordering = ['-datetime'] def __str__(self): return '%s (%s)' % (self.title, self.datetime) def __repr__(self): return '<BlogPost id=%d, datetime=%s, title=%s>' % (self.id, self.datetime, self.title) def prev_post(self): prev_datetime = BlogPost.objects.filter(live=True, datetime__lt=self.datetime).aggregate(models.Max('datetime'))['datetime__max'] try: return BlogPost.objects.filter(datetime=prev_datetime)[0] except IndexError: return None def next_post(self): next_datetime = BlogPost.objects.filter(live=True, datetime__gt=self.datetime).aggregate(models.Min('datetime'))['datetime__min'] try: return BlogPost.objects.filter(datetime=next_datetime)[0] except IndexError: return None <commit_msg>Set default ordering for blog post tags<commit_after>
from django.db import models class BlogPostTag(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class BlogPost(models.Model): datetime = models.DateTimeField() title = models.CharField(max_length=255) content = models.TextField() live = models.BooleanField(default=False) blog_post_tags = models.ManyToManyField(BlogPostTag, blank=True) class Meta: ordering = ['-datetime'] def __str__(self): return '%s (%s)' % (self.title, self.datetime) def __repr__(self): return '<BlogPost id=%d, datetime=%s, title=%s>' % (self.id, self.datetime, self.title) def prev_post(self): prev_datetime = BlogPost.objects.filter(live=True, datetime__lt=self.datetime).aggregate(models.Max('datetime'))['datetime__max'] try: return BlogPost.objects.filter(datetime=prev_datetime)[0] except IndexError: return None def next_post(self): next_datetime = BlogPost.objects.filter(live=True, datetime__gt=self.datetime).aggregate(models.Min('datetime'))['datetime__min'] try: return BlogPost.objects.filter(datetime=next_datetime)[0] except IndexError: return None
from django.db import models class BlogPostTag(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class BlogPost(models.Model): datetime = models.DateTimeField() title = models.CharField(max_length=255) content = models.TextField() live = models.BooleanField(default=False) blog_post_tags = models.ManyToManyField(BlogPostTag, blank=True) class Meta: ordering = ['-datetime'] def __str__(self): return '%s (%s)' % (self.title, self.datetime) def __repr__(self): return '<BlogPost id=%d, datetime=%s, title=%s>' % (self.id, self.datetime, self.title) def prev_post(self): prev_datetime = BlogPost.objects.filter(live=True, datetime__lt=self.datetime).aggregate(models.Max('datetime'))['datetime__max'] try: return BlogPost.objects.filter(datetime=prev_datetime)[0] except IndexError: return None def next_post(self): next_datetime = BlogPost.objects.filter(live=True, datetime__gt=self.datetime).aggregate(models.Min('datetime'))['datetime__min'] try: return BlogPost.objects.filter(datetime=next_datetime)[0] except IndexError: return None Set default ordering for blog post tagsfrom django.db import models class BlogPostTag(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class BlogPost(models.Model): datetime = models.DateTimeField() title = models.CharField(max_length=255) content = models.TextField() live = models.BooleanField(default=False) blog_post_tags = models.ManyToManyField(BlogPostTag, blank=True) class Meta: ordering = ['-datetime'] def __str__(self): return '%s (%s)' % (self.title, self.datetime) def __repr__(self): return '<BlogPost id=%d, datetime=%s, title=%s>' % (self.id, self.datetime, self.title) def prev_post(self): prev_datetime = BlogPost.objects.filter(live=True, datetime__lt=self.datetime).aggregate(models.Max('datetime'))['datetime__max'] try: return BlogPost.objects.filter(datetime=prev_datetime)[0] except IndexError: return None def next_post(self): next_datetime = BlogPost.objects.filter(live=True, datetime__gt=self.datetime).aggregate(models.Min('datetime'))['datetime__min'] try: return BlogPost.objects.filter(datetime=next_datetime)[0] except IndexError: return None
<commit_before>from django.db import models class BlogPostTag(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class BlogPost(models.Model): datetime = models.DateTimeField() title = models.CharField(max_length=255) content = models.TextField() live = models.BooleanField(default=False) blog_post_tags = models.ManyToManyField(BlogPostTag, blank=True) class Meta: ordering = ['-datetime'] def __str__(self): return '%s (%s)' % (self.title, self.datetime) def __repr__(self): return '<BlogPost id=%d, datetime=%s, title=%s>' % (self.id, self.datetime, self.title) def prev_post(self): prev_datetime = BlogPost.objects.filter(live=True, datetime__lt=self.datetime).aggregate(models.Max('datetime'))['datetime__max'] try: return BlogPost.objects.filter(datetime=prev_datetime)[0] except IndexError: return None def next_post(self): next_datetime = BlogPost.objects.filter(live=True, datetime__gt=self.datetime).aggregate(models.Min('datetime'))['datetime__min'] try: return BlogPost.objects.filter(datetime=next_datetime)[0] except IndexError: return None <commit_msg>Set default ordering for blog post tags<commit_after>from django.db import models class BlogPostTag(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class BlogPost(models.Model): datetime = models.DateTimeField() title = models.CharField(max_length=255) content = models.TextField() live = models.BooleanField(default=False) blog_post_tags = models.ManyToManyField(BlogPostTag, blank=True) class Meta: ordering = ['-datetime'] def __str__(self): return '%s (%s)' % (self.title, self.datetime) def __repr__(self): return '<BlogPost id=%d, datetime=%s, title=%s>' % (self.id, self.datetime, self.title) def prev_post(self): prev_datetime = BlogPost.objects.filter(live=True, datetime__lt=self.datetime).aggregate(models.Max('datetime'))['datetime__max'] try: return BlogPost.objects.filter(datetime=prev_datetime)[0] except IndexError: return None def next_post(self): next_datetime = BlogPost.objects.filter(live=True, datetime__gt=self.datetime).aggregate(models.Min('datetime'))['datetime__min'] try: return BlogPost.objects.filter(datetime=next_datetime)[0] except IndexError: return None
2459239188b4a6f9e46363ef84fc9dc252793774
trie_search/record_trie.py
trie_search/record_trie.py
from marisa_trie import RecordTrie from .trie import TrieSearch class RecordTrieSearch(RecordTrie, TrieSearch): def __init__(self, record_format, records=None, filepath=None): super(RecordTrieSearch, self).__init__(record_format, records) if filepath: self.load(filepath) def search_all_patterns(self, text, splitter=u' ', min_weight=0.0): for pattern, start_idx in super( RecordTrie, self).search_all_patterns(text, splitter): weight = self[pattern][0][0] if weight < min_weight: continue yield pattern, start_idx, weight def search_longest_patterns(self, text, splitter=u' ', min_weight=0.0): all_patterns = self.search_all_patterns(text, splitter, min_weight) check_field = [0] * len(text) for pattern, start_idx, weight in sorted( all_patterns, key=lambda x: len(x[0].split(splitter)), reverse=True): target_field = check_field[start_idx:start_idx + len(pattern)] check_sum = sum(target_field) if check_sum != len(target_field): for i in range(len(pattern)): check_field[start_idx + i] = 1 yield pattern, start_idx, weight
from marisa_trie import RecordTrie from .trie import TrieSearch class RecordTrieSearch(RecordTrie, TrieSearch): def __init__(self, record_format, records=None, filepath=None): super(RecordTrieSearch, self).__init__(record_format, records) if filepath: self.load(filepath) def search_all_patterns(self, text, splitter=u' ', min_weight=0.0): for pattern, start_idx in super( RecordTrie, self).search_all_patterns(text, splitter): weight = self[pattern][0][0] if weight < min_weight: continue yield pattern, start_idx, weight def search_longest_patterns(self, text, splitter=u' ', min_weight=0.0): all_patterns = self.search_all_patterns(text, splitter, min_weight) check_field = [0] * len(text) for pattern, start_idx, weight in sorted( all_patterns, key=lambda x: len(x[0]), reverse=True): target_field = check_field[start_idx:start_idx + len(pattern)] check_sum = sum(target_field) if check_sum != len(target_field): for i in range(len(pattern)): check_field[start_idx + i] = 1 yield pattern, start_idx, weight
Modify the condition for selection of longest patterns
Modify the condition for selection of longest patterns
Python
mit
nkmrtty/trie-search
from marisa_trie import RecordTrie from .trie import TrieSearch class RecordTrieSearch(RecordTrie, TrieSearch): def __init__(self, record_format, records=None, filepath=None): super(RecordTrieSearch, self).__init__(record_format, records) if filepath: self.load(filepath) def search_all_patterns(self, text, splitter=u' ', min_weight=0.0): for pattern, start_idx in super( RecordTrie, self).search_all_patterns(text, splitter): weight = self[pattern][0][0] if weight < min_weight: continue yield pattern, start_idx, weight def search_longest_patterns(self, text, splitter=u' ', min_weight=0.0): all_patterns = self.search_all_patterns(text, splitter, min_weight) check_field = [0] * len(text) for pattern, start_idx, weight in sorted( all_patterns, key=lambda x: len(x[0].split(splitter)), reverse=True): target_field = check_field[start_idx:start_idx + len(pattern)] check_sum = sum(target_field) if check_sum != len(target_field): for i in range(len(pattern)): check_field[start_idx + i] = 1 yield pattern, start_idx, weight Modify the condition for selection of longest patterns
from marisa_trie import RecordTrie from .trie import TrieSearch class RecordTrieSearch(RecordTrie, TrieSearch): def __init__(self, record_format, records=None, filepath=None): super(RecordTrieSearch, self).__init__(record_format, records) if filepath: self.load(filepath) def search_all_patterns(self, text, splitter=u' ', min_weight=0.0): for pattern, start_idx in super( RecordTrie, self).search_all_patterns(text, splitter): weight = self[pattern][0][0] if weight < min_weight: continue yield pattern, start_idx, weight def search_longest_patterns(self, text, splitter=u' ', min_weight=0.0): all_patterns = self.search_all_patterns(text, splitter, min_weight) check_field = [0] * len(text) for pattern, start_idx, weight in sorted( all_patterns, key=lambda x: len(x[0]), reverse=True): target_field = check_field[start_idx:start_idx + len(pattern)] check_sum = sum(target_field) if check_sum != len(target_field): for i in range(len(pattern)): check_field[start_idx + i] = 1 yield pattern, start_idx, weight
<commit_before>from marisa_trie import RecordTrie from .trie import TrieSearch class RecordTrieSearch(RecordTrie, TrieSearch): def __init__(self, record_format, records=None, filepath=None): super(RecordTrieSearch, self).__init__(record_format, records) if filepath: self.load(filepath) def search_all_patterns(self, text, splitter=u' ', min_weight=0.0): for pattern, start_idx in super( RecordTrie, self).search_all_patterns(text, splitter): weight = self[pattern][0][0] if weight < min_weight: continue yield pattern, start_idx, weight def search_longest_patterns(self, text, splitter=u' ', min_weight=0.0): all_patterns = self.search_all_patterns(text, splitter, min_weight) check_field = [0] * len(text) for pattern, start_idx, weight in sorted( all_patterns, key=lambda x: len(x[0].split(splitter)), reverse=True): target_field = check_field[start_idx:start_idx + len(pattern)] check_sum = sum(target_field) if check_sum != len(target_field): for i in range(len(pattern)): check_field[start_idx + i] = 1 yield pattern, start_idx, weight <commit_msg>Modify the condition for selection of longest patterns<commit_after>
from marisa_trie import RecordTrie from .trie import TrieSearch class RecordTrieSearch(RecordTrie, TrieSearch): def __init__(self, record_format, records=None, filepath=None): super(RecordTrieSearch, self).__init__(record_format, records) if filepath: self.load(filepath) def search_all_patterns(self, text, splitter=u' ', min_weight=0.0): for pattern, start_idx in super( RecordTrie, self).search_all_patterns(text, splitter): weight = self[pattern][0][0] if weight < min_weight: continue yield pattern, start_idx, weight def search_longest_patterns(self, text, splitter=u' ', min_weight=0.0): all_patterns = self.search_all_patterns(text, splitter, min_weight) check_field = [0] * len(text) for pattern, start_idx, weight in sorted( all_patterns, key=lambda x: len(x[0]), reverse=True): target_field = check_field[start_idx:start_idx + len(pattern)] check_sum = sum(target_field) if check_sum != len(target_field): for i in range(len(pattern)): check_field[start_idx + i] = 1 yield pattern, start_idx, weight
from marisa_trie import RecordTrie from .trie import TrieSearch class RecordTrieSearch(RecordTrie, TrieSearch): def __init__(self, record_format, records=None, filepath=None): super(RecordTrieSearch, self).__init__(record_format, records) if filepath: self.load(filepath) def search_all_patterns(self, text, splitter=u' ', min_weight=0.0): for pattern, start_idx in super( RecordTrie, self).search_all_patterns(text, splitter): weight = self[pattern][0][0] if weight < min_weight: continue yield pattern, start_idx, weight def search_longest_patterns(self, text, splitter=u' ', min_weight=0.0): all_patterns = self.search_all_patterns(text, splitter, min_weight) check_field = [0] * len(text) for pattern, start_idx, weight in sorted( all_patterns, key=lambda x: len(x[0].split(splitter)), reverse=True): target_field = check_field[start_idx:start_idx + len(pattern)] check_sum = sum(target_field) if check_sum != len(target_field): for i in range(len(pattern)): check_field[start_idx + i] = 1 yield pattern, start_idx, weight Modify the condition for selection of longest patternsfrom marisa_trie import RecordTrie from .trie import TrieSearch class RecordTrieSearch(RecordTrie, TrieSearch): def __init__(self, record_format, records=None, filepath=None): super(RecordTrieSearch, self).__init__(record_format, records) if filepath: self.load(filepath) def search_all_patterns(self, text, splitter=u' ', min_weight=0.0): for pattern, start_idx in super( RecordTrie, self).search_all_patterns(text, splitter): weight = self[pattern][0][0] if weight < min_weight: continue yield pattern, start_idx, weight def search_longest_patterns(self, text, splitter=u' ', min_weight=0.0): all_patterns = self.search_all_patterns(text, splitter, min_weight) check_field = [0] * len(text) for pattern, start_idx, weight in sorted( all_patterns, key=lambda x: len(x[0]), reverse=True): target_field = check_field[start_idx:start_idx + len(pattern)] check_sum = sum(target_field) if check_sum != len(target_field): for i in range(len(pattern)): check_field[start_idx + i] = 1 yield pattern, start_idx, weight
<commit_before>from marisa_trie import RecordTrie from .trie import TrieSearch class RecordTrieSearch(RecordTrie, TrieSearch): def __init__(self, record_format, records=None, filepath=None): super(RecordTrieSearch, self).__init__(record_format, records) if filepath: self.load(filepath) def search_all_patterns(self, text, splitter=u' ', min_weight=0.0): for pattern, start_idx in super( RecordTrie, self).search_all_patterns(text, splitter): weight = self[pattern][0][0] if weight < min_weight: continue yield pattern, start_idx, weight def search_longest_patterns(self, text, splitter=u' ', min_weight=0.0): all_patterns = self.search_all_patterns(text, splitter, min_weight) check_field = [0] * len(text) for pattern, start_idx, weight in sorted( all_patterns, key=lambda x: len(x[0].split(splitter)), reverse=True): target_field = check_field[start_idx:start_idx + len(pattern)] check_sum = sum(target_field) if check_sum != len(target_field): for i in range(len(pattern)): check_field[start_idx + i] = 1 yield pattern, start_idx, weight <commit_msg>Modify the condition for selection of longest patterns<commit_after>from marisa_trie import RecordTrie from .trie import TrieSearch class RecordTrieSearch(RecordTrie, TrieSearch): def __init__(self, record_format, records=None, filepath=None): super(RecordTrieSearch, self).__init__(record_format, records) if filepath: self.load(filepath) def search_all_patterns(self, text, splitter=u' ', min_weight=0.0): for pattern, start_idx in super( RecordTrie, self).search_all_patterns(text, splitter): weight = self[pattern][0][0] if weight < min_weight: continue yield pattern, start_idx, weight def search_longest_patterns(self, text, splitter=u' ', min_weight=0.0): all_patterns = self.search_all_patterns(text, splitter, min_weight) check_field = [0] * len(text) for pattern, start_idx, weight in sorted( all_patterns, key=lambda x: len(x[0]), reverse=True): target_field = check_field[start_idx:start_idx + len(pattern)] check_sum = sum(target_field) if check_sum != len(target_field): for i in range(len(pattern)): check_field[start_idx + i] = 1 yield pattern, start_idx, weight
caf1cce23853955bf0a04fc4e255f23b730dca97
tests/test__utils.py
tests/test__utils.py
# -*- coding: utf-8 -*- import pytest import numpy as np import dask.array as da import dask.array.utils as dau import dask_ndfourier._utils @pytest.mark.parametrize( "a, s, n, axis", [ (da.ones((3, 4), chunks=(3, 4)), da.ones((2,), chunks=(2,)), -1, -1), ] ) def test_norm_args(a, s, n, axis): s2, n2, axis2 = dask_ndfourier._utils._norm_args(a, s, n=n, axis=axis) assert isinstance(s2, da.Array)
# -*- coding: utf-8 -*- import pytest import numpy as np import dask.array as da import dask.array.utils as dau import dask_ndfourier._utils @pytest.mark.parametrize( "a, s, n, axis", [ (da.ones((3, 4), chunks=(3, 4)), da.ones((2,), chunks=(2,)), -1, -1), ] ) def test_norm_args(a, s, n, axis): a2, s2, n2, axis2 = dask_ndfourier._utils._norm_args(a, s, n=n, axis=axis) assert isinstance(a2, da.Array) assert isinstance(s2, da.Array)
Update the argument normalization test
Update the argument normalization test Needs to make sure it unpacks the right number of return values. Also since we are changing the input array, it is good to add a check to make sure it is still of the expected type.
Python
bsd-3-clause
dask-image/dask-ndfourier
# -*- coding: utf-8 -*- import pytest import numpy as np import dask.array as da import dask.array.utils as dau import dask_ndfourier._utils @pytest.mark.parametrize( "a, s, n, axis", [ (da.ones((3, 4), chunks=(3, 4)), da.ones((2,), chunks=(2,)), -1, -1), ] ) def test_norm_args(a, s, n, axis): s2, n2, axis2 = dask_ndfourier._utils._norm_args(a, s, n=n, axis=axis) assert isinstance(s2, da.Array) Update the argument normalization test Needs to make sure it unpacks the right number of return values. Also since we are changing the input array, it is good to add a check to make sure it is still of the expected type.
# -*- coding: utf-8 -*- import pytest import numpy as np import dask.array as da import dask.array.utils as dau import dask_ndfourier._utils @pytest.mark.parametrize( "a, s, n, axis", [ (da.ones((3, 4), chunks=(3, 4)), da.ones((2,), chunks=(2,)), -1, -1), ] ) def test_norm_args(a, s, n, axis): a2, s2, n2, axis2 = dask_ndfourier._utils._norm_args(a, s, n=n, axis=axis) assert isinstance(a2, da.Array) assert isinstance(s2, da.Array)
<commit_before># -*- coding: utf-8 -*- import pytest import numpy as np import dask.array as da import dask.array.utils as dau import dask_ndfourier._utils @pytest.mark.parametrize( "a, s, n, axis", [ (da.ones((3, 4), chunks=(3, 4)), da.ones((2,), chunks=(2,)), -1, -1), ] ) def test_norm_args(a, s, n, axis): s2, n2, axis2 = dask_ndfourier._utils._norm_args(a, s, n=n, axis=axis) assert isinstance(s2, da.Array) <commit_msg>Update the argument normalization test Needs to make sure it unpacks the right number of return values. Also since we are changing the input array, it is good to add a check to make sure it is still of the expected type.<commit_after>
# -*- coding: utf-8 -*- import pytest import numpy as np import dask.array as da import dask.array.utils as dau import dask_ndfourier._utils @pytest.mark.parametrize( "a, s, n, axis", [ (da.ones((3, 4), chunks=(3, 4)), da.ones((2,), chunks=(2,)), -1, -1), ] ) def test_norm_args(a, s, n, axis): a2, s2, n2, axis2 = dask_ndfourier._utils._norm_args(a, s, n=n, axis=axis) assert isinstance(a2, da.Array) assert isinstance(s2, da.Array)
# -*- coding: utf-8 -*- import pytest import numpy as np import dask.array as da import dask.array.utils as dau import dask_ndfourier._utils @pytest.mark.parametrize( "a, s, n, axis", [ (da.ones((3, 4), chunks=(3, 4)), da.ones((2,), chunks=(2,)), -1, -1), ] ) def test_norm_args(a, s, n, axis): s2, n2, axis2 = dask_ndfourier._utils._norm_args(a, s, n=n, axis=axis) assert isinstance(s2, da.Array) Update the argument normalization test Needs to make sure it unpacks the right number of return values. Also since we are changing the input array, it is good to add a check to make sure it is still of the expected type.# -*- coding: utf-8 -*- import pytest import numpy as np import dask.array as da import dask.array.utils as dau import dask_ndfourier._utils @pytest.mark.parametrize( "a, s, n, axis", [ (da.ones((3, 4), chunks=(3, 4)), da.ones((2,), chunks=(2,)), -1, -1), ] ) def test_norm_args(a, s, n, axis): a2, s2, n2, axis2 = dask_ndfourier._utils._norm_args(a, s, n=n, axis=axis) assert isinstance(a2, da.Array) assert isinstance(s2, da.Array)
<commit_before># -*- coding: utf-8 -*- import pytest import numpy as np import dask.array as da import dask.array.utils as dau import dask_ndfourier._utils @pytest.mark.parametrize( "a, s, n, axis", [ (da.ones((3, 4), chunks=(3, 4)), da.ones((2,), chunks=(2,)), -1, -1), ] ) def test_norm_args(a, s, n, axis): s2, n2, axis2 = dask_ndfourier._utils._norm_args(a, s, n=n, axis=axis) assert isinstance(s2, da.Array) <commit_msg>Update the argument normalization test Needs to make sure it unpacks the right number of return values. Also since we are changing the input array, it is good to add a check to make sure it is still of the expected type.<commit_after># -*- coding: utf-8 -*- import pytest import numpy as np import dask.array as da import dask.array.utils as dau import dask_ndfourier._utils @pytest.mark.parametrize( "a, s, n, axis", [ (da.ones((3, 4), chunks=(3, 4)), da.ones((2,), chunks=(2,)), -1, -1), ] ) def test_norm_args(a, s, n, axis): a2, s2, n2, axis2 = dask_ndfourier._utils._norm_args(a, s, n=n, axis=axis) assert isinstance(a2, da.Array) assert isinstance(s2, da.Array)
23fbdabb97689a355abaac7310d3b1e887f921b8
tests/test_logger.py
tests/test_logger.py
"""This module is about testing the logger.""" import sys from unittest import TestCase LOGGER = sys.modules["Rainmeter.logger"] class TestFunctions(TestCase): """Test class wrapper using unittest.""" # pylint: disable=W0703; This is acceptable since we are testing it not failing def test_info(self): """Info should not through exceptions due to settings.""" try: LOGGER.info("info test") except Exception as error: self.fail("logger.info() raised exception '" + error + "'") def test_error(self): """Error should not through exception due to settings.""" try: LOGGER.error("error test") except Exception as error: self.fail("logger.error() raised exception '" + error + "'")
"""This module is about testing the logger.""" import sys from unittest import TestCase LOGGER = sys.modules["Rainmeter.logger"] class TestFunctions(TestCase): """Test class wrapper using unittest.""" # pylint: disable=W0703; This is acceptable since we are testing it not failing def test_info(self): """Info should not through exceptions due to settings.""" try: LOGGER.info("info test") except Exception as error: self.fail("logger.info() raised exception '" + str(error) + "'") def test_error(self): """Error should not through exception due to settings.""" try: LOGGER.error("error test") except Exception as error: self.fail("logger.error() raised exception '" + str(error) + "'")
Convert exceptions in a type-safe manner to string before string cats
Convert exceptions in a type-safe manner to string before string cats
Python
mit
thatsIch/sublime-rainmeter
"""This module is about testing the logger.""" import sys from unittest import TestCase LOGGER = sys.modules["Rainmeter.logger"] class TestFunctions(TestCase): """Test class wrapper using unittest.""" # pylint: disable=W0703; This is acceptable since we are testing it not failing def test_info(self): """Info should not through exceptions due to settings.""" try: LOGGER.info("info test") except Exception as error: self.fail("logger.info() raised exception '" + error + "'") def test_error(self): """Error should not through exception due to settings.""" try: LOGGER.error("error test") except Exception as error: self.fail("logger.error() raised exception '" + error + "'") Convert exceptions in a type-safe manner to string before string cats
"""This module is about testing the logger.""" import sys from unittest import TestCase LOGGER = sys.modules["Rainmeter.logger"] class TestFunctions(TestCase): """Test class wrapper using unittest.""" # pylint: disable=W0703; This is acceptable since we are testing it not failing def test_info(self): """Info should not through exceptions due to settings.""" try: LOGGER.info("info test") except Exception as error: self.fail("logger.info() raised exception '" + str(error) + "'") def test_error(self): """Error should not through exception due to settings.""" try: LOGGER.error("error test") except Exception as error: self.fail("logger.error() raised exception '" + str(error) + "'")
<commit_before>"""This module is about testing the logger.""" import sys from unittest import TestCase LOGGER = sys.modules["Rainmeter.logger"] class TestFunctions(TestCase): """Test class wrapper using unittest.""" # pylint: disable=W0703; This is acceptable since we are testing it not failing def test_info(self): """Info should not through exceptions due to settings.""" try: LOGGER.info("info test") except Exception as error: self.fail("logger.info() raised exception '" + error + "'") def test_error(self): """Error should not through exception due to settings.""" try: LOGGER.error("error test") except Exception as error: self.fail("logger.error() raised exception '" + error + "'") <commit_msg>Convert exceptions in a type-safe manner to string before string cats<commit_after>
"""This module is about testing the logger.""" import sys from unittest import TestCase LOGGER = sys.modules["Rainmeter.logger"] class TestFunctions(TestCase): """Test class wrapper using unittest.""" # pylint: disable=W0703; This is acceptable since we are testing it not failing def test_info(self): """Info should not through exceptions due to settings.""" try: LOGGER.info("info test") except Exception as error: self.fail("logger.info() raised exception '" + str(error) + "'") def test_error(self): """Error should not through exception due to settings.""" try: LOGGER.error("error test") except Exception as error: self.fail("logger.error() raised exception '" + str(error) + "'")
"""This module is about testing the logger.""" import sys from unittest import TestCase LOGGER = sys.modules["Rainmeter.logger"] class TestFunctions(TestCase): """Test class wrapper using unittest.""" # pylint: disable=W0703; This is acceptable since we are testing it not failing def test_info(self): """Info should not through exceptions due to settings.""" try: LOGGER.info("info test") except Exception as error: self.fail("logger.info() raised exception '" + error + "'") def test_error(self): """Error should not through exception due to settings.""" try: LOGGER.error("error test") except Exception as error: self.fail("logger.error() raised exception '" + error + "'") Convert exceptions in a type-safe manner to string before string cats"""This module is about testing the logger.""" import sys from unittest import TestCase LOGGER = sys.modules["Rainmeter.logger"] class TestFunctions(TestCase): """Test class wrapper using unittest.""" # pylint: disable=W0703; This is acceptable since we are testing it not failing def test_info(self): """Info should not through exceptions due to settings.""" try: LOGGER.info("info test") except Exception as error: self.fail("logger.info() raised exception '" + str(error) + "'") def test_error(self): """Error should not through exception due to settings.""" try: LOGGER.error("error test") except Exception as error: self.fail("logger.error() raised exception '" + str(error) + "'")
<commit_before>"""This module is about testing the logger.""" import sys from unittest import TestCase LOGGER = sys.modules["Rainmeter.logger"] class TestFunctions(TestCase): """Test class wrapper using unittest.""" # pylint: disable=W0703; This is acceptable since we are testing it not failing def test_info(self): """Info should not through exceptions due to settings.""" try: LOGGER.info("info test") except Exception as error: self.fail("logger.info() raised exception '" + error + "'") def test_error(self): """Error should not through exception due to settings.""" try: LOGGER.error("error test") except Exception as error: self.fail("logger.error() raised exception '" + error + "'") <commit_msg>Convert exceptions in a type-safe manner to string before string cats<commit_after>"""This module is about testing the logger.""" import sys from unittest import TestCase LOGGER = sys.modules["Rainmeter.logger"] class TestFunctions(TestCase): """Test class wrapper using unittest.""" # pylint: disable=W0703; This is acceptable since we are testing it not failing def test_info(self): """Info should not through exceptions due to settings.""" try: LOGGER.info("info test") except Exception as error: self.fail("logger.info() raised exception '" + str(error) + "'") def test_error(self): """Error should not through exception due to settings.""" try: LOGGER.error("error test") except Exception as error: self.fail("logger.error() raised exception '" + str(error) + "'")
6446af2cd11bdc5069fdc8ab47a0881089e7cbab
tests/test_normal.py
tests/test_normal.py
""" Just to make sure the plugin doesn't choke on doctests:: >>> print('Yay, doctests!') Yay, doctests! """ import time from functools import partial import pytest def test_fast(benchmark): @benchmark def result(): return time.sleep(0.000001) assert result is None def test_slow(benchmark): assert benchmark(partial(time.sleep, 0.001)) is None def test_slower(benchmark): benchmark(lambda: time.sleep(0.01)) @pytest.mark.benchmark(min_rounds=2, timer=time.time) def test_xfast(benchmark): benchmark(str) def test_fast(benchmark): benchmark(int)
""" Just to make sure the plugin doesn't choke on doctests:: >>> print('Yay, doctests!') Yay, doctests! """ import time from functools import partial import pytest def test_fast(benchmark): @benchmark def result(): return time.sleep(0.000001) assert result is None def test_slow(benchmark): assert benchmark(partial(time.sleep, 0.001)) is None def test_slower(benchmark): benchmark(lambda: time.sleep(0.01)) @pytest.mark.benchmark(min_rounds=2, timer=time.time, max_time=0.01) def test_xfast(benchmark): benchmark(str) def test_fast(benchmark): benchmark(int) @pytest.fixture(params=range(5)) def foo(request): return request.param @pytest.mark.benchmark(max_time=0.001, min_rounds=5) def test_xfast_parametrized(benchmark, foo): benchmark(int)
Add a parametrized sample test. Make xfast faster.
Add a parametrized sample test. Make xfast faster.
Python
bsd-2-clause
SectorLabs/pytest-benchmark,thedrow/pytest-benchmark,aldanor/pytest-benchmark,ionelmc/pytest-benchmark
""" Just to make sure the plugin doesn't choke on doctests:: >>> print('Yay, doctests!') Yay, doctests! """ import time from functools import partial import pytest def test_fast(benchmark): @benchmark def result(): return time.sleep(0.000001) assert result is None def test_slow(benchmark): assert benchmark(partial(time.sleep, 0.001)) is None def test_slower(benchmark): benchmark(lambda: time.sleep(0.01)) @pytest.mark.benchmark(min_rounds=2, timer=time.time) def test_xfast(benchmark): benchmark(str) def test_fast(benchmark): benchmark(int) Add a parametrized sample test. Make xfast faster.
""" Just to make sure the plugin doesn't choke on doctests:: >>> print('Yay, doctests!') Yay, doctests! """ import time from functools import partial import pytest def test_fast(benchmark): @benchmark def result(): return time.sleep(0.000001) assert result is None def test_slow(benchmark): assert benchmark(partial(time.sleep, 0.001)) is None def test_slower(benchmark): benchmark(lambda: time.sleep(0.01)) @pytest.mark.benchmark(min_rounds=2, timer=time.time, max_time=0.01) def test_xfast(benchmark): benchmark(str) def test_fast(benchmark): benchmark(int) @pytest.fixture(params=range(5)) def foo(request): return request.param @pytest.mark.benchmark(max_time=0.001, min_rounds=5) def test_xfast_parametrized(benchmark, foo): benchmark(int)
<commit_before>""" Just to make sure the plugin doesn't choke on doctests:: >>> print('Yay, doctests!') Yay, doctests! """ import time from functools import partial import pytest def test_fast(benchmark): @benchmark def result(): return time.sleep(0.000001) assert result is None def test_slow(benchmark): assert benchmark(partial(time.sleep, 0.001)) is None def test_slower(benchmark): benchmark(lambda: time.sleep(0.01)) @pytest.mark.benchmark(min_rounds=2, timer=time.time) def test_xfast(benchmark): benchmark(str) def test_fast(benchmark): benchmark(int) <commit_msg>Add a parametrized sample test. Make xfast faster.<commit_after>
""" Just to make sure the plugin doesn't choke on doctests:: >>> print('Yay, doctests!') Yay, doctests! """ import time from functools import partial import pytest def test_fast(benchmark): @benchmark def result(): return time.sleep(0.000001) assert result is None def test_slow(benchmark): assert benchmark(partial(time.sleep, 0.001)) is None def test_slower(benchmark): benchmark(lambda: time.sleep(0.01)) @pytest.mark.benchmark(min_rounds=2, timer=time.time, max_time=0.01) def test_xfast(benchmark): benchmark(str) def test_fast(benchmark): benchmark(int) @pytest.fixture(params=range(5)) def foo(request): return request.param @pytest.mark.benchmark(max_time=0.001, min_rounds=5) def test_xfast_parametrized(benchmark, foo): benchmark(int)
""" Just to make sure the plugin doesn't choke on doctests:: >>> print('Yay, doctests!') Yay, doctests! """ import time from functools import partial import pytest def test_fast(benchmark): @benchmark def result(): return time.sleep(0.000001) assert result is None def test_slow(benchmark): assert benchmark(partial(time.sleep, 0.001)) is None def test_slower(benchmark): benchmark(lambda: time.sleep(0.01)) @pytest.mark.benchmark(min_rounds=2, timer=time.time) def test_xfast(benchmark): benchmark(str) def test_fast(benchmark): benchmark(int) Add a parametrized sample test. Make xfast faster.""" Just to make sure the plugin doesn't choke on doctests:: >>> print('Yay, doctests!') Yay, doctests! """ import time from functools import partial import pytest def test_fast(benchmark): @benchmark def result(): return time.sleep(0.000001) assert result is None def test_slow(benchmark): assert benchmark(partial(time.sleep, 0.001)) is None def test_slower(benchmark): benchmark(lambda: time.sleep(0.01)) @pytest.mark.benchmark(min_rounds=2, timer=time.time, max_time=0.01) def test_xfast(benchmark): benchmark(str) def test_fast(benchmark): benchmark(int) @pytest.fixture(params=range(5)) def foo(request): return request.param @pytest.mark.benchmark(max_time=0.001, min_rounds=5) def test_xfast_parametrized(benchmark, foo): benchmark(int)
<commit_before>""" Just to make sure the plugin doesn't choke on doctests:: >>> print('Yay, doctests!') Yay, doctests! """ import time from functools import partial import pytest def test_fast(benchmark): @benchmark def result(): return time.sleep(0.000001) assert result is None def test_slow(benchmark): assert benchmark(partial(time.sleep, 0.001)) is None def test_slower(benchmark): benchmark(lambda: time.sleep(0.01)) @pytest.mark.benchmark(min_rounds=2, timer=time.time) def test_xfast(benchmark): benchmark(str) def test_fast(benchmark): benchmark(int) <commit_msg>Add a parametrized sample test. Make xfast faster.<commit_after>""" Just to make sure the plugin doesn't choke on doctests:: >>> print('Yay, doctests!') Yay, doctests! """ import time from functools import partial import pytest def test_fast(benchmark): @benchmark def result(): return time.sleep(0.000001) assert result is None def test_slow(benchmark): assert benchmark(partial(time.sleep, 0.001)) is None def test_slower(benchmark): benchmark(lambda: time.sleep(0.01)) @pytest.mark.benchmark(min_rounds=2, timer=time.time, max_time=0.01) def test_xfast(benchmark): benchmark(str) def test_fast(benchmark): benchmark(int) @pytest.fixture(params=range(5)) def foo(request): return request.param @pytest.mark.benchmark(max_time=0.001, min_rounds=5) def test_xfast_parametrized(benchmark, foo): benchmark(int)
6dd4eb21f6598bbaad329645a3965ad9d47c41db
fortuitus/frunner/tasks.py
fortuitus/frunner/tasks.py
from celery import task @task() def add(x, y): """ Test task. """ return x + y
from celery import task @task() def add(x, y): """ Test task. """ return x + y @task() def run_tests(test_id): """ A task that actually runs the API testing. First it copies the test data to the run history tables, then runs the tests. """ # TODO pass
Add test runner task stub
Add test runner task stub
Python
mit
elegion/djangodash2012,elegion/djangodash2012
from celery import task @task() def add(x, y): """ Test task. """ return x + y Add test runner task stub
from celery import task @task() def add(x, y): """ Test task. """ return x + y @task() def run_tests(test_id): """ A task that actually runs the API testing. First it copies the test data to the run history tables, then runs the tests. """ # TODO pass
<commit_before>from celery import task @task() def add(x, y): """ Test task. """ return x + y <commit_msg>Add test runner task stub<commit_after>
from celery import task @task() def add(x, y): """ Test task. """ return x + y @task() def run_tests(test_id): """ A task that actually runs the API testing. First it copies the test data to the run history tables, then runs the tests. """ # TODO pass
from celery import task @task() def add(x, y): """ Test task. """ return x + y Add test runner task stubfrom celery import task @task() def add(x, y): """ Test task. """ return x + y @task() def run_tests(test_id): """ A task that actually runs the API testing. First it copies the test data to the run history tables, then runs the tests. """ # TODO pass
<commit_before>from celery import task @task() def add(x, y): """ Test task. """ return x + y <commit_msg>Add test runner task stub<commit_after>from celery import task @task() def add(x, y): """ Test task. """ return x + y @task() def run_tests(test_id): """ A task that actually runs the API testing. First it copies the test data to the run history tables, then runs the tests. """ # TODO pass
0a517d99330c4691e076bf1023901a85a63c75a6
tmt/visi/__init__.py
tmt/visi/__init__.py
from os.path import join, dirname, realpath from tmt.util import load_config from visi.util import check_visi_config __version__ = '0.1.0' logo = ''' _ _ __ _(_)__(_) visi (%(version)s) \ V / (_-< | Convert Visitron's .stk files to .png images \_/|_/__/_| https://github.com/HackerMD/TissueMAPSToolbox ''' # Create configuration dictionary that defines default parameters config_filename = join(dirname(realpath(__file__)), 'visi.config') config = load_config(config_filename) check_visi_config(config)
from os.path import join, dirname, realpath from tmt.util import load_config from tmt.visi.util import check_visi_config __version__ = '0.1.0' logo = ''' _ _ __ _(_)__(_) visi (%(version)s) \ V / (_-< | Convert Visitron's .stk files to .png images \_/|_/__/_| https://github.com/HackerMD/TissueMAPSToolbox ''' # Create configuration dictionary that defines default parameters config_filename = join(dirname(realpath(__file__)), 'visi.config') config = load_config(config_filename) check_visi_config(config)
Fix import issue in visi
Fix import issue in visi
Python
agpl-3.0
TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary
from os.path import join, dirname, realpath from tmt.util import load_config from visi.util import check_visi_config __version__ = '0.1.0' logo = ''' _ _ __ _(_)__(_) visi (%(version)s) \ V / (_-< | Convert Visitron's .stk files to .png images \_/|_/__/_| https://github.com/HackerMD/TissueMAPSToolbox ''' # Create configuration dictionary that defines default parameters config_filename = join(dirname(realpath(__file__)), 'visi.config') config = load_config(config_filename) check_visi_config(config) Fix import issue in visi
from os.path import join, dirname, realpath from tmt.util import load_config from tmt.visi.util import check_visi_config __version__ = '0.1.0' logo = ''' _ _ __ _(_)__(_) visi (%(version)s) \ V / (_-< | Convert Visitron's .stk files to .png images \_/|_/__/_| https://github.com/HackerMD/TissueMAPSToolbox ''' # Create configuration dictionary that defines default parameters config_filename = join(dirname(realpath(__file__)), 'visi.config') config = load_config(config_filename) check_visi_config(config)
<commit_before>from os.path import join, dirname, realpath from tmt.util import load_config from visi.util import check_visi_config __version__ = '0.1.0' logo = ''' _ _ __ _(_)__(_) visi (%(version)s) \ V / (_-< | Convert Visitron's .stk files to .png images \_/|_/__/_| https://github.com/HackerMD/TissueMAPSToolbox ''' # Create configuration dictionary that defines default parameters config_filename = join(dirname(realpath(__file__)), 'visi.config') config = load_config(config_filename) check_visi_config(config) <commit_msg>Fix import issue in visi<commit_after>
from os.path import join, dirname, realpath from tmt.util import load_config from tmt.visi.util import check_visi_config __version__ = '0.1.0' logo = ''' _ _ __ _(_)__(_) visi (%(version)s) \ V / (_-< | Convert Visitron's .stk files to .png images \_/|_/__/_| https://github.com/HackerMD/TissueMAPSToolbox ''' # Create configuration dictionary that defines default parameters config_filename = join(dirname(realpath(__file__)), 'visi.config') config = load_config(config_filename) check_visi_config(config)
from os.path import join, dirname, realpath from tmt.util import load_config from visi.util import check_visi_config __version__ = '0.1.0' logo = ''' _ _ __ _(_)__(_) visi (%(version)s) \ V / (_-< | Convert Visitron's .stk files to .png images \_/|_/__/_| https://github.com/HackerMD/TissueMAPSToolbox ''' # Create configuration dictionary that defines default parameters config_filename = join(dirname(realpath(__file__)), 'visi.config') config = load_config(config_filename) check_visi_config(config) Fix import issue in visifrom os.path import join, dirname, realpath from tmt.util import load_config from tmt.visi.util import check_visi_config __version__ = '0.1.0' logo = ''' _ _ __ _(_)__(_) visi (%(version)s) \ V / (_-< | Convert Visitron's .stk files to .png images \_/|_/__/_| https://github.com/HackerMD/TissueMAPSToolbox ''' # Create configuration dictionary that defines default parameters config_filename = join(dirname(realpath(__file__)), 'visi.config') config = load_config(config_filename) check_visi_config(config)
<commit_before>from os.path import join, dirname, realpath from tmt.util import load_config from visi.util import check_visi_config __version__ = '0.1.0' logo = ''' _ _ __ _(_)__(_) visi (%(version)s) \ V / (_-< | Convert Visitron's .stk files to .png images \_/|_/__/_| https://github.com/HackerMD/TissueMAPSToolbox ''' # Create configuration dictionary that defines default parameters config_filename = join(dirname(realpath(__file__)), 'visi.config') config = load_config(config_filename) check_visi_config(config) <commit_msg>Fix import issue in visi<commit_after>from os.path import join, dirname, realpath from tmt.util import load_config from tmt.visi.util import check_visi_config __version__ = '0.1.0' logo = ''' _ _ __ _(_)__(_) visi (%(version)s) \ V / (_-< | Convert Visitron's .stk files to .png images \_/|_/__/_| https://github.com/HackerMD/TissueMAPSToolbox ''' # Create configuration dictionary that defines default parameters config_filename = join(dirname(realpath(__file__)), 'visi.config') config = load_config(config_filename) check_visi_config(config)
512ca99144da537da61e7437d17782e5a95addb9
S3utility/s3_sqs_message.py
S3utility/s3_sqs_message.py
from boto.sqs.message import Message import json from s3_notification_info import S3NotificationInfo class S3SQSMessage(Message): def __init__(self, queue=None, body='', xml_attrs=None): Message.__init__(self, queue, body) self.payload = None self.notification_type = 'S3Info' def event_name(self): return self.payload['Records'][0]['eventName'] def event_time(self): return self.payload['Records'][0]['eventTime'] def bucket_name(self): return self.payload['Records'][0]['s3']['bucket']['name'] def file_name(self): return self.payload['Records'][0]['s3']['object']['key'] def file_etag(self): return self.payload['Records'][0]['s3']['object']['eTag'] def file_size(self): return self.payload['Records'][0]['s3']['object']['size'] def set_body(self, body): """ Override set_body to construct json payload Note Boto JSONMessage seemed to have encoding issues with S3 notification messages """ if body is not None and len(body) > 0: self.payload = json.loads(body) if body and 'Records' in self.payload.keys(): self.notification_type = 'S3Event' super(Message, self).set_body(body)
from boto.sqs.message import Message import json from s3_notification_info import S3NotificationInfo class S3SQSMessage(Message): def __init__(self, queue=None, body='', xml_attrs=None): Message.__init__(self, queue, body) self.payload = None self.notification_type = 'S3Info' def event_name(self): return self.payload['Records'][0]['eventName'] def event_time(self): return self.payload['Records'][0]['eventTime'] def bucket_name(self): return self.payload['Records'][0]['s3']['bucket']['name'] def file_name(self): return self.payload['Records'][0]['s3']['object']['key'] def file_etag(self): if 'eTag' in self.payload['Records'][0]['s3']['object']: return self.payload['Records'][0]['s3']['object']['eTag'] else: return None def file_size(self): return self.payload['Records'][0]['s3']['object']['size'] def set_body(self, body): """ Override set_body to construct json payload Note Boto JSONMessage seemed to have encoding issues with S3 notification messages """ if body is not None and len(body) > 0: self.payload = json.loads(body) if body and 'Records' in self.payload.keys(): self.notification_type = 'S3Event' super(Message, self).set_body(body)
Tweak for when SQS message is missing the eTag from a bucket notification.
Tweak for when SQS message is missing the eTag from a bucket notification.
Python
mit
gnott/elife-bot,gnott/elife-bot,jhroot/elife-bot,jhroot/elife-bot,gnott/elife-bot,jhroot/elife-bot
from boto.sqs.message import Message import json from s3_notification_info import S3NotificationInfo class S3SQSMessage(Message): def __init__(self, queue=None, body='', xml_attrs=None): Message.__init__(self, queue, body) self.payload = None self.notification_type = 'S3Info' def event_name(self): return self.payload['Records'][0]['eventName'] def event_time(self): return self.payload['Records'][0]['eventTime'] def bucket_name(self): return self.payload['Records'][0]['s3']['bucket']['name'] def file_name(self): return self.payload['Records'][0]['s3']['object']['key'] def file_etag(self): return self.payload['Records'][0]['s3']['object']['eTag'] def file_size(self): return self.payload['Records'][0]['s3']['object']['size'] def set_body(self, body): """ Override set_body to construct json payload Note Boto JSONMessage seemed to have encoding issues with S3 notification messages """ if body is not None and len(body) > 0: self.payload = json.loads(body) if body and 'Records' in self.payload.keys(): self.notification_type = 'S3Event' super(Message, self).set_body(body) Tweak for when SQS message is missing the eTag from a bucket notification.
from boto.sqs.message import Message import json from s3_notification_info import S3NotificationInfo class S3SQSMessage(Message): def __init__(self, queue=None, body='', xml_attrs=None): Message.__init__(self, queue, body) self.payload = None self.notification_type = 'S3Info' def event_name(self): return self.payload['Records'][0]['eventName'] def event_time(self): return self.payload['Records'][0]['eventTime'] def bucket_name(self): return self.payload['Records'][0]['s3']['bucket']['name'] def file_name(self): return self.payload['Records'][0]['s3']['object']['key'] def file_etag(self): if 'eTag' in self.payload['Records'][0]['s3']['object']: return self.payload['Records'][0]['s3']['object']['eTag'] else: return None def file_size(self): return self.payload['Records'][0]['s3']['object']['size'] def set_body(self, body): """ Override set_body to construct json payload Note Boto JSONMessage seemed to have encoding issues with S3 notification messages """ if body is not None and len(body) > 0: self.payload = json.loads(body) if body and 'Records' in self.payload.keys(): self.notification_type = 'S3Event' super(Message, self).set_body(body)
<commit_before>from boto.sqs.message import Message import json from s3_notification_info import S3NotificationInfo class S3SQSMessage(Message): def __init__(self, queue=None, body='', xml_attrs=None): Message.__init__(self, queue, body) self.payload = None self.notification_type = 'S3Info' def event_name(self): return self.payload['Records'][0]['eventName'] def event_time(self): return self.payload['Records'][0]['eventTime'] def bucket_name(self): return self.payload['Records'][0]['s3']['bucket']['name'] def file_name(self): return self.payload['Records'][0]['s3']['object']['key'] def file_etag(self): return self.payload['Records'][0]['s3']['object']['eTag'] def file_size(self): return self.payload['Records'][0]['s3']['object']['size'] def set_body(self, body): """ Override set_body to construct json payload Note Boto JSONMessage seemed to have encoding issues with S3 notification messages """ if body is not None and len(body) > 0: self.payload = json.loads(body) if body and 'Records' in self.payload.keys(): self.notification_type = 'S3Event' super(Message, self).set_body(body) <commit_msg>Tweak for when SQS message is missing the eTag from a bucket notification.<commit_after>
from boto.sqs.message import Message import json from s3_notification_info import S3NotificationInfo class S3SQSMessage(Message): def __init__(self, queue=None, body='', xml_attrs=None): Message.__init__(self, queue, body) self.payload = None self.notification_type = 'S3Info' def event_name(self): return self.payload['Records'][0]['eventName'] def event_time(self): return self.payload['Records'][0]['eventTime'] def bucket_name(self): return self.payload['Records'][0]['s3']['bucket']['name'] def file_name(self): return self.payload['Records'][0]['s3']['object']['key'] def file_etag(self): if 'eTag' in self.payload['Records'][0]['s3']['object']: return self.payload['Records'][0]['s3']['object']['eTag'] else: return None def file_size(self): return self.payload['Records'][0]['s3']['object']['size'] def set_body(self, body): """ Override set_body to construct json payload Note Boto JSONMessage seemed to have encoding issues with S3 notification messages """ if body is not None and len(body) > 0: self.payload = json.loads(body) if body and 'Records' in self.payload.keys(): self.notification_type = 'S3Event' super(Message, self).set_body(body)
from boto.sqs.message import Message import json from s3_notification_info import S3NotificationInfo class S3SQSMessage(Message): def __init__(self, queue=None, body='', xml_attrs=None): Message.__init__(self, queue, body) self.payload = None self.notification_type = 'S3Info' def event_name(self): return self.payload['Records'][0]['eventName'] def event_time(self): return self.payload['Records'][0]['eventTime'] def bucket_name(self): return self.payload['Records'][0]['s3']['bucket']['name'] def file_name(self): return self.payload['Records'][0]['s3']['object']['key'] def file_etag(self): return self.payload['Records'][0]['s3']['object']['eTag'] def file_size(self): return self.payload['Records'][0]['s3']['object']['size'] def set_body(self, body): """ Override set_body to construct json payload Note Boto JSONMessage seemed to have encoding issues with S3 notification messages """ if body is not None and len(body) > 0: self.payload = json.loads(body) if body and 'Records' in self.payload.keys(): self.notification_type = 'S3Event' super(Message, self).set_body(body) Tweak for when SQS message is missing the eTag from a bucket notification.from boto.sqs.message import Message import json from s3_notification_info import S3NotificationInfo class S3SQSMessage(Message): def __init__(self, queue=None, body='', xml_attrs=None): Message.__init__(self, queue, body) self.payload = None self.notification_type = 'S3Info' def event_name(self): return self.payload['Records'][0]['eventName'] def event_time(self): return self.payload['Records'][0]['eventTime'] def bucket_name(self): return self.payload['Records'][0]['s3']['bucket']['name'] def file_name(self): return self.payload['Records'][0]['s3']['object']['key'] def file_etag(self): if 'eTag' in self.payload['Records'][0]['s3']['object']: return self.payload['Records'][0]['s3']['object']['eTag'] else: return None def file_size(self): return self.payload['Records'][0]['s3']['object']['size'] def set_body(self, body): """ Override set_body to construct json payload Note Boto JSONMessage seemed to have encoding issues with S3 notification messages """ if body is not None and len(body) > 0: self.payload = json.loads(body) if body and 'Records' in self.payload.keys(): self.notification_type = 'S3Event' super(Message, self).set_body(body)
<commit_before>from boto.sqs.message import Message import json from s3_notification_info import S3NotificationInfo class S3SQSMessage(Message): def __init__(self, queue=None, body='', xml_attrs=None): Message.__init__(self, queue, body) self.payload = None self.notification_type = 'S3Info' def event_name(self): return self.payload['Records'][0]['eventName'] def event_time(self): return self.payload['Records'][0]['eventTime'] def bucket_name(self): return self.payload['Records'][0]['s3']['bucket']['name'] def file_name(self): return self.payload['Records'][0]['s3']['object']['key'] def file_etag(self): return self.payload['Records'][0]['s3']['object']['eTag'] def file_size(self): return self.payload['Records'][0]['s3']['object']['size'] def set_body(self, body): """ Override set_body to construct json payload Note Boto JSONMessage seemed to have encoding issues with S3 notification messages """ if body is not None and len(body) > 0: self.payload = json.loads(body) if body and 'Records' in self.payload.keys(): self.notification_type = 'S3Event' super(Message, self).set_body(body) <commit_msg>Tweak for when SQS message is missing the eTag from a bucket notification.<commit_after>from boto.sqs.message import Message import json from s3_notification_info import S3NotificationInfo class S3SQSMessage(Message): def __init__(self, queue=None, body='', xml_attrs=None): Message.__init__(self, queue, body) self.payload = None self.notification_type = 'S3Info' def event_name(self): return self.payload['Records'][0]['eventName'] def event_time(self): return self.payload['Records'][0]['eventTime'] def bucket_name(self): return self.payload['Records'][0]['s3']['bucket']['name'] def file_name(self): return self.payload['Records'][0]['s3']['object']['key'] def file_etag(self): if 'eTag' in self.payload['Records'][0]['s3']['object']: return self.payload['Records'][0]['s3']['object']['eTag'] else: return None def file_size(self): return self.payload['Records'][0]['s3']['object']['size'] def set_body(self, body): """ Override set_body to construct json payload Note Boto JSONMessage seemed to have encoding issues with S3 notification messages """ if body is not None and len(body) > 0: self.payload = json.loads(body) if body and 'Records' in self.payload.keys(): self.notification_type = 'S3Event' super(Message, self).set_body(body)
566ae40b7f546e3773933217506f917845c8b468
virtool/subtractions/db.py
virtool/subtractions/db.py
import virtool.utils PROJECTION = [ "_id", "file", "ready", "job" ] async def get_linked_samples(db, subtraction_id): cursor = db.samples.find({"subtraction.id": subtraction_id}, ["name"]) return [virtool.utils.base_processor(d) async for d in cursor]
import virtool.utils PROJECTION = [ "_id", "count", "file", "ready", "job", "nickname", "user" ] async def get_linked_samples(db, subtraction_id): cursor = db.samples.find({"subtraction.id": subtraction_id}, ["name"]) return [virtool.utils.base_processor(d) async for d in cursor]
Return more fields in subtraction find API response
Return more fields in subtraction find API response
Python
mit
igboyes/virtool,virtool/virtool,igboyes/virtool,virtool/virtool
import virtool.utils PROJECTION = [ "_id", "file", "ready", "job" ] async def get_linked_samples(db, subtraction_id): cursor = db.samples.find({"subtraction.id": subtraction_id}, ["name"]) return [virtool.utils.base_processor(d) async for d in cursor] Return more fields in subtraction find API response
import virtool.utils PROJECTION = [ "_id", "count", "file", "ready", "job", "nickname", "user" ] async def get_linked_samples(db, subtraction_id): cursor = db.samples.find({"subtraction.id": subtraction_id}, ["name"]) return [virtool.utils.base_processor(d) async for d in cursor]
<commit_before>import virtool.utils PROJECTION = [ "_id", "file", "ready", "job" ] async def get_linked_samples(db, subtraction_id): cursor = db.samples.find({"subtraction.id": subtraction_id}, ["name"]) return [virtool.utils.base_processor(d) async for d in cursor] <commit_msg>Return more fields in subtraction find API response<commit_after>
import virtool.utils PROJECTION = [ "_id", "count", "file", "ready", "job", "nickname", "user" ] async def get_linked_samples(db, subtraction_id): cursor = db.samples.find({"subtraction.id": subtraction_id}, ["name"]) return [virtool.utils.base_processor(d) async for d in cursor]
import virtool.utils PROJECTION = [ "_id", "file", "ready", "job" ] async def get_linked_samples(db, subtraction_id): cursor = db.samples.find({"subtraction.id": subtraction_id}, ["name"]) return [virtool.utils.base_processor(d) async for d in cursor] Return more fields in subtraction find API responseimport virtool.utils PROJECTION = [ "_id", "count", "file", "ready", "job", "nickname", "user" ] async def get_linked_samples(db, subtraction_id): cursor = db.samples.find({"subtraction.id": subtraction_id}, ["name"]) return [virtool.utils.base_processor(d) async for d in cursor]
<commit_before>import virtool.utils PROJECTION = [ "_id", "file", "ready", "job" ] async def get_linked_samples(db, subtraction_id): cursor = db.samples.find({"subtraction.id": subtraction_id}, ["name"]) return [virtool.utils.base_processor(d) async for d in cursor] <commit_msg>Return more fields in subtraction find API response<commit_after>import virtool.utils PROJECTION = [ "_id", "count", "file", "ready", "job", "nickname", "user" ] async def get_linked_samples(db, subtraction_id): cursor = db.samples.find({"subtraction.id": subtraction_id}, ["name"]) return [virtool.utils.base_processor(d) async for d in cursor]
d918c5e28bc2505407cc3245ecae378bdb97ba19
registration/admin.py
registration/admin.py
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin)
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') raw_id_fields = ['user'] search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin)
Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.
Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.
Python
bsd-3-clause
sandipagr/django-registration,myimages/django-registration,euanlau/django-registration,Troyhy/django-registration,kennydude/djregs,spurfly/django-registration,futurecolors/django-registration,hacklabr/django-registration,futurecolors/django-registration,awakeup/django-registration,sandipagr/django-registration,akvo/django-registration,liberation/django-registration,spurfly/django-registration,liberation/django-registration,austinhappel/django-registration,Troyhy/django-registration,mypebble/djregs,akvo/django-registration,jnns/django-registration,ubernostrum/django-registration,austinhappel/django-registration,gone/django-registration,artursmet/django-registration,euanlau/django-registration,dirtycoder/django-registration,gone/django-registration,danielsamuels/django-registration,tdruez/django-registration,hacklabr/django-registration,artursmet/django-registration
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin) Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') raw_id_fields = ['user'] search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin)
<commit_before>from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin) <commit_msg>Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.<commit_after>
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') raw_id_fields = ['user'] search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin)
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin) Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') raw_id_fields = ['user'] search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin)
<commit_before>from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin) <commit_msg>Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.<commit_after>from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') raw_id_fields = ['user'] search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin)
b42003c15132f8e5874f1b5e8a7133b813a71aaa
backdrop/read/config/development.py
backdrop/read/config/development.py
DATABASE_NAME = "backdrop" MONGO_HOST = 'localhost' MONGO_PORT = 27017 LOG_LEVEL = "DEBUG" RAW_QUERIES_ALLOWED = { "licensing_journey": True }
DATABASE_NAME = "backdrop" MONGO_HOST = 'localhost' MONGO_PORT = 27017 LOG_LEVEL = "DEBUG" RAW_QUERIES_ALLOWED = { "licensing_journey": True, "government_annotations": True, }
Allow raw queries to annotations bucket
Allow raw queries to annotations bucket This bucket holds the annotations for the insidegov dashboard.
Python
mit
alphagov/backdrop,alphagov/backdrop,alphagov/backdrop
DATABASE_NAME = "backdrop" MONGO_HOST = 'localhost' MONGO_PORT = 27017 LOG_LEVEL = "DEBUG" RAW_QUERIES_ALLOWED = { "licensing_journey": True } Allow raw queries to annotations bucket This bucket holds the annotations for the insidegov dashboard.
DATABASE_NAME = "backdrop" MONGO_HOST = 'localhost' MONGO_PORT = 27017 LOG_LEVEL = "DEBUG" RAW_QUERIES_ALLOWED = { "licensing_journey": True, "government_annotations": True, }
<commit_before>DATABASE_NAME = "backdrop" MONGO_HOST = 'localhost' MONGO_PORT = 27017 LOG_LEVEL = "DEBUG" RAW_QUERIES_ALLOWED = { "licensing_journey": True } <commit_msg>Allow raw queries to annotations bucket This bucket holds the annotations for the insidegov dashboard.<commit_after>
DATABASE_NAME = "backdrop" MONGO_HOST = 'localhost' MONGO_PORT = 27017 LOG_LEVEL = "DEBUG" RAW_QUERIES_ALLOWED = { "licensing_journey": True, "government_annotations": True, }
DATABASE_NAME = "backdrop" MONGO_HOST = 'localhost' MONGO_PORT = 27017 LOG_LEVEL = "DEBUG" RAW_QUERIES_ALLOWED = { "licensing_journey": True } Allow raw queries to annotations bucket This bucket holds the annotations for the insidegov dashboard.DATABASE_NAME = "backdrop" MONGO_HOST = 'localhost' MONGO_PORT = 27017 LOG_LEVEL = "DEBUG" RAW_QUERIES_ALLOWED = { "licensing_journey": True, "government_annotations": True, }
<commit_before>DATABASE_NAME = "backdrop" MONGO_HOST = 'localhost' MONGO_PORT = 27017 LOG_LEVEL = "DEBUG" RAW_QUERIES_ALLOWED = { "licensing_journey": True } <commit_msg>Allow raw queries to annotations bucket This bucket holds the annotations for the insidegov dashboard.<commit_after>DATABASE_NAME = "backdrop" MONGO_HOST = 'localhost' MONGO_PORT = 27017 LOG_LEVEL = "DEBUG" RAW_QUERIES_ALLOWED = { "licensing_journey": True, "government_annotations": True, }
32ce73328d7644601a848cf5ac6d0de1242eb900
config.py
config.py
import os class Config(object): DEBUG = False SECRET_KEY = os.urandom(30).encode('hex') TEMP_DIR = 'tmp' LIB_DIR = 'books' MONGO = { 'HOST' : 'localhost', 'PORT' : 27017, 'DATABASE' : 'Alexandria' } class Debug(Config): DEBUG=True
class Config(object): DEBUG = False SECRET_KEY = 'CHANGEME' TEMP_DIR = 'tmp' LIB_DIR = 'books' MONGO = { 'HOST' : 'localhost', 'PORT' : 27017, 'DATABASE' : 'Alexandria' } class Debug(Config): DEBUG=True
Use constant secret key for easier debugging
Use constant secret key for easier debugging
Python
mit
citruspi/Alexandria,citruspi/Alexandria
import os class Config(object): DEBUG = False SECRET_KEY = os.urandom(30).encode('hex') TEMP_DIR = 'tmp' LIB_DIR = 'books' MONGO = { 'HOST' : 'localhost', 'PORT' : 27017, 'DATABASE' : 'Alexandria' } class Debug(Config): DEBUG=True Use constant secret key for easier debugging
class Config(object): DEBUG = False SECRET_KEY = 'CHANGEME' TEMP_DIR = 'tmp' LIB_DIR = 'books' MONGO = { 'HOST' : 'localhost', 'PORT' : 27017, 'DATABASE' : 'Alexandria' } class Debug(Config): DEBUG=True
<commit_before>import os class Config(object): DEBUG = False SECRET_KEY = os.urandom(30).encode('hex') TEMP_DIR = 'tmp' LIB_DIR = 'books' MONGO = { 'HOST' : 'localhost', 'PORT' : 27017, 'DATABASE' : 'Alexandria' } class Debug(Config): DEBUG=True <commit_msg>Use constant secret key for easier debugging<commit_after>
class Config(object): DEBUG = False SECRET_KEY = 'CHANGEME' TEMP_DIR = 'tmp' LIB_DIR = 'books' MONGO = { 'HOST' : 'localhost', 'PORT' : 27017, 'DATABASE' : 'Alexandria' } class Debug(Config): DEBUG=True
import os class Config(object): DEBUG = False SECRET_KEY = os.urandom(30).encode('hex') TEMP_DIR = 'tmp' LIB_DIR = 'books' MONGO = { 'HOST' : 'localhost', 'PORT' : 27017, 'DATABASE' : 'Alexandria' } class Debug(Config): DEBUG=True Use constant secret key for easier debuggingclass Config(object): DEBUG = False SECRET_KEY = 'CHANGEME' TEMP_DIR = 'tmp' LIB_DIR = 'books' MONGO = { 'HOST' : 'localhost', 'PORT' : 27017, 'DATABASE' : 'Alexandria' } class Debug(Config): DEBUG=True
<commit_before>import os class Config(object): DEBUG = False SECRET_KEY = os.urandom(30).encode('hex') TEMP_DIR = 'tmp' LIB_DIR = 'books' MONGO = { 'HOST' : 'localhost', 'PORT' : 27017, 'DATABASE' : 'Alexandria' } class Debug(Config): DEBUG=True <commit_msg>Use constant secret key for easier debugging<commit_after>class Config(object): DEBUG = False SECRET_KEY = 'CHANGEME' TEMP_DIR = 'tmp' LIB_DIR = 'books' MONGO = { 'HOST' : 'localhost', 'PORT' : 27017, 'DATABASE' : 'Alexandria' } class Debug(Config): DEBUG=True
0d58d7c7a3eee8748efbf7405aba7a5f3e0f7eb3
bluebottle/funding_telesom/admin.py
bluebottle/funding_telesom/admin.py
from django.contrib import admin from bluebottle.funding.admin import PaymentChildAdmin, PaymentProviderChildAdmin, BankAccountChildAdmin from bluebottle.funding.models import PaymentProvider, Payment from bluebottle.funding_telesom.models import TelesomPayment, TelesomPaymentProvider, TelesomBankAccount @admin.register(TelesomPayment) class TelesomPaymentAdmin(PaymentChildAdmin): base_model = Payment fields = PaymentChildAdmin.fields + [ 'account_name', 'account_number', 'response', 'unique_id', 'reference_id', 'transaction_id', 'transaction_amount', 'issuer_transaction_id', 'amount', 'currency' ] list_display = ['created', 'account_name', 'account_number', 'amount', 'status'] @admin.register(TelesomPaymentProvider) class TelesomPaymentProviderAdmin(PaymentProviderChildAdmin): base_model = PaymentProvider @admin.register(TelesomBankAccount) class TelesomBankAccountAdmin(BankAccountChildAdmin): model = TelesomBankAccount fields = ('account_name', 'mobile_number') + BankAccountChildAdmin.fields list_filter = ['reviewed'] search_fields = ['account_name', 'mobile_number'] list_display = ['created', 'account_name', 'mobile_number', 'reviewed']
from django.contrib import admin from bluebottle.funding.admin import PaymentChildAdmin, PaymentProviderChildAdmin, BankAccountChildAdmin from bluebottle.funding.models import PaymentProvider, Payment from bluebottle.funding_telesom.models import TelesomPayment, TelesomPaymentProvider, TelesomBankAccount @admin.register(TelesomPayment) class TelesomPaymentAdmin(PaymentChildAdmin): base_model = Payment fields = PaymentChildAdmin.fields + [ 'account_name', 'account_number', 'response', 'unique_id', 'reference_id', 'transaction_id', 'transaction_amount', 'issuer_transaction_id', 'amount', 'currency' ] search_fields = ['account_name', 'account_number'] list_display = ['created', 'account_name', 'account_number', 'amount', 'status'] @admin.register(TelesomPaymentProvider) class TelesomPaymentProviderAdmin(PaymentProviderChildAdmin): base_model = PaymentProvider @admin.register(TelesomBankAccount) class TelesomBankAccountAdmin(BankAccountChildAdmin): model = TelesomBankAccount fields = ('account_name', 'mobile_number') + BankAccountChildAdmin.fields list_filter = ['reviewed'] search_fields = ['account_name', 'mobile_number'] list_display = ['created', 'account_name', 'mobile_number', 'reviewed']
Add some search fields to Zaad
Add some search fields to Zaad
Python
bsd-3-clause
onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
from django.contrib import admin from bluebottle.funding.admin import PaymentChildAdmin, PaymentProviderChildAdmin, BankAccountChildAdmin from bluebottle.funding.models import PaymentProvider, Payment from bluebottle.funding_telesom.models import TelesomPayment, TelesomPaymentProvider, TelesomBankAccount @admin.register(TelesomPayment) class TelesomPaymentAdmin(PaymentChildAdmin): base_model = Payment fields = PaymentChildAdmin.fields + [ 'account_name', 'account_number', 'response', 'unique_id', 'reference_id', 'transaction_id', 'transaction_amount', 'issuer_transaction_id', 'amount', 'currency' ] list_display = ['created', 'account_name', 'account_number', 'amount', 'status'] @admin.register(TelesomPaymentProvider) class TelesomPaymentProviderAdmin(PaymentProviderChildAdmin): base_model = PaymentProvider @admin.register(TelesomBankAccount) class TelesomBankAccountAdmin(BankAccountChildAdmin): model = TelesomBankAccount fields = ('account_name', 'mobile_number') + BankAccountChildAdmin.fields list_filter = ['reviewed'] search_fields = ['account_name', 'mobile_number'] list_display = ['created', 'account_name', 'mobile_number', 'reviewed'] Add some search fields to Zaad
from django.contrib import admin from bluebottle.funding.admin import PaymentChildAdmin, PaymentProviderChildAdmin, BankAccountChildAdmin from bluebottle.funding.models import PaymentProvider, Payment from bluebottle.funding_telesom.models import TelesomPayment, TelesomPaymentProvider, TelesomBankAccount @admin.register(TelesomPayment) class TelesomPaymentAdmin(PaymentChildAdmin): base_model = Payment fields = PaymentChildAdmin.fields + [ 'account_name', 'account_number', 'response', 'unique_id', 'reference_id', 'transaction_id', 'transaction_amount', 'issuer_transaction_id', 'amount', 'currency' ] search_fields = ['account_name', 'account_number'] list_display = ['created', 'account_name', 'account_number', 'amount', 'status'] @admin.register(TelesomPaymentProvider) class TelesomPaymentProviderAdmin(PaymentProviderChildAdmin): base_model = PaymentProvider @admin.register(TelesomBankAccount) class TelesomBankAccountAdmin(BankAccountChildAdmin): model = TelesomBankAccount fields = ('account_name', 'mobile_number') + BankAccountChildAdmin.fields list_filter = ['reviewed'] search_fields = ['account_name', 'mobile_number'] list_display = ['created', 'account_name', 'mobile_number', 'reviewed']
<commit_before>from django.contrib import admin from bluebottle.funding.admin import PaymentChildAdmin, PaymentProviderChildAdmin, BankAccountChildAdmin from bluebottle.funding.models import PaymentProvider, Payment from bluebottle.funding_telesom.models import TelesomPayment, TelesomPaymentProvider, TelesomBankAccount @admin.register(TelesomPayment) class TelesomPaymentAdmin(PaymentChildAdmin): base_model = Payment fields = PaymentChildAdmin.fields + [ 'account_name', 'account_number', 'response', 'unique_id', 'reference_id', 'transaction_id', 'transaction_amount', 'issuer_transaction_id', 'amount', 'currency' ] list_display = ['created', 'account_name', 'account_number', 'amount', 'status'] @admin.register(TelesomPaymentProvider) class TelesomPaymentProviderAdmin(PaymentProviderChildAdmin): base_model = PaymentProvider @admin.register(TelesomBankAccount) class TelesomBankAccountAdmin(BankAccountChildAdmin): model = TelesomBankAccount fields = ('account_name', 'mobile_number') + BankAccountChildAdmin.fields list_filter = ['reviewed'] search_fields = ['account_name', 'mobile_number'] list_display = ['created', 'account_name', 'mobile_number', 'reviewed'] <commit_msg>Add some search fields to Zaad<commit_after>
from django.contrib import admin from bluebottle.funding.admin import PaymentChildAdmin, PaymentProviderChildAdmin, BankAccountChildAdmin from bluebottle.funding.models import PaymentProvider, Payment from bluebottle.funding_telesom.models import TelesomPayment, TelesomPaymentProvider, TelesomBankAccount @admin.register(TelesomPayment) class TelesomPaymentAdmin(PaymentChildAdmin): base_model = Payment fields = PaymentChildAdmin.fields + [ 'account_name', 'account_number', 'response', 'unique_id', 'reference_id', 'transaction_id', 'transaction_amount', 'issuer_transaction_id', 'amount', 'currency' ] search_fields = ['account_name', 'account_number'] list_display = ['created', 'account_name', 'account_number', 'amount', 'status'] @admin.register(TelesomPaymentProvider) class TelesomPaymentProviderAdmin(PaymentProviderChildAdmin): base_model = PaymentProvider @admin.register(TelesomBankAccount) class TelesomBankAccountAdmin(BankAccountChildAdmin): model = TelesomBankAccount fields = ('account_name', 'mobile_number') + BankAccountChildAdmin.fields list_filter = ['reviewed'] search_fields = ['account_name', 'mobile_number'] list_display = ['created', 'account_name', 'mobile_number', 'reviewed']
from django.contrib import admin from bluebottle.funding.admin import PaymentChildAdmin, PaymentProviderChildAdmin, BankAccountChildAdmin from bluebottle.funding.models import PaymentProvider, Payment from bluebottle.funding_telesom.models import TelesomPayment, TelesomPaymentProvider, TelesomBankAccount @admin.register(TelesomPayment) class TelesomPaymentAdmin(PaymentChildAdmin): base_model = Payment fields = PaymentChildAdmin.fields + [ 'account_name', 'account_number', 'response', 'unique_id', 'reference_id', 'transaction_id', 'transaction_amount', 'issuer_transaction_id', 'amount', 'currency' ] list_display = ['created', 'account_name', 'account_number', 'amount', 'status'] @admin.register(TelesomPaymentProvider) class TelesomPaymentProviderAdmin(PaymentProviderChildAdmin): base_model = PaymentProvider @admin.register(TelesomBankAccount) class TelesomBankAccountAdmin(BankAccountChildAdmin): model = TelesomBankAccount fields = ('account_name', 'mobile_number') + BankAccountChildAdmin.fields list_filter = ['reviewed'] search_fields = ['account_name', 'mobile_number'] list_display = ['created', 'account_name', 'mobile_number', 'reviewed'] Add some search fields to Zaadfrom django.contrib import admin from bluebottle.funding.admin import PaymentChildAdmin, PaymentProviderChildAdmin, BankAccountChildAdmin from bluebottle.funding.models import PaymentProvider, Payment from bluebottle.funding_telesom.models import TelesomPayment, TelesomPaymentProvider, TelesomBankAccount @admin.register(TelesomPayment) class TelesomPaymentAdmin(PaymentChildAdmin): base_model = Payment fields = PaymentChildAdmin.fields + [ 'account_name', 'account_number', 'response', 'unique_id', 'reference_id', 'transaction_id', 'transaction_amount', 'issuer_transaction_id', 'amount', 'currency' ] search_fields = ['account_name', 'account_number'] list_display = ['created', 'account_name', 'account_number', 'amount', 'status'] @admin.register(TelesomPaymentProvider) class TelesomPaymentProviderAdmin(PaymentProviderChildAdmin): base_model = PaymentProvider @admin.register(TelesomBankAccount) class TelesomBankAccountAdmin(BankAccountChildAdmin): model = TelesomBankAccount fields = ('account_name', 'mobile_number') + BankAccountChildAdmin.fields list_filter = ['reviewed'] search_fields = ['account_name', 'mobile_number'] list_display = ['created', 'account_name', 'mobile_number', 'reviewed']
<commit_before>from django.contrib import admin from bluebottle.funding.admin import PaymentChildAdmin, PaymentProviderChildAdmin, BankAccountChildAdmin from bluebottle.funding.models import PaymentProvider, Payment from bluebottle.funding_telesom.models import TelesomPayment, TelesomPaymentProvider, TelesomBankAccount @admin.register(TelesomPayment) class TelesomPaymentAdmin(PaymentChildAdmin): base_model = Payment fields = PaymentChildAdmin.fields + [ 'account_name', 'account_number', 'response', 'unique_id', 'reference_id', 'transaction_id', 'transaction_amount', 'issuer_transaction_id', 'amount', 'currency' ] list_display = ['created', 'account_name', 'account_number', 'amount', 'status'] @admin.register(TelesomPaymentProvider) class TelesomPaymentProviderAdmin(PaymentProviderChildAdmin): base_model = PaymentProvider @admin.register(TelesomBankAccount) class TelesomBankAccountAdmin(BankAccountChildAdmin): model = TelesomBankAccount fields = ('account_name', 'mobile_number') + BankAccountChildAdmin.fields list_filter = ['reviewed'] search_fields = ['account_name', 'mobile_number'] list_display = ['created', 'account_name', 'mobile_number', 'reviewed'] <commit_msg>Add some search fields to Zaad<commit_after>from django.contrib import admin from bluebottle.funding.admin import PaymentChildAdmin, PaymentProviderChildAdmin, BankAccountChildAdmin from bluebottle.funding.models import PaymentProvider, Payment from bluebottle.funding_telesom.models import TelesomPayment, TelesomPaymentProvider, TelesomBankAccount @admin.register(TelesomPayment) class TelesomPaymentAdmin(PaymentChildAdmin): base_model = Payment fields = PaymentChildAdmin.fields + [ 'account_name', 'account_number', 'response', 'unique_id', 'reference_id', 'transaction_id', 'transaction_amount', 'issuer_transaction_id', 'amount', 'currency' ] search_fields = ['account_name', 'account_number'] list_display = ['created', 'account_name', 'account_number', 'amount', 'status'] @admin.register(TelesomPaymentProvider) class TelesomPaymentProviderAdmin(PaymentProviderChildAdmin): base_model = PaymentProvider @admin.register(TelesomBankAccount) class TelesomBankAccountAdmin(BankAccountChildAdmin): model = TelesomBankAccount fields = ('account_name', 'mobile_number') + BankAccountChildAdmin.fields list_filter = ['reviewed'] search_fields = ['account_name', 'mobile_number'] list_display = ['created', 'account_name', 'mobile_number', 'reviewed']
cda1d6b1cdb0a36a3e9d9e5a65eabfb22a29e94e
src/ocspdash/web/blueprints/ui.py
src/ocspdash/web/blueprints/ui.py
import base64 from collections import namedtuple, OrderedDict from itertools import groupby import json from operator import itemgetter from typing import List from flask import Blueprint, render_template, request, current_app import nacl.signing import nacl.encoding import nacl.exceptions from ...models import Location ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Shows the user the home view""" payload = current_app.manager.make_payload() return render_template('index.html', payload=payload) @ui.route('/submit', methods=['POST']) def submit(): data = request.data location_id = int(request.headers['authorization']) location = current_app.manager.get_location_by_id(location_id) if not location.activated: abort(403, f'Not activated: {location}') pubkey = location.pubkey try: verify_key = nacl.signing.VerifyKey(pubkey, encoder=nacl.encoding.URLSafeBase64Encoder) payload = verify_key.verify(data, encoder=nacl.encoding.URLSafeBase64Encoder) except nacl.exceptions.BadSignatureError: return '', '403' print(json.loads(base64.urlsafe_b64decode(payload).decode('utf-8'))) return '', 204
import base64 from collections import namedtuple, OrderedDict from itertools import groupby import json from operator import itemgetter from typing import List from flask import Blueprint, render_template, request, current_app import nacl.signing import nacl.encoding import nacl.exceptions from ...models import Location ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Shows the user the home view""" payload = current_app.manager.make_payload() return render_template('index.html', payload=payload) @ui.route('/submit', methods=['POST']) def submit(): data = request.data location_id = int(request.headers['authorization']) location = current_app.manager.get_location_by_id(location_id) if not location.activated: abort(403, f'Not activated: {location}') pubkey = location.pubkey try: verify_key = nacl.signing.VerifyKey(pubkey, encoder=nacl.encoding.URLSafeBase64Encoder) payload = verify_key.verify(data, encoder=nacl.encoding.URLSafeBase64Encoder) print(json.loads(base64.urlsafe_b64decode(payload).decode('utf-8'))) return '', 204 except nacl.exceptions.BadSignatureError as e: abort(403, f'Bad Signature: {e}')
Handle bad signature with flask abort
Handle bad signature with flask abort
Python
mit
scolby33/OCSPdash,scolby33/OCSPdash,scolby33/OCSPdash
import base64 from collections import namedtuple, OrderedDict from itertools import groupby import json from operator import itemgetter from typing import List from flask import Blueprint, render_template, request, current_app import nacl.signing import nacl.encoding import nacl.exceptions from ...models import Location ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Shows the user the home view""" payload = current_app.manager.make_payload() return render_template('index.html', payload=payload) @ui.route('/submit', methods=['POST']) def submit(): data = request.data location_id = int(request.headers['authorization']) location = current_app.manager.get_location_by_id(location_id) if not location.activated: abort(403, f'Not activated: {location}') pubkey = location.pubkey try: verify_key = nacl.signing.VerifyKey(pubkey, encoder=nacl.encoding.URLSafeBase64Encoder) payload = verify_key.verify(data, encoder=nacl.encoding.URLSafeBase64Encoder) except nacl.exceptions.BadSignatureError: return '', '403' print(json.loads(base64.urlsafe_b64decode(payload).decode('utf-8'))) return '', 204 Handle bad signature with flask abort
import base64 from collections import namedtuple, OrderedDict from itertools import groupby import json from operator import itemgetter from typing import List from flask import Blueprint, render_template, request, current_app import nacl.signing import nacl.encoding import nacl.exceptions from ...models import Location ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Shows the user the home view""" payload = current_app.manager.make_payload() return render_template('index.html', payload=payload) @ui.route('/submit', methods=['POST']) def submit(): data = request.data location_id = int(request.headers['authorization']) location = current_app.manager.get_location_by_id(location_id) if not location.activated: abort(403, f'Not activated: {location}') pubkey = location.pubkey try: verify_key = nacl.signing.VerifyKey(pubkey, encoder=nacl.encoding.URLSafeBase64Encoder) payload = verify_key.verify(data, encoder=nacl.encoding.URLSafeBase64Encoder) print(json.loads(base64.urlsafe_b64decode(payload).decode('utf-8'))) return '', 204 except nacl.exceptions.BadSignatureError as e: abort(403, f'Bad Signature: {e}')
<commit_before>import base64 from collections import namedtuple, OrderedDict from itertools import groupby import json from operator import itemgetter from typing import List from flask import Blueprint, render_template, request, current_app import nacl.signing import nacl.encoding import nacl.exceptions from ...models import Location ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Shows the user the home view""" payload = current_app.manager.make_payload() return render_template('index.html', payload=payload) @ui.route('/submit', methods=['POST']) def submit(): data = request.data location_id = int(request.headers['authorization']) location = current_app.manager.get_location_by_id(location_id) if not location.activated: abort(403, f'Not activated: {location}') pubkey = location.pubkey try: verify_key = nacl.signing.VerifyKey(pubkey, encoder=nacl.encoding.URLSafeBase64Encoder) payload = verify_key.verify(data, encoder=nacl.encoding.URLSafeBase64Encoder) except nacl.exceptions.BadSignatureError: return '', '403' print(json.loads(base64.urlsafe_b64decode(payload).decode('utf-8'))) return '', 204 <commit_msg>Handle bad signature with flask abort<commit_after>
import base64 from collections import namedtuple, OrderedDict from itertools import groupby import json from operator import itemgetter from typing import List from flask import Blueprint, render_template, request, current_app import nacl.signing import nacl.encoding import nacl.exceptions from ...models import Location ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Shows the user the home view""" payload = current_app.manager.make_payload() return render_template('index.html', payload=payload) @ui.route('/submit', methods=['POST']) def submit(): data = request.data location_id = int(request.headers['authorization']) location = current_app.manager.get_location_by_id(location_id) if not location.activated: abort(403, f'Not activated: {location}') pubkey = location.pubkey try: verify_key = nacl.signing.VerifyKey(pubkey, encoder=nacl.encoding.URLSafeBase64Encoder) payload = verify_key.verify(data, encoder=nacl.encoding.URLSafeBase64Encoder) print(json.loads(base64.urlsafe_b64decode(payload).decode('utf-8'))) return '', 204 except nacl.exceptions.BadSignatureError as e: abort(403, f'Bad Signature: {e}')
import base64 from collections import namedtuple, OrderedDict from itertools import groupby import json from operator import itemgetter from typing import List from flask import Blueprint, render_template, request, current_app import nacl.signing import nacl.encoding import nacl.exceptions from ...models import Location ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Shows the user the home view""" payload = current_app.manager.make_payload() return render_template('index.html', payload=payload) @ui.route('/submit', methods=['POST']) def submit(): data = request.data location_id = int(request.headers['authorization']) location = current_app.manager.get_location_by_id(location_id) if not location.activated: abort(403, f'Not activated: {location}') pubkey = location.pubkey try: verify_key = nacl.signing.VerifyKey(pubkey, encoder=nacl.encoding.URLSafeBase64Encoder) payload = verify_key.verify(data, encoder=nacl.encoding.URLSafeBase64Encoder) except nacl.exceptions.BadSignatureError: return '', '403' print(json.loads(base64.urlsafe_b64decode(payload).decode('utf-8'))) return '', 204 Handle bad signature with flask abortimport base64 from collections import namedtuple, OrderedDict from itertools import groupby import json from operator import itemgetter from typing import List from flask import Blueprint, render_template, request, current_app import nacl.signing import nacl.encoding import nacl.exceptions from ...models import Location ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Shows the user the home view""" payload = current_app.manager.make_payload() return render_template('index.html', payload=payload) @ui.route('/submit', methods=['POST']) def submit(): data = request.data location_id = int(request.headers['authorization']) location = current_app.manager.get_location_by_id(location_id) if not location.activated: abort(403, f'Not activated: {location}') pubkey = location.pubkey try: verify_key = nacl.signing.VerifyKey(pubkey, encoder=nacl.encoding.URLSafeBase64Encoder) payload = verify_key.verify(data, encoder=nacl.encoding.URLSafeBase64Encoder) print(json.loads(base64.urlsafe_b64decode(payload).decode('utf-8'))) return '', 204 except nacl.exceptions.BadSignatureError as e: abort(403, f'Bad Signature: {e}')
<commit_before>import base64 from collections import namedtuple, OrderedDict from itertools import groupby import json from operator import itemgetter from typing import List from flask import Blueprint, render_template, request, current_app import nacl.signing import nacl.encoding import nacl.exceptions from ...models import Location ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Shows the user the home view""" payload = current_app.manager.make_payload() return render_template('index.html', payload=payload) @ui.route('/submit', methods=['POST']) def submit(): data = request.data location_id = int(request.headers['authorization']) location = current_app.manager.get_location_by_id(location_id) if not location.activated: abort(403, f'Not activated: {location}') pubkey = location.pubkey try: verify_key = nacl.signing.VerifyKey(pubkey, encoder=nacl.encoding.URLSafeBase64Encoder) payload = verify_key.verify(data, encoder=nacl.encoding.URLSafeBase64Encoder) except nacl.exceptions.BadSignatureError: return '', '403' print(json.loads(base64.urlsafe_b64decode(payload).decode('utf-8'))) return '', 204 <commit_msg>Handle bad signature with flask abort<commit_after>import base64 from collections import namedtuple, OrderedDict from itertools import groupby import json from operator import itemgetter from typing import List from flask import Blueprint, render_template, request, current_app import nacl.signing import nacl.encoding import nacl.exceptions from ...models import Location ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Shows the user the home view""" payload = current_app.manager.make_payload() return render_template('index.html', payload=payload) @ui.route('/submit', methods=['POST']) def submit(): data = request.data location_id = int(request.headers['authorization']) location = current_app.manager.get_location_by_id(location_id) if not location.activated: abort(403, f'Not activated: {location}') pubkey = location.pubkey try: verify_key = nacl.signing.VerifyKey(pubkey, encoder=nacl.encoding.URLSafeBase64Encoder) payload = verify_key.verify(data, encoder=nacl.encoding.URLSafeBase64Encoder) print(json.loads(base64.urlsafe_b64decode(payload).decode('utf-8'))) return '', 204 except nacl.exceptions.BadSignatureError as e: abort(403, f'Bad Signature: {e}')
234df393c438fdf729dc050d20084e1fe1a4c2ee
backend/mcapi/mcdir.py
backend/mcapi/mcdir.py
import utils from os import environ import os.path MCDIR = environ.get("MCDIR") or '/mcfs/data' def for_uid(uidstr): pieces = uidstr.split('-') path = os.path.join(MCDIR, pieces[1][0:2], pieces[1][2:4]) utils.mkdirp(path) return path
import utils from os import environ import os.path MCDIR = environ.get("MCDIR") or '/mcfs/data/materialscommons' def for_uid(uidstr): pieces = uidstr.split('-') path = os.path.join(MCDIR, pieces[1][0:2], pieces[1][2:4]) utils.mkdirp(path) return path
Change directory where data is written to.
Change directory where data is written to.
Python
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
import utils from os import environ import os.path MCDIR = environ.get("MCDIR") or '/mcfs/data' def for_uid(uidstr): pieces = uidstr.split('-') path = os.path.join(MCDIR, pieces[1][0:2], pieces[1][2:4]) utils.mkdirp(path) return path Change directory where data is written to.
import utils from os import environ import os.path MCDIR = environ.get("MCDIR") or '/mcfs/data/materialscommons' def for_uid(uidstr): pieces = uidstr.split('-') path = os.path.join(MCDIR, pieces[1][0:2], pieces[1][2:4]) utils.mkdirp(path) return path
<commit_before>import utils from os import environ import os.path MCDIR = environ.get("MCDIR") or '/mcfs/data' def for_uid(uidstr): pieces = uidstr.split('-') path = os.path.join(MCDIR, pieces[1][0:2], pieces[1][2:4]) utils.mkdirp(path) return path <commit_msg>Change directory where data is written to.<commit_after>
import utils from os import environ import os.path MCDIR = environ.get("MCDIR") or '/mcfs/data/materialscommons' def for_uid(uidstr): pieces = uidstr.split('-') path = os.path.join(MCDIR, pieces[1][0:2], pieces[1][2:4]) utils.mkdirp(path) return path
import utils from os import environ import os.path MCDIR = environ.get("MCDIR") or '/mcfs/data' def for_uid(uidstr): pieces = uidstr.split('-') path = os.path.join(MCDIR, pieces[1][0:2], pieces[1][2:4]) utils.mkdirp(path) return path Change directory where data is written to.import utils from os import environ import os.path MCDIR = environ.get("MCDIR") or '/mcfs/data/materialscommons' def for_uid(uidstr): pieces = uidstr.split('-') path = os.path.join(MCDIR, pieces[1][0:2], pieces[1][2:4]) utils.mkdirp(path) return path
<commit_before>import utils from os import environ import os.path MCDIR = environ.get("MCDIR") or '/mcfs/data' def for_uid(uidstr): pieces = uidstr.split('-') path = os.path.join(MCDIR, pieces[1][0:2], pieces[1][2:4]) utils.mkdirp(path) return path <commit_msg>Change directory where data is written to.<commit_after>import utils from os import environ import os.path MCDIR = environ.get("MCDIR") or '/mcfs/data/materialscommons' def for_uid(uidstr): pieces = uidstr.split('-') path = os.path.join(MCDIR, pieces[1][0:2], pieces[1][2:4]) utils.mkdirp(path) return path
72f84b49ea9781f3252c49a1805c0ce19af5c635
corehq/apps/case_search/dsl_utils.py
corehq/apps/case_search/dsl_utils.py
from django.utils.translation import gettext as _ from eulxml.xpath.ast import FunctionCall, UnaryExpression, serialize from corehq.apps.case_search.exceptions import ( CaseFilterError, XPathFunctionException, ) from corehq.apps.case_search.xpath_functions import XPATH_VALUE_FUNCTIONS def unwrap_value(value, context): """Returns the value of the node if it is wrapped in a function, otherwise just returns the node """ if isinstance(value, (str, int, float, bool)): return value if isinstance(value, UnaryExpression) and value.op == '-': return -1 * value.right if not isinstance(value, FunctionCall): return value try: return XPATH_VALUE_FUNCTIONS[value.name](value, context) except KeyError: raise CaseFilterError( _("We don't know what to do with the function \"{}\". Accepted functions are: {}").format( value.name, ", ".join(list(XPATH_VALUE_FUNCTIONS.keys())), ), serialize(value) ) except XPathFunctionException as e: raise CaseFilterError(str(e), serialize(value))
from django.utils.translation import gettext as _ from eulxml.xpath.ast import FunctionCall, UnaryExpression, serialize from corehq.apps.case_search.exceptions import ( CaseFilterError, XPathFunctionException, ) from corehq.apps.case_search.xpath_functions import XPATH_VALUE_FUNCTIONS def unwrap_value(value, context): """Returns the value of the node if it is wrapped in a function, otherwise just returns the node """ if isinstance(value, UnaryExpression) and value.op == '-': return -1 * value.right if not isinstance(value, FunctionCall): return value try: return XPATH_VALUE_FUNCTIONS[value.name](value, context) except KeyError: raise CaseFilterError( _("We don't know what to do with the function \"{}\". Accepted functions are: {}").format( value.name, ", ".join(list(XPATH_VALUE_FUNCTIONS.keys())), ), serialize(value) ) except XPathFunctionException as e: raise CaseFilterError(str(e), serialize(value))
Revert "support unwrapping of basic types"
Revert "support unwrapping of basic types" This reverts commit 86a5a1c8
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from django.utils.translation import gettext as _ from eulxml.xpath.ast import FunctionCall, UnaryExpression, serialize from corehq.apps.case_search.exceptions import ( CaseFilterError, XPathFunctionException, ) from corehq.apps.case_search.xpath_functions import XPATH_VALUE_FUNCTIONS def unwrap_value(value, context): """Returns the value of the node if it is wrapped in a function, otherwise just returns the node """ if isinstance(value, (str, int, float, bool)): return value if isinstance(value, UnaryExpression) and value.op == '-': return -1 * value.right if not isinstance(value, FunctionCall): return value try: return XPATH_VALUE_FUNCTIONS[value.name](value, context) except KeyError: raise CaseFilterError( _("We don't know what to do with the function \"{}\". Accepted functions are: {}").format( value.name, ", ".join(list(XPATH_VALUE_FUNCTIONS.keys())), ), serialize(value) ) except XPathFunctionException as e: raise CaseFilterError(str(e), serialize(value)) Revert "support unwrapping of basic types" This reverts commit 86a5a1c8
from django.utils.translation import gettext as _ from eulxml.xpath.ast import FunctionCall, UnaryExpression, serialize from corehq.apps.case_search.exceptions import ( CaseFilterError, XPathFunctionException, ) from corehq.apps.case_search.xpath_functions import XPATH_VALUE_FUNCTIONS def unwrap_value(value, context): """Returns the value of the node if it is wrapped in a function, otherwise just returns the node """ if isinstance(value, UnaryExpression) and value.op == '-': return -1 * value.right if not isinstance(value, FunctionCall): return value try: return XPATH_VALUE_FUNCTIONS[value.name](value, context) except KeyError: raise CaseFilterError( _("We don't know what to do with the function \"{}\". Accepted functions are: {}").format( value.name, ", ".join(list(XPATH_VALUE_FUNCTIONS.keys())), ), serialize(value) ) except XPathFunctionException as e: raise CaseFilterError(str(e), serialize(value))
<commit_before>from django.utils.translation import gettext as _ from eulxml.xpath.ast import FunctionCall, UnaryExpression, serialize from corehq.apps.case_search.exceptions import ( CaseFilterError, XPathFunctionException, ) from corehq.apps.case_search.xpath_functions import XPATH_VALUE_FUNCTIONS def unwrap_value(value, context): """Returns the value of the node if it is wrapped in a function, otherwise just returns the node """ if isinstance(value, (str, int, float, bool)): return value if isinstance(value, UnaryExpression) and value.op == '-': return -1 * value.right if not isinstance(value, FunctionCall): return value try: return XPATH_VALUE_FUNCTIONS[value.name](value, context) except KeyError: raise CaseFilterError( _("We don't know what to do with the function \"{}\". Accepted functions are: {}").format( value.name, ", ".join(list(XPATH_VALUE_FUNCTIONS.keys())), ), serialize(value) ) except XPathFunctionException as e: raise CaseFilterError(str(e), serialize(value)) <commit_msg>Revert "support unwrapping of basic types" This reverts commit 86a5a1c8<commit_after>
from django.utils.translation import gettext as _ from eulxml.xpath.ast import FunctionCall, UnaryExpression, serialize from corehq.apps.case_search.exceptions import ( CaseFilterError, XPathFunctionException, ) from corehq.apps.case_search.xpath_functions import XPATH_VALUE_FUNCTIONS def unwrap_value(value, context): """Returns the value of the node if it is wrapped in a function, otherwise just returns the node """ if isinstance(value, UnaryExpression) and value.op == '-': return -1 * value.right if not isinstance(value, FunctionCall): return value try: return XPATH_VALUE_FUNCTIONS[value.name](value, context) except KeyError: raise CaseFilterError( _("We don't know what to do with the function \"{}\". Accepted functions are: {}").format( value.name, ", ".join(list(XPATH_VALUE_FUNCTIONS.keys())), ), serialize(value) ) except XPathFunctionException as e: raise CaseFilterError(str(e), serialize(value))
from django.utils.translation import gettext as _ from eulxml.xpath.ast import FunctionCall, UnaryExpression, serialize from corehq.apps.case_search.exceptions import ( CaseFilterError, XPathFunctionException, ) from corehq.apps.case_search.xpath_functions import XPATH_VALUE_FUNCTIONS def unwrap_value(value, context): """Returns the value of the node if it is wrapped in a function, otherwise just returns the node """ if isinstance(value, (str, int, float, bool)): return value if isinstance(value, UnaryExpression) and value.op == '-': return -1 * value.right if not isinstance(value, FunctionCall): return value try: return XPATH_VALUE_FUNCTIONS[value.name](value, context) except KeyError: raise CaseFilterError( _("We don't know what to do with the function \"{}\". Accepted functions are: {}").format( value.name, ", ".join(list(XPATH_VALUE_FUNCTIONS.keys())), ), serialize(value) ) except XPathFunctionException as e: raise CaseFilterError(str(e), serialize(value)) Revert "support unwrapping of basic types" This reverts commit 86a5a1c8from django.utils.translation import gettext as _ from eulxml.xpath.ast import FunctionCall, UnaryExpression, serialize from corehq.apps.case_search.exceptions import ( CaseFilterError, XPathFunctionException, ) from corehq.apps.case_search.xpath_functions import XPATH_VALUE_FUNCTIONS def unwrap_value(value, context): """Returns the value of the node if it is wrapped in a function, otherwise just returns the node """ if isinstance(value, UnaryExpression) and value.op == '-': return -1 * value.right if not isinstance(value, FunctionCall): return value try: return XPATH_VALUE_FUNCTIONS[value.name](value, context) except KeyError: raise CaseFilterError( _("We don't know what to do with the function \"{}\". Accepted functions are: {}").format( value.name, ", ".join(list(XPATH_VALUE_FUNCTIONS.keys())), ), serialize(value) ) except XPathFunctionException as e: raise CaseFilterError(str(e), serialize(value))
<commit_before>from django.utils.translation import gettext as _ from eulxml.xpath.ast import FunctionCall, UnaryExpression, serialize from corehq.apps.case_search.exceptions import ( CaseFilterError, XPathFunctionException, ) from corehq.apps.case_search.xpath_functions import XPATH_VALUE_FUNCTIONS def unwrap_value(value, context): """Returns the value of the node if it is wrapped in a function, otherwise just returns the node """ if isinstance(value, (str, int, float, bool)): return value if isinstance(value, UnaryExpression) and value.op == '-': return -1 * value.right if not isinstance(value, FunctionCall): return value try: return XPATH_VALUE_FUNCTIONS[value.name](value, context) except KeyError: raise CaseFilterError( _("We don't know what to do with the function \"{}\". Accepted functions are: {}").format( value.name, ", ".join(list(XPATH_VALUE_FUNCTIONS.keys())), ), serialize(value) ) except XPathFunctionException as e: raise CaseFilterError(str(e), serialize(value)) <commit_msg>Revert "support unwrapping of basic types" This reverts commit 86a5a1c8<commit_after>from django.utils.translation import gettext as _ from eulxml.xpath.ast import FunctionCall, UnaryExpression, serialize from corehq.apps.case_search.exceptions import ( CaseFilterError, XPathFunctionException, ) from corehq.apps.case_search.xpath_functions import XPATH_VALUE_FUNCTIONS def unwrap_value(value, context): """Returns the value of the node if it is wrapped in a function, otherwise just returns the node """ if isinstance(value, UnaryExpression) and value.op == '-': return -1 * value.right if not isinstance(value, FunctionCall): return value try: return XPATH_VALUE_FUNCTIONS[value.name](value, context) except KeyError: raise CaseFilterError( _("We don't know what to do with the function \"{}\". Accepted functions are: {}").format( value.name, ", ".join(list(XPATH_VALUE_FUNCTIONS.keys())), ), serialize(value) ) except XPathFunctionException as e: raise CaseFilterError(str(e), serialize(value))
f6a974a1dc5337e482fe6fcac402597735892567
saleor/delivery/__init__.py
saleor/delivery/__init__.py
from __future__ import unicode_literals from django.conf import settings from prices import Price from satchless.item import Item class BaseDelivery(Item): def __init__(self, delivery_group): self.group = delivery_group def get_price_per_item(self, **kwargs): return Price(0, currency=settings.SATCHLESS_DEFAULT_CURRENCY) class DummyShipping(BaseDelivery): def __unicode__(self): return 'Dummy shipping' def get_price_per_item(self, **kwargs): weight = sum(line.product.weight for line in self.group) qty = sum(line.quantity for line in self.group) return Price(qty * weight, currency=settings.SATCHLESS_DEFAULT_CURRENCY) class DigitalDelivery(BaseDelivery): def __unicode__(self): return 'Digital delivery'
from __future__ import unicode_literals from re import sub from django.conf import settings from prices import Price from satchless.item import ItemSet from ..cart import ShippedGroup class BaseDelivery(ItemSet): group = None def __init__(self, delivery_group): self.group = delivery_group def __iter__(self): return iter(self.group) def get_delivery_total(self, **kwargs): return Price(0, currency=settings.SATCHLESS_DEFAULT_CURRENCY) def get_total_with_delivery(self): return self.group.get_total() + self.get_delivery_total() @property def name(self): ''' Returns undescored version of class name ''' name = type(self).__name__ name = sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '_\\1', name) return name.lower().strip('_') class DummyShipping(BaseDelivery): address = None def __init__(self, delivery_group, address): self.address = address super(DummyShipping, self).__init__(delivery_group) def __unicode__(self): return 'Dummy shipping' def get_delivery_total(self, **kwargs): weight = sum(line.product.weight for line in self.group) qty = sum(line.quantity for line in self.group) return Price(qty * weight, currency=settings.SATCHLESS_DEFAULT_CURRENCY) class DigitalDelivery(BaseDelivery): email = None def __init__(self, delivery_group, email): self.email = email super(DigitalDelivery, self).__init__(delivery_group) def __unicode__(self): return 'Digital delivery' def get_delivery_methods_for_group(group, **kwargs): if isinstance(group, ShippedGroup): yield DummyShipping(group, kwargs['address']) else: yield DigitalDelivery(group, kwargs['email'])
Use the delivery classes as proxy for items groups
Use the delivery classes as proxy for items groups
Python
bsd-3-clause
Drekscott/Motlaesaleor,taedori81/saleor,rchav/vinerack,maferelo/saleor,rodrigozn/CW-Shop,dashmug/saleor,taedori81/saleor,laosunhust/saleor,laosunhust/saleor,car3oon/saleor,mociepka/saleor,hongquan/saleor,arth-co/saleor,taedori81/saleor,car3oon/saleor,spartonia/saleor,dashmug/saleor,hongquan/saleor,hongquan/saleor,car3oon/saleor,avorio/saleor,rchav/vinerack,spartonia/saleor,dashmug/saleor,arth-co/saleor,maferelo/saleor,paweltin/saleor,spartonia/saleor,taedori81/saleor,KenMutemi/saleor,avorio/saleor,arth-co/saleor,josesanch/saleor,Drekscott/Motlaesaleor,josesanch/saleor,KenMutemi/saleor,HyperManTT/ECommerceSaleor,tfroehlich82/saleor,avorio/saleor,jreigel/saleor,paweltin/saleor,tfroehlich82/saleor,rodrigozn/CW-Shop,UITools/saleor,josesanch/saleor,itbabu/saleor,rchav/vinerack,HyperManTT/ECommerceSaleor,spartonia/saleor,UITools/saleor,UITools/saleor,jreigel/saleor,itbabu/saleor,arth-co/saleor,KenMutemi/saleor,tfroehlich82/saleor,mociepka/saleor,Drekscott/Motlaesaleor,HyperManTT/ECommerceSaleor,paweltin/saleor,Drekscott/Motlaesaleor,maferelo/saleor,laosunhust/saleor,avorio/saleor,mociepka/saleor,itbabu/saleor,paweltin/saleor,laosunhust/saleor,jreigel/saleor,rodrigozn/CW-Shop,UITools/saleor,UITools/saleor
from __future__ import unicode_literals from django.conf import settings from prices import Price from satchless.item import Item class BaseDelivery(Item): def __init__(self, delivery_group): self.group = delivery_group def get_price_per_item(self, **kwargs): return Price(0, currency=settings.SATCHLESS_DEFAULT_CURRENCY) class DummyShipping(BaseDelivery): def __unicode__(self): return 'Dummy shipping' def get_price_per_item(self, **kwargs): weight = sum(line.product.weight for line in self.group) qty = sum(line.quantity for line in self.group) return Price(qty * weight, currency=settings.SATCHLESS_DEFAULT_CURRENCY) class DigitalDelivery(BaseDelivery): def __unicode__(self): return 'Digital delivery' Use the delivery classes as proxy for items groups
from __future__ import unicode_literals from re import sub from django.conf import settings from prices import Price from satchless.item import ItemSet from ..cart import ShippedGroup class BaseDelivery(ItemSet): group = None def __init__(self, delivery_group): self.group = delivery_group def __iter__(self): return iter(self.group) def get_delivery_total(self, **kwargs): return Price(0, currency=settings.SATCHLESS_DEFAULT_CURRENCY) def get_total_with_delivery(self): return self.group.get_total() + self.get_delivery_total() @property def name(self): ''' Returns undescored version of class name ''' name = type(self).__name__ name = sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '_\\1', name) return name.lower().strip('_') class DummyShipping(BaseDelivery): address = None def __init__(self, delivery_group, address): self.address = address super(DummyShipping, self).__init__(delivery_group) def __unicode__(self): return 'Dummy shipping' def get_delivery_total(self, **kwargs): weight = sum(line.product.weight for line in self.group) qty = sum(line.quantity for line in self.group) return Price(qty * weight, currency=settings.SATCHLESS_DEFAULT_CURRENCY) class DigitalDelivery(BaseDelivery): email = None def __init__(self, delivery_group, email): self.email = email super(DigitalDelivery, self).__init__(delivery_group) def __unicode__(self): return 'Digital delivery' def get_delivery_methods_for_group(group, **kwargs): if isinstance(group, ShippedGroup): yield DummyShipping(group, kwargs['address']) else: yield DigitalDelivery(group, kwargs['email'])
<commit_before>from __future__ import unicode_literals from django.conf import settings from prices import Price from satchless.item import Item class BaseDelivery(Item): def __init__(self, delivery_group): self.group = delivery_group def get_price_per_item(self, **kwargs): return Price(0, currency=settings.SATCHLESS_DEFAULT_CURRENCY) class DummyShipping(BaseDelivery): def __unicode__(self): return 'Dummy shipping' def get_price_per_item(self, **kwargs): weight = sum(line.product.weight for line in self.group) qty = sum(line.quantity for line in self.group) return Price(qty * weight, currency=settings.SATCHLESS_DEFAULT_CURRENCY) class DigitalDelivery(BaseDelivery): def __unicode__(self): return 'Digital delivery' <commit_msg>Use the delivery classes as proxy for items groups<commit_after>
from __future__ import unicode_literals from re import sub from django.conf import settings from prices import Price from satchless.item import ItemSet from ..cart import ShippedGroup class BaseDelivery(ItemSet): group = None def __init__(self, delivery_group): self.group = delivery_group def __iter__(self): return iter(self.group) def get_delivery_total(self, **kwargs): return Price(0, currency=settings.SATCHLESS_DEFAULT_CURRENCY) def get_total_with_delivery(self): return self.group.get_total() + self.get_delivery_total() @property def name(self): ''' Returns undescored version of class name ''' name = type(self).__name__ name = sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '_\\1', name) return name.lower().strip('_') class DummyShipping(BaseDelivery): address = None def __init__(self, delivery_group, address): self.address = address super(DummyShipping, self).__init__(delivery_group) def __unicode__(self): return 'Dummy shipping' def get_delivery_total(self, **kwargs): weight = sum(line.product.weight for line in self.group) qty = sum(line.quantity for line in self.group) return Price(qty * weight, currency=settings.SATCHLESS_DEFAULT_CURRENCY) class DigitalDelivery(BaseDelivery): email = None def __init__(self, delivery_group, email): self.email = email super(DigitalDelivery, self).__init__(delivery_group) def __unicode__(self): return 'Digital delivery' def get_delivery_methods_for_group(group, **kwargs): if isinstance(group, ShippedGroup): yield DummyShipping(group, kwargs['address']) else: yield DigitalDelivery(group, kwargs['email'])
from __future__ import unicode_literals from django.conf import settings from prices import Price from satchless.item import Item class BaseDelivery(Item): def __init__(self, delivery_group): self.group = delivery_group def get_price_per_item(self, **kwargs): return Price(0, currency=settings.SATCHLESS_DEFAULT_CURRENCY) class DummyShipping(BaseDelivery): def __unicode__(self): return 'Dummy shipping' def get_price_per_item(self, **kwargs): weight = sum(line.product.weight for line in self.group) qty = sum(line.quantity for line in self.group) return Price(qty * weight, currency=settings.SATCHLESS_DEFAULT_CURRENCY) class DigitalDelivery(BaseDelivery): def __unicode__(self): return 'Digital delivery' Use the delivery classes as proxy for items groupsfrom __future__ import unicode_literals from re import sub from django.conf import settings from prices import Price from satchless.item import ItemSet from ..cart import ShippedGroup class BaseDelivery(ItemSet): group = None def __init__(self, delivery_group): self.group = delivery_group def __iter__(self): return iter(self.group) def get_delivery_total(self, **kwargs): return Price(0, currency=settings.SATCHLESS_DEFAULT_CURRENCY) def get_total_with_delivery(self): return self.group.get_total() + self.get_delivery_total() @property def name(self): ''' Returns undescored version of class name ''' name = type(self).__name__ name = sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '_\\1', name) return name.lower().strip('_') class DummyShipping(BaseDelivery): address = None def __init__(self, delivery_group, address): self.address = address super(DummyShipping, self).__init__(delivery_group) def __unicode__(self): return 'Dummy shipping' def get_delivery_total(self, **kwargs): weight = sum(line.product.weight for line in self.group) qty = sum(line.quantity for line in self.group) return Price(qty * weight, currency=settings.SATCHLESS_DEFAULT_CURRENCY) class DigitalDelivery(BaseDelivery): email = None def __init__(self, delivery_group, email): self.email = email super(DigitalDelivery, self).__init__(delivery_group) def __unicode__(self): return 'Digital delivery' def get_delivery_methods_for_group(group, **kwargs): if isinstance(group, ShippedGroup): yield DummyShipping(group, kwargs['address']) else: yield DigitalDelivery(group, kwargs['email'])
<commit_before>from __future__ import unicode_literals from django.conf import settings from prices import Price from satchless.item import Item class BaseDelivery(Item): def __init__(self, delivery_group): self.group = delivery_group def get_price_per_item(self, **kwargs): return Price(0, currency=settings.SATCHLESS_DEFAULT_CURRENCY) class DummyShipping(BaseDelivery): def __unicode__(self): return 'Dummy shipping' def get_price_per_item(self, **kwargs): weight = sum(line.product.weight for line in self.group) qty = sum(line.quantity for line in self.group) return Price(qty * weight, currency=settings.SATCHLESS_DEFAULT_CURRENCY) class DigitalDelivery(BaseDelivery): def __unicode__(self): return 'Digital delivery' <commit_msg>Use the delivery classes as proxy for items groups<commit_after>from __future__ import unicode_literals from re import sub from django.conf import settings from prices import Price from satchless.item import ItemSet from ..cart import ShippedGroup class BaseDelivery(ItemSet): group = None def __init__(self, delivery_group): self.group = delivery_group def __iter__(self): return iter(self.group) def get_delivery_total(self, **kwargs): return Price(0, currency=settings.SATCHLESS_DEFAULT_CURRENCY) def get_total_with_delivery(self): return self.group.get_total() + self.get_delivery_total() @property def name(self): ''' Returns undescored version of class name ''' name = type(self).__name__ name = sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '_\\1', name) return name.lower().strip('_') class DummyShipping(BaseDelivery): address = None def __init__(self, delivery_group, address): self.address = address super(DummyShipping, self).__init__(delivery_group) def __unicode__(self): return 'Dummy shipping' def get_delivery_total(self, **kwargs): weight = sum(line.product.weight for line in self.group) qty = sum(line.quantity for line in self.group) return Price(qty * weight, currency=settings.SATCHLESS_DEFAULT_CURRENCY) class DigitalDelivery(BaseDelivery): email = None def __init__(self, delivery_group, email): self.email = email super(DigitalDelivery, self).__init__(delivery_group) def __unicode__(self): return 'Digital delivery' def get_delivery_methods_for_group(group, **kwargs): if isinstance(group, ShippedGroup): yield DummyShipping(group, kwargs['address']) else: yield DigitalDelivery(group, kwargs['email'])
510edc5b7d5320deb568b2fab1d654ee4d7a5c83
autogenerate_config_docs/hooks.py
autogenerate_config_docs/hooks.py
# # A collection of shared functions for managing help flag mapping files. # # 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. # """Hooks to handle configuration options not handled on module import or with a call to _register_runtime_opts(). The HOOKS dict associate hook functions with a module path.""" def keystone_config(): from keystone.common import config config.configure() HOOKS = {'keystone.common.config': keystone_config}
# # A collection of shared functions for managing help flag mapping files. # # 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. # """Hooks to handle configuration options not handled on module import or with a call to _register_runtime_opts(). The HOOKS dict associate hook functions with a module path.""" def keystone_config(): from keystone.common import config config.configure() def glance_store_config(): import glance_store from oslo.config import cfg glance_store.backend.register_opts(cfg.CONF) HOOKS = {'keystone.common.config': keystone_config, 'glance.common.config': glance_store_config}
Add a hook to load glance_store options
Add a hook to load glance_store options The backends configuration options are now in the glance_store package and are loaded at runtime. This patch adds a hook that calls a glance_store function to load the options. Change-Id: Iefd49afd578f2b5fa9318d8ed8fb9f7a76d8ba34
Python
apache-2.0
openstack/openstack-doc-tools,savinash47/openstack-doc-tools,savinash47/openstack-doc-tools,openstack/openstack-doc-tools,savinash47/openstack-doc-tools
# # A collection of shared functions for managing help flag mapping files. # # 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. # """Hooks to handle configuration options not handled on module import or with a call to _register_runtime_opts(). The HOOKS dict associate hook functions with a module path.""" def keystone_config(): from keystone.common import config config.configure() HOOKS = {'keystone.common.config': keystone_config} Add a hook to load glance_store options The backends configuration options are now in the glance_store package and are loaded at runtime. This patch adds a hook that calls a glance_store function to load the options. Change-Id: Iefd49afd578f2b5fa9318d8ed8fb9f7a76d8ba34
# # A collection of shared functions for managing help flag mapping files. # # 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. # """Hooks to handle configuration options not handled on module import or with a call to _register_runtime_opts(). The HOOKS dict associate hook functions with a module path.""" def keystone_config(): from keystone.common import config config.configure() def glance_store_config(): import glance_store from oslo.config import cfg glance_store.backend.register_opts(cfg.CONF) HOOKS = {'keystone.common.config': keystone_config, 'glance.common.config': glance_store_config}
<commit_before># # A collection of shared functions for managing help flag mapping files. # # 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. # """Hooks to handle configuration options not handled on module import or with a call to _register_runtime_opts(). The HOOKS dict associate hook functions with a module path.""" def keystone_config(): from keystone.common import config config.configure() HOOKS = {'keystone.common.config': keystone_config} <commit_msg>Add a hook to load glance_store options The backends configuration options are now in the glance_store package and are loaded at runtime. This patch adds a hook that calls a glance_store function to load the options. Change-Id: Iefd49afd578f2b5fa9318d8ed8fb9f7a76d8ba34<commit_after>
# # A collection of shared functions for managing help flag mapping files. # # 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. # """Hooks to handle configuration options not handled on module import or with a call to _register_runtime_opts(). The HOOKS dict associate hook functions with a module path.""" def keystone_config(): from keystone.common import config config.configure() def glance_store_config(): import glance_store from oslo.config import cfg glance_store.backend.register_opts(cfg.CONF) HOOKS = {'keystone.common.config': keystone_config, 'glance.common.config': glance_store_config}
# # A collection of shared functions for managing help flag mapping files. # # 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. # """Hooks to handle configuration options not handled on module import or with a call to _register_runtime_opts(). The HOOKS dict associate hook functions with a module path.""" def keystone_config(): from keystone.common import config config.configure() HOOKS = {'keystone.common.config': keystone_config} Add a hook to load glance_store options The backends configuration options are now in the glance_store package and are loaded at runtime. This patch adds a hook that calls a glance_store function to load the options. Change-Id: Iefd49afd578f2b5fa9318d8ed8fb9f7a76d8ba34# # A collection of shared functions for managing help flag mapping files. # # 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. # """Hooks to handle configuration options not handled on module import or with a call to _register_runtime_opts(). The HOOKS dict associate hook functions with a module path.""" def keystone_config(): from keystone.common import config config.configure() def glance_store_config(): import glance_store from oslo.config import cfg glance_store.backend.register_opts(cfg.CONF) HOOKS = {'keystone.common.config': keystone_config, 'glance.common.config': glance_store_config}
<commit_before># # A collection of shared functions for managing help flag mapping files. # # 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. # """Hooks to handle configuration options not handled on module import or with a call to _register_runtime_opts(). The HOOKS dict associate hook functions with a module path.""" def keystone_config(): from keystone.common import config config.configure() HOOKS = {'keystone.common.config': keystone_config} <commit_msg>Add a hook to load glance_store options The backends configuration options are now in the glance_store package and are loaded at runtime. This patch adds a hook that calls a glance_store function to load the options. Change-Id: Iefd49afd578f2b5fa9318d8ed8fb9f7a76d8ba34<commit_after># # A collection of shared functions for managing help flag mapping files. # # 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. # """Hooks to handle configuration options not handled on module import or with a call to _register_runtime_opts(). The HOOKS dict associate hook functions with a module path.""" def keystone_config(): from keystone.common import config config.configure() def glance_store_config(): import glance_store from oslo.config import cfg glance_store.backend.register_opts(cfg.CONF) HOOKS = {'keystone.common.config': keystone_config, 'glance.common.config': glance_store_config}
dcf2dcb41e66ce01e386d526370ce23064e6e2a3
schemer/exceptions.py
schemer/exceptions.py
class SchemaFormatException(Exception): """Exception which encapsulates a problem found during the verification of a a schema.""" def __init__(self, message, path): self._message = message.format(path) self._path = path @property def path(self): """The field path at which the format error was found.""" return self._path def __str__(self): return self._message class ValidationException(Exception): """Exception which is thrown in response to the failed validation of a document against it's associated schema.""" def __init__(self, errors): self._errors = errors @property def errors(self): """A dict containing the validation error(s) found at each field path.""" return self._errors def __str__(self): return repr(self._errors)
class SchemaFormatException(Exception): """Exception which encapsulates a problem found during the verification of a a schema.""" def __init__(self, message, path): self._message = message.format('\"{}\"'.format(path)) self._path = path @property def path(self): """The field path at which the format error was found.""" return self._path def __str__(self): return self._message class ValidationException(Exception): """Exception which is thrown in response to the failed validation of a document against it's associated schema.""" def __init__(self, errors): self._errors = errors @property def errors(self): """A dict containing the validation error(s) found at each field path.""" return self._errors def __str__(self): return repr(self._errors)
Improve formatting of schema format exception messages
Improve formatting of schema format exception messages
Python
mit
gamechanger/schemer
class SchemaFormatException(Exception): """Exception which encapsulates a problem found during the verification of a a schema.""" def __init__(self, message, path): self._message = message.format(path) self._path = path @property def path(self): """The field path at which the format error was found.""" return self._path def __str__(self): return self._message class ValidationException(Exception): """Exception which is thrown in response to the failed validation of a document against it's associated schema.""" def __init__(self, errors): self._errors = errors @property def errors(self): """A dict containing the validation error(s) found at each field path.""" return self._errors def __str__(self): return repr(self._errors) Improve formatting of schema format exception messages
class SchemaFormatException(Exception): """Exception which encapsulates a problem found during the verification of a a schema.""" def __init__(self, message, path): self._message = message.format('\"{}\"'.format(path)) self._path = path @property def path(self): """The field path at which the format error was found.""" return self._path def __str__(self): return self._message class ValidationException(Exception): """Exception which is thrown in response to the failed validation of a document against it's associated schema.""" def __init__(self, errors): self._errors = errors @property def errors(self): """A dict containing the validation error(s) found at each field path.""" return self._errors def __str__(self): return repr(self._errors)
<commit_before> class SchemaFormatException(Exception): """Exception which encapsulates a problem found during the verification of a a schema.""" def __init__(self, message, path): self._message = message.format(path) self._path = path @property def path(self): """The field path at which the format error was found.""" return self._path def __str__(self): return self._message class ValidationException(Exception): """Exception which is thrown in response to the failed validation of a document against it's associated schema.""" def __init__(self, errors): self._errors = errors @property def errors(self): """A dict containing the validation error(s) found at each field path.""" return self._errors def __str__(self): return repr(self._errors) <commit_msg>Improve formatting of schema format exception messages<commit_after>
class SchemaFormatException(Exception): """Exception which encapsulates a problem found during the verification of a a schema.""" def __init__(self, message, path): self._message = message.format('\"{}\"'.format(path)) self._path = path @property def path(self): """The field path at which the format error was found.""" return self._path def __str__(self): return self._message class ValidationException(Exception): """Exception which is thrown in response to the failed validation of a document against it's associated schema.""" def __init__(self, errors): self._errors = errors @property def errors(self): """A dict containing the validation error(s) found at each field path.""" return self._errors def __str__(self): return repr(self._errors)
class SchemaFormatException(Exception): """Exception which encapsulates a problem found during the verification of a a schema.""" def __init__(self, message, path): self._message = message.format(path) self._path = path @property def path(self): """The field path at which the format error was found.""" return self._path def __str__(self): return self._message class ValidationException(Exception): """Exception which is thrown in response to the failed validation of a document against it's associated schema.""" def __init__(self, errors): self._errors = errors @property def errors(self): """A dict containing the validation error(s) found at each field path.""" return self._errors def __str__(self): return repr(self._errors) Improve formatting of schema format exception messages class SchemaFormatException(Exception): """Exception which encapsulates a problem found during the verification of a a schema.""" def __init__(self, message, path): self._message = message.format('\"{}\"'.format(path)) self._path = path @property def path(self): """The field path at which the format error was found.""" return self._path def __str__(self): return self._message class ValidationException(Exception): """Exception which is thrown in response to the failed validation of a document against it's associated schema.""" def __init__(self, errors): self._errors = errors @property def errors(self): """A dict containing the validation error(s) found at each field path.""" return self._errors def __str__(self): return repr(self._errors)
<commit_before> class SchemaFormatException(Exception): """Exception which encapsulates a problem found during the verification of a a schema.""" def __init__(self, message, path): self._message = message.format(path) self._path = path @property def path(self): """The field path at which the format error was found.""" return self._path def __str__(self): return self._message class ValidationException(Exception): """Exception which is thrown in response to the failed validation of a document against it's associated schema.""" def __init__(self, errors): self._errors = errors @property def errors(self): """A dict containing the validation error(s) found at each field path.""" return self._errors def __str__(self): return repr(self._errors) <commit_msg>Improve formatting of schema format exception messages<commit_after> class SchemaFormatException(Exception): """Exception which encapsulates a problem found during the verification of a a schema.""" def __init__(self, message, path): self._message = message.format('\"{}\"'.format(path)) self._path = path @property def path(self): """The field path at which the format error was found.""" return self._path def __str__(self): return self._message class ValidationException(Exception): """Exception which is thrown in response to the failed validation of a document against it's associated schema.""" def __init__(self, errors): self._errors = errors @property def errors(self): """A dict containing the validation error(s) found at each field path.""" return self._errors def __str__(self): return repr(self._errors)
2823b35d3bf3d521ae3c9769e2696455bbed8318
scriptorium/config.py
scriptorium/config.py
#!/usr/bin/env python """Configuration related functionality for scriptorium.""" import os import yaml import scriptorium _DEFAULT_DIR = os.path.join(os.path.expanduser("~"), '.scriptorium') _CFG_FILE = os.path.join(_DEFAULT_DIR, 'config') _DEFAULT_CFG = { 'TEMPLATE_DIR': os.path.join(_DEFAULT_DIR, 'templates'), 'LATEX_CMD': 'xelatex' } def read_config(): """Read configuration values for scriptorium.""" try: with open(_CFG_FILE, 'Ur') as cfg_fp: cfg = yaml.load(cfg_fp) scriptorium.CONFIG.update(cfg) except EnvironmentError: if not os.path.exists(scriptorium.CONFIG['TEMPLATE_DIR']): os.makedirs(scriptorium.CONFIG['TEMPLATE_DIR']) #Save configuration from first time save_config() def save_config(): """Save configuration values for scriptorium.""" with open(_CFG_FILE, 'w') as cfg_fp: yaml.dump(scriptorium.CONFIG, cfg_fp)
#!/usr/bin/env python """Configuration related functionality for scriptorium.""" import os import yaml import scriptorium _DEFAULT_DIR = os.path.join(os.path.expanduser("~"), '.scriptorium') _CFG_FILE = os.path.join(_DEFAULT_DIR, 'config') _DEFAULT_CFG = { 'TEMPLATE_DIR': os.path.join(_DEFAULT_DIR, 'templates'), 'LATEX_CMD': 'xelatex' } def _sanitize_paths(cfg): """Ensure that paths in configuration options have ~ symbols expanded.""" cfg['TEMPLATE_DIR'] = os.path.expanduser(cfg['TEMPLATE_DIR']) def read_config(): """Read configuration values for scriptorium.""" try: with open(_CFG_FILE, 'Ur') as cfg_fp: cfg = yaml.load(cfg_fp) scriptorium.CONFIG.update(cfg) _sanitize_paths(scriptorium.CONFIG) except EnvironmentError: if not os.path.exists(scriptorium.CONFIG['TEMPLATE_DIR']): os.makedirs(scriptorium.CONFIG['TEMPLATE_DIR']) #Save configuration from first time save_config() def save_config(): """Save configuration values for scriptorium.""" _sanitize_paths(scriptorium.CONFIG) with open(_CFG_FILE, 'w') as cfg_fp: yaml.dump(scriptorium.CONFIG, cfg_fp)
Expand home directory wildcards to ensure path is valid
Expand home directory wildcards to ensure path is valid
Python
mit
jasedit/scriptorium,jasedit/papers_base
#!/usr/bin/env python """Configuration related functionality for scriptorium.""" import os import yaml import scriptorium _DEFAULT_DIR = os.path.join(os.path.expanduser("~"), '.scriptorium') _CFG_FILE = os.path.join(_DEFAULT_DIR, 'config') _DEFAULT_CFG = { 'TEMPLATE_DIR': os.path.join(_DEFAULT_DIR, 'templates'), 'LATEX_CMD': 'xelatex' } def read_config(): """Read configuration values for scriptorium.""" try: with open(_CFG_FILE, 'Ur') as cfg_fp: cfg = yaml.load(cfg_fp) scriptorium.CONFIG.update(cfg) except EnvironmentError: if not os.path.exists(scriptorium.CONFIG['TEMPLATE_DIR']): os.makedirs(scriptorium.CONFIG['TEMPLATE_DIR']) #Save configuration from first time save_config() def save_config(): """Save configuration values for scriptorium.""" with open(_CFG_FILE, 'w') as cfg_fp: yaml.dump(scriptorium.CONFIG, cfg_fp) Expand home directory wildcards to ensure path is valid
#!/usr/bin/env python """Configuration related functionality for scriptorium.""" import os import yaml import scriptorium _DEFAULT_DIR = os.path.join(os.path.expanduser("~"), '.scriptorium') _CFG_FILE = os.path.join(_DEFAULT_DIR, 'config') _DEFAULT_CFG = { 'TEMPLATE_DIR': os.path.join(_DEFAULT_DIR, 'templates'), 'LATEX_CMD': 'xelatex' } def _sanitize_paths(cfg): """Ensure that paths in configuration options have ~ symbols expanded.""" cfg['TEMPLATE_DIR'] = os.path.expanduser(cfg['TEMPLATE_DIR']) def read_config(): """Read configuration values for scriptorium.""" try: with open(_CFG_FILE, 'Ur') as cfg_fp: cfg = yaml.load(cfg_fp) scriptorium.CONFIG.update(cfg) _sanitize_paths(scriptorium.CONFIG) except EnvironmentError: if not os.path.exists(scriptorium.CONFIG['TEMPLATE_DIR']): os.makedirs(scriptorium.CONFIG['TEMPLATE_DIR']) #Save configuration from first time save_config() def save_config(): """Save configuration values for scriptorium.""" _sanitize_paths(scriptorium.CONFIG) with open(_CFG_FILE, 'w') as cfg_fp: yaml.dump(scriptorium.CONFIG, cfg_fp)
<commit_before>#!/usr/bin/env python """Configuration related functionality for scriptorium.""" import os import yaml import scriptorium _DEFAULT_DIR = os.path.join(os.path.expanduser("~"), '.scriptorium') _CFG_FILE = os.path.join(_DEFAULT_DIR, 'config') _DEFAULT_CFG = { 'TEMPLATE_DIR': os.path.join(_DEFAULT_DIR, 'templates'), 'LATEX_CMD': 'xelatex' } def read_config(): """Read configuration values for scriptorium.""" try: with open(_CFG_FILE, 'Ur') as cfg_fp: cfg = yaml.load(cfg_fp) scriptorium.CONFIG.update(cfg) except EnvironmentError: if not os.path.exists(scriptorium.CONFIG['TEMPLATE_DIR']): os.makedirs(scriptorium.CONFIG['TEMPLATE_DIR']) #Save configuration from first time save_config() def save_config(): """Save configuration values for scriptorium.""" with open(_CFG_FILE, 'w') as cfg_fp: yaml.dump(scriptorium.CONFIG, cfg_fp) <commit_msg>Expand home directory wildcards to ensure path is valid<commit_after>
#!/usr/bin/env python """Configuration related functionality for scriptorium.""" import os import yaml import scriptorium _DEFAULT_DIR = os.path.join(os.path.expanduser("~"), '.scriptorium') _CFG_FILE = os.path.join(_DEFAULT_DIR, 'config') _DEFAULT_CFG = { 'TEMPLATE_DIR': os.path.join(_DEFAULT_DIR, 'templates'), 'LATEX_CMD': 'xelatex' } def _sanitize_paths(cfg): """Ensure that paths in configuration options have ~ symbols expanded.""" cfg['TEMPLATE_DIR'] = os.path.expanduser(cfg['TEMPLATE_DIR']) def read_config(): """Read configuration values for scriptorium.""" try: with open(_CFG_FILE, 'Ur') as cfg_fp: cfg = yaml.load(cfg_fp) scriptorium.CONFIG.update(cfg) _sanitize_paths(scriptorium.CONFIG) except EnvironmentError: if not os.path.exists(scriptorium.CONFIG['TEMPLATE_DIR']): os.makedirs(scriptorium.CONFIG['TEMPLATE_DIR']) #Save configuration from first time save_config() def save_config(): """Save configuration values for scriptorium.""" _sanitize_paths(scriptorium.CONFIG) with open(_CFG_FILE, 'w') as cfg_fp: yaml.dump(scriptorium.CONFIG, cfg_fp)
#!/usr/bin/env python """Configuration related functionality for scriptorium.""" import os import yaml import scriptorium _DEFAULT_DIR = os.path.join(os.path.expanduser("~"), '.scriptorium') _CFG_FILE = os.path.join(_DEFAULT_DIR, 'config') _DEFAULT_CFG = { 'TEMPLATE_DIR': os.path.join(_DEFAULT_DIR, 'templates'), 'LATEX_CMD': 'xelatex' } def read_config(): """Read configuration values for scriptorium.""" try: with open(_CFG_FILE, 'Ur') as cfg_fp: cfg = yaml.load(cfg_fp) scriptorium.CONFIG.update(cfg) except EnvironmentError: if not os.path.exists(scriptorium.CONFIG['TEMPLATE_DIR']): os.makedirs(scriptorium.CONFIG['TEMPLATE_DIR']) #Save configuration from first time save_config() def save_config(): """Save configuration values for scriptorium.""" with open(_CFG_FILE, 'w') as cfg_fp: yaml.dump(scriptorium.CONFIG, cfg_fp) Expand home directory wildcards to ensure path is valid#!/usr/bin/env python """Configuration related functionality for scriptorium.""" import os import yaml import scriptorium _DEFAULT_DIR = os.path.join(os.path.expanduser("~"), '.scriptorium') _CFG_FILE = os.path.join(_DEFAULT_DIR, 'config') _DEFAULT_CFG = { 'TEMPLATE_DIR': os.path.join(_DEFAULT_DIR, 'templates'), 'LATEX_CMD': 'xelatex' } def _sanitize_paths(cfg): """Ensure that paths in configuration options have ~ symbols expanded.""" cfg['TEMPLATE_DIR'] = os.path.expanduser(cfg['TEMPLATE_DIR']) def read_config(): """Read configuration values for scriptorium.""" try: with open(_CFG_FILE, 'Ur') as cfg_fp: cfg = yaml.load(cfg_fp) scriptorium.CONFIG.update(cfg) _sanitize_paths(scriptorium.CONFIG) except EnvironmentError: if not os.path.exists(scriptorium.CONFIG['TEMPLATE_DIR']): os.makedirs(scriptorium.CONFIG['TEMPLATE_DIR']) #Save configuration from first time save_config() def save_config(): """Save configuration values for scriptorium.""" _sanitize_paths(scriptorium.CONFIG) with open(_CFG_FILE, 'w') as cfg_fp: yaml.dump(scriptorium.CONFIG, cfg_fp)
<commit_before>#!/usr/bin/env python """Configuration related functionality for scriptorium.""" import os import yaml import scriptorium _DEFAULT_DIR = os.path.join(os.path.expanduser("~"), '.scriptorium') _CFG_FILE = os.path.join(_DEFAULT_DIR, 'config') _DEFAULT_CFG = { 'TEMPLATE_DIR': os.path.join(_DEFAULT_DIR, 'templates'), 'LATEX_CMD': 'xelatex' } def read_config(): """Read configuration values for scriptorium.""" try: with open(_CFG_FILE, 'Ur') as cfg_fp: cfg = yaml.load(cfg_fp) scriptorium.CONFIG.update(cfg) except EnvironmentError: if not os.path.exists(scriptorium.CONFIG['TEMPLATE_DIR']): os.makedirs(scriptorium.CONFIG['TEMPLATE_DIR']) #Save configuration from first time save_config() def save_config(): """Save configuration values for scriptorium.""" with open(_CFG_FILE, 'w') as cfg_fp: yaml.dump(scriptorium.CONFIG, cfg_fp) <commit_msg>Expand home directory wildcards to ensure path is valid<commit_after>#!/usr/bin/env python """Configuration related functionality for scriptorium.""" import os import yaml import scriptorium _DEFAULT_DIR = os.path.join(os.path.expanduser("~"), '.scriptorium') _CFG_FILE = os.path.join(_DEFAULT_DIR, 'config') _DEFAULT_CFG = { 'TEMPLATE_DIR': os.path.join(_DEFAULT_DIR, 'templates'), 'LATEX_CMD': 'xelatex' } def _sanitize_paths(cfg): """Ensure that paths in configuration options have ~ symbols expanded.""" cfg['TEMPLATE_DIR'] = os.path.expanduser(cfg['TEMPLATE_DIR']) def read_config(): """Read configuration values for scriptorium.""" try: with open(_CFG_FILE, 'Ur') as cfg_fp: cfg = yaml.load(cfg_fp) scriptorium.CONFIG.update(cfg) _sanitize_paths(scriptorium.CONFIG) except EnvironmentError: if not os.path.exists(scriptorium.CONFIG['TEMPLATE_DIR']): os.makedirs(scriptorium.CONFIG['TEMPLATE_DIR']) #Save configuration from first time save_config() def save_config(): """Save configuration values for scriptorium.""" _sanitize_paths(scriptorium.CONFIG) with open(_CFG_FILE, 'w') as cfg_fp: yaml.dump(scriptorium.CONFIG, cfg_fp)
58915da451e59400d5f5a2a757c5af0919e87b61
buck-tools/onos_oar.py
buck-tools/onos_oar.py
#!/usr/bin/env python #FIXME Add license from zipfile import ZipFile def generateOar(output, files=[]): # Note this is not a compressed zip with ZipFile(output, 'w') as zip: for file, mvnCoords in files: filename = file.split('/')[-1] if mvnCoords == 'NONE': dest = filename else: groupId, artifactId, version = mvnCoords.split(':') groupId = groupId.replace('.', '/') extension = filename.split('.')[-1] if extension == 'jar': filename = '%s-%s.jar' % ( artifactId, version ) elif 'features.xml' in filename: filename = '%s-%s-features.xml' % ( artifactId, version ) dest = 'm2/%s/%s/%s/%s' % ( groupId, artifactId, version, filename ) zip.write(file, dest) if __name__ == '__main__': import sys if len(sys.argv) < 2: print 'USAGE' sys.exit(1) output = sys.argv[1] args = sys.argv[2:] if len(args) % 2 != 0: print 'There must be an even number of args: file mvn_coords' sys.exit(2) files = zip(*[iter(args)]*2) generateOar(output, files)
#!/usr/bin/env python #FIXME Add license from zipfile import ZipFile def generateOar(output, files=[]): # Note this is not a compressed zip with ZipFile(output, 'w') as zip: for file, mvnCoords in files: filename = file.split('/')[-1] if mvnCoords == 'NONE': dest = filename else: parts = mvnCoords.split(':') if len(parts) > 3: parts.insert(2, parts.pop()) # move version to the 3rd position groupId, artifactId, version = parts[0:3] groupId = groupId.replace('.', '/') extension = filename.split('.')[-1] if extension == 'jar': filename = '%s-%s.jar' % ( artifactId, version ) elif 'features.xml' in filename: filename = '%s-%s-features.xml' % ( artifactId, version ) dest = 'm2/%s/%s/%s/%s' % ( groupId, artifactId, version, filename ) zip.write(file, dest) if __name__ == '__main__': import sys if len(sys.argv) < 2: print 'USAGE' sys.exit(1) output = sys.argv[1] args = sys.argv[2:] if len(args) % 2 != 0: print 'There must be an even number of args: file mvn_coords' sys.exit(2) files = zip(*[iter(args)]*2) generateOar(output, files)
Allow OAR file rule to use non-OSGI jars
Allow OAR file rule to use non-OSGI jars Change-Id: If2a82bdb5b217270ca02760f1c6cfc6f8f0dc7da
Python
apache-2.0
y-higuchi/onos,donNewtonAlpha/onos,VinodKumarS-Huawei/ietf96yang,kuujo/onos,LorenzReinhart/ONOSnew,gkatsikas/onos,maheshraju-Huawei/actn,VinodKumarS-Huawei/ietf96yang,gkatsikas/onos,opennetworkinglab/onos,mengmoya/onos,osinstom/onos,sdnwiselab/onos,osinstom/onos,sdnwiselab/onos,LorenzReinhart/ONOSnew,y-higuchi/onos,LorenzReinhart/ONOSnew,sdnwiselab/onos,donNewtonAlpha/onos,osinstom/onos,opennetworkinglab/onos,gkatsikas/onos,opennetworkinglab/onos,oplinkoms/onos,oplinkoms/onos,kuujo/onos,kuujo/onos,sdnwiselab/onos,sdnwiselab/onos,opennetworkinglab/onos,maheshraju-Huawei/actn,y-higuchi/onos,VinodKumarS-Huawei/ietf96yang,Shashikanth-Huawei/bmp,LorenzReinhart/ONOSnew,oplinkoms/onos,kuujo/onos,maheshraju-Huawei/actn,oplinkoms/onos,oplinkoms/onos,gkatsikas/onos,mengmoya/onos,osinstom/onos,opennetworkinglab/onos,Shashikanth-Huawei/bmp,maheshraju-Huawei/actn,sdnwiselab/onos,donNewtonAlpha/onos,Shashikanth-Huawei/bmp,VinodKumarS-Huawei/ietf96yang,kuujo/onos,y-higuchi/onos,Shashikanth-Huawei/bmp,maheshraju-Huawei/actn,opennetworkinglab/onos,osinstom/onos,gkatsikas/onos,donNewtonAlpha/onos,kuujo/onos,LorenzReinhart/ONOSnew,donNewtonAlpha/onos,mengmoya/onos,gkatsikas/onos,VinodKumarS-Huawei/ietf96yang,oplinkoms/onos,mengmoya/onos,oplinkoms/onos,Shashikanth-Huawei/bmp,y-higuchi/onos,kuujo/onos,mengmoya/onos
#!/usr/bin/env python #FIXME Add license from zipfile import ZipFile def generateOar(output, files=[]): # Note this is not a compressed zip with ZipFile(output, 'w') as zip: for file, mvnCoords in files: filename = file.split('/')[-1] if mvnCoords == 'NONE': dest = filename else: groupId, artifactId, version = mvnCoords.split(':') groupId = groupId.replace('.', '/') extension = filename.split('.')[-1] if extension == 'jar': filename = '%s-%s.jar' % ( artifactId, version ) elif 'features.xml' in filename: filename = '%s-%s-features.xml' % ( artifactId, version ) dest = 'm2/%s/%s/%s/%s' % ( groupId, artifactId, version, filename ) zip.write(file, dest) if __name__ == '__main__': import sys if len(sys.argv) < 2: print 'USAGE' sys.exit(1) output = sys.argv[1] args = sys.argv[2:] if len(args) % 2 != 0: print 'There must be an even number of args: file mvn_coords' sys.exit(2) files = zip(*[iter(args)]*2) generateOar(output, files) Allow OAR file rule to use non-OSGI jars Change-Id: If2a82bdb5b217270ca02760f1c6cfc6f8f0dc7da
#!/usr/bin/env python #FIXME Add license from zipfile import ZipFile def generateOar(output, files=[]): # Note this is not a compressed zip with ZipFile(output, 'w') as zip: for file, mvnCoords in files: filename = file.split('/')[-1] if mvnCoords == 'NONE': dest = filename else: parts = mvnCoords.split(':') if len(parts) > 3: parts.insert(2, parts.pop()) # move version to the 3rd position groupId, artifactId, version = parts[0:3] groupId = groupId.replace('.', '/') extension = filename.split('.')[-1] if extension == 'jar': filename = '%s-%s.jar' % ( artifactId, version ) elif 'features.xml' in filename: filename = '%s-%s-features.xml' % ( artifactId, version ) dest = 'm2/%s/%s/%s/%s' % ( groupId, artifactId, version, filename ) zip.write(file, dest) if __name__ == '__main__': import sys if len(sys.argv) < 2: print 'USAGE' sys.exit(1) output = sys.argv[1] args = sys.argv[2:] if len(args) % 2 != 0: print 'There must be an even number of args: file mvn_coords' sys.exit(2) files = zip(*[iter(args)]*2) generateOar(output, files)
<commit_before>#!/usr/bin/env python #FIXME Add license from zipfile import ZipFile def generateOar(output, files=[]): # Note this is not a compressed zip with ZipFile(output, 'w') as zip: for file, mvnCoords in files: filename = file.split('/')[-1] if mvnCoords == 'NONE': dest = filename else: groupId, artifactId, version = mvnCoords.split(':') groupId = groupId.replace('.', '/') extension = filename.split('.')[-1] if extension == 'jar': filename = '%s-%s.jar' % ( artifactId, version ) elif 'features.xml' in filename: filename = '%s-%s-features.xml' % ( artifactId, version ) dest = 'm2/%s/%s/%s/%s' % ( groupId, artifactId, version, filename ) zip.write(file, dest) if __name__ == '__main__': import sys if len(sys.argv) < 2: print 'USAGE' sys.exit(1) output = sys.argv[1] args = sys.argv[2:] if len(args) % 2 != 0: print 'There must be an even number of args: file mvn_coords' sys.exit(2) files = zip(*[iter(args)]*2) generateOar(output, files) <commit_msg>Allow OAR file rule to use non-OSGI jars Change-Id: If2a82bdb5b217270ca02760f1c6cfc6f8f0dc7da<commit_after>
#!/usr/bin/env python #FIXME Add license from zipfile import ZipFile def generateOar(output, files=[]): # Note this is not a compressed zip with ZipFile(output, 'w') as zip: for file, mvnCoords in files: filename = file.split('/')[-1] if mvnCoords == 'NONE': dest = filename else: parts = mvnCoords.split(':') if len(parts) > 3: parts.insert(2, parts.pop()) # move version to the 3rd position groupId, artifactId, version = parts[0:3] groupId = groupId.replace('.', '/') extension = filename.split('.')[-1] if extension == 'jar': filename = '%s-%s.jar' % ( artifactId, version ) elif 'features.xml' in filename: filename = '%s-%s-features.xml' % ( artifactId, version ) dest = 'm2/%s/%s/%s/%s' % ( groupId, artifactId, version, filename ) zip.write(file, dest) if __name__ == '__main__': import sys if len(sys.argv) < 2: print 'USAGE' sys.exit(1) output = sys.argv[1] args = sys.argv[2:] if len(args) % 2 != 0: print 'There must be an even number of args: file mvn_coords' sys.exit(2) files = zip(*[iter(args)]*2) generateOar(output, files)
#!/usr/bin/env python #FIXME Add license from zipfile import ZipFile def generateOar(output, files=[]): # Note this is not a compressed zip with ZipFile(output, 'w') as zip: for file, mvnCoords in files: filename = file.split('/')[-1] if mvnCoords == 'NONE': dest = filename else: groupId, artifactId, version = mvnCoords.split(':') groupId = groupId.replace('.', '/') extension = filename.split('.')[-1] if extension == 'jar': filename = '%s-%s.jar' % ( artifactId, version ) elif 'features.xml' in filename: filename = '%s-%s-features.xml' % ( artifactId, version ) dest = 'm2/%s/%s/%s/%s' % ( groupId, artifactId, version, filename ) zip.write(file, dest) if __name__ == '__main__': import sys if len(sys.argv) < 2: print 'USAGE' sys.exit(1) output = sys.argv[1] args = sys.argv[2:] if len(args) % 2 != 0: print 'There must be an even number of args: file mvn_coords' sys.exit(2) files = zip(*[iter(args)]*2) generateOar(output, files) Allow OAR file rule to use non-OSGI jars Change-Id: If2a82bdb5b217270ca02760f1c6cfc6f8f0dc7da#!/usr/bin/env python #FIXME Add license from zipfile import ZipFile def generateOar(output, files=[]): # Note this is not a compressed zip with ZipFile(output, 'w') as zip: for file, mvnCoords in files: filename = file.split('/')[-1] if mvnCoords == 'NONE': dest = filename else: parts = mvnCoords.split(':') if len(parts) > 3: parts.insert(2, parts.pop()) # move version to the 3rd position groupId, artifactId, version = parts[0:3] groupId = groupId.replace('.', '/') extension = filename.split('.')[-1] if extension == 'jar': filename = '%s-%s.jar' % ( artifactId, version ) elif 'features.xml' in filename: filename = '%s-%s-features.xml' % ( artifactId, version ) dest = 'm2/%s/%s/%s/%s' % ( groupId, artifactId, version, filename ) zip.write(file, dest) if __name__ == '__main__': import sys if len(sys.argv) < 2: print 'USAGE' sys.exit(1) output = sys.argv[1] args = sys.argv[2:] if len(args) % 2 != 0: print 'There must be an even number of args: file mvn_coords' sys.exit(2) files = zip(*[iter(args)]*2) generateOar(output, files)
<commit_before>#!/usr/bin/env python #FIXME Add license from zipfile import ZipFile def generateOar(output, files=[]): # Note this is not a compressed zip with ZipFile(output, 'w') as zip: for file, mvnCoords in files: filename = file.split('/')[-1] if mvnCoords == 'NONE': dest = filename else: groupId, artifactId, version = mvnCoords.split(':') groupId = groupId.replace('.', '/') extension = filename.split('.')[-1] if extension == 'jar': filename = '%s-%s.jar' % ( artifactId, version ) elif 'features.xml' in filename: filename = '%s-%s-features.xml' % ( artifactId, version ) dest = 'm2/%s/%s/%s/%s' % ( groupId, artifactId, version, filename ) zip.write(file, dest) if __name__ == '__main__': import sys if len(sys.argv) < 2: print 'USAGE' sys.exit(1) output = sys.argv[1] args = sys.argv[2:] if len(args) % 2 != 0: print 'There must be an even number of args: file mvn_coords' sys.exit(2) files = zip(*[iter(args)]*2) generateOar(output, files) <commit_msg>Allow OAR file rule to use non-OSGI jars Change-Id: If2a82bdb5b217270ca02760f1c6cfc6f8f0dc7da<commit_after>#!/usr/bin/env python #FIXME Add license from zipfile import ZipFile def generateOar(output, files=[]): # Note this is not a compressed zip with ZipFile(output, 'w') as zip: for file, mvnCoords in files: filename = file.split('/')[-1] if mvnCoords == 'NONE': dest = filename else: parts = mvnCoords.split(':') if len(parts) > 3: parts.insert(2, parts.pop()) # move version to the 3rd position groupId, artifactId, version = parts[0:3] groupId = groupId.replace('.', '/') extension = filename.split('.')[-1] if extension == 'jar': filename = '%s-%s.jar' % ( artifactId, version ) elif 'features.xml' in filename: filename = '%s-%s-features.xml' % ( artifactId, version ) dest = 'm2/%s/%s/%s/%s' % ( groupId, artifactId, version, filename ) zip.write(file, dest) if __name__ == '__main__': import sys if len(sys.argv) < 2: print 'USAGE' sys.exit(1) output = sys.argv[1] args = sys.argv[2:] if len(args) % 2 != 0: print 'There must be an even number of args: file mvn_coords' sys.exit(2) files = zip(*[iter(args)]*2) generateOar(output, files)
2d57d87b15c73fe1f9b884dc57ecf2c25a5e7454
tensorflow_probability/python/internal/backend/numpy/tensor_spec.py
tensorflow_probability/python/internal/backend/numpy/tensor_spec.py
# Copyright 2021 The TensorFlow Probability Authors. # # 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. # ============================================================================ """Numpy stub for `tensor_spec`.""" __all__ = [ 'TensorSpec', ] class DenseSpec(object): def __init__(self, shape, dtype, name=None): self.shape = shape self.dtype = dtype self.name = name def __repr__(self): return '{}(shape={}, dtype={}, name={})'.format( type(self).__name__, self.shape, repr(self.dtype), repr(self.name)) class TensorSpec(DenseSpec): pass
# Copyright 2021 The TensorFlow Probability Authors. # # 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. # ============================================================================ """Numpy stub for `tensor_spec`.""" from tensorflow_probability.python.internal.backend.numpy.ops import _convert_to_tensor __all__ = [ 'TensorSpec', ] class DenseSpec(object): def __init__(self, shape, dtype, name=None): self.shape = shape self.dtype = dtype self.name = name def __repr__(self): return '{}(shape={}, dtype={}, name={})'.format( type(self).__name__, self.shape, repr(self.dtype), repr(self.name)) class TensorSpec(DenseSpec): @classmethod def from_tensor(cls, tensor, name=None): tensor = _convert_to_tensor(tensor) return cls(tensor.shape, tensor.dtype, name)
Add `from_tensor` classmethod to `TensorSpec` in the Numpy backend.
Add `from_tensor` classmethod to `TensorSpec` in the Numpy backend. PiperOrigin-RevId: 466171774
Python
apache-2.0
tensorflow/probability,tensorflow/probability
# Copyright 2021 The TensorFlow Probability Authors. # # 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. # ============================================================================ """Numpy stub for `tensor_spec`.""" __all__ = [ 'TensorSpec', ] class DenseSpec(object): def __init__(self, shape, dtype, name=None): self.shape = shape self.dtype = dtype self.name = name def __repr__(self): return '{}(shape={}, dtype={}, name={})'.format( type(self).__name__, self.shape, repr(self.dtype), repr(self.name)) class TensorSpec(DenseSpec): pass Add `from_tensor` classmethod to `TensorSpec` in the Numpy backend. PiperOrigin-RevId: 466171774
# Copyright 2021 The TensorFlow Probability Authors. # # 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. # ============================================================================ """Numpy stub for `tensor_spec`.""" from tensorflow_probability.python.internal.backend.numpy.ops import _convert_to_tensor __all__ = [ 'TensorSpec', ] class DenseSpec(object): def __init__(self, shape, dtype, name=None): self.shape = shape self.dtype = dtype self.name = name def __repr__(self): return '{}(shape={}, dtype={}, name={})'.format( type(self).__name__, self.shape, repr(self.dtype), repr(self.name)) class TensorSpec(DenseSpec): @classmethod def from_tensor(cls, tensor, name=None): tensor = _convert_to_tensor(tensor) return cls(tensor.shape, tensor.dtype, name)
<commit_before># Copyright 2021 The TensorFlow Probability Authors. # # 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. # ============================================================================ """Numpy stub for `tensor_spec`.""" __all__ = [ 'TensorSpec', ] class DenseSpec(object): def __init__(self, shape, dtype, name=None): self.shape = shape self.dtype = dtype self.name = name def __repr__(self): return '{}(shape={}, dtype={}, name={})'.format( type(self).__name__, self.shape, repr(self.dtype), repr(self.name)) class TensorSpec(DenseSpec): pass <commit_msg>Add `from_tensor` classmethod to `TensorSpec` in the Numpy backend. PiperOrigin-RevId: 466171774<commit_after>
# Copyright 2021 The TensorFlow Probability Authors. # # 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. # ============================================================================ """Numpy stub for `tensor_spec`.""" from tensorflow_probability.python.internal.backend.numpy.ops import _convert_to_tensor __all__ = [ 'TensorSpec', ] class DenseSpec(object): def __init__(self, shape, dtype, name=None): self.shape = shape self.dtype = dtype self.name = name def __repr__(self): return '{}(shape={}, dtype={}, name={})'.format( type(self).__name__, self.shape, repr(self.dtype), repr(self.name)) class TensorSpec(DenseSpec): @classmethod def from_tensor(cls, tensor, name=None): tensor = _convert_to_tensor(tensor) return cls(tensor.shape, tensor.dtype, name)
# Copyright 2021 The TensorFlow Probability Authors. # # 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. # ============================================================================ """Numpy stub for `tensor_spec`.""" __all__ = [ 'TensorSpec', ] class DenseSpec(object): def __init__(self, shape, dtype, name=None): self.shape = shape self.dtype = dtype self.name = name def __repr__(self): return '{}(shape={}, dtype={}, name={})'.format( type(self).__name__, self.shape, repr(self.dtype), repr(self.name)) class TensorSpec(DenseSpec): pass Add `from_tensor` classmethod to `TensorSpec` in the Numpy backend. PiperOrigin-RevId: 466171774# Copyright 2021 The TensorFlow Probability Authors. # # 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. # ============================================================================ """Numpy stub for `tensor_spec`.""" from tensorflow_probability.python.internal.backend.numpy.ops import _convert_to_tensor __all__ = [ 'TensorSpec', ] class DenseSpec(object): def __init__(self, shape, dtype, name=None): self.shape = shape self.dtype = dtype self.name = name def __repr__(self): return '{}(shape={}, dtype={}, name={})'.format( type(self).__name__, self.shape, repr(self.dtype), repr(self.name)) class TensorSpec(DenseSpec): @classmethod def from_tensor(cls, tensor, name=None): tensor = _convert_to_tensor(tensor) return cls(tensor.shape, tensor.dtype, name)
<commit_before># Copyright 2021 The TensorFlow Probability Authors. # # 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. # ============================================================================ """Numpy stub for `tensor_spec`.""" __all__ = [ 'TensorSpec', ] class DenseSpec(object): def __init__(self, shape, dtype, name=None): self.shape = shape self.dtype = dtype self.name = name def __repr__(self): return '{}(shape={}, dtype={}, name={})'.format( type(self).__name__, self.shape, repr(self.dtype), repr(self.name)) class TensorSpec(DenseSpec): pass <commit_msg>Add `from_tensor` classmethod to `TensorSpec` in the Numpy backend. PiperOrigin-RevId: 466171774<commit_after># Copyright 2021 The TensorFlow Probability Authors. # # 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. # ============================================================================ """Numpy stub for `tensor_spec`.""" from tensorflow_probability.python.internal.backend.numpy.ops import _convert_to_tensor __all__ = [ 'TensorSpec', ] class DenseSpec(object): def __init__(self, shape, dtype, name=None): self.shape = shape self.dtype = dtype self.name = name def __repr__(self): return '{}(shape={}, dtype={}, name={})'.format( type(self).__name__, self.shape, repr(self.dtype), repr(self.name)) class TensorSpec(DenseSpec): @classmethod def from_tensor(cls, tensor, name=None): tensor = _convert_to_tensor(tensor) return cls(tensor.shape, tensor.dtype, name)
311e02e13bf7ffd9f138fb562b02d51283e89abd
wheel_cms/settings/production.py
wheel_cms/settings/production.py
from settings.base import * from wheelcms_project.settings.base.util import get_env_variable if not DATABASE_URL: PG_DEFAULT_DB = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': get_env_variable('DB_NAME'), 'USER': get_env_variable('DB_USER'), 'PASSWORD': get_env_variable('DB_PASSWORD'), 'HOST': get_env_variable('DB_HOST', 'localhost'), 'PORT': get_env_variable('DB_PORT', ''), } DATABASES = { 'default': PG_DEFAULT_DB } DEBUG=False STRACKS_URL = get_env_variable('STRACKS_URL', '') STRACKS_CONNECTOR = None if STRACKS_URL: from stracks_api.connector import ASyncHTTPConnector STRACKS_CONNECTOR = ASyncHTTPConnector(STRACKS_URL) MIDDLEWARE_CLASSES += ( 'stracks_api.middleware.StracksMiddleware', )
from settings.base import * from wheelcms_project.settings.base.util import get_env_variable DEBUG=False STRACKS_URL = get_env_variable('STRACKS_URL', '') STRACKS_CONNECTOR = None if STRACKS_URL: from stracks_api.connector import ASyncHTTPConnector STRACKS_CONNECTOR = ASyncHTTPConnector(STRACKS_URL) MIDDLEWARE_CLASSES += ( 'stracks_api.middleware.StracksMiddleware', )
Remove old style db config
Remove old style db config
Python
bsd-2-clause
wheelcms/wheel-site,wheelcms/wheel-site
from settings.base import * from wheelcms_project.settings.base.util import get_env_variable if not DATABASE_URL: PG_DEFAULT_DB = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': get_env_variable('DB_NAME'), 'USER': get_env_variable('DB_USER'), 'PASSWORD': get_env_variable('DB_PASSWORD'), 'HOST': get_env_variable('DB_HOST', 'localhost'), 'PORT': get_env_variable('DB_PORT', ''), } DATABASES = { 'default': PG_DEFAULT_DB } DEBUG=False STRACKS_URL = get_env_variable('STRACKS_URL', '') STRACKS_CONNECTOR = None if STRACKS_URL: from stracks_api.connector import ASyncHTTPConnector STRACKS_CONNECTOR = ASyncHTTPConnector(STRACKS_URL) MIDDLEWARE_CLASSES += ( 'stracks_api.middleware.StracksMiddleware', ) Remove old style db config
from settings.base import * from wheelcms_project.settings.base.util import get_env_variable DEBUG=False STRACKS_URL = get_env_variable('STRACKS_URL', '') STRACKS_CONNECTOR = None if STRACKS_URL: from stracks_api.connector import ASyncHTTPConnector STRACKS_CONNECTOR = ASyncHTTPConnector(STRACKS_URL) MIDDLEWARE_CLASSES += ( 'stracks_api.middleware.StracksMiddleware', )
<commit_before>from settings.base import * from wheelcms_project.settings.base.util import get_env_variable if not DATABASE_URL: PG_DEFAULT_DB = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': get_env_variable('DB_NAME'), 'USER': get_env_variable('DB_USER'), 'PASSWORD': get_env_variable('DB_PASSWORD'), 'HOST': get_env_variable('DB_HOST', 'localhost'), 'PORT': get_env_variable('DB_PORT', ''), } DATABASES = { 'default': PG_DEFAULT_DB } DEBUG=False STRACKS_URL = get_env_variable('STRACKS_URL', '') STRACKS_CONNECTOR = None if STRACKS_URL: from stracks_api.connector import ASyncHTTPConnector STRACKS_CONNECTOR = ASyncHTTPConnector(STRACKS_URL) MIDDLEWARE_CLASSES += ( 'stracks_api.middleware.StracksMiddleware', ) <commit_msg>Remove old style db config<commit_after>
from settings.base import * from wheelcms_project.settings.base.util import get_env_variable DEBUG=False STRACKS_URL = get_env_variable('STRACKS_URL', '') STRACKS_CONNECTOR = None if STRACKS_URL: from stracks_api.connector import ASyncHTTPConnector STRACKS_CONNECTOR = ASyncHTTPConnector(STRACKS_URL) MIDDLEWARE_CLASSES += ( 'stracks_api.middleware.StracksMiddleware', )
from settings.base import * from wheelcms_project.settings.base.util import get_env_variable if not DATABASE_URL: PG_DEFAULT_DB = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': get_env_variable('DB_NAME'), 'USER': get_env_variable('DB_USER'), 'PASSWORD': get_env_variable('DB_PASSWORD'), 'HOST': get_env_variable('DB_HOST', 'localhost'), 'PORT': get_env_variable('DB_PORT', ''), } DATABASES = { 'default': PG_DEFAULT_DB } DEBUG=False STRACKS_URL = get_env_variable('STRACKS_URL', '') STRACKS_CONNECTOR = None if STRACKS_URL: from stracks_api.connector import ASyncHTTPConnector STRACKS_CONNECTOR = ASyncHTTPConnector(STRACKS_URL) MIDDLEWARE_CLASSES += ( 'stracks_api.middleware.StracksMiddleware', ) Remove old style db configfrom settings.base import * from wheelcms_project.settings.base.util import get_env_variable DEBUG=False STRACKS_URL = get_env_variable('STRACKS_URL', '') STRACKS_CONNECTOR = None if STRACKS_URL: from stracks_api.connector import ASyncHTTPConnector STRACKS_CONNECTOR = ASyncHTTPConnector(STRACKS_URL) MIDDLEWARE_CLASSES += ( 'stracks_api.middleware.StracksMiddleware', )
<commit_before>from settings.base import * from wheelcms_project.settings.base.util import get_env_variable if not DATABASE_URL: PG_DEFAULT_DB = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': get_env_variable('DB_NAME'), 'USER': get_env_variable('DB_USER'), 'PASSWORD': get_env_variable('DB_PASSWORD'), 'HOST': get_env_variable('DB_HOST', 'localhost'), 'PORT': get_env_variable('DB_PORT', ''), } DATABASES = { 'default': PG_DEFAULT_DB } DEBUG=False STRACKS_URL = get_env_variable('STRACKS_URL', '') STRACKS_CONNECTOR = None if STRACKS_URL: from stracks_api.connector import ASyncHTTPConnector STRACKS_CONNECTOR = ASyncHTTPConnector(STRACKS_URL) MIDDLEWARE_CLASSES += ( 'stracks_api.middleware.StracksMiddleware', ) <commit_msg>Remove old style db config<commit_after>from settings.base import * from wheelcms_project.settings.base.util import get_env_variable DEBUG=False STRACKS_URL = get_env_variable('STRACKS_URL', '') STRACKS_CONNECTOR = None if STRACKS_URL: from stracks_api.connector import ASyncHTTPConnector STRACKS_CONNECTOR = ASyncHTTPConnector(STRACKS_URL) MIDDLEWARE_CLASSES += ( 'stracks_api.middleware.StracksMiddleware', )
ba5bfeb652804e57203b1794c6293b8227590ac1
pyinstalive/logger.py
pyinstalive/logger.py
def colors(state): color = '' if (state == 'BLUE'): color = '\033[94m' if (state == 'GREEN'): color = '\033[92m' if (state == 'YELLOW'): color = '\033[93m' if (state == 'RED'): color = '\033[91m' if (state == 'ENDC'): color = '\033[0m' if (state == 'WHITE'): color = '\033[0m' return color def log(string, color): print('\033[1m' + colors(color) + string + colors("ENDC")) def seperator(color): print('\033[1m' + colors(color) + ("-" * 50) + colors("ENDC"))
import sys import os def colors(state): color = '' if (state == 'BLUE'): color = '\033[94m' if (state == 'GREEN'): color = '\033[92m' if (state == 'YELLOW'): color = '\033[93m' if (state == 'RED'): color = '\033[91m' if (state == 'ENDC'): color = '\033[0m' if (state == 'WHITE'): color = '\033[0m' return color def supports_color(): """ from https://github.com/django/django/blob/master/django/core/management/color.py Return True if the running system's terminal supports color, and False otherwise. """ plat = sys.platform supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 'ANSICON' in os.environ) # isatty is not always implemented, #6223. is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() if not supported_platform or not is_a_tty: return False return True def log(string, color): if not supports_color(): print(string) else: print('\033[1m' + colors(color) + string + colors("ENDC")) def seperator(color): if not supports_color(): print("-" * 50) else: print('\033[1m' + colors(color) + ("-" * 50) + colors("ENDC"))
Add proper logging support for consoles that don't accept ANSI
Add proper logging support for consoles that don't accept ANSI
Python
mit
notcammy/PyInstaLive
def colors(state): color = '' if (state == 'BLUE'): color = '\033[94m' if (state == 'GREEN'): color = '\033[92m' if (state == 'YELLOW'): color = '\033[93m' if (state == 'RED'): color = '\033[91m' if (state == 'ENDC'): color = '\033[0m' if (state == 'WHITE'): color = '\033[0m' return color def log(string, color): print('\033[1m' + colors(color) + string + colors("ENDC")) def seperator(color): print('\033[1m' + colors(color) + ("-" * 50) + colors("ENDC"))Add proper logging support for consoles that don't accept ANSI
import sys import os def colors(state): color = '' if (state == 'BLUE'): color = '\033[94m' if (state == 'GREEN'): color = '\033[92m' if (state == 'YELLOW'): color = '\033[93m' if (state == 'RED'): color = '\033[91m' if (state == 'ENDC'): color = '\033[0m' if (state == 'WHITE'): color = '\033[0m' return color def supports_color(): """ from https://github.com/django/django/blob/master/django/core/management/color.py Return True if the running system's terminal supports color, and False otherwise. """ plat = sys.platform supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 'ANSICON' in os.environ) # isatty is not always implemented, #6223. is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() if not supported_platform or not is_a_tty: return False return True def log(string, color): if not supports_color(): print(string) else: print('\033[1m' + colors(color) + string + colors("ENDC")) def seperator(color): if not supports_color(): print("-" * 50) else: print('\033[1m' + colors(color) + ("-" * 50) + colors("ENDC"))
<commit_before>def colors(state): color = '' if (state == 'BLUE'): color = '\033[94m' if (state == 'GREEN'): color = '\033[92m' if (state == 'YELLOW'): color = '\033[93m' if (state == 'RED'): color = '\033[91m' if (state == 'ENDC'): color = '\033[0m' if (state == 'WHITE'): color = '\033[0m' return color def log(string, color): print('\033[1m' + colors(color) + string + colors("ENDC")) def seperator(color): print('\033[1m' + colors(color) + ("-" * 50) + colors("ENDC"))<commit_msg>Add proper logging support for consoles that don't accept ANSI<commit_after>
import sys import os def colors(state): color = '' if (state == 'BLUE'): color = '\033[94m' if (state == 'GREEN'): color = '\033[92m' if (state == 'YELLOW'): color = '\033[93m' if (state == 'RED'): color = '\033[91m' if (state == 'ENDC'): color = '\033[0m' if (state == 'WHITE'): color = '\033[0m' return color def supports_color(): """ from https://github.com/django/django/blob/master/django/core/management/color.py Return True if the running system's terminal supports color, and False otherwise. """ plat = sys.platform supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 'ANSICON' in os.environ) # isatty is not always implemented, #6223. is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() if not supported_platform or not is_a_tty: return False return True def log(string, color): if not supports_color(): print(string) else: print('\033[1m' + colors(color) + string + colors("ENDC")) def seperator(color): if not supports_color(): print("-" * 50) else: print('\033[1m' + colors(color) + ("-" * 50) + colors("ENDC"))
def colors(state): color = '' if (state == 'BLUE'): color = '\033[94m' if (state == 'GREEN'): color = '\033[92m' if (state == 'YELLOW'): color = '\033[93m' if (state == 'RED'): color = '\033[91m' if (state == 'ENDC'): color = '\033[0m' if (state == 'WHITE'): color = '\033[0m' return color def log(string, color): print('\033[1m' + colors(color) + string + colors("ENDC")) def seperator(color): print('\033[1m' + colors(color) + ("-" * 50) + colors("ENDC"))Add proper logging support for consoles that don't accept ANSIimport sys import os def colors(state): color = '' if (state == 'BLUE'): color = '\033[94m' if (state == 'GREEN'): color = '\033[92m' if (state == 'YELLOW'): color = '\033[93m' if (state == 'RED'): color = '\033[91m' if (state == 'ENDC'): color = '\033[0m' if (state == 'WHITE'): color = '\033[0m' return color def supports_color(): """ from https://github.com/django/django/blob/master/django/core/management/color.py Return True if the running system's terminal supports color, and False otherwise. """ plat = sys.platform supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 'ANSICON' in os.environ) # isatty is not always implemented, #6223. is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() if not supported_platform or not is_a_tty: return False return True def log(string, color): if not supports_color(): print(string) else: print('\033[1m' + colors(color) + string + colors("ENDC")) def seperator(color): if not supports_color(): print("-" * 50) else: print('\033[1m' + colors(color) + ("-" * 50) + colors("ENDC"))
<commit_before>def colors(state): color = '' if (state == 'BLUE'): color = '\033[94m' if (state == 'GREEN'): color = '\033[92m' if (state == 'YELLOW'): color = '\033[93m' if (state == 'RED'): color = '\033[91m' if (state == 'ENDC'): color = '\033[0m' if (state == 'WHITE'): color = '\033[0m' return color def log(string, color): print('\033[1m' + colors(color) + string + colors("ENDC")) def seperator(color): print('\033[1m' + colors(color) + ("-" * 50) + colors("ENDC"))<commit_msg>Add proper logging support for consoles that don't accept ANSI<commit_after>import sys import os def colors(state): color = '' if (state == 'BLUE'): color = '\033[94m' if (state == 'GREEN'): color = '\033[92m' if (state == 'YELLOW'): color = '\033[93m' if (state == 'RED'): color = '\033[91m' if (state == 'ENDC'): color = '\033[0m' if (state == 'WHITE'): color = '\033[0m' return color def supports_color(): """ from https://github.com/django/django/blob/master/django/core/management/color.py Return True if the running system's terminal supports color, and False otherwise. """ plat = sys.platform supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 'ANSICON' in os.environ) # isatty is not always implemented, #6223. is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() if not supported_platform or not is_a_tty: return False return True def log(string, color): if not supports_color(): print(string) else: print('\033[1m' + colors(color) + string + colors("ENDC")) def seperator(color): if not supports_color(): print("-" * 50) else: print('\033[1m' + colors(color) + ("-" * 50) + colors("ENDC"))