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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
18ec52a1c34e263e4d909fc1ee19500f9adac26b
|
examples/django_example/example/app/models.py
|
examples/django_example/example/app/models.py
|
from django.db import models
# Create your models here.
|
# Define a custom User class to work with django-social-auth
from django.contrib.auth.models import AbstractUser, UserManager
class CustomUser(AbstractUser):
objects = UserManager()
|
Define a custom user model
|
Define a custom user model
|
Python
|
bsd-3-clause
|
S01780/python-social-auth,tobias47n9e/social-core,falcon1kr/python-social-auth,ByteInternet/python-social-auth,muhammad-ammar/python-social-auth,contracode/python-social-auth,S01780/python-social-auth,clef/python-social-auth,lawrence34/python-social-auth,python-social-auth/social-storage-sqlalchemy,fearlessspider/python-social-auth,MSOpenTech/python-social-auth,Andygmb/python-social-auth,mrwags/python-social-auth,ariestiyansyah/python-social-auth,clef/python-social-auth,bjorand/python-social-auth,cjltsod/python-social-auth,barseghyanartur/python-social-auth,nirmalvp/python-social-auth,Andygmb/python-social-auth,garrett-schlesinger/python-social-auth,henocdz/python-social-auth,VishvajitP/python-social-auth,duoduo369/python-social-auth,merutak/python-social-auth,drxos/python-social-auth,firstjob/python-social-auth,webjunkie/python-social-auth,DhiaEddineSaidi/python-social-auth,python-social-auth/social-app-django,barseghyanartur/python-social-auth,rsteca/python-social-auth,jneves/python-social-auth,mrwags/python-social-auth,mrwags/python-social-auth,frankier/python-social-auth,JJediny/python-social-auth,joelstanner/python-social-auth,lamby/python-social-auth,bjorand/python-social-auth,python-social-auth/social-core,chandolia/python-social-auth,jeyraof/python-social-auth,cmichal/python-social-auth,falcon1kr/python-social-auth,robbiet480/python-social-auth,contracode/python-social-auth,lawrence34/python-social-auth,yprez/python-social-auth,bjorand/python-social-auth,garrett-schlesinger/python-social-auth,clef/python-social-auth,python-social-auth/social-app-django,jameslittle/python-social-auth,tkajtoch/python-social-auth,python-social-auth/social-app-django,JerzySpendel/python-social-auth,muhammad-ammar/python-social-auth,msampathkumar/python-social-auth,webjunkie/python-social-auth,mark-adams/python-social-auth,iruga090/python-social-auth,contracode/python-social-auth,JJediny/python-social-auth,lamby/python-social-auth,cmichal/python-social-auth,alrusdi/python-social-auth,python-social-auth/social-docs,yprez/python-social-auth,san-mate/python-social-auth,jeyraof/python-social-auth,ononeor12/python-social-auth,jneves/python-social-auth,lawrence34/python-social-auth,DhiaEddineSaidi/python-social-auth,python-social-auth/social-app-cherrypy,michael-borisov/python-social-auth,SeanHayes/python-social-auth,lneoe/python-social-auth,joelstanner/python-social-auth,duoduo369/python-social-auth,lneoe/python-social-auth,fearlessspider/python-social-auth,chandolia/python-social-auth,hsr-ba-fs15-dat/python-social-auth,daniula/python-social-auth,VishvajitP/python-social-auth,daniula/python-social-auth,alrusdi/python-social-auth,mark-adams/python-social-auth,barseghyanartur/python-social-auth,rsalmaso/python-social-auth,mathspace/python-social-auth,JJediny/python-social-auth,michael-borisov/python-social-auth,san-mate/python-social-auth,lneoe/python-social-auth,jameslittle/python-social-auth,rsteca/python-social-auth,henocdz/python-social-auth,S01780/python-social-auth,tkajtoch/python-social-auth,tutumcloud/python-social-auth,michael-borisov/python-social-auth,JerzySpendel/python-social-auth,degs098/python-social-auth,robbiet480/python-social-auth,rsalmaso/python-social-auth,nirmalvp/python-social-auth,falcon1kr/python-social-auth,python-social-auth/social-core,ariestiyansyah/python-social-auth,ariestiyansyah/python-social-auth,ByteInternet/python-social-auth,hsr-ba-fs15-dat/python-social-auth,nirmalvp/python-social-auth,DhiaEddineSaidi/python-social-auth,joelstanner/python-social-auth,ononeor12/python-social-auth,wildtetris/python-social-auth,henocdz/python-social-auth,mathspace/python-social-auth,MSOpenTech/python-social-auth,wildtetris/python-social-auth,degs098/python-social-auth,noodle-learns-programming/python-social-auth,SeanHayes/python-social-auth,mchdks/python-social-auth,lamby/python-social-auth,merutak/python-social-auth,jneves/python-social-auth,chandolia/python-social-auth,mchdks/python-social-auth,webjunkie/python-social-auth,ByteInternet/python-social-auth,fearlessspider/python-social-auth,firstjob/python-social-auth,noodle-learns-programming/python-social-auth,VishvajitP/python-social-auth,daniula/python-social-auth,mark-adams/python-social-auth,tkajtoch/python-social-auth,san-mate/python-social-auth,jeyraof/python-social-auth,robbiet480/python-social-auth,wildtetris/python-social-auth,jameslittle/python-social-auth,msampathkumar/python-social-auth,alrusdi/python-social-auth,msampathkumar/python-social-auth,yprez/python-social-auth,firstjob/python-social-auth,ononeor12/python-social-auth,tutumcloud/python-social-auth,noodle-learns-programming/python-social-auth,mathspace/python-social-auth,hsr-ba-fs15-dat/python-social-auth,muhammad-ammar/python-social-auth,degs098/python-social-auth,rsteca/python-social-auth,JerzySpendel/python-social-auth,frankier/python-social-auth,mchdks/python-social-auth,Andygmb/python-social-auth,iruga090/python-social-auth,merutak/python-social-auth,MSOpenTech/python-social-auth,cjltsod/python-social-auth,cmichal/python-social-auth,drxos/python-social-auth,drxos/python-social-auth,iruga090/python-social-auth
|
from django.db import models
# Create your models here.
Define a custom user model
|
# Define a custom User class to work with django-social-auth
from django.contrib.auth.models import AbstractUser, UserManager
class CustomUser(AbstractUser):
objects = UserManager()
|
<commit_before>from django.db import models
# Create your models here.
<commit_msg>Define a custom user model<commit_after>
|
# Define a custom User class to work with django-social-auth
from django.contrib.auth.models import AbstractUser, UserManager
class CustomUser(AbstractUser):
objects = UserManager()
|
from django.db import models
# Create your models here.
Define a custom user model# Define a custom User class to work with django-social-auth
from django.contrib.auth.models import AbstractUser, UserManager
class CustomUser(AbstractUser):
objects = UserManager()
|
<commit_before>from django.db import models
# Create your models here.
<commit_msg>Define a custom user model<commit_after># Define a custom User class to work with django-social-auth
from django.contrib.auth.models import AbstractUser, UserManager
class CustomUser(AbstractUser):
objects = UserManager()
|
c476cb5cf1bead63f19871fa1db9769e236fbe09
|
siren_files.py
|
siren_files.py
|
#!/usr/bin/python
#
source_files = ['check_siren.py', 'colours', 'credits', 'dataview', 'dijkstra_4',
'displayobject', 'displaytable', 'editini', 'flexiplot', 'floaters',
'getmap', 'getmerra2', 'getmodels', 'grid', 'indexweather', 'inisyntax',
'makegrid', 'makeweatherfiles',
'newstation', 'plotweather', 'powerclasses',
'powermatch', 'powermodel', 'powerplot', 'sammodels', 'samrun',
'senutils', 'siren', 'sirenicons', 'sirenm', 'sirenupd', 'ssc',
'station', 'superpower', 'towns', 'turbine', 'updateswis',
'viewresource', 'visualise', 'wascene', 'worldwindow', 'zoompan',
'getfiles.ini', 'about.html', 'credits.html', 'help.html',
'makeweatherfiles.html', 'SIREN_notes.html', 'siren_versions.csv',
'siren_files.py', 'compare_to_siren.git.py']
version_files = ['flexiplot', 'getmap', 'getmerra2', 'indexweather', 'makegrid',
'makeweatherfiles',
'powermatch', 'powerplot', 'siren', 'sirenm', 'sirenupd',
'updateswis']
|
#!/usr/bin/python
#
source_files = ['check_siren.py', 'colours', 'credits', 'dataview', 'dijkstra_4',
'displayobject', 'displaytable', 'editini', 'flexiplot', 'floaters',
'getmap', 'getmerra2', 'getmodels', 'grid', 'indexweather', 'inisyntax',
'makegrid', 'makeweatherfiles',
'newstation', 'plotweather', 'powerclasses',
'powermatch', 'powermodel', 'powerplot', 'sammodels', 'samrun',
'senutils', 'siren', 'sirenicons', 'sirenm', 'sirenupd', 'ssc',
'station', 'superpower', 'towns', 'turbine', 'updateswis',
'viewresource', 'visualise', 'wascene', 'worldwindow', 'zoompan',
'getfiles.ini', 'about.html', 'credits.html', 'help.html',
'SIREN_notes.html', 'siren_versions.csv',
'siren_files.py', 'compare_to_siren.git.py']
version_files = ['flexiplot', 'getmap', 'getmerra2', 'indexweather', 'makegrid',
'makeweatherfiles',
'powermatch', 'powerplot', 'siren', 'sirenm', 'sirenupd',
'template', 'updateswis']
|
Remove makeweatherfiles, add template for Windows version file
|
Remove makeweatherfiles, add template for Windows version file
|
Python
|
agpl-3.0
|
ozsolarwind/siren,ozsolarwind/siren
|
#!/usr/bin/python
#
source_files = ['check_siren.py', 'colours', 'credits', 'dataview', 'dijkstra_4',
'displayobject', 'displaytable', 'editini', 'flexiplot', 'floaters',
'getmap', 'getmerra2', 'getmodels', 'grid', 'indexweather', 'inisyntax',
'makegrid', 'makeweatherfiles',
'newstation', 'plotweather', 'powerclasses',
'powermatch', 'powermodel', 'powerplot', 'sammodels', 'samrun',
'senutils', 'siren', 'sirenicons', 'sirenm', 'sirenupd', 'ssc',
'station', 'superpower', 'towns', 'turbine', 'updateswis',
'viewresource', 'visualise', 'wascene', 'worldwindow', 'zoompan',
'getfiles.ini', 'about.html', 'credits.html', 'help.html',
'makeweatherfiles.html', 'SIREN_notes.html', 'siren_versions.csv',
'siren_files.py', 'compare_to_siren.git.py']
version_files = ['flexiplot', 'getmap', 'getmerra2', 'indexweather', 'makegrid',
'makeweatherfiles',
'powermatch', 'powerplot', 'siren', 'sirenm', 'sirenupd',
'updateswis']
Remove makeweatherfiles, add template for Windows version file
|
#!/usr/bin/python
#
source_files = ['check_siren.py', 'colours', 'credits', 'dataview', 'dijkstra_4',
'displayobject', 'displaytable', 'editini', 'flexiplot', 'floaters',
'getmap', 'getmerra2', 'getmodels', 'grid', 'indexweather', 'inisyntax',
'makegrid', 'makeweatherfiles',
'newstation', 'plotweather', 'powerclasses',
'powermatch', 'powermodel', 'powerplot', 'sammodels', 'samrun',
'senutils', 'siren', 'sirenicons', 'sirenm', 'sirenupd', 'ssc',
'station', 'superpower', 'towns', 'turbine', 'updateswis',
'viewresource', 'visualise', 'wascene', 'worldwindow', 'zoompan',
'getfiles.ini', 'about.html', 'credits.html', 'help.html',
'SIREN_notes.html', 'siren_versions.csv',
'siren_files.py', 'compare_to_siren.git.py']
version_files = ['flexiplot', 'getmap', 'getmerra2', 'indexweather', 'makegrid',
'makeweatherfiles',
'powermatch', 'powerplot', 'siren', 'sirenm', 'sirenupd',
'template', 'updateswis']
|
<commit_before>#!/usr/bin/python
#
source_files = ['check_siren.py', 'colours', 'credits', 'dataview', 'dijkstra_4',
'displayobject', 'displaytable', 'editini', 'flexiplot', 'floaters',
'getmap', 'getmerra2', 'getmodels', 'grid', 'indexweather', 'inisyntax',
'makegrid', 'makeweatherfiles',
'newstation', 'plotweather', 'powerclasses',
'powermatch', 'powermodel', 'powerplot', 'sammodels', 'samrun',
'senutils', 'siren', 'sirenicons', 'sirenm', 'sirenupd', 'ssc',
'station', 'superpower', 'towns', 'turbine', 'updateswis',
'viewresource', 'visualise', 'wascene', 'worldwindow', 'zoompan',
'getfiles.ini', 'about.html', 'credits.html', 'help.html',
'makeweatherfiles.html', 'SIREN_notes.html', 'siren_versions.csv',
'siren_files.py', 'compare_to_siren.git.py']
version_files = ['flexiplot', 'getmap', 'getmerra2', 'indexweather', 'makegrid',
'makeweatherfiles',
'powermatch', 'powerplot', 'siren', 'sirenm', 'sirenupd',
'updateswis']
<commit_msg>Remove makeweatherfiles, add template for Windows version file<commit_after>
|
#!/usr/bin/python
#
source_files = ['check_siren.py', 'colours', 'credits', 'dataview', 'dijkstra_4',
'displayobject', 'displaytable', 'editini', 'flexiplot', 'floaters',
'getmap', 'getmerra2', 'getmodels', 'grid', 'indexweather', 'inisyntax',
'makegrid', 'makeweatherfiles',
'newstation', 'plotweather', 'powerclasses',
'powermatch', 'powermodel', 'powerplot', 'sammodels', 'samrun',
'senutils', 'siren', 'sirenicons', 'sirenm', 'sirenupd', 'ssc',
'station', 'superpower', 'towns', 'turbine', 'updateswis',
'viewresource', 'visualise', 'wascene', 'worldwindow', 'zoompan',
'getfiles.ini', 'about.html', 'credits.html', 'help.html',
'SIREN_notes.html', 'siren_versions.csv',
'siren_files.py', 'compare_to_siren.git.py']
version_files = ['flexiplot', 'getmap', 'getmerra2', 'indexweather', 'makegrid',
'makeweatherfiles',
'powermatch', 'powerplot', 'siren', 'sirenm', 'sirenupd',
'template', 'updateswis']
|
#!/usr/bin/python
#
source_files = ['check_siren.py', 'colours', 'credits', 'dataview', 'dijkstra_4',
'displayobject', 'displaytable', 'editini', 'flexiplot', 'floaters',
'getmap', 'getmerra2', 'getmodels', 'grid', 'indexweather', 'inisyntax',
'makegrid', 'makeweatherfiles',
'newstation', 'plotweather', 'powerclasses',
'powermatch', 'powermodel', 'powerplot', 'sammodels', 'samrun',
'senutils', 'siren', 'sirenicons', 'sirenm', 'sirenupd', 'ssc',
'station', 'superpower', 'towns', 'turbine', 'updateswis',
'viewresource', 'visualise', 'wascene', 'worldwindow', 'zoompan',
'getfiles.ini', 'about.html', 'credits.html', 'help.html',
'makeweatherfiles.html', 'SIREN_notes.html', 'siren_versions.csv',
'siren_files.py', 'compare_to_siren.git.py']
version_files = ['flexiplot', 'getmap', 'getmerra2', 'indexweather', 'makegrid',
'makeweatherfiles',
'powermatch', 'powerplot', 'siren', 'sirenm', 'sirenupd',
'updateswis']
Remove makeweatherfiles, add template for Windows version file#!/usr/bin/python
#
source_files = ['check_siren.py', 'colours', 'credits', 'dataview', 'dijkstra_4',
'displayobject', 'displaytable', 'editini', 'flexiplot', 'floaters',
'getmap', 'getmerra2', 'getmodels', 'grid', 'indexweather', 'inisyntax',
'makegrid', 'makeweatherfiles',
'newstation', 'plotweather', 'powerclasses',
'powermatch', 'powermodel', 'powerplot', 'sammodels', 'samrun',
'senutils', 'siren', 'sirenicons', 'sirenm', 'sirenupd', 'ssc',
'station', 'superpower', 'towns', 'turbine', 'updateswis',
'viewresource', 'visualise', 'wascene', 'worldwindow', 'zoompan',
'getfiles.ini', 'about.html', 'credits.html', 'help.html',
'SIREN_notes.html', 'siren_versions.csv',
'siren_files.py', 'compare_to_siren.git.py']
version_files = ['flexiplot', 'getmap', 'getmerra2', 'indexweather', 'makegrid',
'makeweatherfiles',
'powermatch', 'powerplot', 'siren', 'sirenm', 'sirenupd',
'template', 'updateswis']
|
<commit_before>#!/usr/bin/python
#
source_files = ['check_siren.py', 'colours', 'credits', 'dataview', 'dijkstra_4',
'displayobject', 'displaytable', 'editini', 'flexiplot', 'floaters',
'getmap', 'getmerra2', 'getmodels', 'grid', 'indexweather', 'inisyntax',
'makegrid', 'makeweatherfiles',
'newstation', 'plotweather', 'powerclasses',
'powermatch', 'powermodel', 'powerplot', 'sammodels', 'samrun',
'senutils', 'siren', 'sirenicons', 'sirenm', 'sirenupd', 'ssc',
'station', 'superpower', 'towns', 'turbine', 'updateswis',
'viewresource', 'visualise', 'wascene', 'worldwindow', 'zoompan',
'getfiles.ini', 'about.html', 'credits.html', 'help.html',
'makeweatherfiles.html', 'SIREN_notes.html', 'siren_versions.csv',
'siren_files.py', 'compare_to_siren.git.py']
version_files = ['flexiplot', 'getmap', 'getmerra2', 'indexweather', 'makegrid',
'makeweatherfiles',
'powermatch', 'powerplot', 'siren', 'sirenm', 'sirenupd',
'updateswis']
<commit_msg>Remove makeweatherfiles, add template for Windows version file<commit_after>#!/usr/bin/python
#
source_files = ['check_siren.py', 'colours', 'credits', 'dataview', 'dijkstra_4',
'displayobject', 'displaytable', 'editini', 'flexiplot', 'floaters',
'getmap', 'getmerra2', 'getmodels', 'grid', 'indexweather', 'inisyntax',
'makegrid', 'makeweatherfiles',
'newstation', 'plotweather', 'powerclasses',
'powermatch', 'powermodel', 'powerplot', 'sammodels', 'samrun',
'senutils', 'siren', 'sirenicons', 'sirenm', 'sirenupd', 'ssc',
'station', 'superpower', 'towns', 'turbine', 'updateswis',
'viewresource', 'visualise', 'wascene', 'worldwindow', 'zoompan',
'getfiles.ini', 'about.html', 'credits.html', 'help.html',
'SIREN_notes.html', 'siren_versions.csv',
'siren_files.py', 'compare_to_siren.git.py']
version_files = ['flexiplot', 'getmap', 'getmerra2', 'indexweather', 'makegrid',
'makeweatherfiles',
'powermatch', 'powerplot', 'siren', 'sirenm', 'sirenupd',
'template', 'updateswis']
|
ecfa18b1c6d8dfd565ab625b3bb600d2d792310f
|
src/bitmessageqt/widgets.py
|
src/bitmessageqt/widgets.py
|
from PyQt4 import uic
import os.path
import sys
def resource_path(path):
try:
return os.path.join(sys._MEIPASS, path)
except:
return os.path.join(os.path.dirname(__file__), path)
def load(path, widget):
uic.loadUi(resource_path(path), widget)
|
from PyQt4 import uic
import os.path
import sys
from shared import codePath
def resource_path(resFile):
baseDir = codePath()
for subDir in ["ui", "bitmessageqt"]:
if os.path.isdir(os.path.join(baseDir, subDir)) and os.path.isfile(os.path.join(baseDir, subDir, resFile)):
return os.path.join(baseDir, subDir, resFile)
def load(resFile, widget):
uic.loadUi(resource_path(resFile), widget)
|
Change UI loading for frozen
|
Change UI loading for frozen
|
Python
|
mit
|
debguy0x/PyBitmessage,bmng-dev/PyBitmessage,hb9kns/PyBitmessage,hb9kns/PyBitmessage,timothyparez/PyBitmessage,torifier/PyBitmessage,hb9kns/PyBitmessage,debguy0x/PyBitmessage,debguy0x/PyBitmessage,torifier/PyBitmessage,timothyparez/PyBitmessage,torifier/PyBitmessage,timothyparez/PyBitmessage,bmng-dev/PyBitmessage,torifier/PyBitmessage,hb9kns/PyBitmessage,debguy0x/PyBitmessage,timothyparez/PyBitmessage,bmng-dev/PyBitmessage
|
from PyQt4 import uic
import os.path
import sys
def resource_path(path):
try:
return os.path.join(sys._MEIPASS, path)
except:
return os.path.join(os.path.dirname(__file__), path)
def load(path, widget):
uic.loadUi(resource_path(path), widget)
Change UI loading for frozen
|
from PyQt4 import uic
import os.path
import sys
from shared import codePath
def resource_path(resFile):
baseDir = codePath()
for subDir in ["ui", "bitmessageqt"]:
if os.path.isdir(os.path.join(baseDir, subDir)) and os.path.isfile(os.path.join(baseDir, subDir, resFile)):
return os.path.join(baseDir, subDir, resFile)
def load(resFile, widget):
uic.loadUi(resource_path(resFile), widget)
|
<commit_before>from PyQt4 import uic
import os.path
import sys
def resource_path(path):
try:
return os.path.join(sys._MEIPASS, path)
except:
return os.path.join(os.path.dirname(__file__), path)
def load(path, widget):
uic.loadUi(resource_path(path), widget)
<commit_msg>Change UI loading for frozen<commit_after>
|
from PyQt4 import uic
import os.path
import sys
from shared import codePath
def resource_path(resFile):
baseDir = codePath()
for subDir in ["ui", "bitmessageqt"]:
if os.path.isdir(os.path.join(baseDir, subDir)) and os.path.isfile(os.path.join(baseDir, subDir, resFile)):
return os.path.join(baseDir, subDir, resFile)
def load(resFile, widget):
uic.loadUi(resource_path(resFile), widget)
|
from PyQt4 import uic
import os.path
import sys
def resource_path(path):
try:
return os.path.join(sys._MEIPASS, path)
except:
return os.path.join(os.path.dirname(__file__), path)
def load(path, widget):
uic.loadUi(resource_path(path), widget)
Change UI loading for frozenfrom PyQt4 import uic
import os.path
import sys
from shared import codePath
def resource_path(resFile):
baseDir = codePath()
for subDir in ["ui", "bitmessageqt"]:
if os.path.isdir(os.path.join(baseDir, subDir)) and os.path.isfile(os.path.join(baseDir, subDir, resFile)):
return os.path.join(baseDir, subDir, resFile)
def load(resFile, widget):
uic.loadUi(resource_path(resFile), widget)
|
<commit_before>from PyQt4 import uic
import os.path
import sys
def resource_path(path):
try:
return os.path.join(sys._MEIPASS, path)
except:
return os.path.join(os.path.dirname(__file__), path)
def load(path, widget):
uic.loadUi(resource_path(path), widget)
<commit_msg>Change UI loading for frozen<commit_after>from PyQt4 import uic
import os.path
import sys
from shared import codePath
def resource_path(resFile):
baseDir = codePath()
for subDir in ["ui", "bitmessageqt"]:
if os.path.isdir(os.path.join(baseDir, subDir)) and os.path.isfile(os.path.join(baseDir, subDir, resFile)):
return os.path.join(baseDir, subDir, resFile)
def load(resFile, widget):
uic.loadUi(resource_path(resFile), widget)
|
b94edbbb717313cc831fa97d3ccf9ab715ff3ade
|
testing/test_cffitsio.py
|
testing/test_cffitsio.py
|
from cffitsio import FitsFile
import os
def test_create_file(tmpdir):
filename = str(tmpdir.join('test.fits'))
f = FitsFile.create(filename)
assert os.path.isfile(filename)
|
import pytest
import cffitsio
import os
@pytest.fixture
def test_dir():
return os.path.join(
os.path.dirname(__file__),
'data')
def test_create_file(tmpdir):
filename = str(tmpdir.join('test.fits'))
f = cffitsio.FitsFile.create(filename)
assert os.path.isfile(filename)
def test_open_file(test_dir):
filename = os.path.join(test_dir, 'all.fits')
with cffitsio.open_fits(filename) as infile:
assert isinstance(infile, cffitsio.FitsFile)
|
Add test for opening file
|
Add test for opening file
|
Python
|
mit
|
mindriot101/fitsio-cffi
|
from cffitsio import FitsFile
import os
def test_create_file(tmpdir):
filename = str(tmpdir.join('test.fits'))
f = FitsFile.create(filename)
assert os.path.isfile(filename)
Add test for opening file
|
import pytest
import cffitsio
import os
@pytest.fixture
def test_dir():
return os.path.join(
os.path.dirname(__file__),
'data')
def test_create_file(tmpdir):
filename = str(tmpdir.join('test.fits'))
f = cffitsio.FitsFile.create(filename)
assert os.path.isfile(filename)
def test_open_file(test_dir):
filename = os.path.join(test_dir, 'all.fits')
with cffitsio.open_fits(filename) as infile:
assert isinstance(infile, cffitsio.FitsFile)
|
<commit_before>from cffitsio import FitsFile
import os
def test_create_file(tmpdir):
filename = str(tmpdir.join('test.fits'))
f = FitsFile.create(filename)
assert os.path.isfile(filename)
<commit_msg>Add test for opening file<commit_after>
|
import pytest
import cffitsio
import os
@pytest.fixture
def test_dir():
return os.path.join(
os.path.dirname(__file__),
'data')
def test_create_file(tmpdir):
filename = str(tmpdir.join('test.fits'))
f = cffitsio.FitsFile.create(filename)
assert os.path.isfile(filename)
def test_open_file(test_dir):
filename = os.path.join(test_dir, 'all.fits')
with cffitsio.open_fits(filename) as infile:
assert isinstance(infile, cffitsio.FitsFile)
|
from cffitsio import FitsFile
import os
def test_create_file(tmpdir):
filename = str(tmpdir.join('test.fits'))
f = FitsFile.create(filename)
assert os.path.isfile(filename)
Add test for opening fileimport pytest
import cffitsio
import os
@pytest.fixture
def test_dir():
return os.path.join(
os.path.dirname(__file__),
'data')
def test_create_file(tmpdir):
filename = str(tmpdir.join('test.fits'))
f = cffitsio.FitsFile.create(filename)
assert os.path.isfile(filename)
def test_open_file(test_dir):
filename = os.path.join(test_dir, 'all.fits')
with cffitsio.open_fits(filename) as infile:
assert isinstance(infile, cffitsio.FitsFile)
|
<commit_before>from cffitsio import FitsFile
import os
def test_create_file(tmpdir):
filename = str(tmpdir.join('test.fits'))
f = FitsFile.create(filename)
assert os.path.isfile(filename)
<commit_msg>Add test for opening file<commit_after>import pytest
import cffitsio
import os
@pytest.fixture
def test_dir():
return os.path.join(
os.path.dirname(__file__),
'data')
def test_create_file(tmpdir):
filename = str(tmpdir.join('test.fits'))
f = cffitsio.FitsFile.create(filename)
assert os.path.isfile(filename)
def test_open_file(test_dir):
filename = os.path.join(test_dir, 'all.fits')
with cffitsio.open_fits(filename) as infile:
assert isinstance(infile, cffitsio.FitsFile)
|
1f10a9c4cf5e00a8290adfe6ee34542e35ffab9b
|
OpenPNM/Algorithms/__init__.py
|
OpenPNM/Algorithms/__init__.py
|
r"""
###############################################################################
:mod:`OpenPNM.Algorithms` -- Algorithms on Networks
###############################################################################
Contents
--------
This submodule contains algorithms for performing simulations on pore networks
Classes
-------
.. autoclass:: GenericAlgorithm
:members:
.. autoclass:: Drainage
:members:
.. autoclass:: InvasionPercolation
:members:
.. autoclass:: FickianDiffusion
:members:
.. autoclass:: StokesFlow
:members:
.. autoclass:: OhmicConduction
:members:
.. autoclass:: FourierConduction
:members:
"""
from .__GenericAlgorithm__ import GenericAlgorithm
from .__GenericLinearTransport__ import GenericLinearTransport
from .__FickianDiffusion__ import FickianDiffusion
from .__FourierConduction__ import FourierConduction
from .__OhmicConduction__ import OhmicConduction
from .__StokesFlow__ import StokesFlow
from .__OrdinaryPercolation__ import OrdinaryPercolation
from .__InvasionPercolation__ import InvasionPercolation
from .__Drainage__ import Drainage
|
r"""
###############################################################################
:mod:`OpenPNM.Algorithms` -- Algorithms on Networks
###############################################################################
Contents
--------
This submodule contains algorithms for performing simulations on pore networks
Classes
-------
.. autoclass:: GenericAlgorithm
:members:
.. autoclass:: Drainage
:members:
.. autoclass:: InvasionPercolation
:members:
.. autoclass:: FickianDiffusion
:members:
.. autoclass:: StokesFlow
:members:
.. autoclass:: OhmicConduction
:members:
.. autoclass:: FourierConduction
:members:
"""
from .__GenericAlgorithm__ import GenericAlgorithm
from .__GenericLinearTransport__ import GenericLinearTransport
from .__FickianDiffusion__ import FickianDiffusion
from .__FourierConduction__ import FourierConduction
from .__OhmicConduction__ import OhmicConduction
from .__StokesFlow__ import StokesFlow
from .__OrdinaryPercolation__ import OrdinaryPercolation
from .__InvasionPercolation__ import InvasionPercolation
from .__Drainage__ import Drainage
from .__InvasionPercolationTT__ import InvasionPercolationTT
|
Add new percolation alg to init - to be renamed later
|
Add new percolation alg to init - to be renamed later
|
Python
|
mit
|
TomTranter/OpenPNM,PMEAL/OpenPNM
|
r"""
###############################################################################
:mod:`OpenPNM.Algorithms` -- Algorithms on Networks
###############################################################################
Contents
--------
This submodule contains algorithms for performing simulations on pore networks
Classes
-------
.. autoclass:: GenericAlgorithm
:members:
.. autoclass:: Drainage
:members:
.. autoclass:: InvasionPercolation
:members:
.. autoclass:: FickianDiffusion
:members:
.. autoclass:: StokesFlow
:members:
.. autoclass:: OhmicConduction
:members:
.. autoclass:: FourierConduction
:members:
"""
from .__GenericAlgorithm__ import GenericAlgorithm
from .__GenericLinearTransport__ import GenericLinearTransport
from .__FickianDiffusion__ import FickianDiffusion
from .__FourierConduction__ import FourierConduction
from .__OhmicConduction__ import OhmicConduction
from .__StokesFlow__ import StokesFlow
from .__OrdinaryPercolation__ import OrdinaryPercolation
from .__InvasionPercolation__ import InvasionPercolation
from .__Drainage__ import Drainage
Add new percolation alg to init - to be renamed later
|
r"""
###############################################################################
:mod:`OpenPNM.Algorithms` -- Algorithms on Networks
###############################################################################
Contents
--------
This submodule contains algorithms for performing simulations on pore networks
Classes
-------
.. autoclass:: GenericAlgorithm
:members:
.. autoclass:: Drainage
:members:
.. autoclass:: InvasionPercolation
:members:
.. autoclass:: FickianDiffusion
:members:
.. autoclass:: StokesFlow
:members:
.. autoclass:: OhmicConduction
:members:
.. autoclass:: FourierConduction
:members:
"""
from .__GenericAlgorithm__ import GenericAlgorithm
from .__GenericLinearTransport__ import GenericLinearTransport
from .__FickianDiffusion__ import FickianDiffusion
from .__FourierConduction__ import FourierConduction
from .__OhmicConduction__ import OhmicConduction
from .__StokesFlow__ import StokesFlow
from .__OrdinaryPercolation__ import OrdinaryPercolation
from .__InvasionPercolation__ import InvasionPercolation
from .__Drainage__ import Drainage
from .__InvasionPercolationTT__ import InvasionPercolationTT
|
<commit_before>r"""
###############################################################################
:mod:`OpenPNM.Algorithms` -- Algorithms on Networks
###############################################################################
Contents
--------
This submodule contains algorithms for performing simulations on pore networks
Classes
-------
.. autoclass:: GenericAlgorithm
:members:
.. autoclass:: Drainage
:members:
.. autoclass:: InvasionPercolation
:members:
.. autoclass:: FickianDiffusion
:members:
.. autoclass:: StokesFlow
:members:
.. autoclass:: OhmicConduction
:members:
.. autoclass:: FourierConduction
:members:
"""
from .__GenericAlgorithm__ import GenericAlgorithm
from .__GenericLinearTransport__ import GenericLinearTransport
from .__FickianDiffusion__ import FickianDiffusion
from .__FourierConduction__ import FourierConduction
from .__OhmicConduction__ import OhmicConduction
from .__StokesFlow__ import StokesFlow
from .__OrdinaryPercolation__ import OrdinaryPercolation
from .__InvasionPercolation__ import InvasionPercolation
from .__Drainage__ import Drainage
<commit_msg>Add new percolation alg to init - to be renamed later<commit_after>
|
r"""
###############################################################################
:mod:`OpenPNM.Algorithms` -- Algorithms on Networks
###############################################################################
Contents
--------
This submodule contains algorithms for performing simulations on pore networks
Classes
-------
.. autoclass:: GenericAlgorithm
:members:
.. autoclass:: Drainage
:members:
.. autoclass:: InvasionPercolation
:members:
.. autoclass:: FickianDiffusion
:members:
.. autoclass:: StokesFlow
:members:
.. autoclass:: OhmicConduction
:members:
.. autoclass:: FourierConduction
:members:
"""
from .__GenericAlgorithm__ import GenericAlgorithm
from .__GenericLinearTransport__ import GenericLinearTransport
from .__FickianDiffusion__ import FickianDiffusion
from .__FourierConduction__ import FourierConduction
from .__OhmicConduction__ import OhmicConduction
from .__StokesFlow__ import StokesFlow
from .__OrdinaryPercolation__ import OrdinaryPercolation
from .__InvasionPercolation__ import InvasionPercolation
from .__Drainage__ import Drainage
from .__InvasionPercolationTT__ import InvasionPercolationTT
|
r"""
###############################################################################
:mod:`OpenPNM.Algorithms` -- Algorithms on Networks
###############################################################################
Contents
--------
This submodule contains algorithms for performing simulations on pore networks
Classes
-------
.. autoclass:: GenericAlgorithm
:members:
.. autoclass:: Drainage
:members:
.. autoclass:: InvasionPercolation
:members:
.. autoclass:: FickianDiffusion
:members:
.. autoclass:: StokesFlow
:members:
.. autoclass:: OhmicConduction
:members:
.. autoclass:: FourierConduction
:members:
"""
from .__GenericAlgorithm__ import GenericAlgorithm
from .__GenericLinearTransport__ import GenericLinearTransport
from .__FickianDiffusion__ import FickianDiffusion
from .__FourierConduction__ import FourierConduction
from .__OhmicConduction__ import OhmicConduction
from .__StokesFlow__ import StokesFlow
from .__OrdinaryPercolation__ import OrdinaryPercolation
from .__InvasionPercolation__ import InvasionPercolation
from .__Drainage__ import Drainage
Add new percolation alg to init - to be renamed laterr"""
###############################################################################
:mod:`OpenPNM.Algorithms` -- Algorithms on Networks
###############################################################################
Contents
--------
This submodule contains algorithms for performing simulations on pore networks
Classes
-------
.. autoclass:: GenericAlgorithm
:members:
.. autoclass:: Drainage
:members:
.. autoclass:: InvasionPercolation
:members:
.. autoclass:: FickianDiffusion
:members:
.. autoclass:: StokesFlow
:members:
.. autoclass:: OhmicConduction
:members:
.. autoclass:: FourierConduction
:members:
"""
from .__GenericAlgorithm__ import GenericAlgorithm
from .__GenericLinearTransport__ import GenericLinearTransport
from .__FickianDiffusion__ import FickianDiffusion
from .__FourierConduction__ import FourierConduction
from .__OhmicConduction__ import OhmicConduction
from .__StokesFlow__ import StokesFlow
from .__OrdinaryPercolation__ import OrdinaryPercolation
from .__InvasionPercolation__ import InvasionPercolation
from .__Drainage__ import Drainage
from .__InvasionPercolationTT__ import InvasionPercolationTT
|
<commit_before>r"""
###############################################################################
:mod:`OpenPNM.Algorithms` -- Algorithms on Networks
###############################################################################
Contents
--------
This submodule contains algorithms for performing simulations on pore networks
Classes
-------
.. autoclass:: GenericAlgorithm
:members:
.. autoclass:: Drainage
:members:
.. autoclass:: InvasionPercolation
:members:
.. autoclass:: FickianDiffusion
:members:
.. autoclass:: StokesFlow
:members:
.. autoclass:: OhmicConduction
:members:
.. autoclass:: FourierConduction
:members:
"""
from .__GenericAlgorithm__ import GenericAlgorithm
from .__GenericLinearTransport__ import GenericLinearTransport
from .__FickianDiffusion__ import FickianDiffusion
from .__FourierConduction__ import FourierConduction
from .__OhmicConduction__ import OhmicConduction
from .__StokesFlow__ import StokesFlow
from .__OrdinaryPercolation__ import OrdinaryPercolation
from .__InvasionPercolation__ import InvasionPercolation
from .__Drainage__ import Drainage
<commit_msg>Add new percolation alg to init - to be renamed later<commit_after>r"""
###############################################################################
:mod:`OpenPNM.Algorithms` -- Algorithms on Networks
###############################################################################
Contents
--------
This submodule contains algorithms for performing simulations on pore networks
Classes
-------
.. autoclass:: GenericAlgorithm
:members:
.. autoclass:: Drainage
:members:
.. autoclass:: InvasionPercolation
:members:
.. autoclass:: FickianDiffusion
:members:
.. autoclass:: StokesFlow
:members:
.. autoclass:: OhmicConduction
:members:
.. autoclass:: FourierConduction
:members:
"""
from .__GenericAlgorithm__ import GenericAlgorithm
from .__GenericLinearTransport__ import GenericLinearTransport
from .__FickianDiffusion__ import FickianDiffusion
from .__FourierConduction__ import FourierConduction
from .__OhmicConduction__ import OhmicConduction
from .__StokesFlow__ import StokesFlow
from .__OrdinaryPercolation__ import OrdinaryPercolation
from .__InvasionPercolation__ import InvasionPercolation
from .__Drainage__ import Drainage
from .__InvasionPercolationTT__ import InvasionPercolationTT
|
7ab7154c1393491bd2874484e02c6af6eb3bb7e7
|
tests/test_functional.py
|
tests/test_functional.py
|
"""Functional tests
Test will produce the following tuple of all path permutations
paths = ['path/to/font_a', 'path/to/font_b']
[
(path/to/font_a, path/to/font_b),
(path/to/font_b, path/to/font_a),
]
and run them through our main diff_fonts functions.
This test is slow and should be run on challenging fonts.
"""
from diffenator.diff import diff_fonts
from itertools import permutations
import collections
from glob import glob
import os
import unittest
class TestFunctionality(unittest.TestCase):
def setUp(self):
_path = os.path.dirname(__file__)
font_paths = glob(os.path.join(_path, 'data', '*.ttf'))
self.font_path_combos = permutations(font_paths, r=2)
def test_diff(self):
for font_a_path, font_b_path in self.font_path_combos:
diff = diff_fonts(font_a_path, font_b_path)
self.assertNotEqual(diff, collections.defaultdict(dict))
if __name__ == '__main__':
unittest.main()
|
"""Functional tests
Test will produce the following tuple of all path permutations
paths = ['path/to/font_a', 'path/to/font_b']
[
(path/to/font_a, path/to/font_b),
(path/to/font_b, path/to/font_a),
]
and run them through our main diff_fonts functions.
This test is slow and should be run on challenging fonts.
"""
from diffenator.diff import diff_fonts
from diffenator.font import InputFont
from itertools import permutations
import collections
from glob import glob
import os
import unittest
class TestFunctionality(unittest.TestCase):
def setUp(self):
_path = os.path.dirname(__file__)
font_paths = glob(os.path.join(_path, 'data', '*.ttf'))
self.font_path_combos = permutations(font_paths, r=2)
def test_diff(self):
for font_a_path, font_b_path in self.font_path_combos:
font_a = InputFont(font_a_path)
font_b = InputFont(font_b_path)
diff = diff_fonts(font_a, font_b)
self.assertNotEqual(diff, collections.defaultdict(dict))
if __name__ == '__main__':
unittest.main()
|
Call diff_fonts with correct params
|
Call diff_fonts with correct params
|
Python
|
apache-2.0
|
googlefonts/fontdiffenator,googlefonts/fontdiffenator
|
"""Functional tests
Test will produce the following tuple of all path permutations
paths = ['path/to/font_a', 'path/to/font_b']
[
(path/to/font_a, path/to/font_b),
(path/to/font_b, path/to/font_a),
]
and run them through our main diff_fonts functions.
This test is slow and should be run on challenging fonts.
"""
from diffenator.diff import diff_fonts
from itertools import permutations
import collections
from glob import glob
import os
import unittest
class TestFunctionality(unittest.TestCase):
def setUp(self):
_path = os.path.dirname(__file__)
font_paths = glob(os.path.join(_path, 'data', '*.ttf'))
self.font_path_combos = permutations(font_paths, r=2)
def test_diff(self):
for font_a_path, font_b_path in self.font_path_combos:
diff = diff_fonts(font_a_path, font_b_path)
self.assertNotEqual(diff, collections.defaultdict(dict))
if __name__ == '__main__':
unittest.main()
Call diff_fonts with correct params
|
"""Functional tests
Test will produce the following tuple of all path permutations
paths = ['path/to/font_a', 'path/to/font_b']
[
(path/to/font_a, path/to/font_b),
(path/to/font_b, path/to/font_a),
]
and run them through our main diff_fonts functions.
This test is slow and should be run on challenging fonts.
"""
from diffenator.diff import diff_fonts
from diffenator.font import InputFont
from itertools import permutations
import collections
from glob import glob
import os
import unittest
class TestFunctionality(unittest.TestCase):
def setUp(self):
_path = os.path.dirname(__file__)
font_paths = glob(os.path.join(_path, 'data', '*.ttf'))
self.font_path_combos = permutations(font_paths, r=2)
def test_diff(self):
for font_a_path, font_b_path in self.font_path_combos:
font_a = InputFont(font_a_path)
font_b = InputFont(font_b_path)
diff = diff_fonts(font_a, font_b)
self.assertNotEqual(diff, collections.defaultdict(dict))
if __name__ == '__main__':
unittest.main()
|
<commit_before>"""Functional tests
Test will produce the following tuple of all path permutations
paths = ['path/to/font_a', 'path/to/font_b']
[
(path/to/font_a, path/to/font_b),
(path/to/font_b, path/to/font_a),
]
and run them through our main diff_fonts functions.
This test is slow and should be run on challenging fonts.
"""
from diffenator.diff import diff_fonts
from itertools import permutations
import collections
from glob import glob
import os
import unittest
class TestFunctionality(unittest.TestCase):
def setUp(self):
_path = os.path.dirname(__file__)
font_paths = glob(os.path.join(_path, 'data', '*.ttf'))
self.font_path_combos = permutations(font_paths, r=2)
def test_diff(self):
for font_a_path, font_b_path in self.font_path_combos:
diff = diff_fonts(font_a_path, font_b_path)
self.assertNotEqual(diff, collections.defaultdict(dict))
if __name__ == '__main__':
unittest.main()
<commit_msg>Call diff_fonts with correct params<commit_after>
|
"""Functional tests
Test will produce the following tuple of all path permutations
paths = ['path/to/font_a', 'path/to/font_b']
[
(path/to/font_a, path/to/font_b),
(path/to/font_b, path/to/font_a),
]
and run them through our main diff_fonts functions.
This test is slow and should be run on challenging fonts.
"""
from diffenator.diff import diff_fonts
from diffenator.font import InputFont
from itertools import permutations
import collections
from glob import glob
import os
import unittest
class TestFunctionality(unittest.TestCase):
def setUp(self):
_path = os.path.dirname(__file__)
font_paths = glob(os.path.join(_path, 'data', '*.ttf'))
self.font_path_combos = permutations(font_paths, r=2)
def test_diff(self):
for font_a_path, font_b_path in self.font_path_combos:
font_a = InputFont(font_a_path)
font_b = InputFont(font_b_path)
diff = diff_fonts(font_a, font_b)
self.assertNotEqual(diff, collections.defaultdict(dict))
if __name__ == '__main__':
unittest.main()
|
"""Functional tests
Test will produce the following tuple of all path permutations
paths = ['path/to/font_a', 'path/to/font_b']
[
(path/to/font_a, path/to/font_b),
(path/to/font_b, path/to/font_a),
]
and run them through our main diff_fonts functions.
This test is slow and should be run on challenging fonts.
"""
from diffenator.diff import diff_fonts
from itertools import permutations
import collections
from glob import glob
import os
import unittest
class TestFunctionality(unittest.TestCase):
def setUp(self):
_path = os.path.dirname(__file__)
font_paths = glob(os.path.join(_path, 'data', '*.ttf'))
self.font_path_combos = permutations(font_paths, r=2)
def test_diff(self):
for font_a_path, font_b_path in self.font_path_combos:
diff = diff_fonts(font_a_path, font_b_path)
self.assertNotEqual(diff, collections.defaultdict(dict))
if __name__ == '__main__':
unittest.main()
Call diff_fonts with correct params"""Functional tests
Test will produce the following tuple of all path permutations
paths = ['path/to/font_a', 'path/to/font_b']
[
(path/to/font_a, path/to/font_b),
(path/to/font_b, path/to/font_a),
]
and run them through our main diff_fonts functions.
This test is slow and should be run on challenging fonts.
"""
from diffenator.diff import diff_fonts
from diffenator.font import InputFont
from itertools import permutations
import collections
from glob import glob
import os
import unittest
class TestFunctionality(unittest.TestCase):
def setUp(self):
_path = os.path.dirname(__file__)
font_paths = glob(os.path.join(_path, 'data', '*.ttf'))
self.font_path_combos = permutations(font_paths, r=2)
def test_diff(self):
for font_a_path, font_b_path in self.font_path_combos:
font_a = InputFont(font_a_path)
font_b = InputFont(font_b_path)
diff = diff_fonts(font_a, font_b)
self.assertNotEqual(diff, collections.defaultdict(dict))
if __name__ == '__main__':
unittest.main()
|
<commit_before>"""Functional tests
Test will produce the following tuple of all path permutations
paths = ['path/to/font_a', 'path/to/font_b']
[
(path/to/font_a, path/to/font_b),
(path/to/font_b, path/to/font_a),
]
and run them through our main diff_fonts functions.
This test is slow and should be run on challenging fonts.
"""
from diffenator.diff import diff_fonts
from itertools import permutations
import collections
from glob import glob
import os
import unittest
class TestFunctionality(unittest.TestCase):
def setUp(self):
_path = os.path.dirname(__file__)
font_paths = glob(os.path.join(_path, 'data', '*.ttf'))
self.font_path_combos = permutations(font_paths, r=2)
def test_diff(self):
for font_a_path, font_b_path in self.font_path_combos:
diff = diff_fonts(font_a_path, font_b_path)
self.assertNotEqual(diff, collections.defaultdict(dict))
if __name__ == '__main__':
unittest.main()
<commit_msg>Call diff_fonts with correct params<commit_after>"""Functional tests
Test will produce the following tuple of all path permutations
paths = ['path/to/font_a', 'path/to/font_b']
[
(path/to/font_a, path/to/font_b),
(path/to/font_b, path/to/font_a),
]
and run them through our main diff_fonts functions.
This test is slow and should be run on challenging fonts.
"""
from diffenator.diff import diff_fonts
from diffenator.font import InputFont
from itertools import permutations
import collections
from glob import glob
import os
import unittest
class TestFunctionality(unittest.TestCase):
def setUp(self):
_path = os.path.dirname(__file__)
font_paths = glob(os.path.join(_path, 'data', '*.ttf'))
self.font_path_combos = permutations(font_paths, r=2)
def test_diff(self):
for font_a_path, font_b_path in self.font_path_combos:
font_a = InputFont(font_a_path)
font_b = InputFont(font_b_path)
diff = diff_fonts(font_a, font_b)
self.assertNotEqual(diff, collections.defaultdict(dict))
if __name__ == '__main__':
unittest.main()
|
4e4112b548cc263da2a455c2db9a2c82a3f84e45
|
ecommerce/theming/models.py
|
ecommerce/theming/models.py
|
import logging
from django.conf import settings
from django.contrib.sites.models import Site
from django.db import models
logger = logging.getLogger(__name__)
class SiteTheme(models.Model):
"""
This is where the information about the site's theme gets stored to the db.
Fields:
site (ForeignKey): Foreign Key field pointing to django Site model
theme_dir_name (CharField): Contains directory name for any site's theme (e.g. 'red-theme')
"""
site = models.ForeignKey(Site, related_name='themes', on_delete=models.CASCADE)
theme_dir_name = models.CharField(max_length=255)
@staticmethod
def get_theme(site):
"""
Get SiteTheme object for given site, returns default site theme if it can not
find a theme for the given site and `DEFAULT_SITE_THEME` setting has a proper value.
Args:
site (django.contrib.sites.models.Site): site object related to the current site.
Returns:
SiteTheme object for given site or a default site set by `DEFAULT_SITE_THEME`
"""
if not site:
logger.warning('A site must be specified when retrieving a theme.')
return None
logger.info('Retrieving theme for site [%d]...', site.id)
theme = site.themes.first()
if theme:
logger.info(
'Setting theme for site [%d] to theme [%d] with assets in [%s]',
site.id, theme.id, theme.theme_dir_name
)
else:
default_theme_dir = settings.DEFAULT_SITE_THEME
if default_theme_dir:
logger.info('No theme found for site [%d]. Using default assets in [%s]', site.id, default_theme_dir)
theme = SiteTheme(site=site, theme_dir_name=settings.DEFAULT_SITE_THEME)
else:
logger.error('No default theme has been defined!')
return theme
|
from django.conf import settings
from django.contrib.sites.models import Site
from django.db import models
class SiteTheme(models.Model):
"""
This is where the information about the site's theme gets stored to the db.
Fields:
site (ForeignKey): Foreign Key field pointing to django Site model
theme_dir_name (CharField): Contains directory name for any site's theme (e.g. 'red-theme')
"""
site = models.ForeignKey(Site, related_name='themes', on_delete=models.CASCADE)
theme_dir_name = models.CharField(max_length=255)
@staticmethod
def get_theme(site):
"""
Get SiteTheme object for given site, returns default site theme if it can not
find a theme for the given site and `DEFAULT_SITE_THEME` setting has a proper value.
Args:
site (django.contrib.sites.models.Site): site object related to the current site.
Returns:
SiteTheme object for given site or a default site set by `DEFAULT_SITE_THEME`
"""
if not site:
return None
theme = site.themes.first()
if (not theme) and settings.DEFAULT_SITE_THEME:
theme = SiteTheme(site=site, theme_dir_name=settings.DEFAULT_SITE_THEME)
return theme
|
Revert "Added logging to SiteTheme.get_theme"
|
Revert "Added logging to SiteTheme.get_theme"
This reverts commit f1436a255bb22ecd7b9ddca803240262bf484981.
|
Python
|
agpl-3.0
|
edx/ecommerce,eduNEXT/edunext-ecommerce,eduNEXT/edunext-ecommerce,edx/ecommerce,edx/ecommerce,edx/ecommerce,eduNEXT/edunext-ecommerce,eduNEXT/edunext-ecommerce
|
import logging
from django.conf import settings
from django.contrib.sites.models import Site
from django.db import models
logger = logging.getLogger(__name__)
class SiteTheme(models.Model):
"""
This is where the information about the site's theme gets stored to the db.
Fields:
site (ForeignKey): Foreign Key field pointing to django Site model
theme_dir_name (CharField): Contains directory name for any site's theme (e.g. 'red-theme')
"""
site = models.ForeignKey(Site, related_name='themes', on_delete=models.CASCADE)
theme_dir_name = models.CharField(max_length=255)
@staticmethod
def get_theme(site):
"""
Get SiteTheme object for given site, returns default site theme if it can not
find a theme for the given site and `DEFAULT_SITE_THEME` setting has a proper value.
Args:
site (django.contrib.sites.models.Site): site object related to the current site.
Returns:
SiteTheme object for given site or a default site set by `DEFAULT_SITE_THEME`
"""
if not site:
logger.warning('A site must be specified when retrieving a theme.')
return None
logger.info('Retrieving theme for site [%d]...', site.id)
theme = site.themes.first()
if theme:
logger.info(
'Setting theme for site [%d] to theme [%d] with assets in [%s]',
site.id, theme.id, theme.theme_dir_name
)
else:
default_theme_dir = settings.DEFAULT_SITE_THEME
if default_theme_dir:
logger.info('No theme found for site [%d]. Using default assets in [%s]', site.id, default_theme_dir)
theme = SiteTheme(site=site, theme_dir_name=settings.DEFAULT_SITE_THEME)
else:
logger.error('No default theme has been defined!')
return theme
Revert "Added logging to SiteTheme.get_theme"
This reverts commit f1436a255bb22ecd7b9ddca803240262bf484981.
|
from django.conf import settings
from django.contrib.sites.models import Site
from django.db import models
class SiteTheme(models.Model):
"""
This is where the information about the site's theme gets stored to the db.
Fields:
site (ForeignKey): Foreign Key field pointing to django Site model
theme_dir_name (CharField): Contains directory name for any site's theme (e.g. 'red-theme')
"""
site = models.ForeignKey(Site, related_name='themes', on_delete=models.CASCADE)
theme_dir_name = models.CharField(max_length=255)
@staticmethod
def get_theme(site):
"""
Get SiteTheme object for given site, returns default site theme if it can not
find a theme for the given site and `DEFAULT_SITE_THEME` setting has a proper value.
Args:
site (django.contrib.sites.models.Site): site object related to the current site.
Returns:
SiteTheme object for given site or a default site set by `DEFAULT_SITE_THEME`
"""
if not site:
return None
theme = site.themes.first()
if (not theme) and settings.DEFAULT_SITE_THEME:
theme = SiteTheme(site=site, theme_dir_name=settings.DEFAULT_SITE_THEME)
return theme
|
<commit_before>import logging
from django.conf import settings
from django.contrib.sites.models import Site
from django.db import models
logger = logging.getLogger(__name__)
class SiteTheme(models.Model):
"""
This is where the information about the site's theme gets stored to the db.
Fields:
site (ForeignKey): Foreign Key field pointing to django Site model
theme_dir_name (CharField): Contains directory name for any site's theme (e.g. 'red-theme')
"""
site = models.ForeignKey(Site, related_name='themes', on_delete=models.CASCADE)
theme_dir_name = models.CharField(max_length=255)
@staticmethod
def get_theme(site):
"""
Get SiteTheme object for given site, returns default site theme if it can not
find a theme for the given site and `DEFAULT_SITE_THEME` setting has a proper value.
Args:
site (django.contrib.sites.models.Site): site object related to the current site.
Returns:
SiteTheme object for given site or a default site set by `DEFAULT_SITE_THEME`
"""
if not site:
logger.warning('A site must be specified when retrieving a theme.')
return None
logger.info('Retrieving theme for site [%d]...', site.id)
theme = site.themes.first()
if theme:
logger.info(
'Setting theme for site [%d] to theme [%d] with assets in [%s]',
site.id, theme.id, theme.theme_dir_name
)
else:
default_theme_dir = settings.DEFAULT_SITE_THEME
if default_theme_dir:
logger.info('No theme found for site [%d]. Using default assets in [%s]', site.id, default_theme_dir)
theme = SiteTheme(site=site, theme_dir_name=settings.DEFAULT_SITE_THEME)
else:
logger.error('No default theme has been defined!')
return theme
<commit_msg>Revert "Added logging to SiteTheme.get_theme"
This reverts commit f1436a255bb22ecd7b9ddca803240262bf484981.<commit_after>
|
from django.conf import settings
from django.contrib.sites.models import Site
from django.db import models
class SiteTheme(models.Model):
"""
This is where the information about the site's theme gets stored to the db.
Fields:
site (ForeignKey): Foreign Key field pointing to django Site model
theme_dir_name (CharField): Contains directory name for any site's theme (e.g. 'red-theme')
"""
site = models.ForeignKey(Site, related_name='themes', on_delete=models.CASCADE)
theme_dir_name = models.CharField(max_length=255)
@staticmethod
def get_theme(site):
"""
Get SiteTheme object for given site, returns default site theme if it can not
find a theme for the given site and `DEFAULT_SITE_THEME` setting has a proper value.
Args:
site (django.contrib.sites.models.Site): site object related to the current site.
Returns:
SiteTheme object for given site or a default site set by `DEFAULT_SITE_THEME`
"""
if not site:
return None
theme = site.themes.first()
if (not theme) and settings.DEFAULT_SITE_THEME:
theme = SiteTheme(site=site, theme_dir_name=settings.DEFAULT_SITE_THEME)
return theme
|
import logging
from django.conf import settings
from django.contrib.sites.models import Site
from django.db import models
logger = logging.getLogger(__name__)
class SiteTheme(models.Model):
"""
This is where the information about the site's theme gets stored to the db.
Fields:
site (ForeignKey): Foreign Key field pointing to django Site model
theme_dir_name (CharField): Contains directory name for any site's theme (e.g. 'red-theme')
"""
site = models.ForeignKey(Site, related_name='themes', on_delete=models.CASCADE)
theme_dir_name = models.CharField(max_length=255)
@staticmethod
def get_theme(site):
"""
Get SiteTheme object for given site, returns default site theme if it can not
find a theme for the given site and `DEFAULT_SITE_THEME` setting has a proper value.
Args:
site (django.contrib.sites.models.Site): site object related to the current site.
Returns:
SiteTheme object for given site or a default site set by `DEFAULT_SITE_THEME`
"""
if not site:
logger.warning('A site must be specified when retrieving a theme.')
return None
logger.info('Retrieving theme for site [%d]...', site.id)
theme = site.themes.first()
if theme:
logger.info(
'Setting theme for site [%d] to theme [%d] with assets in [%s]',
site.id, theme.id, theme.theme_dir_name
)
else:
default_theme_dir = settings.DEFAULT_SITE_THEME
if default_theme_dir:
logger.info('No theme found for site [%d]. Using default assets in [%s]', site.id, default_theme_dir)
theme = SiteTheme(site=site, theme_dir_name=settings.DEFAULT_SITE_THEME)
else:
logger.error('No default theme has been defined!')
return theme
Revert "Added logging to SiteTheme.get_theme"
This reverts commit f1436a255bb22ecd7b9ddca803240262bf484981.from django.conf import settings
from django.contrib.sites.models import Site
from django.db import models
class SiteTheme(models.Model):
"""
This is where the information about the site's theme gets stored to the db.
Fields:
site (ForeignKey): Foreign Key field pointing to django Site model
theme_dir_name (CharField): Contains directory name for any site's theme (e.g. 'red-theme')
"""
site = models.ForeignKey(Site, related_name='themes', on_delete=models.CASCADE)
theme_dir_name = models.CharField(max_length=255)
@staticmethod
def get_theme(site):
"""
Get SiteTheme object for given site, returns default site theme if it can not
find a theme for the given site and `DEFAULT_SITE_THEME` setting has a proper value.
Args:
site (django.contrib.sites.models.Site): site object related to the current site.
Returns:
SiteTheme object for given site or a default site set by `DEFAULT_SITE_THEME`
"""
if not site:
return None
theme = site.themes.first()
if (not theme) and settings.DEFAULT_SITE_THEME:
theme = SiteTheme(site=site, theme_dir_name=settings.DEFAULT_SITE_THEME)
return theme
|
<commit_before>import logging
from django.conf import settings
from django.contrib.sites.models import Site
from django.db import models
logger = logging.getLogger(__name__)
class SiteTheme(models.Model):
"""
This is where the information about the site's theme gets stored to the db.
Fields:
site (ForeignKey): Foreign Key field pointing to django Site model
theme_dir_name (CharField): Contains directory name for any site's theme (e.g. 'red-theme')
"""
site = models.ForeignKey(Site, related_name='themes', on_delete=models.CASCADE)
theme_dir_name = models.CharField(max_length=255)
@staticmethod
def get_theme(site):
"""
Get SiteTheme object for given site, returns default site theme if it can not
find a theme for the given site and `DEFAULT_SITE_THEME` setting has a proper value.
Args:
site (django.contrib.sites.models.Site): site object related to the current site.
Returns:
SiteTheme object for given site or a default site set by `DEFAULT_SITE_THEME`
"""
if not site:
logger.warning('A site must be specified when retrieving a theme.')
return None
logger.info('Retrieving theme for site [%d]...', site.id)
theme = site.themes.first()
if theme:
logger.info(
'Setting theme for site [%d] to theme [%d] with assets in [%s]',
site.id, theme.id, theme.theme_dir_name
)
else:
default_theme_dir = settings.DEFAULT_SITE_THEME
if default_theme_dir:
logger.info('No theme found for site [%d]. Using default assets in [%s]', site.id, default_theme_dir)
theme = SiteTheme(site=site, theme_dir_name=settings.DEFAULT_SITE_THEME)
else:
logger.error('No default theme has been defined!')
return theme
<commit_msg>Revert "Added logging to SiteTheme.get_theme"
This reverts commit f1436a255bb22ecd7b9ddca803240262bf484981.<commit_after>from django.conf import settings
from django.contrib.sites.models import Site
from django.db import models
class SiteTheme(models.Model):
"""
This is where the information about the site's theme gets stored to the db.
Fields:
site (ForeignKey): Foreign Key field pointing to django Site model
theme_dir_name (CharField): Contains directory name for any site's theme (e.g. 'red-theme')
"""
site = models.ForeignKey(Site, related_name='themes', on_delete=models.CASCADE)
theme_dir_name = models.CharField(max_length=255)
@staticmethod
def get_theme(site):
"""
Get SiteTheme object for given site, returns default site theme if it can not
find a theme for the given site and `DEFAULT_SITE_THEME` setting has a proper value.
Args:
site (django.contrib.sites.models.Site): site object related to the current site.
Returns:
SiteTheme object for given site or a default site set by `DEFAULT_SITE_THEME`
"""
if not site:
return None
theme = site.themes.first()
if (not theme) and settings.DEFAULT_SITE_THEME:
theme = SiteTheme(site=site, theme_dir_name=settings.DEFAULT_SITE_THEME)
return theme
|
d7df867b2a5e7c8f5255d9e7627999c3e2132e9c
|
example/tests/test_utils.py
|
example/tests/test_utils.py
|
"""
Test rest_framework_json_api's utils functions.
"""
from rest_framework_json_api import utils
from ..serializers import EntrySerializer
from ..tests import TestBase
class GetRelatedResourceTests(TestBase):
"""
Ensure the `get_related_resource_type` function returns correct types.
"""
def test_reverse_relation(self):
"""
Ensure reverse foreign keys have their types identified correctly.
"""
serializer = EntrySerializer()
field = serializer.fields['comments']
self.assertEqual(utils.get_related_resource_type(field), 'comments')
|
"""
Test rest_framework_json_api's utils functions.
"""
from rest_framework_json_api import utils
from ..serializers import EntrySerializer
from ..tests import TestBase
class GetRelatedResourceTests(TestBase):
"""
Ensure the `get_related_resource_type` function returns correct types.
"""
def test_reverse_relation(self):
"""
Ensure reverse foreign keys have their types identified correctly.
"""
serializer = EntrySerializer()
field = serializer.fields['comments']
self.assertEqual(utils.get_related_resource_type(field), 'comments')
def test_m2m_relation(self):
"""
Ensure m2ms have their types identified correctly.
"""
serializer = EntrySerializer()
field = serializer.fields['authors']
self.assertEqual(utils.get_related_resource_type(field), 'authors')
|
Add failing test for m2m too.
|
Add failing test for m2m too.
|
Python
|
bsd-2-clause
|
abdulhaq-e/django-rest-framework-json-api,django-json-api/django-rest-framework-json-api,leo-naeka/django-rest-framework-json-api,Instawork/django-rest-framework-json-api,django-json-api/rest_framework_ember,django-json-api/django-rest-framework-json-api
|
"""
Test rest_framework_json_api's utils functions.
"""
from rest_framework_json_api import utils
from ..serializers import EntrySerializer
from ..tests import TestBase
class GetRelatedResourceTests(TestBase):
"""
Ensure the `get_related_resource_type` function returns correct types.
"""
def test_reverse_relation(self):
"""
Ensure reverse foreign keys have their types identified correctly.
"""
serializer = EntrySerializer()
field = serializer.fields['comments']
self.assertEqual(utils.get_related_resource_type(field), 'comments')
Add failing test for m2m too.
|
"""
Test rest_framework_json_api's utils functions.
"""
from rest_framework_json_api import utils
from ..serializers import EntrySerializer
from ..tests import TestBase
class GetRelatedResourceTests(TestBase):
"""
Ensure the `get_related_resource_type` function returns correct types.
"""
def test_reverse_relation(self):
"""
Ensure reverse foreign keys have their types identified correctly.
"""
serializer = EntrySerializer()
field = serializer.fields['comments']
self.assertEqual(utils.get_related_resource_type(field), 'comments')
def test_m2m_relation(self):
"""
Ensure m2ms have their types identified correctly.
"""
serializer = EntrySerializer()
field = serializer.fields['authors']
self.assertEqual(utils.get_related_resource_type(field), 'authors')
|
<commit_before>"""
Test rest_framework_json_api's utils functions.
"""
from rest_framework_json_api import utils
from ..serializers import EntrySerializer
from ..tests import TestBase
class GetRelatedResourceTests(TestBase):
"""
Ensure the `get_related_resource_type` function returns correct types.
"""
def test_reverse_relation(self):
"""
Ensure reverse foreign keys have their types identified correctly.
"""
serializer = EntrySerializer()
field = serializer.fields['comments']
self.assertEqual(utils.get_related_resource_type(field), 'comments')
<commit_msg>Add failing test for m2m too.<commit_after>
|
"""
Test rest_framework_json_api's utils functions.
"""
from rest_framework_json_api import utils
from ..serializers import EntrySerializer
from ..tests import TestBase
class GetRelatedResourceTests(TestBase):
"""
Ensure the `get_related_resource_type` function returns correct types.
"""
def test_reverse_relation(self):
"""
Ensure reverse foreign keys have their types identified correctly.
"""
serializer = EntrySerializer()
field = serializer.fields['comments']
self.assertEqual(utils.get_related_resource_type(field), 'comments')
def test_m2m_relation(self):
"""
Ensure m2ms have their types identified correctly.
"""
serializer = EntrySerializer()
field = serializer.fields['authors']
self.assertEqual(utils.get_related_resource_type(field), 'authors')
|
"""
Test rest_framework_json_api's utils functions.
"""
from rest_framework_json_api import utils
from ..serializers import EntrySerializer
from ..tests import TestBase
class GetRelatedResourceTests(TestBase):
"""
Ensure the `get_related_resource_type` function returns correct types.
"""
def test_reverse_relation(self):
"""
Ensure reverse foreign keys have their types identified correctly.
"""
serializer = EntrySerializer()
field = serializer.fields['comments']
self.assertEqual(utils.get_related_resource_type(field), 'comments')
Add failing test for m2m too."""
Test rest_framework_json_api's utils functions.
"""
from rest_framework_json_api import utils
from ..serializers import EntrySerializer
from ..tests import TestBase
class GetRelatedResourceTests(TestBase):
"""
Ensure the `get_related_resource_type` function returns correct types.
"""
def test_reverse_relation(self):
"""
Ensure reverse foreign keys have their types identified correctly.
"""
serializer = EntrySerializer()
field = serializer.fields['comments']
self.assertEqual(utils.get_related_resource_type(field), 'comments')
def test_m2m_relation(self):
"""
Ensure m2ms have their types identified correctly.
"""
serializer = EntrySerializer()
field = serializer.fields['authors']
self.assertEqual(utils.get_related_resource_type(field), 'authors')
|
<commit_before>"""
Test rest_framework_json_api's utils functions.
"""
from rest_framework_json_api import utils
from ..serializers import EntrySerializer
from ..tests import TestBase
class GetRelatedResourceTests(TestBase):
"""
Ensure the `get_related_resource_type` function returns correct types.
"""
def test_reverse_relation(self):
"""
Ensure reverse foreign keys have their types identified correctly.
"""
serializer = EntrySerializer()
field = serializer.fields['comments']
self.assertEqual(utils.get_related_resource_type(field), 'comments')
<commit_msg>Add failing test for m2m too.<commit_after>"""
Test rest_framework_json_api's utils functions.
"""
from rest_framework_json_api import utils
from ..serializers import EntrySerializer
from ..tests import TestBase
class GetRelatedResourceTests(TestBase):
"""
Ensure the `get_related_resource_type` function returns correct types.
"""
def test_reverse_relation(self):
"""
Ensure reverse foreign keys have their types identified correctly.
"""
serializer = EntrySerializer()
field = serializer.fields['comments']
self.assertEqual(utils.get_related_resource_type(field), 'comments')
def test_m2m_relation(self):
"""
Ensure m2ms have their types identified correctly.
"""
serializer = EntrySerializer()
field = serializer.fields['authors']
self.assertEqual(utils.get_related_resource_type(field), 'authors')
|
e790e47e6b87bc2e49e8b74d491eb023c4468254
|
src/sentry/web/frontend/csrf_failure.py
|
src/sentry/web/frontend/csrf_failure.py
|
from __future__ import absolute_import
from django.middleware.csrf import REASON_NO_REFERER
from sentry.web.frontend.base import BaseView
class CsrfFailureView(BaseView):
auth_required = False
sudo_required = False
def handle(self, request, reason=""):
context = {
'no_referer': reason == REASON_NO_REFERER
}
return self.respond('sentry/403-csrf-failure.html', status=403)
view = CsrfFailureView.as_view()
|
from __future__ import absolute_import
from django.middleware.csrf import REASON_NO_REFERER
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from django.utils.decorators import method_decorator
from sentry.web.helpers import render_to_response
class CsrfFailureView(View):
@method_decorator(csrf_exempt)
def dispatch(self, request, reason=""):
context = {
'no_referer': reason == REASON_NO_REFERER,
'request': request,
}
return render_to_response('sentry/403-csrf-failure.html', context, request,
status=403)
view = CsrfFailureView.as_view()
|
Kill possible recursion on csrf decorator
|
Kill possible recursion on csrf decorator
|
Python
|
bsd-3-clause
|
boneyao/sentry,jean/sentry,boneyao/sentry,mvaled/sentry,felixbuenemann/sentry,kevinlondon/sentry,TedaLIEz/sentry,JamesMura/sentry,kevinastone/sentry,korealerts1/sentry,JackDanger/sentry,songyi199111/sentry,songyi199111/sentry,fuziontech/sentry,JamesMura/sentry,BuildingLink/sentry,camilonova/sentry,wujuguang/sentry,argonemyth/sentry,wujuguang/sentry,pauloschilling/sentry,zenefits/sentry,nicholasserra/sentry,beeftornado/sentry,ewdurbin/sentry,gg7/sentry,Natim/sentry,vperron/sentry,Natim/sentry,korealerts1/sentry,kevinlondon/sentry,alexm92/sentry,wong2/sentry,gencer/sentry,BayanGroup/sentry,fuziontech/sentry,jean/sentry,JTCunning/sentry,alexm92/sentry,drcapulet/sentry,gencer/sentry,ifduyue/sentry,ewdurbin/sentry,imankulov/sentry,felixbuenemann/sentry,hongliang5623/sentry,wujuguang/sentry,pauloschilling/sentry,drcapulet/sentry,looker/sentry,nicholasserra/sentry,Kryz/sentry,mvaled/sentry,ewdurbin/sentry,wong2/sentry,imankulov/sentry,jean/sentry,kevinastone/sentry,1tush/sentry,mvaled/sentry,fotinakis/sentry,1tush/sentry,gencer/sentry,hongliang5623/sentry,vperron/sentry,looker/sentry,JackDanger/sentry,hongliang5623/sentry,zenefits/sentry,nicholasserra/sentry,zenefits/sentry,jokey2k/sentry,JamesMura/sentry,songyi199111/sentry,1tush/sentry,drcapulet/sentry,ngonzalvez/sentry,mvaled/sentry,Kryz/sentry,BayanGroup/sentry,kevinlondon/sentry,daevaorn/sentry,ifduyue/sentry,ifduyue/sentry,fotinakis/sentry,zenefits/sentry,BuildingLink/sentry,camilonova/sentry,JTCunning/sentry,TedaLIEz/sentry,Natim/sentry,ngonzalvez/sentry,llonchj/sentry,BuildingLink/sentry,argonemyth/sentry,jean/sentry,argonemyth/sentry,wong2/sentry,looker/sentry,looker/sentry,vperron/sentry,TedaLIEz/sentry,ngonzalvez/sentry,JamesMura/sentry,camilonova/sentry,beeftornado/sentry,looker/sentry,jokey2k/sentry,zenefits/sentry,BayanGroup/sentry,JackDanger/sentry,daevaorn/sentry,BuildingLink/sentry,gg7/sentry,BuildingLink/sentry,Kryz/sentry,gg7/sentry,JTCunning/sentry,boneyao/sentry,mitsuhiko/sentry,ifduyue/sentry,llonchj/sentry,mvaled/sentry,fotinakis/sentry,korealerts1/sentry,jean/sentry,mvaled/sentry,llonchj/sentry,mitsuhiko/sentry,felixbuenemann/sentry,beeftornado/sentry,fuziontech/sentry,JamesMura/sentry,kevinastone/sentry,imankulov/sentry,daevaorn/sentry,jokey2k/sentry,gencer/sentry,pauloschilling/sentry,gencer/sentry,ifduyue/sentry,fotinakis/sentry,alexm92/sentry,daevaorn/sentry
|
from __future__ import absolute_import
from django.middleware.csrf import REASON_NO_REFERER
from sentry.web.frontend.base import BaseView
class CsrfFailureView(BaseView):
auth_required = False
sudo_required = False
def handle(self, request, reason=""):
context = {
'no_referer': reason == REASON_NO_REFERER
}
return self.respond('sentry/403-csrf-failure.html', status=403)
view = CsrfFailureView.as_view()
Kill possible recursion on csrf decorator
|
from __future__ import absolute_import
from django.middleware.csrf import REASON_NO_REFERER
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from django.utils.decorators import method_decorator
from sentry.web.helpers import render_to_response
class CsrfFailureView(View):
@method_decorator(csrf_exempt)
def dispatch(self, request, reason=""):
context = {
'no_referer': reason == REASON_NO_REFERER,
'request': request,
}
return render_to_response('sentry/403-csrf-failure.html', context, request,
status=403)
view = CsrfFailureView.as_view()
|
<commit_before>from __future__ import absolute_import
from django.middleware.csrf import REASON_NO_REFERER
from sentry.web.frontend.base import BaseView
class CsrfFailureView(BaseView):
auth_required = False
sudo_required = False
def handle(self, request, reason=""):
context = {
'no_referer': reason == REASON_NO_REFERER
}
return self.respond('sentry/403-csrf-failure.html', status=403)
view = CsrfFailureView.as_view()
<commit_msg>Kill possible recursion on csrf decorator<commit_after>
|
from __future__ import absolute_import
from django.middleware.csrf import REASON_NO_REFERER
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from django.utils.decorators import method_decorator
from sentry.web.helpers import render_to_response
class CsrfFailureView(View):
@method_decorator(csrf_exempt)
def dispatch(self, request, reason=""):
context = {
'no_referer': reason == REASON_NO_REFERER,
'request': request,
}
return render_to_response('sentry/403-csrf-failure.html', context, request,
status=403)
view = CsrfFailureView.as_view()
|
from __future__ import absolute_import
from django.middleware.csrf import REASON_NO_REFERER
from sentry.web.frontend.base import BaseView
class CsrfFailureView(BaseView):
auth_required = False
sudo_required = False
def handle(self, request, reason=""):
context = {
'no_referer': reason == REASON_NO_REFERER
}
return self.respond('sentry/403-csrf-failure.html', status=403)
view = CsrfFailureView.as_view()
Kill possible recursion on csrf decoratorfrom __future__ import absolute_import
from django.middleware.csrf import REASON_NO_REFERER
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from django.utils.decorators import method_decorator
from sentry.web.helpers import render_to_response
class CsrfFailureView(View):
@method_decorator(csrf_exempt)
def dispatch(self, request, reason=""):
context = {
'no_referer': reason == REASON_NO_REFERER,
'request': request,
}
return render_to_response('sentry/403-csrf-failure.html', context, request,
status=403)
view = CsrfFailureView.as_view()
|
<commit_before>from __future__ import absolute_import
from django.middleware.csrf import REASON_NO_REFERER
from sentry.web.frontend.base import BaseView
class CsrfFailureView(BaseView):
auth_required = False
sudo_required = False
def handle(self, request, reason=""):
context = {
'no_referer': reason == REASON_NO_REFERER
}
return self.respond('sentry/403-csrf-failure.html', status=403)
view = CsrfFailureView.as_view()
<commit_msg>Kill possible recursion on csrf decorator<commit_after>from __future__ import absolute_import
from django.middleware.csrf import REASON_NO_REFERER
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from django.utils.decorators import method_decorator
from sentry.web.helpers import render_to_response
class CsrfFailureView(View):
@method_decorator(csrf_exempt)
def dispatch(self, request, reason=""):
context = {
'no_referer': reason == REASON_NO_REFERER,
'request': request,
}
return render_to_response('sentry/403-csrf-failure.html', context, request,
status=403)
view = CsrfFailureView.as_view()
|
156d62f15963bc95f52db7eb1493fad6890e2fc7
|
dadi/__init__.py
|
dadi/__init__.py
|
import numpy
# This gives a nicer printout for masked arrays.
numpy.ma.default_real_fill_value = numpy.nan
import IO
import Integration
import PhiManip
import SFS
import ms
try:
import os
__DIRECTORY__ = os.path.dirname(IO.__file__)
__svn_file__ = os.path.join(__DIRECTORY__, 'svnversion')
__SVNVERSION__ = file(__svn_file__).read().strip()
except:
__SVNVERSION__ = 'Unknown'
|
import numpy
# This gives a nicer printout for masked arrays.
numpy.ma.default_real_fill_value = numpy.nan
import IO
import Integration
import PhiManip
import SFS
import ms
import Plotting
try:
import os
__DIRECTORY__ = os.path.dirname(IO.__file__)
__svn_file__ = os.path.join(__DIRECTORY__, 'svnversion')
__SVNVERSION__ = file(__svn_file__).read().strip()
except:
__SVNVERSION__ = 'Unknown'
|
Add Plotting to default imports.
|
Add Plotting to default imports.
git-svn-id: 4c7b13231a96299fde701bb5dec4bd2aaf383fc6@43 979d6bd5-6d4d-0410-bece-f567c23bd345
|
Python
|
bsd-3-clause
|
beni55/dadi,beni55/dadi,ChenHsiang/dadi,RyanGutenkunst/dadi,paulirish/dadi,yangjl/dadi,ChenHsiang/dadi,cheese1213/dadi,yangjl/dadi,cheese1213/dadi,paulirish/dadi,niuhuifei/dadi,niuhuifei/dadi,RyanGutenkunst/dadi
|
import numpy
# This gives a nicer printout for masked arrays.
numpy.ma.default_real_fill_value = numpy.nan
import IO
import Integration
import PhiManip
import SFS
import ms
try:
import os
__DIRECTORY__ = os.path.dirname(IO.__file__)
__svn_file__ = os.path.join(__DIRECTORY__, 'svnversion')
__SVNVERSION__ = file(__svn_file__).read().strip()
except:
__SVNVERSION__ = 'Unknown'
Add Plotting to default imports.
git-svn-id: 4c7b13231a96299fde701bb5dec4bd2aaf383fc6@43 979d6bd5-6d4d-0410-bece-f567c23bd345
|
import numpy
# This gives a nicer printout for masked arrays.
numpy.ma.default_real_fill_value = numpy.nan
import IO
import Integration
import PhiManip
import SFS
import ms
import Plotting
try:
import os
__DIRECTORY__ = os.path.dirname(IO.__file__)
__svn_file__ = os.path.join(__DIRECTORY__, 'svnversion')
__SVNVERSION__ = file(__svn_file__).read().strip()
except:
__SVNVERSION__ = 'Unknown'
|
<commit_before>import numpy
# This gives a nicer printout for masked arrays.
numpy.ma.default_real_fill_value = numpy.nan
import IO
import Integration
import PhiManip
import SFS
import ms
try:
import os
__DIRECTORY__ = os.path.dirname(IO.__file__)
__svn_file__ = os.path.join(__DIRECTORY__, 'svnversion')
__SVNVERSION__ = file(__svn_file__).read().strip()
except:
__SVNVERSION__ = 'Unknown'
<commit_msg>Add Plotting to default imports.
git-svn-id: 4c7b13231a96299fde701bb5dec4bd2aaf383fc6@43 979d6bd5-6d4d-0410-bece-f567c23bd345<commit_after>
|
import numpy
# This gives a nicer printout for masked arrays.
numpy.ma.default_real_fill_value = numpy.nan
import IO
import Integration
import PhiManip
import SFS
import ms
import Plotting
try:
import os
__DIRECTORY__ = os.path.dirname(IO.__file__)
__svn_file__ = os.path.join(__DIRECTORY__, 'svnversion')
__SVNVERSION__ = file(__svn_file__).read().strip()
except:
__SVNVERSION__ = 'Unknown'
|
import numpy
# This gives a nicer printout for masked arrays.
numpy.ma.default_real_fill_value = numpy.nan
import IO
import Integration
import PhiManip
import SFS
import ms
try:
import os
__DIRECTORY__ = os.path.dirname(IO.__file__)
__svn_file__ = os.path.join(__DIRECTORY__, 'svnversion')
__SVNVERSION__ = file(__svn_file__).read().strip()
except:
__SVNVERSION__ = 'Unknown'
Add Plotting to default imports.
git-svn-id: 4c7b13231a96299fde701bb5dec4bd2aaf383fc6@43 979d6bd5-6d4d-0410-bece-f567c23bd345import numpy
# This gives a nicer printout for masked arrays.
numpy.ma.default_real_fill_value = numpy.nan
import IO
import Integration
import PhiManip
import SFS
import ms
import Plotting
try:
import os
__DIRECTORY__ = os.path.dirname(IO.__file__)
__svn_file__ = os.path.join(__DIRECTORY__, 'svnversion')
__SVNVERSION__ = file(__svn_file__).read().strip()
except:
__SVNVERSION__ = 'Unknown'
|
<commit_before>import numpy
# This gives a nicer printout for masked arrays.
numpy.ma.default_real_fill_value = numpy.nan
import IO
import Integration
import PhiManip
import SFS
import ms
try:
import os
__DIRECTORY__ = os.path.dirname(IO.__file__)
__svn_file__ = os.path.join(__DIRECTORY__, 'svnversion')
__SVNVERSION__ = file(__svn_file__).read().strip()
except:
__SVNVERSION__ = 'Unknown'
<commit_msg>Add Plotting to default imports.
git-svn-id: 4c7b13231a96299fde701bb5dec4bd2aaf383fc6@43 979d6bd5-6d4d-0410-bece-f567c23bd345<commit_after>import numpy
# This gives a nicer printout for masked arrays.
numpy.ma.default_real_fill_value = numpy.nan
import IO
import Integration
import PhiManip
import SFS
import ms
import Plotting
try:
import os
__DIRECTORY__ = os.path.dirname(IO.__file__)
__svn_file__ = os.path.join(__DIRECTORY__, 'svnversion')
__SVNVERSION__ = file(__svn_file__).read().strip()
except:
__SVNVERSION__ = 'Unknown'
|
cb72e1107096df9b80915fad4ee0fd1d930c7b59
|
examples/redis/src/bolts.py
|
examples/redis/src/bolts.py
|
from collections import Counter
from redis import StrictRedis
from streamparse import Bolt
class WordCountBolt(Bolt):
outputs = ['word', 'count']
def initialize(self, conf, ctx):
self.counter = Counter()
self.total = 0
def _increment(self, word, inc_by):
self.counter[word] += inc_by
self.total += inc_by
def process(self, tup):
word = tup.values[0]
self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, self.counter[word]])
class RedisWordCountBolt(Bolt):
def initialize(self, conf, ctx):
self.redis = StrictRedis()
self.total = 0
def _increment(self, word, inc_by):
self.total += inc_by
return self.redis.zincrby("words", word, inc_by)
def process(self, tup):
word = tup.values[0]
count = self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, count])
|
from collections import Counter
from redis import StrictRedis
from streamparse import Bolt
class WordCountBolt(Bolt):
outputs = ['word', 'count']
def initialize(self, conf, ctx):
self.counter = Counter()
self.total = 0
def _increment(self, word, inc_by):
self.counter[word] += inc_by
self.total += inc_by
def process(self, tup):
word = tup.values[0]
self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, self.counter[word]])
class RedisWordCountBolt(Bolt):
outputs = ['word', 'count']
def initialize(self, conf, ctx):
self.redis = StrictRedis()
self.total = 0
def _increment(self, word, inc_by):
self.total += inc_by
return self.redis.zincrby("words", word, inc_by)
def process(self, tup):
word = tup.values[0]
count = self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, count])
|
Add missing outputs to wordcount_mem topology
|
Add missing outputs to wordcount_mem topology
|
Python
|
apache-2.0
|
Parsely/streamparse,Parsely/streamparse
|
from collections import Counter
from redis import StrictRedis
from streamparse import Bolt
class WordCountBolt(Bolt):
outputs = ['word', 'count']
def initialize(self, conf, ctx):
self.counter = Counter()
self.total = 0
def _increment(self, word, inc_by):
self.counter[word] += inc_by
self.total += inc_by
def process(self, tup):
word = tup.values[0]
self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, self.counter[word]])
class RedisWordCountBolt(Bolt):
def initialize(self, conf, ctx):
self.redis = StrictRedis()
self.total = 0
def _increment(self, word, inc_by):
self.total += inc_by
return self.redis.zincrby("words", word, inc_by)
def process(self, tup):
word = tup.values[0]
count = self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, count])
Add missing outputs to wordcount_mem topology
|
from collections import Counter
from redis import StrictRedis
from streamparse import Bolt
class WordCountBolt(Bolt):
outputs = ['word', 'count']
def initialize(self, conf, ctx):
self.counter = Counter()
self.total = 0
def _increment(self, word, inc_by):
self.counter[word] += inc_by
self.total += inc_by
def process(self, tup):
word = tup.values[0]
self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, self.counter[word]])
class RedisWordCountBolt(Bolt):
outputs = ['word', 'count']
def initialize(self, conf, ctx):
self.redis = StrictRedis()
self.total = 0
def _increment(self, word, inc_by):
self.total += inc_by
return self.redis.zincrby("words", word, inc_by)
def process(self, tup):
word = tup.values[0]
count = self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, count])
|
<commit_before>from collections import Counter
from redis import StrictRedis
from streamparse import Bolt
class WordCountBolt(Bolt):
outputs = ['word', 'count']
def initialize(self, conf, ctx):
self.counter = Counter()
self.total = 0
def _increment(self, word, inc_by):
self.counter[word] += inc_by
self.total += inc_by
def process(self, tup):
word = tup.values[0]
self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, self.counter[word]])
class RedisWordCountBolt(Bolt):
def initialize(self, conf, ctx):
self.redis = StrictRedis()
self.total = 0
def _increment(self, word, inc_by):
self.total += inc_by
return self.redis.zincrby("words", word, inc_by)
def process(self, tup):
word = tup.values[0]
count = self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, count])
<commit_msg>Add missing outputs to wordcount_mem topology<commit_after>
|
from collections import Counter
from redis import StrictRedis
from streamparse import Bolt
class WordCountBolt(Bolt):
outputs = ['word', 'count']
def initialize(self, conf, ctx):
self.counter = Counter()
self.total = 0
def _increment(self, word, inc_by):
self.counter[word] += inc_by
self.total += inc_by
def process(self, tup):
word = tup.values[0]
self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, self.counter[word]])
class RedisWordCountBolt(Bolt):
outputs = ['word', 'count']
def initialize(self, conf, ctx):
self.redis = StrictRedis()
self.total = 0
def _increment(self, word, inc_by):
self.total += inc_by
return self.redis.zincrby("words", word, inc_by)
def process(self, tup):
word = tup.values[0]
count = self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, count])
|
from collections import Counter
from redis import StrictRedis
from streamparse import Bolt
class WordCountBolt(Bolt):
outputs = ['word', 'count']
def initialize(self, conf, ctx):
self.counter = Counter()
self.total = 0
def _increment(self, word, inc_by):
self.counter[word] += inc_by
self.total += inc_by
def process(self, tup):
word = tup.values[0]
self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, self.counter[word]])
class RedisWordCountBolt(Bolt):
def initialize(self, conf, ctx):
self.redis = StrictRedis()
self.total = 0
def _increment(self, word, inc_by):
self.total += inc_by
return self.redis.zincrby("words", word, inc_by)
def process(self, tup):
word = tup.values[0]
count = self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, count])
Add missing outputs to wordcount_mem topologyfrom collections import Counter
from redis import StrictRedis
from streamparse import Bolt
class WordCountBolt(Bolt):
outputs = ['word', 'count']
def initialize(self, conf, ctx):
self.counter = Counter()
self.total = 0
def _increment(self, word, inc_by):
self.counter[word] += inc_by
self.total += inc_by
def process(self, tup):
word = tup.values[0]
self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, self.counter[word]])
class RedisWordCountBolt(Bolt):
outputs = ['word', 'count']
def initialize(self, conf, ctx):
self.redis = StrictRedis()
self.total = 0
def _increment(self, word, inc_by):
self.total += inc_by
return self.redis.zincrby("words", word, inc_by)
def process(self, tup):
word = tup.values[0]
count = self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, count])
|
<commit_before>from collections import Counter
from redis import StrictRedis
from streamparse import Bolt
class WordCountBolt(Bolt):
outputs = ['word', 'count']
def initialize(self, conf, ctx):
self.counter = Counter()
self.total = 0
def _increment(self, word, inc_by):
self.counter[word] += inc_by
self.total += inc_by
def process(self, tup):
word = tup.values[0]
self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, self.counter[word]])
class RedisWordCountBolt(Bolt):
def initialize(self, conf, ctx):
self.redis = StrictRedis()
self.total = 0
def _increment(self, word, inc_by):
self.total += inc_by
return self.redis.zincrby("words", word, inc_by)
def process(self, tup):
word = tup.values[0]
count = self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, count])
<commit_msg>Add missing outputs to wordcount_mem topology<commit_after>from collections import Counter
from redis import StrictRedis
from streamparse import Bolt
class WordCountBolt(Bolt):
outputs = ['word', 'count']
def initialize(self, conf, ctx):
self.counter = Counter()
self.total = 0
def _increment(self, word, inc_by):
self.counter[word] += inc_by
self.total += inc_by
def process(self, tup):
word = tup.values[0]
self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, self.counter[word]])
class RedisWordCountBolt(Bolt):
outputs = ['word', 'count']
def initialize(self, conf, ctx):
self.redis = StrictRedis()
self.total = 0
def _increment(self, word, inc_by):
self.total += inc_by
return self.redis.zincrby("words", word, inc_by)
def process(self, tup):
word = tup.values[0]
count = self._increment(word, 10 if word == "dog" else 1)
if self.total % 1000 == 0:
self.logger.info("counted %i words", self.total)
self.emit([word, count])
|
9ad0ecfd45fa82421a6a4faf961724d97180e904
|
setup.py
|
setup.py
|
from setuptools import setup
import os
version = 0.1
setup(
version=version,
description="A script allowing to setup Amazon EC2 instances through configuration files.",
long_description=open("README.txt").read() + "\n\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
name="mr.awsome",
author='Florian Schulze',
author_email='florian.schulze@gmx.net',
include_package_data=True,
zip_safe=False,
packages=['mr'],
namespace_packages=['mr'],
install_requires=[
'setuptools',
'boto',
'Fabric',
],
)
|
from setuptools import setup
import os
version = 0.1
setup(
version=version,
description="A script allowing to setup Amazon EC2 instances through configuration files.",
long_description=open("README.txt").read() + "\n\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
name="mr.awsome",
author='Florian Schulze',
author_email='florian.schulze@gmx.net',
url='http://github.com/fschulze/mr.awsome',
include_package_data=True,
zip_safe=False,
packages=['mr'],
namespace_packages=['mr'],
install_requires=[
'setuptools',
'boto',
'Fabric',
],
)
|
Add a url to github.
|
Add a url to github.
|
Python
|
bsd-3-clause
|
fschulze/ploy,ployground/ploy_ec2,ployground/ploy_fabric,ployground/ploy
|
from setuptools import setup
import os
version = 0.1
setup(
version=version,
description="A script allowing to setup Amazon EC2 instances through configuration files.",
long_description=open("README.txt").read() + "\n\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
name="mr.awsome",
author='Florian Schulze',
author_email='florian.schulze@gmx.net',
include_package_data=True,
zip_safe=False,
packages=['mr'],
namespace_packages=['mr'],
install_requires=[
'setuptools',
'boto',
'Fabric',
],
)Add a url to github.
|
from setuptools import setup
import os
version = 0.1
setup(
version=version,
description="A script allowing to setup Amazon EC2 instances through configuration files.",
long_description=open("README.txt").read() + "\n\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
name="mr.awsome",
author='Florian Schulze',
author_email='florian.schulze@gmx.net',
url='http://github.com/fschulze/mr.awsome',
include_package_data=True,
zip_safe=False,
packages=['mr'],
namespace_packages=['mr'],
install_requires=[
'setuptools',
'boto',
'Fabric',
],
)
|
<commit_before>from setuptools import setup
import os
version = 0.1
setup(
version=version,
description="A script allowing to setup Amazon EC2 instances through configuration files.",
long_description=open("README.txt").read() + "\n\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
name="mr.awsome",
author='Florian Schulze',
author_email='florian.schulze@gmx.net',
include_package_data=True,
zip_safe=False,
packages=['mr'],
namespace_packages=['mr'],
install_requires=[
'setuptools',
'boto',
'Fabric',
],
)<commit_msg>Add a url to github.<commit_after>
|
from setuptools import setup
import os
version = 0.1
setup(
version=version,
description="A script allowing to setup Amazon EC2 instances through configuration files.",
long_description=open("README.txt").read() + "\n\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
name="mr.awsome",
author='Florian Schulze',
author_email='florian.schulze@gmx.net',
url='http://github.com/fschulze/mr.awsome',
include_package_data=True,
zip_safe=False,
packages=['mr'],
namespace_packages=['mr'],
install_requires=[
'setuptools',
'boto',
'Fabric',
],
)
|
from setuptools import setup
import os
version = 0.1
setup(
version=version,
description="A script allowing to setup Amazon EC2 instances through configuration files.",
long_description=open("README.txt").read() + "\n\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
name="mr.awsome",
author='Florian Schulze',
author_email='florian.schulze@gmx.net',
include_package_data=True,
zip_safe=False,
packages=['mr'],
namespace_packages=['mr'],
install_requires=[
'setuptools',
'boto',
'Fabric',
],
)Add a url to github.from setuptools import setup
import os
version = 0.1
setup(
version=version,
description="A script allowing to setup Amazon EC2 instances through configuration files.",
long_description=open("README.txt").read() + "\n\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
name="mr.awsome",
author='Florian Schulze',
author_email='florian.schulze@gmx.net',
url='http://github.com/fschulze/mr.awsome',
include_package_data=True,
zip_safe=False,
packages=['mr'],
namespace_packages=['mr'],
install_requires=[
'setuptools',
'boto',
'Fabric',
],
)
|
<commit_before>from setuptools import setup
import os
version = 0.1
setup(
version=version,
description="A script allowing to setup Amazon EC2 instances through configuration files.",
long_description=open("README.txt").read() + "\n\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
name="mr.awsome",
author='Florian Schulze',
author_email='florian.schulze@gmx.net',
include_package_data=True,
zip_safe=False,
packages=['mr'],
namespace_packages=['mr'],
install_requires=[
'setuptools',
'boto',
'Fabric',
],
)<commit_msg>Add a url to github.<commit_after>from setuptools import setup
import os
version = 0.1
setup(
version=version,
description="A script allowing to setup Amazon EC2 instances through configuration files.",
long_description=open("README.txt").read() + "\n\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
name="mr.awsome",
author='Florian Schulze',
author_email='florian.schulze@gmx.net',
url='http://github.com/fschulze/mr.awsome',
include_package_data=True,
zip_safe=False,
packages=['mr'],
namespace_packages=['mr'],
install_requires=[
'setuptools',
'boto',
'Fabric',
],
)
|
2340b8047584a29ca75d3b674f67bdc96e9f94e3
|
setup.py
|
setup.py
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-utils',
version='0.11',
packages=['moj_utils', 'moj_utils.templatetags'],
include_package_data=True,
license='BSD License',
description='A set of utilities for MoJ Django-based services',
long_description=README,
install_requires=['Django>=1.8,<1.9'],
classifiers=[
'Framework :: Django',
'Intended Audience :: MoJ Developers',
'Programming Language :: Python :: 3.4',
],
test_suite='runtests.runtests',
)
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-utils',
version='0.11',
packages=['moj_utils', 'moj_utils.templatetags'],
include_package_data=True,
license='BSD License',
description='A set of utilities for MoJ Django-based services',
long_description=README,
install_requires=['Django>=1.8'],
classifiers=[
'Framework :: Django',
'Intended Audience :: MoJ Developers',
'Programming Language :: Python :: 3.4',
],
test_suite='runtests.runtests',
)
|
Remove <1.9 version limit on Django version
|
Remove <1.9 version limit on Django version
|
Python
|
mit
|
ministryofjustice/django-utils,ministryofjustice/django-utils
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-utils',
version='0.11',
packages=['moj_utils', 'moj_utils.templatetags'],
include_package_data=True,
license='BSD License',
description='A set of utilities for MoJ Django-based services',
long_description=README,
install_requires=['Django>=1.8,<1.9'],
classifiers=[
'Framework :: Django',
'Intended Audience :: MoJ Developers',
'Programming Language :: Python :: 3.4',
],
test_suite='runtests.runtests',
)
Remove <1.9 version limit on Django version
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-utils',
version='0.11',
packages=['moj_utils', 'moj_utils.templatetags'],
include_package_data=True,
license='BSD License',
description='A set of utilities for MoJ Django-based services',
long_description=README,
install_requires=['Django>=1.8'],
classifiers=[
'Framework :: Django',
'Intended Audience :: MoJ Developers',
'Programming Language :: Python :: 3.4',
],
test_suite='runtests.runtests',
)
|
<commit_before>import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-utils',
version='0.11',
packages=['moj_utils', 'moj_utils.templatetags'],
include_package_data=True,
license='BSD License',
description='A set of utilities for MoJ Django-based services',
long_description=README,
install_requires=['Django>=1.8,<1.9'],
classifiers=[
'Framework :: Django',
'Intended Audience :: MoJ Developers',
'Programming Language :: Python :: 3.4',
],
test_suite='runtests.runtests',
)
<commit_msg>Remove <1.9 version limit on Django version<commit_after>
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-utils',
version='0.11',
packages=['moj_utils', 'moj_utils.templatetags'],
include_package_data=True,
license='BSD License',
description='A set of utilities for MoJ Django-based services',
long_description=README,
install_requires=['Django>=1.8'],
classifiers=[
'Framework :: Django',
'Intended Audience :: MoJ Developers',
'Programming Language :: Python :: 3.4',
],
test_suite='runtests.runtests',
)
|
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-utils',
version='0.11',
packages=['moj_utils', 'moj_utils.templatetags'],
include_package_data=True,
license='BSD License',
description='A set of utilities for MoJ Django-based services',
long_description=README,
install_requires=['Django>=1.8,<1.9'],
classifiers=[
'Framework :: Django',
'Intended Audience :: MoJ Developers',
'Programming Language :: Python :: 3.4',
],
test_suite='runtests.runtests',
)
Remove <1.9 version limit on Django versionimport os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-utils',
version='0.11',
packages=['moj_utils', 'moj_utils.templatetags'],
include_package_data=True,
license='BSD License',
description='A set of utilities for MoJ Django-based services',
long_description=README,
install_requires=['Django>=1.8'],
classifiers=[
'Framework :: Django',
'Intended Audience :: MoJ Developers',
'Programming Language :: Python :: 3.4',
],
test_suite='runtests.runtests',
)
|
<commit_before>import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-utils',
version='0.11',
packages=['moj_utils', 'moj_utils.templatetags'],
include_package_data=True,
license='BSD License',
description='A set of utilities for MoJ Django-based services',
long_description=README,
install_requires=['Django>=1.8,<1.9'],
classifiers=[
'Framework :: Django',
'Intended Audience :: MoJ Developers',
'Programming Language :: Python :: 3.4',
],
test_suite='runtests.runtests',
)
<commit_msg>Remove <1.9 version limit on Django version<commit_after>import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-utils',
version='0.11',
packages=['moj_utils', 'moj_utils.templatetags'],
include_package_data=True,
license='BSD License',
description='A set of utilities for MoJ Django-based services',
long_description=README,
install_requires=['Django>=1.8'],
classifiers=[
'Framework :: Django',
'Intended Audience :: MoJ Developers',
'Programming Language :: Python :: 3.4',
],
test_suite='runtests.runtests',
)
|
933fcfff7a9c63b03e13b0bb7756f0530603c556
|
series.py
|
series.py
|
"""Read and print an integer series."""
import sys
def read_series(filename):
f = open(filename, mode='rt', encoding='utf-8')
series = []
for line in f:
a = int(line.strip())
series.append(a)
f.close()
return series
def main(filename):
print(read_series(filename))
if __name__ == '__main__':
main(sys.argv[1])
|
"""Read and print an integer series."""
import sys
def read_series(filename):
try:
f = open(filename, mode='rt', encoding='utf-8')
return [int(line.strip()) for line in f]
finally:
f.close()
def main(filename):
print(read_series(filename))
if __name__ == '__main__':
main(sys.argv[1])
|
Refactor to ensure closing and also use list comprehension
|
Refactor to ensure closing and also use list comprehension
|
Python
|
mit
|
kentoj/python-fundamentals
|
"""Read and print an integer series."""
import sys
def read_series(filename):
f = open(filename, mode='rt', encoding='utf-8')
series = []
for line in f:
a = int(line.strip())
series.append(a)
f.close()
return series
def main(filename):
print(read_series(filename))
if __name__ == '__main__':
main(sys.argv[1])
Refactor to ensure closing and also use list comprehension
|
"""Read and print an integer series."""
import sys
def read_series(filename):
try:
f = open(filename, mode='rt', encoding='utf-8')
return [int(line.strip()) for line in f]
finally:
f.close()
def main(filename):
print(read_series(filename))
if __name__ == '__main__':
main(sys.argv[1])
|
<commit_before>"""Read and print an integer series."""
import sys
def read_series(filename):
f = open(filename, mode='rt', encoding='utf-8')
series = []
for line in f:
a = int(line.strip())
series.append(a)
f.close()
return series
def main(filename):
print(read_series(filename))
if __name__ == '__main__':
main(sys.argv[1])
<commit_msg>Refactor to ensure closing and also use list comprehension<commit_after>
|
"""Read and print an integer series."""
import sys
def read_series(filename):
try:
f = open(filename, mode='rt', encoding='utf-8')
return [int(line.strip()) for line in f]
finally:
f.close()
def main(filename):
print(read_series(filename))
if __name__ == '__main__':
main(sys.argv[1])
|
"""Read and print an integer series."""
import sys
def read_series(filename):
f = open(filename, mode='rt', encoding='utf-8')
series = []
for line in f:
a = int(line.strip())
series.append(a)
f.close()
return series
def main(filename):
print(read_series(filename))
if __name__ == '__main__':
main(sys.argv[1])
Refactor to ensure closing and also use list comprehension"""Read and print an integer series."""
import sys
def read_series(filename):
try:
f = open(filename, mode='rt', encoding='utf-8')
return [int(line.strip()) for line in f]
finally:
f.close()
def main(filename):
print(read_series(filename))
if __name__ == '__main__':
main(sys.argv[1])
|
<commit_before>"""Read and print an integer series."""
import sys
def read_series(filename):
f = open(filename, mode='rt', encoding='utf-8')
series = []
for line in f:
a = int(line.strip())
series.append(a)
f.close()
return series
def main(filename):
print(read_series(filename))
if __name__ == '__main__':
main(sys.argv[1])
<commit_msg>Refactor to ensure closing and also use list comprehension<commit_after>"""Read and print an integer series."""
import sys
def read_series(filename):
try:
f = open(filename, mode='rt', encoding='utf-8')
return [int(line.strip()) for line in f]
finally:
f.close()
def main(filename):
print(read_series(filename))
if __name__ == '__main__':
main(sys.argv[1])
|
fcd1dd23be83d45307564428150924d266fa48f4
|
setup.py
|
setup.py
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.5',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
#setup_requires=[
# 'nose==1.3.1',
# 'mock==1.0.1',
# 'six==1.5.2',
# 'blinker==1.3',
#],
install_requires=[
'Flask>=0.10.1',
],
# Install these with "pip install -e '.[paging]'" or '.[docs]'
extras_require={
'paging': 'pycrypto>=2.6',
'docs': 'sphinx',
}
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.5',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
#setup_requires=[
# 'nose==1.3.1',
# 'mock==1.0.1',
# 'six==1.5.2',
# 'blinker==1.3',
#],
install_requires=[
'Flask==0.12.3',
],
# Install these with "pip install -e '.[paging]'" or '.[docs]'
extras_require={
'paging': 'pycrypto>=2.6',
'docs': 'sphinx',
}
)
|
Fix flask version after vulnerability
|
Fix flask version after vulnerability
No ambiguity left to ensure version is above vulnerable one
|
Python
|
bsd-3-clause
|
CanalTP/flask-restful
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.5',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
#setup_requires=[
# 'nose==1.3.1',
# 'mock==1.0.1',
# 'six==1.5.2',
# 'blinker==1.3',
#],
install_requires=[
'Flask>=0.10.1',
],
# Install these with "pip install -e '.[paging]'" or '.[docs]'
extras_require={
'paging': 'pycrypto>=2.6',
'docs': 'sphinx',
}
)
Fix flask version after vulnerability
No ambiguity left to ensure version is above vulnerable one
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.5',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
#setup_requires=[
# 'nose==1.3.1',
# 'mock==1.0.1',
# 'six==1.5.2',
# 'blinker==1.3',
#],
install_requires=[
'Flask==0.12.3',
],
# Install these with "pip install -e '.[paging]'" or '.[docs]'
extras_require={
'paging': 'pycrypto>=2.6',
'docs': 'sphinx',
}
)
|
<commit_before>#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.5',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
#setup_requires=[
# 'nose==1.3.1',
# 'mock==1.0.1',
# 'six==1.5.2',
# 'blinker==1.3',
#],
install_requires=[
'Flask>=0.10.1',
],
# Install these with "pip install -e '.[paging]'" or '.[docs]'
extras_require={
'paging': 'pycrypto>=2.6',
'docs': 'sphinx',
}
)
<commit_msg>Fix flask version after vulnerability
No ambiguity left to ensure version is above vulnerable one<commit_after>
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.5',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
#setup_requires=[
# 'nose==1.3.1',
# 'mock==1.0.1',
# 'six==1.5.2',
# 'blinker==1.3',
#],
install_requires=[
'Flask==0.12.3',
],
# Install these with "pip install -e '.[paging]'" or '.[docs]'
extras_require={
'paging': 'pycrypto>=2.6',
'docs': 'sphinx',
}
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.5',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
#setup_requires=[
# 'nose==1.3.1',
# 'mock==1.0.1',
# 'six==1.5.2',
# 'blinker==1.3',
#],
install_requires=[
'Flask>=0.10.1',
],
# Install these with "pip install -e '.[paging]'" or '.[docs]'
extras_require={
'paging': 'pycrypto>=2.6',
'docs': 'sphinx',
}
)
Fix flask version after vulnerability
No ambiguity left to ensure version is above vulnerable one#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.5',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
#setup_requires=[
# 'nose==1.3.1',
# 'mock==1.0.1',
# 'six==1.5.2',
# 'blinker==1.3',
#],
install_requires=[
'Flask==0.12.3',
],
# Install these with "pip install -e '.[paging]'" or '.[docs]'
extras_require={
'paging': 'pycrypto>=2.6',
'docs': 'sphinx',
}
)
|
<commit_before>#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.5',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
#setup_requires=[
# 'nose==1.3.1',
# 'mock==1.0.1',
# 'six==1.5.2',
# 'blinker==1.3',
#],
install_requires=[
'Flask>=0.10.1',
],
# Install these with "pip install -e '.[paging]'" or '.[docs]'
extras_require={
'paging': 'pycrypto>=2.6',
'docs': 'sphinx',
}
)
<commit_msg>Fix flask version after vulnerability
No ambiguity left to ensure version is above vulnerable one<commit_after>#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.5',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
#setup_requires=[
# 'nose==1.3.1',
# 'mock==1.0.1',
# 'six==1.5.2',
# 'blinker==1.3',
#],
install_requires=[
'Flask==0.12.3',
],
# Install these with "pip install -e '.[paging]'" or '.[docs]'
extras_require={
'paging': 'pycrypto>=2.6',
'docs': 'sphinx',
}
)
|
35c44f0f585d11dea632e509b9eec20d4697dc9d
|
functions/eitu/timeedit_to_csv.py
|
functions/eitu/timeedit_to_csv.py
|
import requests
import csv
import ics_parser
URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics'
URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics'
def fetch_and_parse(url):
return ics_parser.parse(requests.get(url).text)
# Fetch and parse iCalendar events
study_activities = fetch_and_parse(URL_STUDY_ACTIVITIES)
activities = fetch_and_parse(URL_ACTIVITIES)
events = study_activities + activities
# Remove duplicate events
events = {e['UID']: e for e in events}.values()
# Write csv
with open('timeedit.csv', 'w') as csvfile:
fieldnames = set()
for e in events: fieldnames = fieldnames | set(e.keys())
writer = csv.DictWriter(csvfile, fieldnames=sorted(list(fieldnames)))
writer.writeheader()
for e in events: writer.writerow(e)
|
import requests
import csv
from datetime import datetime
import ics_parser
URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics'
URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics'
def fetch_and_parse(url):
return ics_parser.parse(requests.get(url).text)
# Fetch and parse iCalendar events
study_activities = fetch_and_parse(URL_STUDY_ACTIVITIES)
activities = fetch_and_parse(URL_ACTIVITIES)
events = study_activities + activities
# Remove duplicates and sort
events = {e['UID']: e for e in events}.values()
events = sorted(events, key=lambda e: e['DTSTART'])
# Write csv
with open('timeedit.csv', 'w') as csvfile:
fieldnames = set()
for e in events: fieldnames = fieldnames | set(e.keys())
writer = csv.DictWriter(csvfile, fieldnames=sorted(list(fieldnames)))
writer.writeheader()
for e in events:
for key, value in e.items():
if isinstance(value, datetime): e[key] = value.isoformat()
writer.writerow(e)
|
Sort events by start and iso format datetimes
|
Sort events by start and iso format datetimes
|
Python
|
mit
|
christianknu/eitu,christianknu/eitu,eitu/eitu,christianknu/eitu,eitu/eitu
|
import requests
import csv
import ics_parser
URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics'
URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics'
def fetch_and_parse(url):
return ics_parser.parse(requests.get(url).text)
# Fetch and parse iCalendar events
study_activities = fetch_and_parse(URL_STUDY_ACTIVITIES)
activities = fetch_and_parse(URL_ACTIVITIES)
events = study_activities + activities
# Remove duplicate events
events = {e['UID']: e for e in events}.values()
# Write csv
with open('timeedit.csv', 'w') as csvfile:
fieldnames = set()
for e in events: fieldnames = fieldnames | set(e.keys())
writer = csv.DictWriter(csvfile, fieldnames=sorted(list(fieldnames)))
writer.writeheader()
for e in events: writer.writerow(e)
Sort events by start and iso format datetimes
|
import requests
import csv
from datetime import datetime
import ics_parser
URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics'
URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics'
def fetch_and_parse(url):
return ics_parser.parse(requests.get(url).text)
# Fetch and parse iCalendar events
study_activities = fetch_and_parse(URL_STUDY_ACTIVITIES)
activities = fetch_and_parse(URL_ACTIVITIES)
events = study_activities + activities
# Remove duplicates and sort
events = {e['UID']: e for e in events}.values()
events = sorted(events, key=lambda e: e['DTSTART'])
# Write csv
with open('timeedit.csv', 'w') as csvfile:
fieldnames = set()
for e in events: fieldnames = fieldnames | set(e.keys())
writer = csv.DictWriter(csvfile, fieldnames=sorted(list(fieldnames)))
writer.writeheader()
for e in events:
for key, value in e.items():
if isinstance(value, datetime): e[key] = value.isoformat()
writer.writerow(e)
|
<commit_before>import requests
import csv
import ics_parser
URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics'
URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics'
def fetch_and_parse(url):
return ics_parser.parse(requests.get(url).text)
# Fetch and parse iCalendar events
study_activities = fetch_and_parse(URL_STUDY_ACTIVITIES)
activities = fetch_and_parse(URL_ACTIVITIES)
events = study_activities + activities
# Remove duplicate events
events = {e['UID']: e for e in events}.values()
# Write csv
with open('timeedit.csv', 'w') as csvfile:
fieldnames = set()
for e in events: fieldnames = fieldnames | set(e.keys())
writer = csv.DictWriter(csvfile, fieldnames=sorted(list(fieldnames)))
writer.writeheader()
for e in events: writer.writerow(e)
<commit_msg>Sort events by start and iso format datetimes<commit_after>
|
import requests
import csv
from datetime import datetime
import ics_parser
URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics'
URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics'
def fetch_and_parse(url):
return ics_parser.parse(requests.get(url).text)
# Fetch and parse iCalendar events
study_activities = fetch_and_parse(URL_STUDY_ACTIVITIES)
activities = fetch_and_parse(URL_ACTIVITIES)
events = study_activities + activities
# Remove duplicates and sort
events = {e['UID']: e for e in events}.values()
events = sorted(events, key=lambda e: e['DTSTART'])
# Write csv
with open('timeedit.csv', 'w') as csvfile:
fieldnames = set()
for e in events: fieldnames = fieldnames | set(e.keys())
writer = csv.DictWriter(csvfile, fieldnames=sorted(list(fieldnames)))
writer.writeheader()
for e in events:
for key, value in e.items():
if isinstance(value, datetime): e[key] = value.isoformat()
writer.writerow(e)
|
import requests
import csv
import ics_parser
URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics'
URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics'
def fetch_and_parse(url):
return ics_parser.parse(requests.get(url).text)
# Fetch and parse iCalendar events
study_activities = fetch_and_parse(URL_STUDY_ACTIVITIES)
activities = fetch_and_parse(URL_ACTIVITIES)
events = study_activities + activities
# Remove duplicate events
events = {e['UID']: e for e in events}.values()
# Write csv
with open('timeedit.csv', 'w') as csvfile:
fieldnames = set()
for e in events: fieldnames = fieldnames | set(e.keys())
writer = csv.DictWriter(csvfile, fieldnames=sorted(list(fieldnames)))
writer.writeheader()
for e in events: writer.writerow(e)
Sort events by start and iso format datetimesimport requests
import csv
from datetime import datetime
import ics_parser
URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics'
URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics'
def fetch_and_parse(url):
return ics_parser.parse(requests.get(url).text)
# Fetch and parse iCalendar events
study_activities = fetch_and_parse(URL_STUDY_ACTIVITIES)
activities = fetch_and_parse(URL_ACTIVITIES)
events = study_activities + activities
# Remove duplicates and sort
events = {e['UID']: e for e in events}.values()
events = sorted(events, key=lambda e: e['DTSTART'])
# Write csv
with open('timeedit.csv', 'w') as csvfile:
fieldnames = set()
for e in events: fieldnames = fieldnames | set(e.keys())
writer = csv.DictWriter(csvfile, fieldnames=sorted(list(fieldnames)))
writer.writeheader()
for e in events:
for key, value in e.items():
if isinstance(value, datetime): e[key] = value.isoformat()
writer.writerow(e)
|
<commit_before>import requests
import csv
import ics_parser
URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics'
URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics'
def fetch_and_parse(url):
return ics_parser.parse(requests.get(url).text)
# Fetch and parse iCalendar events
study_activities = fetch_and_parse(URL_STUDY_ACTIVITIES)
activities = fetch_and_parse(URL_ACTIVITIES)
events = study_activities + activities
# Remove duplicate events
events = {e['UID']: e for e in events}.values()
# Write csv
with open('timeedit.csv', 'w') as csvfile:
fieldnames = set()
for e in events: fieldnames = fieldnames | set(e.keys())
writer = csv.DictWriter(csvfile, fieldnames=sorted(list(fieldnames)))
writer.writeheader()
for e in events: writer.writerow(e)
<commit_msg>Sort events by start and iso format datetimes<commit_after>import requests
import csv
from datetime import datetime
import ics_parser
URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics'
URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics'
def fetch_and_parse(url):
return ics_parser.parse(requests.get(url).text)
# Fetch and parse iCalendar events
study_activities = fetch_and_parse(URL_STUDY_ACTIVITIES)
activities = fetch_and_parse(URL_ACTIVITIES)
events = study_activities + activities
# Remove duplicates and sort
events = {e['UID']: e for e in events}.values()
events = sorted(events, key=lambda e: e['DTSTART'])
# Write csv
with open('timeedit.csv', 'w') as csvfile:
fieldnames = set()
for e in events: fieldnames = fieldnames | set(e.keys())
writer = csv.DictWriter(csvfile, fieldnames=sorted(list(fieldnames)))
writer.writeheader()
for e in events:
for key, value in e.items():
if isinstance(value, datetime): e[key] = value.isoformat()
writer.writerow(e)
|
0261bb2bd82a9ff543f813eab90eb61e173f27cd
|
setup.py
|
setup.py
|
from setuptools import setup
classifiers = ['Development Status :: 5 - Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules']
setup(name='avroconsumer',
version='1.0.0',
description='Base consumer class for working with Avro datums',
maintainer='Gavin M. Roy',
maintainer_email='gavinr@aweber.com',
url='https://github.com/gmr/avroconsumer',
install_requires=['rejected', 'fastavro'],
license='BSDv3',
package_data={'': ['LICENSE', 'README.rst']},
py_modules=['avroconsumer'],
classifiers=classifiers)
|
from setuptools import setup
classifiers = ['Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules']
setup(name='avroconsumer',
version='1.0.0',
description='Base consumer class for working with Avro datums',
maintainer='Gavin M. Roy',
maintainer_email='gavinr@aweber.com',
url='https://github.com/gmr/avroconsumer',
install_requires=['rejected', 'fastavro'],
license='BSDv3',
package_data={'': ['LICENSE', 'README.rst']},
py_modules=['avroconsumer'],
classifiers=classifiers)
|
Fix the trove classifer for dev status
|
Fix the trove classifer for dev status
|
Python
|
bsd-3-clause
|
aweber/avroconsumer
|
from setuptools import setup
classifiers = ['Development Status :: 5 - Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules']
setup(name='avroconsumer',
version='1.0.0',
description='Base consumer class for working with Avro datums',
maintainer='Gavin M. Roy',
maintainer_email='gavinr@aweber.com',
url='https://github.com/gmr/avroconsumer',
install_requires=['rejected', 'fastavro'],
license='BSDv3',
package_data={'': ['LICENSE', 'README.rst']},
py_modules=['avroconsumer'],
classifiers=classifiers)
Fix the trove classifer for dev status
|
from setuptools import setup
classifiers = ['Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules']
setup(name='avroconsumer',
version='1.0.0',
description='Base consumer class for working with Avro datums',
maintainer='Gavin M. Roy',
maintainer_email='gavinr@aweber.com',
url='https://github.com/gmr/avroconsumer',
install_requires=['rejected', 'fastavro'],
license='BSDv3',
package_data={'': ['LICENSE', 'README.rst']},
py_modules=['avroconsumer'],
classifiers=classifiers)
|
<commit_before>from setuptools import setup
classifiers = ['Development Status :: 5 - Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules']
setup(name='avroconsumer',
version='1.0.0',
description='Base consumer class for working with Avro datums',
maintainer='Gavin M. Roy',
maintainer_email='gavinr@aweber.com',
url='https://github.com/gmr/avroconsumer',
install_requires=['rejected', 'fastavro'],
license='BSDv3',
package_data={'': ['LICENSE', 'README.rst']},
py_modules=['avroconsumer'],
classifiers=classifiers)
<commit_msg>Fix the trove classifer for dev status<commit_after>
|
from setuptools import setup
classifiers = ['Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules']
setup(name='avroconsumer',
version='1.0.0',
description='Base consumer class for working with Avro datums',
maintainer='Gavin M. Roy',
maintainer_email='gavinr@aweber.com',
url='https://github.com/gmr/avroconsumer',
install_requires=['rejected', 'fastavro'],
license='BSDv3',
package_data={'': ['LICENSE', 'README.rst']},
py_modules=['avroconsumer'],
classifiers=classifiers)
|
from setuptools import setup
classifiers = ['Development Status :: 5 - Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules']
setup(name='avroconsumer',
version='1.0.0',
description='Base consumer class for working with Avro datums',
maintainer='Gavin M. Roy',
maintainer_email='gavinr@aweber.com',
url='https://github.com/gmr/avroconsumer',
install_requires=['rejected', 'fastavro'],
license='BSDv3',
package_data={'': ['LICENSE', 'README.rst']},
py_modules=['avroconsumer'],
classifiers=classifiers)
Fix the trove classifer for dev statusfrom setuptools import setup
classifiers = ['Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules']
setup(name='avroconsumer',
version='1.0.0',
description='Base consumer class for working with Avro datums',
maintainer='Gavin M. Roy',
maintainer_email='gavinr@aweber.com',
url='https://github.com/gmr/avroconsumer',
install_requires=['rejected', 'fastavro'],
license='BSDv3',
package_data={'': ['LICENSE', 'README.rst']},
py_modules=['avroconsumer'],
classifiers=classifiers)
|
<commit_before>from setuptools import setup
classifiers = ['Development Status :: 5 - Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules']
setup(name='avroconsumer',
version='1.0.0',
description='Base consumer class for working with Avro datums',
maintainer='Gavin M. Roy',
maintainer_email='gavinr@aweber.com',
url='https://github.com/gmr/avroconsumer',
install_requires=['rejected', 'fastavro'],
license='BSDv3',
package_data={'': ['LICENSE', 'README.rst']},
py_modules=['avroconsumer'],
classifiers=classifiers)
<commit_msg>Fix the trove classifer for dev status<commit_after>from setuptools import setup
classifiers = ['Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules']
setup(name='avroconsumer',
version='1.0.0',
description='Base consumer class for working with Avro datums',
maintainer='Gavin M. Roy',
maintainer_email='gavinr@aweber.com',
url='https://github.com/gmr/avroconsumer',
install_requires=['rejected', 'fastavro'],
license='BSDv3',
package_data={'': ['LICENSE', 'README.rst']},
py_modules=['avroconsumer'],
classifiers=classifiers)
|
d1b680153b9ae56c701bc05d6f7f421f5715439f
|
setup.py
|
setup.py
|
#!/bin/env python
# -*- coding: utf8 -*-
from setuptools import setup
setup(
name='fedimg',
version='0.0.1',
description='Service to automatically upload built Fedora images \
to internal and external cloud providers.',
classifiers=[
"Programming Language :: Python :: 2",
"License :: OSI Approved :: GNU Affero General Public License \
v3 or later (AGPLv3+)",
]
keywords='python Fedora cloud image uploader',
author='David Gay',
author_email='oddshocks@riseup.net',
url='https://github.com/oddshocks/fedimg',
license='AGPLv3+',
include_package_data=True,
zip_safe=False,
install_requires=["fedmsg"],
packages=[],
entry_points="""
[moksha.consumer]
fedimg = fedimg:FedImg
""",
)
|
#!/bin/env python
# -*- coding: utf8 -*-
from setuptools import setup
setup(
name='fedimg',
version='0.0.1',
description='Service to automatically upload built Fedora images \
to internal and external cloud providers.',
classifiers=[
"Programming Language :: Python :: 2",
"License :: OSI Approved :: GNU Affero General Public License \
v3 or later (AGPLv3+)",
]
keywords='python Fedora cloud image uploader',
author='David Gay',
author_email='oddshocks@riseup.net',
url='https://github.com/oddshocks/fedimg',
license='AGPLv3+',
include_package_data=True,
zip_safe=False,
install_requires=["fedmsg"],
packages=[],
entry_points="""
[moksha.consumer]
fedimg = fedimg:FedImg
""",
)
|
Add a quick little newline.
|
Add a quick little newline.
|
Python
|
agpl-3.0
|
fedora-infra/fedimg,fedora-infra/fedimg
|
#!/bin/env python
# -*- coding: utf8 -*-
from setuptools import setup
setup(
name='fedimg',
version='0.0.1',
description='Service to automatically upload built Fedora images \
to internal and external cloud providers.',
classifiers=[
"Programming Language :: Python :: 2",
"License :: OSI Approved :: GNU Affero General Public License \
v3 or later (AGPLv3+)",
]
keywords='python Fedora cloud image uploader',
author='David Gay',
author_email='oddshocks@riseup.net',
url='https://github.com/oddshocks/fedimg',
license='AGPLv3+',
include_package_data=True,
zip_safe=False,
install_requires=["fedmsg"],
packages=[],
entry_points="""
[moksha.consumer]
fedimg = fedimg:FedImg
""",
)
Add a quick little newline.
|
#!/bin/env python
# -*- coding: utf8 -*-
from setuptools import setup
setup(
name='fedimg',
version='0.0.1',
description='Service to automatically upload built Fedora images \
to internal and external cloud providers.',
classifiers=[
"Programming Language :: Python :: 2",
"License :: OSI Approved :: GNU Affero General Public License \
v3 or later (AGPLv3+)",
]
keywords='python Fedora cloud image uploader',
author='David Gay',
author_email='oddshocks@riseup.net',
url='https://github.com/oddshocks/fedimg',
license='AGPLv3+',
include_package_data=True,
zip_safe=False,
install_requires=["fedmsg"],
packages=[],
entry_points="""
[moksha.consumer]
fedimg = fedimg:FedImg
""",
)
|
<commit_before>#!/bin/env python
# -*- coding: utf8 -*-
from setuptools import setup
setup(
name='fedimg',
version='0.0.1',
description='Service to automatically upload built Fedora images \
to internal and external cloud providers.',
classifiers=[
"Programming Language :: Python :: 2",
"License :: OSI Approved :: GNU Affero General Public License \
v3 or later (AGPLv3+)",
]
keywords='python Fedora cloud image uploader',
author='David Gay',
author_email='oddshocks@riseup.net',
url='https://github.com/oddshocks/fedimg',
license='AGPLv3+',
include_package_data=True,
zip_safe=False,
install_requires=["fedmsg"],
packages=[],
entry_points="""
[moksha.consumer]
fedimg = fedimg:FedImg
""",
)
<commit_msg>Add a quick little newline.<commit_after>
|
#!/bin/env python
# -*- coding: utf8 -*-
from setuptools import setup
setup(
name='fedimg',
version='0.0.1',
description='Service to automatically upload built Fedora images \
to internal and external cloud providers.',
classifiers=[
"Programming Language :: Python :: 2",
"License :: OSI Approved :: GNU Affero General Public License \
v3 or later (AGPLv3+)",
]
keywords='python Fedora cloud image uploader',
author='David Gay',
author_email='oddshocks@riseup.net',
url='https://github.com/oddshocks/fedimg',
license='AGPLv3+',
include_package_data=True,
zip_safe=False,
install_requires=["fedmsg"],
packages=[],
entry_points="""
[moksha.consumer]
fedimg = fedimg:FedImg
""",
)
|
#!/bin/env python
# -*- coding: utf8 -*-
from setuptools import setup
setup(
name='fedimg',
version='0.0.1',
description='Service to automatically upload built Fedora images \
to internal and external cloud providers.',
classifiers=[
"Programming Language :: Python :: 2",
"License :: OSI Approved :: GNU Affero General Public License \
v3 or later (AGPLv3+)",
]
keywords='python Fedora cloud image uploader',
author='David Gay',
author_email='oddshocks@riseup.net',
url='https://github.com/oddshocks/fedimg',
license='AGPLv3+',
include_package_data=True,
zip_safe=False,
install_requires=["fedmsg"],
packages=[],
entry_points="""
[moksha.consumer]
fedimg = fedimg:FedImg
""",
)
Add a quick little newline.#!/bin/env python
# -*- coding: utf8 -*-
from setuptools import setup
setup(
name='fedimg',
version='0.0.1',
description='Service to automatically upload built Fedora images \
to internal and external cloud providers.',
classifiers=[
"Programming Language :: Python :: 2",
"License :: OSI Approved :: GNU Affero General Public License \
v3 or later (AGPLv3+)",
]
keywords='python Fedora cloud image uploader',
author='David Gay',
author_email='oddshocks@riseup.net',
url='https://github.com/oddshocks/fedimg',
license='AGPLv3+',
include_package_data=True,
zip_safe=False,
install_requires=["fedmsg"],
packages=[],
entry_points="""
[moksha.consumer]
fedimg = fedimg:FedImg
""",
)
|
<commit_before>#!/bin/env python
# -*- coding: utf8 -*-
from setuptools import setup
setup(
name='fedimg',
version='0.0.1',
description='Service to automatically upload built Fedora images \
to internal and external cloud providers.',
classifiers=[
"Programming Language :: Python :: 2",
"License :: OSI Approved :: GNU Affero General Public License \
v3 or later (AGPLv3+)",
]
keywords='python Fedora cloud image uploader',
author='David Gay',
author_email='oddshocks@riseup.net',
url='https://github.com/oddshocks/fedimg',
license='AGPLv3+',
include_package_data=True,
zip_safe=False,
install_requires=["fedmsg"],
packages=[],
entry_points="""
[moksha.consumer]
fedimg = fedimg:FedImg
""",
)
<commit_msg>Add a quick little newline.<commit_after>#!/bin/env python
# -*- coding: utf8 -*-
from setuptools import setup
setup(
name='fedimg',
version='0.0.1',
description='Service to automatically upload built Fedora images \
to internal and external cloud providers.',
classifiers=[
"Programming Language :: Python :: 2",
"License :: OSI Approved :: GNU Affero General Public License \
v3 or later (AGPLv3+)",
]
keywords='python Fedora cloud image uploader',
author='David Gay',
author_email='oddshocks@riseup.net',
url='https://github.com/oddshocks/fedimg',
license='AGPLv3+',
include_package_data=True,
zip_safe=False,
install_requires=["fedmsg"],
packages=[],
entry_points="""
[moksha.consumer]
fedimg = fedimg:FedImg
""",
)
|
194e01f54c710c7eebc0105942c10337dedb90d9
|
setup.py
|
setup.py
|
#!/usr/bin/env python
from distutils.core import setup
import os
from deflect import __version__ as version
def read_file(filename):
"""
Utility function to read a provided filename.
"""
return open(os.path.join(os.path.dirname(__file__), filename)).read()
packages = [
'deflect',
]
package_data = {
'': ['LICENSE', 'README.rst'],
}
setup(
name='django-deflect',
version=version,
description='A Django short URL redirection application',
long_description=read_file('README.rst'),
author='Jason Bittel',
author_email='jason.bittel@gmail.com',
url='https://github.com/jbittel/django-deflect',
download_url='https://github.com/jbittel/django-deflect/downloads',
package_dir={'deflect': 'deflect'},
packages=packages,
package_data=package_data,
license='BSD',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Programming Language :: Python',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
],
keywords=['django'],
)
|
#!/usr/bin/env python
from distutils.core import setup
import os
from deflect import __version__ as version
def read_file(filename):
"""
Utility function to read a provided filename.
"""
return open(os.path.join(os.path.dirname(__file__), filename)).read()
packages = [
'deflect',
'deflect.tests',
]
package_data = {
'': ['LICENSE', 'README.rst'],
}
setup(
name='django-deflect',
version=version,
description='A Django short URL redirection application',
long_description=read_file('README.rst'),
author='Jason Bittel',
author_email='jason.bittel@gmail.com',
url='https://github.com/jbittel/django-deflect',
download_url='https://github.com/jbittel/django-deflect/downloads',
package_dir={'deflect': 'deflect'},
packages=packages,
package_data=package_data,
license='BSD',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Programming Language :: Python',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
],
keywords=['django'],
)
|
Add tests module to packaging list
|
Add tests module to packaging list
|
Python
|
bsd-3-clause
|
jbittel/django-deflect
|
#!/usr/bin/env python
from distutils.core import setup
import os
from deflect import __version__ as version
def read_file(filename):
"""
Utility function to read a provided filename.
"""
return open(os.path.join(os.path.dirname(__file__), filename)).read()
packages = [
'deflect',
]
package_data = {
'': ['LICENSE', 'README.rst'],
}
setup(
name='django-deflect',
version=version,
description='A Django short URL redirection application',
long_description=read_file('README.rst'),
author='Jason Bittel',
author_email='jason.bittel@gmail.com',
url='https://github.com/jbittel/django-deflect',
download_url='https://github.com/jbittel/django-deflect/downloads',
package_dir={'deflect': 'deflect'},
packages=packages,
package_data=package_data,
license='BSD',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Programming Language :: Python',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
],
keywords=['django'],
)
Add tests module to packaging list
|
#!/usr/bin/env python
from distutils.core import setup
import os
from deflect import __version__ as version
def read_file(filename):
"""
Utility function to read a provided filename.
"""
return open(os.path.join(os.path.dirname(__file__), filename)).read()
packages = [
'deflect',
'deflect.tests',
]
package_data = {
'': ['LICENSE', 'README.rst'],
}
setup(
name='django-deflect',
version=version,
description='A Django short URL redirection application',
long_description=read_file('README.rst'),
author='Jason Bittel',
author_email='jason.bittel@gmail.com',
url='https://github.com/jbittel/django-deflect',
download_url='https://github.com/jbittel/django-deflect/downloads',
package_dir={'deflect': 'deflect'},
packages=packages,
package_data=package_data,
license='BSD',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Programming Language :: Python',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
],
keywords=['django'],
)
|
<commit_before>#!/usr/bin/env python
from distutils.core import setup
import os
from deflect import __version__ as version
def read_file(filename):
"""
Utility function to read a provided filename.
"""
return open(os.path.join(os.path.dirname(__file__), filename)).read()
packages = [
'deflect',
]
package_data = {
'': ['LICENSE', 'README.rst'],
}
setup(
name='django-deflect',
version=version,
description='A Django short URL redirection application',
long_description=read_file('README.rst'),
author='Jason Bittel',
author_email='jason.bittel@gmail.com',
url='https://github.com/jbittel/django-deflect',
download_url='https://github.com/jbittel/django-deflect/downloads',
package_dir={'deflect': 'deflect'},
packages=packages,
package_data=package_data,
license='BSD',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Programming Language :: Python',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
],
keywords=['django'],
)
<commit_msg>Add tests module to packaging list<commit_after>
|
#!/usr/bin/env python
from distutils.core import setup
import os
from deflect import __version__ as version
def read_file(filename):
"""
Utility function to read a provided filename.
"""
return open(os.path.join(os.path.dirname(__file__), filename)).read()
packages = [
'deflect',
'deflect.tests',
]
package_data = {
'': ['LICENSE', 'README.rst'],
}
setup(
name='django-deflect',
version=version,
description='A Django short URL redirection application',
long_description=read_file('README.rst'),
author='Jason Bittel',
author_email='jason.bittel@gmail.com',
url='https://github.com/jbittel/django-deflect',
download_url='https://github.com/jbittel/django-deflect/downloads',
package_dir={'deflect': 'deflect'},
packages=packages,
package_data=package_data,
license='BSD',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Programming Language :: Python',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
],
keywords=['django'],
)
|
#!/usr/bin/env python
from distutils.core import setup
import os
from deflect import __version__ as version
def read_file(filename):
"""
Utility function to read a provided filename.
"""
return open(os.path.join(os.path.dirname(__file__), filename)).read()
packages = [
'deflect',
]
package_data = {
'': ['LICENSE', 'README.rst'],
}
setup(
name='django-deflect',
version=version,
description='A Django short URL redirection application',
long_description=read_file('README.rst'),
author='Jason Bittel',
author_email='jason.bittel@gmail.com',
url='https://github.com/jbittel/django-deflect',
download_url='https://github.com/jbittel/django-deflect/downloads',
package_dir={'deflect': 'deflect'},
packages=packages,
package_data=package_data,
license='BSD',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Programming Language :: Python',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
],
keywords=['django'],
)
Add tests module to packaging list#!/usr/bin/env python
from distutils.core import setup
import os
from deflect import __version__ as version
def read_file(filename):
"""
Utility function to read a provided filename.
"""
return open(os.path.join(os.path.dirname(__file__), filename)).read()
packages = [
'deflect',
'deflect.tests',
]
package_data = {
'': ['LICENSE', 'README.rst'],
}
setup(
name='django-deflect',
version=version,
description='A Django short URL redirection application',
long_description=read_file('README.rst'),
author='Jason Bittel',
author_email='jason.bittel@gmail.com',
url='https://github.com/jbittel/django-deflect',
download_url='https://github.com/jbittel/django-deflect/downloads',
package_dir={'deflect': 'deflect'},
packages=packages,
package_data=package_data,
license='BSD',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Programming Language :: Python',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
],
keywords=['django'],
)
|
<commit_before>#!/usr/bin/env python
from distutils.core import setup
import os
from deflect import __version__ as version
def read_file(filename):
"""
Utility function to read a provided filename.
"""
return open(os.path.join(os.path.dirname(__file__), filename)).read()
packages = [
'deflect',
]
package_data = {
'': ['LICENSE', 'README.rst'],
}
setup(
name='django-deflect',
version=version,
description='A Django short URL redirection application',
long_description=read_file('README.rst'),
author='Jason Bittel',
author_email='jason.bittel@gmail.com',
url='https://github.com/jbittel/django-deflect',
download_url='https://github.com/jbittel/django-deflect/downloads',
package_dir={'deflect': 'deflect'},
packages=packages,
package_data=package_data,
license='BSD',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Programming Language :: Python',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
],
keywords=['django'],
)
<commit_msg>Add tests module to packaging list<commit_after>#!/usr/bin/env python
from distutils.core import setup
import os
from deflect import __version__ as version
def read_file(filename):
"""
Utility function to read a provided filename.
"""
return open(os.path.join(os.path.dirname(__file__), filename)).read()
packages = [
'deflect',
'deflect.tests',
]
package_data = {
'': ['LICENSE', 'README.rst'],
}
setup(
name='django-deflect',
version=version,
description='A Django short URL redirection application',
long_description=read_file('README.rst'),
author='Jason Bittel',
author_email='jason.bittel@gmail.com',
url='https://github.com/jbittel/django-deflect',
download_url='https://github.com/jbittel/django-deflect/downloads',
package_dir={'deflect': 'deflect'},
packages=packages,
package_data=package_data,
license='BSD',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Programming Language :: Python',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
],
keywords=['django'],
)
|
cfb4d6fb92f7eaed5bfea18ae0b3b772ce868097
|
tasks.py
|
tasks.py
|
from invoke import task, run
@task
def clean_docs():
run("rm -rf docs/_build")
@task('clean_docs')
def docs():
run("sphinx-build docs docs/_build")
run("open docs/_build/index.html")
@task
def flake8():
run("flake8 binaryornot tests")
@task
def autopep8():
run("autopep8 --in-place --aggressive -r binaryornot")
run("autopep8 --in-place --aggressive -r tests")
@task
def test():
run("python setup.py test")
@task
def coverage():
run("coverage run --source binaryornot setup.py test")
run("coverage report -m")
run("coverage html")
run("open htmlcov/index.html")
@task
def clean_build():
run("rm -fr build/")
run("rm -fr dist/")
run("rm -fr *.egg-info")
@task
def clean_pyc():
run("find . -name '*.pyc' -exec rm -f {} +")
run("find . -name '*.pyo' -exec rm -f {} +")
run("find . -name '*~' -exec rm -f {} +")
@task('clean_build', 'clean_pyc')
def sdist():
run("python setup.py sdist")
run("ls -l dist")
@task('sdist')
def release():
run("python setup.py upload")
|
from invoke import task, run
@task
def clean_docs():
run("rm -rf docs/_build")
run("rm -rf docs/binaryornot.rst")
run("rm -rf docs/modules.rst")
@task('clean_docs')
def docs():
run("sphinx-apidoc -o docs/ binaryornot/")
run("sphinx-build docs docs/_build")
run("open docs/_build/index.html")
@task
def flake8():
run("flake8 binaryornot tests")
@task
def autopep8():
run("autopep8 --in-place --aggressive -r binaryornot")
run("autopep8 --in-place --aggressive -r tests")
@task
def test():
run("python setup.py test")
@task
def coverage():
run("coverage run --source binaryornot setup.py test")
run("coverage report -m")
run("coverage html")
run("open htmlcov/index.html")
@task
def clean_build():
run("rm -fr build/")
run("rm -fr dist/")
run("rm -fr *.egg-info")
@task
def clean_pyc():
run("find . -name '*.pyc' -exec rm -f {} +")
run("find . -name '*.pyo' -exec rm -f {} +")
run("find . -name '*~' -exec rm -f {} +")
@task('clean_build', 'clean_pyc')
def sdist():
run("python setup.py sdist")
run("ls -l dist")
@task('sdist')
def release():
run("python setup.py upload")
|
Use sphinx-apidoc to generate API docs from docstrings.
|
Use sphinx-apidoc to generate API docs from docstrings.
|
Python
|
bsd-3-clause
|
hackebrot/binaryornot,hackebrot/binaryornot,audreyr/binaryornot,0k/binaryornot,audreyr/binaryornot,pombredanne/binaryornot,0k/binaryornot,pombredanne/binaryornot,hackebrot/binaryornot,audreyr/binaryornot,pombredanne/binaryornot
|
from invoke import task, run
@task
def clean_docs():
run("rm -rf docs/_build")
@task('clean_docs')
def docs():
run("sphinx-build docs docs/_build")
run("open docs/_build/index.html")
@task
def flake8():
run("flake8 binaryornot tests")
@task
def autopep8():
run("autopep8 --in-place --aggressive -r binaryornot")
run("autopep8 --in-place --aggressive -r tests")
@task
def test():
run("python setup.py test")
@task
def coverage():
run("coverage run --source binaryornot setup.py test")
run("coverage report -m")
run("coverage html")
run("open htmlcov/index.html")
@task
def clean_build():
run("rm -fr build/")
run("rm -fr dist/")
run("rm -fr *.egg-info")
@task
def clean_pyc():
run("find . -name '*.pyc' -exec rm -f {} +")
run("find . -name '*.pyo' -exec rm -f {} +")
run("find . -name '*~' -exec rm -f {} +")
@task('clean_build', 'clean_pyc')
def sdist():
run("python setup.py sdist")
run("ls -l dist")
@task('sdist')
def release():
run("python setup.py upload")
Use sphinx-apidoc to generate API docs from docstrings.
|
from invoke import task, run
@task
def clean_docs():
run("rm -rf docs/_build")
run("rm -rf docs/binaryornot.rst")
run("rm -rf docs/modules.rst")
@task('clean_docs')
def docs():
run("sphinx-apidoc -o docs/ binaryornot/")
run("sphinx-build docs docs/_build")
run("open docs/_build/index.html")
@task
def flake8():
run("flake8 binaryornot tests")
@task
def autopep8():
run("autopep8 --in-place --aggressive -r binaryornot")
run("autopep8 --in-place --aggressive -r tests")
@task
def test():
run("python setup.py test")
@task
def coverage():
run("coverage run --source binaryornot setup.py test")
run("coverage report -m")
run("coverage html")
run("open htmlcov/index.html")
@task
def clean_build():
run("rm -fr build/")
run("rm -fr dist/")
run("rm -fr *.egg-info")
@task
def clean_pyc():
run("find . -name '*.pyc' -exec rm -f {} +")
run("find . -name '*.pyo' -exec rm -f {} +")
run("find . -name '*~' -exec rm -f {} +")
@task('clean_build', 'clean_pyc')
def sdist():
run("python setup.py sdist")
run("ls -l dist")
@task('sdist')
def release():
run("python setup.py upload")
|
<commit_before>from invoke import task, run
@task
def clean_docs():
run("rm -rf docs/_build")
@task('clean_docs')
def docs():
run("sphinx-build docs docs/_build")
run("open docs/_build/index.html")
@task
def flake8():
run("flake8 binaryornot tests")
@task
def autopep8():
run("autopep8 --in-place --aggressive -r binaryornot")
run("autopep8 --in-place --aggressive -r tests")
@task
def test():
run("python setup.py test")
@task
def coverage():
run("coverage run --source binaryornot setup.py test")
run("coverage report -m")
run("coverage html")
run("open htmlcov/index.html")
@task
def clean_build():
run("rm -fr build/")
run("rm -fr dist/")
run("rm -fr *.egg-info")
@task
def clean_pyc():
run("find . -name '*.pyc' -exec rm -f {} +")
run("find . -name '*.pyo' -exec rm -f {} +")
run("find . -name '*~' -exec rm -f {} +")
@task('clean_build', 'clean_pyc')
def sdist():
run("python setup.py sdist")
run("ls -l dist")
@task('sdist')
def release():
run("python setup.py upload")
<commit_msg>Use sphinx-apidoc to generate API docs from docstrings.<commit_after>
|
from invoke import task, run
@task
def clean_docs():
run("rm -rf docs/_build")
run("rm -rf docs/binaryornot.rst")
run("rm -rf docs/modules.rst")
@task('clean_docs')
def docs():
run("sphinx-apidoc -o docs/ binaryornot/")
run("sphinx-build docs docs/_build")
run("open docs/_build/index.html")
@task
def flake8():
run("flake8 binaryornot tests")
@task
def autopep8():
run("autopep8 --in-place --aggressive -r binaryornot")
run("autopep8 --in-place --aggressive -r tests")
@task
def test():
run("python setup.py test")
@task
def coverage():
run("coverage run --source binaryornot setup.py test")
run("coverage report -m")
run("coverage html")
run("open htmlcov/index.html")
@task
def clean_build():
run("rm -fr build/")
run("rm -fr dist/")
run("rm -fr *.egg-info")
@task
def clean_pyc():
run("find . -name '*.pyc' -exec rm -f {} +")
run("find . -name '*.pyo' -exec rm -f {} +")
run("find . -name '*~' -exec rm -f {} +")
@task('clean_build', 'clean_pyc')
def sdist():
run("python setup.py sdist")
run("ls -l dist")
@task('sdist')
def release():
run("python setup.py upload")
|
from invoke import task, run
@task
def clean_docs():
run("rm -rf docs/_build")
@task('clean_docs')
def docs():
run("sphinx-build docs docs/_build")
run("open docs/_build/index.html")
@task
def flake8():
run("flake8 binaryornot tests")
@task
def autopep8():
run("autopep8 --in-place --aggressive -r binaryornot")
run("autopep8 --in-place --aggressive -r tests")
@task
def test():
run("python setup.py test")
@task
def coverage():
run("coverage run --source binaryornot setup.py test")
run("coverage report -m")
run("coverage html")
run("open htmlcov/index.html")
@task
def clean_build():
run("rm -fr build/")
run("rm -fr dist/")
run("rm -fr *.egg-info")
@task
def clean_pyc():
run("find . -name '*.pyc' -exec rm -f {} +")
run("find . -name '*.pyo' -exec rm -f {} +")
run("find . -name '*~' -exec rm -f {} +")
@task('clean_build', 'clean_pyc')
def sdist():
run("python setup.py sdist")
run("ls -l dist")
@task('sdist')
def release():
run("python setup.py upload")
Use sphinx-apidoc to generate API docs from docstrings.from invoke import task, run
@task
def clean_docs():
run("rm -rf docs/_build")
run("rm -rf docs/binaryornot.rst")
run("rm -rf docs/modules.rst")
@task('clean_docs')
def docs():
run("sphinx-apidoc -o docs/ binaryornot/")
run("sphinx-build docs docs/_build")
run("open docs/_build/index.html")
@task
def flake8():
run("flake8 binaryornot tests")
@task
def autopep8():
run("autopep8 --in-place --aggressive -r binaryornot")
run("autopep8 --in-place --aggressive -r tests")
@task
def test():
run("python setup.py test")
@task
def coverage():
run("coverage run --source binaryornot setup.py test")
run("coverage report -m")
run("coverage html")
run("open htmlcov/index.html")
@task
def clean_build():
run("rm -fr build/")
run("rm -fr dist/")
run("rm -fr *.egg-info")
@task
def clean_pyc():
run("find . -name '*.pyc' -exec rm -f {} +")
run("find . -name '*.pyo' -exec rm -f {} +")
run("find . -name '*~' -exec rm -f {} +")
@task('clean_build', 'clean_pyc')
def sdist():
run("python setup.py sdist")
run("ls -l dist")
@task('sdist')
def release():
run("python setup.py upload")
|
<commit_before>from invoke import task, run
@task
def clean_docs():
run("rm -rf docs/_build")
@task('clean_docs')
def docs():
run("sphinx-build docs docs/_build")
run("open docs/_build/index.html")
@task
def flake8():
run("flake8 binaryornot tests")
@task
def autopep8():
run("autopep8 --in-place --aggressive -r binaryornot")
run("autopep8 --in-place --aggressive -r tests")
@task
def test():
run("python setup.py test")
@task
def coverage():
run("coverage run --source binaryornot setup.py test")
run("coverage report -m")
run("coverage html")
run("open htmlcov/index.html")
@task
def clean_build():
run("rm -fr build/")
run("rm -fr dist/")
run("rm -fr *.egg-info")
@task
def clean_pyc():
run("find . -name '*.pyc' -exec rm -f {} +")
run("find . -name '*.pyo' -exec rm -f {} +")
run("find . -name '*~' -exec rm -f {} +")
@task('clean_build', 'clean_pyc')
def sdist():
run("python setup.py sdist")
run("ls -l dist")
@task('sdist')
def release():
run("python setup.py upload")
<commit_msg>Use sphinx-apidoc to generate API docs from docstrings.<commit_after>from invoke import task, run
@task
def clean_docs():
run("rm -rf docs/_build")
run("rm -rf docs/binaryornot.rst")
run("rm -rf docs/modules.rst")
@task('clean_docs')
def docs():
run("sphinx-apidoc -o docs/ binaryornot/")
run("sphinx-build docs docs/_build")
run("open docs/_build/index.html")
@task
def flake8():
run("flake8 binaryornot tests")
@task
def autopep8():
run("autopep8 --in-place --aggressive -r binaryornot")
run("autopep8 --in-place --aggressive -r tests")
@task
def test():
run("python setup.py test")
@task
def coverage():
run("coverage run --source binaryornot setup.py test")
run("coverage report -m")
run("coverage html")
run("open htmlcov/index.html")
@task
def clean_build():
run("rm -fr build/")
run("rm -fr dist/")
run("rm -fr *.egg-info")
@task
def clean_pyc():
run("find . -name '*.pyc' -exec rm -f {} +")
run("find . -name '*.pyo' -exec rm -f {} +")
run("find . -name '*~' -exec rm -f {} +")
@task('clean_build', 'clean_pyc')
def sdist():
run("python setup.py sdist")
run("ls -l dist")
@task('sdist')
def release():
run("python setup.py upload")
|
7979bac3580852c051d739b0ee95967c8b2572dd
|
cloudkittyclient/__init__.py
|
cloudkittyclient/__init__.py
|
# -*- coding: utf-8 -*-
# Copyright 2015 Objectif Libre
# 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 pbr.version
__version__ = pbr.version.VersionInfo(
'cloudkittyclient').version_string()
|
# -*- coding: utf-8 -*-
# Copyright 2015 Objectif Libre
# 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 pbr.version
__version__ = pbr.version.VersionInfo(
'python-cloudkittyclient').version_string()
|
Fix the wrong input package of pbr of cloudkittyclient
|
Fix the wrong input package of pbr of cloudkittyclient
The cloudkittyclient cannot work because wrong package name was
inputed to pbr.version.VersionInfo() method.
Change-Id: Iff65bf5b2efd50b0dd29070b89ac5a607d0ecfcb
Closes-Bug: #1448406
|
Python
|
apache-2.0
|
muraliselva10/python-cloudkittyclient,openstack/python-cloudkittyclient,stackforge/python-cloudkittyclient,FNST-OpenStack/python-cloudkittyclient
|
# -*- coding: utf-8 -*-
# Copyright 2015 Objectif Libre
# 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 pbr.version
__version__ = pbr.version.VersionInfo(
'cloudkittyclient').version_string()
Fix the wrong input package of pbr of cloudkittyclient
The cloudkittyclient cannot work because wrong package name was
inputed to pbr.version.VersionInfo() method.
Change-Id: Iff65bf5b2efd50b0dd29070b89ac5a607d0ecfcb
Closes-Bug: #1448406
|
# -*- coding: utf-8 -*-
# Copyright 2015 Objectif Libre
# 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 pbr.version
__version__ = pbr.version.VersionInfo(
'python-cloudkittyclient').version_string()
|
<commit_before># -*- coding: utf-8 -*-
# Copyright 2015 Objectif Libre
# 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 pbr.version
__version__ = pbr.version.VersionInfo(
'cloudkittyclient').version_string()
<commit_msg>Fix the wrong input package of pbr of cloudkittyclient
The cloudkittyclient cannot work because wrong package name was
inputed to pbr.version.VersionInfo() method.
Change-Id: Iff65bf5b2efd50b0dd29070b89ac5a607d0ecfcb
Closes-Bug: #1448406<commit_after>
|
# -*- coding: utf-8 -*-
# Copyright 2015 Objectif Libre
# 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 pbr.version
__version__ = pbr.version.VersionInfo(
'python-cloudkittyclient').version_string()
|
# -*- coding: utf-8 -*-
# Copyright 2015 Objectif Libre
# 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 pbr.version
__version__ = pbr.version.VersionInfo(
'cloudkittyclient').version_string()
Fix the wrong input package of pbr of cloudkittyclient
The cloudkittyclient cannot work because wrong package name was
inputed to pbr.version.VersionInfo() method.
Change-Id: Iff65bf5b2efd50b0dd29070b89ac5a607d0ecfcb
Closes-Bug: #1448406# -*- coding: utf-8 -*-
# Copyright 2015 Objectif Libre
# 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 pbr.version
__version__ = pbr.version.VersionInfo(
'python-cloudkittyclient').version_string()
|
<commit_before># -*- coding: utf-8 -*-
# Copyright 2015 Objectif Libre
# 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 pbr.version
__version__ = pbr.version.VersionInfo(
'cloudkittyclient').version_string()
<commit_msg>Fix the wrong input package of pbr of cloudkittyclient
The cloudkittyclient cannot work because wrong package name was
inputed to pbr.version.VersionInfo() method.
Change-Id: Iff65bf5b2efd50b0dd29070b89ac5a607d0ecfcb
Closes-Bug: #1448406<commit_after># -*- coding: utf-8 -*-
# Copyright 2015 Objectif Libre
# 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 pbr.version
__version__ = pbr.version.VersionInfo(
'python-cloudkittyclient').version_string()
|
00ab7f48fff7f824e7db41bd8fedf1623f904a42
|
awsume/awsumepy/lib/saml.py
|
awsume/awsumepy/lib/saml.py
|
import base64
import xmltodict
import json
import colorama
from . safe_print import safe_print
from . exceptions import SAMLAssertionParseError
def parse_assertion(assertion: str) -> list:
roles = []
response = xmltodict.parse(base64.b64decode(assertion))
attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {})
if not attributes:
raise SAMLAssertionParseError()
for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']:
for value in attribute['saml2:AttributeValue']:
roles.append(value['#text'])
return roles
|
import base64
import xmltodict
import json
import colorama
from . safe_print import safe_print
from . exceptions import SAMLAssertionParseError
def parse_assertion(assertion: str) -> list:
roles = []
response = xmltodict.parse(base64.b64decode(assertion))
if response.get('saml2p:Response') is not None:
attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {})
attribute_value_key = 'saml2:AttributeValue'
else:
attributes = response.get('samlp:Response', {}).get('saml:Assertion', {}).get('saml:AttributeStatement', {}).get('saml:Attribute', {})
attribute_value_key = 'saml:AttributeValue'
if not attributes:
raise SAMLAssertionParseError()
for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']:
for value in attribute[attribute_value_key]:
roles.append(value['#text'])
return roles
|
Handle SAML 1 in addition to SAML 2.
|
Handle SAML 1 in addition to SAML 2.
|
Python
|
mit
|
trek10inc/awsume,trek10inc/awsume
|
import base64
import xmltodict
import json
import colorama
from . safe_print import safe_print
from . exceptions import SAMLAssertionParseError
def parse_assertion(assertion: str) -> list:
roles = []
response = xmltodict.parse(base64.b64decode(assertion))
attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {})
if not attributes:
raise SAMLAssertionParseError()
for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']:
for value in attribute['saml2:AttributeValue']:
roles.append(value['#text'])
return roles
Handle SAML 1 in addition to SAML 2.
|
import base64
import xmltodict
import json
import colorama
from . safe_print import safe_print
from . exceptions import SAMLAssertionParseError
def parse_assertion(assertion: str) -> list:
roles = []
response = xmltodict.parse(base64.b64decode(assertion))
if response.get('saml2p:Response') is not None:
attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {})
attribute_value_key = 'saml2:AttributeValue'
else:
attributes = response.get('samlp:Response', {}).get('saml:Assertion', {}).get('saml:AttributeStatement', {}).get('saml:Attribute', {})
attribute_value_key = 'saml:AttributeValue'
if not attributes:
raise SAMLAssertionParseError()
for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']:
for value in attribute[attribute_value_key]:
roles.append(value['#text'])
return roles
|
<commit_before>import base64
import xmltodict
import json
import colorama
from . safe_print import safe_print
from . exceptions import SAMLAssertionParseError
def parse_assertion(assertion: str) -> list:
roles = []
response = xmltodict.parse(base64.b64decode(assertion))
attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {})
if not attributes:
raise SAMLAssertionParseError()
for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']:
for value in attribute['saml2:AttributeValue']:
roles.append(value['#text'])
return roles
<commit_msg>Handle SAML 1 in addition to SAML 2.<commit_after>
|
import base64
import xmltodict
import json
import colorama
from . safe_print import safe_print
from . exceptions import SAMLAssertionParseError
def parse_assertion(assertion: str) -> list:
roles = []
response = xmltodict.parse(base64.b64decode(assertion))
if response.get('saml2p:Response') is not None:
attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {})
attribute_value_key = 'saml2:AttributeValue'
else:
attributes = response.get('samlp:Response', {}).get('saml:Assertion', {}).get('saml:AttributeStatement', {}).get('saml:Attribute', {})
attribute_value_key = 'saml:AttributeValue'
if not attributes:
raise SAMLAssertionParseError()
for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']:
for value in attribute[attribute_value_key]:
roles.append(value['#text'])
return roles
|
import base64
import xmltodict
import json
import colorama
from . safe_print import safe_print
from . exceptions import SAMLAssertionParseError
def parse_assertion(assertion: str) -> list:
roles = []
response = xmltodict.parse(base64.b64decode(assertion))
attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {})
if not attributes:
raise SAMLAssertionParseError()
for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']:
for value in attribute['saml2:AttributeValue']:
roles.append(value['#text'])
return roles
Handle SAML 1 in addition to SAML 2.import base64
import xmltodict
import json
import colorama
from . safe_print import safe_print
from . exceptions import SAMLAssertionParseError
def parse_assertion(assertion: str) -> list:
roles = []
response = xmltodict.parse(base64.b64decode(assertion))
if response.get('saml2p:Response') is not None:
attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {})
attribute_value_key = 'saml2:AttributeValue'
else:
attributes = response.get('samlp:Response', {}).get('saml:Assertion', {}).get('saml:AttributeStatement', {}).get('saml:Attribute', {})
attribute_value_key = 'saml:AttributeValue'
if not attributes:
raise SAMLAssertionParseError()
for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']:
for value in attribute[attribute_value_key]:
roles.append(value['#text'])
return roles
|
<commit_before>import base64
import xmltodict
import json
import colorama
from . safe_print import safe_print
from . exceptions import SAMLAssertionParseError
def parse_assertion(assertion: str) -> list:
roles = []
response = xmltodict.parse(base64.b64decode(assertion))
attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {})
if not attributes:
raise SAMLAssertionParseError()
for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']:
for value in attribute['saml2:AttributeValue']:
roles.append(value['#text'])
return roles
<commit_msg>Handle SAML 1 in addition to SAML 2.<commit_after>import base64
import xmltodict
import json
import colorama
from . safe_print import safe_print
from . exceptions import SAMLAssertionParseError
def parse_assertion(assertion: str) -> list:
roles = []
response = xmltodict.parse(base64.b64decode(assertion))
if response.get('saml2p:Response') is not None:
attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {})
attribute_value_key = 'saml2:AttributeValue'
else:
attributes = response.get('samlp:Response', {}).get('saml:Assertion', {}).get('saml:AttributeStatement', {}).get('saml:Attribute', {})
attribute_value_key = 'saml:AttributeValue'
if not attributes:
raise SAMLAssertionParseError()
for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']:
for value in attribute[attribute_value_key]:
roles.append(value['#text'])
return roles
|
28062a6a978b52c3eb3ce6b6c4b8c14832b8673f
|
billing/integrations/amazon_fps_integration.py
|
billing/integrations/amazon_fps_integration.py
|
from billing.integration import Integration
from django.conf import settings
from boto.connection import FPSConnection
FPS_PROD_API_ENDPOINT = "fps.amazonaws.com"
FPS_SANDBOX_API_ENDPOINT = "fps.sandbox.amazonaws.com"
class AmazonFpsIntegration(Integration):
# TODO: Document the fields for each flow
fields = {"transactionAmount": "",
"pipelineName": "",
"paymentReason": "",
"returnURL": "",}
def __init__(self, options={}):
self.aws_access_key = options.get("aws_access_key", None) or settings.AWS_ACCESS_KEY
self.aws_secret_access_key = options.get("aws_secret_access_key", None) or settings.AWS_SECRET_ACCESS_KEY
super(AmazonFpsIntegration, self).__init__(options=options)
self.fps_connection = FPSConnection(self.aws_access_key, self.aws_secret_access_key, **options)
@property
def service_url(self):
if self.test_mode:
return FPS_SANDBOX_API_ENDPOINT
return FPS_PROD_API_ENDPOINT
@property
def link_url(self):
return self.fps_connection.make_url(self.fields["returnURL"],
self.fields["paymentReason"],
self.fields["pipelineName"],
self.fields["transactionAmount"],
**self.fields)
|
from billing.integration import Integration
from django.conf import settings
from boto.fps.connection import FPSConnection
FPS_PROD_API_ENDPOINT = "fps.amazonaws.com"
FPS_SANDBOX_API_ENDPOINT = "fps.sandbox.amazonaws.com"
class AmazonFpsIntegration(Integration):
# TODO: Document the fields for each flow
fields = {"transactionAmount": "",
"pipelineName": "",
"paymentReason": "",
"returnURL": "",}
def __init__(self, options={}):
self.aws_access_key = options.get("aws_access_key", None) or settings.AWS_ACCESS_KEY
self.aws_secret_access_key = options.get("aws_secret_access_key", None) or settings.AWS_SECRET_ACCESS_KEY
super(AmazonFpsIntegration, self).__init__(options=options)
self.fps_connection = FPSConnection(self.aws_access_key, self.aws_secret_access_key, **options)
@property
def service_url(self):
if self.test_mode:
return FPS_SANDBOX_API_ENDPOINT
return FPS_PROD_API_ENDPOINT
@property
def link_url(self):
return self.fps_connection.make_url(self.fields["returnURL"],
self.fields["paymentReason"],
self.fields["pipelineName"],
self.fields["transactionAmount"],
**self.fields)
|
Use the correct module path for the AmazonFPS app.
|
Fix: Use the correct module path for the AmazonFPS app.
|
Python
|
bsd-3-clause
|
biddyweb/merchant,SimpleTax/merchant,biddyweb/merchant,spookylukey/merchant,agiliq/merchant,agiliq/merchant,digideskio/merchant,mjrulesamrat/merchant,spookylukey/merchant,SimpleTax/merchant,mjrulesamrat/merchant,digideskio/merchant
|
from billing.integration import Integration
from django.conf import settings
from boto.connection import FPSConnection
FPS_PROD_API_ENDPOINT = "fps.amazonaws.com"
FPS_SANDBOX_API_ENDPOINT = "fps.sandbox.amazonaws.com"
class AmazonFpsIntegration(Integration):
# TODO: Document the fields for each flow
fields = {"transactionAmount": "",
"pipelineName": "",
"paymentReason": "",
"returnURL": "",}
def __init__(self, options={}):
self.aws_access_key = options.get("aws_access_key", None) or settings.AWS_ACCESS_KEY
self.aws_secret_access_key = options.get("aws_secret_access_key", None) or settings.AWS_SECRET_ACCESS_KEY
super(AmazonFpsIntegration, self).__init__(options=options)
self.fps_connection = FPSConnection(self.aws_access_key, self.aws_secret_access_key, **options)
@property
def service_url(self):
if self.test_mode:
return FPS_SANDBOX_API_ENDPOINT
return FPS_PROD_API_ENDPOINT
@property
def link_url(self):
return self.fps_connection.make_url(self.fields["returnURL"],
self.fields["paymentReason"],
self.fields["pipelineName"],
self.fields["transactionAmount"],
**self.fields)
Fix: Use the correct module path for the AmazonFPS app.
|
from billing.integration import Integration
from django.conf import settings
from boto.fps.connection import FPSConnection
FPS_PROD_API_ENDPOINT = "fps.amazonaws.com"
FPS_SANDBOX_API_ENDPOINT = "fps.sandbox.amazonaws.com"
class AmazonFpsIntegration(Integration):
# TODO: Document the fields for each flow
fields = {"transactionAmount": "",
"pipelineName": "",
"paymentReason": "",
"returnURL": "",}
def __init__(self, options={}):
self.aws_access_key = options.get("aws_access_key", None) or settings.AWS_ACCESS_KEY
self.aws_secret_access_key = options.get("aws_secret_access_key", None) or settings.AWS_SECRET_ACCESS_KEY
super(AmazonFpsIntegration, self).__init__(options=options)
self.fps_connection = FPSConnection(self.aws_access_key, self.aws_secret_access_key, **options)
@property
def service_url(self):
if self.test_mode:
return FPS_SANDBOX_API_ENDPOINT
return FPS_PROD_API_ENDPOINT
@property
def link_url(self):
return self.fps_connection.make_url(self.fields["returnURL"],
self.fields["paymentReason"],
self.fields["pipelineName"],
self.fields["transactionAmount"],
**self.fields)
|
<commit_before>from billing.integration import Integration
from django.conf import settings
from boto.connection import FPSConnection
FPS_PROD_API_ENDPOINT = "fps.amazonaws.com"
FPS_SANDBOX_API_ENDPOINT = "fps.sandbox.amazonaws.com"
class AmazonFpsIntegration(Integration):
# TODO: Document the fields for each flow
fields = {"transactionAmount": "",
"pipelineName": "",
"paymentReason": "",
"returnURL": "",}
def __init__(self, options={}):
self.aws_access_key = options.get("aws_access_key", None) or settings.AWS_ACCESS_KEY
self.aws_secret_access_key = options.get("aws_secret_access_key", None) or settings.AWS_SECRET_ACCESS_KEY
super(AmazonFpsIntegration, self).__init__(options=options)
self.fps_connection = FPSConnection(self.aws_access_key, self.aws_secret_access_key, **options)
@property
def service_url(self):
if self.test_mode:
return FPS_SANDBOX_API_ENDPOINT
return FPS_PROD_API_ENDPOINT
@property
def link_url(self):
return self.fps_connection.make_url(self.fields["returnURL"],
self.fields["paymentReason"],
self.fields["pipelineName"],
self.fields["transactionAmount"],
**self.fields)
<commit_msg>Fix: Use the correct module path for the AmazonFPS app.<commit_after>
|
from billing.integration import Integration
from django.conf import settings
from boto.fps.connection import FPSConnection
FPS_PROD_API_ENDPOINT = "fps.amazonaws.com"
FPS_SANDBOX_API_ENDPOINT = "fps.sandbox.amazonaws.com"
class AmazonFpsIntegration(Integration):
# TODO: Document the fields for each flow
fields = {"transactionAmount": "",
"pipelineName": "",
"paymentReason": "",
"returnURL": "",}
def __init__(self, options={}):
self.aws_access_key = options.get("aws_access_key", None) or settings.AWS_ACCESS_KEY
self.aws_secret_access_key = options.get("aws_secret_access_key", None) or settings.AWS_SECRET_ACCESS_KEY
super(AmazonFpsIntegration, self).__init__(options=options)
self.fps_connection = FPSConnection(self.aws_access_key, self.aws_secret_access_key, **options)
@property
def service_url(self):
if self.test_mode:
return FPS_SANDBOX_API_ENDPOINT
return FPS_PROD_API_ENDPOINT
@property
def link_url(self):
return self.fps_connection.make_url(self.fields["returnURL"],
self.fields["paymentReason"],
self.fields["pipelineName"],
self.fields["transactionAmount"],
**self.fields)
|
from billing.integration import Integration
from django.conf import settings
from boto.connection import FPSConnection
FPS_PROD_API_ENDPOINT = "fps.amazonaws.com"
FPS_SANDBOX_API_ENDPOINT = "fps.sandbox.amazonaws.com"
class AmazonFpsIntegration(Integration):
# TODO: Document the fields for each flow
fields = {"transactionAmount": "",
"pipelineName": "",
"paymentReason": "",
"returnURL": "",}
def __init__(self, options={}):
self.aws_access_key = options.get("aws_access_key", None) or settings.AWS_ACCESS_KEY
self.aws_secret_access_key = options.get("aws_secret_access_key", None) or settings.AWS_SECRET_ACCESS_KEY
super(AmazonFpsIntegration, self).__init__(options=options)
self.fps_connection = FPSConnection(self.aws_access_key, self.aws_secret_access_key, **options)
@property
def service_url(self):
if self.test_mode:
return FPS_SANDBOX_API_ENDPOINT
return FPS_PROD_API_ENDPOINT
@property
def link_url(self):
return self.fps_connection.make_url(self.fields["returnURL"],
self.fields["paymentReason"],
self.fields["pipelineName"],
self.fields["transactionAmount"],
**self.fields)
Fix: Use the correct module path for the AmazonFPS app.from billing.integration import Integration
from django.conf import settings
from boto.fps.connection import FPSConnection
FPS_PROD_API_ENDPOINT = "fps.amazonaws.com"
FPS_SANDBOX_API_ENDPOINT = "fps.sandbox.amazonaws.com"
class AmazonFpsIntegration(Integration):
# TODO: Document the fields for each flow
fields = {"transactionAmount": "",
"pipelineName": "",
"paymentReason": "",
"returnURL": "",}
def __init__(self, options={}):
self.aws_access_key = options.get("aws_access_key", None) or settings.AWS_ACCESS_KEY
self.aws_secret_access_key = options.get("aws_secret_access_key", None) or settings.AWS_SECRET_ACCESS_KEY
super(AmazonFpsIntegration, self).__init__(options=options)
self.fps_connection = FPSConnection(self.aws_access_key, self.aws_secret_access_key, **options)
@property
def service_url(self):
if self.test_mode:
return FPS_SANDBOX_API_ENDPOINT
return FPS_PROD_API_ENDPOINT
@property
def link_url(self):
return self.fps_connection.make_url(self.fields["returnURL"],
self.fields["paymentReason"],
self.fields["pipelineName"],
self.fields["transactionAmount"],
**self.fields)
|
<commit_before>from billing.integration import Integration
from django.conf import settings
from boto.connection import FPSConnection
FPS_PROD_API_ENDPOINT = "fps.amazonaws.com"
FPS_SANDBOX_API_ENDPOINT = "fps.sandbox.amazonaws.com"
class AmazonFpsIntegration(Integration):
# TODO: Document the fields for each flow
fields = {"transactionAmount": "",
"pipelineName": "",
"paymentReason": "",
"returnURL": "",}
def __init__(self, options={}):
self.aws_access_key = options.get("aws_access_key", None) or settings.AWS_ACCESS_KEY
self.aws_secret_access_key = options.get("aws_secret_access_key", None) or settings.AWS_SECRET_ACCESS_KEY
super(AmazonFpsIntegration, self).__init__(options=options)
self.fps_connection = FPSConnection(self.aws_access_key, self.aws_secret_access_key, **options)
@property
def service_url(self):
if self.test_mode:
return FPS_SANDBOX_API_ENDPOINT
return FPS_PROD_API_ENDPOINT
@property
def link_url(self):
return self.fps_connection.make_url(self.fields["returnURL"],
self.fields["paymentReason"],
self.fields["pipelineName"],
self.fields["transactionAmount"],
**self.fields)
<commit_msg>Fix: Use the correct module path for the AmazonFPS app.<commit_after>from billing.integration import Integration
from django.conf import settings
from boto.fps.connection import FPSConnection
FPS_PROD_API_ENDPOINT = "fps.amazonaws.com"
FPS_SANDBOX_API_ENDPOINT = "fps.sandbox.amazonaws.com"
class AmazonFpsIntegration(Integration):
# TODO: Document the fields for each flow
fields = {"transactionAmount": "",
"pipelineName": "",
"paymentReason": "",
"returnURL": "",}
def __init__(self, options={}):
self.aws_access_key = options.get("aws_access_key", None) or settings.AWS_ACCESS_KEY
self.aws_secret_access_key = options.get("aws_secret_access_key", None) or settings.AWS_SECRET_ACCESS_KEY
super(AmazonFpsIntegration, self).__init__(options=options)
self.fps_connection = FPSConnection(self.aws_access_key, self.aws_secret_access_key, **options)
@property
def service_url(self):
if self.test_mode:
return FPS_SANDBOX_API_ENDPOINT
return FPS_PROD_API_ENDPOINT
@property
def link_url(self):
return self.fps_connection.make_url(self.fields["returnURL"],
self.fields["paymentReason"],
self.fields["pipelineName"],
self.fields["transactionAmount"],
**self.fields)
|
ae15b27fd2370c423858aa0710f0d3eddb26738d
|
crispy_forms/tests/base.py
|
crispy_forms/tests/base.py
|
# -*- coding: utf-8 -*-
import os
import django
from django.conf import settings
from django.template import loader
from django.test import TestCase
try:
from django.test import override_settings
except ImportError:
from django.test.utils import override_settings
class CrispyTestCase(TestCase):
def setUp(self):
template_dirs = [os.path.join(os.path.dirname(__file__), 'templates')]
template_dirs = template_dirs + list(settings.TEMPLATE_DIRS)
template_loaders = ['django.template.loaders.filesystem.Loader']
template_loaders = template_loaders + list(settings.TEMPLATE_LOADERS)
# ensuring test templates directory is loaded first
self.__overriden_settings = override_settings(**{
'TEMPLATE_LOADERS': template_loaders,
'TEMPLATE_DIRS': template_dirs,
})
self.__overriden_settings.enable()
if django.VERSION < 1.8:
# resetting template loaders cache
self.__template_source_loaders = loader.template_source_loaders
loader.template_source_loaders = None
def tearDown(self):
if django.VERSION < 1.8:
loader.template_source_loaders = self.__template_source_loaders
self.__overriden_settings.disable()
@property
def current_template_pack(self):
return getattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap')
|
# -*- coding: utf-8 -*-
import os
import django
from django.conf import settings
from django.template import loader
from django.test import TestCase
try:
from django.test import override_settings
except ImportError:
from django.test.utils import override_settings
class CrispyTestCase(TestCase):
def setUp(self):
template_dirs = [os.path.join(os.path.dirname(__file__), 'templates')]
template_dirs = template_dirs + list(settings.TEMPLATE_DIRS)
template_loaders = ['django.template.loaders.filesystem.Loader']
template_loaders = template_loaders + list(settings.TEMPLATE_LOADERS)
# ensuring test templates directory is loaded first
self.__overriden_settings = override_settings(**{
'TEMPLATE_LOADERS': template_loaders,
'TEMPLATE_DIRS': template_dirs,
})
self.__overriden_settings.enable()
if django.VERSION < (1,8):
# resetting template loaders cache
self.__template_source_loaders = loader.template_source_loaders
loader.template_source_loaders = None
def tearDown(self):
if django.VERSION < (1,8):
loader.template_source_loaders = self.__template_source_loaders
self.__overriden_settings.disable()
@property
def current_template_pack(self):
return getattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap')
|
Use tuple for version check
|
Use tuple for version check
|
Python
|
mit
|
RamezIssac/django-crispy-forms,Stranger6667/django-crispy-forms,scuml/django-crispy-forms,impulse-cloud/django-crispy-forms,dzhuang/django-crispy-forms,alanwj/django-crispy-forms,avsd/django-crispy-forms,tarunlnmiit/django-crispy-forms,saydulk/django-crispy-forms,schrd/django-crispy-forms,dzhuang/django-crispy-forms,ngenovictor/django-crispy-forms,IanLee1521/django-crispy-forms,damienjones/django-crispy-forms,schrd/django-crispy-forms,django-crispy-forms/django-crispy-forms,maraujop/django-crispy-forms,VishvajitP/django-crispy-forms,jtyoung/django-crispy-forms,VishvajitP/django-crispy-forms,davidszotten/django-crispy-forms,dessibelle/django-crispy-forms,smirolo/django-crispy-forms,Stranger6667/django-crispy-forms,jtyoung/django-crispy-forms,django-crispy-forms/django-crispy-forms,ngenovictor/django-crispy-forms,maraujop/django-crispy-forms,damienjones/django-crispy-forms,RamezIssac/django-crispy-forms,saydulk/django-crispy-forms,dessibelle/django-crispy-forms,scuml/django-crispy-forms,davidszotten/django-crispy-forms,avsd/django-crispy-forms,IanLee1521/django-crispy-forms,impulse-cloud/django-crispy-forms,smirolo/django-crispy-forms,tarunlnmiit/django-crispy-forms,alanwj/django-crispy-forms
|
# -*- coding: utf-8 -*-
import os
import django
from django.conf import settings
from django.template import loader
from django.test import TestCase
try:
from django.test import override_settings
except ImportError:
from django.test.utils import override_settings
class CrispyTestCase(TestCase):
def setUp(self):
template_dirs = [os.path.join(os.path.dirname(__file__), 'templates')]
template_dirs = template_dirs + list(settings.TEMPLATE_DIRS)
template_loaders = ['django.template.loaders.filesystem.Loader']
template_loaders = template_loaders + list(settings.TEMPLATE_LOADERS)
# ensuring test templates directory is loaded first
self.__overriden_settings = override_settings(**{
'TEMPLATE_LOADERS': template_loaders,
'TEMPLATE_DIRS': template_dirs,
})
self.__overriden_settings.enable()
if django.VERSION < 1.8:
# resetting template loaders cache
self.__template_source_loaders = loader.template_source_loaders
loader.template_source_loaders = None
def tearDown(self):
if django.VERSION < 1.8:
loader.template_source_loaders = self.__template_source_loaders
self.__overriden_settings.disable()
@property
def current_template_pack(self):
return getattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap')
Use tuple for version check
|
# -*- coding: utf-8 -*-
import os
import django
from django.conf import settings
from django.template import loader
from django.test import TestCase
try:
from django.test import override_settings
except ImportError:
from django.test.utils import override_settings
class CrispyTestCase(TestCase):
def setUp(self):
template_dirs = [os.path.join(os.path.dirname(__file__), 'templates')]
template_dirs = template_dirs + list(settings.TEMPLATE_DIRS)
template_loaders = ['django.template.loaders.filesystem.Loader']
template_loaders = template_loaders + list(settings.TEMPLATE_LOADERS)
# ensuring test templates directory is loaded first
self.__overriden_settings = override_settings(**{
'TEMPLATE_LOADERS': template_loaders,
'TEMPLATE_DIRS': template_dirs,
})
self.__overriden_settings.enable()
if django.VERSION < (1,8):
# resetting template loaders cache
self.__template_source_loaders = loader.template_source_loaders
loader.template_source_loaders = None
def tearDown(self):
if django.VERSION < (1,8):
loader.template_source_loaders = self.__template_source_loaders
self.__overriden_settings.disable()
@property
def current_template_pack(self):
return getattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap')
|
<commit_before># -*- coding: utf-8 -*-
import os
import django
from django.conf import settings
from django.template import loader
from django.test import TestCase
try:
from django.test import override_settings
except ImportError:
from django.test.utils import override_settings
class CrispyTestCase(TestCase):
def setUp(self):
template_dirs = [os.path.join(os.path.dirname(__file__), 'templates')]
template_dirs = template_dirs + list(settings.TEMPLATE_DIRS)
template_loaders = ['django.template.loaders.filesystem.Loader']
template_loaders = template_loaders + list(settings.TEMPLATE_LOADERS)
# ensuring test templates directory is loaded first
self.__overriden_settings = override_settings(**{
'TEMPLATE_LOADERS': template_loaders,
'TEMPLATE_DIRS': template_dirs,
})
self.__overriden_settings.enable()
if django.VERSION < 1.8:
# resetting template loaders cache
self.__template_source_loaders = loader.template_source_loaders
loader.template_source_loaders = None
def tearDown(self):
if django.VERSION < 1.8:
loader.template_source_loaders = self.__template_source_loaders
self.__overriden_settings.disable()
@property
def current_template_pack(self):
return getattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap')
<commit_msg>Use tuple for version check<commit_after>
|
# -*- coding: utf-8 -*-
import os
import django
from django.conf import settings
from django.template import loader
from django.test import TestCase
try:
from django.test import override_settings
except ImportError:
from django.test.utils import override_settings
class CrispyTestCase(TestCase):
def setUp(self):
template_dirs = [os.path.join(os.path.dirname(__file__), 'templates')]
template_dirs = template_dirs + list(settings.TEMPLATE_DIRS)
template_loaders = ['django.template.loaders.filesystem.Loader']
template_loaders = template_loaders + list(settings.TEMPLATE_LOADERS)
# ensuring test templates directory is loaded first
self.__overriden_settings = override_settings(**{
'TEMPLATE_LOADERS': template_loaders,
'TEMPLATE_DIRS': template_dirs,
})
self.__overriden_settings.enable()
if django.VERSION < (1,8):
# resetting template loaders cache
self.__template_source_loaders = loader.template_source_loaders
loader.template_source_loaders = None
def tearDown(self):
if django.VERSION < (1,8):
loader.template_source_loaders = self.__template_source_loaders
self.__overriden_settings.disable()
@property
def current_template_pack(self):
return getattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap')
|
# -*- coding: utf-8 -*-
import os
import django
from django.conf import settings
from django.template import loader
from django.test import TestCase
try:
from django.test import override_settings
except ImportError:
from django.test.utils import override_settings
class CrispyTestCase(TestCase):
def setUp(self):
template_dirs = [os.path.join(os.path.dirname(__file__), 'templates')]
template_dirs = template_dirs + list(settings.TEMPLATE_DIRS)
template_loaders = ['django.template.loaders.filesystem.Loader']
template_loaders = template_loaders + list(settings.TEMPLATE_LOADERS)
# ensuring test templates directory is loaded first
self.__overriden_settings = override_settings(**{
'TEMPLATE_LOADERS': template_loaders,
'TEMPLATE_DIRS': template_dirs,
})
self.__overriden_settings.enable()
if django.VERSION < 1.8:
# resetting template loaders cache
self.__template_source_loaders = loader.template_source_loaders
loader.template_source_loaders = None
def tearDown(self):
if django.VERSION < 1.8:
loader.template_source_loaders = self.__template_source_loaders
self.__overriden_settings.disable()
@property
def current_template_pack(self):
return getattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap')
Use tuple for version check# -*- coding: utf-8 -*-
import os
import django
from django.conf import settings
from django.template import loader
from django.test import TestCase
try:
from django.test import override_settings
except ImportError:
from django.test.utils import override_settings
class CrispyTestCase(TestCase):
def setUp(self):
template_dirs = [os.path.join(os.path.dirname(__file__), 'templates')]
template_dirs = template_dirs + list(settings.TEMPLATE_DIRS)
template_loaders = ['django.template.loaders.filesystem.Loader']
template_loaders = template_loaders + list(settings.TEMPLATE_LOADERS)
# ensuring test templates directory is loaded first
self.__overriden_settings = override_settings(**{
'TEMPLATE_LOADERS': template_loaders,
'TEMPLATE_DIRS': template_dirs,
})
self.__overriden_settings.enable()
if django.VERSION < (1,8):
# resetting template loaders cache
self.__template_source_loaders = loader.template_source_loaders
loader.template_source_loaders = None
def tearDown(self):
if django.VERSION < (1,8):
loader.template_source_loaders = self.__template_source_loaders
self.__overriden_settings.disable()
@property
def current_template_pack(self):
return getattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap')
|
<commit_before># -*- coding: utf-8 -*-
import os
import django
from django.conf import settings
from django.template import loader
from django.test import TestCase
try:
from django.test import override_settings
except ImportError:
from django.test.utils import override_settings
class CrispyTestCase(TestCase):
def setUp(self):
template_dirs = [os.path.join(os.path.dirname(__file__), 'templates')]
template_dirs = template_dirs + list(settings.TEMPLATE_DIRS)
template_loaders = ['django.template.loaders.filesystem.Loader']
template_loaders = template_loaders + list(settings.TEMPLATE_LOADERS)
# ensuring test templates directory is loaded first
self.__overriden_settings = override_settings(**{
'TEMPLATE_LOADERS': template_loaders,
'TEMPLATE_DIRS': template_dirs,
})
self.__overriden_settings.enable()
if django.VERSION < 1.8:
# resetting template loaders cache
self.__template_source_loaders = loader.template_source_loaders
loader.template_source_loaders = None
def tearDown(self):
if django.VERSION < 1.8:
loader.template_source_loaders = self.__template_source_loaders
self.__overriden_settings.disable()
@property
def current_template_pack(self):
return getattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap')
<commit_msg>Use tuple for version check<commit_after># -*- coding: utf-8 -*-
import os
import django
from django.conf import settings
from django.template import loader
from django.test import TestCase
try:
from django.test import override_settings
except ImportError:
from django.test.utils import override_settings
class CrispyTestCase(TestCase):
def setUp(self):
template_dirs = [os.path.join(os.path.dirname(__file__), 'templates')]
template_dirs = template_dirs + list(settings.TEMPLATE_DIRS)
template_loaders = ['django.template.loaders.filesystem.Loader']
template_loaders = template_loaders + list(settings.TEMPLATE_LOADERS)
# ensuring test templates directory is loaded first
self.__overriden_settings = override_settings(**{
'TEMPLATE_LOADERS': template_loaders,
'TEMPLATE_DIRS': template_dirs,
})
self.__overriden_settings.enable()
if django.VERSION < (1,8):
# resetting template loaders cache
self.__template_source_loaders = loader.template_source_loaders
loader.template_source_loaders = None
def tearDown(self):
if django.VERSION < (1,8):
loader.template_source_loaders = self.__template_source_loaders
self.__overriden_settings.disable()
@property
def current_template_pack(self):
return getattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap')
|
e5939631835ce04d808246fdc391c95354f3b044
|
slug/posix.py
|
slug/posix.py
|
"""
Versions of the base functionality optimized for by-the-spec POSIX.
Linux/Mac/BSD-specific code should live elsewhere.
"""
import signal
from . import base
__all__ = ('Process',)
class Process(base.Process):
def pause(self):
"""
Pause the process, able to be continued later
"""
self.signal(signal.SIGSTOP)
def unpause(self):
# continue is a reserved word
"""
Continue the process after it's been paused
"""
self.signal(signal.SIGCONT)
|
"""
Versions of the base functionality optimized for by-the-spec POSIX.
Linux/Mac/BSD-specific code should live elsewhere.
"""
import signal
import selectors
from . import base
__all__ = ('Process', 'Valve')
class Process(base.Process):
def pause(self):
"""
Pause the process, able to be continued later
"""
self.signal(signal.SIGSTOP)
def unpause(self):
# continue is a reserved word
"""
Continue the process after it's been paused
"""
self.signal(signal.SIGCONT)
class Valve(base.Valve):
"""
Forwards from one file-like to another, but this flow may be paused and
resumed.
This implementation doesn't support changing the target descriptors after
initialization.
"""
def _thread(self):
sel = selectors.DefaultSelector()
sel.register(self.side_in, selectors.EVENT_READ)
while True:
sel.select()
# Don't care about the event, there's only one thing it can be.
# This feels like there's a race condition in here, but I think the
# window is small enough we can call it "slight asyncronousity".
if not self.gate.is_set():
self.gate.wait()
continue
chunk = self.side_in.read(self.CHUNKSIZE)
if chunk == b'':
break
else:
self.side_out.write(chunk)
if not self.keepopen:
self.side_out.close()
|
Correct Valve behavior on Posix
|
Correct Valve behavior on Posix
|
Python
|
bsd-3-clause
|
xonsh/slug
|
"""
Versions of the base functionality optimized for by-the-spec POSIX.
Linux/Mac/BSD-specific code should live elsewhere.
"""
import signal
from . import base
__all__ = ('Process',)
class Process(base.Process):
def pause(self):
"""
Pause the process, able to be continued later
"""
self.signal(signal.SIGSTOP)
def unpause(self):
# continue is a reserved word
"""
Continue the process after it's been paused
"""
self.signal(signal.SIGCONT)
Correct Valve behavior on Posix
|
"""
Versions of the base functionality optimized for by-the-spec POSIX.
Linux/Mac/BSD-specific code should live elsewhere.
"""
import signal
import selectors
from . import base
__all__ = ('Process', 'Valve')
class Process(base.Process):
def pause(self):
"""
Pause the process, able to be continued later
"""
self.signal(signal.SIGSTOP)
def unpause(self):
# continue is a reserved word
"""
Continue the process after it's been paused
"""
self.signal(signal.SIGCONT)
class Valve(base.Valve):
"""
Forwards from one file-like to another, but this flow may be paused and
resumed.
This implementation doesn't support changing the target descriptors after
initialization.
"""
def _thread(self):
sel = selectors.DefaultSelector()
sel.register(self.side_in, selectors.EVENT_READ)
while True:
sel.select()
# Don't care about the event, there's only one thing it can be.
# This feels like there's a race condition in here, but I think the
# window is small enough we can call it "slight asyncronousity".
if not self.gate.is_set():
self.gate.wait()
continue
chunk = self.side_in.read(self.CHUNKSIZE)
if chunk == b'':
break
else:
self.side_out.write(chunk)
if not self.keepopen:
self.side_out.close()
|
<commit_before>"""
Versions of the base functionality optimized for by-the-spec POSIX.
Linux/Mac/BSD-specific code should live elsewhere.
"""
import signal
from . import base
__all__ = ('Process',)
class Process(base.Process):
def pause(self):
"""
Pause the process, able to be continued later
"""
self.signal(signal.SIGSTOP)
def unpause(self):
# continue is a reserved word
"""
Continue the process after it's been paused
"""
self.signal(signal.SIGCONT)
<commit_msg>Correct Valve behavior on Posix<commit_after>
|
"""
Versions of the base functionality optimized for by-the-spec POSIX.
Linux/Mac/BSD-specific code should live elsewhere.
"""
import signal
import selectors
from . import base
__all__ = ('Process', 'Valve')
class Process(base.Process):
def pause(self):
"""
Pause the process, able to be continued later
"""
self.signal(signal.SIGSTOP)
def unpause(self):
# continue is a reserved word
"""
Continue the process after it's been paused
"""
self.signal(signal.SIGCONT)
class Valve(base.Valve):
"""
Forwards from one file-like to another, but this flow may be paused and
resumed.
This implementation doesn't support changing the target descriptors after
initialization.
"""
def _thread(self):
sel = selectors.DefaultSelector()
sel.register(self.side_in, selectors.EVENT_READ)
while True:
sel.select()
# Don't care about the event, there's only one thing it can be.
# This feels like there's a race condition in here, but I think the
# window is small enough we can call it "slight asyncronousity".
if not self.gate.is_set():
self.gate.wait()
continue
chunk = self.side_in.read(self.CHUNKSIZE)
if chunk == b'':
break
else:
self.side_out.write(chunk)
if not self.keepopen:
self.side_out.close()
|
"""
Versions of the base functionality optimized for by-the-spec POSIX.
Linux/Mac/BSD-specific code should live elsewhere.
"""
import signal
from . import base
__all__ = ('Process',)
class Process(base.Process):
def pause(self):
"""
Pause the process, able to be continued later
"""
self.signal(signal.SIGSTOP)
def unpause(self):
# continue is a reserved word
"""
Continue the process after it's been paused
"""
self.signal(signal.SIGCONT)
Correct Valve behavior on Posix"""
Versions of the base functionality optimized for by-the-spec POSIX.
Linux/Mac/BSD-specific code should live elsewhere.
"""
import signal
import selectors
from . import base
__all__ = ('Process', 'Valve')
class Process(base.Process):
def pause(self):
"""
Pause the process, able to be continued later
"""
self.signal(signal.SIGSTOP)
def unpause(self):
# continue is a reserved word
"""
Continue the process after it's been paused
"""
self.signal(signal.SIGCONT)
class Valve(base.Valve):
"""
Forwards from one file-like to another, but this flow may be paused and
resumed.
This implementation doesn't support changing the target descriptors after
initialization.
"""
def _thread(self):
sel = selectors.DefaultSelector()
sel.register(self.side_in, selectors.EVENT_READ)
while True:
sel.select()
# Don't care about the event, there's only one thing it can be.
# This feels like there's a race condition in here, but I think the
# window is small enough we can call it "slight asyncronousity".
if not self.gate.is_set():
self.gate.wait()
continue
chunk = self.side_in.read(self.CHUNKSIZE)
if chunk == b'':
break
else:
self.side_out.write(chunk)
if not self.keepopen:
self.side_out.close()
|
<commit_before>"""
Versions of the base functionality optimized for by-the-spec POSIX.
Linux/Mac/BSD-specific code should live elsewhere.
"""
import signal
from . import base
__all__ = ('Process',)
class Process(base.Process):
def pause(self):
"""
Pause the process, able to be continued later
"""
self.signal(signal.SIGSTOP)
def unpause(self):
# continue is a reserved word
"""
Continue the process after it's been paused
"""
self.signal(signal.SIGCONT)
<commit_msg>Correct Valve behavior on Posix<commit_after>"""
Versions of the base functionality optimized for by-the-spec POSIX.
Linux/Mac/BSD-specific code should live elsewhere.
"""
import signal
import selectors
from . import base
__all__ = ('Process', 'Valve')
class Process(base.Process):
def pause(self):
"""
Pause the process, able to be continued later
"""
self.signal(signal.SIGSTOP)
def unpause(self):
# continue is a reserved word
"""
Continue the process after it's been paused
"""
self.signal(signal.SIGCONT)
class Valve(base.Valve):
"""
Forwards from one file-like to another, but this flow may be paused and
resumed.
This implementation doesn't support changing the target descriptors after
initialization.
"""
def _thread(self):
sel = selectors.DefaultSelector()
sel.register(self.side_in, selectors.EVENT_READ)
while True:
sel.select()
# Don't care about the event, there's only one thing it can be.
# This feels like there's a race condition in here, but I think the
# window is small enough we can call it "slight asyncronousity".
if not self.gate.is_set():
self.gate.wait()
continue
chunk = self.side_in.read(self.CHUNKSIZE)
if chunk == b'':
break
else:
self.side_out.write(chunk)
if not self.keepopen:
self.side_out.close()
|
99947acb784d975319bd99240abed066a4f0a51f
|
pytablewriter/_converter.py
|
pytablewriter/_converter.py
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import re
def lower_bool_converter(bool_value):
return str(bool_value).lower()
def strip_quote(text, value):
re_replace = re.compile(
'["\']%s["\']' % (value), re.MULTILINE)
return re_replace.sub(value, text)
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import re
def lower_bool_converter(bool_value):
return str(bool_value).lower()
def str_datetime_converter(value):
return value.strftime("%Y-%m-%dT%H:%M:%S%z")
def strip_quote(text, value):
re_replace = re.compile(
'["\']%s["\']' % (value), re.MULTILINE)
return re_replace.sub(value, text)
|
Add a converter which convert datetime to string
|
Add a converter which convert datetime to string
|
Python
|
mit
|
thombashi/pytablewriter
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import re
def lower_bool_converter(bool_value):
return str(bool_value).lower()
def strip_quote(text, value):
re_replace = re.compile(
'["\']%s["\']' % (value), re.MULTILINE)
return re_replace.sub(value, text)
Add a converter which convert datetime to string
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import re
def lower_bool_converter(bool_value):
return str(bool_value).lower()
def str_datetime_converter(value):
return value.strftime("%Y-%m-%dT%H:%M:%S%z")
def strip_quote(text, value):
re_replace = re.compile(
'["\']%s["\']' % (value), re.MULTILINE)
return re_replace.sub(value, text)
|
<commit_before># encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import re
def lower_bool_converter(bool_value):
return str(bool_value).lower()
def strip_quote(text, value):
re_replace = re.compile(
'["\']%s["\']' % (value), re.MULTILINE)
return re_replace.sub(value, text)
<commit_msg>Add a converter which convert datetime to string<commit_after>
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import re
def lower_bool_converter(bool_value):
return str(bool_value).lower()
def str_datetime_converter(value):
return value.strftime("%Y-%m-%dT%H:%M:%S%z")
def strip_quote(text, value):
re_replace = re.compile(
'["\']%s["\']' % (value), re.MULTILINE)
return re_replace.sub(value, text)
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import re
def lower_bool_converter(bool_value):
return str(bool_value).lower()
def strip_quote(text, value):
re_replace = re.compile(
'["\']%s["\']' % (value), re.MULTILINE)
return re_replace.sub(value, text)
Add a converter which convert datetime to string# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import re
def lower_bool_converter(bool_value):
return str(bool_value).lower()
def str_datetime_converter(value):
return value.strftime("%Y-%m-%dT%H:%M:%S%z")
def strip_quote(text, value):
re_replace = re.compile(
'["\']%s["\']' % (value), re.MULTILINE)
return re_replace.sub(value, text)
|
<commit_before># encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import re
def lower_bool_converter(bool_value):
return str(bool_value).lower()
def strip_quote(text, value):
re_replace = re.compile(
'["\']%s["\']' % (value), re.MULTILINE)
return re_replace.sub(value, text)
<commit_msg>Add a converter which convert datetime to string<commit_after># encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import re
def lower_bool_converter(bool_value):
return str(bool_value).lower()
def str_datetime_converter(value):
return value.strftime("%Y-%m-%dT%H:%M:%S%z")
def strip_quote(text, value):
re_replace = re.compile(
'["\']%s["\']' % (value), re.MULTILINE)
return re_replace.sub(value, text)
|
14610d40b4d13f16af73685eea1e67fd76e27a65
|
python/helpers/pydev/_pydevd_frame_eval/pydevd_frame_eval_main.py
|
python/helpers/pydev/_pydevd_frame_eval/pydevd_frame_eval_main.py
|
import os
import sys
IS_PY36_OR_OLDER = False
if (sys.version_info[0] == 3 and sys.version_info[1] >= 6) or sys.version_info[0] > 3:
IS_PY36_OR_OLDER = True
set_frame_eval = None
stop_frame_eval = None
if IS_PY36_OR_OLDER:
try:
from _pydevd_frame_eval.pydevd_frame_evaluator import frame_eval_func, stop_frame_eval
except ImportError:
from _pydev_bundle.pydev_monkey import log_error_once
dirname = os.path.dirname(__file__)
log_error_once("warning: Debugger speedups for Python 3.6 not found. Run '\"%s\" \"%s\" build_ext --inplace' to build." % (
sys.executable, os.path.join(dirname, 'setup.py')))
|
import os
import sys
IS_PY36_OR_OLDER = False
if (sys.version_info[0] == 3 and sys.version_info[1] >= 6) or sys.version_info[0] > 3:
IS_PY36_OR_OLDER = True
set_frame_eval = None
stop_frame_eval = None
use_frame_eval = os.environ.get('PYDEVD_USE_FRAME_EVAL', None)
if use_frame_eval == 'NO':
frame_eval_func, stop_frame_eval = None, None
else:
if IS_PY36_OR_OLDER:
try:
from _pydevd_frame_eval.pydevd_frame_evaluator import frame_eval_func, stop_frame_eval
except ImportError:
from _pydev_bundle.pydev_monkey import log_error_once
dirname = os.path.dirname(__file__)
log_error_once("warning: Debugger speedups for Python 3.6 not found. Run '\"%s\" \"%s\" build_ext --inplace' to build." % (
sys.executable, os.path.join(dirname, 'setup.py')))
|
Add ability to disable frame evaluation
|
Add ability to disable frame evaluation
|
Python
|
apache-2.0
|
apixandru/intellij-community,mglukhikh/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,vvv1559/intellij-community,da1z/intellij-community,FHannes/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,signed/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,ibinti/intellij-community,apixandru/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,apixandru/intellij-community,signed/intellij-community,apixandru/intellij-community,asedunov/intellij-community,ibinti/intellij-community,allotria/intellij-community,semonte/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,FHannes/intellij-community,apixandru/intellij-community,da1z/intellij-community,asedunov/intellij-community,xfournet/intellij-community,allotria/intellij-community,da1z/intellij-community,semonte/intellij-community,semonte/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ibinti/intellij-community,xfournet/intellij-community,xfournet/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,asedunov/intellij-community,da1z/intellij-community,FHannes/intellij-community,semonte/intellij-community,ibinti/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,FHannes/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,vvv1559/intellij-community,semonte/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,semonte/intellij-community,asedunov/intellij-community,allotria/intellij-community,ibinti/intellij-community,ibinti/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,FHannes/intellij-community,FHannes/intellij-community,semonte/intellij-community,asedunov/intellij-community,xfournet/intellij-community,signed/intellij-community,semonte/intellij-community,vvv1559/intellij-community,signed/intellij-community,ibinti/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,da1z/intellij-community,asedunov/intellij-community,ibinti/intellij-community,da1z/intellij-community,vvv1559/intellij-community,signed/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,da1z/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,signed/intellij-community,xfournet/intellij-community,signed/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,signed/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,apixandru/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,signed/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,da1z/intellij-community,da1z/intellij-community,asedunov/intellij-community,da1z/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,allotria/intellij-community,suncycheng/intellij-community,da1z/intellij-community,semonte/intellij-community,FHannes/intellij-community,asedunov/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,signed/intellij-community,vvv1559/intellij-community,semonte/intellij-community
|
import os
import sys
IS_PY36_OR_OLDER = False
if (sys.version_info[0] == 3 and sys.version_info[1] >= 6) or sys.version_info[0] > 3:
IS_PY36_OR_OLDER = True
set_frame_eval = None
stop_frame_eval = None
if IS_PY36_OR_OLDER:
try:
from _pydevd_frame_eval.pydevd_frame_evaluator import frame_eval_func, stop_frame_eval
except ImportError:
from _pydev_bundle.pydev_monkey import log_error_once
dirname = os.path.dirname(__file__)
log_error_once("warning: Debugger speedups for Python 3.6 not found. Run '\"%s\" \"%s\" build_ext --inplace' to build." % (
sys.executable, os.path.join(dirname, 'setup.py')))
Add ability to disable frame evaluation
|
import os
import sys
IS_PY36_OR_OLDER = False
if (sys.version_info[0] == 3 and sys.version_info[1] >= 6) or sys.version_info[0] > 3:
IS_PY36_OR_OLDER = True
set_frame_eval = None
stop_frame_eval = None
use_frame_eval = os.environ.get('PYDEVD_USE_FRAME_EVAL', None)
if use_frame_eval == 'NO':
frame_eval_func, stop_frame_eval = None, None
else:
if IS_PY36_OR_OLDER:
try:
from _pydevd_frame_eval.pydevd_frame_evaluator import frame_eval_func, stop_frame_eval
except ImportError:
from _pydev_bundle.pydev_monkey import log_error_once
dirname = os.path.dirname(__file__)
log_error_once("warning: Debugger speedups for Python 3.6 not found. Run '\"%s\" \"%s\" build_ext --inplace' to build." % (
sys.executable, os.path.join(dirname, 'setup.py')))
|
<commit_before>import os
import sys
IS_PY36_OR_OLDER = False
if (sys.version_info[0] == 3 and sys.version_info[1] >= 6) or sys.version_info[0] > 3:
IS_PY36_OR_OLDER = True
set_frame_eval = None
stop_frame_eval = None
if IS_PY36_OR_OLDER:
try:
from _pydevd_frame_eval.pydevd_frame_evaluator import frame_eval_func, stop_frame_eval
except ImportError:
from _pydev_bundle.pydev_monkey import log_error_once
dirname = os.path.dirname(__file__)
log_error_once("warning: Debugger speedups for Python 3.6 not found. Run '\"%s\" \"%s\" build_ext --inplace' to build." % (
sys.executable, os.path.join(dirname, 'setup.py')))
<commit_msg>Add ability to disable frame evaluation<commit_after>
|
import os
import sys
IS_PY36_OR_OLDER = False
if (sys.version_info[0] == 3 and sys.version_info[1] >= 6) or sys.version_info[0] > 3:
IS_PY36_OR_OLDER = True
set_frame_eval = None
stop_frame_eval = None
use_frame_eval = os.environ.get('PYDEVD_USE_FRAME_EVAL', None)
if use_frame_eval == 'NO':
frame_eval_func, stop_frame_eval = None, None
else:
if IS_PY36_OR_OLDER:
try:
from _pydevd_frame_eval.pydevd_frame_evaluator import frame_eval_func, stop_frame_eval
except ImportError:
from _pydev_bundle.pydev_monkey import log_error_once
dirname = os.path.dirname(__file__)
log_error_once("warning: Debugger speedups for Python 3.6 not found. Run '\"%s\" \"%s\" build_ext --inplace' to build." % (
sys.executable, os.path.join(dirname, 'setup.py')))
|
import os
import sys
IS_PY36_OR_OLDER = False
if (sys.version_info[0] == 3 and sys.version_info[1] >= 6) or sys.version_info[0] > 3:
IS_PY36_OR_OLDER = True
set_frame_eval = None
stop_frame_eval = None
if IS_PY36_OR_OLDER:
try:
from _pydevd_frame_eval.pydevd_frame_evaluator import frame_eval_func, stop_frame_eval
except ImportError:
from _pydev_bundle.pydev_monkey import log_error_once
dirname = os.path.dirname(__file__)
log_error_once("warning: Debugger speedups for Python 3.6 not found. Run '\"%s\" \"%s\" build_ext --inplace' to build." % (
sys.executable, os.path.join(dirname, 'setup.py')))
Add ability to disable frame evaluationimport os
import sys
IS_PY36_OR_OLDER = False
if (sys.version_info[0] == 3 and sys.version_info[1] >= 6) or sys.version_info[0] > 3:
IS_PY36_OR_OLDER = True
set_frame_eval = None
stop_frame_eval = None
use_frame_eval = os.environ.get('PYDEVD_USE_FRAME_EVAL', None)
if use_frame_eval == 'NO':
frame_eval_func, stop_frame_eval = None, None
else:
if IS_PY36_OR_OLDER:
try:
from _pydevd_frame_eval.pydevd_frame_evaluator import frame_eval_func, stop_frame_eval
except ImportError:
from _pydev_bundle.pydev_monkey import log_error_once
dirname = os.path.dirname(__file__)
log_error_once("warning: Debugger speedups for Python 3.6 not found. Run '\"%s\" \"%s\" build_ext --inplace' to build." % (
sys.executable, os.path.join(dirname, 'setup.py')))
|
<commit_before>import os
import sys
IS_PY36_OR_OLDER = False
if (sys.version_info[0] == 3 and sys.version_info[1] >= 6) or sys.version_info[0] > 3:
IS_PY36_OR_OLDER = True
set_frame_eval = None
stop_frame_eval = None
if IS_PY36_OR_OLDER:
try:
from _pydevd_frame_eval.pydevd_frame_evaluator import frame_eval_func, stop_frame_eval
except ImportError:
from _pydev_bundle.pydev_monkey import log_error_once
dirname = os.path.dirname(__file__)
log_error_once("warning: Debugger speedups for Python 3.6 not found. Run '\"%s\" \"%s\" build_ext --inplace' to build." % (
sys.executable, os.path.join(dirname, 'setup.py')))
<commit_msg>Add ability to disable frame evaluation<commit_after>import os
import sys
IS_PY36_OR_OLDER = False
if (sys.version_info[0] == 3 and sys.version_info[1] >= 6) or sys.version_info[0] > 3:
IS_PY36_OR_OLDER = True
set_frame_eval = None
stop_frame_eval = None
use_frame_eval = os.environ.get('PYDEVD_USE_FRAME_EVAL', None)
if use_frame_eval == 'NO':
frame_eval_func, stop_frame_eval = None, None
else:
if IS_PY36_OR_OLDER:
try:
from _pydevd_frame_eval.pydevd_frame_evaluator import frame_eval_func, stop_frame_eval
except ImportError:
from _pydev_bundle.pydev_monkey import log_error_once
dirname = os.path.dirname(__file__)
log_error_once("warning: Debugger speedups for Python 3.6 not found. Run '\"%s\" \"%s\" build_ext --inplace' to build." % (
sys.executable, os.path.join(dirname, 'setup.py')))
|
0cf6d8d4b3af400c7e8893f50406f33674522512
|
purchase_order_line_deep_sort/__manifest__.py
|
purchase_order_line_deep_sort/__manifest__.py
|
# Copyright 2018 Tecnativa - Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3
{
"name": "Purchase Order Line Deep Sort",
"version": "13.0.1.0.0",
"author": "Tecnativa," "Odoo Community Association (OCA)",
"license": "AGPL-3",
"category": "Purchase Management",
"website": "https://github.com/OCA/purchase-workflow",
"summary": "Purchase Order Line Sort",
"depends": ["purchase"],
"data": ["views/res_config_settings_views.xml", "views/purchase_order_views.xml"],
"installable": True,
}
|
# Copyright 2018 Tecnativa - Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3
{
"name": "Purchase Order Line Deep Sort",
"version": "13.0.1.0.0",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"category": "Purchase Management",
"website": "https://github.com/OCA/purchase-workflow",
"summary": "Purchase Order Line Sort",
"depends": ["purchase"],
"data": ["views/res_config_settings_views.xml", "views/purchase_order_views.xml"],
"installable": True,
}
|
Delete empty " " spaces in same string line
|
[FIX] Delete empty " " spaces in same string line
|
Python
|
agpl-3.0
|
OCA/purchase-workflow,OCA/purchase-workflow
|
# Copyright 2018 Tecnativa - Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3
{
"name": "Purchase Order Line Deep Sort",
"version": "13.0.1.0.0",
"author": "Tecnativa," "Odoo Community Association (OCA)",
"license": "AGPL-3",
"category": "Purchase Management",
"website": "https://github.com/OCA/purchase-workflow",
"summary": "Purchase Order Line Sort",
"depends": ["purchase"],
"data": ["views/res_config_settings_views.xml", "views/purchase_order_views.xml"],
"installable": True,
}
[FIX] Delete empty " " spaces in same string line
|
# Copyright 2018 Tecnativa - Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3
{
"name": "Purchase Order Line Deep Sort",
"version": "13.0.1.0.0",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"category": "Purchase Management",
"website": "https://github.com/OCA/purchase-workflow",
"summary": "Purchase Order Line Sort",
"depends": ["purchase"],
"data": ["views/res_config_settings_views.xml", "views/purchase_order_views.xml"],
"installable": True,
}
|
<commit_before># Copyright 2018 Tecnativa - Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3
{
"name": "Purchase Order Line Deep Sort",
"version": "13.0.1.0.0",
"author": "Tecnativa," "Odoo Community Association (OCA)",
"license": "AGPL-3",
"category": "Purchase Management",
"website": "https://github.com/OCA/purchase-workflow",
"summary": "Purchase Order Line Sort",
"depends": ["purchase"],
"data": ["views/res_config_settings_views.xml", "views/purchase_order_views.xml"],
"installable": True,
}
<commit_msg>[FIX] Delete empty " " spaces in same string line<commit_after>
|
# Copyright 2018 Tecnativa - Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3
{
"name": "Purchase Order Line Deep Sort",
"version": "13.0.1.0.0",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"category": "Purchase Management",
"website": "https://github.com/OCA/purchase-workflow",
"summary": "Purchase Order Line Sort",
"depends": ["purchase"],
"data": ["views/res_config_settings_views.xml", "views/purchase_order_views.xml"],
"installable": True,
}
|
# Copyright 2018 Tecnativa - Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3
{
"name": "Purchase Order Line Deep Sort",
"version": "13.0.1.0.0",
"author": "Tecnativa," "Odoo Community Association (OCA)",
"license": "AGPL-3",
"category": "Purchase Management",
"website": "https://github.com/OCA/purchase-workflow",
"summary": "Purchase Order Line Sort",
"depends": ["purchase"],
"data": ["views/res_config_settings_views.xml", "views/purchase_order_views.xml"],
"installable": True,
}
[FIX] Delete empty " " spaces in same string line# Copyright 2018 Tecnativa - Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3
{
"name": "Purchase Order Line Deep Sort",
"version": "13.0.1.0.0",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"category": "Purchase Management",
"website": "https://github.com/OCA/purchase-workflow",
"summary": "Purchase Order Line Sort",
"depends": ["purchase"],
"data": ["views/res_config_settings_views.xml", "views/purchase_order_views.xml"],
"installable": True,
}
|
<commit_before># Copyright 2018 Tecnativa - Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3
{
"name": "Purchase Order Line Deep Sort",
"version": "13.0.1.0.0",
"author": "Tecnativa," "Odoo Community Association (OCA)",
"license": "AGPL-3",
"category": "Purchase Management",
"website": "https://github.com/OCA/purchase-workflow",
"summary": "Purchase Order Line Sort",
"depends": ["purchase"],
"data": ["views/res_config_settings_views.xml", "views/purchase_order_views.xml"],
"installable": True,
}
<commit_msg>[FIX] Delete empty " " spaces in same string line<commit_after># Copyright 2018 Tecnativa - Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3
{
"name": "Purchase Order Line Deep Sort",
"version": "13.0.1.0.0",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"category": "Purchase Management",
"website": "https://github.com/OCA/purchase-workflow",
"summary": "Purchase Order Line Sort",
"depends": ["purchase"],
"data": ["views/res_config_settings_views.xml", "views/purchase_order_views.xml"],
"installable": True,
}
|
24ff6aa99c7ee78d58200aad03c50722563cb1a0
|
purchase_product_usage/models/account_move.py
|
purchase_product_usage/models/account_move.py
|
# Copyright 2019 Aleph Objects, Inc.
# Copyright 2019 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0).
from odoo import api, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
@api.onchange(
"amount_currency",
"currency_id",
"debit",
"credit",
"tax_ids",
"account_id",
"analytic_account_id",
"analytic_tag_ids",
)
def _onchange_mark_recompute_taxes(self):
for line in self:
if line.purchase_line_id.usage_id.account_id:
account = line.purchase_line_id.usage_id.account_id
else:
account = line._get_computed_account()
line.account_id = account
return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
|
# Copyright 2019 Aleph Objects, Inc.
# Copyright 2019 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0).
from odoo import api, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
@api.onchange(
"amount_currency",
"currency_id",
"debit",
"credit",
"tax_ids",
"account_id",
"analytic_account_id",
"analytic_tag_ids",
)
def _onchange_mark_recompute_taxes(self):
for line in self:
if line.purchase_line_id.usage_id.account_id:
line.account_id = line.purchase_line_id.usage_id.account_id
return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
|
Change only account if usage is defined in POL
|
[13.0][FIX] purchase_product_usage: Change only account if usage is defined in POL
|
Python
|
agpl-3.0
|
OCA/purchase-workflow,OCA/purchase-workflow
|
# Copyright 2019 Aleph Objects, Inc.
# Copyright 2019 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0).
from odoo import api, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
@api.onchange(
"amount_currency",
"currency_id",
"debit",
"credit",
"tax_ids",
"account_id",
"analytic_account_id",
"analytic_tag_ids",
)
def _onchange_mark_recompute_taxes(self):
for line in self:
if line.purchase_line_id.usage_id.account_id:
account = line.purchase_line_id.usage_id.account_id
else:
account = line._get_computed_account()
line.account_id = account
return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
[13.0][FIX] purchase_product_usage: Change only account if usage is defined in POL
|
# Copyright 2019 Aleph Objects, Inc.
# Copyright 2019 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0).
from odoo import api, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
@api.onchange(
"amount_currency",
"currency_id",
"debit",
"credit",
"tax_ids",
"account_id",
"analytic_account_id",
"analytic_tag_ids",
)
def _onchange_mark_recompute_taxes(self):
for line in self:
if line.purchase_line_id.usage_id.account_id:
line.account_id = line.purchase_line_id.usage_id.account_id
return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
|
<commit_before># Copyright 2019 Aleph Objects, Inc.
# Copyright 2019 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0).
from odoo import api, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
@api.onchange(
"amount_currency",
"currency_id",
"debit",
"credit",
"tax_ids",
"account_id",
"analytic_account_id",
"analytic_tag_ids",
)
def _onchange_mark_recompute_taxes(self):
for line in self:
if line.purchase_line_id.usage_id.account_id:
account = line.purchase_line_id.usage_id.account_id
else:
account = line._get_computed_account()
line.account_id = account
return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
<commit_msg>[13.0][FIX] purchase_product_usage: Change only account if usage is defined in POL<commit_after>
|
# Copyright 2019 Aleph Objects, Inc.
# Copyright 2019 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0).
from odoo import api, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
@api.onchange(
"amount_currency",
"currency_id",
"debit",
"credit",
"tax_ids",
"account_id",
"analytic_account_id",
"analytic_tag_ids",
)
def _onchange_mark_recompute_taxes(self):
for line in self:
if line.purchase_line_id.usage_id.account_id:
line.account_id = line.purchase_line_id.usage_id.account_id
return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
|
# Copyright 2019 Aleph Objects, Inc.
# Copyright 2019 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0).
from odoo import api, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
@api.onchange(
"amount_currency",
"currency_id",
"debit",
"credit",
"tax_ids",
"account_id",
"analytic_account_id",
"analytic_tag_ids",
)
def _onchange_mark_recompute_taxes(self):
for line in self:
if line.purchase_line_id.usage_id.account_id:
account = line.purchase_line_id.usage_id.account_id
else:
account = line._get_computed_account()
line.account_id = account
return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
[13.0][FIX] purchase_product_usage: Change only account if usage is defined in POL# Copyright 2019 Aleph Objects, Inc.
# Copyright 2019 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0).
from odoo import api, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
@api.onchange(
"amount_currency",
"currency_id",
"debit",
"credit",
"tax_ids",
"account_id",
"analytic_account_id",
"analytic_tag_ids",
)
def _onchange_mark_recompute_taxes(self):
for line in self:
if line.purchase_line_id.usage_id.account_id:
line.account_id = line.purchase_line_id.usage_id.account_id
return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
|
<commit_before># Copyright 2019 Aleph Objects, Inc.
# Copyright 2019 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0).
from odoo import api, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
@api.onchange(
"amount_currency",
"currency_id",
"debit",
"credit",
"tax_ids",
"account_id",
"analytic_account_id",
"analytic_tag_ids",
)
def _onchange_mark_recompute_taxes(self):
for line in self:
if line.purchase_line_id.usage_id.account_id:
account = line.purchase_line_id.usage_id.account_id
else:
account = line._get_computed_account()
line.account_id = account
return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
<commit_msg>[13.0][FIX] purchase_product_usage: Change only account if usage is defined in POL<commit_after># Copyright 2019 Aleph Objects, Inc.
# Copyright 2019 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0).
from odoo import api, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
@api.onchange(
"amount_currency",
"currency_id",
"debit",
"credit",
"tax_ids",
"account_id",
"analytic_account_id",
"analytic_tag_ids",
)
def _onchange_mark_recompute_taxes(self):
for line in self:
if line.purchase_line_id.usage_id.account_id:
line.account_id = line.purchase_line_id.usage_id.account_id
return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
|
cc6c40b64f8dfde533977883124e22e0fbc80e5c
|
soco/__init__.py
|
soco/__init__.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
""" SoCo (Sonos Controller) is a simple library to control Sonos speakers """
# Will be parsed by setup.py to determine package metadata
__author__ = 'Rahim Sonawalla <rsonawalla@gmail.com>'
__version__ = '0.7'
__website__ = 'https://github.com/SoCo/SoCo'
__license__ = 'MIT License'
from .core import discover, SoCo, SonosDiscovery
from .exceptions import SoCoException, UnknownSoCoException
__all__ = ['discover', 'SonosDiscovery', 'SoCo', 'SoCoException', 'UnknownSoCoException']
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
""" SoCo (Sonos Controller) is a simple library to control Sonos speakers """
# Will be parsed by setup.py to determine package metadata
__author__ = 'The SoCo-Team <python-soco@googlegroups.com>'
__version__ = '0.7'
__website__ = 'https://github.com/SoCo/SoCo'
__license__ = 'MIT License'
from .core import discover, SoCo, SonosDiscovery
from .exceptions import SoCoException, UnknownSoCoException
__all__ = ['discover', 'SonosDiscovery', 'SoCo', 'SoCoException', 'UnknownSoCoException']
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
Update author info to "The SoCo-Team"
|
Update author info to "The SoCo-Team"
|
Python
|
mit
|
TrondKjeldas/SoCo,flavio/SoCo,dundeemt/SoCo,xxdede/SoCo,KennethNielsen/SoCo,petteraas/SoCo,bwhaley/SoCo,xxdede/SoCo,oyvindmal/SocoWebService,TrondKjeldas/SoCo,TrondKjeldas/SoCo,petteraas/SoCo,dajobe/SoCo,intfrr/SoCo,intfrr/SoCo,xxdede/SoCo,fgend31/SoCo,jlmcgehee21/SoCo,DPH/SoCo,dsully/SoCo,meska/SoCo,bwhaley/SoCo,dajobe/SoCo,SoCo/SoCo,flavio/SoCo,lawrenceakka/SoCo,SoCo/SoCo,lawrenceakka/SoCo,KennethNielsen/SoCo,bwhaley/SoCo,fxstein/SoCo,petteraas/SoCo,fgend31/SoCo,jlmcgehee21/SoCo,fxstein/SoCo,simonalpha/SoCo,DPH/SoCo,oyvindmal/SocoWebService,simonalpha/SoCo,meska/SoCo,dundeemt/SoCo,dsully/SoCo
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
""" SoCo (Sonos Controller) is a simple library to control Sonos speakers """
# Will be parsed by setup.py to determine package metadata
__author__ = 'Rahim Sonawalla <rsonawalla@gmail.com>'
__version__ = '0.7'
__website__ = 'https://github.com/SoCo/SoCo'
__license__ = 'MIT License'
from .core import discover, SoCo, SonosDiscovery
from .exceptions import SoCoException, UnknownSoCoException
__all__ = ['discover', 'SonosDiscovery', 'SoCo', 'SoCoException', 'UnknownSoCoException']
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
Update author info to "The SoCo-Team"
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
""" SoCo (Sonos Controller) is a simple library to control Sonos speakers """
# Will be parsed by setup.py to determine package metadata
__author__ = 'The SoCo-Team <python-soco@googlegroups.com>'
__version__ = '0.7'
__website__ = 'https://github.com/SoCo/SoCo'
__license__ = 'MIT License'
from .core import discover, SoCo, SonosDiscovery
from .exceptions import SoCoException, UnknownSoCoException
__all__ = ['discover', 'SonosDiscovery', 'SoCo', 'SoCoException', 'UnknownSoCoException']
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
""" SoCo (Sonos Controller) is a simple library to control Sonos speakers """
# Will be parsed by setup.py to determine package metadata
__author__ = 'Rahim Sonawalla <rsonawalla@gmail.com>'
__version__ = '0.7'
__website__ = 'https://github.com/SoCo/SoCo'
__license__ = 'MIT License'
from .core import discover, SoCo, SonosDiscovery
from .exceptions import SoCoException, UnknownSoCoException
__all__ = ['discover', 'SonosDiscovery', 'SoCo', 'SoCoException', 'UnknownSoCoException']
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
<commit_msg>Update author info to "The SoCo-Team"<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
""" SoCo (Sonos Controller) is a simple library to control Sonos speakers """
# Will be parsed by setup.py to determine package metadata
__author__ = 'The SoCo-Team <python-soco@googlegroups.com>'
__version__ = '0.7'
__website__ = 'https://github.com/SoCo/SoCo'
__license__ = 'MIT License'
from .core import discover, SoCo, SonosDiscovery
from .exceptions import SoCoException, UnknownSoCoException
__all__ = ['discover', 'SonosDiscovery', 'SoCo', 'SoCoException', 'UnknownSoCoException']
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
""" SoCo (Sonos Controller) is a simple library to control Sonos speakers """
# Will be parsed by setup.py to determine package metadata
__author__ = 'Rahim Sonawalla <rsonawalla@gmail.com>'
__version__ = '0.7'
__website__ = 'https://github.com/SoCo/SoCo'
__license__ = 'MIT License'
from .core import discover, SoCo, SonosDiscovery
from .exceptions import SoCoException, UnknownSoCoException
__all__ = ['discover', 'SonosDiscovery', 'SoCo', 'SoCoException', 'UnknownSoCoException']
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
Update author info to "The SoCo-Team"# -*- coding: utf-8 -*-
from __future__ import unicode_literals
""" SoCo (Sonos Controller) is a simple library to control Sonos speakers """
# Will be parsed by setup.py to determine package metadata
__author__ = 'The SoCo-Team <python-soco@googlegroups.com>'
__version__ = '0.7'
__website__ = 'https://github.com/SoCo/SoCo'
__license__ = 'MIT License'
from .core import discover, SoCo, SonosDiscovery
from .exceptions import SoCoException, UnknownSoCoException
__all__ = ['discover', 'SonosDiscovery', 'SoCo', 'SoCoException', 'UnknownSoCoException']
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
""" SoCo (Sonos Controller) is a simple library to control Sonos speakers """
# Will be parsed by setup.py to determine package metadata
__author__ = 'Rahim Sonawalla <rsonawalla@gmail.com>'
__version__ = '0.7'
__website__ = 'https://github.com/SoCo/SoCo'
__license__ = 'MIT License'
from .core import discover, SoCo, SonosDiscovery
from .exceptions import SoCoException, UnknownSoCoException
__all__ = ['discover', 'SonosDiscovery', 'SoCo', 'SoCoException', 'UnknownSoCoException']
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
<commit_msg>Update author info to "The SoCo-Team"<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
""" SoCo (Sonos Controller) is a simple library to control Sonos speakers """
# Will be parsed by setup.py to determine package metadata
__author__ = 'The SoCo-Team <python-soco@googlegroups.com>'
__version__ = '0.7'
__website__ = 'https://github.com/SoCo/SoCo'
__license__ = 'MIT License'
from .core import discover, SoCo, SonosDiscovery
from .exceptions import SoCoException, UnknownSoCoException
__all__ = ['discover', 'SonosDiscovery', 'SoCo', 'SoCoException', 'UnknownSoCoException']
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
2b047e4acd3508382a263533e66254aed7af14a8
|
ggplot/components/labels.py
|
ggplot/components/labels.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from copy import deepcopy
from ..utils.exceptions import GgplotError
class labs(object):
"""
General class for all label adding classes
"""
labels = {}
def __init__(self, *args, **kwargs):
if args and not isinstance(args, dict):
raise GgplotError(
"'labs' excepts either a dictionary as",
"an argument or keyword arguments")
self.labels = args
else:
self.labels = kwargs
def __radd__(self, gg):
gg = deepcopy(gg)
gg.labels.update(self.labels)
return gg
class xlab(labs):
"""
Create x-axis label
"""
def __init__(self, xlab):
if xlab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'x': xlab}
class ylab(labs):
"""
Create y-axis label
"""
def __init__(self, ylab):
if ylab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'y': ylab}
class ggtitle(labs):
"""
Create plot title
"""
def __init__(self, title):
if title is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.label = {'title': title}
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from copy import deepcopy
from ..utils.exceptions import GgplotError
class labs(object):
"""
General class for all label adding classes
"""
labels = {}
def __init__(self, *args, **kwargs):
if args and not isinstance(args, dict):
raise GgplotError(
"'labs' excepts either a dictionary as",
"an argument or keyword arguments")
self.labels = args
else:
self.labels = kwargs
def __radd__(self, gg):
gg = deepcopy(gg)
gg.labels.update(self.labels)
return gg
class xlab(labs):
"""
Create x-axis label
"""
def __init__(self, xlab):
if xlab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'x': xlab}
class ylab(labs):
"""
Create y-axis label
"""
def __init__(self, ylab):
if ylab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'y': ylab}
class ggtitle(labs):
"""
Create plot title
"""
def __init__(self, title):
if title is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'title': title}
|
Fix plot title not showing up
|
Fix plot title not showing up
|
Python
|
mit
|
has2k1/plotnine,has2k1/plotnine
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from copy import deepcopy
from ..utils.exceptions import GgplotError
class labs(object):
"""
General class for all label adding classes
"""
labels = {}
def __init__(self, *args, **kwargs):
if args and not isinstance(args, dict):
raise GgplotError(
"'labs' excepts either a dictionary as",
"an argument or keyword arguments")
self.labels = args
else:
self.labels = kwargs
def __radd__(self, gg):
gg = deepcopy(gg)
gg.labels.update(self.labels)
return gg
class xlab(labs):
"""
Create x-axis label
"""
def __init__(self, xlab):
if xlab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'x': xlab}
class ylab(labs):
"""
Create y-axis label
"""
def __init__(self, ylab):
if ylab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'y': ylab}
class ggtitle(labs):
"""
Create plot title
"""
def __init__(self, title):
if title is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.label = {'title': title}
Fix plot title not showing up
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from copy import deepcopy
from ..utils.exceptions import GgplotError
class labs(object):
"""
General class for all label adding classes
"""
labels = {}
def __init__(self, *args, **kwargs):
if args and not isinstance(args, dict):
raise GgplotError(
"'labs' excepts either a dictionary as",
"an argument or keyword arguments")
self.labels = args
else:
self.labels = kwargs
def __radd__(self, gg):
gg = deepcopy(gg)
gg.labels.update(self.labels)
return gg
class xlab(labs):
"""
Create x-axis label
"""
def __init__(self, xlab):
if xlab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'x': xlab}
class ylab(labs):
"""
Create y-axis label
"""
def __init__(self, ylab):
if ylab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'y': ylab}
class ggtitle(labs):
"""
Create plot title
"""
def __init__(self, title):
if title is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'title': title}
|
<commit_before>from __future__ import (absolute_import, division, print_function,
unicode_literals)
from copy import deepcopy
from ..utils.exceptions import GgplotError
class labs(object):
"""
General class for all label adding classes
"""
labels = {}
def __init__(self, *args, **kwargs):
if args and not isinstance(args, dict):
raise GgplotError(
"'labs' excepts either a dictionary as",
"an argument or keyword arguments")
self.labels = args
else:
self.labels = kwargs
def __radd__(self, gg):
gg = deepcopy(gg)
gg.labels.update(self.labels)
return gg
class xlab(labs):
"""
Create x-axis label
"""
def __init__(self, xlab):
if xlab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'x': xlab}
class ylab(labs):
"""
Create y-axis label
"""
def __init__(self, ylab):
if ylab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'y': ylab}
class ggtitle(labs):
"""
Create plot title
"""
def __init__(self, title):
if title is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.label = {'title': title}
<commit_msg>Fix plot title not showing up<commit_after>
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from copy import deepcopy
from ..utils.exceptions import GgplotError
class labs(object):
"""
General class for all label adding classes
"""
labels = {}
def __init__(self, *args, **kwargs):
if args and not isinstance(args, dict):
raise GgplotError(
"'labs' excepts either a dictionary as",
"an argument or keyword arguments")
self.labels = args
else:
self.labels = kwargs
def __radd__(self, gg):
gg = deepcopy(gg)
gg.labels.update(self.labels)
return gg
class xlab(labs):
"""
Create x-axis label
"""
def __init__(self, xlab):
if xlab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'x': xlab}
class ylab(labs):
"""
Create y-axis label
"""
def __init__(self, ylab):
if ylab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'y': ylab}
class ggtitle(labs):
"""
Create plot title
"""
def __init__(self, title):
if title is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'title': title}
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from copy import deepcopy
from ..utils.exceptions import GgplotError
class labs(object):
"""
General class for all label adding classes
"""
labels = {}
def __init__(self, *args, **kwargs):
if args and not isinstance(args, dict):
raise GgplotError(
"'labs' excepts either a dictionary as",
"an argument or keyword arguments")
self.labels = args
else:
self.labels = kwargs
def __radd__(self, gg):
gg = deepcopy(gg)
gg.labels.update(self.labels)
return gg
class xlab(labs):
"""
Create x-axis label
"""
def __init__(self, xlab):
if xlab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'x': xlab}
class ylab(labs):
"""
Create y-axis label
"""
def __init__(self, ylab):
if ylab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'y': ylab}
class ggtitle(labs):
"""
Create plot title
"""
def __init__(self, title):
if title is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.label = {'title': title}
Fix plot title not showing upfrom __future__ import (absolute_import, division, print_function,
unicode_literals)
from copy import deepcopy
from ..utils.exceptions import GgplotError
class labs(object):
"""
General class for all label adding classes
"""
labels = {}
def __init__(self, *args, **kwargs):
if args and not isinstance(args, dict):
raise GgplotError(
"'labs' excepts either a dictionary as",
"an argument or keyword arguments")
self.labels = args
else:
self.labels = kwargs
def __radd__(self, gg):
gg = deepcopy(gg)
gg.labels.update(self.labels)
return gg
class xlab(labs):
"""
Create x-axis label
"""
def __init__(self, xlab):
if xlab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'x': xlab}
class ylab(labs):
"""
Create y-axis label
"""
def __init__(self, ylab):
if ylab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'y': ylab}
class ggtitle(labs):
"""
Create plot title
"""
def __init__(self, title):
if title is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'title': title}
|
<commit_before>from __future__ import (absolute_import, division, print_function,
unicode_literals)
from copy import deepcopy
from ..utils.exceptions import GgplotError
class labs(object):
"""
General class for all label adding classes
"""
labels = {}
def __init__(self, *args, **kwargs):
if args and not isinstance(args, dict):
raise GgplotError(
"'labs' excepts either a dictionary as",
"an argument or keyword arguments")
self.labels = args
else:
self.labels = kwargs
def __radd__(self, gg):
gg = deepcopy(gg)
gg.labels.update(self.labels)
return gg
class xlab(labs):
"""
Create x-axis label
"""
def __init__(self, xlab):
if xlab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'x': xlab}
class ylab(labs):
"""
Create y-axis label
"""
def __init__(self, ylab):
if ylab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'y': ylab}
class ggtitle(labs):
"""
Create plot title
"""
def __init__(self, title):
if title is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.label = {'title': title}
<commit_msg>Fix plot title not showing up<commit_after>from __future__ import (absolute_import, division, print_function,
unicode_literals)
from copy import deepcopy
from ..utils.exceptions import GgplotError
class labs(object):
"""
General class for all label adding classes
"""
labels = {}
def __init__(self, *args, **kwargs):
if args and not isinstance(args, dict):
raise GgplotError(
"'labs' excepts either a dictionary as",
"an argument or keyword arguments")
self.labels = args
else:
self.labels = kwargs
def __radd__(self, gg):
gg = deepcopy(gg)
gg.labels.update(self.labels)
return gg
class xlab(labs):
"""
Create x-axis label
"""
def __init__(self, xlab):
if xlab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'x': xlab}
class ylab(labs):
"""
Create y-axis label
"""
def __init__(self, ylab):
if ylab is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'y': ylab}
class ggtitle(labs):
"""
Create plot title
"""
def __init__(self, title):
if title is None:
raise GgplotError("Arguments to",
self.__class__.__name__,
"cannot be None")
self.labels = {'title': title}
|
910fd1b323f05b695cccf6d3250b340c46cc2db5
|
venvctrl/cli/relocate.py
|
venvctrl/cli/relocate.py
|
"""Relocate a virtual environment."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import argparse
from .. import api
def relocate(source, destination, move=False):
"""Adjust the virtual environment settings and optional move it.
Args:
source (str): Path to the existing virtual environment.
destination (str): Desired path of the virtual environment.
move (bool): Whether or not to actually move the files. Default False.
"""
venv = api.VirtualEnvironment(source)
if not move:
venv.relocate(destination)
return None
venv.move(destination)
def main():
"""Relocate a virtual environment."""
parser = argparse.ArgumentParser(
description='Relocate a virtual environment.'
)
parser.add_argument(
'--source',
help='The existing virtual environment.',
required=True,
)
parser.add_argument(
'--destination',
help='The location for which to configure the virtual environment.',
required=True,
)
parser.add_argument(
'--move',
help='Move the virtual environment to the destination.',
default=False,
action='store_true',
)
args = parser.parse_args()
relocate(args.source, args.destination, args.move)
if __name__ == '__main__':
main()
|
"""Relocate a virtual environment."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import argparse
from .. import api
def relocate(source, destination, move=False):
"""Adjust the virtual environment settings and optional move it.
Args:
source (str): Path to the existing virtual environment.
destination (str): Desired path of the virtual environment.
move (bool): Whether or not to actually move the files. Default False.
"""
venv = api.VirtualEnvironment(source)
if not move:
venv.relocate(destination)
return None
venv.move(destination)
return None
def main():
"""Relocate a virtual environment."""
parser = argparse.ArgumentParser(
description='Relocate a virtual environment.'
)
parser.add_argument(
'--source',
help='The existing virtual environment.',
required=True,
)
parser.add_argument(
'--destination',
help='The location for which to configure the virtual environment.',
required=True,
)
parser.add_argument(
'--move',
help='Move the virtual environment to the destination.',
default=False,
action='store_true',
)
args = parser.parse_args()
relocate(args.source, args.destination, args.move)
if __name__ == '__main__':
main()
|
Fix cli module for new lint detection
|
Fix cli module for new lint detection
Since the last commit (2015), some of the test dependencies have
updated. This commit specifically addresses updates in PyLint which
result in more lint being detected in the project that previous test
runs.
|
Python
|
mit
|
kevinconway/venvctrl
|
"""Relocate a virtual environment."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import argparse
from .. import api
def relocate(source, destination, move=False):
"""Adjust the virtual environment settings and optional move it.
Args:
source (str): Path to the existing virtual environment.
destination (str): Desired path of the virtual environment.
move (bool): Whether or not to actually move the files. Default False.
"""
venv = api.VirtualEnvironment(source)
if not move:
venv.relocate(destination)
return None
venv.move(destination)
def main():
"""Relocate a virtual environment."""
parser = argparse.ArgumentParser(
description='Relocate a virtual environment.'
)
parser.add_argument(
'--source',
help='The existing virtual environment.',
required=True,
)
parser.add_argument(
'--destination',
help='The location for which to configure the virtual environment.',
required=True,
)
parser.add_argument(
'--move',
help='Move the virtual environment to the destination.',
default=False,
action='store_true',
)
args = parser.parse_args()
relocate(args.source, args.destination, args.move)
if __name__ == '__main__':
main()
Fix cli module for new lint detection
Since the last commit (2015), some of the test dependencies have
updated. This commit specifically addresses updates in PyLint which
result in more lint being detected in the project that previous test
runs.
|
"""Relocate a virtual environment."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import argparse
from .. import api
def relocate(source, destination, move=False):
"""Adjust the virtual environment settings and optional move it.
Args:
source (str): Path to the existing virtual environment.
destination (str): Desired path of the virtual environment.
move (bool): Whether or not to actually move the files. Default False.
"""
venv = api.VirtualEnvironment(source)
if not move:
venv.relocate(destination)
return None
venv.move(destination)
return None
def main():
"""Relocate a virtual environment."""
parser = argparse.ArgumentParser(
description='Relocate a virtual environment.'
)
parser.add_argument(
'--source',
help='The existing virtual environment.',
required=True,
)
parser.add_argument(
'--destination',
help='The location for which to configure the virtual environment.',
required=True,
)
parser.add_argument(
'--move',
help='Move the virtual environment to the destination.',
default=False,
action='store_true',
)
args = parser.parse_args()
relocate(args.source, args.destination, args.move)
if __name__ == '__main__':
main()
|
<commit_before>"""Relocate a virtual environment."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import argparse
from .. import api
def relocate(source, destination, move=False):
"""Adjust the virtual environment settings and optional move it.
Args:
source (str): Path to the existing virtual environment.
destination (str): Desired path of the virtual environment.
move (bool): Whether or not to actually move the files. Default False.
"""
venv = api.VirtualEnvironment(source)
if not move:
venv.relocate(destination)
return None
venv.move(destination)
def main():
"""Relocate a virtual environment."""
parser = argparse.ArgumentParser(
description='Relocate a virtual environment.'
)
parser.add_argument(
'--source',
help='The existing virtual environment.',
required=True,
)
parser.add_argument(
'--destination',
help='The location for which to configure the virtual environment.',
required=True,
)
parser.add_argument(
'--move',
help='Move the virtual environment to the destination.',
default=False,
action='store_true',
)
args = parser.parse_args()
relocate(args.source, args.destination, args.move)
if __name__ == '__main__':
main()
<commit_msg>Fix cli module for new lint detection
Since the last commit (2015), some of the test dependencies have
updated. This commit specifically addresses updates in PyLint which
result in more lint being detected in the project that previous test
runs.<commit_after>
|
"""Relocate a virtual environment."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import argparse
from .. import api
def relocate(source, destination, move=False):
"""Adjust the virtual environment settings and optional move it.
Args:
source (str): Path to the existing virtual environment.
destination (str): Desired path of the virtual environment.
move (bool): Whether or not to actually move the files. Default False.
"""
venv = api.VirtualEnvironment(source)
if not move:
venv.relocate(destination)
return None
venv.move(destination)
return None
def main():
"""Relocate a virtual environment."""
parser = argparse.ArgumentParser(
description='Relocate a virtual environment.'
)
parser.add_argument(
'--source',
help='The existing virtual environment.',
required=True,
)
parser.add_argument(
'--destination',
help='The location for which to configure the virtual environment.',
required=True,
)
parser.add_argument(
'--move',
help='Move the virtual environment to the destination.',
default=False,
action='store_true',
)
args = parser.parse_args()
relocate(args.source, args.destination, args.move)
if __name__ == '__main__':
main()
|
"""Relocate a virtual environment."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import argparse
from .. import api
def relocate(source, destination, move=False):
"""Adjust the virtual environment settings and optional move it.
Args:
source (str): Path to the existing virtual environment.
destination (str): Desired path of the virtual environment.
move (bool): Whether or not to actually move the files. Default False.
"""
venv = api.VirtualEnvironment(source)
if not move:
venv.relocate(destination)
return None
venv.move(destination)
def main():
"""Relocate a virtual environment."""
parser = argparse.ArgumentParser(
description='Relocate a virtual environment.'
)
parser.add_argument(
'--source',
help='The existing virtual environment.',
required=True,
)
parser.add_argument(
'--destination',
help='The location for which to configure the virtual environment.',
required=True,
)
parser.add_argument(
'--move',
help='Move the virtual environment to the destination.',
default=False,
action='store_true',
)
args = parser.parse_args()
relocate(args.source, args.destination, args.move)
if __name__ == '__main__':
main()
Fix cli module for new lint detection
Since the last commit (2015), some of the test dependencies have
updated. This commit specifically addresses updates in PyLint which
result in more lint being detected in the project that previous test
runs."""Relocate a virtual environment."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import argparse
from .. import api
def relocate(source, destination, move=False):
"""Adjust the virtual environment settings and optional move it.
Args:
source (str): Path to the existing virtual environment.
destination (str): Desired path of the virtual environment.
move (bool): Whether or not to actually move the files. Default False.
"""
venv = api.VirtualEnvironment(source)
if not move:
venv.relocate(destination)
return None
venv.move(destination)
return None
def main():
"""Relocate a virtual environment."""
parser = argparse.ArgumentParser(
description='Relocate a virtual environment.'
)
parser.add_argument(
'--source',
help='The existing virtual environment.',
required=True,
)
parser.add_argument(
'--destination',
help='The location for which to configure the virtual environment.',
required=True,
)
parser.add_argument(
'--move',
help='Move the virtual environment to the destination.',
default=False,
action='store_true',
)
args = parser.parse_args()
relocate(args.source, args.destination, args.move)
if __name__ == '__main__':
main()
|
<commit_before>"""Relocate a virtual environment."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import argparse
from .. import api
def relocate(source, destination, move=False):
"""Adjust the virtual environment settings and optional move it.
Args:
source (str): Path to the existing virtual environment.
destination (str): Desired path of the virtual environment.
move (bool): Whether or not to actually move the files. Default False.
"""
venv = api.VirtualEnvironment(source)
if not move:
venv.relocate(destination)
return None
venv.move(destination)
def main():
"""Relocate a virtual environment."""
parser = argparse.ArgumentParser(
description='Relocate a virtual environment.'
)
parser.add_argument(
'--source',
help='The existing virtual environment.',
required=True,
)
parser.add_argument(
'--destination',
help='The location for which to configure the virtual environment.',
required=True,
)
parser.add_argument(
'--move',
help='Move the virtual environment to the destination.',
default=False,
action='store_true',
)
args = parser.parse_args()
relocate(args.source, args.destination, args.move)
if __name__ == '__main__':
main()
<commit_msg>Fix cli module for new lint detection
Since the last commit (2015), some of the test dependencies have
updated. This commit specifically addresses updates in PyLint which
result in more lint being detected in the project that previous test
runs.<commit_after>"""Relocate a virtual environment."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import argparse
from .. import api
def relocate(source, destination, move=False):
"""Adjust the virtual environment settings and optional move it.
Args:
source (str): Path to the existing virtual environment.
destination (str): Desired path of the virtual environment.
move (bool): Whether or not to actually move the files. Default False.
"""
venv = api.VirtualEnvironment(source)
if not move:
venv.relocate(destination)
return None
venv.move(destination)
return None
def main():
"""Relocate a virtual environment."""
parser = argparse.ArgumentParser(
description='Relocate a virtual environment.'
)
parser.add_argument(
'--source',
help='The existing virtual environment.',
required=True,
)
parser.add_argument(
'--destination',
help='The location for which to configure the virtual environment.',
required=True,
)
parser.add_argument(
'--move',
help='Move the virtual environment to the destination.',
default=False,
action='store_true',
)
args = parser.parse_args()
relocate(args.source, args.destination, args.move)
if __name__ == '__main__':
main()
|
742569a4781132d11de6d41811ee11ad55560294
|
django_slack/exceptions.py
|
django_slack/exceptions.py
|
import six
class SlackException(ValueError):
def __init__(self, message, message_data):
super(SlackException, self).__init__(message)
self.message_data = message_data
@six.python_2_unicode_compatible
class ChannelNotFound(SlackException):
def __str__(self):
# Override base __str__ to ensure we include the channel name in the
# error message
return u"{}: channel '{}' could not be found".format(
self.__class__.__name__,
self.message_data['channel'],
)
class IsArchived(SlackException):
pass
class MsgTooLong(SlackException):
pass
class NoText(SlackException):
pass
class RateLimited(SlackException):
pass
class NotAuthed(SlackException):
pass
class InvalidAuth(SlackException):
pass
class TokenRevoked(SlackException):
pass
class AccountInactive(SlackException):
pass
class UserIsBot(SlackException):
pass
LABEL_TO_EXCEPTION = {
'channel_not_found': ChannelNotFound,
'is_archived': IsArchived,
'msg_too_long': MsgTooLong,
'no_text': NoText,
'rate_limited': RateLimited,
'not_authed': NotAuthed,
'invalid_auth': InvalidAuth,
'token_revoked': TokenRevoked,
'account_inactive': AccountInactive,
'user_is_bot': UserIsBot,
}
|
import six
class SlackException(ValueError):
def __init__(self, message, message_data):
super(SlackException, self).__init__(message)
self.message_data = message_data
@six.python_2_unicode_compatible
class ChannelNotFound(SlackException):
def __str__(self):
# Override base __str__ to ensure we include the channel name in the
# error message
return u"{}: channel '{}' could not be found".format(
self.__class__.__name__,
self.message_data['channel'],
)
class IsArchived(SlackException):
pass
class FatalError(SlackException):
pass
class MsgTooLong(SlackException):
pass
class NoText(SlackException):
pass
class RateLimited(SlackException):
pass
class NotAuthed(SlackException):
pass
class InvalidAuth(SlackException):
pass
class TokenRevoked(SlackException):
pass
class AccountInactive(SlackException):
pass
class UserIsBot(SlackException):
pass
LABEL_TO_EXCEPTION = {
'channel_not_found': ChannelNotFound,
'is_archived': IsArchived,
'fatal_error': FatalError,
'msg_too_long': MsgTooLong,
'no_text': NoText,
'rate_limited': RateLimited,
'not_authed': NotAuthed,
'invalid_auth': InvalidAuth,
'token_revoked': TokenRevoked,
'account_inactive': AccountInactive,
'user_is_bot': UserIsBot,
}
|
Add another specific error class
|
Add another specific error class
|
Python
|
bsd-3-clause
|
lamby/django-slack
|
import six
class SlackException(ValueError):
def __init__(self, message, message_data):
super(SlackException, self).__init__(message)
self.message_data = message_data
@six.python_2_unicode_compatible
class ChannelNotFound(SlackException):
def __str__(self):
# Override base __str__ to ensure we include the channel name in the
# error message
return u"{}: channel '{}' could not be found".format(
self.__class__.__name__,
self.message_data['channel'],
)
class IsArchived(SlackException):
pass
class MsgTooLong(SlackException):
pass
class NoText(SlackException):
pass
class RateLimited(SlackException):
pass
class NotAuthed(SlackException):
pass
class InvalidAuth(SlackException):
pass
class TokenRevoked(SlackException):
pass
class AccountInactive(SlackException):
pass
class UserIsBot(SlackException):
pass
LABEL_TO_EXCEPTION = {
'channel_not_found': ChannelNotFound,
'is_archived': IsArchived,
'msg_too_long': MsgTooLong,
'no_text': NoText,
'rate_limited': RateLimited,
'not_authed': NotAuthed,
'invalid_auth': InvalidAuth,
'token_revoked': TokenRevoked,
'account_inactive': AccountInactive,
'user_is_bot': UserIsBot,
}
Add another specific error class
|
import six
class SlackException(ValueError):
def __init__(self, message, message_data):
super(SlackException, self).__init__(message)
self.message_data = message_data
@six.python_2_unicode_compatible
class ChannelNotFound(SlackException):
def __str__(self):
# Override base __str__ to ensure we include the channel name in the
# error message
return u"{}: channel '{}' could not be found".format(
self.__class__.__name__,
self.message_data['channel'],
)
class IsArchived(SlackException):
pass
class FatalError(SlackException):
pass
class MsgTooLong(SlackException):
pass
class NoText(SlackException):
pass
class RateLimited(SlackException):
pass
class NotAuthed(SlackException):
pass
class InvalidAuth(SlackException):
pass
class TokenRevoked(SlackException):
pass
class AccountInactive(SlackException):
pass
class UserIsBot(SlackException):
pass
LABEL_TO_EXCEPTION = {
'channel_not_found': ChannelNotFound,
'is_archived': IsArchived,
'fatal_error': FatalError,
'msg_too_long': MsgTooLong,
'no_text': NoText,
'rate_limited': RateLimited,
'not_authed': NotAuthed,
'invalid_auth': InvalidAuth,
'token_revoked': TokenRevoked,
'account_inactive': AccountInactive,
'user_is_bot': UserIsBot,
}
|
<commit_before>import six
class SlackException(ValueError):
def __init__(self, message, message_data):
super(SlackException, self).__init__(message)
self.message_data = message_data
@six.python_2_unicode_compatible
class ChannelNotFound(SlackException):
def __str__(self):
# Override base __str__ to ensure we include the channel name in the
# error message
return u"{}: channel '{}' could not be found".format(
self.__class__.__name__,
self.message_data['channel'],
)
class IsArchived(SlackException):
pass
class MsgTooLong(SlackException):
pass
class NoText(SlackException):
pass
class RateLimited(SlackException):
pass
class NotAuthed(SlackException):
pass
class InvalidAuth(SlackException):
pass
class TokenRevoked(SlackException):
pass
class AccountInactive(SlackException):
pass
class UserIsBot(SlackException):
pass
LABEL_TO_EXCEPTION = {
'channel_not_found': ChannelNotFound,
'is_archived': IsArchived,
'msg_too_long': MsgTooLong,
'no_text': NoText,
'rate_limited': RateLimited,
'not_authed': NotAuthed,
'invalid_auth': InvalidAuth,
'token_revoked': TokenRevoked,
'account_inactive': AccountInactive,
'user_is_bot': UserIsBot,
}
<commit_msg>Add another specific error class<commit_after>
|
import six
class SlackException(ValueError):
def __init__(self, message, message_data):
super(SlackException, self).__init__(message)
self.message_data = message_data
@six.python_2_unicode_compatible
class ChannelNotFound(SlackException):
def __str__(self):
# Override base __str__ to ensure we include the channel name in the
# error message
return u"{}: channel '{}' could not be found".format(
self.__class__.__name__,
self.message_data['channel'],
)
class IsArchived(SlackException):
pass
class FatalError(SlackException):
pass
class MsgTooLong(SlackException):
pass
class NoText(SlackException):
pass
class RateLimited(SlackException):
pass
class NotAuthed(SlackException):
pass
class InvalidAuth(SlackException):
pass
class TokenRevoked(SlackException):
pass
class AccountInactive(SlackException):
pass
class UserIsBot(SlackException):
pass
LABEL_TO_EXCEPTION = {
'channel_not_found': ChannelNotFound,
'is_archived': IsArchived,
'fatal_error': FatalError,
'msg_too_long': MsgTooLong,
'no_text': NoText,
'rate_limited': RateLimited,
'not_authed': NotAuthed,
'invalid_auth': InvalidAuth,
'token_revoked': TokenRevoked,
'account_inactive': AccountInactive,
'user_is_bot': UserIsBot,
}
|
import six
class SlackException(ValueError):
def __init__(self, message, message_data):
super(SlackException, self).__init__(message)
self.message_data = message_data
@six.python_2_unicode_compatible
class ChannelNotFound(SlackException):
def __str__(self):
# Override base __str__ to ensure we include the channel name in the
# error message
return u"{}: channel '{}' could not be found".format(
self.__class__.__name__,
self.message_data['channel'],
)
class IsArchived(SlackException):
pass
class MsgTooLong(SlackException):
pass
class NoText(SlackException):
pass
class RateLimited(SlackException):
pass
class NotAuthed(SlackException):
pass
class InvalidAuth(SlackException):
pass
class TokenRevoked(SlackException):
pass
class AccountInactive(SlackException):
pass
class UserIsBot(SlackException):
pass
LABEL_TO_EXCEPTION = {
'channel_not_found': ChannelNotFound,
'is_archived': IsArchived,
'msg_too_long': MsgTooLong,
'no_text': NoText,
'rate_limited': RateLimited,
'not_authed': NotAuthed,
'invalid_auth': InvalidAuth,
'token_revoked': TokenRevoked,
'account_inactive': AccountInactive,
'user_is_bot': UserIsBot,
}
Add another specific error classimport six
class SlackException(ValueError):
def __init__(self, message, message_data):
super(SlackException, self).__init__(message)
self.message_data = message_data
@six.python_2_unicode_compatible
class ChannelNotFound(SlackException):
def __str__(self):
# Override base __str__ to ensure we include the channel name in the
# error message
return u"{}: channel '{}' could not be found".format(
self.__class__.__name__,
self.message_data['channel'],
)
class IsArchived(SlackException):
pass
class FatalError(SlackException):
pass
class MsgTooLong(SlackException):
pass
class NoText(SlackException):
pass
class RateLimited(SlackException):
pass
class NotAuthed(SlackException):
pass
class InvalidAuth(SlackException):
pass
class TokenRevoked(SlackException):
pass
class AccountInactive(SlackException):
pass
class UserIsBot(SlackException):
pass
LABEL_TO_EXCEPTION = {
'channel_not_found': ChannelNotFound,
'is_archived': IsArchived,
'fatal_error': FatalError,
'msg_too_long': MsgTooLong,
'no_text': NoText,
'rate_limited': RateLimited,
'not_authed': NotAuthed,
'invalid_auth': InvalidAuth,
'token_revoked': TokenRevoked,
'account_inactive': AccountInactive,
'user_is_bot': UserIsBot,
}
|
<commit_before>import six
class SlackException(ValueError):
def __init__(self, message, message_data):
super(SlackException, self).__init__(message)
self.message_data = message_data
@six.python_2_unicode_compatible
class ChannelNotFound(SlackException):
def __str__(self):
# Override base __str__ to ensure we include the channel name in the
# error message
return u"{}: channel '{}' could not be found".format(
self.__class__.__name__,
self.message_data['channel'],
)
class IsArchived(SlackException):
pass
class MsgTooLong(SlackException):
pass
class NoText(SlackException):
pass
class RateLimited(SlackException):
pass
class NotAuthed(SlackException):
pass
class InvalidAuth(SlackException):
pass
class TokenRevoked(SlackException):
pass
class AccountInactive(SlackException):
pass
class UserIsBot(SlackException):
pass
LABEL_TO_EXCEPTION = {
'channel_not_found': ChannelNotFound,
'is_archived': IsArchived,
'msg_too_long': MsgTooLong,
'no_text': NoText,
'rate_limited': RateLimited,
'not_authed': NotAuthed,
'invalid_auth': InvalidAuth,
'token_revoked': TokenRevoked,
'account_inactive': AccountInactive,
'user_is_bot': UserIsBot,
}
<commit_msg>Add another specific error class<commit_after>import six
class SlackException(ValueError):
def __init__(self, message, message_data):
super(SlackException, self).__init__(message)
self.message_data = message_data
@six.python_2_unicode_compatible
class ChannelNotFound(SlackException):
def __str__(self):
# Override base __str__ to ensure we include the channel name in the
# error message
return u"{}: channel '{}' could not be found".format(
self.__class__.__name__,
self.message_data['channel'],
)
class IsArchived(SlackException):
pass
class FatalError(SlackException):
pass
class MsgTooLong(SlackException):
pass
class NoText(SlackException):
pass
class RateLimited(SlackException):
pass
class NotAuthed(SlackException):
pass
class InvalidAuth(SlackException):
pass
class TokenRevoked(SlackException):
pass
class AccountInactive(SlackException):
pass
class UserIsBot(SlackException):
pass
LABEL_TO_EXCEPTION = {
'channel_not_found': ChannelNotFound,
'is_archived': IsArchived,
'fatal_error': FatalError,
'msg_too_long': MsgTooLong,
'no_text': NoText,
'rate_limited': RateLimited,
'not_authed': NotAuthed,
'invalid_auth': InvalidAuth,
'token_revoked': TokenRevoked,
'account_inactive': AccountInactive,
'user_is_bot': UserIsBot,
}
|
220e0008924878f774f570cc0122c563f2c17465
|
recipes/migrations/0010_auto_20150919_1228.py
|
recipes/migrations/0010_auto_20150919_1228.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def change_to_usage(apps, schema_editor):
Recipe = apps.get_model("recipes", "Recipe")
Ingredient = apps.get_model("recipes", "Ingredient")
IngredientUsage = apps.get_model("recipes", "IngredientUsage")
for recipe in Recipe.objects.all():
for ingredient in recipe.ingredient_set.all():
u = IngredientUsage(recipe=r, ingredient=i, quantity=1)
u.save()
class Migration(migrations.Migration):
dependencies = [
('recipes', '0009_auto_20150919_1226'),
]
operations = [
migrations.RunPython(change_to_usage),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def change_to_usage(apps, schema_editor):
Recipe = apps.get_model("recipes", "Recipe")
Ingredient = apps.get_model("recipes", "Ingredient")
IngredientUsage = apps.get_model("recipes", "IngredientUsage")
for recipe in Recipe.objects.all():
for ingredient in recipe.ingredient_set.all():
u = IngredientUsage(recipe=recipe, ingredient=ingredient,
quantity=1)
u.save()
class Migration(migrations.Migration):
dependencies = [
('recipes', '0009_auto_20150919_1226'),
]
operations = [
migrations.RunPython(change_to_usage),
]
|
Make the data migration actually work
|
Make the data migration actually work
|
Python
|
agpl-3.0
|
XeryusTC/rotd,XeryusTC/rotd,XeryusTC/rotd
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def change_to_usage(apps, schema_editor):
Recipe = apps.get_model("recipes", "Recipe")
Ingredient = apps.get_model("recipes", "Ingredient")
IngredientUsage = apps.get_model("recipes", "IngredientUsage")
for recipe in Recipe.objects.all():
for ingredient in recipe.ingredient_set.all():
u = IngredientUsage(recipe=r, ingredient=i, quantity=1)
u.save()
class Migration(migrations.Migration):
dependencies = [
('recipes', '0009_auto_20150919_1226'),
]
operations = [
migrations.RunPython(change_to_usage),
]
Make the data migration actually work
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def change_to_usage(apps, schema_editor):
Recipe = apps.get_model("recipes", "Recipe")
Ingredient = apps.get_model("recipes", "Ingredient")
IngredientUsage = apps.get_model("recipes", "IngredientUsage")
for recipe in Recipe.objects.all():
for ingredient in recipe.ingredient_set.all():
u = IngredientUsage(recipe=recipe, ingredient=ingredient,
quantity=1)
u.save()
class Migration(migrations.Migration):
dependencies = [
('recipes', '0009_auto_20150919_1226'),
]
operations = [
migrations.RunPython(change_to_usage),
]
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def change_to_usage(apps, schema_editor):
Recipe = apps.get_model("recipes", "Recipe")
Ingredient = apps.get_model("recipes", "Ingredient")
IngredientUsage = apps.get_model("recipes", "IngredientUsage")
for recipe in Recipe.objects.all():
for ingredient in recipe.ingredient_set.all():
u = IngredientUsage(recipe=r, ingredient=i, quantity=1)
u.save()
class Migration(migrations.Migration):
dependencies = [
('recipes', '0009_auto_20150919_1226'),
]
operations = [
migrations.RunPython(change_to_usage),
]
<commit_msg>Make the data migration actually work<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def change_to_usage(apps, schema_editor):
Recipe = apps.get_model("recipes", "Recipe")
Ingredient = apps.get_model("recipes", "Ingredient")
IngredientUsage = apps.get_model("recipes", "IngredientUsage")
for recipe in Recipe.objects.all():
for ingredient in recipe.ingredient_set.all():
u = IngredientUsage(recipe=recipe, ingredient=ingredient,
quantity=1)
u.save()
class Migration(migrations.Migration):
dependencies = [
('recipes', '0009_auto_20150919_1226'),
]
operations = [
migrations.RunPython(change_to_usage),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def change_to_usage(apps, schema_editor):
Recipe = apps.get_model("recipes", "Recipe")
Ingredient = apps.get_model("recipes", "Ingredient")
IngredientUsage = apps.get_model("recipes", "IngredientUsage")
for recipe in Recipe.objects.all():
for ingredient in recipe.ingredient_set.all():
u = IngredientUsage(recipe=r, ingredient=i, quantity=1)
u.save()
class Migration(migrations.Migration):
dependencies = [
('recipes', '0009_auto_20150919_1226'),
]
operations = [
migrations.RunPython(change_to_usage),
]
Make the data migration actually work# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def change_to_usage(apps, schema_editor):
Recipe = apps.get_model("recipes", "Recipe")
Ingredient = apps.get_model("recipes", "Ingredient")
IngredientUsage = apps.get_model("recipes", "IngredientUsage")
for recipe in Recipe.objects.all():
for ingredient in recipe.ingredient_set.all():
u = IngredientUsage(recipe=recipe, ingredient=ingredient,
quantity=1)
u.save()
class Migration(migrations.Migration):
dependencies = [
('recipes', '0009_auto_20150919_1226'),
]
operations = [
migrations.RunPython(change_to_usage),
]
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def change_to_usage(apps, schema_editor):
Recipe = apps.get_model("recipes", "Recipe")
Ingredient = apps.get_model("recipes", "Ingredient")
IngredientUsage = apps.get_model("recipes", "IngredientUsage")
for recipe in Recipe.objects.all():
for ingredient in recipe.ingredient_set.all():
u = IngredientUsage(recipe=r, ingredient=i, quantity=1)
u.save()
class Migration(migrations.Migration):
dependencies = [
('recipes', '0009_auto_20150919_1226'),
]
operations = [
migrations.RunPython(change_to_usage),
]
<commit_msg>Make the data migration actually work<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def change_to_usage(apps, schema_editor):
Recipe = apps.get_model("recipes", "Recipe")
Ingredient = apps.get_model("recipes", "Ingredient")
IngredientUsage = apps.get_model("recipes", "IngredientUsage")
for recipe in Recipe.objects.all():
for ingredient in recipe.ingredient_set.all():
u = IngredientUsage(recipe=recipe, ingredient=ingredient,
quantity=1)
u.save()
class Migration(migrations.Migration):
dependencies = [
('recipes', '0009_auto_20150919_1226'),
]
operations = [
migrations.RunPython(change_to_usage),
]
|
afddecff42b7d8b78048f122488e70eb48660327
|
test-mm.py
|
test-mm.py
|
from psautohint import autohint
from psautohint import psautohint
d = "tests/data/source-code-pro"
mm = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold")
gg = []
ii = None
for m in mm:
f = autohint.openOpenTypeFile("%s/%s/font.otf" % (d, m), "font.otf", None)
g = f.convertToBez("A", False)
gg.append(g[0])
if ii is None:
ii = f.getFontInfo(f.getPSName(), "%s/%s/font.otf" % (d, m), False, False, [], [])
ii = ii.getFontInfo()
gg = psautohint.autohint(ii, gg, True)
gg = psautohint.autohintmm(ii, [gg], True)
|
from psautohint import autohint
from psautohint import psautohint
baseDir = "tests/data/source-code-pro"
masters = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold")
glyphList = None
fonts = []
for master in masters:
print("Hinting %s" % master)
path = "%s/%s/font.otf" % (baseDir, master)
font = autohint.openOpenTypeFile(path, "font.otf", None)
names = font.getGlyphList()
info = font.getFontInfo(font.getPSName(), path, False, False, [], [])
info = info.getFontInfo()
if glyphList is None:
glyphList = names
else:
assert glyphList == names
glyphs = []
for name in names:
glyph = font.convertToBez(name, False)
glyphs.append(glyph[0])
fonts.append(psautohint.autohint(info, glyphs, False, False, False))
glyphs = []
for i in range(len(glyphList)):
glyphs.append([f[i] for f in fonts])
print("MM Hinting")
glyphs = psautohint.autohintmm(info, glyphs, True)
|
Rewrite the test script to hint all glyphs
|
Rewrite the test script to hint all glyphs
Which reveals that no MM-compatible hinting is really done :(
|
Python
|
apache-2.0
|
khaledhosny/psautohint,khaledhosny/psautohint
|
from psautohint import autohint
from psautohint import psautohint
d = "tests/data/source-code-pro"
mm = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold")
gg = []
ii = None
for m in mm:
f = autohint.openOpenTypeFile("%s/%s/font.otf" % (d, m), "font.otf", None)
g = f.convertToBez("A", False)
gg.append(g[0])
if ii is None:
ii = f.getFontInfo(f.getPSName(), "%s/%s/font.otf" % (d, m), False, False, [], [])
ii = ii.getFontInfo()
gg = psautohint.autohint(ii, gg, True)
gg = psautohint.autohintmm(ii, [gg], True)
Rewrite the test script to hint all glyphs
Which reveals that no MM-compatible hinting is really done :(
|
from psautohint import autohint
from psautohint import psautohint
baseDir = "tests/data/source-code-pro"
masters = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold")
glyphList = None
fonts = []
for master in masters:
print("Hinting %s" % master)
path = "%s/%s/font.otf" % (baseDir, master)
font = autohint.openOpenTypeFile(path, "font.otf", None)
names = font.getGlyphList()
info = font.getFontInfo(font.getPSName(), path, False, False, [], [])
info = info.getFontInfo()
if glyphList is None:
glyphList = names
else:
assert glyphList == names
glyphs = []
for name in names:
glyph = font.convertToBez(name, False)
glyphs.append(glyph[0])
fonts.append(psautohint.autohint(info, glyphs, False, False, False))
glyphs = []
for i in range(len(glyphList)):
glyphs.append([f[i] for f in fonts])
print("MM Hinting")
glyphs = psautohint.autohintmm(info, glyphs, True)
|
<commit_before>from psautohint import autohint
from psautohint import psautohint
d = "tests/data/source-code-pro"
mm = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold")
gg = []
ii = None
for m in mm:
f = autohint.openOpenTypeFile("%s/%s/font.otf" % (d, m), "font.otf", None)
g = f.convertToBez("A", False)
gg.append(g[0])
if ii is None:
ii = f.getFontInfo(f.getPSName(), "%s/%s/font.otf" % (d, m), False, False, [], [])
ii = ii.getFontInfo()
gg = psautohint.autohint(ii, gg, True)
gg = psautohint.autohintmm(ii, [gg], True)
<commit_msg>Rewrite the test script to hint all glyphs
Which reveals that no MM-compatible hinting is really done :(<commit_after>
|
from psautohint import autohint
from psautohint import psautohint
baseDir = "tests/data/source-code-pro"
masters = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold")
glyphList = None
fonts = []
for master in masters:
print("Hinting %s" % master)
path = "%s/%s/font.otf" % (baseDir, master)
font = autohint.openOpenTypeFile(path, "font.otf", None)
names = font.getGlyphList()
info = font.getFontInfo(font.getPSName(), path, False, False, [], [])
info = info.getFontInfo()
if glyphList is None:
glyphList = names
else:
assert glyphList == names
glyphs = []
for name in names:
glyph = font.convertToBez(name, False)
glyphs.append(glyph[0])
fonts.append(psautohint.autohint(info, glyphs, False, False, False))
glyphs = []
for i in range(len(glyphList)):
glyphs.append([f[i] for f in fonts])
print("MM Hinting")
glyphs = psautohint.autohintmm(info, glyphs, True)
|
from psautohint import autohint
from psautohint import psautohint
d = "tests/data/source-code-pro"
mm = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold")
gg = []
ii = None
for m in mm:
f = autohint.openOpenTypeFile("%s/%s/font.otf" % (d, m), "font.otf", None)
g = f.convertToBez("A", False)
gg.append(g[0])
if ii is None:
ii = f.getFontInfo(f.getPSName(), "%s/%s/font.otf" % (d, m), False, False, [], [])
ii = ii.getFontInfo()
gg = psautohint.autohint(ii, gg, True)
gg = psautohint.autohintmm(ii, [gg], True)
Rewrite the test script to hint all glyphs
Which reveals that no MM-compatible hinting is really done :(from psautohint import autohint
from psautohint import psautohint
baseDir = "tests/data/source-code-pro"
masters = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold")
glyphList = None
fonts = []
for master in masters:
print("Hinting %s" % master)
path = "%s/%s/font.otf" % (baseDir, master)
font = autohint.openOpenTypeFile(path, "font.otf", None)
names = font.getGlyphList()
info = font.getFontInfo(font.getPSName(), path, False, False, [], [])
info = info.getFontInfo()
if glyphList is None:
glyphList = names
else:
assert glyphList == names
glyphs = []
for name in names:
glyph = font.convertToBez(name, False)
glyphs.append(glyph[0])
fonts.append(psautohint.autohint(info, glyphs, False, False, False))
glyphs = []
for i in range(len(glyphList)):
glyphs.append([f[i] for f in fonts])
print("MM Hinting")
glyphs = psautohint.autohintmm(info, glyphs, True)
|
<commit_before>from psautohint import autohint
from psautohint import psautohint
d = "tests/data/source-code-pro"
mm = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold")
gg = []
ii = None
for m in mm:
f = autohint.openOpenTypeFile("%s/%s/font.otf" % (d, m), "font.otf", None)
g = f.convertToBez("A", False)
gg.append(g[0])
if ii is None:
ii = f.getFontInfo(f.getPSName(), "%s/%s/font.otf" % (d, m), False, False, [], [])
ii = ii.getFontInfo()
gg = psautohint.autohint(ii, gg, True)
gg = psautohint.autohintmm(ii, [gg], True)
<commit_msg>Rewrite the test script to hint all glyphs
Which reveals that no MM-compatible hinting is really done :(<commit_after>from psautohint import autohint
from psautohint import psautohint
baseDir = "tests/data/source-code-pro"
masters = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold")
glyphList = None
fonts = []
for master in masters:
print("Hinting %s" % master)
path = "%s/%s/font.otf" % (baseDir, master)
font = autohint.openOpenTypeFile(path, "font.otf", None)
names = font.getGlyphList()
info = font.getFontInfo(font.getPSName(), path, False, False, [], [])
info = info.getFontInfo()
if glyphList is None:
glyphList = names
else:
assert glyphList == names
glyphs = []
for name in names:
glyph = font.convertToBez(name, False)
glyphs.append(glyph[0])
fonts.append(psautohint.autohint(info, glyphs, False, False, False))
glyphs = []
for i in range(len(glyphList)):
glyphs.append([f[i] for f in fonts])
print("MM Hinting")
glyphs = psautohint.autohintmm(info, glyphs, True)
|
cc48f8c744c3e8afebdb0c832412b673fef4c727
|
test/functions/dsmm_test.py
|
test/functions/dsmm_test.py
|
import torch
import gpytorch
from torch.autograd import Variable
def test_forward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 3))
res = gpytorch.dsmm(Variable(sparse), dense)
actual = torch.mm(Variable(sparse.to_dense()), dense)
assert(torch.norm(res.data - actual.data) < 1e-7)
def test_backward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 4), requires_grad=True)
dense_copy = Variable(dense.data.clone(), requires_grad=True)
grad_output = torch.randn(2, 4)
res = gpytorch.dsmm(Variable(sparse), dense)
res.backward(grad_output)
actual = torch.mm(Variable(sparse.to_dense()), dense_copy)
actual.backward(grad_output)
assert(torch.norm(dense.grad.data - dense_copy.grad.data) < 1e-7)
|
import torch
import gpytorch
from torch.autograd import Variable
def test_forward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 3))
res = gpytorch.dsmm(Variable(sparse), dense)
actual = torch.mm(Variable(sparse.to_dense()), dense)
assert(torch.norm(res.data - actual.data) < 1e-5)
def test_backward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 4), requires_grad=True)
dense_copy = Variable(dense.data.clone(), requires_grad=True)
grad_output = torch.randn(2, 4)
res = gpytorch.dsmm(Variable(sparse), dense)
res.backward(grad_output)
actual = torch.mm(Variable(sparse.to_dense()), dense_copy)
actual.backward(grad_output)
assert(torch.norm(dense.grad.data - dense_copy.grad.data) < 1e-5)
|
Increase DSMM test tolerance to 1e-5 to improve consistency.
|
Increase DSMM test tolerance to 1e-5 to improve consistency.
|
Python
|
mit
|
jrg365/gpytorch,jrg365/gpytorch,jrg365/gpytorch
|
import torch
import gpytorch
from torch.autograd import Variable
def test_forward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 3))
res = gpytorch.dsmm(Variable(sparse), dense)
actual = torch.mm(Variable(sparse.to_dense()), dense)
assert(torch.norm(res.data - actual.data) < 1e-7)
def test_backward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 4), requires_grad=True)
dense_copy = Variable(dense.data.clone(), requires_grad=True)
grad_output = torch.randn(2, 4)
res = gpytorch.dsmm(Variable(sparse), dense)
res.backward(grad_output)
actual = torch.mm(Variable(sparse.to_dense()), dense_copy)
actual.backward(grad_output)
assert(torch.norm(dense.grad.data - dense_copy.grad.data) < 1e-7)
Increase DSMM test tolerance to 1e-5 to improve consistency.
|
import torch
import gpytorch
from torch.autograd import Variable
def test_forward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 3))
res = gpytorch.dsmm(Variable(sparse), dense)
actual = torch.mm(Variable(sparse.to_dense()), dense)
assert(torch.norm(res.data - actual.data) < 1e-5)
def test_backward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 4), requires_grad=True)
dense_copy = Variable(dense.data.clone(), requires_grad=True)
grad_output = torch.randn(2, 4)
res = gpytorch.dsmm(Variable(sparse), dense)
res.backward(grad_output)
actual = torch.mm(Variable(sparse.to_dense()), dense_copy)
actual.backward(grad_output)
assert(torch.norm(dense.grad.data - dense_copy.grad.data) < 1e-5)
|
<commit_before>import torch
import gpytorch
from torch.autograd import Variable
def test_forward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 3))
res = gpytorch.dsmm(Variable(sparse), dense)
actual = torch.mm(Variable(sparse.to_dense()), dense)
assert(torch.norm(res.data - actual.data) < 1e-7)
def test_backward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 4), requires_grad=True)
dense_copy = Variable(dense.data.clone(), requires_grad=True)
grad_output = torch.randn(2, 4)
res = gpytorch.dsmm(Variable(sparse), dense)
res.backward(grad_output)
actual = torch.mm(Variable(sparse.to_dense()), dense_copy)
actual.backward(grad_output)
assert(torch.norm(dense.grad.data - dense_copy.grad.data) < 1e-7)
<commit_msg>Increase DSMM test tolerance to 1e-5 to improve consistency.<commit_after>
|
import torch
import gpytorch
from torch.autograd import Variable
def test_forward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 3))
res = gpytorch.dsmm(Variable(sparse), dense)
actual = torch.mm(Variable(sparse.to_dense()), dense)
assert(torch.norm(res.data - actual.data) < 1e-5)
def test_backward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 4), requires_grad=True)
dense_copy = Variable(dense.data.clone(), requires_grad=True)
grad_output = torch.randn(2, 4)
res = gpytorch.dsmm(Variable(sparse), dense)
res.backward(grad_output)
actual = torch.mm(Variable(sparse.to_dense()), dense_copy)
actual.backward(grad_output)
assert(torch.norm(dense.grad.data - dense_copy.grad.data) < 1e-5)
|
import torch
import gpytorch
from torch.autograd import Variable
def test_forward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 3))
res = gpytorch.dsmm(Variable(sparse), dense)
actual = torch.mm(Variable(sparse.to_dense()), dense)
assert(torch.norm(res.data - actual.data) < 1e-7)
def test_backward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 4), requires_grad=True)
dense_copy = Variable(dense.data.clone(), requires_grad=True)
grad_output = torch.randn(2, 4)
res = gpytorch.dsmm(Variable(sparse), dense)
res.backward(grad_output)
actual = torch.mm(Variable(sparse.to_dense()), dense_copy)
actual.backward(grad_output)
assert(torch.norm(dense.grad.data - dense_copy.grad.data) < 1e-7)
Increase DSMM test tolerance to 1e-5 to improve consistency.import torch
import gpytorch
from torch.autograd import Variable
def test_forward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 3))
res = gpytorch.dsmm(Variable(sparse), dense)
actual = torch.mm(Variable(sparse.to_dense()), dense)
assert(torch.norm(res.data - actual.data) < 1e-5)
def test_backward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 4), requires_grad=True)
dense_copy = Variable(dense.data.clone(), requires_grad=True)
grad_output = torch.randn(2, 4)
res = gpytorch.dsmm(Variable(sparse), dense)
res.backward(grad_output)
actual = torch.mm(Variable(sparse.to_dense()), dense_copy)
actual.backward(grad_output)
assert(torch.norm(dense.grad.data - dense_copy.grad.data) < 1e-5)
|
<commit_before>import torch
import gpytorch
from torch.autograd import Variable
def test_forward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 3))
res = gpytorch.dsmm(Variable(sparse), dense)
actual = torch.mm(Variable(sparse.to_dense()), dense)
assert(torch.norm(res.data - actual.data) < 1e-7)
def test_backward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 4), requires_grad=True)
dense_copy = Variable(dense.data.clone(), requires_grad=True)
grad_output = torch.randn(2, 4)
res = gpytorch.dsmm(Variable(sparse), dense)
res.backward(grad_output)
actual = torch.mm(Variable(sparse.to_dense()), dense_copy)
actual.backward(grad_output)
assert(torch.norm(dense.grad.data - dense_copy.grad.data) < 1e-7)
<commit_msg>Increase DSMM test tolerance to 1e-5 to improve consistency.<commit_after>import torch
import gpytorch
from torch.autograd import Variable
def test_forward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 3))
res = gpytorch.dsmm(Variable(sparse), dense)
actual = torch.mm(Variable(sparse.to_dense()), dense)
assert(torch.norm(res.data - actual.data) < 1e-5)
def test_backward():
i = torch.LongTensor([[0, 1, 1],
[2, 0, 2]])
v = torch.FloatTensor([3, 4, 5])
sparse = torch.sparse.FloatTensor(i, v, torch.Size([2, 3]))
dense = Variable(torch.randn(3, 4), requires_grad=True)
dense_copy = Variable(dense.data.clone(), requires_grad=True)
grad_output = torch.randn(2, 4)
res = gpytorch.dsmm(Variable(sparse), dense)
res.backward(grad_output)
actual = torch.mm(Variable(sparse.to_dense()), dense_copy)
actual.backward(grad_output)
assert(torch.norm(dense.grad.data - dense_copy.grad.data) < 1e-5)
|
93623d3bc8336073b65f586e2d1573831c492084
|
iatidataquality/__init__.py
|
iatidataquality/__init__.py
|
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3.0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__.split('.')[0])
app.config.from_pyfile('../config.py')
db = SQLAlchemy(app)
import api
import routes
import publishers
import publisher_conditions
import tests
import organisations
import organisations_feedback
import registry
import packages
import indicators
import aggregationtypes
|
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3.0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__.split('.')[0])
app.config.from_pyfile('../config.py')
db = SQLAlchemy(app)
import api
import routes
import publishers
import publisher_conditions
import tests
import organisations
import organisations_feedback
import registry
import packages
import indicators
import aggregationtypes
import survey
|
Add survey controller to routes
|
Add survey controller to routes
|
Python
|
agpl-3.0
|
pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality
|
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3.0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__.split('.')[0])
app.config.from_pyfile('../config.py')
db = SQLAlchemy(app)
import api
import routes
import publishers
import publisher_conditions
import tests
import organisations
import organisations_feedback
import registry
import packages
import indicators
import aggregationtypes
Add survey controller to routes
|
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3.0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__.split('.')[0])
app.config.from_pyfile('../config.py')
db = SQLAlchemy(app)
import api
import routes
import publishers
import publisher_conditions
import tests
import organisations
import organisations_feedback
import registry
import packages
import indicators
import aggregationtypes
import survey
|
<commit_before>
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3.0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__.split('.')[0])
app.config.from_pyfile('../config.py')
db = SQLAlchemy(app)
import api
import routes
import publishers
import publisher_conditions
import tests
import organisations
import organisations_feedback
import registry
import packages
import indicators
import aggregationtypes
<commit_msg>Add survey controller to routes<commit_after>
|
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3.0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__.split('.')[0])
app.config.from_pyfile('../config.py')
db = SQLAlchemy(app)
import api
import routes
import publishers
import publisher_conditions
import tests
import organisations
import organisations_feedback
import registry
import packages
import indicators
import aggregationtypes
import survey
|
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3.0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__.split('.')[0])
app.config.from_pyfile('../config.py')
db = SQLAlchemy(app)
import api
import routes
import publishers
import publisher_conditions
import tests
import organisations
import organisations_feedback
import registry
import packages
import indicators
import aggregationtypes
Add survey controller to routes
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3.0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__.split('.')[0])
app.config.from_pyfile('../config.py')
db = SQLAlchemy(app)
import api
import routes
import publishers
import publisher_conditions
import tests
import organisations
import organisations_feedback
import registry
import packages
import indicators
import aggregationtypes
import survey
|
<commit_before>
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3.0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__.split('.')[0])
app.config.from_pyfile('../config.py')
db = SQLAlchemy(app)
import api
import routes
import publishers
import publisher_conditions
import tests
import organisations
import organisations_feedback
import registry
import packages
import indicators
import aggregationtypes
<commit_msg>Add survey controller to routes<commit_after>
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3.0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__.split('.')[0])
app.config.from_pyfile('../config.py')
db = SQLAlchemy(app)
import api
import routes
import publishers
import publisher_conditions
import tests
import organisations
import organisations_feedback
import registry
import packages
import indicators
import aggregationtypes
import survey
|
b90f01bb8e10751ccfa51872dc32054b5be31d1b
|
vishwin_http/__init__.py
|
vishwin_http/__init__.py
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from flask import Flask
from werkzeug.contrib.cache import FileSystemCache
import pkg_resources
app=Flask(__name__)
#app.config.from_object('config')
cache=FileSystemCache(pkg_resources.resource_filename('vishwin_http', 'cache'), default_timeout=60 * 60) # one hour timeout
import vishwin_http.views
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from flask import Flask
from werkzeug.contrib.cache import MemcachedCache
import pkg_resources
app=Flask(__name__)
app.config.from_object('config')
# set up a memcached Werkzeug cache, prefixing each key, with default timeout of one hour
cache=MemcachedCache(servers=app.config['MEMCACHED_SERVERS'], key_prefix=app.config['MEMCACHED_KEYPREFIX'], default_timeout=60 * 60)
import vishwin_http.views
|
Switch to memcached cache backend
|
Switch to memcached cache backend
- Reinstate config file
- Read server locations and key prefix from config
|
Python
|
mpl-2.0
|
vishwin/vishwin.info-http,vishwin/vishwin.info-http,vishwin/vishwin.info-http
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from flask import Flask
from werkzeug.contrib.cache import FileSystemCache
import pkg_resources
app=Flask(__name__)
#app.config.from_object('config')
cache=FileSystemCache(pkg_resources.resource_filename('vishwin_http', 'cache'), default_timeout=60 * 60) # one hour timeout
import vishwin_http.views
Switch to memcached cache backend
- Reinstate config file
- Read server locations and key prefix from config
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from flask import Flask
from werkzeug.contrib.cache import MemcachedCache
import pkg_resources
app=Flask(__name__)
app.config.from_object('config')
# set up a memcached Werkzeug cache, prefixing each key, with default timeout of one hour
cache=MemcachedCache(servers=app.config['MEMCACHED_SERVERS'], key_prefix=app.config['MEMCACHED_KEYPREFIX'], default_timeout=60 * 60)
import vishwin_http.views
|
<commit_before># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from flask import Flask
from werkzeug.contrib.cache import FileSystemCache
import pkg_resources
app=Flask(__name__)
#app.config.from_object('config')
cache=FileSystemCache(pkg_resources.resource_filename('vishwin_http', 'cache'), default_timeout=60 * 60) # one hour timeout
import vishwin_http.views
<commit_msg>Switch to memcached cache backend
- Reinstate config file
- Read server locations and key prefix from config<commit_after>
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from flask import Flask
from werkzeug.contrib.cache import MemcachedCache
import pkg_resources
app=Flask(__name__)
app.config.from_object('config')
# set up a memcached Werkzeug cache, prefixing each key, with default timeout of one hour
cache=MemcachedCache(servers=app.config['MEMCACHED_SERVERS'], key_prefix=app.config['MEMCACHED_KEYPREFIX'], default_timeout=60 * 60)
import vishwin_http.views
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from flask import Flask
from werkzeug.contrib.cache import FileSystemCache
import pkg_resources
app=Flask(__name__)
#app.config.from_object('config')
cache=FileSystemCache(pkg_resources.resource_filename('vishwin_http', 'cache'), default_timeout=60 * 60) # one hour timeout
import vishwin_http.views
Switch to memcached cache backend
- Reinstate config file
- Read server locations and key prefix from config# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from flask import Flask
from werkzeug.contrib.cache import MemcachedCache
import pkg_resources
app=Flask(__name__)
app.config.from_object('config')
# set up a memcached Werkzeug cache, prefixing each key, with default timeout of one hour
cache=MemcachedCache(servers=app.config['MEMCACHED_SERVERS'], key_prefix=app.config['MEMCACHED_KEYPREFIX'], default_timeout=60 * 60)
import vishwin_http.views
|
<commit_before># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from flask import Flask
from werkzeug.contrib.cache import FileSystemCache
import pkg_resources
app=Flask(__name__)
#app.config.from_object('config')
cache=FileSystemCache(pkg_resources.resource_filename('vishwin_http', 'cache'), default_timeout=60 * 60) # one hour timeout
import vishwin_http.views
<commit_msg>Switch to memcached cache backend
- Reinstate config file
- Read server locations and key prefix from config<commit_after># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from flask import Flask
from werkzeug.contrib.cache import MemcachedCache
import pkg_resources
app=Flask(__name__)
app.config.from_object('config')
# set up a memcached Werkzeug cache, prefixing each key, with default timeout of one hour
cache=MemcachedCache(servers=app.config['MEMCACHED_SERVERS'], key_prefix=app.config['MEMCACHED_KEYPREFIX'], default_timeout=60 * 60)
import vishwin_http.views
|
3eb37589ab7a2e58922a69f42bbc1ec443df44ed
|
addons/purchase/models/stock_config_settings.py
|
addons/purchase/models/stock_config_settings.py
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class StockConfigSettings(models.TransientModel):
_inherit = 'stock.config.settings'
po_lead = fields.Float(related='company_id.po_lead', default=lambda self: self.env.user.company_id.po_lead)
use_po_lead = fields.Boolean(
string="Security Lead Time for Purchase",
oldname='default_new_po_lead',
help="Margin of error for vendor lead times. When the system generates Purchase Orders for reordering products,they will be scheduled that many days earlier to cope with unexpected vendor delays.")
@api.onchange('use_po_lead')
def _onchange_use_po_lead(self):
if not self.use_po_lead:
self.po_lead = 0.0
def get_default_fields(self, fields):
return dict(
use_po_lead=self.env['ir.config_parameter'].sudo().get_param('purchase.use_po_lead')
)
def set_fields(self):
self.env['ir.config_parameter'].sudo().set_param('purchase.use_po_lead', self.use_po_lead)
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class StockConfigSettings(models.TransientModel):
_inherit = 'stock.config.settings'
po_lead = fields.Float(related='company_id.po_lead')
use_po_lead = fields.Boolean(
string="Security Lead Time for Purchase",
oldname='default_new_po_lead',
help="Margin of error for vendor lead times. When the system generates Purchase Orders for reordering products,they will be scheduled that many days earlier to cope with unexpected vendor delays.")
@api.onchange('use_po_lead')
def _onchange_use_po_lead(self):
if not self.use_po_lead:
self.po_lead = 0.0
def get_default_fields(self, fields):
return dict(
use_po_lead=self.env['ir.config_parameter'].sudo().get_param('purchase.use_po_lead')
)
def set_fields(self):
self.env['ir.config_parameter'].sudo().set_param('purchase.use_po_lead', self.use_po_lead)
|
Remove useless default value for po_lead
|
[IMP] purchase: Remove useless default value for po_lead
|
Python
|
agpl-3.0
|
ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class StockConfigSettings(models.TransientModel):
_inherit = 'stock.config.settings'
po_lead = fields.Float(related='company_id.po_lead', default=lambda self: self.env.user.company_id.po_lead)
use_po_lead = fields.Boolean(
string="Security Lead Time for Purchase",
oldname='default_new_po_lead',
help="Margin of error for vendor lead times. When the system generates Purchase Orders for reordering products,they will be scheduled that many days earlier to cope with unexpected vendor delays.")
@api.onchange('use_po_lead')
def _onchange_use_po_lead(self):
if not self.use_po_lead:
self.po_lead = 0.0
def get_default_fields(self, fields):
return dict(
use_po_lead=self.env['ir.config_parameter'].sudo().get_param('purchase.use_po_lead')
)
def set_fields(self):
self.env['ir.config_parameter'].sudo().set_param('purchase.use_po_lead', self.use_po_lead)
[IMP] purchase: Remove useless default value for po_lead
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class StockConfigSettings(models.TransientModel):
_inherit = 'stock.config.settings'
po_lead = fields.Float(related='company_id.po_lead')
use_po_lead = fields.Boolean(
string="Security Lead Time for Purchase",
oldname='default_new_po_lead',
help="Margin of error for vendor lead times. When the system generates Purchase Orders for reordering products,they will be scheduled that many days earlier to cope with unexpected vendor delays.")
@api.onchange('use_po_lead')
def _onchange_use_po_lead(self):
if not self.use_po_lead:
self.po_lead = 0.0
def get_default_fields(self, fields):
return dict(
use_po_lead=self.env['ir.config_parameter'].sudo().get_param('purchase.use_po_lead')
)
def set_fields(self):
self.env['ir.config_parameter'].sudo().set_param('purchase.use_po_lead', self.use_po_lead)
|
<commit_before># -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class StockConfigSettings(models.TransientModel):
_inherit = 'stock.config.settings'
po_lead = fields.Float(related='company_id.po_lead', default=lambda self: self.env.user.company_id.po_lead)
use_po_lead = fields.Boolean(
string="Security Lead Time for Purchase",
oldname='default_new_po_lead',
help="Margin of error for vendor lead times. When the system generates Purchase Orders for reordering products,they will be scheduled that many days earlier to cope with unexpected vendor delays.")
@api.onchange('use_po_lead')
def _onchange_use_po_lead(self):
if not self.use_po_lead:
self.po_lead = 0.0
def get_default_fields(self, fields):
return dict(
use_po_lead=self.env['ir.config_parameter'].sudo().get_param('purchase.use_po_lead')
)
def set_fields(self):
self.env['ir.config_parameter'].sudo().set_param('purchase.use_po_lead', self.use_po_lead)
<commit_msg>[IMP] purchase: Remove useless default value for po_lead<commit_after>
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class StockConfigSettings(models.TransientModel):
_inherit = 'stock.config.settings'
po_lead = fields.Float(related='company_id.po_lead')
use_po_lead = fields.Boolean(
string="Security Lead Time for Purchase",
oldname='default_new_po_lead',
help="Margin of error for vendor lead times. When the system generates Purchase Orders for reordering products,they will be scheduled that many days earlier to cope with unexpected vendor delays.")
@api.onchange('use_po_lead')
def _onchange_use_po_lead(self):
if not self.use_po_lead:
self.po_lead = 0.0
def get_default_fields(self, fields):
return dict(
use_po_lead=self.env['ir.config_parameter'].sudo().get_param('purchase.use_po_lead')
)
def set_fields(self):
self.env['ir.config_parameter'].sudo().set_param('purchase.use_po_lead', self.use_po_lead)
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class StockConfigSettings(models.TransientModel):
_inherit = 'stock.config.settings'
po_lead = fields.Float(related='company_id.po_lead', default=lambda self: self.env.user.company_id.po_lead)
use_po_lead = fields.Boolean(
string="Security Lead Time for Purchase",
oldname='default_new_po_lead',
help="Margin of error for vendor lead times. When the system generates Purchase Orders for reordering products,they will be scheduled that many days earlier to cope with unexpected vendor delays.")
@api.onchange('use_po_lead')
def _onchange_use_po_lead(self):
if not self.use_po_lead:
self.po_lead = 0.0
def get_default_fields(self, fields):
return dict(
use_po_lead=self.env['ir.config_parameter'].sudo().get_param('purchase.use_po_lead')
)
def set_fields(self):
self.env['ir.config_parameter'].sudo().set_param('purchase.use_po_lead', self.use_po_lead)
[IMP] purchase: Remove useless default value for po_lead# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class StockConfigSettings(models.TransientModel):
_inherit = 'stock.config.settings'
po_lead = fields.Float(related='company_id.po_lead')
use_po_lead = fields.Boolean(
string="Security Lead Time for Purchase",
oldname='default_new_po_lead',
help="Margin of error for vendor lead times. When the system generates Purchase Orders for reordering products,they will be scheduled that many days earlier to cope with unexpected vendor delays.")
@api.onchange('use_po_lead')
def _onchange_use_po_lead(self):
if not self.use_po_lead:
self.po_lead = 0.0
def get_default_fields(self, fields):
return dict(
use_po_lead=self.env['ir.config_parameter'].sudo().get_param('purchase.use_po_lead')
)
def set_fields(self):
self.env['ir.config_parameter'].sudo().set_param('purchase.use_po_lead', self.use_po_lead)
|
<commit_before># -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class StockConfigSettings(models.TransientModel):
_inherit = 'stock.config.settings'
po_lead = fields.Float(related='company_id.po_lead', default=lambda self: self.env.user.company_id.po_lead)
use_po_lead = fields.Boolean(
string="Security Lead Time for Purchase",
oldname='default_new_po_lead',
help="Margin of error for vendor lead times. When the system generates Purchase Orders for reordering products,they will be scheduled that many days earlier to cope with unexpected vendor delays.")
@api.onchange('use_po_lead')
def _onchange_use_po_lead(self):
if not self.use_po_lead:
self.po_lead = 0.0
def get_default_fields(self, fields):
return dict(
use_po_lead=self.env['ir.config_parameter'].sudo().get_param('purchase.use_po_lead')
)
def set_fields(self):
self.env['ir.config_parameter'].sudo().set_param('purchase.use_po_lead', self.use_po_lead)
<commit_msg>[IMP] purchase: Remove useless default value for po_lead<commit_after># -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class StockConfigSettings(models.TransientModel):
_inherit = 'stock.config.settings'
po_lead = fields.Float(related='company_id.po_lead')
use_po_lead = fields.Boolean(
string="Security Lead Time for Purchase",
oldname='default_new_po_lead',
help="Margin of error for vendor lead times. When the system generates Purchase Orders for reordering products,they will be scheduled that many days earlier to cope with unexpected vendor delays.")
@api.onchange('use_po_lead')
def _onchange_use_po_lead(self):
if not self.use_po_lead:
self.po_lead = 0.0
def get_default_fields(self, fields):
return dict(
use_po_lead=self.env['ir.config_parameter'].sudo().get_param('purchase.use_po_lead')
)
def set_fields(self):
self.env['ir.config_parameter'].sudo().set_param('purchase.use_po_lead', self.use_po_lead)
|
a2ffa3d02ef4b7cd345602b475f86ac172bd7c6c
|
support/jenkins/buildAllModuleCombination.py
|
support/jenkins/buildAllModuleCombination.py
|
import os
from subprocess import call
from itertools import product, repeat
# To be called from the main OpenSpace
modules = os.listdir("modules")
modules.remove("base")
# Get 2**len(modules) combinatorical combinations of ON/OFF
settings = []
for args in product(*repeat(("ON", "OFF"), len(modules))):
settings.append(args)
# Create all commands
cmds = []
for s in settings:
cmd = ["cmake", "-DGHOUL_USE_DEVIL=NO", "-DOPENSPACE_MODULE_BASE=ON"]
for m,s in zip(modules, s):
cmd.append("-DOPENSPACE_MODULE_" + m.upper() + "=" + s)
cmd.append("..")
cmds.append(cmd)
# Build cmake and compile
for c in cmds:
print "CMake:" , cmd
call(["rm", "-rf", "build", "bin"])
call(["mkdir", "build"])
call(["cd", "build"])
call(cmd)
call(["make", "-j4"])
call(["cd", ".."])
|
import os
from subprocess import call
from itertools import product, repeat
import shutil
# To be called from the main OpenSpace
modules = os.listdir("modules")
modules.remove("base")
# Get 2**len(modules) combinatorical combinations of ON/OFF
settings = []
for args in product(*repeat(("ON", "OFF"), len(modules))):
settings.append(args)
# Create all commands
cmds = []
for s in settings:
cmd = ["cmake", "-DGHOUL_USE_DEVIL=NO", "-DOPENSPACE_MODULE_BASE=ON"]
for m,s in zip(modules, s):
cmd.append("-DOPENSPACE_MODULE_" + m.upper() + "=" + s)
cmd.append("..")
cmds.append(cmd)
# Build cmake and compile
for c in cmds:
print "CMake:" , cmd
shutil.rmtree("build")
shutil.rmtree("bin")
os.makedirs("build")
os.chdir("build")
call(cmd)
call(["make", "-j4"])
os.chdir("..")
|
Use python internal functions for generating, removing and changing directories
|
Use python internal functions for generating, removing and changing directories
|
Python
|
mit
|
OpenSpace/OpenSpace,OpenSpace/OpenSpace,OpenSpace/OpenSpace,OpenSpace/OpenSpace
|
import os
from subprocess import call
from itertools import product, repeat
# To be called from the main OpenSpace
modules = os.listdir("modules")
modules.remove("base")
# Get 2**len(modules) combinatorical combinations of ON/OFF
settings = []
for args in product(*repeat(("ON", "OFF"), len(modules))):
settings.append(args)
# Create all commands
cmds = []
for s in settings:
cmd = ["cmake", "-DGHOUL_USE_DEVIL=NO", "-DOPENSPACE_MODULE_BASE=ON"]
for m,s in zip(modules, s):
cmd.append("-DOPENSPACE_MODULE_" + m.upper() + "=" + s)
cmd.append("..")
cmds.append(cmd)
# Build cmake and compile
for c in cmds:
print "CMake:" , cmd
call(["rm", "-rf", "build", "bin"])
call(["mkdir", "build"])
call(["cd", "build"])
call(cmd)
call(["make", "-j4"])
call(["cd", ".."])
Use python internal functions for generating, removing and changing directories
|
import os
from subprocess import call
from itertools import product, repeat
import shutil
# To be called from the main OpenSpace
modules = os.listdir("modules")
modules.remove("base")
# Get 2**len(modules) combinatorical combinations of ON/OFF
settings = []
for args in product(*repeat(("ON", "OFF"), len(modules))):
settings.append(args)
# Create all commands
cmds = []
for s in settings:
cmd = ["cmake", "-DGHOUL_USE_DEVIL=NO", "-DOPENSPACE_MODULE_BASE=ON"]
for m,s in zip(modules, s):
cmd.append("-DOPENSPACE_MODULE_" + m.upper() + "=" + s)
cmd.append("..")
cmds.append(cmd)
# Build cmake and compile
for c in cmds:
print "CMake:" , cmd
shutil.rmtree("build")
shutil.rmtree("bin")
os.makedirs("build")
os.chdir("build")
call(cmd)
call(["make", "-j4"])
os.chdir("..")
|
<commit_before>import os
from subprocess import call
from itertools import product, repeat
# To be called from the main OpenSpace
modules = os.listdir("modules")
modules.remove("base")
# Get 2**len(modules) combinatorical combinations of ON/OFF
settings = []
for args in product(*repeat(("ON", "OFF"), len(modules))):
settings.append(args)
# Create all commands
cmds = []
for s in settings:
cmd = ["cmake", "-DGHOUL_USE_DEVIL=NO", "-DOPENSPACE_MODULE_BASE=ON"]
for m,s in zip(modules, s):
cmd.append("-DOPENSPACE_MODULE_" + m.upper() + "=" + s)
cmd.append("..")
cmds.append(cmd)
# Build cmake and compile
for c in cmds:
print "CMake:" , cmd
call(["rm", "-rf", "build", "bin"])
call(["mkdir", "build"])
call(["cd", "build"])
call(cmd)
call(["make", "-j4"])
call(["cd", ".."])
<commit_msg>Use python internal functions for generating, removing and changing directories<commit_after>
|
import os
from subprocess import call
from itertools import product, repeat
import shutil
# To be called from the main OpenSpace
modules = os.listdir("modules")
modules.remove("base")
# Get 2**len(modules) combinatorical combinations of ON/OFF
settings = []
for args in product(*repeat(("ON", "OFF"), len(modules))):
settings.append(args)
# Create all commands
cmds = []
for s in settings:
cmd = ["cmake", "-DGHOUL_USE_DEVIL=NO", "-DOPENSPACE_MODULE_BASE=ON"]
for m,s in zip(modules, s):
cmd.append("-DOPENSPACE_MODULE_" + m.upper() + "=" + s)
cmd.append("..")
cmds.append(cmd)
# Build cmake and compile
for c in cmds:
print "CMake:" , cmd
shutil.rmtree("build")
shutil.rmtree("bin")
os.makedirs("build")
os.chdir("build")
call(cmd)
call(["make", "-j4"])
os.chdir("..")
|
import os
from subprocess import call
from itertools import product, repeat
# To be called from the main OpenSpace
modules = os.listdir("modules")
modules.remove("base")
# Get 2**len(modules) combinatorical combinations of ON/OFF
settings = []
for args in product(*repeat(("ON", "OFF"), len(modules))):
settings.append(args)
# Create all commands
cmds = []
for s in settings:
cmd = ["cmake", "-DGHOUL_USE_DEVIL=NO", "-DOPENSPACE_MODULE_BASE=ON"]
for m,s in zip(modules, s):
cmd.append("-DOPENSPACE_MODULE_" + m.upper() + "=" + s)
cmd.append("..")
cmds.append(cmd)
# Build cmake and compile
for c in cmds:
print "CMake:" , cmd
call(["rm", "-rf", "build", "bin"])
call(["mkdir", "build"])
call(["cd", "build"])
call(cmd)
call(["make", "-j4"])
call(["cd", ".."])
Use python internal functions for generating, removing and changing directoriesimport os
from subprocess import call
from itertools import product, repeat
import shutil
# To be called from the main OpenSpace
modules = os.listdir("modules")
modules.remove("base")
# Get 2**len(modules) combinatorical combinations of ON/OFF
settings = []
for args in product(*repeat(("ON", "OFF"), len(modules))):
settings.append(args)
# Create all commands
cmds = []
for s in settings:
cmd = ["cmake", "-DGHOUL_USE_DEVIL=NO", "-DOPENSPACE_MODULE_BASE=ON"]
for m,s in zip(modules, s):
cmd.append("-DOPENSPACE_MODULE_" + m.upper() + "=" + s)
cmd.append("..")
cmds.append(cmd)
# Build cmake and compile
for c in cmds:
print "CMake:" , cmd
shutil.rmtree("build")
shutil.rmtree("bin")
os.makedirs("build")
os.chdir("build")
call(cmd)
call(["make", "-j4"])
os.chdir("..")
|
<commit_before>import os
from subprocess import call
from itertools import product, repeat
# To be called from the main OpenSpace
modules = os.listdir("modules")
modules.remove("base")
# Get 2**len(modules) combinatorical combinations of ON/OFF
settings = []
for args in product(*repeat(("ON", "OFF"), len(modules))):
settings.append(args)
# Create all commands
cmds = []
for s in settings:
cmd = ["cmake", "-DGHOUL_USE_DEVIL=NO", "-DOPENSPACE_MODULE_BASE=ON"]
for m,s in zip(modules, s):
cmd.append("-DOPENSPACE_MODULE_" + m.upper() + "=" + s)
cmd.append("..")
cmds.append(cmd)
# Build cmake and compile
for c in cmds:
print "CMake:" , cmd
call(["rm", "-rf", "build", "bin"])
call(["mkdir", "build"])
call(["cd", "build"])
call(cmd)
call(["make", "-j4"])
call(["cd", ".."])
<commit_msg>Use python internal functions for generating, removing and changing directories<commit_after>import os
from subprocess import call
from itertools import product, repeat
import shutil
# To be called from the main OpenSpace
modules = os.listdir("modules")
modules.remove("base")
# Get 2**len(modules) combinatorical combinations of ON/OFF
settings = []
for args in product(*repeat(("ON", "OFF"), len(modules))):
settings.append(args)
# Create all commands
cmds = []
for s in settings:
cmd = ["cmake", "-DGHOUL_USE_DEVIL=NO", "-DOPENSPACE_MODULE_BASE=ON"]
for m,s in zip(modules, s):
cmd.append("-DOPENSPACE_MODULE_" + m.upper() + "=" + s)
cmd.append("..")
cmds.append(cmd)
# Build cmake and compile
for c in cmds:
print "CMake:" , cmd
shutil.rmtree("build")
shutil.rmtree("bin")
os.makedirs("build")
os.chdir("build")
call(cmd)
call(["make", "-j4"])
os.chdir("..")
|
d8d6647c1710cd0d66119da4e5a604578efb4bc7
|
scikits/talkbox/__init__.py
|
scikits/talkbox/__init__.py
|
__all__ = []
from tools import *
import tools
__all__ += tools.__all__
import linpred
from linpred import *
__all__ += linpred.__all__
from numpy.testing import Tester
test = Tester().test
bench = Tester().bench
|
__all__ = []
from tools import *
import tools
__all__ += tools.__all__
import linpred
from linpred import *
__all__ += linpred.__all__
import version
from numpy.testing import Tester
test = Tester().test
bench = Tester().bench
|
Make version module available in main namespace.
|
Make version module available in main namespace.
|
Python
|
mit
|
cournape/talkbox,cournape/talkbox
|
__all__ = []
from tools import *
import tools
__all__ += tools.__all__
import linpred
from linpred import *
__all__ += linpred.__all__
from numpy.testing import Tester
test = Tester().test
bench = Tester().bench
Make version module available in main namespace.
|
__all__ = []
from tools import *
import tools
__all__ += tools.__all__
import linpred
from linpred import *
__all__ += linpred.__all__
import version
from numpy.testing import Tester
test = Tester().test
bench = Tester().bench
|
<commit_before>__all__ = []
from tools import *
import tools
__all__ += tools.__all__
import linpred
from linpred import *
__all__ += linpred.__all__
from numpy.testing import Tester
test = Tester().test
bench = Tester().bench
<commit_msg>Make version module available in main namespace.<commit_after>
|
__all__ = []
from tools import *
import tools
__all__ += tools.__all__
import linpred
from linpred import *
__all__ += linpred.__all__
import version
from numpy.testing import Tester
test = Tester().test
bench = Tester().bench
|
__all__ = []
from tools import *
import tools
__all__ += tools.__all__
import linpred
from linpred import *
__all__ += linpred.__all__
from numpy.testing import Tester
test = Tester().test
bench = Tester().bench
Make version module available in main namespace.__all__ = []
from tools import *
import tools
__all__ += tools.__all__
import linpred
from linpred import *
__all__ += linpred.__all__
import version
from numpy.testing import Tester
test = Tester().test
bench = Tester().bench
|
<commit_before>__all__ = []
from tools import *
import tools
__all__ += tools.__all__
import linpred
from linpred import *
__all__ += linpred.__all__
from numpy.testing import Tester
test = Tester().test
bench = Tester().bench
<commit_msg>Make version module available in main namespace.<commit_after>__all__ = []
from tools import *
import tools
__all__ += tools.__all__
import linpred
from linpred import *
__all__ += linpred.__all__
import version
from numpy.testing import Tester
test = Tester().test
bench = Tester().bench
|
31ee84042a12fc65be539de896daf755b342d9a0
|
junction/proposals/permissions.py
|
junction/proposals/permissions.py
|
# -*- coding: utf-8 -*-
from django.core.exceptions import PermissionDenied
from junction.conferences.models import ConferenceProposalReviewer
from .models import ProposalSectionReviewer
def is_proposal_author(user, proposal):
return user.is_authenticated() and proposal.author == user
def is_proposal_reviewer(user, conference):
is_reviewer = ConferenceProposalReviewer.objects.filter(
reviewer=user, conference=conference, active=True).exists()
return user.is_authenticated() and is_reviewer
def is_proposal_section_reviewer(user, conference, proposal):
return user.is_authenticated() and ProposalSectionReviewer.objects.filter(
conference_reviewer__reviewer=user,
conference_reviewer__conference=conference,
proposal_section=proposal.proposal_section,
active=True).exists()
def is_proposal_author_or_proposal_reviewer(user, conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_reviewer(user, conference)
def is_proposal_author_or_proposal_section_reviewer(user,
conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_section_reviewer(user, conference, proposal)
def is_proposal_author_or_permisson_denied(user, proposal):
if is_proposal_author(user, proposal):
return True
raise PermissionDenied
|
# -*- coding: utf-8 -*-
from django.core.exceptions import PermissionDenied
from junction.conferences.models import ConferenceProposalReviewer
from .models import ProposalSectionReviewer
def is_proposal_author(user, proposal):
return user.is_authenticated() and proposal.author == user
def is_proposal_reviewer(user, conference):
authenticated = user.is_authenticated()
is_reviewer = ConferenceProposalReviewer.objects.filter(
reviewer=user, conference=conference, active=True).exists()
return authenticated and is_reviewer
def is_proposal_section_reviewer(user, conference, proposal):
return user.is_authenticated() and ProposalSectionReviewer.objects.filter(
conference_reviewer__reviewer=user,
conference_reviewer__conference=conference,
proposal_section=proposal.proposal_section,
active=True).exists()
def is_proposal_author_or_proposal_reviewer(user, conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_reviewer(user, conference)
def is_proposal_author_or_proposal_section_reviewer(user,
conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_section_reviewer(user, conference, proposal)
def is_proposal_author_or_permisson_denied(user, proposal):
if is_proposal_author(user, proposal):
return True
raise PermissionDenied
|
Move check for authentication to top
|
Move check for authentication to top
|
Python
|
mit
|
ChillarAnand/junction,pythonindia/junction,ChillarAnand/junction,ChillarAnand/junction,pythonindia/junction,ChillarAnand/junction,pythonindia/junction,pythonindia/junction
|
# -*- coding: utf-8 -*-
from django.core.exceptions import PermissionDenied
from junction.conferences.models import ConferenceProposalReviewer
from .models import ProposalSectionReviewer
def is_proposal_author(user, proposal):
return user.is_authenticated() and proposal.author == user
def is_proposal_reviewer(user, conference):
is_reviewer = ConferenceProposalReviewer.objects.filter(
reviewer=user, conference=conference, active=True).exists()
return user.is_authenticated() and is_reviewer
def is_proposal_section_reviewer(user, conference, proposal):
return user.is_authenticated() and ProposalSectionReviewer.objects.filter(
conference_reviewer__reviewer=user,
conference_reviewer__conference=conference,
proposal_section=proposal.proposal_section,
active=True).exists()
def is_proposal_author_or_proposal_reviewer(user, conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_reviewer(user, conference)
def is_proposal_author_or_proposal_section_reviewer(user,
conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_section_reviewer(user, conference, proposal)
def is_proposal_author_or_permisson_denied(user, proposal):
if is_proposal_author(user, proposal):
return True
raise PermissionDenied
Move check for authentication to top
|
# -*- coding: utf-8 -*-
from django.core.exceptions import PermissionDenied
from junction.conferences.models import ConferenceProposalReviewer
from .models import ProposalSectionReviewer
def is_proposal_author(user, proposal):
return user.is_authenticated() and proposal.author == user
def is_proposal_reviewer(user, conference):
authenticated = user.is_authenticated()
is_reviewer = ConferenceProposalReviewer.objects.filter(
reviewer=user, conference=conference, active=True).exists()
return authenticated and is_reviewer
def is_proposal_section_reviewer(user, conference, proposal):
return user.is_authenticated() and ProposalSectionReviewer.objects.filter(
conference_reviewer__reviewer=user,
conference_reviewer__conference=conference,
proposal_section=proposal.proposal_section,
active=True).exists()
def is_proposal_author_or_proposal_reviewer(user, conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_reviewer(user, conference)
def is_proposal_author_or_proposal_section_reviewer(user,
conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_section_reviewer(user, conference, proposal)
def is_proposal_author_or_permisson_denied(user, proposal):
if is_proposal_author(user, proposal):
return True
raise PermissionDenied
|
<commit_before># -*- coding: utf-8 -*-
from django.core.exceptions import PermissionDenied
from junction.conferences.models import ConferenceProposalReviewer
from .models import ProposalSectionReviewer
def is_proposal_author(user, proposal):
return user.is_authenticated() and proposal.author == user
def is_proposal_reviewer(user, conference):
is_reviewer = ConferenceProposalReviewer.objects.filter(
reviewer=user, conference=conference, active=True).exists()
return user.is_authenticated() and is_reviewer
def is_proposal_section_reviewer(user, conference, proposal):
return user.is_authenticated() and ProposalSectionReviewer.objects.filter(
conference_reviewer__reviewer=user,
conference_reviewer__conference=conference,
proposal_section=proposal.proposal_section,
active=True).exists()
def is_proposal_author_or_proposal_reviewer(user, conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_reviewer(user, conference)
def is_proposal_author_or_proposal_section_reviewer(user,
conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_section_reviewer(user, conference, proposal)
def is_proposal_author_or_permisson_denied(user, proposal):
if is_proposal_author(user, proposal):
return True
raise PermissionDenied
<commit_msg>Move check for authentication to top<commit_after>
|
# -*- coding: utf-8 -*-
from django.core.exceptions import PermissionDenied
from junction.conferences.models import ConferenceProposalReviewer
from .models import ProposalSectionReviewer
def is_proposal_author(user, proposal):
return user.is_authenticated() and proposal.author == user
def is_proposal_reviewer(user, conference):
authenticated = user.is_authenticated()
is_reviewer = ConferenceProposalReviewer.objects.filter(
reviewer=user, conference=conference, active=True).exists()
return authenticated and is_reviewer
def is_proposal_section_reviewer(user, conference, proposal):
return user.is_authenticated() and ProposalSectionReviewer.objects.filter(
conference_reviewer__reviewer=user,
conference_reviewer__conference=conference,
proposal_section=proposal.proposal_section,
active=True).exists()
def is_proposal_author_or_proposal_reviewer(user, conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_reviewer(user, conference)
def is_proposal_author_or_proposal_section_reviewer(user,
conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_section_reviewer(user, conference, proposal)
def is_proposal_author_or_permisson_denied(user, proposal):
if is_proposal_author(user, proposal):
return True
raise PermissionDenied
|
# -*- coding: utf-8 -*-
from django.core.exceptions import PermissionDenied
from junction.conferences.models import ConferenceProposalReviewer
from .models import ProposalSectionReviewer
def is_proposal_author(user, proposal):
return user.is_authenticated() and proposal.author == user
def is_proposal_reviewer(user, conference):
is_reviewer = ConferenceProposalReviewer.objects.filter(
reviewer=user, conference=conference, active=True).exists()
return user.is_authenticated() and is_reviewer
def is_proposal_section_reviewer(user, conference, proposal):
return user.is_authenticated() and ProposalSectionReviewer.objects.filter(
conference_reviewer__reviewer=user,
conference_reviewer__conference=conference,
proposal_section=proposal.proposal_section,
active=True).exists()
def is_proposal_author_or_proposal_reviewer(user, conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_reviewer(user, conference)
def is_proposal_author_or_proposal_section_reviewer(user,
conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_section_reviewer(user, conference, proposal)
def is_proposal_author_or_permisson_denied(user, proposal):
if is_proposal_author(user, proposal):
return True
raise PermissionDenied
Move check for authentication to top# -*- coding: utf-8 -*-
from django.core.exceptions import PermissionDenied
from junction.conferences.models import ConferenceProposalReviewer
from .models import ProposalSectionReviewer
def is_proposal_author(user, proposal):
return user.is_authenticated() and proposal.author == user
def is_proposal_reviewer(user, conference):
authenticated = user.is_authenticated()
is_reviewer = ConferenceProposalReviewer.objects.filter(
reviewer=user, conference=conference, active=True).exists()
return authenticated and is_reviewer
def is_proposal_section_reviewer(user, conference, proposal):
return user.is_authenticated() and ProposalSectionReviewer.objects.filter(
conference_reviewer__reviewer=user,
conference_reviewer__conference=conference,
proposal_section=proposal.proposal_section,
active=True).exists()
def is_proposal_author_or_proposal_reviewer(user, conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_reviewer(user, conference)
def is_proposal_author_or_proposal_section_reviewer(user,
conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_section_reviewer(user, conference, proposal)
def is_proposal_author_or_permisson_denied(user, proposal):
if is_proposal_author(user, proposal):
return True
raise PermissionDenied
|
<commit_before># -*- coding: utf-8 -*-
from django.core.exceptions import PermissionDenied
from junction.conferences.models import ConferenceProposalReviewer
from .models import ProposalSectionReviewer
def is_proposal_author(user, proposal):
return user.is_authenticated() and proposal.author == user
def is_proposal_reviewer(user, conference):
is_reviewer = ConferenceProposalReviewer.objects.filter(
reviewer=user, conference=conference, active=True).exists()
return user.is_authenticated() and is_reviewer
def is_proposal_section_reviewer(user, conference, proposal):
return user.is_authenticated() and ProposalSectionReviewer.objects.filter(
conference_reviewer__reviewer=user,
conference_reviewer__conference=conference,
proposal_section=proposal.proposal_section,
active=True).exists()
def is_proposal_author_or_proposal_reviewer(user, conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_reviewer(user, conference)
def is_proposal_author_or_proposal_section_reviewer(user,
conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_section_reviewer(user, conference, proposal)
def is_proposal_author_or_permisson_denied(user, proposal):
if is_proposal_author(user, proposal):
return True
raise PermissionDenied
<commit_msg>Move check for authentication to top<commit_after># -*- coding: utf-8 -*-
from django.core.exceptions import PermissionDenied
from junction.conferences.models import ConferenceProposalReviewer
from .models import ProposalSectionReviewer
def is_proposal_author(user, proposal):
return user.is_authenticated() and proposal.author == user
def is_proposal_reviewer(user, conference):
authenticated = user.is_authenticated()
is_reviewer = ConferenceProposalReviewer.objects.filter(
reviewer=user, conference=conference, active=True).exists()
return authenticated and is_reviewer
def is_proposal_section_reviewer(user, conference, proposal):
return user.is_authenticated() and ProposalSectionReviewer.objects.filter(
conference_reviewer__reviewer=user,
conference_reviewer__conference=conference,
proposal_section=proposal.proposal_section,
active=True).exists()
def is_proposal_author_or_proposal_reviewer(user, conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_reviewer(user, conference)
def is_proposal_author_or_proposal_section_reviewer(user,
conference, proposal):
return is_proposal_author(user, proposal) or \
is_proposal_section_reviewer(user, conference, proposal)
def is_proposal_author_or_permisson_denied(user, proposal):
if is_proposal_author(user, proposal):
return True
raise PermissionDenied
|
c67a468d9b02e396c184305dc7b1bbb97982cf7b
|
python/testData/debug/test_multithread.py
|
python/testData/debug/test_multithread.py
|
try:
import thread
except :
import _thread as thread
import threading
def bar(y):
z = 100 + y
print("Z=%d"%z)
t = None
def foo(x):
global t
y = x + 1
print("Y=%d"%y)
t = threading.Thread(target=bar, args=(y,))
t.start()
id = thread.start_new_thread(foo, (1,))
while True:
pass
|
try:
import thread
except :
import _thread as thread
import threading
from time import sleep
def bar(y):
z = 100 + y
print("Z=%d"%z)
t = None
def foo(x):
global t
y = x + 1
print("Y=%d"%y)
t = threading.Thread(target=bar, args=(y,))
t.start()
id = thread.start_new_thread(foo, (1,))
while True:
sleep(1)
|
Fix tests: add sleep to the main thread in order to stop in the child threads on the slow IronPython.
|
Fix tests: add sleep to the main thread in order to stop in the child threads on the slow IronPython.
|
Python
|
apache-2.0
|
FHannes/intellij-community,signed/intellij-community,xfournet/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,hurricup/intellij-community,xfournet/intellij-community,apixandru/intellij-community,da1z/intellij-community,retomerz/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,allotria/intellij-community,signed/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,apixandru/intellij-community,ibinti/intellij-community,ibinti/intellij-community,ibinti/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,retomerz/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,signed/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,signed/intellij-community,da1z/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,asedunov/intellij-community,fitermay/intellij-community,ibinti/intellij-community,FHannes/intellij-community,da1z/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,hurricup/intellij-community,signed/intellij-community,asedunov/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,allotria/intellij-community,da1z/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,FHannes/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,semonte/intellij-community,da1z/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,signed/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,fitermay/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,signed/intellij-community,signed/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,xfournet/intellij-community,apixandru/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,allotria/intellij-community,ibinti/intellij-community,fitermay/intellij-community,hurricup/intellij-community,allotria/intellij-community,FHannes/intellij-community,fitermay/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,FHannes/intellij-community,asedunov/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,asedunov/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,semonte/intellij-community,semonte/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,da1z/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,fitermay/intellij-community,signed/intellij-community,asedunov/intellij-community,xfournet/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,apixandru/intellij-community,da1z/intellij-community,signed/intellij-community,apixandru/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,semonte/intellij-community,ibinti/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,allotria/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,signed/intellij-community,allotria/intellij-community,hurricup/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community
|
try:
import thread
except :
import _thread as thread
import threading
def bar(y):
z = 100 + y
print("Z=%d"%z)
t = None
def foo(x):
global t
y = x + 1
print("Y=%d"%y)
t = threading.Thread(target=bar, args=(y,))
t.start()
id = thread.start_new_thread(foo, (1,))
while True:
pass
Fix tests: add sleep to the main thread in order to stop in the child threads on the slow IronPython.
|
try:
import thread
except :
import _thread as thread
import threading
from time import sleep
def bar(y):
z = 100 + y
print("Z=%d"%z)
t = None
def foo(x):
global t
y = x + 1
print("Y=%d"%y)
t = threading.Thread(target=bar, args=(y,))
t.start()
id = thread.start_new_thread(foo, (1,))
while True:
sleep(1)
|
<commit_before>try:
import thread
except :
import _thread as thread
import threading
def bar(y):
z = 100 + y
print("Z=%d"%z)
t = None
def foo(x):
global t
y = x + 1
print("Y=%d"%y)
t = threading.Thread(target=bar, args=(y,))
t.start()
id = thread.start_new_thread(foo, (1,))
while True:
pass
<commit_msg>Fix tests: add sleep to the main thread in order to stop in the child threads on the slow IronPython.<commit_after>
|
try:
import thread
except :
import _thread as thread
import threading
from time import sleep
def bar(y):
z = 100 + y
print("Z=%d"%z)
t = None
def foo(x):
global t
y = x + 1
print("Y=%d"%y)
t = threading.Thread(target=bar, args=(y,))
t.start()
id = thread.start_new_thread(foo, (1,))
while True:
sleep(1)
|
try:
import thread
except :
import _thread as thread
import threading
def bar(y):
z = 100 + y
print("Z=%d"%z)
t = None
def foo(x):
global t
y = x + 1
print("Y=%d"%y)
t = threading.Thread(target=bar, args=(y,))
t.start()
id = thread.start_new_thread(foo, (1,))
while True:
pass
Fix tests: add sleep to the main thread in order to stop in the child threads on the slow IronPython.try:
import thread
except :
import _thread as thread
import threading
from time import sleep
def bar(y):
z = 100 + y
print("Z=%d"%z)
t = None
def foo(x):
global t
y = x + 1
print("Y=%d"%y)
t = threading.Thread(target=bar, args=(y,))
t.start()
id = thread.start_new_thread(foo, (1,))
while True:
sleep(1)
|
<commit_before>try:
import thread
except :
import _thread as thread
import threading
def bar(y):
z = 100 + y
print("Z=%d"%z)
t = None
def foo(x):
global t
y = x + 1
print("Y=%d"%y)
t = threading.Thread(target=bar, args=(y,))
t.start()
id = thread.start_new_thread(foo, (1,))
while True:
pass
<commit_msg>Fix tests: add sleep to the main thread in order to stop in the child threads on the slow IronPython.<commit_after>try:
import thread
except :
import _thread as thread
import threading
from time import sleep
def bar(y):
z = 100 + y
print("Z=%d"%z)
t = None
def foo(x):
global t
y = x + 1
print("Y=%d"%y)
t = threading.Thread(target=bar, args=(y,))
t.start()
id = thread.start_new_thread(foo, (1,))
while True:
sleep(1)
|
7aedf3e0b4e6d3f75f00e55e7b6deb02cbacffc0
|
mff_rams_plugin/automated_emails.py
|
mff_rams_plugin/automated_emails.py
|
from uber.config import c
from uber.automated_emails import MarketplaceEmailFixture
from uber.utils import days_before
MarketplaceEmailFixture(
'Your {EVENT_NAME} ({EVENT_DATE}) Dealer registration is due in one week',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(7, g.dealer_payment_due, 2)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_due_soon_mff')
MarketplaceEmailFixture(
'Last chance to pay for your {EVENT_NAME} ({EVENT_DATE}) Dealer registration',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(7, g.dealer_payment_due, 2)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_last_chance_mff')
|
from uber.config import c
from uber.automated_emails import MarketplaceEmailFixture
from uber.utils import days_before
MarketplaceEmailFixture(
'Your {EVENT_NAME} ({EVENT_DATE}) Dealer registration is due in one week',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(7, g.dealer_payment_due, 2)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_due_soon_mff')
MarketplaceEmailFixture(
'Last chance to pay for your {EVENT_NAME} ({EVENT_DATE}) Dealer registration',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(2, g.dealer_payment_due)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_last_chance_mff')
|
Fix 'last chance' reminder email Both payment reminder emails were accidentally configured to go out at the same time.
|
Fix 'last chance' reminder email
Both payment reminder emails were accidentally configured to go out at the same time.
|
Python
|
agpl-3.0
|
MidwestFurryFandom/mff-rams-plugin,MidwestFurryFandom/mff-rams-plugin
|
from uber.config import c
from uber.automated_emails import MarketplaceEmailFixture
from uber.utils import days_before
MarketplaceEmailFixture(
'Your {EVENT_NAME} ({EVENT_DATE}) Dealer registration is due in one week',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(7, g.dealer_payment_due, 2)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_due_soon_mff')
MarketplaceEmailFixture(
'Last chance to pay for your {EVENT_NAME} ({EVENT_DATE}) Dealer registration',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(7, g.dealer_payment_due, 2)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_last_chance_mff')Fix 'last chance' reminder email
Both payment reminder emails were accidentally configured to go out at the same time.
|
from uber.config import c
from uber.automated_emails import MarketplaceEmailFixture
from uber.utils import days_before
MarketplaceEmailFixture(
'Your {EVENT_NAME} ({EVENT_DATE}) Dealer registration is due in one week',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(7, g.dealer_payment_due, 2)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_due_soon_mff')
MarketplaceEmailFixture(
'Last chance to pay for your {EVENT_NAME} ({EVENT_DATE}) Dealer registration',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(2, g.dealer_payment_due)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_last_chance_mff')
|
<commit_before>from uber.config import c
from uber.automated_emails import MarketplaceEmailFixture
from uber.utils import days_before
MarketplaceEmailFixture(
'Your {EVENT_NAME} ({EVENT_DATE}) Dealer registration is due in one week',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(7, g.dealer_payment_due, 2)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_due_soon_mff')
MarketplaceEmailFixture(
'Last chance to pay for your {EVENT_NAME} ({EVENT_DATE}) Dealer registration',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(7, g.dealer_payment_due, 2)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_last_chance_mff')<commit_msg>Fix 'last chance' reminder email
Both payment reminder emails were accidentally configured to go out at the same time.<commit_after>
|
from uber.config import c
from uber.automated_emails import MarketplaceEmailFixture
from uber.utils import days_before
MarketplaceEmailFixture(
'Your {EVENT_NAME} ({EVENT_DATE}) Dealer registration is due in one week',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(7, g.dealer_payment_due, 2)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_due_soon_mff')
MarketplaceEmailFixture(
'Last chance to pay for your {EVENT_NAME} ({EVENT_DATE}) Dealer registration',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(2, g.dealer_payment_due)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_last_chance_mff')
|
from uber.config import c
from uber.automated_emails import MarketplaceEmailFixture
from uber.utils import days_before
MarketplaceEmailFixture(
'Your {EVENT_NAME} ({EVENT_DATE}) Dealer registration is due in one week',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(7, g.dealer_payment_due, 2)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_due_soon_mff')
MarketplaceEmailFixture(
'Last chance to pay for your {EVENT_NAME} ({EVENT_DATE}) Dealer registration',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(7, g.dealer_payment_due, 2)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_last_chance_mff')Fix 'last chance' reminder email
Both payment reminder emails were accidentally configured to go out at the same time.from uber.config import c
from uber.automated_emails import MarketplaceEmailFixture
from uber.utils import days_before
MarketplaceEmailFixture(
'Your {EVENT_NAME} ({EVENT_DATE}) Dealer registration is due in one week',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(7, g.dealer_payment_due, 2)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_due_soon_mff')
MarketplaceEmailFixture(
'Last chance to pay for your {EVENT_NAME} ({EVENT_DATE}) Dealer registration',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(2, g.dealer_payment_due)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_last_chance_mff')
|
<commit_before>from uber.config import c
from uber.automated_emails import MarketplaceEmailFixture
from uber.utils import days_before
MarketplaceEmailFixture(
'Your {EVENT_NAME} ({EVENT_DATE}) Dealer registration is due in one week',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(7, g.dealer_payment_due, 2)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_due_soon_mff')
MarketplaceEmailFixture(
'Last chance to pay for your {EVENT_NAME} ({EVENT_DATE}) Dealer registration',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(7, g.dealer_payment_due, 2)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_last_chance_mff')<commit_msg>Fix 'last chance' reminder email
Both payment reminder emails were accidentally configured to go out at the same time.<commit_after>from uber.config import c
from uber.automated_emails import MarketplaceEmailFixture
from uber.utils import days_before
MarketplaceEmailFixture(
'Your {EVENT_NAME} ({EVENT_DATE}) Dealer registration is due in one week',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(7, g.dealer_payment_due, 2)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_due_soon_mff')
MarketplaceEmailFixture(
'Last chance to pay for your {EVENT_NAME} ({EVENT_DATE}) Dealer registration',
'dealers/payment_reminder.txt',
lambda g: g.status == c.APPROVED and days_before(2, g.dealer_payment_due)() and g.is_unpaid,
needs_approval=False,
ident='dealer_reg_payment_reminder_last_chance_mff')
|
7bbd2effa7d1b07e3c924b23ed082bf3dcd2920e
|
hungarian-nltk/src/snowball_stemmer_sentence.py
|
hungarian-nltk/src/snowball_stemmer_sentence.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from nltk.stem.snowball import HungarianStemmer
class SnowballStemmerSentence:
def __init__(self, tokenize_sentence, stemmer = HungarianStemmer()):
self.sentence = tokenize_sentence
self.stemmer = stemmer
def pretty_result(self):
#for key, word in enumerate(self.result()):
# print "{0}. '{1}'".format(key, word)
for result in self.pretty_result_msg():
print result
def pretty_result_msg(self):
#for key, word in enumerate(self.result()):
# print "{0}. '{1}'".format(key, word)
return ["{0}. '{1}'".format(key, word) for key, word in enumerate(self.result())]
def print_result(self):
print self.result_msg()
def result_msg(self):
return self.result()
def result(self):
return self.__stemming()
def __stemming(self):
return [self.__stemming_actual_word(word) for word in self.sentence]
def __stemming_actual_word(self, word):
return self.stemmer.stem(word)
import unittest
class TestSnowballStemmerSentence(unittest.TestCase):
def setUp(self):
self.test_data = ["Szeretném"]
self.subject = SnowballStemmerSentence(self.test_data)
def test_sentence(self):
self.assertEqual(self.subject.sentence, self.test_data)
def test_result(self):
self.assertEqual(self.subject.result(), [u'szeretne'])
def test_result_msg(self):
self.assertEqual(self.subject.result_msg(), [u'szeretne'])
def test_pretty_result_msg(self):
self.assertEqual(self.subject.pretty_result_msg(), [u"0. 'szeretne'"])
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from nltk.stem.snowball import HungarianStemmer
class SnowballStemmerSentence:
def __init__(self, tokenize_sentence, stemmer = HungarianStemmer()):
self.sentence = tokenize_sentence
self.stemmer = stemmer
def pretty_result(self):
for result in self.pretty_result_msg():
print result
def pretty_result_msg(self):
return ["{0}. '{1}'".format(key, word) for key, word in enumerate(self.result())]
def print_result(self):
print self.result_msg()
def result_msg(self):
return self.result()
def result(self):
return self.__stemming()
def __stemming(self):
return [self.__stemming_actual_word(word) for word in self.sentence]
def __stemming_actual_word(self, word):
return self.stemmer.stem(word)
|
Delete testcases from src file
|
Delete testcases from src file
|
Python
|
apache-2.0
|
davidpgero/hungarian-nltk
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from nltk.stem.snowball import HungarianStemmer
class SnowballStemmerSentence:
def __init__(self, tokenize_sentence, stemmer = HungarianStemmer()):
self.sentence = tokenize_sentence
self.stemmer = stemmer
def pretty_result(self):
#for key, word in enumerate(self.result()):
# print "{0}. '{1}'".format(key, word)
for result in self.pretty_result_msg():
print result
def pretty_result_msg(self):
#for key, word in enumerate(self.result()):
# print "{0}. '{1}'".format(key, word)
return ["{0}. '{1}'".format(key, word) for key, word in enumerate(self.result())]
def print_result(self):
print self.result_msg()
def result_msg(self):
return self.result()
def result(self):
return self.__stemming()
def __stemming(self):
return [self.__stemming_actual_word(word) for word in self.sentence]
def __stemming_actual_word(self, word):
return self.stemmer.stem(word)
import unittest
class TestSnowballStemmerSentence(unittest.TestCase):
def setUp(self):
self.test_data = ["Szeretném"]
self.subject = SnowballStemmerSentence(self.test_data)
def test_sentence(self):
self.assertEqual(self.subject.sentence, self.test_data)
def test_result(self):
self.assertEqual(self.subject.result(), [u'szeretne'])
def test_result_msg(self):
self.assertEqual(self.subject.result_msg(), [u'szeretne'])
def test_pretty_result_msg(self):
self.assertEqual(self.subject.pretty_result_msg(), [u"0. 'szeretne'"])
if __name__ == '__main__':
unittest.main()Delete testcases from src file
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from nltk.stem.snowball import HungarianStemmer
class SnowballStemmerSentence:
def __init__(self, tokenize_sentence, stemmer = HungarianStemmer()):
self.sentence = tokenize_sentence
self.stemmer = stemmer
def pretty_result(self):
for result in self.pretty_result_msg():
print result
def pretty_result_msg(self):
return ["{0}. '{1}'".format(key, word) for key, word in enumerate(self.result())]
def print_result(self):
print self.result_msg()
def result_msg(self):
return self.result()
def result(self):
return self.__stemming()
def __stemming(self):
return [self.__stemming_actual_word(word) for word in self.sentence]
def __stemming_actual_word(self, word):
return self.stemmer.stem(word)
|
<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from nltk.stem.snowball import HungarianStemmer
class SnowballStemmerSentence:
def __init__(self, tokenize_sentence, stemmer = HungarianStemmer()):
self.sentence = tokenize_sentence
self.stemmer = stemmer
def pretty_result(self):
#for key, word in enumerate(self.result()):
# print "{0}. '{1}'".format(key, word)
for result in self.pretty_result_msg():
print result
def pretty_result_msg(self):
#for key, word in enumerate(self.result()):
# print "{0}. '{1}'".format(key, word)
return ["{0}. '{1}'".format(key, word) for key, word in enumerate(self.result())]
def print_result(self):
print self.result_msg()
def result_msg(self):
return self.result()
def result(self):
return self.__stemming()
def __stemming(self):
return [self.__stemming_actual_word(word) for word in self.sentence]
def __stemming_actual_word(self, word):
return self.stemmer.stem(word)
import unittest
class TestSnowballStemmerSentence(unittest.TestCase):
def setUp(self):
self.test_data = ["Szeretném"]
self.subject = SnowballStemmerSentence(self.test_data)
def test_sentence(self):
self.assertEqual(self.subject.sentence, self.test_data)
def test_result(self):
self.assertEqual(self.subject.result(), [u'szeretne'])
def test_result_msg(self):
self.assertEqual(self.subject.result_msg(), [u'szeretne'])
def test_pretty_result_msg(self):
self.assertEqual(self.subject.pretty_result_msg(), [u"0. 'szeretne'"])
if __name__ == '__main__':
unittest.main()<commit_msg>Delete testcases from src file<commit_after>
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from nltk.stem.snowball import HungarianStemmer
class SnowballStemmerSentence:
def __init__(self, tokenize_sentence, stemmer = HungarianStemmer()):
self.sentence = tokenize_sentence
self.stemmer = stemmer
def pretty_result(self):
for result in self.pretty_result_msg():
print result
def pretty_result_msg(self):
return ["{0}. '{1}'".format(key, word) for key, word in enumerate(self.result())]
def print_result(self):
print self.result_msg()
def result_msg(self):
return self.result()
def result(self):
return self.__stemming()
def __stemming(self):
return [self.__stemming_actual_word(word) for word in self.sentence]
def __stemming_actual_word(self, word):
return self.stemmer.stem(word)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from nltk.stem.snowball import HungarianStemmer
class SnowballStemmerSentence:
def __init__(self, tokenize_sentence, stemmer = HungarianStemmer()):
self.sentence = tokenize_sentence
self.stemmer = stemmer
def pretty_result(self):
#for key, word in enumerate(self.result()):
# print "{0}. '{1}'".format(key, word)
for result in self.pretty_result_msg():
print result
def pretty_result_msg(self):
#for key, word in enumerate(self.result()):
# print "{0}. '{1}'".format(key, word)
return ["{0}. '{1}'".format(key, word) for key, word in enumerate(self.result())]
def print_result(self):
print self.result_msg()
def result_msg(self):
return self.result()
def result(self):
return self.__stemming()
def __stemming(self):
return [self.__stemming_actual_word(word) for word in self.sentence]
def __stemming_actual_word(self, word):
return self.stemmer.stem(word)
import unittest
class TestSnowballStemmerSentence(unittest.TestCase):
def setUp(self):
self.test_data = ["Szeretném"]
self.subject = SnowballStemmerSentence(self.test_data)
def test_sentence(self):
self.assertEqual(self.subject.sentence, self.test_data)
def test_result(self):
self.assertEqual(self.subject.result(), [u'szeretne'])
def test_result_msg(self):
self.assertEqual(self.subject.result_msg(), [u'szeretne'])
def test_pretty_result_msg(self):
self.assertEqual(self.subject.pretty_result_msg(), [u"0. 'szeretne'"])
if __name__ == '__main__':
unittest.main()Delete testcases from src file#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from nltk.stem.snowball import HungarianStemmer
class SnowballStemmerSentence:
def __init__(self, tokenize_sentence, stemmer = HungarianStemmer()):
self.sentence = tokenize_sentence
self.stemmer = stemmer
def pretty_result(self):
for result in self.pretty_result_msg():
print result
def pretty_result_msg(self):
return ["{0}. '{1}'".format(key, word) for key, word in enumerate(self.result())]
def print_result(self):
print self.result_msg()
def result_msg(self):
return self.result()
def result(self):
return self.__stemming()
def __stemming(self):
return [self.__stemming_actual_word(word) for word in self.sentence]
def __stemming_actual_word(self, word):
return self.stemmer.stem(word)
|
<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from nltk.stem.snowball import HungarianStemmer
class SnowballStemmerSentence:
def __init__(self, tokenize_sentence, stemmer = HungarianStemmer()):
self.sentence = tokenize_sentence
self.stemmer = stemmer
def pretty_result(self):
#for key, word in enumerate(self.result()):
# print "{0}. '{1}'".format(key, word)
for result in self.pretty_result_msg():
print result
def pretty_result_msg(self):
#for key, word in enumerate(self.result()):
# print "{0}. '{1}'".format(key, word)
return ["{0}. '{1}'".format(key, word) for key, word in enumerate(self.result())]
def print_result(self):
print self.result_msg()
def result_msg(self):
return self.result()
def result(self):
return self.__stemming()
def __stemming(self):
return [self.__stemming_actual_word(word) for word in self.sentence]
def __stemming_actual_word(self, word):
return self.stemmer.stem(word)
import unittest
class TestSnowballStemmerSentence(unittest.TestCase):
def setUp(self):
self.test_data = ["Szeretném"]
self.subject = SnowballStemmerSentence(self.test_data)
def test_sentence(self):
self.assertEqual(self.subject.sentence, self.test_data)
def test_result(self):
self.assertEqual(self.subject.result(), [u'szeretne'])
def test_result_msg(self):
self.assertEqual(self.subject.result_msg(), [u'szeretne'])
def test_pretty_result_msg(self):
self.assertEqual(self.subject.pretty_result_msg(), [u"0. 'szeretne'"])
if __name__ == '__main__':
unittest.main()<commit_msg>Delete testcases from src file<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from nltk.stem.snowball import HungarianStemmer
class SnowballStemmerSentence:
def __init__(self, tokenize_sentence, stemmer = HungarianStemmer()):
self.sentence = tokenize_sentence
self.stemmer = stemmer
def pretty_result(self):
for result in self.pretty_result_msg():
print result
def pretty_result_msg(self):
return ["{0}. '{1}'".format(key, word) for key, word in enumerate(self.result())]
def print_result(self):
print self.result_msg()
def result_msg(self):
return self.result()
def result(self):
return self.__stemming()
def __stemming(self):
return [self.__stemming_actual_word(word) for word in self.sentence]
def __stemming_actual_word(self, word):
return self.stemmer.stem(word)
|
763073bc71e59953b7010840fc7923fc15881265
|
tests/scoring_engine/models/test_settings.py
|
tests/scoring_engine/models/test_settings.py
|
from scoring_engine.models.setting import Setting
from tests.scoring_engine.unit_test import UnitTest
class TestSetting(UnitTest):
def test_init_setting(self):
setting = Setting(name='test_setting', value='test value example')
assert setting.id is None
assert setting.name == 'test_setting'
assert setting.value == 'test value example'
self.session.add(setting)
self.session.commit()
assert setting.id is not None
def test_get_setting(self):
setting_old = Setting(name='test_setting', value='test value example')
self.session.add(setting_old)
setting_new = Setting(name='test_setting', value='updated example')
self.session.add(setting_new)
self.session.commit()
assert Setting.get_setting('test_setting', self.session).value == 'updated example'
|
from scoring_engine.models.setting import Setting
from tests.scoring_engine.unit_test import UnitTest
class TestSetting(UnitTest):
def test_init_setting(self):
setting = Setting(name='test_setting', value='test value example')
assert setting.id is None
assert setting.name == 'test_setting'
assert setting.value == 'test value example'
self.session.add(setting)
self.session.commit()
assert setting.id is not None
def test_get_setting(self):
setting_old = Setting(name='test_setting', value='test value example')
self.session.add(setting_old)
setting_new = Setting(name='test_setting', value='updated example')
self.session.add(setting_new)
self.session.commit()
assert Setting.get_setting('test_setting').value == 'updated example'
|
Remove leftover parameter in settings tests
|
Remove leftover parameter in settings tests
|
Python
|
mit
|
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
|
from scoring_engine.models.setting import Setting
from tests.scoring_engine.unit_test import UnitTest
class TestSetting(UnitTest):
def test_init_setting(self):
setting = Setting(name='test_setting', value='test value example')
assert setting.id is None
assert setting.name == 'test_setting'
assert setting.value == 'test value example'
self.session.add(setting)
self.session.commit()
assert setting.id is not None
def test_get_setting(self):
setting_old = Setting(name='test_setting', value='test value example')
self.session.add(setting_old)
setting_new = Setting(name='test_setting', value='updated example')
self.session.add(setting_new)
self.session.commit()
assert Setting.get_setting('test_setting', self.session).value == 'updated example'
Remove leftover parameter in settings tests
|
from scoring_engine.models.setting import Setting
from tests.scoring_engine.unit_test import UnitTest
class TestSetting(UnitTest):
def test_init_setting(self):
setting = Setting(name='test_setting', value='test value example')
assert setting.id is None
assert setting.name == 'test_setting'
assert setting.value == 'test value example'
self.session.add(setting)
self.session.commit()
assert setting.id is not None
def test_get_setting(self):
setting_old = Setting(name='test_setting', value='test value example')
self.session.add(setting_old)
setting_new = Setting(name='test_setting', value='updated example')
self.session.add(setting_new)
self.session.commit()
assert Setting.get_setting('test_setting').value == 'updated example'
|
<commit_before>from scoring_engine.models.setting import Setting
from tests.scoring_engine.unit_test import UnitTest
class TestSetting(UnitTest):
def test_init_setting(self):
setting = Setting(name='test_setting', value='test value example')
assert setting.id is None
assert setting.name == 'test_setting'
assert setting.value == 'test value example'
self.session.add(setting)
self.session.commit()
assert setting.id is not None
def test_get_setting(self):
setting_old = Setting(name='test_setting', value='test value example')
self.session.add(setting_old)
setting_new = Setting(name='test_setting', value='updated example')
self.session.add(setting_new)
self.session.commit()
assert Setting.get_setting('test_setting', self.session).value == 'updated example'
<commit_msg>Remove leftover parameter in settings tests<commit_after>
|
from scoring_engine.models.setting import Setting
from tests.scoring_engine.unit_test import UnitTest
class TestSetting(UnitTest):
def test_init_setting(self):
setting = Setting(name='test_setting', value='test value example')
assert setting.id is None
assert setting.name == 'test_setting'
assert setting.value == 'test value example'
self.session.add(setting)
self.session.commit()
assert setting.id is not None
def test_get_setting(self):
setting_old = Setting(name='test_setting', value='test value example')
self.session.add(setting_old)
setting_new = Setting(name='test_setting', value='updated example')
self.session.add(setting_new)
self.session.commit()
assert Setting.get_setting('test_setting').value == 'updated example'
|
from scoring_engine.models.setting import Setting
from tests.scoring_engine.unit_test import UnitTest
class TestSetting(UnitTest):
def test_init_setting(self):
setting = Setting(name='test_setting', value='test value example')
assert setting.id is None
assert setting.name == 'test_setting'
assert setting.value == 'test value example'
self.session.add(setting)
self.session.commit()
assert setting.id is not None
def test_get_setting(self):
setting_old = Setting(name='test_setting', value='test value example')
self.session.add(setting_old)
setting_new = Setting(name='test_setting', value='updated example')
self.session.add(setting_new)
self.session.commit()
assert Setting.get_setting('test_setting', self.session).value == 'updated example'
Remove leftover parameter in settings testsfrom scoring_engine.models.setting import Setting
from tests.scoring_engine.unit_test import UnitTest
class TestSetting(UnitTest):
def test_init_setting(self):
setting = Setting(name='test_setting', value='test value example')
assert setting.id is None
assert setting.name == 'test_setting'
assert setting.value == 'test value example'
self.session.add(setting)
self.session.commit()
assert setting.id is not None
def test_get_setting(self):
setting_old = Setting(name='test_setting', value='test value example')
self.session.add(setting_old)
setting_new = Setting(name='test_setting', value='updated example')
self.session.add(setting_new)
self.session.commit()
assert Setting.get_setting('test_setting').value == 'updated example'
|
<commit_before>from scoring_engine.models.setting import Setting
from tests.scoring_engine.unit_test import UnitTest
class TestSetting(UnitTest):
def test_init_setting(self):
setting = Setting(name='test_setting', value='test value example')
assert setting.id is None
assert setting.name == 'test_setting'
assert setting.value == 'test value example'
self.session.add(setting)
self.session.commit()
assert setting.id is not None
def test_get_setting(self):
setting_old = Setting(name='test_setting', value='test value example')
self.session.add(setting_old)
setting_new = Setting(name='test_setting', value='updated example')
self.session.add(setting_new)
self.session.commit()
assert Setting.get_setting('test_setting', self.session).value == 'updated example'
<commit_msg>Remove leftover parameter in settings tests<commit_after>from scoring_engine.models.setting import Setting
from tests.scoring_engine.unit_test import UnitTest
class TestSetting(UnitTest):
def test_init_setting(self):
setting = Setting(name='test_setting', value='test value example')
assert setting.id is None
assert setting.name == 'test_setting'
assert setting.value == 'test value example'
self.session.add(setting)
self.session.commit()
assert setting.id is not None
def test_get_setting(self):
setting_old = Setting(name='test_setting', value='test value example')
self.session.add(setting_old)
setting_new = Setting(name='test_setting', value='updated example')
self.session.add(setting_new)
self.session.commit()
assert Setting.get_setting('test_setting').value == 'updated example'
|
b025558ecf354894132fcfc9bda33bd8a627a27e
|
lib/python/mod_python/__init__.py
|
lib/python/mod_python/__init__.py
|
#
# Copyright 2004 Apache Software Foundation
#
# 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.
#
# Originally developed by Gregory Trubetskoy.
#
# $Id$
__all__ = ["apache", "cgihandler", "psp",
"publisher", "util"]
|
#
# Copyright 2004 Apache Software Foundation
#
# 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.
#
# Originally developed by Gregory Trubetskoy.
#
# $Id$
__all__ = ["apache", "cgihandler", "psp",
"publisher", "util"]
version = "3.2.0-dev-20050518"
|
Fix for MODPYTHON-55 : added a version attribute to the mod_python package.
|
Fix for MODPYTHON-55 : added a version attribute to the mod_python package.
|
Python
|
apache-2.0
|
grisha/mod_python,carlmcdade/mod_python,dacaiguoguo/mod_python,dacaiguoguo/mod_python,dacaiguoguo/mod_python,grisha/mod_python,runt18/mod_python,runt18/mod_python,carlmcdade/mod_python,grisha/mod_python,runt18/mod_python,carlmcdade/mod_python
|
#
# Copyright 2004 Apache Software Foundation
#
# 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.
#
# Originally developed by Gregory Trubetskoy.
#
# $Id$
__all__ = ["apache", "cgihandler", "psp",
"publisher", "util"]
Fix for MODPYTHON-55 : added a version attribute to the mod_python package.
|
#
# Copyright 2004 Apache Software Foundation
#
# 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.
#
# Originally developed by Gregory Trubetskoy.
#
# $Id$
__all__ = ["apache", "cgihandler", "psp",
"publisher", "util"]
version = "3.2.0-dev-20050518"
|
<commit_before> #
# Copyright 2004 Apache Software Foundation
#
# 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.
#
# Originally developed by Gregory Trubetskoy.
#
# $Id$
__all__ = ["apache", "cgihandler", "psp",
"publisher", "util"]
<commit_msg>Fix for MODPYTHON-55 : added a version attribute to the mod_python package.<commit_after>
|
#
# Copyright 2004 Apache Software Foundation
#
# 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.
#
# Originally developed by Gregory Trubetskoy.
#
# $Id$
__all__ = ["apache", "cgihandler", "psp",
"publisher", "util"]
version = "3.2.0-dev-20050518"
|
#
# Copyright 2004 Apache Software Foundation
#
# 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.
#
# Originally developed by Gregory Trubetskoy.
#
# $Id$
__all__ = ["apache", "cgihandler", "psp",
"publisher", "util"]
Fix for MODPYTHON-55 : added a version attribute to the mod_python package. #
# Copyright 2004 Apache Software Foundation
#
# 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.
#
# Originally developed by Gregory Trubetskoy.
#
# $Id$
__all__ = ["apache", "cgihandler", "psp",
"publisher", "util"]
version = "3.2.0-dev-20050518"
|
<commit_before> #
# Copyright 2004 Apache Software Foundation
#
# 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.
#
# Originally developed by Gregory Trubetskoy.
#
# $Id$
__all__ = ["apache", "cgihandler", "psp",
"publisher", "util"]
<commit_msg>Fix for MODPYTHON-55 : added a version attribute to the mod_python package.<commit_after> #
# Copyright 2004 Apache Software Foundation
#
# 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.
#
# Originally developed by Gregory Trubetskoy.
#
# $Id$
__all__ = ["apache", "cgihandler", "psp",
"publisher", "util"]
version = "3.2.0-dev-20050518"
|
087a58c80d0c0764881fdf45d4bdf997a99de29f
|
srv/budget.py
|
srv/budget.py
|
"""
Main budget web app (backend)
Written by Fela Maslen, 2016
"""
from flask import Flask, request, render_template
from srv.config import PIE_TOLERANCE
from srv.misc import get_serial
from srv.rest_api import WebAPI
APP = Flask('budget')
@APP.route('/api', methods=['GET', 'POST'])
def api():
""" api entry point """
the_api = WebAPI(request)
if the_api.res['api_error']:
return "Unknown server error", 500
return the_api.get_json(), the_api.res['code']
@APP.route('/')
def index():
""" web app entry point """
dev = 'dev' in request.args
serial = get_serial()
return render_template('index.html', dev=dev, serial=serial, \
pie_tolerance=PIE_TOLERANCE)
if __name__ == '__main__':
APP.run(host='0.0.0.0', port=8000)
|
"""
Main budget web app (backend)
Written by Fela Maslen, 2016
"""
from flask import Flask, request, render_template
from srv.config import PIE_TOLERANCE
from srv.misc import get_serial
from srv.rest_api import WebAPI
APP = Flask('budget')
@APP.route('/api', methods=['GET', 'POST'])
def api():
""" api entry point """
the_api = WebAPI(request)
if the_api.res['api_error']:
return "Unknown server error", 500
return the_api.get_json(), the_api.res['code']
@APP.route('/')
@APP.route('/index.html')
def index():
""" web app entry point """
dev = 'dev' in request.args
serial = get_serial()
return render_template('index.html', dev=dev, serial=serial, \
pie_tolerance=PIE_TOLERANCE)
if __name__ == '__main__':
APP.run(host='0.0.0.0', port=8000)
|
Add index.html alias on api
|
Add index.html alias on api
|
Python
|
mit
|
felamaslen/budget,felamaslen/budget,felamaslen/budget,felamaslen/budget,felamaslen/budget,felamaslen/budget
|
"""
Main budget web app (backend)
Written by Fela Maslen, 2016
"""
from flask import Flask, request, render_template
from srv.config import PIE_TOLERANCE
from srv.misc import get_serial
from srv.rest_api import WebAPI
APP = Flask('budget')
@APP.route('/api', methods=['GET', 'POST'])
def api():
""" api entry point """
the_api = WebAPI(request)
if the_api.res['api_error']:
return "Unknown server error", 500
return the_api.get_json(), the_api.res['code']
@APP.route('/')
def index():
""" web app entry point """
dev = 'dev' in request.args
serial = get_serial()
return render_template('index.html', dev=dev, serial=serial, \
pie_tolerance=PIE_TOLERANCE)
if __name__ == '__main__':
APP.run(host='0.0.0.0', port=8000)
Add index.html alias on api
|
"""
Main budget web app (backend)
Written by Fela Maslen, 2016
"""
from flask import Flask, request, render_template
from srv.config import PIE_TOLERANCE
from srv.misc import get_serial
from srv.rest_api import WebAPI
APP = Flask('budget')
@APP.route('/api', methods=['GET', 'POST'])
def api():
""" api entry point """
the_api = WebAPI(request)
if the_api.res['api_error']:
return "Unknown server error", 500
return the_api.get_json(), the_api.res['code']
@APP.route('/')
@APP.route('/index.html')
def index():
""" web app entry point """
dev = 'dev' in request.args
serial = get_serial()
return render_template('index.html', dev=dev, serial=serial, \
pie_tolerance=PIE_TOLERANCE)
if __name__ == '__main__':
APP.run(host='0.0.0.0', port=8000)
|
<commit_before>"""
Main budget web app (backend)
Written by Fela Maslen, 2016
"""
from flask import Flask, request, render_template
from srv.config import PIE_TOLERANCE
from srv.misc import get_serial
from srv.rest_api import WebAPI
APP = Flask('budget')
@APP.route('/api', methods=['GET', 'POST'])
def api():
""" api entry point """
the_api = WebAPI(request)
if the_api.res['api_error']:
return "Unknown server error", 500
return the_api.get_json(), the_api.res['code']
@APP.route('/')
def index():
""" web app entry point """
dev = 'dev' in request.args
serial = get_serial()
return render_template('index.html', dev=dev, serial=serial, \
pie_tolerance=PIE_TOLERANCE)
if __name__ == '__main__':
APP.run(host='0.0.0.0', port=8000)
<commit_msg>Add index.html alias on api<commit_after>
|
"""
Main budget web app (backend)
Written by Fela Maslen, 2016
"""
from flask import Flask, request, render_template
from srv.config import PIE_TOLERANCE
from srv.misc import get_serial
from srv.rest_api import WebAPI
APP = Flask('budget')
@APP.route('/api', methods=['GET', 'POST'])
def api():
""" api entry point """
the_api = WebAPI(request)
if the_api.res['api_error']:
return "Unknown server error", 500
return the_api.get_json(), the_api.res['code']
@APP.route('/')
@APP.route('/index.html')
def index():
""" web app entry point """
dev = 'dev' in request.args
serial = get_serial()
return render_template('index.html', dev=dev, serial=serial, \
pie_tolerance=PIE_TOLERANCE)
if __name__ == '__main__':
APP.run(host='0.0.0.0', port=8000)
|
"""
Main budget web app (backend)
Written by Fela Maslen, 2016
"""
from flask import Flask, request, render_template
from srv.config import PIE_TOLERANCE
from srv.misc import get_serial
from srv.rest_api import WebAPI
APP = Flask('budget')
@APP.route('/api', methods=['GET', 'POST'])
def api():
""" api entry point """
the_api = WebAPI(request)
if the_api.res['api_error']:
return "Unknown server error", 500
return the_api.get_json(), the_api.res['code']
@APP.route('/')
def index():
""" web app entry point """
dev = 'dev' in request.args
serial = get_serial()
return render_template('index.html', dev=dev, serial=serial, \
pie_tolerance=PIE_TOLERANCE)
if __name__ == '__main__':
APP.run(host='0.0.0.0', port=8000)
Add index.html alias on api"""
Main budget web app (backend)
Written by Fela Maslen, 2016
"""
from flask import Flask, request, render_template
from srv.config import PIE_TOLERANCE
from srv.misc import get_serial
from srv.rest_api import WebAPI
APP = Flask('budget')
@APP.route('/api', methods=['GET', 'POST'])
def api():
""" api entry point """
the_api = WebAPI(request)
if the_api.res['api_error']:
return "Unknown server error", 500
return the_api.get_json(), the_api.res['code']
@APP.route('/')
@APP.route('/index.html')
def index():
""" web app entry point """
dev = 'dev' in request.args
serial = get_serial()
return render_template('index.html', dev=dev, serial=serial, \
pie_tolerance=PIE_TOLERANCE)
if __name__ == '__main__':
APP.run(host='0.0.0.0', port=8000)
|
<commit_before>"""
Main budget web app (backend)
Written by Fela Maslen, 2016
"""
from flask import Flask, request, render_template
from srv.config import PIE_TOLERANCE
from srv.misc import get_serial
from srv.rest_api import WebAPI
APP = Flask('budget')
@APP.route('/api', methods=['GET', 'POST'])
def api():
""" api entry point """
the_api = WebAPI(request)
if the_api.res['api_error']:
return "Unknown server error", 500
return the_api.get_json(), the_api.res['code']
@APP.route('/')
def index():
""" web app entry point """
dev = 'dev' in request.args
serial = get_serial()
return render_template('index.html', dev=dev, serial=serial, \
pie_tolerance=PIE_TOLERANCE)
if __name__ == '__main__':
APP.run(host='0.0.0.0', port=8000)
<commit_msg>Add index.html alias on api<commit_after>"""
Main budget web app (backend)
Written by Fela Maslen, 2016
"""
from flask import Flask, request, render_template
from srv.config import PIE_TOLERANCE
from srv.misc import get_serial
from srv.rest_api import WebAPI
APP = Flask('budget')
@APP.route('/api', methods=['GET', 'POST'])
def api():
""" api entry point """
the_api = WebAPI(request)
if the_api.res['api_error']:
return "Unknown server error", 500
return the_api.get_json(), the_api.res['code']
@APP.route('/')
@APP.route('/index.html')
def index():
""" web app entry point """
dev = 'dev' in request.args
serial = get_serial()
return render_template('index.html', dev=dev, serial=serial, \
pie_tolerance=PIE_TOLERANCE)
if __name__ == '__main__':
APP.run(host='0.0.0.0', port=8000)
|
c02bf0729872450110de981cfb016ea0e864f93b
|
ato_children/api/filters.py
|
ato_children/api/filters.py
|
import django_filters
from ..models import Gift
class GiftFilter(django_filters.FilterSet):
"""docstring for GiftFilter"""
class Meta:
model = Gift
fields = ['region']
|
import django_filters
from ..models import Gift
class GiftFilter(django_filters.FilterSet):
"""docstring for GiftFilter"""
class Meta:
model = Gift
fields = ['region', 'status']
|
Enable status filter in API
|
Enable status filter in API
|
Python
|
mit
|
webknjaz/webchallenge-ato-children,webknjaz/webchallenge-ato-children,webknjaz/webchallenge-ato-children,webknjaz/webchallenge-ato-children
|
import django_filters
from ..models import Gift
class GiftFilter(django_filters.FilterSet):
"""docstring for GiftFilter"""
class Meta:
model = Gift
fields = ['region']
Enable status filter in API
|
import django_filters
from ..models import Gift
class GiftFilter(django_filters.FilterSet):
"""docstring for GiftFilter"""
class Meta:
model = Gift
fields = ['region', 'status']
|
<commit_before>import django_filters
from ..models import Gift
class GiftFilter(django_filters.FilterSet):
"""docstring for GiftFilter"""
class Meta:
model = Gift
fields = ['region']
<commit_msg>Enable status filter in API<commit_after>
|
import django_filters
from ..models import Gift
class GiftFilter(django_filters.FilterSet):
"""docstring for GiftFilter"""
class Meta:
model = Gift
fields = ['region', 'status']
|
import django_filters
from ..models import Gift
class GiftFilter(django_filters.FilterSet):
"""docstring for GiftFilter"""
class Meta:
model = Gift
fields = ['region']
Enable status filter in APIimport django_filters
from ..models import Gift
class GiftFilter(django_filters.FilterSet):
"""docstring for GiftFilter"""
class Meta:
model = Gift
fields = ['region', 'status']
|
<commit_before>import django_filters
from ..models import Gift
class GiftFilter(django_filters.FilterSet):
"""docstring for GiftFilter"""
class Meta:
model = Gift
fields = ['region']
<commit_msg>Enable status filter in API<commit_after>import django_filters
from ..models import Gift
class GiftFilter(django_filters.FilterSet):
"""docstring for GiftFilter"""
class Meta:
model = Gift
fields = ['region', 'status']
|
64c937439911760c7fdc0c70af323381ad13b86d
|
fellowms/forms.py
|
fellowms/forms.py
|
from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
exclude = [
"home_lon",
"home_lat",
"inauguration_year",
"mentor",
]
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
labels = {
'fellow': 'Fellow',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = [
'id',
'status',
]
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
|
from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
exclude = [
"home_lon",
"home_lat",
"inauguration_year",
"funding_notes",
"mentor",
]
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
labels = {
'fellow': 'Fellow',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = [
'id',
'status',
]
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
|
Update form to handle notes about funding
|
Update form to handle notes about funding
|
Python
|
bsd-3-clause
|
softwaresaved/fat,softwaresaved/fat,softwaresaved/fat,softwaresaved/fat
|
from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
exclude = [
"home_lon",
"home_lat",
"inauguration_year",
"mentor",
]
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
labels = {
'fellow': 'Fellow',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = [
'id',
'status',
]
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
Update form to handle notes about funding
|
from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
exclude = [
"home_lon",
"home_lat",
"inauguration_year",
"funding_notes",
"mentor",
]
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
labels = {
'fellow': 'Fellow',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = [
'id',
'status',
]
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
|
<commit_before>from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
exclude = [
"home_lon",
"home_lat",
"inauguration_year",
"mentor",
]
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
labels = {
'fellow': 'Fellow',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = [
'id',
'status',
]
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
<commit_msg>Update form to handle notes about funding<commit_after>
|
from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
exclude = [
"home_lon",
"home_lat",
"inauguration_year",
"funding_notes",
"mentor",
]
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
labels = {
'fellow': 'Fellow',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = [
'id',
'status',
]
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
|
from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
exclude = [
"home_lon",
"home_lat",
"inauguration_year",
"mentor",
]
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
labels = {
'fellow': 'Fellow',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = [
'id',
'status',
]
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
Update form to handle notes about fundingfrom django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
exclude = [
"home_lon",
"home_lat",
"inauguration_year",
"funding_notes",
"mentor",
]
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
labels = {
'fellow': 'Fellow',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = [
'id',
'status',
]
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
|
<commit_before>from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
exclude = [
"home_lon",
"home_lat",
"inauguration_year",
"mentor",
]
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
labels = {
'fellow': 'Fellow',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = [
'id',
'status',
]
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
<commit_msg>Update form to handle notes about funding<commit_after>from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
exclude = [
"home_lon",
"home_lat",
"inauguration_year",
"funding_notes",
"mentor",
]
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
labels = {
'fellow': 'Fellow',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = [
'id',
'status',
]
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
|
7ea233b7f955f7dbb291d0662fe321cddfceba80
|
mopidy/frontends/lastfm/__init__.py
|
mopidy/frontends/lastfm/__init__.py
|
from __future__ import unicode_literals
import mopidy
from mopidy import ext
from mopidy.exceptions import ExtensionError
__doc__ = """
Frontend which scrobbles the music you play to your `Last.fm
<http://www.last.fm>`_ profile.
.. note::
This frontend requires a free user account at Last.fm.
**Dependencies:**
.. literalinclude:: ../../../requirements/lastfm.txt
**Settings:**
- :attr:`mopidy.settings.LASTFM_USERNAME`
- :attr:`mopidy.settings.LASTFM_PASSWORD`
**Usage:**
The frontend is enabled by default if all dependencies are available.
"""
class Extension(ext.Extension):
name = 'Mopidy-Lastfm'
version = mopidy.__version__
def get_default_config(self):
return '[ext.lastfm]'
def validate_config(self, config):
pass
def validate_environment(self):
try:
import pylast # noqa
except ImportError as e:
raise ExtensionError('pylast library not found', e)
def get_frontend_classes(self):
from .actor import LastfmFrontend
return [LastfmFrontend]
|
from __future__ import unicode_literals
import mopidy
from mopidy import exceptions, ext
from mopidy.utils import config, formatting
default_config = """
[ext.lastfm]
# If the Last.fm extension should be enabled or not
enabled = true
# Your Last.fm username
username =
# Your Last.fm password
password =
"""
__doc__ = """
Frontend which scrobbles the music you play to your `Last.fm
<http://www.last.fm>`_ profile.
.. note::
This frontend requires a free user account at Last.fm.
**Dependencies:**
.. literalinclude:: ../../../requirements/lastfm.txt
**Default config:**
.. code-block:: ini
%(config)s
**Usage:**
The frontend is enabled by default if all dependencies are available.
""" % {'config': formatting.indent(default_config)}
class Extension(ext.Extension):
name = 'Mopidy-Lastfm'
version = mopidy.__version__
def get_default_config(self):
return default_config
def get_config_schema(self):
schema = config.ExtensionConfigSchema()
schema['username'] = config.String()
schema['password'] = config.String(secret=True)
return schema
def validate_environment(self):
try:
import pylast # noqa
except ImportError as e:
raise exceptions.ExtensionError('pylast library not found', e)
def get_frontend_classes(self):
from .actor import LastfmFrontend
return [LastfmFrontend]
|
Add default config and config schema
|
lastfm: Add default config and config schema
|
Python
|
apache-2.0
|
diandiankan/mopidy,jmarsik/mopidy,ZenithDK/mopidy,diandiankan/mopidy,bacontext/mopidy,ali/mopidy,jcass77/mopidy,quartz55/mopidy,rawdlite/mopidy,priestd09/mopidy,kingosticks/mopidy,mopidy/mopidy,bencevans/mopidy,swak/mopidy,mokieyue/mopidy,hkariti/mopidy,quartz55/mopidy,kingosticks/mopidy,vrs01/mopidy,glogiotatidis/mopidy,dbrgn/mopidy,rawdlite/mopidy,vrs01/mopidy,liamw9534/mopidy,jodal/mopidy,ali/mopidy,SuperStarPL/mopidy,pacificIT/mopidy,abarisain/mopidy,adamcik/mopidy,woutervanwijk/mopidy,ZenithDK/mopidy,ZenithDK/mopidy,adamcik/mopidy,tkem/mopidy,dbrgn/mopidy,diandiankan/mopidy,rawdlite/mopidy,mopidy/mopidy,priestd09/mopidy,glogiotatidis/mopidy,tkem/mopidy,ZenithDK/mopidy,hkariti/mopidy,rawdlite/mopidy,vrs01/mopidy,mokieyue/mopidy,jodal/mopidy,diandiankan/mopidy,SuperStarPL/mopidy,adamcik/mopidy,liamw9534/mopidy,quartz55/mopidy,pacificIT/mopidy,bencevans/mopidy,ali/mopidy,bencevans/mopidy,dbrgn/mopidy,glogiotatidis/mopidy,jmarsik/mopidy,mokieyue/mopidy,jcass77/mopidy,abarisain/mopidy,tkem/mopidy,dbrgn/mopidy,hkariti/mopidy,jmarsik/mopidy,jodal/mopidy,swak/mopidy,vrs01/mopidy,quartz55/mopidy,SuperStarPL/mopidy,SuperStarPL/mopidy,bacontext/mopidy,jmarsik/mopidy,bacontext/mopidy,mokieyue/mopidy,tkem/mopidy,swak/mopidy,priestd09/mopidy,hkariti/mopidy,woutervanwijk/mopidy,pacificIT/mopidy,ali/mopidy,bacontext/mopidy,bencevans/mopidy,mopidy/mopidy,kingosticks/mopidy,glogiotatidis/mopidy,jcass77/mopidy,swak/mopidy,pacificIT/mopidy
|
from __future__ import unicode_literals
import mopidy
from mopidy import ext
from mopidy.exceptions import ExtensionError
__doc__ = """
Frontend which scrobbles the music you play to your `Last.fm
<http://www.last.fm>`_ profile.
.. note::
This frontend requires a free user account at Last.fm.
**Dependencies:**
.. literalinclude:: ../../../requirements/lastfm.txt
**Settings:**
- :attr:`mopidy.settings.LASTFM_USERNAME`
- :attr:`mopidy.settings.LASTFM_PASSWORD`
**Usage:**
The frontend is enabled by default if all dependencies are available.
"""
class Extension(ext.Extension):
name = 'Mopidy-Lastfm'
version = mopidy.__version__
def get_default_config(self):
return '[ext.lastfm]'
def validate_config(self, config):
pass
def validate_environment(self):
try:
import pylast # noqa
except ImportError as e:
raise ExtensionError('pylast library not found', e)
def get_frontend_classes(self):
from .actor import LastfmFrontend
return [LastfmFrontend]
lastfm: Add default config and config schema
|
from __future__ import unicode_literals
import mopidy
from mopidy import exceptions, ext
from mopidy.utils import config, formatting
default_config = """
[ext.lastfm]
# If the Last.fm extension should be enabled or not
enabled = true
# Your Last.fm username
username =
# Your Last.fm password
password =
"""
__doc__ = """
Frontend which scrobbles the music you play to your `Last.fm
<http://www.last.fm>`_ profile.
.. note::
This frontend requires a free user account at Last.fm.
**Dependencies:**
.. literalinclude:: ../../../requirements/lastfm.txt
**Default config:**
.. code-block:: ini
%(config)s
**Usage:**
The frontend is enabled by default if all dependencies are available.
""" % {'config': formatting.indent(default_config)}
class Extension(ext.Extension):
name = 'Mopidy-Lastfm'
version = mopidy.__version__
def get_default_config(self):
return default_config
def get_config_schema(self):
schema = config.ExtensionConfigSchema()
schema['username'] = config.String()
schema['password'] = config.String(secret=True)
return schema
def validate_environment(self):
try:
import pylast # noqa
except ImportError as e:
raise exceptions.ExtensionError('pylast library not found', e)
def get_frontend_classes(self):
from .actor import LastfmFrontend
return [LastfmFrontend]
|
<commit_before>from __future__ import unicode_literals
import mopidy
from mopidy import ext
from mopidy.exceptions import ExtensionError
__doc__ = """
Frontend which scrobbles the music you play to your `Last.fm
<http://www.last.fm>`_ profile.
.. note::
This frontend requires a free user account at Last.fm.
**Dependencies:**
.. literalinclude:: ../../../requirements/lastfm.txt
**Settings:**
- :attr:`mopidy.settings.LASTFM_USERNAME`
- :attr:`mopidy.settings.LASTFM_PASSWORD`
**Usage:**
The frontend is enabled by default if all dependencies are available.
"""
class Extension(ext.Extension):
name = 'Mopidy-Lastfm'
version = mopidy.__version__
def get_default_config(self):
return '[ext.lastfm]'
def validate_config(self, config):
pass
def validate_environment(self):
try:
import pylast # noqa
except ImportError as e:
raise ExtensionError('pylast library not found', e)
def get_frontend_classes(self):
from .actor import LastfmFrontend
return [LastfmFrontend]
<commit_msg>lastfm: Add default config and config schema<commit_after>
|
from __future__ import unicode_literals
import mopidy
from mopidy import exceptions, ext
from mopidy.utils import config, formatting
default_config = """
[ext.lastfm]
# If the Last.fm extension should be enabled or not
enabled = true
# Your Last.fm username
username =
# Your Last.fm password
password =
"""
__doc__ = """
Frontend which scrobbles the music you play to your `Last.fm
<http://www.last.fm>`_ profile.
.. note::
This frontend requires a free user account at Last.fm.
**Dependencies:**
.. literalinclude:: ../../../requirements/lastfm.txt
**Default config:**
.. code-block:: ini
%(config)s
**Usage:**
The frontend is enabled by default if all dependencies are available.
""" % {'config': formatting.indent(default_config)}
class Extension(ext.Extension):
name = 'Mopidy-Lastfm'
version = mopidy.__version__
def get_default_config(self):
return default_config
def get_config_schema(self):
schema = config.ExtensionConfigSchema()
schema['username'] = config.String()
schema['password'] = config.String(secret=True)
return schema
def validate_environment(self):
try:
import pylast # noqa
except ImportError as e:
raise exceptions.ExtensionError('pylast library not found', e)
def get_frontend_classes(self):
from .actor import LastfmFrontend
return [LastfmFrontend]
|
from __future__ import unicode_literals
import mopidy
from mopidy import ext
from mopidy.exceptions import ExtensionError
__doc__ = """
Frontend which scrobbles the music you play to your `Last.fm
<http://www.last.fm>`_ profile.
.. note::
This frontend requires a free user account at Last.fm.
**Dependencies:**
.. literalinclude:: ../../../requirements/lastfm.txt
**Settings:**
- :attr:`mopidy.settings.LASTFM_USERNAME`
- :attr:`mopidy.settings.LASTFM_PASSWORD`
**Usage:**
The frontend is enabled by default if all dependencies are available.
"""
class Extension(ext.Extension):
name = 'Mopidy-Lastfm'
version = mopidy.__version__
def get_default_config(self):
return '[ext.lastfm]'
def validate_config(self, config):
pass
def validate_environment(self):
try:
import pylast # noqa
except ImportError as e:
raise ExtensionError('pylast library not found', e)
def get_frontend_classes(self):
from .actor import LastfmFrontend
return [LastfmFrontend]
lastfm: Add default config and config schemafrom __future__ import unicode_literals
import mopidy
from mopidy import exceptions, ext
from mopidy.utils import config, formatting
default_config = """
[ext.lastfm]
# If the Last.fm extension should be enabled or not
enabled = true
# Your Last.fm username
username =
# Your Last.fm password
password =
"""
__doc__ = """
Frontend which scrobbles the music you play to your `Last.fm
<http://www.last.fm>`_ profile.
.. note::
This frontend requires a free user account at Last.fm.
**Dependencies:**
.. literalinclude:: ../../../requirements/lastfm.txt
**Default config:**
.. code-block:: ini
%(config)s
**Usage:**
The frontend is enabled by default if all dependencies are available.
""" % {'config': formatting.indent(default_config)}
class Extension(ext.Extension):
name = 'Mopidy-Lastfm'
version = mopidy.__version__
def get_default_config(self):
return default_config
def get_config_schema(self):
schema = config.ExtensionConfigSchema()
schema['username'] = config.String()
schema['password'] = config.String(secret=True)
return schema
def validate_environment(self):
try:
import pylast # noqa
except ImportError as e:
raise exceptions.ExtensionError('pylast library not found', e)
def get_frontend_classes(self):
from .actor import LastfmFrontend
return [LastfmFrontend]
|
<commit_before>from __future__ import unicode_literals
import mopidy
from mopidy import ext
from mopidy.exceptions import ExtensionError
__doc__ = """
Frontend which scrobbles the music you play to your `Last.fm
<http://www.last.fm>`_ profile.
.. note::
This frontend requires a free user account at Last.fm.
**Dependencies:**
.. literalinclude:: ../../../requirements/lastfm.txt
**Settings:**
- :attr:`mopidy.settings.LASTFM_USERNAME`
- :attr:`mopidy.settings.LASTFM_PASSWORD`
**Usage:**
The frontend is enabled by default if all dependencies are available.
"""
class Extension(ext.Extension):
name = 'Mopidy-Lastfm'
version = mopidy.__version__
def get_default_config(self):
return '[ext.lastfm]'
def validate_config(self, config):
pass
def validate_environment(self):
try:
import pylast # noqa
except ImportError as e:
raise ExtensionError('pylast library not found', e)
def get_frontend_classes(self):
from .actor import LastfmFrontend
return [LastfmFrontend]
<commit_msg>lastfm: Add default config and config schema<commit_after>from __future__ import unicode_literals
import mopidy
from mopidy import exceptions, ext
from mopidy.utils import config, formatting
default_config = """
[ext.lastfm]
# If the Last.fm extension should be enabled or not
enabled = true
# Your Last.fm username
username =
# Your Last.fm password
password =
"""
__doc__ = """
Frontend which scrobbles the music you play to your `Last.fm
<http://www.last.fm>`_ profile.
.. note::
This frontend requires a free user account at Last.fm.
**Dependencies:**
.. literalinclude:: ../../../requirements/lastfm.txt
**Default config:**
.. code-block:: ini
%(config)s
**Usage:**
The frontend is enabled by default if all dependencies are available.
""" % {'config': formatting.indent(default_config)}
class Extension(ext.Extension):
name = 'Mopidy-Lastfm'
version = mopidy.__version__
def get_default_config(self):
return default_config
def get_config_schema(self):
schema = config.ExtensionConfigSchema()
schema['username'] = config.String()
schema['password'] = config.String(secret=True)
return schema
def validate_environment(self):
try:
import pylast # noqa
except ImportError as e:
raise exceptions.ExtensionError('pylast library not found', e)
def get_frontend_classes(self):
from .actor import LastfmFrontend
return [LastfmFrontend]
|
79cb3d5b8fdca5eba436f0c879633d1994f857a5
|
detect_tone.py
|
detect_tone.py
|
from gz_dsp import *
from cfg import *
# By FFT, I mean Goertzel transform
def detect_tone(signal):
ideal_samples_per_fft = SAMPLE_FREQ/float(FFT_FREQ)
samples_per_cycle = SAMPLE_FREQ/MORSE_FREQ
aspf = actual_samples_per_fft = int(samples_per_cycle*max(round(ideal_samples_per_fft/samples_per_cycle), 1))
coeffs = []
for i in xrange(0, len(signal), int(aspf/OVERLAP_FACTOR)):
samples = signal[i:i+aspf]
if len(samples) < aspf: #fail if you run out of data
break
intensity = gz_dsp(samples, MORSE_FREQ)
coeffs.append(intensity/(aspf**2/4))
coeffs_per_second = SAMPLE_FREQ/aspf
return coeffs, coeffs_per_second
|
from gz_dsp import *
from cfg import *
def detect_tone(signal):
ideal_samples_per_transform = SAMPLE_FREQ/float(transform_FREQ)
samples_per_cycle = SAMPLE_FREQ/MORSE_FREQ
aspt = actual_samples_per_transform = int(samples_per_cycle*max(round(ideal_samples_per_transform/samples_per_cycle), 1))
coeffs = []
for i in xrange(0, len(signal), int(aspt/OVERLAP_FACTOR)):
samples = signal[i:i+aspt]
if len(samples) < aspt: #fail if you run out of data
break
intensity = gz_dsp(samples, MORSE_FREQ)
coeffs.append(intensity/(aspt**2/4))
coeffs_per_second = SAMPLE_FREQ/aspt
return coeffs, coeffs_per_second
|
Change variable names to reflect that it doesn't use FFT's anymore
|
Change variable names to reflect that it doesn't use FFT's anymore
|
Python
|
mit
|
nickodell/morse-code
|
from gz_dsp import *
from cfg import *
# By FFT, I mean Goertzel transform
def detect_tone(signal):
ideal_samples_per_fft = SAMPLE_FREQ/float(FFT_FREQ)
samples_per_cycle = SAMPLE_FREQ/MORSE_FREQ
aspf = actual_samples_per_fft = int(samples_per_cycle*max(round(ideal_samples_per_fft/samples_per_cycle), 1))
coeffs = []
for i in xrange(0, len(signal), int(aspf/OVERLAP_FACTOR)):
samples = signal[i:i+aspf]
if len(samples) < aspf: #fail if you run out of data
break
intensity = gz_dsp(samples, MORSE_FREQ)
coeffs.append(intensity/(aspf**2/4))
coeffs_per_second = SAMPLE_FREQ/aspf
return coeffs, coeffs_per_second
Change variable names to reflect that it doesn't use FFT's anymore
|
from gz_dsp import *
from cfg import *
def detect_tone(signal):
ideal_samples_per_transform = SAMPLE_FREQ/float(transform_FREQ)
samples_per_cycle = SAMPLE_FREQ/MORSE_FREQ
aspt = actual_samples_per_transform = int(samples_per_cycle*max(round(ideal_samples_per_transform/samples_per_cycle), 1))
coeffs = []
for i in xrange(0, len(signal), int(aspt/OVERLAP_FACTOR)):
samples = signal[i:i+aspt]
if len(samples) < aspt: #fail if you run out of data
break
intensity = gz_dsp(samples, MORSE_FREQ)
coeffs.append(intensity/(aspt**2/4))
coeffs_per_second = SAMPLE_FREQ/aspt
return coeffs, coeffs_per_second
|
<commit_before>from gz_dsp import *
from cfg import *
# By FFT, I mean Goertzel transform
def detect_tone(signal):
ideal_samples_per_fft = SAMPLE_FREQ/float(FFT_FREQ)
samples_per_cycle = SAMPLE_FREQ/MORSE_FREQ
aspf = actual_samples_per_fft = int(samples_per_cycle*max(round(ideal_samples_per_fft/samples_per_cycle), 1))
coeffs = []
for i in xrange(0, len(signal), int(aspf/OVERLAP_FACTOR)):
samples = signal[i:i+aspf]
if len(samples) < aspf: #fail if you run out of data
break
intensity = gz_dsp(samples, MORSE_FREQ)
coeffs.append(intensity/(aspf**2/4))
coeffs_per_second = SAMPLE_FREQ/aspf
return coeffs, coeffs_per_second
<commit_msg>Change variable names to reflect that it doesn't use FFT's anymore<commit_after>
|
from gz_dsp import *
from cfg import *
def detect_tone(signal):
ideal_samples_per_transform = SAMPLE_FREQ/float(transform_FREQ)
samples_per_cycle = SAMPLE_FREQ/MORSE_FREQ
aspt = actual_samples_per_transform = int(samples_per_cycle*max(round(ideal_samples_per_transform/samples_per_cycle), 1))
coeffs = []
for i in xrange(0, len(signal), int(aspt/OVERLAP_FACTOR)):
samples = signal[i:i+aspt]
if len(samples) < aspt: #fail if you run out of data
break
intensity = gz_dsp(samples, MORSE_FREQ)
coeffs.append(intensity/(aspt**2/4))
coeffs_per_second = SAMPLE_FREQ/aspt
return coeffs, coeffs_per_second
|
from gz_dsp import *
from cfg import *
# By FFT, I mean Goertzel transform
def detect_tone(signal):
ideal_samples_per_fft = SAMPLE_FREQ/float(FFT_FREQ)
samples_per_cycle = SAMPLE_FREQ/MORSE_FREQ
aspf = actual_samples_per_fft = int(samples_per_cycle*max(round(ideal_samples_per_fft/samples_per_cycle), 1))
coeffs = []
for i in xrange(0, len(signal), int(aspf/OVERLAP_FACTOR)):
samples = signal[i:i+aspf]
if len(samples) < aspf: #fail if you run out of data
break
intensity = gz_dsp(samples, MORSE_FREQ)
coeffs.append(intensity/(aspf**2/4))
coeffs_per_second = SAMPLE_FREQ/aspf
return coeffs, coeffs_per_second
Change variable names to reflect that it doesn't use FFT's anymorefrom gz_dsp import *
from cfg import *
def detect_tone(signal):
ideal_samples_per_transform = SAMPLE_FREQ/float(transform_FREQ)
samples_per_cycle = SAMPLE_FREQ/MORSE_FREQ
aspt = actual_samples_per_transform = int(samples_per_cycle*max(round(ideal_samples_per_transform/samples_per_cycle), 1))
coeffs = []
for i in xrange(0, len(signal), int(aspt/OVERLAP_FACTOR)):
samples = signal[i:i+aspt]
if len(samples) < aspt: #fail if you run out of data
break
intensity = gz_dsp(samples, MORSE_FREQ)
coeffs.append(intensity/(aspt**2/4))
coeffs_per_second = SAMPLE_FREQ/aspt
return coeffs, coeffs_per_second
|
<commit_before>from gz_dsp import *
from cfg import *
# By FFT, I mean Goertzel transform
def detect_tone(signal):
ideal_samples_per_fft = SAMPLE_FREQ/float(FFT_FREQ)
samples_per_cycle = SAMPLE_FREQ/MORSE_FREQ
aspf = actual_samples_per_fft = int(samples_per_cycle*max(round(ideal_samples_per_fft/samples_per_cycle), 1))
coeffs = []
for i in xrange(0, len(signal), int(aspf/OVERLAP_FACTOR)):
samples = signal[i:i+aspf]
if len(samples) < aspf: #fail if you run out of data
break
intensity = gz_dsp(samples, MORSE_FREQ)
coeffs.append(intensity/(aspf**2/4))
coeffs_per_second = SAMPLE_FREQ/aspf
return coeffs, coeffs_per_second
<commit_msg>Change variable names to reflect that it doesn't use FFT's anymore<commit_after>from gz_dsp import *
from cfg import *
def detect_tone(signal):
ideal_samples_per_transform = SAMPLE_FREQ/float(transform_FREQ)
samples_per_cycle = SAMPLE_FREQ/MORSE_FREQ
aspt = actual_samples_per_transform = int(samples_per_cycle*max(round(ideal_samples_per_transform/samples_per_cycle), 1))
coeffs = []
for i in xrange(0, len(signal), int(aspt/OVERLAP_FACTOR)):
samples = signal[i:i+aspt]
if len(samples) < aspt: #fail if you run out of data
break
intensity = gz_dsp(samples, MORSE_FREQ)
coeffs.append(intensity/(aspt**2/4))
coeffs_per_second = SAMPLE_FREQ/aspt
return coeffs, coeffs_per_second
|
135e579f8d087bff88e0d67addc455210a0866da
|
django/applications/catmaid/control/__init__.py
|
django/applications/catmaid/control/__init__.py
|
from common import *
from connector import *
from label import *
from link import *
from neurohdf import *
from neuron import *
from node import *
from object import *
from project import *
from search import *
from skeletongroup import *
from skeletonexport import *
from skeleton import *
from stack import *
from stats import *
from textlabel import *
from tile import *
from tree import *
from treenode import *
from treenodetable import *
from wiringdiagram import *
from analytics import *
from importer import *
from graph import *
from useranalytics import *
from circles import *
from neuron_annotations import *
|
from common import *
from connector import *
from label import *
from link import *
from neurohdf import *
from neuron import *
from node import *
from object import *
from project import *
from search import *
from skeletongroup import *
from skeletonexport import *
from skeleton import *
from stack import *
from stats import *
from textlabel import *
from tile import *
from tree import *
from treenode import *
from treenodetable import *
from wiringdiagram import *
from analytics import *
from graph import *
from useranalytics import *
from circles import *
from neuron_annotations import *
|
Remove superfluous importer namespace import in catmaid.control
|
Remove superfluous importer namespace import in catmaid.control
I double checked that no importer methods are used directly through the
catmaid.control module.
This relates to issue #570.
|
Python
|
agpl-3.0
|
fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID
|
from common import *
from connector import *
from label import *
from link import *
from neurohdf import *
from neuron import *
from node import *
from object import *
from project import *
from search import *
from skeletongroup import *
from skeletonexport import *
from skeleton import *
from stack import *
from stats import *
from textlabel import *
from tile import *
from tree import *
from treenode import *
from treenodetable import *
from wiringdiagram import *
from analytics import *
from importer import *
from graph import *
from useranalytics import *
from circles import *
from neuron_annotations import *
Remove superfluous importer namespace import in catmaid.control
I double checked that no importer methods are used directly through the
catmaid.control module.
This relates to issue #570.
|
from common import *
from connector import *
from label import *
from link import *
from neurohdf import *
from neuron import *
from node import *
from object import *
from project import *
from search import *
from skeletongroup import *
from skeletonexport import *
from skeleton import *
from stack import *
from stats import *
from textlabel import *
from tile import *
from tree import *
from treenode import *
from treenodetable import *
from wiringdiagram import *
from analytics import *
from graph import *
from useranalytics import *
from circles import *
from neuron_annotations import *
|
<commit_before>from common import *
from connector import *
from label import *
from link import *
from neurohdf import *
from neuron import *
from node import *
from object import *
from project import *
from search import *
from skeletongroup import *
from skeletonexport import *
from skeleton import *
from stack import *
from stats import *
from textlabel import *
from tile import *
from tree import *
from treenode import *
from treenodetable import *
from wiringdiagram import *
from analytics import *
from importer import *
from graph import *
from useranalytics import *
from circles import *
from neuron_annotations import *
<commit_msg>Remove superfluous importer namespace import in catmaid.control
I double checked that no importer methods are used directly through the
catmaid.control module.
This relates to issue #570.<commit_after>
|
from common import *
from connector import *
from label import *
from link import *
from neurohdf import *
from neuron import *
from node import *
from object import *
from project import *
from search import *
from skeletongroup import *
from skeletonexport import *
from skeleton import *
from stack import *
from stats import *
from textlabel import *
from tile import *
from tree import *
from treenode import *
from treenodetable import *
from wiringdiagram import *
from analytics import *
from graph import *
from useranalytics import *
from circles import *
from neuron_annotations import *
|
from common import *
from connector import *
from label import *
from link import *
from neurohdf import *
from neuron import *
from node import *
from object import *
from project import *
from search import *
from skeletongroup import *
from skeletonexport import *
from skeleton import *
from stack import *
from stats import *
from textlabel import *
from tile import *
from tree import *
from treenode import *
from treenodetable import *
from wiringdiagram import *
from analytics import *
from importer import *
from graph import *
from useranalytics import *
from circles import *
from neuron_annotations import *
Remove superfluous importer namespace import in catmaid.control
I double checked that no importer methods are used directly through the
catmaid.control module.
This relates to issue #570.from common import *
from connector import *
from label import *
from link import *
from neurohdf import *
from neuron import *
from node import *
from object import *
from project import *
from search import *
from skeletongroup import *
from skeletonexport import *
from skeleton import *
from stack import *
from stats import *
from textlabel import *
from tile import *
from tree import *
from treenode import *
from treenodetable import *
from wiringdiagram import *
from analytics import *
from graph import *
from useranalytics import *
from circles import *
from neuron_annotations import *
|
<commit_before>from common import *
from connector import *
from label import *
from link import *
from neurohdf import *
from neuron import *
from node import *
from object import *
from project import *
from search import *
from skeletongroup import *
from skeletonexport import *
from skeleton import *
from stack import *
from stats import *
from textlabel import *
from tile import *
from tree import *
from treenode import *
from treenodetable import *
from wiringdiagram import *
from analytics import *
from importer import *
from graph import *
from useranalytics import *
from circles import *
from neuron_annotations import *
<commit_msg>Remove superfluous importer namespace import in catmaid.control
I double checked that no importer methods are used directly through the
catmaid.control module.
This relates to issue #570.<commit_after>from common import *
from connector import *
from label import *
from link import *
from neurohdf import *
from neuron import *
from node import *
from object import *
from project import *
from search import *
from skeletongroup import *
from skeletonexport import *
from skeleton import *
from stack import *
from stats import *
from textlabel import *
from tile import *
from tree import *
from treenode import *
from treenodetable import *
from wiringdiagram import *
from analytics import *
from graph import *
from useranalytics import *
from circles import *
from neuron_annotations import *
|
c5a1eab4cc08e26d852cc9e1f73478c65174af3c
|
students/psbriant/final_project/test_clean_data.py
|
students/psbriant/final_project/test_clean_data.py
|
"""
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Tests for Final Project
"""
import clean_data as cd
import matplotlib.pyplot as plt
import pandas
import pytest
def get_data():
"""
Retrieve data from csv file to test.
"""
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
return data
def test_clean():
"""
"""
def test_rename_columns():
"""
Test whether rename_columns successfully renames each column.
"""
data = get_data()
data = data.drop(["Date Value"], axis=1)
column_names = list(data.columns.values)
column_list = cd.rename_columns(column_names)
assert column_list[0:5] == ["Date", "90001", "90002", "90003", "90004"]
def test_find_low_water_use():
"""
"""
@pytest.mark.mpl_image_compare
def test_plot_zipcode():
"""
Test zipcode based wateruse graphs.
To Do: fix test that fails
"""
data = get_data()
cleaned = cd.clean(data)
wateruse = cd.plot_zipcode(cleaned, "90012")
return wateruse
|
"""
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Tests for Final Project
"""
import clean_data as cd
import matplotlib.pyplot as plt
import pandas
import pytest
def get_data():
"""
Retrieve data from csv file to test.
"""
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
return data
def test_clean():
"""
"""
def test_rename_columns():
"""
Test whether rename_columns successfully renames each column.
"""
data = get_data()
data = data.drop(["Date Value"], axis=1)
column_names = list(data.columns.values)
column_list = cd.rename_columns(column_names)
assert column_list[0:5] == ["Date", "90001", "90002", "90003", "90004"]
def test_find_low_water_use():
"""
"""
@pytest.mark.mpl_image_compare
def test_plot_zipcode():
"""
Test zipcode based wateruse graphs.
To Do: fix test that fails
"""
data = get_data()
cleaned = cd.clean(data)
wateruse = cd.plot_zipcode(cleaned, "90012")
return wateruse
def test_user_interface():
"""
Tests user interface.
"""
|
Add empty test function for user interface.
|
Add empty test function for user interface.
|
Python
|
unlicense
|
UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016
|
"""
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Tests for Final Project
"""
import clean_data as cd
import matplotlib.pyplot as plt
import pandas
import pytest
def get_data():
"""
Retrieve data from csv file to test.
"""
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
return data
def test_clean():
"""
"""
def test_rename_columns():
"""
Test whether rename_columns successfully renames each column.
"""
data = get_data()
data = data.drop(["Date Value"], axis=1)
column_names = list(data.columns.values)
column_list = cd.rename_columns(column_names)
assert column_list[0:5] == ["Date", "90001", "90002", "90003", "90004"]
def test_find_low_water_use():
"""
"""
@pytest.mark.mpl_image_compare
def test_plot_zipcode():
"""
Test zipcode based wateruse graphs.
To Do: fix test that fails
"""
data = get_data()
cleaned = cd.clean(data)
wateruse = cd.plot_zipcode(cleaned, "90012")
return wateruse
Add empty test function for user interface.
|
"""
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Tests for Final Project
"""
import clean_data as cd
import matplotlib.pyplot as plt
import pandas
import pytest
def get_data():
"""
Retrieve data from csv file to test.
"""
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
return data
def test_clean():
"""
"""
def test_rename_columns():
"""
Test whether rename_columns successfully renames each column.
"""
data = get_data()
data = data.drop(["Date Value"], axis=1)
column_names = list(data.columns.values)
column_list = cd.rename_columns(column_names)
assert column_list[0:5] == ["Date", "90001", "90002", "90003", "90004"]
def test_find_low_water_use():
"""
"""
@pytest.mark.mpl_image_compare
def test_plot_zipcode():
"""
Test zipcode based wateruse graphs.
To Do: fix test that fails
"""
data = get_data()
cleaned = cd.clean(data)
wateruse = cd.plot_zipcode(cleaned, "90012")
return wateruse
def test_user_interface():
"""
Tests user interface.
"""
|
<commit_before>"""
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Tests for Final Project
"""
import clean_data as cd
import matplotlib.pyplot as plt
import pandas
import pytest
def get_data():
"""
Retrieve data from csv file to test.
"""
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
return data
def test_clean():
"""
"""
def test_rename_columns():
"""
Test whether rename_columns successfully renames each column.
"""
data = get_data()
data = data.drop(["Date Value"], axis=1)
column_names = list(data.columns.values)
column_list = cd.rename_columns(column_names)
assert column_list[0:5] == ["Date", "90001", "90002", "90003", "90004"]
def test_find_low_water_use():
"""
"""
@pytest.mark.mpl_image_compare
def test_plot_zipcode():
"""
Test zipcode based wateruse graphs.
To Do: fix test that fails
"""
data = get_data()
cleaned = cd.clean(data)
wateruse = cd.plot_zipcode(cleaned, "90012")
return wateruse
<commit_msg>Add empty test function for user interface.<commit_after>
|
"""
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Tests for Final Project
"""
import clean_data as cd
import matplotlib.pyplot as plt
import pandas
import pytest
def get_data():
"""
Retrieve data from csv file to test.
"""
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
return data
def test_clean():
"""
"""
def test_rename_columns():
"""
Test whether rename_columns successfully renames each column.
"""
data = get_data()
data = data.drop(["Date Value"], axis=1)
column_names = list(data.columns.values)
column_list = cd.rename_columns(column_names)
assert column_list[0:5] == ["Date", "90001", "90002", "90003", "90004"]
def test_find_low_water_use():
"""
"""
@pytest.mark.mpl_image_compare
def test_plot_zipcode():
"""
Test zipcode based wateruse graphs.
To Do: fix test that fails
"""
data = get_data()
cleaned = cd.clean(data)
wateruse = cd.plot_zipcode(cleaned, "90012")
return wateruse
def test_user_interface():
"""
Tests user interface.
"""
|
"""
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Tests for Final Project
"""
import clean_data as cd
import matplotlib.pyplot as plt
import pandas
import pytest
def get_data():
"""
Retrieve data from csv file to test.
"""
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
return data
def test_clean():
"""
"""
def test_rename_columns():
"""
Test whether rename_columns successfully renames each column.
"""
data = get_data()
data = data.drop(["Date Value"], axis=1)
column_names = list(data.columns.values)
column_list = cd.rename_columns(column_names)
assert column_list[0:5] == ["Date", "90001", "90002", "90003", "90004"]
def test_find_low_water_use():
"""
"""
@pytest.mark.mpl_image_compare
def test_plot_zipcode():
"""
Test zipcode based wateruse graphs.
To Do: fix test that fails
"""
data = get_data()
cleaned = cd.clean(data)
wateruse = cd.plot_zipcode(cleaned, "90012")
return wateruse
Add empty test function for user interface."""
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Tests for Final Project
"""
import clean_data as cd
import matplotlib.pyplot as plt
import pandas
import pytest
def get_data():
"""
Retrieve data from csv file to test.
"""
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
return data
def test_clean():
"""
"""
def test_rename_columns():
"""
Test whether rename_columns successfully renames each column.
"""
data = get_data()
data = data.drop(["Date Value"], axis=1)
column_names = list(data.columns.values)
column_list = cd.rename_columns(column_names)
assert column_list[0:5] == ["Date", "90001", "90002", "90003", "90004"]
def test_find_low_water_use():
"""
"""
@pytest.mark.mpl_image_compare
def test_plot_zipcode():
"""
Test zipcode based wateruse graphs.
To Do: fix test that fails
"""
data = get_data()
cleaned = cd.clean(data)
wateruse = cd.plot_zipcode(cleaned, "90012")
return wateruse
def test_user_interface():
"""
Tests user interface.
"""
|
<commit_before>"""
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Tests for Final Project
"""
import clean_data as cd
import matplotlib.pyplot as plt
import pandas
import pytest
def get_data():
"""
Retrieve data from csv file to test.
"""
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
return data
def test_clean():
"""
"""
def test_rename_columns():
"""
Test whether rename_columns successfully renames each column.
"""
data = get_data()
data = data.drop(["Date Value"], axis=1)
column_names = list(data.columns.values)
column_list = cd.rename_columns(column_names)
assert column_list[0:5] == ["Date", "90001", "90002", "90003", "90004"]
def test_find_low_water_use():
"""
"""
@pytest.mark.mpl_image_compare
def test_plot_zipcode():
"""
Test zipcode based wateruse graphs.
To Do: fix test that fails
"""
data = get_data()
cleaned = cd.clean(data)
wateruse = cd.plot_zipcode(cleaned, "90012")
return wateruse
<commit_msg>Add empty test function for user interface.<commit_after>"""
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Tests for Final Project
"""
import clean_data as cd
import matplotlib.pyplot as plt
import pandas
import pytest
def get_data():
"""
Retrieve data from csv file to test.
"""
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
return data
def test_clean():
"""
"""
def test_rename_columns():
"""
Test whether rename_columns successfully renames each column.
"""
data = get_data()
data = data.drop(["Date Value"], axis=1)
column_names = list(data.columns.values)
column_list = cd.rename_columns(column_names)
assert column_list[0:5] == ["Date", "90001", "90002", "90003", "90004"]
def test_find_low_water_use():
"""
"""
@pytest.mark.mpl_image_compare
def test_plot_zipcode():
"""
Test zipcode based wateruse graphs.
To Do: fix test that fails
"""
data = get_data()
cleaned = cd.clean(data)
wateruse = cd.plot_zipcode(cleaned, "90012")
return wateruse
def test_user_interface():
"""
Tests user interface.
"""
|
cd1b68aaaefffc15ce10789445d7749c99deb3d4
|
shingen/generators/hosts.py
|
shingen/generators/hosts.py
|
from ..shinkenconfig import ConfigObject
def generate_host_config(config, project_name, instance):
co = ConfigObject('host')
co.properties['use'] = 'generic-host'
co.properties['host_name'] = instance['name']
co.properties['address'] = instance['ip'][0]
projects = [project_name, config.get('default-hostgroup', 'labshost')]
co.properties['hostgroups'] = ','.join(projects)
co.properties['contact_groups'] = project_name
return co
|
from ..shinkenconfig import ConfigObject
def generate_host_config(config, project_name, instance):
co = ConfigObject('host')
co.properties['use'] = 'generic-host'
co.properties['host_name'] = instance['name']
co.properties['address'] = instance['ip'][0]
projects = [project_name, config.get('default-hostgroup', 'labshost')]
co.properties['hostgroups'] = ','.join(projects)
co.properties['contact_groups'] = project_name
co.properties['notes'] = project_name # Used for auto deriving graphite path
return co
|
Put project name in 'notes' field of host
|
Put project name in 'notes' field of host
Labs' graphite metrics architecture means we need both the
project name and the hostname to find a full path to our
host. Abusing this field for that purpose.
Change-Id: If097526f413f36407acdff852cc81216f9c84556
|
Python
|
apache-2.0
|
wikimedia/operations-software-shinkengen
|
from ..shinkenconfig import ConfigObject
def generate_host_config(config, project_name, instance):
co = ConfigObject('host')
co.properties['use'] = 'generic-host'
co.properties['host_name'] = instance['name']
co.properties['address'] = instance['ip'][0]
projects = [project_name, config.get('default-hostgroup', 'labshost')]
co.properties['hostgroups'] = ','.join(projects)
co.properties['contact_groups'] = project_name
return co
Put project name in 'notes' field of host
Labs' graphite metrics architecture means we need both the
project name and the hostname to find a full path to our
host. Abusing this field for that purpose.
Change-Id: If097526f413f36407acdff852cc81216f9c84556
|
from ..shinkenconfig import ConfigObject
def generate_host_config(config, project_name, instance):
co = ConfigObject('host')
co.properties['use'] = 'generic-host'
co.properties['host_name'] = instance['name']
co.properties['address'] = instance['ip'][0]
projects = [project_name, config.get('default-hostgroup', 'labshost')]
co.properties['hostgroups'] = ','.join(projects)
co.properties['contact_groups'] = project_name
co.properties['notes'] = project_name # Used for auto deriving graphite path
return co
|
<commit_before>from ..shinkenconfig import ConfigObject
def generate_host_config(config, project_name, instance):
co = ConfigObject('host')
co.properties['use'] = 'generic-host'
co.properties['host_name'] = instance['name']
co.properties['address'] = instance['ip'][0]
projects = [project_name, config.get('default-hostgroup', 'labshost')]
co.properties['hostgroups'] = ','.join(projects)
co.properties['contact_groups'] = project_name
return co
<commit_msg>Put project name in 'notes' field of host
Labs' graphite metrics architecture means we need both the
project name and the hostname to find a full path to our
host. Abusing this field for that purpose.
Change-Id: If097526f413f36407acdff852cc81216f9c84556<commit_after>
|
from ..shinkenconfig import ConfigObject
def generate_host_config(config, project_name, instance):
co = ConfigObject('host')
co.properties['use'] = 'generic-host'
co.properties['host_name'] = instance['name']
co.properties['address'] = instance['ip'][0]
projects = [project_name, config.get('default-hostgroup', 'labshost')]
co.properties['hostgroups'] = ','.join(projects)
co.properties['contact_groups'] = project_name
co.properties['notes'] = project_name # Used for auto deriving graphite path
return co
|
from ..shinkenconfig import ConfigObject
def generate_host_config(config, project_name, instance):
co = ConfigObject('host')
co.properties['use'] = 'generic-host'
co.properties['host_name'] = instance['name']
co.properties['address'] = instance['ip'][0]
projects = [project_name, config.get('default-hostgroup', 'labshost')]
co.properties['hostgroups'] = ','.join(projects)
co.properties['contact_groups'] = project_name
return co
Put project name in 'notes' field of host
Labs' graphite metrics architecture means we need both the
project name and the hostname to find a full path to our
host. Abusing this field for that purpose.
Change-Id: If097526f413f36407acdff852cc81216f9c84556from ..shinkenconfig import ConfigObject
def generate_host_config(config, project_name, instance):
co = ConfigObject('host')
co.properties['use'] = 'generic-host'
co.properties['host_name'] = instance['name']
co.properties['address'] = instance['ip'][0]
projects = [project_name, config.get('default-hostgroup', 'labshost')]
co.properties['hostgroups'] = ','.join(projects)
co.properties['contact_groups'] = project_name
co.properties['notes'] = project_name # Used for auto deriving graphite path
return co
|
<commit_before>from ..shinkenconfig import ConfigObject
def generate_host_config(config, project_name, instance):
co = ConfigObject('host')
co.properties['use'] = 'generic-host'
co.properties['host_name'] = instance['name']
co.properties['address'] = instance['ip'][0]
projects = [project_name, config.get('default-hostgroup', 'labshost')]
co.properties['hostgroups'] = ','.join(projects)
co.properties['contact_groups'] = project_name
return co
<commit_msg>Put project name in 'notes' field of host
Labs' graphite metrics architecture means we need both the
project name and the hostname to find a full path to our
host. Abusing this field for that purpose.
Change-Id: If097526f413f36407acdff852cc81216f9c84556<commit_after>from ..shinkenconfig import ConfigObject
def generate_host_config(config, project_name, instance):
co = ConfigObject('host')
co.properties['use'] = 'generic-host'
co.properties['host_name'] = instance['name']
co.properties['address'] = instance['ip'][0]
projects = [project_name, config.get('default-hostgroup', 'labshost')]
co.properties['hostgroups'] = ','.join(projects)
co.properties['contact_groups'] = project_name
co.properties['notes'] = project_name # Used for auto deriving graphite path
return co
|
dfaf3d1461a25ca26ed7562831373603010d2f29
|
xml_json_import/__init__.py
|
xml_json_import/__init__.py
|
from django.conf import settings
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
|
from django.conf import settings
from os import path
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
if not path.exists(settings.XSLT_FILES_DIR):
raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist')
|
Throw exception for not existing XSLT_FILES_DIR path
|
Throw exception for not existing XSLT_FILES_DIR path
|
Python
|
mit
|
lev-veshnyakov/django-import-data,lev-veshnyakov/django-import-data
|
from django.conf import settings
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
Throw exception for not existing XSLT_FILES_DIR path
|
from django.conf import settings
from os import path
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
if not path.exists(settings.XSLT_FILES_DIR):
raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist')
|
<commit_before>from django.conf import settings
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
<commit_msg>Throw exception for not existing XSLT_FILES_DIR path<commit_after>
|
from django.conf import settings
from os import path
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
if not path.exists(settings.XSLT_FILES_DIR):
raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist')
|
from django.conf import settings
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
Throw exception for not existing XSLT_FILES_DIR pathfrom django.conf import settings
from os import path
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
if not path.exists(settings.XSLT_FILES_DIR):
raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist')
|
<commit_before>from django.conf import settings
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
<commit_msg>Throw exception for not existing XSLT_FILES_DIR path<commit_after>from django.conf import settings
from os import path
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
if not path.exists(settings.XSLT_FILES_DIR):
raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist')
|
4063752757a97c444b8913947a0890f2c2387bca
|
numpy/array_api/_set_functions.py
|
numpy/array_api/_set_functions.py
|
from __future__ import annotations
from ._array_object import Array
from typing import Tuple, Union
import numpy as np
def unique(x: Array, /, *, return_counts: bool = False, return_index: bool = False, return_inverse: bool = False) -> Union[Array, Tuple[Array, ...]]:
"""
Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`.
See its docstring for more information.
"""
return Array._new(np.unique(x._array, return_counts=return_counts, return_index=return_index, return_inverse=return_inverse))
|
from __future__ import annotations
from ._array_object import Array
from typing import Tuple, Union
import numpy as np
def unique(x: Array, /, *, return_counts: bool = False, return_index: bool = False, return_inverse: bool = False) -> Union[Array, Tuple[Array, ...]]:
"""
Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`.
See its docstring for more information.
"""
res = np.unique(x._array, return_counts=return_counts,
return_index=return_index, return_inverse=return_inverse)
if isinstance(res, tuple):
return tuple(Array._new(i) for i in res)
return Array._new(res)
|
Fix the array API unique() function
|
Fix the array API unique() function
|
Python
|
bsd-3-clause
|
simongibbons/numpy,rgommers/numpy,numpy/numpy,numpy/numpy,charris/numpy,numpy/numpy,endolith/numpy,mattip/numpy,simongibbons/numpy,endolith/numpy,jakirkham/numpy,anntzer/numpy,seberg/numpy,anntzer/numpy,rgommers/numpy,mattip/numpy,pdebuyl/numpy,pdebuyl/numpy,mhvk/numpy,seberg/numpy,charris/numpy,seberg/numpy,endolith/numpy,pdebuyl/numpy,charris/numpy,endolith/numpy,mhvk/numpy,numpy/numpy,mhvk/numpy,anntzer/numpy,mattip/numpy,jakirkham/numpy,simongibbons/numpy,pdebuyl/numpy,rgommers/numpy,mhvk/numpy,jakirkham/numpy,simongibbons/numpy,simongibbons/numpy,anntzer/numpy,rgommers/numpy,seberg/numpy,charris/numpy,jakirkham/numpy,mattip/numpy,mhvk/numpy,jakirkham/numpy
|
from __future__ import annotations
from ._array_object import Array
from typing import Tuple, Union
import numpy as np
def unique(x: Array, /, *, return_counts: bool = False, return_index: bool = False, return_inverse: bool = False) -> Union[Array, Tuple[Array, ...]]:
"""
Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`.
See its docstring for more information.
"""
return Array._new(np.unique(x._array, return_counts=return_counts, return_index=return_index, return_inverse=return_inverse))
Fix the array API unique() function
|
from __future__ import annotations
from ._array_object import Array
from typing import Tuple, Union
import numpy as np
def unique(x: Array, /, *, return_counts: bool = False, return_index: bool = False, return_inverse: bool = False) -> Union[Array, Tuple[Array, ...]]:
"""
Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`.
See its docstring for more information.
"""
res = np.unique(x._array, return_counts=return_counts,
return_index=return_index, return_inverse=return_inverse)
if isinstance(res, tuple):
return tuple(Array._new(i) for i in res)
return Array._new(res)
|
<commit_before>from __future__ import annotations
from ._array_object import Array
from typing import Tuple, Union
import numpy as np
def unique(x: Array, /, *, return_counts: bool = False, return_index: bool = False, return_inverse: bool = False) -> Union[Array, Tuple[Array, ...]]:
"""
Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`.
See its docstring for more information.
"""
return Array._new(np.unique(x._array, return_counts=return_counts, return_index=return_index, return_inverse=return_inverse))
<commit_msg>Fix the array API unique() function<commit_after>
|
from __future__ import annotations
from ._array_object import Array
from typing import Tuple, Union
import numpy as np
def unique(x: Array, /, *, return_counts: bool = False, return_index: bool = False, return_inverse: bool = False) -> Union[Array, Tuple[Array, ...]]:
"""
Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`.
See its docstring for more information.
"""
res = np.unique(x._array, return_counts=return_counts,
return_index=return_index, return_inverse=return_inverse)
if isinstance(res, tuple):
return tuple(Array._new(i) for i in res)
return Array._new(res)
|
from __future__ import annotations
from ._array_object import Array
from typing import Tuple, Union
import numpy as np
def unique(x: Array, /, *, return_counts: bool = False, return_index: bool = False, return_inverse: bool = False) -> Union[Array, Tuple[Array, ...]]:
"""
Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`.
See its docstring for more information.
"""
return Array._new(np.unique(x._array, return_counts=return_counts, return_index=return_index, return_inverse=return_inverse))
Fix the array API unique() functionfrom __future__ import annotations
from ._array_object import Array
from typing import Tuple, Union
import numpy as np
def unique(x: Array, /, *, return_counts: bool = False, return_index: bool = False, return_inverse: bool = False) -> Union[Array, Tuple[Array, ...]]:
"""
Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`.
See its docstring for more information.
"""
res = np.unique(x._array, return_counts=return_counts,
return_index=return_index, return_inverse=return_inverse)
if isinstance(res, tuple):
return tuple(Array._new(i) for i in res)
return Array._new(res)
|
<commit_before>from __future__ import annotations
from ._array_object import Array
from typing import Tuple, Union
import numpy as np
def unique(x: Array, /, *, return_counts: bool = False, return_index: bool = False, return_inverse: bool = False) -> Union[Array, Tuple[Array, ...]]:
"""
Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`.
See its docstring for more information.
"""
return Array._new(np.unique(x._array, return_counts=return_counts, return_index=return_index, return_inverse=return_inverse))
<commit_msg>Fix the array API unique() function<commit_after>from __future__ import annotations
from ._array_object import Array
from typing import Tuple, Union
import numpy as np
def unique(x: Array, /, *, return_counts: bool = False, return_index: bool = False, return_inverse: bool = False) -> Union[Array, Tuple[Array, ...]]:
"""
Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`.
See its docstring for more information.
"""
res = np.unique(x._array, return_counts=return_counts,
return_index=return_index, return_inverse=return_inverse)
if isinstance(res, tuple):
return tuple(Array._new(i) for i in res)
return Array._new(res)
|
5c2ffba0f4200a4ba501de08adfbb88504f6252a
|
alg_selection_sort.py
|
alg_selection_sort.py
|
def selection_sort(a_list):
"""Selection Sort algortihm.
Concept:
- Find out the max item's original slot first,
- then swap it and the item at the max slot.
- Iterate the procedure for the next max, etc.
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
if a_list[slot] > a_list[select_slot]:
select_slot = slot
temp = a_list[max_slot]
a_list[max_slot] = a_list[select_slot]
a_list[select_slot] = temp
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By selection sort: ')
selection_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
|
def selection_sort(a_list):
"""Selection Sort algortihm.
Concept:
- Find out the max item's original slot first,
- then swap it and the item at the max slot.
- Iterate the procedure for the next max, etc.
Selection sort is more efficient than bubble sort
since the former does not swap for all successive pairs,
and just do one swapping for each iteration.
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
if a_list[slot] > a_list[select_slot]:
select_slot = slot
temp = a_list[max_slot]
a_list[max_slot] = a_list[select_slot]
a_list[select_slot] = temp
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By selection sort: ')
selection_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
|
Add comment about more efficient than bubble sort
|
Add comment about more efficient than bubble sort
|
Python
|
bsd-2-clause
|
bowen0701/algorithms_data_structures
|
def selection_sort(a_list):
"""Selection Sort algortihm.
Concept:
- Find out the max item's original slot first,
- then swap it and the item at the max slot.
- Iterate the procedure for the next max, etc.
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
if a_list[slot] > a_list[select_slot]:
select_slot = slot
temp = a_list[max_slot]
a_list[max_slot] = a_list[select_slot]
a_list[select_slot] = temp
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By selection sort: ')
selection_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
Add comment about more efficient than bubble sort
|
def selection_sort(a_list):
"""Selection Sort algortihm.
Concept:
- Find out the max item's original slot first,
- then swap it and the item at the max slot.
- Iterate the procedure for the next max, etc.
Selection sort is more efficient than bubble sort
since the former does not swap for all successive pairs,
and just do one swapping for each iteration.
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
if a_list[slot] > a_list[select_slot]:
select_slot = slot
temp = a_list[max_slot]
a_list[max_slot] = a_list[select_slot]
a_list[select_slot] = temp
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By selection sort: ')
selection_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
|
<commit_before>def selection_sort(a_list):
"""Selection Sort algortihm.
Concept:
- Find out the max item's original slot first,
- then swap it and the item at the max slot.
- Iterate the procedure for the next max, etc.
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
if a_list[slot] > a_list[select_slot]:
select_slot = slot
temp = a_list[max_slot]
a_list[max_slot] = a_list[select_slot]
a_list[select_slot] = temp
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By selection sort: ')
selection_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
<commit_msg>Add comment about more efficient than bubble sort<commit_after>
|
def selection_sort(a_list):
"""Selection Sort algortihm.
Concept:
- Find out the max item's original slot first,
- then swap it and the item at the max slot.
- Iterate the procedure for the next max, etc.
Selection sort is more efficient than bubble sort
since the former does not swap for all successive pairs,
and just do one swapping for each iteration.
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
if a_list[slot] > a_list[select_slot]:
select_slot = slot
temp = a_list[max_slot]
a_list[max_slot] = a_list[select_slot]
a_list[select_slot] = temp
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By selection sort: ')
selection_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
|
def selection_sort(a_list):
"""Selection Sort algortihm.
Concept:
- Find out the max item's original slot first,
- then swap it and the item at the max slot.
- Iterate the procedure for the next max, etc.
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
if a_list[slot] > a_list[select_slot]:
select_slot = slot
temp = a_list[max_slot]
a_list[max_slot] = a_list[select_slot]
a_list[select_slot] = temp
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By selection sort: ')
selection_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
Add comment about more efficient than bubble sortdef selection_sort(a_list):
"""Selection Sort algortihm.
Concept:
- Find out the max item's original slot first,
- then swap it and the item at the max slot.
- Iterate the procedure for the next max, etc.
Selection sort is more efficient than bubble sort
since the former does not swap for all successive pairs,
and just do one swapping for each iteration.
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
if a_list[slot] > a_list[select_slot]:
select_slot = slot
temp = a_list[max_slot]
a_list[max_slot] = a_list[select_slot]
a_list[select_slot] = temp
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By selection sort: ')
selection_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
|
<commit_before>def selection_sort(a_list):
"""Selection Sort algortihm.
Concept:
- Find out the max item's original slot first,
- then swap it and the item at the max slot.
- Iterate the procedure for the next max, etc.
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
if a_list[slot] > a_list[select_slot]:
select_slot = slot
temp = a_list[max_slot]
a_list[max_slot] = a_list[select_slot]
a_list[select_slot] = temp
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By selection sort: ')
selection_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
<commit_msg>Add comment about more efficient than bubble sort<commit_after>def selection_sort(a_list):
"""Selection Sort algortihm.
Concept:
- Find out the max item's original slot first,
- then swap it and the item at the max slot.
- Iterate the procedure for the next max, etc.
Selection sort is more efficient than bubble sort
since the former does not swap for all successive pairs,
and just do one swapping for each iteration.
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
if a_list[slot] > a_list[select_slot]:
select_slot = slot
temp = a_list[max_slot]
a_list[max_slot] = a_list[select_slot]
a_list[select_slot] = temp
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By selection sort: ')
selection_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
|
b4932c9e95b34a875c8d5234a1aa025aa5d5dad0
|
migrations/versions/07ebe99161d5_add_banner_image_url_to_sessio.py
|
migrations/versions/07ebe99161d5_add_banner_image_url_to_sessio.py
|
"""add banner_image_url field to session
Revision ID: 07ebe99161d5
Revises: d6b1904bea0e
Create Date: 2018-11-21 19:06:35.140390
"""
# revision identifiers, used by Alembic.
revision = '07ebe99161d5'
down_revision = 'd6b1904bea0e'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('session', sa.Column('banner_image_url', sa.Unicode(length=2000), nullable=True))
def downgrade():
op.drop_column('session', 'banner_image_url')
|
"""add banner_image_url field to session
Revision ID: 07ebe99161d5
Revises: 60a132ae73f1
Create Date: 2018-11-21 19:06:35.140390
"""
# revision identifiers, used by Alembic.
revision = '07ebe99161d5'
down_revision = '60a132ae73f1'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('session', sa.Column('banner_image_url', sa.Unicode(length=2000), nullable=True))
def downgrade():
op.drop_column('session', 'banner_image_url')
|
Update down_revision in migration file.
|
Update down_revision in migration file.
|
Python
|
agpl-3.0
|
hasgeek/funnel,hasgeek/funnel,hasgeek/funnel,hasgeek/funnel,hasgeek/funnel
|
"""add banner_image_url field to session
Revision ID: 07ebe99161d5
Revises: d6b1904bea0e
Create Date: 2018-11-21 19:06:35.140390
"""
# revision identifiers, used by Alembic.
revision = '07ebe99161d5'
down_revision = 'd6b1904bea0e'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('session', sa.Column('banner_image_url', sa.Unicode(length=2000), nullable=True))
def downgrade():
op.drop_column('session', 'banner_image_url')
Update down_revision in migration file.
|
"""add banner_image_url field to session
Revision ID: 07ebe99161d5
Revises: 60a132ae73f1
Create Date: 2018-11-21 19:06:35.140390
"""
# revision identifiers, used by Alembic.
revision = '07ebe99161d5'
down_revision = '60a132ae73f1'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('session', sa.Column('banner_image_url', sa.Unicode(length=2000), nullable=True))
def downgrade():
op.drop_column('session', 'banner_image_url')
|
<commit_before>"""add banner_image_url field to session
Revision ID: 07ebe99161d5
Revises: d6b1904bea0e
Create Date: 2018-11-21 19:06:35.140390
"""
# revision identifiers, used by Alembic.
revision = '07ebe99161d5'
down_revision = 'd6b1904bea0e'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('session', sa.Column('banner_image_url', sa.Unicode(length=2000), nullable=True))
def downgrade():
op.drop_column('session', 'banner_image_url')
<commit_msg>Update down_revision in migration file.<commit_after>
|
"""add banner_image_url field to session
Revision ID: 07ebe99161d5
Revises: 60a132ae73f1
Create Date: 2018-11-21 19:06:35.140390
"""
# revision identifiers, used by Alembic.
revision = '07ebe99161d5'
down_revision = '60a132ae73f1'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('session', sa.Column('banner_image_url', sa.Unicode(length=2000), nullable=True))
def downgrade():
op.drop_column('session', 'banner_image_url')
|
"""add banner_image_url field to session
Revision ID: 07ebe99161d5
Revises: d6b1904bea0e
Create Date: 2018-11-21 19:06:35.140390
"""
# revision identifiers, used by Alembic.
revision = '07ebe99161d5'
down_revision = 'd6b1904bea0e'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('session', sa.Column('banner_image_url', sa.Unicode(length=2000), nullable=True))
def downgrade():
op.drop_column('session', 'banner_image_url')
Update down_revision in migration file."""add banner_image_url field to session
Revision ID: 07ebe99161d5
Revises: 60a132ae73f1
Create Date: 2018-11-21 19:06:35.140390
"""
# revision identifiers, used by Alembic.
revision = '07ebe99161d5'
down_revision = '60a132ae73f1'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('session', sa.Column('banner_image_url', sa.Unicode(length=2000), nullable=True))
def downgrade():
op.drop_column('session', 'banner_image_url')
|
<commit_before>"""add banner_image_url field to session
Revision ID: 07ebe99161d5
Revises: d6b1904bea0e
Create Date: 2018-11-21 19:06:35.140390
"""
# revision identifiers, used by Alembic.
revision = '07ebe99161d5'
down_revision = 'd6b1904bea0e'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('session', sa.Column('banner_image_url', sa.Unicode(length=2000), nullable=True))
def downgrade():
op.drop_column('session', 'banner_image_url')
<commit_msg>Update down_revision in migration file.<commit_after>"""add banner_image_url field to session
Revision ID: 07ebe99161d5
Revises: 60a132ae73f1
Create Date: 2018-11-21 19:06:35.140390
"""
# revision identifiers, used by Alembic.
revision = '07ebe99161d5'
down_revision = '60a132ae73f1'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('session', sa.Column('banner_image_url', sa.Unicode(length=2000), nullable=True))
def downgrade():
op.drop_column('session', 'banner_image_url')
|
906803349e6a4c37311b73a25c1787716b69c17a
|
glaciertests/__init__.py
|
glaciertests/__init__.py
|
from glaciertests.util import GlacierTestsConfig
def purge_prefix_vaults():
conn = GlacierTestsConfig().connection()
all_vaults = conn.list_vaults()
for vault in all_vaults['VaultList']:
if vault['VaultName'].startswith(GlacierTestsConfig().prefix()):
conn.delete_vault(vault['VaultName'])
def setup():
purge_prefix_vaults()
def teardown():
purge_prefix_vaults()
|
from glaciertests.util import GlacierTestsConfig
def purge_prefix_vaults():
conn = GlacierTestsConfig().connection()
all_vaults = conn.list_vaults()
jobs = {}
for vault in all_vaults['VaultList']:
if vault['VaultName'].startswith(GlacierTestsConfig().prefix()):
# Try to delete and only schedule an inventory job if delete fails
try:
conn.delete_vault(vault['VaultName'])
except Exception as e:
jobs[vault['VaultName']] = enumerate_vault(vault['VaultName'],
conn)
while jobs:
remaining = {}
while jobs:
vault, job_id = jobs.popitem()
status = conn.describe_job(vault, job_id)
if status['Completed'] == 'false':
remaining[vault] = job_id
continue
resp = conn.get_job_output(vault, job_id)
for archive in resp['ArchiveList']:
conn.delete_archive(vault, archive['ArchiveId'])
jobs = remaining
def enumerate_vault(vault, conn):
job_data = {
'Type': 'inventory-retrieval',
}
result = conn.initiate_job(vault, job_data)
print(result)
return result['JobId']
def setup():
purge_prefix_vaults()
def teardown():
purge_prefix_vaults()
|
Remove vaults with data before and after tests.
|
Remove vaults with data before and after tests.
|
Python
|
mit
|
bouncestorage/glacier-tests,timuralp/glacier-tests,bouncestorage/glacier-tests,timuralp/glacier-tests
|
from glaciertests.util import GlacierTestsConfig
def purge_prefix_vaults():
conn = GlacierTestsConfig().connection()
all_vaults = conn.list_vaults()
for vault in all_vaults['VaultList']:
if vault['VaultName'].startswith(GlacierTestsConfig().prefix()):
conn.delete_vault(vault['VaultName'])
def setup():
purge_prefix_vaults()
def teardown():
purge_prefix_vaults()
Remove vaults with data before and after tests.
|
from glaciertests.util import GlacierTestsConfig
def purge_prefix_vaults():
conn = GlacierTestsConfig().connection()
all_vaults = conn.list_vaults()
jobs = {}
for vault in all_vaults['VaultList']:
if vault['VaultName'].startswith(GlacierTestsConfig().prefix()):
# Try to delete and only schedule an inventory job if delete fails
try:
conn.delete_vault(vault['VaultName'])
except Exception as e:
jobs[vault['VaultName']] = enumerate_vault(vault['VaultName'],
conn)
while jobs:
remaining = {}
while jobs:
vault, job_id = jobs.popitem()
status = conn.describe_job(vault, job_id)
if status['Completed'] == 'false':
remaining[vault] = job_id
continue
resp = conn.get_job_output(vault, job_id)
for archive in resp['ArchiveList']:
conn.delete_archive(vault, archive['ArchiveId'])
jobs = remaining
def enumerate_vault(vault, conn):
job_data = {
'Type': 'inventory-retrieval',
}
result = conn.initiate_job(vault, job_data)
print(result)
return result['JobId']
def setup():
purge_prefix_vaults()
def teardown():
purge_prefix_vaults()
|
<commit_before>from glaciertests.util import GlacierTestsConfig
def purge_prefix_vaults():
conn = GlacierTestsConfig().connection()
all_vaults = conn.list_vaults()
for vault in all_vaults['VaultList']:
if vault['VaultName'].startswith(GlacierTestsConfig().prefix()):
conn.delete_vault(vault['VaultName'])
def setup():
purge_prefix_vaults()
def teardown():
purge_prefix_vaults()
<commit_msg>Remove vaults with data before and after tests.<commit_after>
|
from glaciertests.util import GlacierTestsConfig
def purge_prefix_vaults():
conn = GlacierTestsConfig().connection()
all_vaults = conn.list_vaults()
jobs = {}
for vault in all_vaults['VaultList']:
if vault['VaultName'].startswith(GlacierTestsConfig().prefix()):
# Try to delete and only schedule an inventory job if delete fails
try:
conn.delete_vault(vault['VaultName'])
except Exception as e:
jobs[vault['VaultName']] = enumerate_vault(vault['VaultName'],
conn)
while jobs:
remaining = {}
while jobs:
vault, job_id = jobs.popitem()
status = conn.describe_job(vault, job_id)
if status['Completed'] == 'false':
remaining[vault] = job_id
continue
resp = conn.get_job_output(vault, job_id)
for archive in resp['ArchiveList']:
conn.delete_archive(vault, archive['ArchiveId'])
jobs = remaining
def enumerate_vault(vault, conn):
job_data = {
'Type': 'inventory-retrieval',
}
result = conn.initiate_job(vault, job_data)
print(result)
return result['JobId']
def setup():
purge_prefix_vaults()
def teardown():
purge_prefix_vaults()
|
from glaciertests.util import GlacierTestsConfig
def purge_prefix_vaults():
conn = GlacierTestsConfig().connection()
all_vaults = conn.list_vaults()
for vault in all_vaults['VaultList']:
if vault['VaultName'].startswith(GlacierTestsConfig().prefix()):
conn.delete_vault(vault['VaultName'])
def setup():
purge_prefix_vaults()
def teardown():
purge_prefix_vaults()
Remove vaults with data before and after tests.from glaciertests.util import GlacierTestsConfig
def purge_prefix_vaults():
conn = GlacierTestsConfig().connection()
all_vaults = conn.list_vaults()
jobs = {}
for vault in all_vaults['VaultList']:
if vault['VaultName'].startswith(GlacierTestsConfig().prefix()):
# Try to delete and only schedule an inventory job if delete fails
try:
conn.delete_vault(vault['VaultName'])
except Exception as e:
jobs[vault['VaultName']] = enumerate_vault(vault['VaultName'],
conn)
while jobs:
remaining = {}
while jobs:
vault, job_id = jobs.popitem()
status = conn.describe_job(vault, job_id)
if status['Completed'] == 'false':
remaining[vault] = job_id
continue
resp = conn.get_job_output(vault, job_id)
for archive in resp['ArchiveList']:
conn.delete_archive(vault, archive['ArchiveId'])
jobs = remaining
def enumerate_vault(vault, conn):
job_data = {
'Type': 'inventory-retrieval',
}
result = conn.initiate_job(vault, job_data)
print(result)
return result['JobId']
def setup():
purge_prefix_vaults()
def teardown():
purge_prefix_vaults()
|
<commit_before>from glaciertests.util import GlacierTestsConfig
def purge_prefix_vaults():
conn = GlacierTestsConfig().connection()
all_vaults = conn.list_vaults()
for vault in all_vaults['VaultList']:
if vault['VaultName'].startswith(GlacierTestsConfig().prefix()):
conn.delete_vault(vault['VaultName'])
def setup():
purge_prefix_vaults()
def teardown():
purge_prefix_vaults()
<commit_msg>Remove vaults with data before and after tests.<commit_after>from glaciertests.util import GlacierTestsConfig
def purge_prefix_vaults():
conn = GlacierTestsConfig().connection()
all_vaults = conn.list_vaults()
jobs = {}
for vault in all_vaults['VaultList']:
if vault['VaultName'].startswith(GlacierTestsConfig().prefix()):
# Try to delete and only schedule an inventory job if delete fails
try:
conn.delete_vault(vault['VaultName'])
except Exception as e:
jobs[vault['VaultName']] = enumerate_vault(vault['VaultName'],
conn)
while jobs:
remaining = {}
while jobs:
vault, job_id = jobs.popitem()
status = conn.describe_job(vault, job_id)
if status['Completed'] == 'false':
remaining[vault] = job_id
continue
resp = conn.get_job_output(vault, job_id)
for archive in resp['ArchiveList']:
conn.delete_archive(vault, archive['ArchiveId'])
jobs = remaining
def enumerate_vault(vault, conn):
job_data = {
'Type': 'inventory-retrieval',
}
result = conn.initiate_job(vault, job_data)
print(result)
return result['JobId']
def setup():
purge_prefix_vaults()
def teardown():
purge_prefix_vaults()
|
140dc4f38e3302a8478a721cbeb9176029689b38
|
Functions/template-python/lambda_function.py
|
Functions/template-python/lambda_function.py
|
"""Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
def lambda_handler(event, context):
print('LOG RequestId: {}\tResponse:\n\n{}'.format(
context.aws_request_id,
None
))
return None
# Comment or remove everything below before deploying to Lambda.
def local_testing():
import context
with open('event.json', 'r') as f:
event = loads(f.read())
print("Event:\n\n{}\n\nFunction Output:\n".format(
dumps(
event,
indent=4
)
))
lambda_handler(event, context)
local_testing()
|
"""Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
# Disable 'testing_locally' when deploying to AWS Lambda
testing_locally = True
verbose = True
class CWLogs(object):
def __init__(self, context):
self.context = context
def event(self, message, event_prefix='LOG'):
print('{} RequestId: {}\t{}'.format(
event_prefix,
self.context.aws_request_id,
message
))
def lambda_handler(event, context):
log = CWLogs(context)
if verbose is True:
log.event('Event: {}'.format(dumps(event)))
log.event('Hello World!')
return None
def local_test():
import context
with open('event.json', 'r') as f:
event = loads(f.read())
print('\nFunction Log:\n')
lambda_handler(event, context)
if testing_locally is True:
local_test()
|
Rewrite custom log format to a class, add verbosity, and vars for options.
|
Rewrite custom log format to a class, add verbosity, and vars for options.
|
Python
|
apache-2.0
|
andrewdefilippis/aws-lambda
|
"""Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
def lambda_handler(event, context):
print('LOG RequestId: {}\tResponse:\n\n{}'.format(
context.aws_request_id,
None
))
return None
# Comment or remove everything below before deploying to Lambda.
def local_testing():
import context
with open('event.json', 'r') as f:
event = loads(f.read())
print("Event:\n\n{}\n\nFunction Output:\n".format(
dumps(
event,
indent=4
)
))
lambda_handler(event, context)
local_testing()
Rewrite custom log format to a class, add verbosity, and vars for options.
|
"""Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
# Disable 'testing_locally' when deploying to AWS Lambda
testing_locally = True
verbose = True
class CWLogs(object):
def __init__(self, context):
self.context = context
def event(self, message, event_prefix='LOG'):
print('{} RequestId: {}\t{}'.format(
event_prefix,
self.context.aws_request_id,
message
))
def lambda_handler(event, context):
log = CWLogs(context)
if verbose is True:
log.event('Event: {}'.format(dumps(event)))
log.event('Hello World!')
return None
def local_test():
import context
with open('event.json', 'r') as f:
event = loads(f.read())
print('\nFunction Log:\n')
lambda_handler(event, context)
if testing_locally is True:
local_test()
|
<commit_before>"""Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
def lambda_handler(event, context):
print('LOG RequestId: {}\tResponse:\n\n{}'.format(
context.aws_request_id,
None
))
return None
# Comment or remove everything below before deploying to Lambda.
def local_testing():
import context
with open('event.json', 'r') as f:
event = loads(f.read())
print("Event:\n\n{}\n\nFunction Output:\n".format(
dumps(
event,
indent=4
)
))
lambda_handler(event, context)
local_testing()
<commit_msg>Rewrite custom log format to a class, add verbosity, and vars for options.<commit_after>
|
"""Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
# Disable 'testing_locally' when deploying to AWS Lambda
testing_locally = True
verbose = True
class CWLogs(object):
def __init__(self, context):
self.context = context
def event(self, message, event_prefix='LOG'):
print('{} RequestId: {}\t{}'.format(
event_prefix,
self.context.aws_request_id,
message
))
def lambda_handler(event, context):
log = CWLogs(context)
if verbose is True:
log.event('Event: {}'.format(dumps(event)))
log.event('Hello World!')
return None
def local_test():
import context
with open('event.json', 'r') as f:
event = loads(f.read())
print('\nFunction Log:\n')
lambda_handler(event, context)
if testing_locally is True:
local_test()
|
"""Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
def lambda_handler(event, context):
print('LOG RequestId: {}\tResponse:\n\n{}'.format(
context.aws_request_id,
None
))
return None
# Comment or remove everything below before deploying to Lambda.
def local_testing():
import context
with open('event.json', 'r') as f:
event = loads(f.read())
print("Event:\n\n{}\n\nFunction Output:\n".format(
dumps(
event,
indent=4
)
))
lambda_handler(event, context)
local_testing()
Rewrite custom log format to a class, add verbosity, and vars for options."""Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
# Disable 'testing_locally' when deploying to AWS Lambda
testing_locally = True
verbose = True
class CWLogs(object):
def __init__(self, context):
self.context = context
def event(self, message, event_prefix='LOG'):
print('{} RequestId: {}\t{}'.format(
event_prefix,
self.context.aws_request_id,
message
))
def lambda_handler(event, context):
log = CWLogs(context)
if verbose is True:
log.event('Event: {}'.format(dumps(event)))
log.event('Hello World!')
return None
def local_test():
import context
with open('event.json', 'r') as f:
event = loads(f.read())
print('\nFunction Log:\n')
lambda_handler(event, context)
if testing_locally is True:
local_test()
|
<commit_before>"""Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
def lambda_handler(event, context):
print('LOG RequestId: {}\tResponse:\n\n{}'.format(
context.aws_request_id,
None
))
return None
# Comment or remove everything below before deploying to Lambda.
def local_testing():
import context
with open('event.json', 'r') as f:
event = loads(f.read())
print("Event:\n\n{}\n\nFunction Output:\n".format(
dumps(
event,
indent=4
)
))
lambda_handler(event, context)
local_testing()
<commit_msg>Rewrite custom log format to a class, add verbosity, and vars for options.<commit_after>"""Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
# Disable 'testing_locally' when deploying to AWS Lambda
testing_locally = True
verbose = True
class CWLogs(object):
def __init__(self, context):
self.context = context
def event(self, message, event_prefix='LOG'):
print('{} RequestId: {}\t{}'.format(
event_prefix,
self.context.aws_request_id,
message
))
def lambda_handler(event, context):
log = CWLogs(context)
if verbose is True:
log.event('Event: {}'.format(dumps(event)))
log.event('Hello World!')
return None
def local_test():
import context
with open('event.json', 'r') as f:
event = loads(f.read())
print('\nFunction Log:\n')
lambda_handler(event, context)
if testing_locally is True:
local_test()
|
1f5f821ac464e9986025988f6c306c742dd842fa
|
Instanssi/ext_blog/templatetags/blog_tags.py
|
Instanssi/ext_blog/templatetags/blog_tags.py
|
# -*- coding: utf-8 -*-
from django import template
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
entries = BlogEntry.objects.filter(event_id=int(event_id), public=True)
return {'entries': entries}
@register.inclusion_tag('ext_blog/blog_rss_tag.html')
def render_blog_rss_tag(event_id):
return {'event_id': event_id}
|
# -*- coding: utf-8 -*-
from django import template
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
entries = BlogEntry.objects.filter(event_id=int(event_id), public=True)
return {'entries': entries}
@register.inclusion_tag('ext_blog/blog_rss_tag.html')
def render_blog_rss_tag(event_id):
return {'event_id': event_id}
@register.simple_tag
def blog_rss_url(event_id):
return 'http://instanssi.org/blog/'+str(event_id)+'/rss/'
|
Tag for getting a valid RSS feed url for event.
|
ext_blog: Tag for getting a valid RSS feed url for event.
|
Python
|
mit
|
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
|
# -*- coding: utf-8 -*-
from django import template
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
entries = BlogEntry.objects.filter(event_id=int(event_id), public=True)
return {'entries': entries}
@register.inclusion_tag('ext_blog/blog_rss_tag.html')
def render_blog_rss_tag(event_id):
return {'event_id': event_id}ext_blog: Tag for getting a valid RSS feed url for event.
|
# -*- coding: utf-8 -*-
from django import template
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
entries = BlogEntry.objects.filter(event_id=int(event_id), public=True)
return {'entries': entries}
@register.inclusion_tag('ext_blog/blog_rss_tag.html')
def render_blog_rss_tag(event_id):
return {'event_id': event_id}
@register.simple_tag
def blog_rss_url(event_id):
return 'http://instanssi.org/blog/'+str(event_id)+'/rss/'
|
<commit_before># -*- coding: utf-8 -*-
from django import template
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
entries = BlogEntry.objects.filter(event_id=int(event_id), public=True)
return {'entries': entries}
@register.inclusion_tag('ext_blog/blog_rss_tag.html')
def render_blog_rss_tag(event_id):
return {'event_id': event_id}<commit_msg>ext_blog: Tag for getting a valid RSS feed url for event.<commit_after>
|
# -*- coding: utf-8 -*-
from django import template
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
entries = BlogEntry.objects.filter(event_id=int(event_id), public=True)
return {'entries': entries}
@register.inclusion_tag('ext_blog/blog_rss_tag.html')
def render_blog_rss_tag(event_id):
return {'event_id': event_id}
@register.simple_tag
def blog_rss_url(event_id):
return 'http://instanssi.org/blog/'+str(event_id)+'/rss/'
|
# -*- coding: utf-8 -*-
from django import template
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
entries = BlogEntry.objects.filter(event_id=int(event_id), public=True)
return {'entries': entries}
@register.inclusion_tag('ext_blog/blog_rss_tag.html')
def render_blog_rss_tag(event_id):
return {'event_id': event_id}ext_blog: Tag for getting a valid RSS feed url for event.# -*- coding: utf-8 -*-
from django import template
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
entries = BlogEntry.objects.filter(event_id=int(event_id), public=True)
return {'entries': entries}
@register.inclusion_tag('ext_blog/blog_rss_tag.html')
def render_blog_rss_tag(event_id):
return {'event_id': event_id}
@register.simple_tag
def blog_rss_url(event_id):
return 'http://instanssi.org/blog/'+str(event_id)+'/rss/'
|
<commit_before># -*- coding: utf-8 -*-
from django import template
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
entries = BlogEntry.objects.filter(event_id=int(event_id), public=True)
return {'entries': entries}
@register.inclusion_tag('ext_blog/blog_rss_tag.html')
def render_blog_rss_tag(event_id):
return {'event_id': event_id}<commit_msg>ext_blog: Tag for getting a valid RSS feed url for event.<commit_after># -*- coding: utf-8 -*-
from django import template
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
entries = BlogEntry.objects.filter(event_id=int(event_id), public=True)
return {'entries': entries}
@register.inclusion_tag('ext_blog/blog_rss_tag.html')
def render_blog_rss_tag(event_id):
return {'event_id': event_id}
@register.simple_tag
def blog_rss_url(event_id):
return 'http://instanssi.org/blog/'+str(event_id)+'/rss/'
|
5cfcf2615e46fc3ef550159e38dc51c7362543af
|
readux/books/management/commands/web_export.py
|
readux/books/management/commands/web_export.py
|
from eulfedora.server import Repository
from django.core.management.base import BaseCommand
import shutil
from readux.books import annotate, export
from readux.books.models import Volume
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
parser.add_argument('--static', action='store_true', default=False,
help='Generate built (static) site instead of jekyll site')
def handle(self, *args, **options):
print args
repo = Repository()
for pid in options['pid']:
vol = repo.get_object(pid, type=Volume)
tei = annotate.annotated_tei(vol.generate_volume_tei(),
vol.annotations())
zipfile = export.website(vol, tei, static=options['static'])
zipfilename = '%s-annotated-site.zip' % pid
shutil.copyfile(zipfile.name, zipfilename)
print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)
|
from eulfedora.server import Repository
from eulxml.xmlmap import load_xmlobject_from_file
from django.core.management.base import BaseCommand
import shutil
from readux.books import annotate, export
from readux.books.models import Volume
from readux.books.tei import Facsimile
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
parser.add_argument('--static', action='store_true', default=False,
help='Generate built (static) site instead of jekyll site')
parser.add_argument('--tei',
help='Use the specified TEI file instead of generating it')
def handle(self, *args, **options):
print args
repo = Repository()
for pid in options['pid']:
vol = repo.get_object(pid, type=Volume)
if options['tei']:
tei = load_xmlobject_from_file(options['tei'], Facsimile)
else:
tei = annotate.annotated_tei(vol.generate_volume_tei(),
vol.annotations())
zipfile = export.website(vol, tei, static=options['static'])
zipfilename = '%s-annotated-site.zip' % vol.noid
shutil.copyfile(zipfile.name, zipfilename)
print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)
|
Add an option to pass in generated TEI, for speed & troubleshooting
|
Add an option to pass in generated TEI, for speed & troubleshooting
|
Python
|
apache-2.0
|
emory-libraries/readux,emory-libraries/readux,emory-libraries/readux
|
from eulfedora.server import Repository
from django.core.management.base import BaseCommand
import shutil
from readux.books import annotate, export
from readux.books.models import Volume
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
parser.add_argument('--static', action='store_true', default=False,
help='Generate built (static) site instead of jekyll site')
def handle(self, *args, **options):
print args
repo = Repository()
for pid in options['pid']:
vol = repo.get_object(pid, type=Volume)
tei = annotate.annotated_tei(vol.generate_volume_tei(),
vol.annotations())
zipfile = export.website(vol, tei, static=options['static'])
zipfilename = '%s-annotated-site.zip' % pid
shutil.copyfile(zipfile.name, zipfilename)
print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)
Add an option to pass in generated TEI, for speed & troubleshooting
|
from eulfedora.server import Repository
from eulxml.xmlmap import load_xmlobject_from_file
from django.core.management.base import BaseCommand
import shutil
from readux.books import annotate, export
from readux.books.models import Volume
from readux.books.tei import Facsimile
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
parser.add_argument('--static', action='store_true', default=False,
help='Generate built (static) site instead of jekyll site')
parser.add_argument('--tei',
help='Use the specified TEI file instead of generating it')
def handle(self, *args, **options):
print args
repo = Repository()
for pid in options['pid']:
vol = repo.get_object(pid, type=Volume)
if options['tei']:
tei = load_xmlobject_from_file(options['tei'], Facsimile)
else:
tei = annotate.annotated_tei(vol.generate_volume_tei(),
vol.annotations())
zipfile = export.website(vol, tei, static=options['static'])
zipfilename = '%s-annotated-site.zip' % vol.noid
shutil.copyfile(zipfile.name, zipfilename)
print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)
|
<commit_before>from eulfedora.server import Repository
from django.core.management.base import BaseCommand
import shutil
from readux.books import annotate, export
from readux.books.models import Volume
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
parser.add_argument('--static', action='store_true', default=False,
help='Generate built (static) site instead of jekyll site')
def handle(self, *args, **options):
print args
repo = Repository()
for pid in options['pid']:
vol = repo.get_object(pid, type=Volume)
tei = annotate.annotated_tei(vol.generate_volume_tei(),
vol.annotations())
zipfile = export.website(vol, tei, static=options['static'])
zipfilename = '%s-annotated-site.zip' % pid
shutil.copyfile(zipfile.name, zipfilename)
print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)
<commit_msg>Add an option to pass in generated TEI, for speed & troubleshooting<commit_after>
|
from eulfedora.server import Repository
from eulxml.xmlmap import load_xmlobject_from_file
from django.core.management.base import BaseCommand
import shutil
from readux.books import annotate, export
from readux.books.models import Volume
from readux.books.tei import Facsimile
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
parser.add_argument('--static', action='store_true', default=False,
help='Generate built (static) site instead of jekyll site')
parser.add_argument('--tei',
help='Use the specified TEI file instead of generating it')
def handle(self, *args, **options):
print args
repo = Repository()
for pid in options['pid']:
vol = repo.get_object(pid, type=Volume)
if options['tei']:
tei = load_xmlobject_from_file(options['tei'], Facsimile)
else:
tei = annotate.annotated_tei(vol.generate_volume_tei(),
vol.annotations())
zipfile = export.website(vol, tei, static=options['static'])
zipfilename = '%s-annotated-site.zip' % vol.noid
shutil.copyfile(zipfile.name, zipfilename)
print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)
|
from eulfedora.server import Repository
from django.core.management.base import BaseCommand
import shutil
from readux.books import annotate, export
from readux.books.models import Volume
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
parser.add_argument('--static', action='store_true', default=False,
help='Generate built (static) site instead of jekyll site')
def handle(self, *args, **options):
print args
repo = Repository()
for pid in options['pid']:
vol = repo.get_object(pid, type=Volume)
tei = annotate.annotated_tei(vol.generate_volume_tei(),
vol.annotations())
zipfile = export.website(vol, tei, static=options['static'])
zipfilename = '%s-annotated-site.zip' % pid
shutil.copyfile(zipfile.name, zipfilename)
print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)
Add an option to pass in generated TEI, for speed & troubleshootingfrom eulfedora.server import Repository
from eulxml.xmlmap import load_xmlobject_from_file
from django.core.management.base import BaseCommand
import shutil
from readux.books import annotate, export
from readux.books.models import Volume
from readux.books.tei import Facsimile
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
parser.add_argument('--static', action='store_true', default=False,
help='Generate built (static) site instead of jekyll site')
parser.add_argument('--tei',
help='Use the specified TEI file instead of generating it')
def handle(self, *args, **options):
print args
repo = Repository()
for pid in options['pid']:
vol = repo.get_object(pid, type=Volume)
if options['tei']:
tei = load_xmlobject_from_file(options['tei'], Facsimile)
else:
tei = annotate.annotated_tei(vol.generate_volume_tei(),
vol.annotations())
zipfile = export.website(vol, tei, static=options['static'])
zipfilename = '%s-annotated-site.zip' % vol.noid
shutil.copyfile(zipfile.name, zipfilename)
print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)
|
<commit_before>from eulfedora.server import Repository
from django.core.management.base import BaseCommand
import shutil
from readux.books import annotate, export
from readux.books.models import Volume
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
parser.add_argument('--static', action='store_true', default=False,
help='Generate built (static) site instead of jekyll site')
def handle(self, *args, **options):
print args
repo = Repository()
for pid in options['pid']:
vol = repo.get_object(pid, type=Volume)
tei = annotate.annotated_tei(vol.generate_volume_tei(),
vol.annotations())
zipfile = export.website(vol, tei, static=options['static'])
zipfilename = '%s-annotated-site.zip' % pid
shutil.copyfile(zipfile.name, zipfilename)
print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)
<commit_msg>Add an option to pass in generated TEI, for speed & troubleshooting<commit_after>from eulfedora.server import Repository
from eulxml.xmlmap import load_xmlobject_from_file
from django.core.management.base import BaseCommand
import shutil
from readux.books import annotate, export
from readux.books.models import Volume
from readux.books.tei import Facsimile
class Command(BaseCommand):
help = 'Construct web export of an annotated volume'
def add_arguments(self, parser):
parser.add_argument('pid', nargs='+', type=str)
parser.add_argument('--static', action='store_true', default=False,
help='Generate built (static) site instead of jekyll site')
parser.add_argument('--tei',
help='Use the specified TEI file instead of generating it')
def handle(self, *args, **options):
print args
repo = Repository()
for pid in options['pid']:
vol = repo.get_object(pid, type=Volume)
if options['tei']:
tei = load_xmlobject_from_file(options['tei'], Facsimile)
else:
tei = annotate.annotated_tei(vol.generate_volume_tei(),
vol.annotations())
zipfile = export.website(vol, tei, static=options['static'])
zipfilename = '%s-annotated-site.zip' % vol.noid
shutil.copyfile(zipfile.name, zipfilename)
print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)
|
b009c40b8cdefaa39c39851b873caa49873527bd
|
learning_journal/models.py
|
learning_journal/models.py
|
import datetime
import psycopg2
from sqlalchemy import (
Column,
DateTime,
Integer,
Unicode,
UnicodeText,
ForeignKey,
)
from pyramid.security import Allow, Everyone
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class Entry(Base):
"""Our Journal Entry class."""
__tablename__ = 'entries'
id = Column(Integer, primary_key=True)
title = Column(Unicode(128), unique=True)
text = Column(UnicodeText)
created = Column(DateTime, default=datetime.datetime.utcnow)
author_id = Column(Integer, ForeignKey('users.id'))
#Ties User model to Entry model
author = relationship('User', back_populates='entries')
@property
def __acl__(self):
"""Add permissions for specific instance of Entry object.
self.author.username is the user who created this Entry instance.
"""
return [
(Allow, Everyone, 'view'),
(Allow, self.author.username, 'edit')
]
|
import datetime
import psycopg2
from sqlalchemy import (
Column,
DateTime,
Integer,
Unicode,
UnicodeText,
ForeignKey,
)
from pyramid.security import Allow, Everyone
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class Entry(Base):
"""Our Journal Entry class."""
__tablename__ = 'entries'
id = Column(Integer, primary_key=True)
title = Column(Unicode(128), unique=True)
text = Column(UnicodeText)
created = Column(DateTime, default=datetime.datetime.utcnow)
@property
def __acl__(self):
"""Add permissions for specific instance of Entry object.
self.author.username is the user who created this Entry instance.
"""
return [
(Allow, Everyone, 'view'),
(Allow, self.author.username, 'edit')
]
|
Remove references to User class
|
Remove references to User class
|
Python
|
mit
|
DZwell/learning_journal,DZwell/learning_journal,DZwell/learning_journal
|
import datetime
import psycopg2
from sqlalchemy import (
Column,
DateTime,
Integer,
Unicode,
UnicodeText,
ForeignKey,
)
from pyramid.security import Allow, Everyone
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class Entry(Base):
"""Our Journal Entry class."""
__tablename__ = 'entries'
id = Column(Integer, primary_key=True)
title = Column(Unicode(128), unique=True)
text = Column(UnicodeText)
created = Column(DateTime, default=datetime.datetime.utcnow)
author_id = Column(Integer, ForeignKey('users.id'))
#Ties User model to Entry model
author = relationship('User', back_populates='entries')
@property
def __acl__(self):
"""Add permissions for specific instance of Entry object.
self.author.username is the user who created this Entry instance.
"""
return [
(Allow, Everyone, 'view'),
(Allow, self.author.username, 'edit')
]
Remove references to User class
|
import datetime
import psycopg2
from sqlalchemy import (
Column,
DateTime,
Integer,
Unicode,
UnicodeText,
ForeignKey,
)
from pyramid.security import Allow, Everyone
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class Entry(Base):
"""Our Journal Entry class."""
__tablename__ = 'entries'
id = Column(Integer, primary_key=True)
title = Column(Unicode(128), unique=True)
text = Column(UnicodeText)
created = Column(DateTime, default=datetime.datetime.utcnow)
@property
def __acl__(self):
"""Add permissions for specific instance of Entry object.
self.author.username is the user who created this Entry instance.
"""
return [
(Allow, Everyone, 'view'),
(Allow, self.author.username, 'edit')
]
|
<commit_before>import datetime
import psycopg2
from sqlalchemy import (
Column,
DateTime,
Integer,
Unicode,
UnicodeText,
ForeignKey,
)
from pyramid.security import Allow, Everyone
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class Entry(Base):
"""Our Journal Entry class."""
__tablename__ = 'entries'
id = Column(Integer, primary_key=True)
title = Column(Unicode(128), unique=True)
text = Column(UnicodeText)
created = Column(DateTime, default=datetime.datetime.utcnow)
author_id = Column(Integer, ForeignKey('users.id'))
#Ties User model to Entry model
author = relationship('User', back_populates='entries')
@property
def __acl__(self):
"""Add permissions for specific instance of Entry object.
self.author.username is the user who created this Entry instance.
"""
return [
(Allow, Everyone, 'view'),
(Allow, self.author.username, 'edit')
]
<commit_msg>Remove references to User class<commit_after>
|
import datetime
import psycopg2
from sqlalchemy import (
Column,
DateTime,
Integer,
Unicode,
UnicodeText,
ForeignKey,
)
from pyramid.security import Allow, Everyone
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class Entry(Base):
"""Our Journal Entry class."""
__tablename__ = 'entries'
id = Column(Integer, primary_key=True)
title = Column(Unicode(128), unique=True)
text = Column(UnicodeText)
created = Column(DateTime, default=datetime.datetime.utcnow)
@property
def __acl__(self):
"""Add permissions for specific instance of Entry object.
self.author.username is the user who created this Entry instance.
"""
return [
(Allow, Everyone, 'view'),
(Allow, self.author.username, 'edit')
]
|
import datetime
import psycopg2
from sqlalchemy import (
Column,
DateTime,
Integer,
Unicode,
UnicodeText,
ForeignKey,
)
from pyramid.security import Allow, Everyone
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class Entry(Base):
"""Our Journal Entry class."""
__tablename__ = 'entries'
id = Column(Integer, primary_key=True)
title = Column(Unicode(128), unique=True)
text = Column(UnicodeText)
created = Column(DateTime, default=datetime.datetime.utcnow)
author_id = Column(Integer, ForeignKey('users.id'))
#Ties User model to Entry model
author = relationship('User', back_populates='entries')
@property
def __acl__(self):
"""Add permissions for specific instance of Entry object.
self.author.username is the user who created this Entry instance.
"""
return [
(Allow, Everyone, 'view'),
(Allow, self.author.username, 'edit')
]
Remove references to User classimport datetime
import psycopg2
from sqlalchemy import (
Column,
DateTime,
Integer,
Unicode,
UnicodeText,
ForeignKey,
)
from pyramid.security import Allow, Everyone
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class Entry(Base):
"""Our Journal Entry class."""
__tablename__ = 'entries'
id = Column(Integer, primary_key=True)
title = Column(Unicode(128), unique=True)
text = Column(UnicodeText)
created = Column(DateTime, default=datetime.datetime.utcnow)
@property
def __acl__(self):
"""Add permissions for specific instance of Entry object.
self.author.username is the user who created this Entry instance.
"""
return [
(Allow, Everyone, 'view'),
(Allow, self.author.username, 'edit')
]
|
<commit_before>import datetime
import psycopg2
from sqlalchemy import (
Column,
DateTime,
Integer,
Unicode,
UnicodeText,
ForeignKey,
)
from pyramid.security import Allow, Everyone
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class Entry(Base):
"""Our Journal Entry class."""
__tablename__ = 'entries'
id = Column(Integer, primary_key=True)
title = Column(Unicode(128), unique=True)
text = Column(UnicodeText)
created = Column(DateTime, default=datetime.datetime.utcnow)
author_id = Column(Integer, ForeignKey('users.id'))
#Ties User model to Entry model
author = relationship('User', back_populates='entries')
@property
def __acl__(self):
"""Add permissions for specific instance of Entry object.
self.author.username is the user who created this Entry instance.
"""
return [
(Allow, Everyone, 'view'),
(Allow, self.author.username, 'edit')
]
<commit_msg>Remove references to User class<commit_after>import datetime
import psycopg2
from sqlalchemy import (
Column,
DateTime,
Integer,
Unicode,
UnicodeText,
ForeignKey,
)
from pyramid.security import Allow, Everyone
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class Entry(Base):
"""Our Journal Entry class."""
__tablename__ = 'entries'
id = Column(Integer, primary_key=True)
title = Column(Unicode(128), unique=True)
text = Column(UnicodeText)
created = Column(DateTime, default=datetime.datetime.utcnow)
@property
def __acl__(self):
"""Add permissions for specific instance of Entry object.
self.author.username is the user who created this Entry instance.
"""
return [
(Allow, Everyone, 'view'),
(Allow, self.author.username, 'edit')
]
|
1ec8f02236c50f2d150daa9211701d2c91c7dfe1
|
paper_to_git/utilities/general.py
|
paper_to_git/utilities/general.py
|
"""
"""
from string import Template
from paper_to_git.config import config
__all__ = [
'generate_metadata',
]
METADATA_TEMPLATE = Template("""\
---
title: $title
date: $date
---
""")
def generate_metadata(doc, metadata_type=None):
"""
Generate the appropriate metadata based on the type specified.
"""
if metadata_type is None:
metadata_type = config.metadata.type
if metadata_type == "yaml":
return generate_yaml_metadata(doc)
raise NotImplementedError
def generate_yaml_metadata(doc):
"""
Generate the YAML metadata to add on top of a PaperDoc when moving a
PaperDoc to a static site generator.
"""
return METADATA_TEMPLATE.safe_substitute(title=doc.title,
date=doc.last_updated)
|
"""
"""
from string import Template
from paper_to_git.config import config
__all__ = [
'generate_metadata',
]
METADATA_TEMPLATE = Template("""\
---
title: "$title"
date: "$date"
---
""")
def generate_metadata(doc, metadata_type=None):
"""
Generate the appropriate metadata based on the type specified.
"""
if metadata_type is None:
metadata_type = config.metadata.type
if metadata_type == "yaml":
return generate_yaml_metadata(doc)
raise NotImplementedError
def generate_yaml_metadata(doc):
"""
Generate the YAML metadata to add on top of a PaperDoc when moving a
PaperDoc to a static site generator.
"""
return METADATA_TEMPLATE.safe_substitute(title=doc.title,
date=doc.last_updated)
|
Fix the metadata for posts.
|
Fix the metadata for posts.
|
Python
|
apache-2.0
|
maxking/paper-to-git,maxking/paper-to-git
|
"""
"""
from string import Template
from paper_to_git.config import config
__all__ = [
'generate_metadata',
]
METADATA_TEMPLATE = Template("""\
---
title: $title
date: $date
---
""")
def generate_metadata(doc, metadata_type=None):
"""
Generate the appropriate metadata based on the type specified.
"""
if metadata_type is None:
metadata_type = config.metadata.type
if metadata_type == "yaml":
return generate_yaml_metadata(doc)
raise NotImplementedError
def generate_yaml_metadata(doc):
"""
Generate the YAML metadata to add on top of a PaperDoc when moving a
PaperDoc to a static site generator.
"""
return METADATA_TEMPLATE.safe_substitute(title=doc.title,
date=doc.last_updated)
Fix the metadata for posts.
|
"""
"""
from string import Template
from paper_to_git.config import config
__all__ = [
'generate_metadata',
]
METADATA_TEMPLATE = Template("""\
---
title: "$title"
date: "$date"
---
""")
def generate_metadata(doc, metadata_type=None):
"""
Generate the appropriate metadata based on the type specified.
"""
if metadata_type is None:
metadata_type = config.metadata.type
if metadata_type == "yaml":
return generate_yaml_metadata(doc)
raise NotImplementedError
def generate_yaml_metadata(doc):
"""
Generate the YAML metadata to add on top of a PaperDoc when moving a
PaperDoc to a static site generator.
"""
return METADATA_TEMPLATE.safe_substitute(title=doc.title,
date=doc.last_updated)
|
<commit_before>"""
"""
from string import Template
from paper_to_git.config import config
__all__ = [
'generate_metadata',
]
METADATA_TEMPLATE = Template("""\
---
title: $title
date: $date
---
""")
def generate_metadata(doc, metadata_type=None):
"""
Generate the appropriate metadata based on the type specified.
"""
if metadata_type is None:
metadata_type = config.metadata.type
if metadata_type == "yaml":
return generate_yaml_metadata(doc)
raise NotImplementedError
def generate_yaml_metadata(doc):
"""
Generate the YAML metadata to add on top of a PaperDoc when moving a
PaperDoc to a static site generator.
"""
return METADATA_TEMPLATE.safe_substitute(title=doc.title,
date=doc.last_updated)
<commit_msg>Fix the metadata for posts.<commit_after>
|
"""
"""
from string import Template
from paper_to_git.config import config
__all__ = [
'generate_metadata',
]
METADATA_TEMPLATE = Template("""\
---
title: "$title"
date: "$date"
---
""")
def generate_metadata(doc, metadata_type=None):
"""
Generate the appropriate metadata based on the type specified.
"""
if metadata_type is None:
metadata_type = config.metadata.type
if metadata_type == "yaml":
return generate_yaml_metadata(doc)
raise NotImplementedError
def generate_yaml_metadata(doc):
"""
Generate the YAML metadata to add on top of a PaperDoc when moving a
PaperDoc to a static site generator.
"""
return METADATA_TEMPLATE.safe_substitute(title=doc.title,
date=doc.last_updated)
|
"""
"""
from string import Template
from paper_to_git.config import config
__all__ = [
'generate_metadata',
]
METADATA_TEMPLATE = Template("""\
---
title: $title
date: $date
---
""")
def generate_metadata(doc, metadata_type=None):
"""
Generate the appropriate metadata based on the type specified.
"""
if metadata_type is None:
metadata_type = config.metadata.type
if metadata_type == "yaml":
return generate_yaml_metadata(doc)
raise NotImplementedError
def generate_yaml_metadata(doc):
"""
Generate the YAML metadata to add on top of a PaperDoc when moving a
PaperDoc to a static site generator.
"""
return METADATA_TEMPLATE.safe_substitute(title=doc.title,
date=doc.last_updated)
Fix the metadata for posts."""
"""
from string import Template
from paper_to_git.config import config
__all__ = [
'generate_metadata',
]
METADATA_TEMPLATE = Template("""\
---
title: "$title"
date: "$date"
---
""")
def generate_metadata(doc, metadata_type=None):
"""
Generate the appropriate metadata based on the type specified.
"""
if metadata_type is None:
metadata_type = config.metadata.type
if metadata_type == "yaml":
return generate_yaml_metadata(doc)
raise NotImplementedError
def generate_yaml_metadata(doc):
"""
Generate the YAML metadata to add on top of a PaperDoc when moving a
PaperDoc to a static site generator.
"""
return METADATA_TEMPLATE.safe_substitute(title=doc.title,
date=doc.last_updated)
|
<commit_before>"""
"""
from string import Template
from paper_to_git.config import config
__all__ = [
'generate_metadata',
]
METADATA_TEMPLATE = Template("""\
---
title: $title
date: $date
---
""")
def generate_metadata(doc, metadata_type=None):
"""
Generate the appropriate metadata based on the type specified.
"""
if metadata_type is None:
metadata_type = config.metadata.type
if metadata_type == "yaml":
return generate_yaml_metadata(doc)
raise NotImplementedError
def generate_yaml_metadata(doc):
"""
Generate the YAML metadata to add on top of a PaperDoc when moving a
PaperDoc to a static site generator.
"""
return METADATA_TEMPLATE.safe_substitute(title=doc.title,
date=doc.last_updated)
<commit_msg>Fix the metadata for posts.<commit_after>"""
"""
from string import Template
from paper_to_git.config import config
__all__ = [
'generate_metadata',
]
METADATA_TEMPLATE = Template("""\
---
title: "$title"
date: "$date"
---
""")
def generate_metadata(doc, metadata_type=None):
"""
Generate the appropriate metadata based on the type specified.
"""
if metadata_type is None:
metadata_type = config.metadata.type
if metadata_type == "yaml":
return generate_yaml_metadata(doc)
raise NotImplementedError
def generate_yaml_metadata(doc):
"""
Generate the YAML metadata to add on top of a PaperDoc when moving a
PaperDoc to a static site generator.
"""
return METADATA_TEMPLATE.safe_substitute(title=doc.title,
date=doc.last_updated)
|
536bdc4e3ca9c68621d518cdaea8b119301f2dc3
|
plugins/linux/lxde_set_wallpaper.py
|
plugins/linux/lxde_set_wallpaper.py
|
import os
import sys
from .. import SetWallpaper
class LXDESetWallpaper(SetWallpaper):
def __init__(self, config):
super(LXDESetWallpaper, self).__init__(config)
def platform_check(self):
return sys.platform == 'linux2' and self.config['linux.desktop-environment'] == 'lxde'
def set(self):
os.system('pcmanfm --set-wallpaper=%s')
if not self.config['keep']:
logging.warning("LXDESetWallpaper works better if you configure "
"the keep plugin (e.g. --keep=2)")
|
import sys
from .. import SetWallpaper
class LXDESetWallpaper(SetWallpaper):
def __init__(self, config):
super(LXDESetWallpaper, self).__init__(config)
self.cycle = 0
def platform_check(self):
return sys.platform == 'linux2' and self.config['linux.desktop-environment'] == 'lxde'
def set(self):
import os
# TODO: Find a better solution than cycling
# - Cause: --set-wallpaper doesn't reload the file if the arguments are the same
os.system(\
'pcmanfm --set-wallpaper=%s --wallpaper-mode=%s' % (self.config['wallpaper'], 'fit' if self.cycle % 2 else 'center'))
self.cycle += 1
|
Revert "Conforming LXDESetWallpaper plugin to conform with keep option (DarwinSetWallpaper), also FastForward merge"
|
Revert "Conforming LXDESetWallpaper plugin to conform with keep option (DarwinSetWallpaper), also FastForward merge"
This reverts commit 7212d223fe95d3042348bb29d9bd353308be2347.
I really should learn to test before I push to github.
|
Python
|
mit
|
loktacar/wallpapermaker
|
import os
import sys
from .. import SetWallpaper
class LXDESetWallpaper(SetWallpaper):
def __init__(self, config):
super(LXDESetWallpaper, self).__init__(config)
def platform_check(self):
return sys.platform == 'linux2' and self.config['linux.desktop-environment'] == 'lxde'
def set(self):
os.system('pcmanfm --set-wallpaper=%s')
if not self.config['keep']:
logging.warning("LXDESetWallpaper works better if you configure "
"the keep plugin (e.g. --keep=2)")
Revert "Conforming LXDESetWallpaper plugin to conform with keep option (DarwinSetWallpaper), also FastForward merge"
This reverts commit 7212d223fe95d3042348bb29d9bd353308be2347.
I really should learn to test before I push to github.
|
import sys
from .. import SetWallpaper
class LXDESetWallpaper(SetWallpaper):
def __init__(self, config):
super(LXDESetWallpaper, self).__init__(config)
self.cycle = 0
def platform_check(self):
return sys.platform == 'linux2' and self.config['linux.desktop-environment'] == 'lxde'
def set(self):
import os
# TODO: Find a better solution than cycling
# - Cause: --set-wallpaper doesn't reload the file if the arguments are the same
os.system(\
'pcmanfm --set-wallpaper=%s --wallpaper-mode=%s' % (self.config['wallpaper'], 'fit' if self.cycle % 2 else 'center'))
self.cycle += 1
|
<commit_before>import os
import sys
from .. import SetWallpaper
class LXDESetWallpaper(SetWallpaper):
def __init__(self, config):
super(LXDESetWallpaper, self).__init__(config)
def platform_check(self):
return sys.platform == 'linux2' and self.config['linux.desktop-environment'] == 'lxde'
def set(self):
os.system('pcmanfm --set-wallpaper=%s')
if not self.config['keep']:
logging.warning("LXDESetWallpaper works better if you configure "
"the keep plugin (e.g. --keep=2)")
<commit_msg>Revert "Conforming LXDESetWallpaper plugin to conform with keep option (DarwinSetWallpaper), also FastForward merge"
This reverts commit 7212d223fe95d3042348bb29d9bd353308be2347.
I really should learn to test before I push to github.<commit_after>
|
import sys
from .. import SetWallpaper
class LXDESetWallpaper(SetWallpaper):
def __init__(self, config):
super(LXDESetWallpaper, self).__init__(config)
self.cycle = 0
def platform_check(self):
return sys.platform == 'linux2' and self.config['linux.desktop-environment'] == 'lxde'
def set(self):
import os
# TODO: Find a better solution than cycling
# - Cause: --set-wallpaper doesn't reload the file if the arguments are the same
os.system(\
'pcmanfm --set-wallpaper=%s --wallpaper-mode=%s' % (self.config['wallpaper'], 'fit' if self.cycle % 2 else 'center'))
self.cycle += 1
|
import os
import sys
from .. import SetWallpaper
class LXDESetWallpaper(SetWallpaper):
def __init__(self, config):
super(LXDESetWallpaper, self).__init__(config)
def platform_check(self):
return sys.platform == 'linux2' and self.config['linux.desktop-environment'] == 'lxde'
def set(self):
os.system('pcmanfm --set-wallpaper=%s')
if not self.config['keep']:
logging.warning("LXDESetWallpaper works better if you configure "
"the keep plugin (e.g. --keep=2)")
Revert "Conforming LXDESetWallpaper plugin to conform with keep option (DarwinSetWallpaper), also FastForward merge"
This reverts commit 7212d223fe95d3042348bb29d9bd353308be2347.
I really should learn to test before I push to github.import sys
from .. import SetWallpaper
class LXDESetWallpaper(SetWallpaper):
def __init__(self, config):
super(LXDESetWallpaper, self).__init__(config)
self.cycle = 0
def platform_check(self):
return sys.platform == 'linux2' and self.config['linux.desktop-environment'] == 'lxde'
def set(self):
import os
# TODO: Find a better solution than cycling
# - Cause: --set-wallpaper doesn't reload the file if the arguments are the same
os.system(\
'pcmanfm --set-wallpaper=%s --wallpaper-mode=%s' % (self.config['wallpaper'], 'fit' if self.cycle % 2 else 'center'))
self.cycle += 1
|
<commit_before>import os
import sys
from .. import SetWallpaper
class LXDESetWallpaper(SetWallpaper):
def __init__(self, config):
super(LXDESetWallpaper, self).__init__(config)
def platform_check(self):
return sys.platform == 'linux2' and self.config['linux.desktop-environment'] == 'lxde'
def set(self):
os.system('pcmanfm --set-wallpaper=%s')
if not self.config['keep']:
logging.warning("LXDESetWallpaper works better if you configure "
"the keep plugin (e.g. --keep=2)")
<commit_msg>Revert "Conforming LXDESetWallpaper plugin to conform with keep option (DarwinSetWallpaper), also FastForward merge"
This reverts commit 7212d223fe95d3042348bb29d9bd353308be2347.
I really should learn to test before I push to github.<commit_after>import sys
from .. import SetWallpaper
class LXDESetWallpaper(SetWallpaper):
def __init__(self, config):
super(LXDESetWallpaper, self).__init__(config)
self.cycle = 0
def platform_check(self):
return sys.platform == 'linux2' and self.config['linux.desktop-environment'] == 'lxde'
def set(self):
import os
# TODO: Find a better solution than cycling
# - Cause: --set-wallpaper doesn't reload the file if the arguments are the same
os.system(\
'pcmanfm --set-wallpaper=%s --wallpaper-mode=%s' % (self.config['wallpaper'], 'fit' if self.cycle % 2 else 'center'))
self.cycle += 1
|
1f793395eab5a8e5b90a16e8db18d9c2869eae2f
|
tests/main.py
|
tests/main.py
|
pytest_plugins = 'pytester'
# TODO: we don't actually _need_ new-style outer classes, do we...no Spec
# any longer!
# TODO: trailing underscore stripping
class FileCollection:
def only_loads_dot_py_files(self, testdir):
testdir.makepyfile(somefile="""
def hello_how_are_you():
pass
""")
testdir.makefile('.txt', someotherfile="whatever")
stdout = testdir.runpytest("-v").stdout.str()
# TODO: find it hard to believe pytest lacks strong "x in y" string
# testing, but I cannot find any outside of fnmatch_lines (which is
# specific to this testdir stuff, and also lacks an opposite...)
assert "somefile.py::hello_how_are_you" in stdout
assert "whatever.txt" not in stdout
|
pytest_plugins = 'pytester'
# TODO: we don't actually _need_ new-style outer classes, do we...no Spec
# any longer!
# TODO: trailing underscore stripping
class FileCollection:
def only_loads_dot_py_files(self, testdir):
testdir.makepyfile(somefile="""
def hello_how_are_you():
pass
""")
testdir.makefile('.txt', someotherfile="whatever")
stdout = testdir.runpytest("-v").stdout.str()
# TODO: find it hard to believe pytest lacks strong "x in y" string
# testing, but I cannot find any outside of fnmatch_lines (which is
# specific to this testdir stuff, and also lacks an opposite...)
assert "somefile.py::hello_how_are_you" in stdout
# This wouldn't actually even happen; we'd get an ImportError instead
# as pytest tries importing 'someotherfile'. But eh.
assert "whatever.txt" not in stdout
def skips_underscored_files(self, testdir):
testdir.makepyfile(hastests="""
from _util import helper
def hello_how_are_you():
helper()
""")
testdir.makepyfile(_util="""
def helper():
pass
""")
# TODO: why Result.str() and not str(Result)? Seems unPythonic
stdout = testdir.runpytest("-v").stdout.str()
assert "hastests.py::hello_how_are_you" in stdout
assert "_util.py" not in stdout
def does_not_consume_conftest_files(self, testdir):
testdir.makepyfile(mytests="""
def hello_how_are_you():
pass
""")
testdir.makepyfile(conftest="""
def this_does_nothing_useful():
pass
""")
stdout = testdir.runpytest("-v").stdout.str()
assert "mytests.py::hello_how_are_you" in stdout
assert "conftest.py" not in stdout
|
Implement basic file selection tests
|
Implement basic file selection tests
|
Python
|
bsd-2-clause
|
bitprophet/pytest-relaxed
|
pytest_plugins = 'pytester'
# TODO: we don't actually _need_ new-style outer classes, do we...no Spec
# any longer!
# TODO: trailing underscore stripping
class FileCollection:
def only_loads_dot_py_files(self, testdir):
testdir.makepyfile(somefile="""
def hello_how_are_you():
pass
""")
testdir.makefile('.txt', someotherfile="whatever")
stdout = testdir.runpytest("-v").stdout.str()
# TODO: find it hard to believe pytest lacks strong "x in y" string
# testing, but I cannot find any outside of fnmatch_lines (which is
# specific to this testdir stuff, and also lacks an opposite...)
assert "somefile.py::hello_how_are_you" in stdout
assert "whatever.txt" not in stdout
Implement basic file selection tests
|
pytest_plugins = 'pytester'
# TODO: we don't actually _need_ new-style outer classes, do we...no Spec
# any longer!
# TODO: trailing underscore stripping
class FileCollection:
def only_loads_dot_py_files(self, testdir):
testdir.makepyfile(somefile="""
def hello_how_are_you():
pass
""")
testdir.makefile('.txt', someotherfile="whatever")
stdout = testdir.runpytest("-v").stdout.str()
# TODO: find it hard to believe pytest lacks strong "x in y" string
# testing, but I cannot find any outside of fnmatch_lines (which is
# specific to this testdir stuff, and also lacks an opposite...)
assert "somefile.py::hello_how_are_you" in stdout
# This wouldn't actually even happen; we'd get an ImportError instead
# as pytest tries importing 'someotherfile'. But eh.
assert "whatever.txt" not in stdout
def skips_underscored_files(self, testdir):
testdir.makepyfile(hastests="""
from _util import helper
def hello_how_are_you():
helper()
""")
testdir.makepyfile(_util="""
def helper():
pass
""")
# TODO: why Result.str() and not str(Result)? Seems unPythonic
stdout = testdir.runpytest("-v").stdout.str()
assert "hastests.py::hello_how_are_you" in stdout
assert "_util.py" not in stdout
def does_not_consume_conftest_files(self, testdir):
testdir.makepyfile(mytests="""
def hello_how_are_you():
pass
""")
testdir.makepyfile(conftest="""
def this_does_nothing_useful():
pass
""")
stdout = testdir.runpytest("-v").stdout.str()
assert "mytests.py::hello_how_are_you" in stdout
assert "conftest.py" not in stdout
|
<commit_before>pytest_plugins = 'pytester'
# TODO: we don't actually _need_ new-style outer classes, do we...no Spec
# any longer!
# TODO: trailing underscore stripping
class FileCollection:
def only_loads_dot_py_files(self, testdir):
testdir.makepyfile(somefile="""
def hello_how_are_you():
pass
""")
testdir.makefile('.txt', someotherfile="whatever")
stdout = testdir.runpytest("-v").stdout.str()
# TODO: find it hard to believe pytest lacks strong "x in y" string
# testing, but I cannot find any outside of fnmatch_lines (which is
# specific to this testdir stuff, and also lacks an opposite...)
assert "somefile.py::hello_how_are_you" in stdout
assert "whatever.txt" not in stdout
<commit_msg>Implement basic file selection tests<commit_after>
|
pytest_plugins = 'pytester'
# TODO: we don't actually _need_ new-style outer classes, do we...no Spec
# any longer!
# TODO: trailing underscore stripping
class FileCollection:
def only_loads_dot_py_files(self, testdir):
testdir.makepyfile(somefile="""
def hello_how_are_you():
pass
""")
testdir.makefile('.txt', someotherfile="whatever")
stdout = testdir.runpytest("-v").stdout.str()
# TODO: find it hard to believe pytest lacks strong "x in y" string
# testing, but I cannot find any outside of fnmatch_lines (which is
# specific to this testdir stuff, and also lacks an opposite...)
assert "somefile.py::hello_how_are_you" in stdout
# This wouldn't actually even happen; we'd get an ImportError instead
# as pytest tries importing 'someotherfile'. But eh.
assert "whatever.txt" not in stdout
def skips_underscored_files(self, testdir):
testdir.makepyfile(hastests="""
from _util import helper
def hello_how_are_you():
helper()
""")
testdir.makepyfile(_util="""
def helper():
pass
""")
# TODO: why Result.str() and not str(Result)? Seems unPythonic
stdout = testdir.runpytest("-v").stdout.str()
assert "hastests.py::hello_how_are_you" in stdout
assert "_util.py" not in stdout
def does_not_consume_conftest_files(self, testdir):
testdir.makepyfile(mytests="""
def hello_how_are_you():
pass
""")
testdir.makepyfile(conftest="""
def this_does_nothing_useful():
pass
""")
stdout = testdir.runpytest("-v").stdout.str()
assert "mytests.py::hello_how_are_you" in stdout
assert "conftest.py" not in stdout
|
pytest_plugins = 'pytester'
# TODO: we don't actually _need_ new-style outer classes, do we...no Spec
# any longer!
# TODO: trailing underscore stripping
class FileCollection:
def only_loads_dot_py_files(self, testdir):
testdir.makepyfile(somefile="""
def hello_how_are_you():
pass
""")
testdir.makefile('.txt', someotherfile="whatever")
stdout = testdir.runpytest("-v").stdout.str()
# TODO: find it hard to believe pytest lacks strong "x in y" string
# testing, but I cannot find any outside of fnmatch_lines (which is
# specific to this testdir stuff, and also lacks an opposite...)
assert "somefile.py::hello_how_are_you" in stdout
assert "whatever.txt" not in stdout
Implement basic file selection testspytest_plugins = 'pytester'
# TODO: we don't actually _need_ new-style outer classes, do we...no Spec
# any longer!
# TODO: trailing underscore stripping
class FileCollection:
def only_loads_dot_py_files(self, testdir):
testdir.makepyfile(somefile="""
def hello_how_are_you():
pass
""")
testdir.makefile('.txt', someotherfile="whatever")
stdout = testdir.runpytest("-v").stdout.str()
# TODO: find it hard to believe pytest lacks strong "x in y" string
# testing, but I cannot find any outside of fnmatch_lines (which is
# specific to this testdir stuff, and also lacks an opposite...)
assert "somefile.py::hello_how_are_you" in stdout
# This wouldn't actually even happen; we'd get an ImportError instead
# as pytest tries importing 'someotherfile'. But eh.
assert "whatever.txt" not in stdout
def skips_underscored_files(self, testdir):
testdir.makepyfile(hastests="""
from _util import helper
def hello_how_are_you():
helper()
""")
testdir.makepyfile(_util="""
def helper():
pass
""")
# TODO: why Result.str() and not str(Result)? Seems unPythonic
stdout = testdir.runpytest("-v").stdout.str()
assert "hastests.py::hello_how_are_you" in stdout
assert "_util.py" not in stdout
def does_not_consume_conftest_files(self, testdir):
testdir.makepyfile(mytests="""
def hello_how_are_you():
pass
""")
testdir.makepyfile(conftest="""
def this_does_nothing_useful():
pass
""")
stdout = testdir.runpytest("-v").stdout.str()
assert "mytests.py::hello_how_are_you" in stdout
assert "conftest.py" not in stdout
|
<commit_before>pytest_plugins = 'pytester'
# TODO: we don't actually _need_ new-style outer classes, do we...no Spec
# any longer!
# TODO: trailing underscore stripping
class FileCollection:
def only_loads_dot_py_files(self, testdir):
testdir.makepyfile(somefile="""
def hello_how_are_you():
pass
""")
testdir.makefile('.txt', someotherfile="whatever")
stdout = testdir.runpytest("-v").stdout.str()
# TODO: find it hard to believe pytest lacks strong "x in y" string
# testing, but I cannot find any outside of fnmatch_lines (which is
# specific to this testdir stuff, and also lacks an opposite...)
assert "somefile.py::hello_how_are_you" in stdout
assert "whatever.txt" not in stdout
<commit_msg>Implement basic file selection tests<commit_after>pytest_plugins = 'pytester'
# TODO: we don't actually _need_ new-style outer classes, do we...no Spec
# any longer!
# TODO: trailing underscore stripping
class FileCollection:
def only_loads_dot_py_files(self, testdir):
testdir.makepyfile(somefile="""
def hello_how_are_you():
pass
""")
testdir.makefile('.txt', someotherfile="whatever")
stdout = testdir.runpytest("-v").stdout.str()
# TODO: find it hard to believe pytest lacks strong "x in y" string
# testing, but I cannot find any outside of fnmatch_lines (which is
# specific to this testdir stuff, and also lacks an opposite...)
assert "somefile.py::hello_how_are_you" in stdout
# This wouldn't actually even happen; we'd get an ImportError instead
# as pytest tries importing 'someotherfile'. But eh.
assert "whatever.txt" not in stdout
def skips_underscored_files(self, testdir):
testdir.makepyfile(hastests="""
from _util import helper
def hello_how_are_you():
helper()
""")
testdir.makepyfile(_util="""
def helper():
pass
""")
# TODO: why Result.str() and not str(Result)? Seems unPythonic
stdout = testdir.runpytest("-v").stdout.str()
assert "hastests.py::hello_how_are_you" in stdout
assert "_util.py" not in stdout
def does_not_consume_conftest_files(self, testdir):
testdir.makepyfile(mytests="""
def hello_how_are_you():
pass
""")
testdir.makepyfile(conftest="""
def this_does_nothing_useful():
pass
""")
stdout = testdir.runpytest("-v").stdout.str()
assert "mytests.py::hello_how_are_you" in stdout
assert "conftest.py" not in stdout
|
728dac0dc05395f89cfe57995b85a39022981fff
|
chrome/test/mini_installer/uninstall_chrome.py
|
chrome/test/mini_installer/uninstall_chrome.py
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import subprocess
# TODO(sukolsak): This should read the uninstall command from the registry and
# run that instead.
subprocess.call('mini_installer.exe --uninstall --multi-install --chrome',
shell=True)
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Uninstall Chrome.
This script reads the uninstall command from registry, calls it, and verifies
the output status code.
"""
import _winreg
import argparse
import subprocess
import sys
def main():
parser = argparse.ArgumentParser(description='Uninstall Chrome.')
parser.add_argument('--system-level', dest='system_level',
action='store_const', const=True, default=False,
help='Uninstall Chrome at system level.')
args = parser.parse_args()
# TODO(sukolsak): Add support for uninstalling MSI-based Chrome installs when
# we support testing MSIs.
if args.system_level:
root_key = _winreg.HKEY_LOCAL_MACHINE
else:
root_key = _winreg.HKEY_CURRENT_USER
sub_key = ('SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\'
'Google Chrome')
key = _winreg.OpenKey(root_key, sub_key, 0, _winreg.KEY_QUERY_VALUE)
uninstall_string, _ = _winreg.QueryValueEx(key, 'UninstallString')
exit_status = subprocess.call(uninstall_string, shell=True)
# The exit status for successful uninstallation of Chrome is 19 (see
# chrome/installer/util/util_constants.h).
if exit_status != 19:
raise Exception('Could not uninstall Chrome. The installer exited with '
'status %d.' % exit_status)
return 0
if __name__ == '__main__':
sys.exit(main())
|
Automate uninstallation of Chrome by running the uninstall command from the registry.
|
Automate uninstallation of Chrome by running the uninstall command from the registry.
NOTRY=True
BUG=264859
TEST=
1) Uninstall Chrome.
2) Put mini_installer.exe in the same folder as test_installer.py.
3) Run "python test_installer.py config\config.config".
4) The script will install Chrome and then uninstall Chrome. At each state, it will check that chrome.exe exists (or doesn't exist). You should see output similar to the following:
"Test: clean -> install chrome -> chrome_installed -> uninstall chrome -> clean ... ok
----------------------------------------------------------------------
Ran 1 test in 12.345s"
Review URL: https://chromiumcodereview.appspot.com/22815017
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@218797 0039d316-1c4b-4281-b951-d872f2087c98
|
Python
|
bsd-3-clause
|
jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,mogoweb/chromium-crosswalk,Just-D/chromium-1,M4sse/chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,dednal/chromium.src,ltilve/chromium,dednal/chromium.src,markYoungH/chromium.src,ltilve/chromium,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,dednal/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,Jonekee/chromium.src,littlstar/chromium.src,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,littlstar/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,patrickm/chromium.src,anirudhSK/chromium,mogoweb/chromium-crosswalk,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,axinging/chromium-crosswalk,anirudhSK/chromium,anirudhSK/chromium,anirudhSK/chromium,hgl888/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,mogoweb/chromium-crosswalk,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,M4sse/chromium.src,ltilve/chromium,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,jaruba/chromium.src,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,dushu1203/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,Jonekee/chromium.src,jaruba/chromium.src,patrickm/chromium.src,anirudhSK/chromium,Chilledheart/chromium,fujunwei/chromium-crosswalk,jaruba/chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,patrickm/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,ondra-novak/chromium.src,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,M4sse/chromium.src,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,ondra-novak/chromium.src,littlstar/chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,M4sse/chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,ltilve/chromium,Fireblend/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,Jonekee/chromium.src,patrickm/chromium.src,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,patrickm/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,Jonekee/chromium.src,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,dednal/chromium.src,anirudhSK/chromium,chuan9/chromium-crosswalk,patrickm/chromium.src,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,anirudhSK/chromium,ondra-novak/chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,Chilledheart/chromium,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,Just-D/chromium-1,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,Just-D/chromium-1,bright-sparks/chromium-spacewalk,ltilve/chromium,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,ltilve/chromium,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,anirudhSK/chromium,M4sse/chromium.src,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,ChromiumWebApps/chromium,ltilve/chromium,mogoweb/chromium-crosswalk,Just-D/chromium-1,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk,ltilve/chromium,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,littlstar/chromium.src,chuan9/chromium-crosswalk,patrickm/chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,Chilledheart/chromium,Fireblend/chromium-crosswalk,dushu1203/chromium.src,Just-D/chromium-1,bright-sparks/chromium-spacewalk,M4sse/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,anirudhSK/chromium,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,ChromiumWebApps/chromium,Chilledheart/chromium,jaruba/chromium.src
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import subprocess
# TODO(sukolsak): This should read the uninstall command from the registry and
# run that instead.
subprocess.call('mini_installer.exe --uninstall --multi-install --chrome',
shell=True)
Automate uninstallation of Chrome by running the uninstall command from the registry.
NOTRY=True
BUG=264859
TEST=
1) Uninstall Chrome.
2) Put mini_installer.exe in the same folder as test_installer.py.
3) Run "python test_installer.py config\config.config".
4) The script will install Chrome and then uninstall Chrome. At each state, it will check that chrome.exe exists (or doesn't exist). You should see output similar to the following:
"Test: clean -> install chrome -> chrome_installed -> uninstall chrome -> clean ... ok
----------------------------------------------------------------------
Ran 1 test in 12.345s"
Review URL: https://chromiumcodereview.appspot.com/22815017
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@218797 0039d316-1c4b-4281-b951-d872f2087c98
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Uninstall Chrome.
This script reads the uninstall command from registry, calls it, and verifies
the output status code.
"""
import _winreg
import argparse
import subprocess
import sys
def main():
parser = argparse.ArgumentParser(description='Uninstall Chrome.')
parser.add_argument('--system-level', dest='system_level',
action='store_const', const=True, default=False,
help='Uninstall Chrome at system level.')
args = parser.parse_args()
# TODO(sukolsak): Add support for uninstalling MSI-based Chrome installs when
# we support testing MSIs.
if args.system_level:
root_key = _winreg.HKEY_LOCAL_MACHINE
else:
root_key = _winreg.HKEY_CURRENT_USER
sub_key = ('SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\'
'Google Chrome')
key = _winreg.OpenKey(root_key, sub_key, 0, _winreg.KEY_QUERY_VALUE)
uninstall_string, _ = _winreg.QueryValueEx(key, 'UninstallString')
exit_status = subprocess.call(uninstall_string, shell=True)
# The exit status for successful uninstallation of Chrome is 19 (see
# chrome/installer/util/util_constants.h).
if exit_status != 19:
raise Exception('Could not uninstall Chrome. The installer exited with '
'status %d.' % exit_status)
return 0
if __name__ == '__main__':
sys.exit(main())
|
<commit_before># Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import subprocess
# TODO(sukolsak): This should read the uninstall command from the registry and
# run that instead.
subprocess.call('mini_installer.exe --uninstall --multi-install --chrome',
shell=True)
<commit_msg>Automate uninstallation of Chrome by running the uninstall command from the registry.
NOTRY=True
BUG=264859
TEST=
1) Uninstall Chrome.
2) Put mini_installer.exe in the same folder as test_installer.py.
3) Run "python test_installer.py config\config.config".
4) The script will install Chrome and then uninstall Chrome. At each state, it will check that chrome.exe exists (or doesn't exist). You should see output similar to the following:
"Test: clean -> install chrome -> chrome_installed -> uninstall chrome -> clean ... ok
----------------------------------------------------------------------
Ran 1 test in 12.345s"
Review URL: https://chromiumcodereview.appspot.com/22815017
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@218797 0039d316-1c4b-4281-b951-d872f2087c98<commit_after>
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Uninstall Chrome.
This script reads the uninstall command from registry, calls it, and verifies
the output status code.
"""
import _winreg
import argparse
import subprocess
import sys
def main():
parser = argparse.ArgumentParser(description='Uninstall Chrome.')
parser.add_argument('--system-level', dest='system_level',
action='store_const', const=True, default=False,
help='Uninstall Chrome at system level.')
args = parser.parse_args()
# TODO(sukolsak): Add support for uninstalling MSI-based Chrome installs when
# we support testing MSIs.
if args.system_level:
root_key = _winreg.HKEY_LOCAL_MACHINE
else:
root_key = _winreg.HKEY_CURRENT_USER
sub_key = ('SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\'
'Google Chrome')
key = _winreg.OpenKey(root_key, sub_key, 0, _winreg.KEY_QUERY_VALUE)
uninstall_string, _ = _winreg.QueryValueEx(key, 'UninstallString')
exit_status = subprocess.call(uninstall_string, shell=True)
# The exit status for successful uninstallation of Chrome is 19 (see
# chrome/installer/util/util_constants.h).
if exit_status != 19:
raise Exception('Could not uninstall Chrome. The installer exited with '
'status %d.' % exit_status)
return 0
if __name__ == '__main__':
sys.exit(main())
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import subprocess
# TODO(sukolsak): This should read the uninstall command from the registry and
# run that instead.
subprocess.call('mini_installer.exe --uninstall --multi-install --chrome',
shell=True)
Automate uninstallation of Chrome by running the uninstall command from the registry.
NOTRY=True
BUG=264859
TEST=
1) Uninstall Chrome.
2) Put mini_installer.exe in the same folder as test_installer.py.
3) Run "python test_installer.py config\config.config".
4) The script will install Chrome and then uninstall Chrome. At each state, it will check that chrome.exe exists (or doesn't exist). You should see output similar to the following:
"Test: clean -> install chrome -> chrome_installed -> uninstall chrome -> clean ... ok
----------------------------------------------------------------------
Ran 1 test in 12.345s"
Review URL: https://chromiumcodereview.appspot.com/22815017
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@218797 0039d316-1c4b-4281-b951-d872f2087c98# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Uninstall Chrome.
This script reads the uninstall command from registry, calls it, and verifies
the output status code.
"""
import _winreg
import argparse
import subprocess
import sys
def main():
parser = argparse.ArgumentParser(description='Uninstall Chrome.')
parser.add_argument('--system-level', dest='system_level',
action='store_const', const=True, default=False,
help='Uninstall Chrome at system level.')
args = parser.parse_args()
# TODO(sukolsak): Add support for uninstalling MSI-based Chrome installs when
# we support testing MSIs.
if args.system_level:
root_key = _winreg.HKEY_LOCAL_MACHINE
else:
root_key = _winreg.HKEY_CURRENT_USER
sub_key = ('SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\'
'Google Chrome')
key = _winreg.OpenKey(root_key, sub_key, 0, _winreg.KEY_QUERY_VALUE)
uninstall_string, _ = _winreg.QueryValueEx(key, 'UninstallString')
exit_status = subprocess.call(uninstall_string, shell=True)
# The exit status for successful uninstallation of Chrome is 19 (see
# chrome/installer/util/util_constants.h).
if exit_status != 19:
raise Exception('Could not uninstall Chrome. The installer exited with '
'status %d.' % exit_status)
return 0
if __name__ == '__main__':
sys.exit(main())
|
<commit_before># Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import subprocess
# TODO(sukolsak): This should read the uninstall command from the registry and
# run that instead.
subprocess.call('mini_installer.exe --uninstall --multi-install --chrome',
shell=True)
<commit_msg>Automate uninstallation of Chrome by running the uninstall command from the registry.
NOTRY=True
BUG=264859
TEST=
1) Uninstall Chrome.
2) Put mini_installer.exe in the same folder as test_installer.py.
3) Run "python test_installer.py config\config.config".
4) The script will install Chrome and then uninstall Chrome. At each state, it will check that chrome.exe exists (or doesn't exist). You should see output similar to the following:
"Test: clean -> install chrome -> chrome_installed -> uninstall chrome -> clean ... ok
----------------------------------------------------------------------
Ran 1 test in 12.345s"
Review URL: https://chromiumcodereview.appspot.com/22815017
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@218797 0039d316-1c4b-4281-b951-d872f2087c98<commit_after># Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Uninstall Chrome.
This script reads the uninstall command from registry, calls it, and verifies
the output status code.
"""
import _winreg
import argparse
import subprocess
import sys
def main():
parser = argparse.ArgumentParser(description='Uninstall Chrome.')
parser.add_argument('--system-level', dest='system_level',
action='store_const', const=True, default=False,
help='Uninstall Chrome at system level.')
args = parser.parse_args()
# TODO(sukolsak): Add support for uninstalling MSI-based Chrome installs when
# we support testing MSIs.
if args.system_level:
root_key = _winreg.HKEY_LOCAL_MACHINE
else:
root_key = _winreg.HKEY_CURRENT_USER
sub_key = ('SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\'
'Google Chrome')
key = _winreg.OpenKey(root_key, sub_key, 0, _winreg.KEY_QUERY_VALUE)
uninstall_string, _ = _winreg.QueryValueEx(key, 'UninstallString')
exit_status = subprocess.call(uninstall_string, shell=True)
# The exit status for successful uninstallation of Chrome is 19 (see
# chrome/installer/util/util_constants.h).
if exit_status != 19:
raise Exception('Could not uninstall Chrome. The installer exited with '
'status %d.' % exit_status)
return 0
if __name__ == '__main__':
sys.exit(main())
|
48426b63bd4123ed6f63a38f3e4e2b401cd5c188
|
planetstack/core/models/__init__.py
|
planetstack/core/models/__init__.py
|
from .plcorebase import PlCoreBase
from .planetstack import PlanetStack
from .project import Project
from .singletonmodel import SingletonModel
from .service import Service
from .service import ServiceAttribute
from .tag import Tag
from .role import Role
from .site import Site,Deployment, DeploymentRole, DeploymentPrivilege, SiteDeployments
from .dashboard import DashboardView
from .user import User, UserDashboardView
from .serviceclass import ServiceClass
from .slice import Slice, SliceDeployments
from .site import SitePrivilege, SiteDeployments
from .userdeployments import UserDeployments
from .image import Image, ImageDeployments
from .node import Node
from .serviceresource import ServiceResource
from .slice import SliceRole
from .slice import SlicePrivilege
from .site import SiteRole
from .site import SitePrivilege
from .planetstack import PlanetStackRole
from .planetstack import PlanetStackPrivilege
from .slicetag import SliceTag
from .flavor import Flavor
from .sliver import Sliver
from .reservation import ReservedResource
from .reservation import Reservation
from .network import Network, NetworkParameterType, NetworkParameter, NetworkSliver, NetworkTemplate, Router, NetworkSlice, NetworkDeployments
from .billing import Account, Invoice, Charge, UsableObject, Payment
|
from .plcorebase import PlCoreBase
from .planetstack import PlanetStack
from .project import Project
from .singletonmodel import SingletonModel
from .service import Service
from .service import ServiceAttribute
from .tag import Tag
from .role import Role
from .site import Site,Deployment, DeploymentRole, DeploymentPrivilege, SiteDeployments
from .dashboard import DashboardView
from .user import User, UserDashboardView
from .serviceclass import ServiceClass
from .slice import Slice, SliceDeployments
from .site import SitePrivilege, SiteDeployments
from .userdeployments import UserDeployments
from .image import Image, ImageDeployments
from .node import Node
from .serviceresource import ServiceResource
from .slice import SliceRole
from .slice import SlicePrivilege
from .credential import UserCredential,SiteCredential,SliceCredential
from .site import SiteRole
from .site import SitePrivilege
from .planetstack import PlanetStackRole
from .planetstack import PlanetStackPrivilege
from .slicetag import SliceTag
from .flavor import Flavor
from .sliver import Sliver
from .reservation import ReservedResource
from .reservation import Reservation
from .network import Network, NetworkParameterType, NetworkParameter, NetworkSliver, NetworkTemplate, Router, NetworkSlice, NetworkDeployments
from .billing import Account, Invoice, Charge, UsableObject, Payment
|
Add credentials module to core list
|
Add credentials module to core list
|
Python
|
apache-2.0
|
xmaruto/mcord,jermowery/xos,cboling/xos,jermowery/xos,xmaruto/mcord,cboling/xos,cboling/xos,cboling/xos,jermowery/xos,xmaruto/mcord,cboling/xos,jermowery/xos,xmaruto/mcord
|
from .plcorebase import PlCoreBase
from .planetstack import PlanetStack
from .project import Project
from .singletonmodel import SingletonModel
from .service import Service
from .service import ServiceAttribute
from .tag import Tag
from .role import Role
from .site import Site,Deployment, DeploymentRole, DeploymentPrivilege, SiteDeployments
from .dashboard import DashboardView
from .user import User, UserDashboardView
from .serviceclass import ServiceClass
from .slice import Slice, SliceDeployments
from .site import SitePrivilege, SiteDeployments
from .userdeployments import UserDeployments
from .image import Image, ImageDeployments
from .node import Node
from .serviceresource import ServiceResource
from .slice import SliceRole
from .slice import SlicePrivilege
from .site import SiteRole
from .site import SitePrivilege
from .planetstack import PlanetStackRole
from .planetstack import PlanetStackPrivilege
from .slicetag import SliceTag
from .flavor import Flavor
from .sliver import Sliver
from .reservation import ReservedResource
from .reservation import Reservation
from .network import Network, NetworkParameterType, NetworkParameter, NetworkSliver, NetworkTemplate, Router, NetworkSlice, NetworkDeployments
from .billing import Account, Invoice, Charge, UsableObject, Payment
Add credentials module to core list
|
from .plcorebase import PlCoreBase
from .planetstack import PlanetStack
from .project import Project
from .singletonmodel import SingletonModel
from .service import Service
from .service import ServiceAttribute
from .tag import Tag
from .role import Role
from .site import Site,Deployment, DeploymentRole, DeploymentPrivilege, SiteDeployments
from .dashboard import DashboardView
from .user import User, UserDashboardView
from .serviceclass import ServiceClass
from .slice import Slice, SliceDeployments
from .site import SitePrivilege, SiteDeployments
from .userdeployments import UserDeployments
from .image import Image, ImageDeployments
from .node import Node
from .serviceresource import ServiceResource
from .slice import SliceRole
from .slice import SlicePrivilege
from .credential import UserCredential,SiteCredential,SliceCredential
from .site import SiteRole
from .site import SitePrivilege
from .planetstack import PlanetStackRole
from .planetstack import PlanetStackPrivilege
from .slicetag import SliceTag
from .flavor import Flavor
from .sliver import Sliver
from .reservation import ReservedResource
from .reservation import Reservation
from .network import Network, NetworkParameterType, NetworkParameter, NetworkSliver, NetworkTemplate, Router, NetworkSlice, NetworkDeployments
from .billing import Account, Invoice, Charge, UsableObject, Payment
|
<commit_before>from .plcorebase import PlCoreBase
from .planetstack import PlanetStack
from .project import Project
from .singletonmodel import SingletonModel
from .service import Service
from .service import ServiceAttribute
from .tag import Tag
from .role import Role
from .site import Site,Deployment, DeploymentRole, DeploymentPrivilege, SiteDeployments
from .dashboard import DashboardView
from .user import User, UserDashboardView
from .serviceclass import ServiceClass
from .slice import Slice, SliceDeployments
from .site import SitePrivilege, SiteDeployments
from .userdeployments import UserDeployments
from .image import Image, ImageDeployments
from .node import Node
from .serviceresource import ServiceResource
from .slice import SliceRole
from .slice import SlicePrivilege
from .site import SiteRole
from .site import SitePrivilege
from .planetstack import PlanetStackRole
from .planetstack import PlanetStackPrivilege
from .slicetag import SliceTag
from .flavor import Flavor
from .sliver import Sliver
from .reservation import ReservedResource
from .reservation import Reservation
from .network import Network, NetworkParameterType, NetworkParameter, NetworkSliver, NetworkTemplate, Router, NetworkSlice, NetworkDeployments
from .billing import Account, Invoice, Charge, UsableObject, Payment
<commit_msg>Add credentials module to core list<commit_after>
|
from .plcorebase import PlCoreBase
from .planetstack import PlanetStack
from .project import Project
from .singletonmodel import SingletonModel
from .service import Service
from .service import ServiceAttribute
from .tag import Tag
from .role import Role
from .site import Site,Deployment, DeploymentRole, DeploymentPrivilege, SiteDeployments
from .dashboard import DashboardView
from .user import User, UserDashboardView
from .serviceclass import ServiceClass
from .slice import Slice, SliceDeployments
from .site import SitePrivilege, SiteDeployments
from .userdeployments import UserDeployments
from .image import Image, ImageDeployments
from .node import Node
from .serviceresource import ServiceResource
from .slice import SliceRole
from .slice import SlicePrivilege
from .credential import UserCredential,SiteCredential,SliceCredential
from .site import SiteRole
from .site import SitePrivilege
from .planetstack import PlanetStackRole
from .planetstack import PlanetStackPrivilege
from .slicetag import SliceTag
from .flavor import Flavor
from .sliver import Sliver
from .reservation import ReservedResource
from .reservation import Reservation
from .network import Network, NetworkParameterType, NetworkParameter, NetworkSliver, NetworkTemplate, Router, NetworkSlice, NetworkDeployments
from .billing import Account, Invoice, Charge, UsableObject, Payment
|
from .plcorebase import PlCoreBase
from .planetstack import PlanetStack
from .project import Project
from .singletonmodel import SingletonModel
from .service import Service
from .service import ServiceAttribute
from .tag import Tag
from .role import Role
from .site import Site,Deployment, DeploymentRole, DeploymentPrivilege, SiteDeployments
from .dashboard import DashboardView
from .user import User, UserDashboardView
from .serviceclass import ServiceClass
from .slice import Slice, SliceDeployments
from .site import SitePrivilege, SiteDeployments
from .userdeployments import UserDeployments
from .image import Image, ImageDeployments
from .node import Node
from .serviceresource import ServiceResource
from .slice import SliceRole
from .slice import SlicePrivilege
from .site import SiteRole
from .site import SitePrivilege
from .planetstack import PlanetStackRole
from .planetstack import PlanetStackPrivilege
from .slicetag import SliceTag
from .flavor import Flavor
from .sliver import Sliver
from .reservation import ReservedResource
from .reservation import Reservation
from .network import Network, NetworkParameterType, NetworkParameter, NetworkSliver, NetworkTemplate, Router, NetworkSlice, NetworkDeployments
from .billing import Account, Invoice, Charge, UsableObject, Payment
Add credentials module to core listfrom .plcorebase import PlCoreBase
from .planetstack import PlanetStack
from .project import Project
from .singletonmodel import SingletonModel
from .service import Service
from .service import ServiceAttribute
from .tag import Tag
from .role import Role
from .site import Site,Deployment, DeploymentRole, DeploymentPrivilege, SiteDeployments
from .dashboard import DashboardView
from .user import User, UserDashboardView
from .serviceclass import ServiceClass
from .slice import Slice, SliceDeployments
from .site import SitePrivilege, SiteDeployments
from .userdeployments import UserDeployments
from .image import Image, ImageDeployments
from .node import Node
from .serviceresource import ServiceResource
from .slice import SliceRole
from .slice import SlicePrivilege
from .credential import UserCredential,SiteCredential,SliceCredential
from .site import SiteRole
from .site import SitePrivilege
from .planetstack import PlanetStackRole
from .planetstack import PlanetStackPrivilege
from .slicetag import SliceTag
from .flavor import Flavor
from .sliver import Sliver
from .reservation import ReservedResource
from .reservation import Reservation
from .network import Network, NetworkParameterType, NetworkParameter, NetworkSliver, NetworkTemplate, Router, NetworkSlice, NetworkDeployments
from .billing import Account, Invoice, Charge, UsableObject, Payment
|
<commit_before>from .plcorebase import PlCoreBase
from .planetstack import PlanetStack
from .project import Project
from .singletonmodel import SingletonModel
from .service import Service
from .service import ServiceAttribute
from .tag import Tag
from .role import Role
from .site import Site,Deployment, DeploymentRole, DeploymentPrivilege, SiteDeployments
from .dashboard import DashboardView
from .user import User, UserDashboardView
from .serviceclass import ServiceClass
from .slice import Slice, SliceDeployments
from .site import SitePrivilege, SiteDeployments
from .userdeployments import UserDeployments
from .image import Image, ImageDeployments
from .node import Node
from .serviceresource import ServiceResource
from .slice import SliceRole
from .slice import SlicePrivilege
from .site import SiteRole
from .site import SitePrivilege
from .planetstack import PlanetStackRole
from .planetstack import PlanetStackPrivilege
from .slicetag import SliceTag
from .flavor import Flavor
from .sliver import Sliver
from .reservation import ReservedResource
from .reservation import Reservation
from .network import Network, NetworkParameterType, NetworkParameter, NetworkSliver, NetworkTemplate, Router, NetworkSlice, NetworkDeployments
from .billing import Account, Invoice, Charge, UsableObject, Payment
<commit_msg>Add credentials module to core list<commit_after>from .plcorebase import PlCoreBase
from .planetstack import PlanetStack
from .project import Project
from .singletonmodel import SingletonModel
from .service import Service
from .service import ServiceAttribute
from .tag import Tag
from .role import Role
from .site import Site,Deployment, DeploymentRole, DeploymentPrivilege, SiteDeployments
from .dashboard import DashboardView
from .user import User, UserDashboardView
from .serviceclass import ServiceClass
from .slice import Slice, SliceDeployments
from .site import SitePrivilege, SiteDeployments
from .userdeployments import UserDeployments
from .image import Image, ImageDeployments
from .node import Node
from .serviceresource import ServiceResource
from .slice import SliceRole
from .slice import SlicePrivilege
from .credential import UserCredential,SiteCredential,SliceCredential
from .site import SiteRole
from .site import SitePrivilege
from .planetstack import PlanetStackRole
from .planetstack import PlanetStackPrivilege
from .slicetag import SliceTag
from .flavor import Flavor
from .sliver import Sliver
from .reservation import ReservedResource
from .reservation import Reservation
from .network import Network, NetworkParameterType, NetworkParameter, NetworkSliver, NetworkTemplate, Router, NetworkSlice, NetworkDeployments
from .billing import Account, Invoice, Charge, UsableObject, Payment
|
24d3f19984e4bfa1ad38faf700ae53f5f4ac10bd
|
jay/urls.py
|
jay/urls.py
|
"""jay URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.views.generic import TemplateView
from . import demo_urls
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', TemplateView.as_view(template_name="base/base.html")),
url(r'^demo/', include(demo_urls)),
url(r'^login/', auth_views.login, {'template_name': 'auth/login.html'}),
url(r'^logout/', auth_views.logout, {'template_name': 'auth/logout.html'}),
]
|
"""jay URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.views.generic import TemplateView
from . import demo_urls
from votes import urls as votes_urls
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', TemplateView.as_view(template_name="base/base.html")),
url(r'^demo/', include(demo_urls)),
url(r'^(?P<system_name>[\w-]+)/', include(votes_urls)),
url(r'^login/', auth_views.login, {'template_name': 'auth/login.html'}),
url(r'^logout/', auth_views.logout, {'template_name': 'auth/logout.html'}),
]
|
Add votes URL scheme to main URL scheme
|
Add votes URL scheme to main URL scheme
|
Python
|
mit
|
OpenJUB/jay,kuboschek/jay,OpenJUB/jay,OpenJUB/jay,kuboschek/jay,kuboschek/jay
|
"""jay URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.views.generic import TemplateView
from . import demo_urls
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', TemplateView.as_view(template_name="base/base.html")),
url(r'^demo/', include(demo_urls)),
url(r'^login/', auth_views.login, {'template_name': 'auth/login.html'}),
url(r'^logout/', auth_views.logout, {'template_name': 'auth/logout.html'}),
]
Add votes URL scheme to main URL scheme
|
"""jay URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.views.generic import TemplateView
from . import demo_urls
from votes import urls as votes_urls
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', TemplateView.as_view(template_name="base/base.html")),
url(r'^demo/', include(demo_urls)),
url(r'^(?P<system_name>[\w-]+)/', include(votes_urls)),
url(r'^login/', auth_views.login, {'template_name': 'auth/login.html'}),
url(r'^logout/', auth_views.logout, {'template_name': 'auth/logout.html'}),
]
|
<commit_before>"""jay URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.views.generic import TemplateView
from . import demo_urls
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', TemplateView.as_view(template_name="base/base.html")),
url(r'^demo/', include(demo_urls)),
url(r'^login/', auth_views.login, {'template_name': 'auth/login.html'}),
url(r'^logout/', auth_views.logout, {'template_name': 'auth/logout.html'}),
]
<commit_msg>Add votes URL scheme to main URL scheme<commit_after>
|
"""jay URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.views.generic import TemplateView
from . import demo_urls
from votes import urls as votes_urls
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', TemplateView.as_view(template_name="base/base.html")),
url(r'^demo/', include(demo_urls)),
url(r'^(?P<system_name>[\w-]+)/', include(votes_urls)),
url(r'^login/', auth_views.login, {'template_name': 'auth/login.html'}),
url(r'^logout/', auth_views.logout, {'template_name': 'auth/logout.html'}),
]
|
"""jay URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.views.generic import TemplateView
from . import demo_urls
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', TemplateView.as_view(template_name="base/base.html")),
url(r'^demo/', include(demo_urls)),
url(r'^login/', auth_views.login, {'template_name': 'auth/login.html'}),
url(r'^logout/', auth_views.logout, {'template_name': 'auth/logout.html'}),
]
Add votes URL scheme to main URL scheme"""jay URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.views.generic import TemplateView
from . import demo_urls
from votes import urls as votes_urls
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', TemplateView.as_view(template_name="base/base.html")),
url(r'^demo/', include(demo_urls)),
url(r'^(?P<system_name>[\w-]+)/', include(votes_urls)),
url(r'^login/', auth_views.login, {'template_name': 'auth/login.html'}),
url(r'^logout/', auth_views.logout, {'template_name': 'auth/logout.html'}),
]
|
<commit_before>"""jay URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.views.generic import TemplateView
from . import demo_urls
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', TemplateView.as_view(template_name="base/base.html")),
url(r'^demo/', include(demo_urls)),
url(r'^login/', auth_views.login, {'template_name': 'auth/login.html'}),
url(r'^logout/', auth_views.logout, {'template_name': 'auth/logout.html'}),
]
<commit_msg>Add votes URL scheme to main URL scheme<commit_after>"""jay URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.views.generic import TemplateView
from . import demo_urls
from votes import urls as votes_urls
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', TemplateView.as_view(template_name="base/base.html")),
url(r'^demo/', include(demo_urls)),
url(r'^(?P<system_name>[\w-]+)/', include(votes_urls)),
url(r'^login/', auth_views.login, {'template_name': 'auth/login.html'}),
url(r'^logout/', auth_views.logout, {'template_name': 'auth/logout.html'}),
]
|
707ded0f673f44b31d0762d8210a6b94074200e8
|
troposphere/certificatemanager.py
|
troposphere/certificatemanager.py
|
from . import AWSObject, AWSProperty, Tags
class DomainValidationOption(AWSProperty):
props = {
'DomainName': (basestring, True),
'ValidationDomain': (basestring, True),
}
class Certificate(AWSObject):
resource_type = "AWS::CertificateManager::Certificate"
props = {
'DomainName': (basestring, True),
'DomainValidationOptions': ([DomainValidationOption], False),
'SubjectAlternativeNames': ([basestring], False),
'Tags': ((Tags, list), False),
'ValidationMethod': (basestring, False),
}
|
# Copyright (c) 2012-2019, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 15.1.0
from . import AWSObject
from . import AWSProperty
from troposphere import Tags
class DomainValidationOption(AWSProperty):
props = {
'DomainName': (basestring, True),
'HostedZoneId': (basestring, False),
'ValidationDomain': (basestring, False),
}
class Certificate(AWSObject):
resource_type = "AWS::CertificateManager::Certificate"
props = {
'CertificateAuthorityArn': (basestring, False),
'CertificateTransparencyLoggingPreference': (basestring, False),
'DomainName': (basestring, True),
'DomainValidationOptions': ([DomainValidationOption], False),
'SubjectAlternativeNames': ([basestring], False),
'Tags': ((Tags, list), False),
'ValidationMethod': (basestring, False),
}
|
Update AWS::CertificateManager::Certificate per 2020-06-11 changes
|
Update AWS::CertificateManager::Certificate per 2020-06-11 changes
|
Python
|
bsd-2-clause
|
cloudtools/troposphere,cloudtools/troposphere
|
from . import AWSObject, AWSProperty, Tags
class DomainValidationOption(AWSProperty):
props = {
'DomainName': (basestring, True),
'ValidationDomain': (basestring, True),
}
class Certificate(AWSObject):
resource_type = "AWS::CertificateManager::Certificate"
props = {
'DomainName': (basestring, True),
'DomainValidationOptions': ([DomainValidationOption], False),
'SubjectAlternativeNames': ([basestring], False),
'Tags': ((Tags, list), False),
'ValidationMethod': (basestring, False),
}
Update AWS::CertificateManager::Certificate per 2020-06-11 changes
|
# Copyright (c) 2012-2019, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 15.1.0
from . import AWSObject
from . import AWSProperty
from troposphere import Tags
class DomainValidationOption(AWSProperty):
props = {
'DomainName': (basestring, True),
'HostedZoneId': (basestring, False),
'ValidationDomain': (basestring, False),
}
class Certificate(AWSObject):
resource_type = "AWS::CertificateManager::Certificate"
props = {
'CertificateAuthorityArn': (basestring, False),
'CertificateTransparencyLoggingPreference': (basestring, False),
'DomainName': (basestring, True),
'DomainValidationOptions': ([DomainValidationOption], False),
'SubjectAlternativeNames': ([basestring], False),
'Tags': ((Tags, list), False),
'ValidationMethod': (basestring, False),
}
|
<commit_before>from . import AWSObject, AWSProperty, Tags
class DomainValidationOption(AWSProperty):
props = {
'DomainName': (basestring, True),
'ValidationDomain': (basestring, True),
}
class Certificate(AWSObject):
resource_type = "AWS::CertificateManager::Certificate"
props = {
'DomainName': (basestring, True),
'DomainValidationOptions': ([DomainValidationOption], False),
'SubjectAlternativeNames': ([basestring], False),
'Tags': ((Tags, list), False),
'ValidationMethod': (basestring, False),
}
<commit_msg>Update AWS::CertificateManager::Certificate per 2020-06-11 changes<commit_after>
|
# Copyright (c) 2012-2019, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 15.1.0
from . import AWSObject
from . import AWSProperty
from troposphere import Tags
class DomainValidationOption(AWSProperty):
props = {
'DomainName': (basestring, True),
'HostedZoneId': (basestring, False),
'ValidationDomain': (basestring, False),
}
class Certificate(AWSObject):
resource_type = "AWS::CertificateManager::Certificate"
props = {
'CertificateAuthorityArn': (basestring, False),
'CertificateTransparencyLoggingPreference': (basestring, False),
'DomainName': (basestring, True),
'DomainValidationOptions': ([DomainValidationOption], False),
'SubjectAlternativeNames': ([basestring], False),
'Tags': ((Tags, list), False),
'ValidationMethod': (basestring, False),
}
|
from . import AWSObject, AWSProperty, Tags
class DomainValidationOption(AWSProperty):
props = {
'DomainName': (basestring, True),
'ValidationDomain': (basestring, True),
}
class Certificate(AWSObject):
resource_type = "AWS::CertificateManager::Certificate"
props = {
'DomainName': (basestring, True),
'DomainValidationOptions': ([DomainValidationOption], False),
'SubjectAlternativeNames': ([basestring], False),
'Tags': ((Tags, list), False),
'ValidationMethod': (basestring, False),
}
Update AWS::CertificateManager::Certificate per 2020-06-11 changes# Copyright (c) 2012-2019, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 15.1.0
from . import AWSObject
from . import AWSProperty
from troposphere import Tags
class DomainValidationOption(AWSProperty):
props = {
'DomainName': (basestring, True),
'HostedZoneId': (basestring, False),
'ValidationDomain': (basestring, False),
}
class Certificate(AWSObject):
resource_type = "AWS::CertificateManager::Certificate"
props = {
'CertificateAuthorityArn': (basestring, False),
'CertificateTransparencyLoggingPreference': (basestring, False),
'DomainName': (basestring, True),
'DomainValidationOptions': ([DomainValidationOption], False),
'SubjectAlternativeNames': ([basestring], False),
'Tags': ((Tags, list), False),
'ValidationMethod': (basestring, False),
}
|
<commit_before>from . import AWSObject, AWSProperty, Tags
class DomainValidationOption(AWSProperty):
props = {
'DomainName': (basestring, True),
'ValidationDomain': (basestring, True),
}
class Certificate(AWSObject):
resource_type = "AWS::CertificateManager::Certificate"
props = {
'DomainName': (basestring, True),
'DomainValidationOptions': ([DomainValidationOption], False),
'SubjectAlternativeNames': ([basestring], False),
'Tags': ((Tags, list), False),
'ValidationMethod': (basestring, False),
}
<commit_msg>Update AWS::CertificateManager::Certificate per 2020-06-11 changes<commit_after># Copyright (c) 2012-2019, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 15.1.0
from . import AWSObject
from . import AWSProperty
from troposphere import Tags
class DomainValidationOption(AWSProperty):
props = {
'DomainName': (basestring, True),
'HostedZoneId': (basestring, False),
'ValidationDomain': (basestring, False),
}
class Certificate(AWSObject):
resource_type = "AWS::CertificateManager::Certificate"
props = {
'CertificateAuthorityArn': (basestring, False),
'CertificateTransparencyLoggingPreference': (basestring, False),
'DomainName': (basestring, True),
'DomainValidationOptions': ([DomainValidationOption], False),
'SubjectAlternativeNames': ([basestring], False),
'Tags': ((Tags, list), False),
'ValidationMethod': (basestring, False),
}
|
bf19eb9083888d33dabec2228ffaa200ce282ef8
|
superlists/functional_tests/test_list_item_validation.py
|
superlists/functional_tests/test_list_item_validation.py
|
from unittest import skip
from .base import FunctionalTest
class ItemValidationTest(FunctionalTest):
def test_cannot_add_empty_list_items(self):
self.fail("write me!")
|
from unittest import skip
from .base import FunctionalTest
class ItemValidationTest(FunctionalTest):
def test_cannot_add_empty_list_items(self):
# Edith goes to the home page and accidentally tries to submit and empty
# list item. She hits Enter on the empty input box
self.browser.get(self.server_url)
self.browser.find_element_by_id('id_new_item').send_keys('\n')
# The home page refreshes, and there is an error message saying
# that list items cannot be blank
error = self.browser.find_element_by_css_selector('.has_error')
self.assertEqual(error.text, "You can't have an empty list item")
# She tries again with some text for the item, which now works
self.browser.find_element_by_id('id_new_item').send_keys('Buy milk\n')
self.check_for_row_in_list_table('1: Buy milk')
# Perversely, she now decides to submit a second blank list item
self.browser.find_element_by_id('id_new_item').send_keys('\n')
# She receives a similar warning on the list page
self.check_for_row_in_list_table('1: Buy milk')
error = self.browser.find_element_by_css_selector('.has-error')
self.assertEqual(error.text, "You can't have an empty list item")
# And she can correct it by filling some text in
self.browser.find_element_by_id('id_new_item').send_keys('Make tea\n')
self.check_for_row_in_list_table('1: Buy milk')
self.check_for_row_in_list_table('2: Make tea')
|
Create test to detect submission of empty list items
|
Create test to detect submission of empty list items
|
Python
|
apache-2.0
|
rocity/the-testing-goat,rocity/the-testing-goat
|
from unittest import skip
from .base import FunctionalTest
class ItemValidationTest(FunctionalTest):
def test_cannot_add_empty_list_items(self):
self.fail("write me!")Create test to detect submission of empty list items
|
from unittest import skip
from .base import FunctionalTest
class ItemValidationTest(FunctionalTest):
def test_cannot_add_empty_list_items(self):
# Edith goes to the home page and accidentally tries to submit and empty
# list item. She hits Enter on the empty input box
self.browser.get(self.server_url)
self.browser.find_element_by_id('id_new_item').send_keys('\n')
# The home page refreshes, and there is an error message saying
# that list items cannot be blank
error = self.browser.find_element_by_css_selector('.has_error')
self.assertEqual(error.text, "You can't have an empty list item")
# She tries again with some text for the item, which now works
self.browser.find_element_by_id('id_new_item').send_keys('Buy milk\n')
self.check_for_row_in_list_table('1: Buy milk')
# Perversely, she now decides to submit a second blank list item
self.browser.find_element_by_id('id_new_item').send_keys('\n')
# She receives a similar warning on the list page
self.check_for_row_in_list_table('1: Buy milk')
error = self.browser.find_element_by_css_selector('.has-error')
self.assertEqual(error.text, "You can't have an empty list item")
# And she can correct it by filling some text in
self.browser.find_element_by_id('id_new_item').send_keys('Make tea\n')
self.check_for_row_in_list_table('1: Buy milk')
self.check_for_row_in_list_table('2: Make tea')
|
<commit_before>from unittest import skip
from .base import FunctionalTest
class ItemValidationTest(FunctionalTest):
def test_cannot_add_empty_list_items(self):
self.fail("write me!")<commit_msg>Create test to detect submission of empty list items<commit_after>
|
from unittest import skip
from .base import FunctionalTest
class ItemValidationTest(FunctionalTest):
def test_cannot_add_empty_list_items(self):
# Edith goes to the home page and accidentally tries to submit and empty
# list item. She hits Enter on the empty input box
self.browser.get(self.server_url)
self.browser.find_element_by_id('id_new_item').send_keys('\n')
# The home page refreshes, and there is an error message saying
# that list items cannot be blank
error = self.browser.find_element_by_css_selector('.has_error')
self.assertEqual(error.text, "You can't have an empty list item")
# She tries again with some text for the item, which now works
self.browser.find_element_by_id('id_new_item').send_keys('Buy milk\n')
self.check_for_row_in_list_table('1: Buy milk')
# Perversely, she now decides to submit a second blank list item
self.browser.find_element_by_id('id_new_item').send_keys('\n')
# She receives a similar warning on the list page
self.check_for_row_in_list_table('1: Buy milk')
error = self.browser.find_element_by_css_selector('.has-error')
self.assertEqual(error.text, "You can't have an empty list item")
# And she can correct it by filling some text in
self.browser.find_element_by_id('id_new_item').send_keys('Make tea\n')
self.check_for_row_in_list_table('1: Buy milk')
self.check_for_row_in_list_table('2: Make tea')
|
from unittest import skip
from .base import FunctionalTest
class ItemValidationTest(FunctionalTest):
def test_cannot_add_empty_list_items(self):
self.fail("write me!")Create test to detect submission of empty list itemsfrom unittest import skip
from .base import FunctionalTest
class ItemValidationTest(FunctionalTest):
def test_cannot_add_empty_list_items(self):
# Edith goes to the home page and accidentally tries to submit and empty
# list item. She hits Enter on the empty input box
self.browser.get(self.server_url)
self.browser.find_element_by_id('id_new_item').send_keys('\n')
# The home page refreshes, and there is an error message saying
# that list items cannot be blank
error = self.browser.find_element_by_css_selector('.has_error')
self.assertEqual(error.text, "You can't have an empty list item")
# She tries again with some text for the item, which now works
self.browser.find_element_by_id('id_new_item').send_keys('Buy milk\n')
self.check_for_row_in_list_table('1: Buy milk')
# Perversely, she now decides to submit a second blank list item
self.browser.find_element_by_id('id_new_item').send_keys('\n')
# She receives a similar warning on the list page
self.check_for_row_in_list_table('1: Buy milk')
error = self.browser.find_element_by_css_selector('.has-error')
self.assertEqual(error.text, "You can't have an empty list item")
# And she can correct it by filling some text in
self.browser.find_element_by_id('id_new_item').send_keys('Make tea\n')
self.check_for_row_in_list_table('1: Buy milk')
self.check_for_row_in_list_table('2: Make tea')
|
<commit_before>from unittest import skip
from .base import FunctionalTest
class ItemValidationTest(FunctionalTest):
def test_cannot_add_empty_list_items(self):
self.fail("write me!")<commit_msg>Create test to detect submission of empty list items<commit_after>from unittest import skip
from .base import FunctionalTest
class ItemValidationTest(FunctionalTest):
def test_cannot_add_empty_list_items(self):
# Edith goes to the home page and accidentally tries to submit and empty
# list item. She hits Enter on the empty input box
self.browser.get(self.server_url)
self.browser.find_element_by_id('id_new_item').send_keys('\n')
# The home page refreshes, and there is an error message saying
# that list items cannot be blank
error = self.browser.find_element_by_css_selector('.has_error')
self.assertEqual(error.text, "You can't have an empty list item")
# She tries again with some text for the item, which now works
self.browser.find_element_by_id('id_new_item').send_keys('Buy milk\n')
self.check_for_row_in_list_table('1: Buy milk')
# Perversely, she now decides to submit a second blank list item
self.browser.find_element_by_id('id_new_item').send_keys('\n')
# She receives a similar warning on the list page
self.check_for_row_in_list_table('1: Buy milk')
error = self.browser.find_element_by_css_selector('.has-error')
self.assertEqual(error.text, "You can't have an empty list item")
# And she can correct it by filling some text in
self.browser.find_element_by_id('id_new_item').send_keys('Make tea\n')
self.check_for_row_in_list_table('1: Buy milk')
self.check_for_row_in_list_table('2: Make tea')
|
2af6a3fcafc7447f15352a32507f5034b42984a6
|
contrail_api_cli/context.py
|
contrail_api_cli/context.py
|
class SchemaNotInitialized(Exception):
pass
class Context(object):
_instance = None
_schema = None
def __new__(class_, *args, **kwargs):
if not isinstance(class_._instance, class_):
class_._instance = object.__new__(class_, *args, **kwargs)
return class_._instance
@property
def schema(self):
if self._schema is None:
raise SchemaNotInitialized("The schema must be fisrt initialized")
else:
return self._schema
@schema.setter
def schema(self, schema):
self._schema = schema
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from six import add_metaclass
from .utils import Singleton
class SchemaNotInitialized(Exception):
pass
@add_metaclass(Singleton)
class Context(object):
_schema = None
@property
def schema(self):
if self._schema is None:
raise SchemaNotInitialized("The schema must be fisrt initialized")
else:
return self._schema
@schema.setter
def schema(self, schema):
self._schema = schema
|
Use Singleton metaclass on Context
|
Use Singleton metaclass on Context
|
Python
|
mit
|
eonpatapon/contrail-api-cli
|
class SchemaNotInitialized(Exception):
pass
class Context(object):
_instance = None
_schema = None
def __new__(class_, *args, **kwargs):
if not isinstance(class_._instance, class_):
class_._instance = object.__new__(class_, *args, **kwargs)
return class_._instance
@property
def schema(self):
if self._schema is None:
raise SchemaNotInitialized("The schema must be fisrt initialized")
else:
return self._schema
@schema.setter
def schema(self, schema):
self._schema = schema
Use Singleton metaclass on Context
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from six import add_metaclass
from .utils import Singleton
class SchemaNotInitialized(Exception):
pass
@add_metaclass(Singleton)
class Context(object):
_schema = None
@property
def schema(self):
if self._schema is None:
raise SchemaNotInitialized("The schema must be fisrt initialized")
else:
return self._schema
@schema.setter
def schema(self, schema):
self._schema = schema
|
<commit_before>class SchemaNotInitialized(Exception):
pass
class Context(object):
_instance = None
_schema = None
def __new__(class_, *args, **kwargs):
if not isinstance(class_._instance, class_):
class_._instance = object.__new__(class_, *args, **kwargs)
return class_._instance
@property
def schema(self):
if self._schema is None:
raise SchemaNotInitialized("The schema must be fisrt initialized")
else:
return self._schema
@schema.setter
def schema(self, schema):
self._schema = schema
<commit_msg>Use Singleton metaclass on Context<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from six import add_metaclass
from .utils import Singleton
class SchemaNotInitialized(Exception):
pass
@add_metaclass(Singleton)
class Context(object):
_schema = None
@property
def schema(self):
if self._schema is None:
raise SchemaNotInitialized("The schema must be fisrt initialized")
else:
return self._schema
@schema.setter
def schema(self, schema):
self._schema = schema
|
class SchemaNotInitialized(Exception):
pass
class Context(object):
_instance = None
_schema = None
def __new__(class_, *args, **kwargs):
if not isinstance(class_._instance, class_):
class_._instance = object.__new__(class_, *args, **kwargs)
return class_._instance
@property
def schema(self):
if self._schema is None:
raise SchemaNotInitialized("The schema must be fisrt initialized")
else:
return self._schema
@schema.setter
def schema(self, schema):
self._schema = schema
Use Singleton metaclass on Context# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from six import add_metaclass
from .utils import Singleton
class SchemaNotInitialized(Exception):
pass
@add_metaclass(Singleton)
class Context(object):
_schema = None
@property
def schema(self):
if self._schema is None:
raise SchemaNotInitialized("The schema must be fisrt initialized")
else:
return self._schema
@schema.setter
def schema(self, schema):
self._schema = schema
|
<commit_before>class SchemaNotInitialized(Exception):
pass
class Context(object):
_instance = None
_schema = None
def __new__(class_, *args, **kwargs):
if not isinstance(class_._instance, class_):
class_._instance = object.__new__(class_, *args, **kwargs)
return class_._instance
@property
def schema(self):
if self._schema is None:
raise SchemaNotInitialized("The schema must be fisrt initialized")
else:
return self._schema
@schema.setter
def schema(self, schema):
self._schema = schema
<commit_msg>Use Singleton metaclass on Context<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from six import add_metaclass
from .utils import Singleton
class SchemaNotInitialized(Exception):
pass
@add_metaclass(Singleton)
class Context(object):
_schema = None
@property
def schema(self):
if self._schema is None:
raise SchemaNotInitialized("The schema must be fisrt initialized")
else:
return self._schema
@schema.setter
def schema(self, schema):
self._schema = schema
|
50451a822e653de12f2f96342b830b194d786d50
|
ocradmin/ocrplugins/urls.py
|
ocradmin/ocrplugins/urls.py
|
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^/?$', 'ocradmin.ocrplugins.views.list'),
(r'^query/?$', 'ocradmin.ocrplugins.views.query'),
(r'^query/(?P<args>.+)/?$', 'ocradmin.ocrplugins.views.query'),
(r'^parse/?$', 'ocradmin.ocrplugins.views.parse'),
(r'^(?P<name>[^/]+)/?$', 'ocradmin.ocrplugins.views.info'),
(r'^(?P<name>\w+)/(?P<method>\w+)/?$', 'ocradmin.ocrplugins.views.run_get_method'),
)
|
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^/?$', 'ocradmin.ocrplugins.views.index'),
(r'^query/?$', 'ocradmin.ocrplugins.views.query'),
(r'^query/(?P<args>.+)/?$', 'ocradmin.ocrplugins.views.query'),
(r'^parse/?$', 'ocradmin.ocrplugins.views.parse'),
(r'^(?P<name>[^/]+)/?$', 'ocradmin.ocrplugins.views.info'),
(r'^(?P<name>\w+)/(?P<method>\w+)/?$', 'ocradmin.ocrplugins.views.run_get_method'),
)
|
Correct name of index view function
|
Correct name of index view function
|
Python
|
apache-2.0
|
vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium
|
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^/?$', 'ocradmin.ocrplugins.views.list'),
(r'^query/?$', 'ocradmin.ocrplugins.views.query'),
(r'^query/(?P<args>.+)/?$', 'ocradmin.ocrplugins.views.query'),
(r'^parse/?$', 'ocradmin.ocrplugins.views.parse'),
(r'^(?P<name>[^/]+)/?$', 'ocradmin.ocrplugins.views.info'),
(r'^(?P<name>\w+)/(?P<method>\w+)/?$', 'ocradmin.ocrplugins.views.run_get_method'),
)
Correct name of index view function
|
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^/?$', 'ocradmin.ocrplugins.views.index'),
(r'^query/?$', 'ocradmin.ocrplugins.views.query'),
(r'^query/(?P<args>.+)/?$', 'ocradmin.ocrplugins.views.query'),
(r'^parse/?$', 'ocradmin.ocrplugins.views.parse'),
(r'^(?P<name>[^/]+)/?$', 'ocradmin.ocrplugins.views.info'),
(r'^(?P<name>\w+)/(?P<method>\w+)/?$', 'ocradmin.ocrplugins.views.run_get_method'),
)
|
<commit_before>from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^/?$', 'ocradmin.ocrplugins.views.list'),
(r'^query/?$', 'ocradmin.ocrplugins.views.query'),
(r'^query/(?P<args>.+)/?$', 'ocradmin.ocrplugins.views.query'),
(r'^parse/?$', 'ocradmin.ocrplugins.views.parse'),
(r'^(?P<name>[^/]+)/?$', 'ocradmin.ocrplugins.views.info'),
(r'^(?P<name>\w+)/(?P<method>\w+)/?$', 'ocradmin.ocrplugins.views.run_get_method'),
)
<commit_msg>Correct name of index view function<commit_after>
|
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^/?$', 'ocradmin.ocrplugins.views.index'),
(r'^query/?$', 'ocradmin.ocrplugins.views.query'),
(r'^query/(?P<args>.+)/?$', 'ocradmin.ocrplugins.views.query'),
(r'^parse/?$', 'ocradmin.ocrplugins.views.parse'),
(r'^(?P<name>[^/]+)/?$', 'ocradmin.ocrplugins.views.info'),
(r'^(?P<name>\w+)/(?P<method>\w+)/?$', 'ocradmin.ocrplugins.views.run_get_method'),
)
|
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^/?$', 'ocradmin.ocrplugins.views.list'),
(r'^query/?$', 'ocradmin.ocrplugins.views.query'),
(r'^query/(?P<args>.+)/?$', 'ocradmin.ocrplugins.views.query'),
(r'^parse/?$', 'ocradmin.ocrplugins.views.parse'),
(r'^(?P<name>[^/]+)/?$', 'ocradmin.ocrplugins.views.info'),
(r'^(?P<name>\w+)/(?P<method>\w+)/?$', 'ocradmin.ocrplugins.views.run_get_method'),
)
Correct name of index view functionfrom django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^/?$', 'ocradmin.ocrplugins.views.index'),
(r'^query/?$', 'ocradmin.ocrplugins.views.query'),
(r'^query/(?P<args>.+)/?$', 'ocradmin.ocrplugins.views.query'),
(r'^parse/?$', 'ocradmin.ocrplugins.views.parse'),
(r'^(?P<name>[^/]+)/?$', 'ocradmin.ocrplugins.views.info'),
(r'^(?P<name>\w+)/(?P<method>\w+)/?$', 'ocradmin.ocrplugins.views.run_get_method'),
)
|
<commit_before>from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^/?$', 'ocradmin.ocrplugins.views.list'),
(r'^query/?$', 'ocradmin.ocrplugins.views.query'),
(r'^query/(?P<args>.+)/?$', 'ocradmin.ocrplugins.views.query'),
(r'^parse/?$', 'ocradmin.ocrplugins.views.parse'),
(r'^(?P<name>[^/]+)/?$', 'ocradmin.ocrplugins.views.info'),
(r'^(?P<name>\w+)/(?P<method>\w+)/?$', 'ocradmin.ocrplugins.views.run_get_method'),
)
<commit_msg>Correct name of index view function<commit_after>from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^/?$', 'ocradmin.ocrplugins.views.index'),
(r'^query/?$', 'ocradmin.ocrplugins.views.query'),
(r'^query/(?P<args>.+)/?$', 'ocradmin.ocrplugins.views.query'),
(r'^parse/?$', 'ocradmin.ocrplugins.views.parse'),
(r'^(?P<name>[^/]+)/?$', 'ocradmin.ocrplugins.views.info'),
(r'^(?P<name>\w+)/(?P<method>\w+)/?$', 'ocradmin.ocrplugins.views.run_get_method'),
)
|
ec2a18c8da029aadb7bc853c73dc6e1484ddac3b
|
into/backends/tests/test_spark.py
|
into/backends/tests/test_spark.py
|
import pytest
from into import into
from pyspark import RDD
data = [['Alice', 100.0, 1],
['Bob', 200.0, 2],
['Alice', 50.0, 3]]
@pytest.fixture
def rdd(sc):
return sc.parallelize(data)
def test_spark_into(rdd):
seq = [1, 2, 3]
assert isinstance(into(rdd, seq), RDD)
assert into([], into(rdd, seq)) == seq
|
import pytest
from into import into, discover
from pyspark import RDD
data = [['Alice', 100.0, 1],
['Bob', 200.0, 2],
['Alice', 50.0, 3]]
@pytest.fixture
def rdd(sc):
return sc.parallelize(data)
def test_spark_into(rdd):
seq = [1, 2, 3]
assert isinstance(into(rdd, seq), RDD)
assert into([], into(rdd, seq)) == seq
def test_discover_rdd(rdd):
assert discover(rdd).subshape[0] == discover(data).subshape[0]
|
Test discover on a vanilla RDD
|
Test discover on a vanilla RDD
|
Python
|
bsd-3-clause
|
ContinuumIO/odo,ywang007/odo,cpcloud/odo,ywang007/odo,alexmojaki/odo,cpcloud/odo,Dannnno/odo,ContinuumIO/odo,cowlicks/odo,Dannnno/odo,quantopian/odo,blaze/odo,quantopian/odo,blaze/odo,alexmojaki/odo,cowlicks/odo
|
import pytest
from into import into
from pyspark import RDD
data = [['Alice', 100.0, 1],
['Bob', 200.0, 2],
['Alice', 50.0, 3]]
@pytest.fixture
def rdd(sc):
return sc.parallelize(data)
def test_spark_into(rdd):
seq = [1, 2, 3]
assert isinstance(into(rdd, seq), RDD)
assert into([], into(rdd, seq)) == seq
Test discover on a vanilla RDD
|
import pytest
from into import into, discover
from pyspark import RDD
data = [['Alice', 100.0, 1],
['Bob', 200.0, 2],
['Alice', 50.0, 3]]
@pytest.fixture
def rdd(sc):
return sc.parallelize(data)
def test_spark_into(rdd):
seq = [1, 2, 3]
assert isinstance(into(rdd, seq), RDD)
assert into([], into(rdd, seq)) == seq
def test_discover_rdd(rdd):
assert discover(rdd).subshape[0] == discover(data).subshape[0]
|
<commit_before>import pytest
from into import into
from pyspark import RDD
data = [['Alice', 100.0, 1],
['Bob', 200.0, 2],
['Alice', 50.0, 3]]
@pytest.fixture
def rdd(sc):
return sc.parallelize(data)
def test_spark_into(rdd):
seq = [1, 2, 3]
assert isinstance(into(rdd, seq), RDD)
assert into([], into(rdd, seq)) == seq
<commit_msg>Test discover on a vanilla RDD<commit_after>
|
import pytest
from into import into, discover
from pyspark import RDD
data = [['Alice', 100.0, 1],
['Bob', 200.0, 2],
['Alice', 50.0, 3]]
@pytest.fixture
def rdd(sc):
return sc.parallelize(data)
def test_spark_into(rdd):
seq = [1, 2, 3]
assert isinstance(into(rdd, seq), RDD)
assert into([], into(rdd, seq)) == seq
def test_discover_rdd(rdd):
assert discover(rdd).subshape[0] == discover(data).subshape[0]
|
import pytest
from into import into
from pyspark import RDD
data = [['Alice', 100.0, 1],
['Bob', 200.0, 2],
['Alice', 50.0, 3]]
@pytest.fixture
def rdd(sc):
return sc.parallelize(data)
def test_spark_into(rdd):
seq = [1, 2, 3]
assert isinstance(into(rdd, seq), RDD)
assert into([], into(rdd, seq)) == seq
Test discover on a vanilla RDDimport pytest
from into import into, discover
from pyspark import RDD
data = [['Alice', 100.0, 1],
['Bob', 200.0, 2],
['Alice', 50.0, 3]]
@pytest.fixture
def rdd(sc):
return sc.parallelize(data)
def test_spark_into(rdd):
seq = [1, 2, 3]
assert isinstance(into(rdd, seq), RDD)
assert into([], into(rdd, seq)) == seq
def test_discover_rdd(rdd):
assert discover(rdd).subshape[0] == discover(data).subshape[0]
|
<commit_before>import pytest
from into import into
from pyspark import RDD
data = [['Alice', 100.0, 1],
['Bob', 200.0, 2],
['Alice', 50.0, 3]]
@pytest.fixture
def rdd(sc):
return sc.parallelize(data)
def test_spark_into(rdd):
seq = [1, 2, 3]
assert isinstance(into(rdd, seq), RDD)
assert into([], into(rdd, seq)) == seq
<commit_msg>Test discover on a vanilla RDD<commit_after>import pytest
from into import into, discover
from pyspark import RDD
data = [['Alice', 100.0, 1],
['Bob', 200.0, 2],
['Alice', 50.0, 3]]
@pytest.fixture
def rdd(sc):
return sc.parallelize(data)
def test_spark_into(rdd):
seq = [1, 2, 3]
assert isinstance(into(rdd, seq), RDD)
assert into([], into(rdd, seq)) == seq
def test_discover_rdd(rdd):
assert discover(rdd).subshape[0] == discover(data).subshape[0]
|
8feb733383a90ea6f16cd9cc696446343b4678e9
|
errorreporter.py
|
errorreporter.py
|
from errormarker import ErrorMarker
from util import delayed
class ErrorReporter(object):
def __init__(self, window, error_report, settings, expand_filename):
self._marker = ErrorMarker(window, error_report, settings)
self._error_report = error_report
self._expand_filename = expand_filename
@delayed(0)
def error(self, filename, line, message):
filename = self._expand_filename(filename)
self._error_report.add_error(filename, line, message)
self._marker.mark_line(filename, line)
self._marker.update_status()
def finish(self):
self._error_report.cycle()
self._marker.mark_errors()
def show_errors(self, filename):
self._marker.mark_errors_in(filename)
def hide_errors(self, filename):
self._error_report.clear_file(filename)
self._marker.hide_errors_in(filename)
def update_status(self):
self._marker.update_status()
|
from errormarker import ErrorMarker
from util import delayed
class ErrorReporter(object):
def __init__(self, window, error_report, settings, expand_filename):
self._marker = ErrorMarker(window, error_report, settings)
self._error_report = error_report
self._expand_filename = expand_filename
@delayed(0)
def error(self, filename, line, message):
filename = self._expand_filename(filename)
self._error_report.add_error(filename, line, message)
self._marker.mark_line(filename, line)
self._marker.update_status()
@delayed(0)
def finish(self):
self._error_report.cycle()
self._marker.mark_errors()
def show_errors(self, filename):
self._marker.mark_errors_in(filename)
def hide_errors(self, filename):
self._error_report.clear_file(filename)
self._marker.hide_errors_in(filename)
def update_status(self):
self._marker.update_status()
|
Fix a race condition in error reporting causing highlighted lines to get out of sync
|
Fix a race condition in error reporting causing highlighted lines to get out of sync
|
Python
|
mit
|
jarhart/SublimeSBT
|
from errormarker import ErrorMarker
from util import delayed
class ErrorReporter(object):
def __init__(self, window, error_report, settings, expand_filename):
self._marker = ErrorMarker(window, error_report, settings)
self._error_report = error_report
self._expand_filename = expand_filename
@delayed(0)
def error(self, filename, line, message):
filename = self._expand_filename(filename)
self._error_report.add_error(filename, line, message)
self._marker.mark_line(filename, line)
self._marker.update_status()
def finish(self):
self._error_report.cycle()
self._marker.mark_errors()
def show_errors(self, filename):
self._marker.mark_errors_in(filename)
def hide_errors(self, filename):
self._error_report.clear_file(filename)
self._marker.hide_errors_in(filename)
def update_status(self):
self._marker.update_status()
Fix a race condition in error reporting causing highlighted lines to get out of sync
|
from errormarker import ErrorMarker
from util import delayed
class ErrorReporter(object):
def __init__(self, window, error_report, settings, expand_filename):
self._marker = ErrorMarker(window, error_report, settings)
self._error_report = error_report
self._expand_filename = expand_filename
@delayed(0)
def error(self, filename, line, message):
filename = self._expand_filename(filename)
self._error_report.add_error(filename, line, message)
self._marker.mark_line(filename, line)
self._marker.update_status()
@delayed(0)
def finish(self):
self._error_report.cycle()
self._marker.mark_errors()
def show_errors(self, filename):
self._marker.mark_errors_in(filename)
def hide_errors(self, filename):
self._error_report.clear_file(filename)
self._marker.hide_errors_in(filename)
def update_status(self):
self._marker.update_status()
|
<commit_before>from errormarker import ErrorMarker
from util import delayed
class ErrorReporter(object):
def __init__(self, window, error_report, settings, expand_filename):
self._marker = ErrorMarker(window, error_report, settings)
self._error_report = error_report
self._expand_filename = expand_filename
@delayed(0)
def error(self, filename, line, message):
filename = self._expand_filename(filename)
self._error_report.add_error(filename, line, message)
self._marker.mark_line(filename, line)
self._marker.update_status()
def finish(self):
self._error_report.cycle()
self._marker.mark_errors()
def show_errors(self, filename):
self._marker.mark_errors_in(filename)
def hide_errors(self, filename):
self._error_report.clear_file(filename)
self._marker.hide_errors_in(filename)
def update_status(self):
self._marker.update_status()
<commit_msg>Fix a race condition in error reporting causing highlighted lines to get out of sync<commit_after>
|
from errormarker import ErrorMarker
from util import delayed
class ErrorReporter(object):
def __init__(self, window, error_report, settings, expand_filename):
self._marker = ErrorMarker(window, error_report, settings)
self._error_report = error_report
self._expand_filename = expand_filename
@delayed(0)
def error(self, filename, line, message):
filename = self._expand_filename(filename)
self._error_report.add_error(filename, line, message)
self._marker.mark_line(filename, line)
self._marker.update_status()
@delayed(0)
def finish(self):
self._error_report.cycle()
self._marker.mark_errors()
def show_errors(self, filename):
self._marker.mark_errors_in(filename)
def hide_errors(self, filename):
self._error_report.clear_file(filename)
self._marker.hide_errors_in(filename)
def update_status(self):
self._marker.update_status()
|
from errormarker import ErrorMarker
from util import delayed
class ErrorReporter(object):
def __init__(self, window, error_report, settings, expand_filename):
self._marker = ErrorMarker(window, error_report, settings)
self._error_report = error_report
self._expand_filename = expand_filename
@delayed(0)
def error(self, filename, line, message):
filename = self._expand_filename(filename)
self._error_report.add_error(filename, line, message)
self._marker.mark_line(filename, line)
self._marker.update_status()
def finish(self):
self._error_report.cycle()
self._marker.mark_errors()
def show_errors(self, filename):
self._marker.mark_errors_in(filename)
def hide_errors(self, filename):
self._error_report.clear_file(filename)
self._marker.hide_errors_in(filename)
def update_status(self):
self._marker.update_status()
Fix a race condition in error reporting causing highlighted lines to get out of syncfrom errormarker import ErrorMarker
from util import delayed
class ErrorReporter(object):
def __init__(self, window, error_report, settings, expand_filename):
self._marker = ErrorMarker(window, error_report, settings)
self._error_report = error_report
self._expand_filename = expand_filename
@delayed(0)
def error(self, filename, line, message):
filename = self._expand_filename(filename)
self._error_report.add_error(filename, line, message)
self._marker.mark_line(filename, line)
self._marker.update_status()
@delayed(0)
def finish(self):
self._error_report.cycle()
self._marker.mark_errors()
def show_errors(self, filename):
self._marker.mark_errors_in(filename)
def hide_errors(self, filename):
self._error_report.clear_file(filename)
self._marker.hide_errors_in(filename)
def update_status(self):
self._marker.update_status()
|
<commit_before>from errormarker import ErrorMarker
from util import delayed
class ErrorReporter(object):
def __init__(self, window, error_report, settings, expand_filename):
self._marker = ErrorMarker(window, error_report, settings)
self._error_report = error_report
self._expand_filename = expand_filename
@delayed(0)
def error(self, filename, line, message):
filename = self._expand_filename(filename)
self._error_report.add_error(filename, line, message)
self._marker.mark_line(filename, line)
self._marker.update_status()
def finish(self):
self._error_report.cycle()
self._marker.mark_errors()
def show_errors(self, filename):
self._marker.mark_errors_in(filename)
def hide_errors(self, filename):
self._error_report.clear_file(filename)
self._marker.hide_errors_in(filename)
def update_status(self):
self._marker.update_status()
<commit_msg>Fix a race condition in error reporting causing highlighted lines to get out of sync<commit_after>from errormarker import ErrorMarker
from util import delayed
class ErrorReporter(object):
def __init__(self, window, error_report, settings, expand_filename):
self._marker = ErrorMarker(window, error_report, settings)
self._error_report = error_report
self._expand_filename = expand_filename
@delayed(0)
def error(self, filename, line, message):
filename = self._expand_filename(filename)
self._error_report.add_error(filename, line, message)
self._marker.mark_line(filename, line)
self._marker.update_status()
@delayed(0)
def finish(self):
self._error_report.cycle()
self._marker.mark_errors()
def show_errors(self, filename):
self._marker.mark_errors_in(filename)
def hide_errors(self, filename):
self._error_report.clear_file(filename)
self._marker.hide_errors_in(filename)
def update_status(self):
self._marker.update_status()
|
9f5e61bf821823c14f6a0640bd334c8732d41296
|
ipkg/files/backends/filesystem.py
|
ipkg/files/backends/filesystem.py
|
try:
from urlparse import urlparse
except ImportError: # Python 3
from urllib.parse import urlparse
from . import BaseFile, BackendException
class LocalFileException(BackendException):
"""An error occurred while accessing a local file."""
class LocalFile(BaseFile):
"""A file on the local filesystem.
"""
def __init__(self, *args, **kw):
super(LocalFile, self).__init__(*args, **kw)
filepath = urlparse(self.name).path
self.__file = open(filepath)
def seek(self, *args):
self.__file.seek(*args)
def tell(self):
return self.__file.tell()
def read(self, *args):
return self.__file.read(*args)
|
import os
try:
from urlparse import urlparse
except ImportError: # Python 3
from urllib.parse import urlparse
from . import BaseFile, BackendException
class LocalFileException(BackendException):
"""An error occurred while accessing a local file."""
class LocalFile(BaseFile):
"""A file on the local filesystem.
"""
def __init__(self, *args, **kw):
super(LocalFile, self).__init__(*args, **kw)
filepath = urlparse(self.name).path
if os.path.isfile(filepath):
self.__file = open(filepath)
else:
raise LocalFileException('Not a file: %s' % filepath)
def seek(self, *args):
self.__file.seek(*args)
def tell(self):
return self.__file.tell()
def read(self, *args):
return self.__file.read(*args)
|
Check if its a file
|
Check if its a file
|
Python
|
mit
|
pmuller/ipkg
|
try:
from urlparse import urlparse
except ImportError: # Python 3
from urllib.parse import urlparse
from . import BaseFile, BackendException
class LocalFileException(BackendException):
"""An error occurred while accessing a local file."""
class LocalFile(BaseFile):
"""A file on the local filesystem.
"""
def __init__(self, *args, **kw):
super(LocalFile, self).__init__(*args, **kw)
filepath = urlparse(self.name).path
self.__file = open(filepath)
def seek(self, *args):
self.__file.seek(*args)
def tell(self):
return self.__file.tell()
def read(self, *args):
return self.__file.read(*args)
Check if its a file
|
import os
try:
from urlparse import urlparse
except ImportError: # Python 3
from urllib.parse import urlparse
from . import BaseFile, BackendException
class LocalFileException(BackendException):
"""An error occurred while accessing a local file."""
class LocalFile(BaseFile):
"""A file on the local filesystem.
"""
def __init__(self, *args, **kw):
super(LocalFile, self).__init__(*args, **kw)
filepath = urlparse(self.name).path
if os.path.isfile(filepath):
self.__file = open(filepath)
else:
raise LocalFileException('Not a file: %s' % filepath)
def seek(self, *args):
self.__file.seek(*args)
def tell(self):
return self.__file.tell()
def read(self, *args):
return self.__file.read(*args)
|
<commit_before>try:
from urlparse import urlparse
except ImportError: # Python 3
from urllib.parse import urlparse
from . import BaseFile, BackendException
class LocalFileException(BackendException):
"""An error occurred while accessing a local file."""
class LocalFile(BaseFile):
"""A file on the local filesystem.
"""
def __init__(self, *args, **kw):
super(LocalFile, self).__init__(*args, **kw)
filepath = urlparse(self.name).path
self.__file = open(filepath)
def seek(self, *args):
self.__file.seek(*args)
def tell(self):
return self.__file.tell()
def read(self, *args):
return self.__file.read(*args)
<commit_msg>Check if its a file<commit_after>
|
import os
try:
from urlparse import urlparse
except ImportError: # Python 3
from urllib.parse import urlparse
from . import BaseFile, BackendException
class LocalFileException(BackendException):
"""An error occurred while accessing a local file."""
class LocalFile(BaseFile):
"""A file on the local filesystem.
"""
def __init__(self, *args, **kw):
super(LocalFile, self).__init__(*args, **kw)
filepath = urlparse(self.name).path
if os.path.isfile(filepath):
self.__file = open(filepath)
else:
raise LocalFileException('Not a file: %s' % filepath)
def seek(self, *args):
self.__file.seek(*args)
def tell(self):
return self.__file.tell()
def read(self, *args):
return self.__file.read(*args)
|
try:
from urlparse import urlparse
except ImportError: # Python 3
from urllib.parse import urlparse
from . import BaseFile, BackendException
class LocalFileException(BackendException):
"""An error occurred while accessing a local file."""
class LocalFile(BaseFile):
"""A file on the local filesystem.
"""
def __init__(self, *args, **kw):
super(LocalFile, self).__init__(*args, **kw)
filepath = urlparse(self.name).path
self.__file = open(filepath)
def seek(self, *args):
self.__file.seek(*args)
def tell(self):
return self.__file.tell()
def read(self, *args):
return self.__file.read(*args)
Check if its a fileimport os
try:
from urlparse import urlparse
except ImportError: # Python 3
from urllib.parse import urlparse
from . import BaseFile, BackendException
class LocalFileException(BackendException):
"""An error occurred while accessing a local file."""
class LocalFile(BaseFile):
"""A file on the local filesystem.
"""
def __init__(self, *args, **kw):
super(LocalFile, self).__init__(*args, **kw)
filepath = urlparse(self.name).path
if os.path.isfile(filepath):
self.__file = open(filepath)
else:
raise LocalFileException('Not a file: %s' % filepath)
def seek(self, *args):
self.__file.seek(*args)
def tell(self):
return self.__file.tell()
def read(self, *args):
return self.__file.read(*args)
|
<commit_before>try:
from urlparse import urlparse
except ImportError: # Python 3
from urllib.parse import urlparse
from . import BaseFile, BackendException
class LocalFileException(BackendException):
"""An error occurred while accessing a local file."""
class LocalFile(BaseFile):
"""A file on the local filesystem.
"""
def __init__(self, *args, **kw):
super(LocalFile, self).__init__(*args, **kw)
filepath = urlparse(self.name).path
self.__file = open(filepath)
def seek(self, *args):
self.__file.seek(*args)
def tell(self):
return self.__file.tell()
def read(self, *args):
return self.__file.read(*args)
<commit_msg>Check if its a file<commit_after>import os
try:
from urlparse import urlparse
except ImportError: # Python 3
from urllib.parse import urlparse
from . import BaseFile, BackendException
class LocalFileException(BackendException):
"""An error occurred while accessing a local file."""
class LocalFile(BaseFile):
"""A file on the local filesystem.
"""
def __init__(self, *args, **kw):
super(LocalFile, self).__init__(*args, **kw)
filepath = urlparse(self.name).path
if os.path.isfile(filepath):
self.__file = open(filepath)
else:
raise LocalFileException('Not a file: %s' % filepath)
def seek(self, *args):
self.__file.seek(*args)
def tell(self):
return self.__file.tell()
def read(self, *args):
return self.__file.read(*args)
|
f12f3d909af496cc2c958cf664c5bdc428eca99e
|
astroquery/nasa_exoplanet_archive/__init__.py
|
astroquery/nasa_exoplanet_archive/__init__.py
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
NASA Exoplanet Archive Query Tool
---------------------------------
Module to query the `NASA Exoplanet Archive <https://exoplanetarchive.ipac.caltech.edu>`_ via `the
API <https://exoplanetarchive.ipac.caltech.edu/docs/program_interfaces.html>`_.
"""
from astropy import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astroquery.nasa_exoplanet_archive`.
"""
url_api = _config.ConfigItem(
"http://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI",
"URL for the NASA Exoplanet Archive API")
url_tap = _config.ConfigItem(
"https://exoplanetarchive.ipac.caltech.edu/TAP/",
"URL for the NASA Exoplanet Archive TAP")
timeout = _config.ConfigItem(
600, "Time limit for requests from the NASA Exoplanet Archive servers")
cache = _config.ConfigItem(False, "Should the requests be cached?")
conf = Conf()
from .core import NasaExoplanetArchive, NasaExoplanetArchiveClass # noqa isort:skip
__all__ = ["NasaExoplanetArchive", "NasaExoplanetArchiveClass", "Conf"]
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
NASA Exoplanet Archive Query Tool
---------------------------------
Module to query the `NASA Exoplanet Archive <https://exoplanetarchive.ipac.caltech.edu>`_ via `the
API <https://exoplanetarchive.ipac.caltech.edu/docs/program_interfaces.html>`_.
"""
from astropy import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astroquery.nasa_exoplanet_archive`.
"""
url_api = _config.ConfigItem(
"https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI",
"URL for the NASA Exoplanet Archive API")
url_tap = _config.ConfigItem(
"https://exoplanetarchive.ipac.caltech.edu/TAP/",
"URL for the NASA Exoplanet Archive TAP")
timeout = _config.ConfigItem(
600, "Time limit for requests from the NASA Exoplanet Archive servers")
cache = _config.ConfigItem(False, "Should the requests be cached?")
conf = Conf()
from .core import NasaExoplanetArchive, NasaExoplanetArchiveClass # noqa isort:skip
__all__ = ["NasaExoplanetArchive", "NasaExoplanetArchiveClass", "Conf"]
|
Add missing s in https for API base URL.
|
Add missing s in https for API base URL.
|
Python
|
bsd-3-clause
|
imbasimba/astroquery,ceb8/astroquery,imbasimba/astroquery,ceb8/astroquery
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
NASA Exoplanet Archive Query Tool
---------------------------------
Module to query the `NASA Exoplanet Archive <https://exoplanetarchive.ipac.caltech.edu>`_ via `the
API <https://exoplanetarchive.ipac.caltech.edu/docs/program_interfaces.html>`_.
"""
from astropy import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astroquery.nasa_exoplanet_archive`.
"""
url_api = _config.ConfigItem(
"http://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI",
"URL for the NASA Exoplanet Archive API")
url_tap = _config.ConfigItem(
"https://exoplanetarchive.ipac.caltech.edu/TAP/",
"URL for the NASA Exoplanet Archive TAP")
timeout = _config.ConfigItem(
600, "Time limit for requests from the NASA Exoplanet Archive servers")
cache = _config.ConfigItem(False, "Should the requests be cached?")
conf = Conf()
from .core import NasaExoplanetArchive, NasaExoplanetArchiveClass # noqa isort:skip
__all__ = ["NasaExoplanetArchive", "NasaExoplanetArchiveClass", "Conf"]
Add missing s in https for API base URL.
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
NASA Exoplanet Archive Query Tool
---------------------------------
Module to query the `NASA Exoplanet Archive <https://exoplanetarchive.ipac.caltech.edu>`_ via `the
API <https://exoplanetarchive.ipac.caltech.edu/docs/program_interfaces.html>`_.
"""
from astropy import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astroquery.nasa_exoplanet_archive`.
"""
url_api = _config.ConfigItem(
"https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI",
"URL for the NASA Exoplanet Archive API")
url_tap = _config.ConfigItem(
"https://exoplanetarchive.ipac.caltech.edu/TAP/",
"URL for the NASA Exoplanet Archive TAP")
timeout = _config.ConfigItem(
600, "Time limit for requests from the NASA Exoplanet Archive servers")
cache = _config.ConfigItem(False, "Should the requests be cached?")
conf = Conf()
from .core import NasaExoplanetArchive, NasaExoplanetArchiveClass # noqa isort:skip
__all__ = ["NasaExoplanetArchive", "NasaExoplanetArchiveClass", "Conf"]
|
<commit_before># Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
NASA Exoplanet Archive Query Tool
---------------------------------
Module to query the `NASA Exoplanet Archive <https://exoplanetarchive.ipac.caltech.edu>`_ via `the
API <https://exoplanetarchive.ipac.caltech.edu/docs/program_interfaces.html>`_.
"""
from astropy import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astroquery.nasa_exoplanet_archive`.
"""
url_api = _config.ConfigItem(
"http://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI",
"URL for the NASA Exoplanet Archive API")
url_tap = _config.ConfigItem(
"https://exoplanetarchive.ipac.caltech.edu/TAP/",
"URL for the NASA Exoplanet Archive TAP")
timeout = _config.ConfigItem(
600, "Time limit for requests from the NASA Exoplanet Archive servers")
cache = _config.ConfigItem(False, "Should the requests be cached?")
conf = Conf()
from .core import NasaExoplanetArchive, NasaExoplanetArchiveClass # noqa isort:skip
__all__ = ["NasaExoplanetArchive", "NasaExoplanetArchiveClass", "Conf"]
<commit_msg>Add missing s in https for API base URL.<commit_after>
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
NASA Exoplanet Archive Query Tool
---------------------------------
Module to query the `NASA Exoplanet Archive <https://exoplanetarchive.ipac.caltech.edu>`_ via `the
API <https://exoplanetarchive.ipac.caltech.edu/docs/program_interfaces.html>`_.
"""
from astropy import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astroquery.nasa_exoplanet_archive`.
"""
url_api = _config.ConfigItem(
"https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI",
"URL for the NASA Exoplanet Archive API")
url_tap = _config.ConfigItem(
"https://exoplanetarchive.ipac.caltech.edu/TAP/",
"URL for the NASA Exoplanet Archive TAP")
timeout = _config.ConfigItem(
600, "Time limit for requests from the NASA Exoplanet Archive servers")
cache = _config.ConfigItem(False, "Should the requests be cached?")
conf = Conf()
from .core import NasaExoplanetArchive, NasaExoplanetArchiveClass # noqa isort:skip
__all__ = ["NasaExoplanetArchive", "NasaExoplanetArchiveClass", "Conf"]
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
NASA Exoplanet Archive Query Tool
---------------------------------
Module to query the `NASA Exoplanet Archive <https://exoplanetarchive.ipac.caltech.edu>`_ via `the
API <https://exoplanetarchive.ipac.caltech.edu/docs/program_interfaces.html>`_.
"""
from astropy import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astroquery.nasa_exoplanet_archive`.
"""
url_api = _config.ConfigItem(
"http://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI",
"URL for the NASA Exoplanet Archive API")
url_tap = _config.ConfigItem(
"https://exoplanetarchive.ipac.caltech.edu/TAP/",
"URL for the NASA Exoplanet Archive TAP")
timeout = _config.ConfigItem(
600, "Time limit for requests from the NASA Exoplanet Archive servers")
cache = _config.ConfigItem(False, "Should the requests be cached?")
conf = Conf()
from .core import NasaExoplanetArchive, NasaExoplanetArchiveClass # noqa isort:skip
__all__ = ["NasaExoplanetArchive", "NasaExoplanetArchiveClass", "Conf"]
Add missing s in https for API base URL.# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
NASA Exoplanet Archive Query Tool
---------------------------------
Module to query the `NASA Exoplanet Archive <https://exoplanetarchive.ipac.caltech.edu>`_ via `the
API <https://exoplanetarchive.ipac.caltech.edu/docs/program_interfaces.html>`_.
"""
from astropy import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astroquery.nasa_exoplanet_archive`.
"""
url_api = _config.ConfigItem(
"https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI",
"URL for the NASA Exoplanet Archive API")
url_tap = _config.ConfigItem(
"https://exoplanetarchive.ipac.caltech.edu/TAP/",
"URL for the NASA Exoplanet Archive TAP")
timeout = _config.ConfigItem(
600, "Time limit for requests from the NASA Exoplanet Archive servers")
cache = _config.ConfigItem(False, "Should the requests be cached?")
conf = Conf()
from .core import NasaExoplanetArchive, NasaExoplanetArchiveClass # noqa isort:skip
__all__ = ["NasaExoplanetArchive", "NasaExoplanetArchiveClass", "Conf"]
|
<commit_before># Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
NASA Exoplanet Archive Query Tool
---------------------------------
Module to query the `NASA Exoplanet Archive <https://exoplanetarchive.ipac.caltech.edu>`_ via `the
API <https://exoplanetarchive.ipac.caltech.edu/docs/program_interfaces.html>`_.
"""
from astropy import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astroquery.nasa_exoplanet_archive`.
"""
url_api = _config.ConfigItem(
"http://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI",
"URL for the NASA Exoplanet Archive API")
url_tap = _config.ConfigItem(
"https://exoplanetarchive.ipac.caltech.edu/TAP/",
"URL for the NASA Exoplanet Archive TAP")
timeout = _config.ConfigItem(
600, "Time limit for requests from the NASA Exoplanet Archive servers")
cache = _config.ConfigItem(False, "Should the requests be cached?")
conf = Conf()
from .core import NasaExoplanetArchive, NasaExoplanetArchiveClass # noqa isort:skip
__all__ = ["NasaExoplanetArchive", "NasaExoplanetArchiveClass", "Conf"]
<commit_msg>Add missing s in https for API base URL.<commit_after># Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
NASA Exoplanet Archive Query Tool
---------------------------------
Module to query the `NASA Exoplanet Archive <https://exoplanetarchive.ipac.caltech.edu>`_ via `the
API <https://exoplanetarchive.ipac.caltech.edu/docs/program_interfaces.html>`_.
"""
from astropy import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astroquery.nasa_exoplanet_archive`.
"""
url_api = _config.ConfigItem(
"https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI",
"URL for the NASA Exoplanet Archive API")
url_tap = _config.ConfigItem(
"https://exoplanetarchive.ipac.caltech.edu/TAP/",
"URL for the NASA Exoplanet Archive TAP")
timeout = _config.ConfigItem(
600, "Time limit for requests from the NASA Exoplanet Archive servers")
cache = _config.ConfigItem(False, "Should the requests be cached?")
conf = Conf()
from .core import NasaExoplanetArchive, NasaExoplanetArchiveClass # noqa isort:skip
__all__ = ["NasaExoplanetArchive", "NasaExoplanetArchiveClass", "Conf"]
|
2261b3c6cb579ae65c1119db45f291e246f536c2
|
examples/main.py
|
examples/main.py
|
import asyncio
import sys
from contextlib import suppress
sys.path.append("..")
from asynccmd import Cmd
class Commander(Cmd):
def __init__(self, intro, prompt):
if sys.platform == 'win32':
super().__init__(mode="Run", run_loop=False)
else:
super().__init__(mode="Reader", run_loop=False)
self.intro = intro
self.prompt = prompt
self.loop = None
def do_tasks(self, arg):
"""
Fake command. Type "prodigy {arg}"
:param arg: args occurred from cmd after command
:return:
"""
print(print(asyncio.Task.all_tasks(loop=self.loop)))
def start(self, loop=None):
self.loop = loop
super().cmdloop(loop)
loop = asyncio.ProactorEventLoop()
#loop = asyncio.get_event_loop()
cmd = Commander(intro="This is example", prompt="example> ")
cmd.start(loop)
try:
loop.run_forever()
except KeyboardInterrupt:
loop.stop()
pending = asyncio.Task.all_tasks(loop=loop)
for task in pending:
task.cancel()
with suppress(asyncio.CancelledError):
loop.run_until_complete(task)
|
import asyncio
import sys
from contextlib import suppress
sys.path.append("..")
from asynccmd import Cmd
class Commander(Cmd):
def __init__(self, intro, prompt):
if sys.platform == 'win32':
super().__init__(mode="Run", run_loop=False)
else:
super().__init__(mode="Reader", run_loop=False)
self.intro = intro
self.prompt = prompt
self.loop = None
def do_tasks(self, arg):
"""
Fake command. Type "prodigy {arg}"
:param arg: args occurred from cmd after command
:return:
"""
print(print(asyncio.Task.all_tasks(loop=self.loop)))
def start(self, loop=None):
self.loop = loop
super().cmdloop(loop)
if sys.platform == 'win32':
loop = asyncio.ProactorEventLoop()
else:
loop = asyncio.get_event_loop()
cmd = Commander(intro="This is example", prompt="example> ")
cmd.start(loop)
try:
loop.run_forever()
except KeyboardInterrupt:
loop.stop()
pending = asyncio.Task.all_tasks(loop=loop)
for task in pending:
task.cancel()
with suppress(asyncio.CancelledError):
loop.run_until_complete(task)
|
FIX example for both Win and NIX
|
FIX example for both Win and NIX
TODO: tasks wont work
|
Python
|
apache-2.0
|
valentinmk/asynccmd
|
import asyncio
import sys
from contextlib import suppress
sys.path.append("..")
from asynccmd import Cmd
class Commander(Cmd):
def __init__(self, intro, prompt):
if sys.platform == 'win32':
super().__init__(mode="Run", run_loop=False)
else:
super().__init__(mode="Reader", run_loop=False)
self.intro = intro
self.prompt = prompt
self.loop = None
def do_tasks(self, arg):
"""
Fake command. Type "prodigy {arg}"
:param arg: args occurred from cmd after command
:return:
"""
print(print(asyncio.Task.all_tasks(loop=self.loop)))
def start(self, loop=None):
self.loop = loop
super().cmdloop(loop)
loop = asyncio.ProactorEventLoop()
#loop = asyncio.get_event_loop()
cmd = Commander(intro="This is example", prompt="example> ")
cmd.start(loop)
try:
loop.run_forever()
except KeyboardInterrupt:
loop.stop()
pending = asyncio.Task.all_tasks(loop=loop)
for task in pending:
task.cancel()
with suppress(asyncio.CancelledError):
loop.run_until_complete(task)
FIX example for both Win and NIX
TODO: tasks wont work
|
import asyncio
import sys
from contextlib import suppress
sys.path.append("..")
from asynccmd import Cmd
class Commander(Cmd):
def __init__(self, intro, prompt):
if sys.platform == 'win32':
super().__init__(mode="Run", run_loop=False)
else:
super().__init__(mode="Reader", run_loop=False)
self.intro = intro
self.prompt = prompt
self.loop = None
def do_tasks(self, arg):
"""
Fake command. Type "prodigy {arg}"
:param arg: args occurred from cmd after command
:return:
"""
print(print(asyncio.Task.all_tasks(loop=self.loop)))
def start(self, loop=None):
self.loop = loop
super().cmdloop(loop)
if sys.platform == 'win32':
loop = asyncio.ProactorEventLoop()
else:
loop = asyncio.get_event_loop()
cmd = Commander(intro="This is example", prompt="example> ")
cmd.start(loop)
try:
loop.run_forever()
except KeyboardInterrupt:
loop.stop()
pending = asyncio.Task.all_tasks(loop=loop)
for task in pending:
task.cancel()
with suppress(asyncio.CancelledError):
loop.run_until_complete(task)
|
<commit_before>import asyncio
import sys
from contextlib import suppress
sys.path.append("..")
from asynccmd import Cmd
class Commander(Cmd):
def __init__(self, intro, prompt):
if sys.platform == 'win32':
super().__init__(mode="Run", run_loop=False)
else:
super().__init__(mode="Reader", run_loop=False)
self.intro = intro
self.prompt = prompt
self.loop = None
def do_tasks(self, arg):
"""
Fake command. Type "prodigy {arg}"
:param arg: args occurred from cmd after command
:return:
"""
print(print(asyncio.Task.all_tasks(loop=self.loop)))
def start(self, loop=None):
self.loop = loop
super().cmdloop(loop)
loop = asyncio.ProactorEventLoop()
#loop = asyncio.get_event_loop()
cmd = Commander(intro="This is example", prompt="example> ")
cmd.start(loop)
try:
loop.run_forever()
except KeyboardInterrupt:
loop.stop()
pending = asyncio.Task.all_tasks(loop=loop)
for task in pending:
task.cancel()
with suppress(asyncio.CancelledError):
loop.run_until_complete(task)
<commit_msg>FIX example for both Win and NIX
TODO: tasks wont work<commit_after>
|
import asyncio
import sys
from contextlib import suppress
sys.path.append("..")
from asynccmd import Cmd
class Commander(Cmd):
def __init__(self, intro, prompt):
if sys.platform == 'win32':
super().__init__(mode="Run", run_loop=False)
else:
super().__init__(mode="Reader", run_loop=False)
self.intro = intro
self.prompt = prompt
self.loop = None
def do_tasks(self, arg):
"""
Fake command. Type "prodigy {arg}"
:param arg: args occurred from cmd after command
:return:
"""
print(print(asyncio.Task.all_tasks(loop=self.loop)))
def start(self, loop=None):
self.loop = loop
super().cmdloop(loop)
if sys.platform == 'win32':
loop = asyncio.ProactorEventLoop()
else:
loop = asyncio.get_event_loop()
cmd = Commander(intro="This is example", prompt="example> ")
cmd.start(loop)
try:
loop.run_forever()
except KeyboardInterrupt:
loop.stop()
pending = asyncio.Task.all_tasks(loop=loop)
for task in pending:
task.cancel()
with suppress(asyncio.CancelledError):
loop.run_until_complete(task)
|
import asyncio
import sys
from contextlib import suppress
sys.path.append("..")
from asynccmd import Cmd
class Commander(Cmd):
def __init__(self, intro, prompt):
if sys.platform == 'win32':
super().__init__(mode="Run", run_loop=False)
else:
super().__init__(mode="Reader", run_loop=False)
self.intro = intro
self.prompt = prompt
self.loop = None
def do_tasks(self, arg):
"""
Fake command. Type "prodigy {arg}"
:param arg: args occurred from cmd after command
:return:
"""
print(print(asyncio.Task.all_tasks(loop=self.loop)))
def start(self, loop=None):
self.loop = loop
super().cmdloop(loop)
loop = asyncio.ProactorEventLoop()
#loop = asyncio.get_event_loop()
cmd = Commander(intro="This is example", prompt="example> ")
cmd.start(loop)
try:
loop.run_forever()
except KeyboardInterrupt:
loop.stop()
pending = asyncio.Task.all_tasks(loop=loop)
for task in pending:
task.cancel()
with suppress(asyncio.CancelledError):
loop.run_until_complete(task)
FIX example for both Win and NIX
TODO: tasks wont workimport asyncio
import sys
from contextlib import suppress
sys.path.append("..")
from asynccmd import Cmd
class Commander(Cmd):
def __init__(self, intro, prompt):
if sys.platform == 'win32':
super().__init__(mode="Run", run_loop=False)
else:
super().__init__(mode="Reader", run_loop=False)
self.intro = intro
self.prompt = prompt
self.loop = None
def do_tasks(self, arg):
"""
Fake command. Type "prodigy {arg}"
:param arg: args occurred from cmd after command
:return:
"""
print(print(asyncio.Task.all_tasks(loop=self.loop)))
def start(self, loop=None):
self.loop = loop
super().cmdloop(loop)
if sys.platform == 'win32':
loop = asyncio.ProactorEventLoop()
else:
loop = asyncio.get_event_loop()
cmd = Commander(intro="This is example", prompt="example> ")
cmd.start(loop)
try:
loop.run_forever()
except KeyboardInterrupt:
loop.stop()
pending = asyncio.Task.all_tasks(loop=loop)
for task in pending:
task.cancel()
with suppress(asyncio.CancelledError):
loop.run_until_complete(task)
|
<commit_before>import asyncio
import sys
from contextlib import suppress
sys.path.append("..")
from asynccmd import Cmd
class Commander(Cmd):
def __init__(self, intro, prompt):
if sys.platform == 'win32':
super().__init__(mode="Run", run_loop=False)
else:
super().__init__(mode="Reader", run_loop=False)
self.intro = intro
self.prompt = prompt
self.loop = None
def do_tasks(self, arg):
"""
Fake command. Type "prodigy {arg}"
:param arg: args occurred from cmd after command
:return:
"""
print(print(asyncio.Task.all_tasks(loop=self.loop)))
def start(self, loop=None):
self.loop = loop
super().cmdloop(loop)
loop = asyncio.ProactorEventLoop()
#loop = asyncio.get_event_loop()
cmd = Commander(intro="This is example", prompt="example> ")
cmd.start(loop)
try:
loop.run_forever()
except KeyboardInterrupt:
loop.stop()
pending = asyncio.Task.all_tasks(loop=loop)
for task in pending:
task.cancel()
with suppress(asyncio.CancelledError):
loop.run_until_complete(task)
<commit_msg>FIX example for both Win and NIX
TODO: tasks wont work<commit_after>import asyncio
import sys
from contextlib import suppress
sys.path.append("..")
from asynccmd import Cmd
class Commander(Cmd):
def __init__(self, intro, prompt):
if sys.platform == 'win32':
super().__init__(mode="Run", run_loop=False)
else:
super().__init__(mode="Reader", run_loop=False)
self.intro = intro
self.prompt = prompt
self.loop = None
def do_tasks(self, arg):
"""
Fake command. Type "prodigy {arg}"
:param arg: args occurred from cmd after command
:return:
"""
print(print(asyncio.Task.all_tasks(loop=self.loop)))
def start(self, loop=None):
self.loop = loop
super().cmdloop(loop)
if sys.platform == 'win32':
loop = asyncio.ProactorEventLoop()
else:
loop = asyncio.get_event_loop()
cmd = Commander(intro="This is example", prompt="example> ")
cmd.start(loop)
try:
loop.run_forever()
except KeyboardInterrupt:
loop.stop()
pending = asyncio.Task.all_tasks(loop=loop)
for task in pending:
task.cancel()
with suppress(asyncio.CancelledError):
loop.run_until_complete(task)
|
df40edea93b530752cc21c3de04825bc791d4910
|
parser2.py
|
parser2.py
|
from pprint import pprint
input = open('example_ignition.txt').read()
hands = input.split('\n\n\n')
for i, h in enumerate(hands):
segments = "seats preflop flop turn river".split()
s = h.split('\n*** ')
hands[i] = {}
while len(s) > 1:
# We don't always have flop, turn, riv, but last element is
# always Summary.
k = segments.pop(0)
v = s.pop(0).splitlines()
hands[i][k] = v
hands[i]['summary'] = s.pop(0).splitlines()
assert len(s) == 0
## [ { s:[] p:[] f:[] s:[] } { s:[] p:[] f:[] t:[] r:[] s:[] } {} {} ]
print(hands[0])
|
from pprint import pprint
input = open('example_ignition.txt').read()
hands = input.split('\n\n\n')
class Hand:
def __init__(self, se=None, p=None, f=None, t=None, r=None, su=None):
self.seats = se
self.preflop = p
self.flop = f
self.turn = t
self.river = r
self.summary = su
def __repr__(self):
return str(self.__dict__)
for i, h in enumerate(hands):
segments = "seats preflop flop turn river".split()
s = h.split('\n*** ')
hands[i] = Hand()
while len(s) > 1:
# We don't always have flop, turn, riv, but last element is
# always Summary.
k = segments.pop(0)
v = s.pop(0).splitlines()
hands[i].__dict__[k] = v
hands[i].summary = s.pop(0).splitlines()
assert len(s) == 0
## [ { s:[] p:[] f:[] s:[] } { s:[] p:[] f:[] t:[] r:[] s:[] } {} {} ]
print(hands[0])
|
Use class instead of dict, preparing for methods.
|
Use class instead of dict, preparing for methods.
|
Python
|
mit
|
zimolzak/Ignition-poker-parser
|
from pprint import pprint
input = open('example_ignition.txt').read()
hands = input.split('\n\n\n')
for i, h in enumerate(hands):
segments = "seats preflop flop turn river".split()
s = h.split('\n*** ')
hands[i] = {}
while len(s) > 1:
# We don't always have flop, turn, riv, but last element is
# always Summary.
k = segments.pop(0)
v = s.pop(0).splitlines()
hands[i][k] = v
hands[i]['summary'] = s.pop(0).splitlines()
assert len(s) == 0
## [ { s:[] p:[] f:[] s:[] } { s:[] p:[] f:[] t:[] r:[] s:[] } {} {} ]
print(hands[0])
Use class instead of dict, preparing for methods.
|
from pprint import pprint
input = open('example_ignition.txt').read()
hands = input.split('\n\n\n')
class Hand:
def __init__(self, se=None, p=None, f=None, t=None, r=None, su=None):
self.seats = se
self.preflop = p
self.flop = f
self.turn = t
self.river = r
self.summary = su
def __repr__(self):
return str(self.__dict__)
for i, h in enumerate(hands):
segments = "seats preflop flop turn river".split()
s = h.split('\n*** ')
hands[i] = Hand()
while len(s) > 1:
# We don't always have flop, turn, riv, but last element is
# always Summary.
k = segments.pop(0)
v = s.pop(0).splitlines()
hands[i].__dict__[k] = v
hands[i].summary = s.pop(0).splitlines()
assert len(s) == 0
## [ { s:[] p:[] f:[] s:[] } { s:[] p:[] f:[] t:[] r:[] s:[] } {} {} ]
print(hands[0])
|
<commit_before>from pprint import pprint
input = open('example_ignition.txt').read()
hands = input.split('\n\n\n')
for i, h in enumerate(hands):
segments = "seats preflop flop turn river".split()
s = h.split('\n*** ')
hands[i] = {}
while len(s) > 1:
# We don't always have flop, turn, riv, but last element is
# always Summary.
k = segments.pop(0)
v = s.pop(0).splitlines()
hands[i][k] = v
hands[i]['summary'] = s.pop(0).splitlines()
assert len(s) == 0
## [ { s:[] p:[] f:[] s:[] } { s:[] p:[] f:[] t:[] r:[] s:[] } {} {} ]
print(hands[0])
<commit_msg>Use class instead of dict, preparing for methods.<commit_after>
|
from pprint import pprint
input = open('example_ignition.txt').read()
hands = input.split('\n\n\n')
class Hand:
def __init__(self, se=None, p=None, f=None, t=None, r=None, su=None):
self.seats = se
self.preflop = p
self.flop = f
self.turn = t
self.river = r
self.summary = su
def __repr__(self):
return str(self.__dict__)
for i, h in enumerate(hands):
segments = "seats preflop flop turn river".split()
s = h.split('\n*** ')
hands[i] = Hand()
while len(s) > 1:
# We don't always have flop, turn, riv, but last element is
# always Summary.
k = segments.pop(0)
v = s.pop(0).splitlines()
hands[i].__dict__[k] = v
hands[i].summary = s.pop(0).splitlines()
assert len(s) == 0
## [ { s:[] p:[] f:[] s:[] } { s:[] p:[] f:[] t:[] r:[] s:[] } {} {} ]
print(hands[0])
|
from pprint import pprint
input = open('example_ignition.txt').read()
hands = input.split('\n\n\n')
for i, h in enumerate(hands):
segments = "seats preflop flop turn river".split()
s = h.split('\n*** ')
hands[i] = {}
while len(s) > 1:
# We don't always have flop, turn, riv, but last element is
# always Summary.
k = segments.pop(0)
v = s.pop(0).splitlines()
hands[i][k] = v
hands[i]['summary'] = s.pop(0).splitlines()
assert len(s) == 0
## [ { s:[] p:[] f:[] s:[] } { s:[] p:[] f:[] t:[] r:[] s:[] } {} {} ]
print(hands[0])
Use class instead of dict, preparing for methods.from pprint import pprint
input = open('example_ignition.txt').read()
hands = input.split('\n\n\n')
class Hand:
def __init__(self, se=None, p=None, f=None, t=None, r=None, su=None):
self.seats = se
self.preflop = p
self.flop = f
self.turn = t
self.river = r
self.summary = su
def __repr__(self):
return str(self.__dict__)
for i, h in enumerate(hands):
segments = "seats preflop flop turn river".split()
s = h.split('\n*** ')
hands[i] = Hand()
while len(s) > 1:
# We don't always have flop, turn, riv, but last element is
# always Summary.
k = segments.pop(0)
v = s.pop(0).splitlines()
hands[i].__dict__[k] = v
hands[i].summary = s.pop(0).splitlines()
assert len(s) == 0
## [ { s:[] p:[] f:[] s:[] } { s:[] p:[] f:[] t:[] r:[] s:[] } {} {} ]
print(hands[0])
|
<commit_before>from pprint import pprint
input = open('example_ignition.txt').read()
hands = input.split('\n\n\n')
for i, h in enumerate(hands):
segments = "seats preflop flop turn river".split()
s = h.split('\n*** ')
hands[i] = {}
while len(s) > 1:
# We don't always have flop, turn, riv, but last element is
# always Summary.
k = segments.pop(0)
v = s.pop(0).splitlines()
hands[i][k] = v
hands[i]['summary'] = s.pop(0).splitlines()
assert len(s) == 0
## [ { s:[] p:[] f:[] s:[] } { s:[] p:[] f:[] t:[] r:[] s:[] } {} {} ]
print(hands[0])
<commit_msg>Use class instead of dict, preparing for methods.<commit_after>from pprint import pprint
input = open('example_ignition.txt').read()
hands = input.split('\n\n\n')
class Hand:
def __init__(self, se=None, p=None, f=None, t=None, r=None, su=None):
self.seats = se
self.preflop = p
self.flop = f
self.turn = t
self.river = r
self.summary = su
def __repr__(self):
return str(self.__dict__)
for i, h in enumerate(hands):
segments = "seats preflop flop turn river".split()
s = h.split('\n*** ')
hands[i] = Hand()
while len(s) > 1:
# We don't always have flop, turn, riv, but last element is
# always Summary.
k = segments.pop(0)
v = s.pop(0).splitlines()
hands[i].__dict__[k] = v
hands[i].summary = s.pop(0).splitlines()
assert len(s) == 0
## [ { s:[] p:[] f:[] s:[] } { s:[] p:[] f:[] t:[] r:[] s:[] } {} {} ]
print(hands[0])
|
f94eefc0fe1d869753ec7bbe5e315c5df6cc8303
|
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/IBEnt,AndreLamurias/IBRel,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()
|
17b6b91cd898f48f18b941dfb2250e7a00bc0506
|
kyokai/context.py
|
kyokai/context.py
|
"""
Stores HTTPRequestContext
"""
from asphalt.core import Context
from typeguard import check_argument_types
class HTTPRequestContext(Context):
"""
Sub-class of context used for HTTP requests.
"""
cfg = {}
def __init__(self, request, parent: Context):
assert check_argument_types()
super().__init__(parent=parent)
self.request = request
|
"""
Stores HTTPRequestContext
"""
from asphalt.core import Context
from typeguard import check_argument_types
import kyokai
class HTTPRequestContext(Context):
"""
Sub-class of context used for HTTP requests.
"""
cfg = {}
def __init__(self, request, parent: Context):
assert check_argument_types()
super().__init__(parent=parent)
self._request = request
@property
def request(self) -> 'kyokai.Request':
return self._request
|
Make request a property on HTTPRequestContext.
|
Make request a property on HTTPRequestContext.
|
Python
|
mit
|
SunDwarf/Kyoukai
|
"""
Stores HTTPRequestContext
"""
from asphalt.core import Context
from typeguard import check_argument_types
class HTTPRequestContext(Context):
"""
Sub-class of context used for HTTP requests.
"""
cfg = {}
def __init__(self, request, parent: Context):
assert check_argument_types()
super().__init__(parent=parent)
self.request = request
Make request a property on HTTPRequestContext.
|
"""
Stores HTTPRequestContext
"""
from asphalt.core import Context
from typeguard import check_argument_types
import kyokai
class HTTPRequestContext(Context):
"""
Sub-class of context used for HTTP requests.
"""
cfg = {}
def __init__(self, request, parent: Context):
assert check_argument_types()
super().__init__(parent=parent)
self._request = request
@property
def request(self) -> 'kyokai.Request':
return self._request
|
<commit_before>"""
Stores HTTPRequestContext
"""
from asphalt.core import Context
from typeguard import check_argument_types
class HTTPRequestContext(Context):
"""
Sub-class of context used for HTTP requests.
"""
cfg = {}
def __init__(self, request, parent: Context):
assert check_argument_types()
super().__init__(parent=parent)
self.request = request
<commit_msg>Make request a property on HTTPRequestContext.<commit_after>
|
"""
Stores HTTPRequestContext
"""
from asphalt.core import Context
from typeguard import check_argument_types
import kyokai
class HTTPRequestContext(Context):
"""
Sub-class of context used for HTTP requests.
"""
cfg = {}
def __init__(self, request, parent: Context):
assert check_argument_types()
super().__init__(parent=parent)
self._request = request
@property
def request(self) -> 'kyokai.Request':
return self._request
|
"""
Stores HTTPRequestContext
"""
from asphalt.core import Context
from typeguard import check_argument_types
class HTTPRequestContext(Context):
"""
Sub-class of context used for HTTP requests.
"""
cfg = {}
def __init__(self, request, parent: Context):
assert check_argument_types()
super().__init__(parent=parent)
self.request = request
Make request a property on HTTPRequestContext."""
Stores HTTPRequestContext
"""
from asphalt.core import Context
from typeguard import check_argument_types
import kyokai
class HTTPRequestContext(Context):
"""
Sub-class of context used for HTTP requests.
"""
cfg = {}
def __init__(self, request, parent: Context):
assert check_argument_types()
super().__init__(parent=parent)
self._request = request
@property
def request(self) -> 'kyokai.Request':
return self._request
|
<commit_before>"""
Stores HTTPRequestContext
"""
from asphalt.core import Context
from typeguard import check_argument_types
class HTTPRequestContext(Context):
"""
Sub-class of context used for HTTP requests.
"""
cfg = {}
def __init__(self, request, parent: Context):
assert check_argument_types()
super().__init__(parent=parent)
self.request = request
<commit_msg>Make request a property on HTTPRequestContext.<commit_after>"""
Stores HTTPRequestContext
"""
from asphalt.core import Context
from typeguard import check_argument_types
import kyokai
class HTTPRequestContext(Context):
"""
Sub-class of context used for HTTP requests.
"""
cfg = {}
def __init__(self, request, parent: Context):
assert check_argument_types()
super().__init__(parent=parent)
self._request = request
@property
def request(self) -> 'kyokai.Request':
return self._request
|
5640a85b2095083da3617380fe315b5c4f26560f
|
rsfmri/examples/rsfmri_wrapper.py
|
rsfmri/examples/rsfmri_wrapper.py
|
from rsfmri import utils
from rsfmri import register
""" This is done in native space, add warped after (Renaud others)??
despike?
split raw func
realign (no slicetime (ANTS))
realign w/slicetime (spm)
generate movement regressors
make meanfunc
files -> 4dfunc
(bias correct anat and meanfunc?)
register anat to meanfunc
pull whole brain, white, ventricle rois (aparc)
erode white and ventricle
bandpass filter 4ddata
extract global, white, ventricle
bandpass filter movement regressors
generate fsf
censor motion from model??
run model
grab residuals
"""
if __name__ == '__main__':
print 'sample rsfmri'
|
from rsfmri import utils
from rsfmri import register
""" This is done in native space, add warped after (Renaud others)??
despike?
split raw func
realign (no slicetime (ANTS))
realign w/slicetime (spm)
generate movement regressors
make meanfunc
remove values < 100 (outside brain)
files -> 4dfunc
(bias correct anat and meanfunc?) not right now
register anat to meanfunc
pull whole brain, white, ventricle rois (aparc)
erode white and ventricle
bandpass filter 4ddata
extract global, white, ventricle
bandpass filter movement regressors
generate fsf
censor motion from model??
run model
grab residuals
"""
if __name__ == '__main__':
print 'sample rsfmri'
|
Update wrapper to show latest changes to code
|
Update wrapper to show latest changes to code
|
Python
|
mit
|
klarnemann/jagust_rsfmri,klarnemann/jagust_rsfmri,klarnemann/jagust_rsfmri
|
from rsfmri import utils
from rsfmri import register
""" This is done in native space, add warped after (Renaud others)??
despike?
split raw func
realign (no slicetime (ANTS))
realign w/slicetime (spm)
generate movement regressors
make meanfunc
files -> 4dfunc
(bias correct anat and meanfunc?)
register anat to meanfunc
pull whole brain, white, ventricle rois (aparc)
erode white and ventricle
bandpass filter 4ddata
extract global, white, ventricle
bandpass filter movement regressors
generate fsf
censor motion from model??
run model
grab residuals
"""
if __name__ == '__main__':
print 'sample rsfmri'Update wrapper to show latest changes to code
|
from rsfmri import utils
from rsfmri import register
""" This is done in native space, add warped after (Renaud others)??
despike?
split raw func
realign (no slicetime (ANTS))
realign w/slicetime (spm)
generate movement regressors
make meanfunc
remove values < 100 (outside brain)
files -> 4dfunc
(bias correct anat and meanfunc?) not right now
register anat to meanfunc
pull whole brain, white, ventricle rois (aparc)
erode white and ventricle
bandpass filter 4ddata
extract global, white, ventricle
bandpass filter movement regressors
generate fsf
censor motion from model??
run model
grab residuals
"""
if __name__ == '__main__':
print 'sample rsfmri'
|
<commit_before>
from rsfmri import utils
from rsfmri import register
""" This is done in native space, add warped after (Renaud others)??
despike?
split raw func
realign (no slicetime (ANTS))
realign w/slicetime (spm)
generate movement regressors
make meanfunc
files -> 4dfunc
(bias correct anat and meanfunc?)
register anat to meanfunc
pull whole brain, white, ventricle rois (aparc)
erode white and ventricle
bandpass filter 4ddata
extract global, white, ventricle
bandpass filter movement regressors
generate fsf
censor motion from model??
run model
grab residuals
"""
if __name__ == '__main__':
print 'sample rsfmri'<commit_msg>Update wrapper to show latest changes to code<commit_after>
|
from rsfmri import utils
from rsfmri import register
""" This is done in native space, add warped after (Renaud others)??
despike?
split raw func
realign (no slicetime (ANTS))
realign w/slicetime (spm)
generate movement regressors
make meanfunc
remove values < 100 (outside brain)
files -> 4dfunc
(bias correct anat and meanfunc?) not right now
register anat to meanfunc
pull whole brain, white, ventricle rois (aparc)
erode white and ventricle
bandpass filter 4ddata
extract global, white, ventricle
bandpass filter movement regressors
generate fsf
censor motion from model??
run model
grab residuals
"""
if __name__ == '__main__':
print 'sample rsfmri'
|
from rsfmri import utils
from rsfmri import register
""" This is done in native space, add warped after (Renaud others)??
despike?
split raw func
realign (no slicetime (ANTS))
realign w/slicetime (spm)
generate movement regressors
make meanfunc
files -> 4dfunc
(bias correct anat and meanfunc?)
register anat to meanfunc
pull whole brain, white, ventricle rois (aparc)
erode white and ventricle
bandpass filter 4ddata
extract global, white, ventricle
bandpass filter movement regressors
generate fsf
censor motion from model??
run model
grab residuals
"""
if __name__ == '__main__':
print 'sample rsfmri'Update wrapper to show latest changes to code
from rsfmri import utils
from rsfmri import register
""" This is done in native space, add warped after (Renaud others)??
despike?
split raw func
realign (no slicetime (ANTS))
realign w/slicetime (spm)
generate movement regressors
make meanfunc
remove values < 100 (outside brain)
files -> 4dfunc
(bias correct anat and meanfunc?) not right now
register anat to meanfunc
pull whole brain, white, ventricle rois (aparc)
erode white and ventricle
bandpass filter 4ddata
extract global, white, ventricle
bandpass filter movement regressors
generate fsf
censor motion from model??
run model
grab residuals
"""
if __name__ == '__main__':
print 'sample rsfmri'
|
<commit_before>
from rsfmri import utils
from rsfmri import register
""" This is done in native space, add warped after (Renaud others)??
despike?
split raw func
realign (no slicetime (ANTS))
realign w/slicetime (spm)
generate movement regressors
make meanfunc
files -> 4dfunc
(bias correct anat and meanfunc?)
register anat to meanfunc
pull whole brain, white, ventricle rois (aparc)
erode white and ventricle
bandpass filter 4ddata
extract global, white, ventricle
bandpass filter movement regressors
generate fsf
censor motion from model??
run model
grab residuals
"""
if __name__ == '__main__':
print 'sample rsfmri'<commit_msg>Update wrapper to show latest changes to code<commit_after>
from rsfmri import utils
from rsfmri import register
""" This is done in native space, add warped after (Renaud others)??
despike?
split raw func
realign (no slicetime (ANTS))
realign w/slicetime (spm)
generate movement regressors
make meanfunc
remove values < 100 (outside brain)
files -> 4dfunc
(bias correct anat and meanfunc?) not right now
register anat to meanfunc
pull whole brain, white, ventricle rois (aparc)
erode white and ventricle
bandpass filter 4ddata
extract global, white, ventricle
bandpass filter movement regressors
generate fsf
censor motion from model??
run model
grab residuals
"""
if __name__ == '__main__':
print 'sample rsfmri'
|
8df03bdd466270127b4185afa792d26e71e323f7
|
avalonstar/apps/api/views.py
|
avalonstar/apps/api/views.py
|
# -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404
from rest_framework import viewsets
from rest_framework.response import Response
from apps.broadcasts.models import Broadcast, Host, Raid, Series
from apps.games.models import Game
from apps.subscribers.models import Ticket
from .serializers import (BroadcastSerializer, GameSerializer, HostSerializer,
RaidSerializer, SeriesSerializer, TicketSerializer)
class BroadcastViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Broadcast.objects.all()
serializer_class = BroadcastSerializer
class HostViewSet(viewsets.ModelViewSet):
queryset = Host.objects.all()
serializer_class = HostSerializer
class RaidViewSet(viewsets.ModelViewSet):
queryset = Raid.objects.all()
serializer_class = RaidSerializer
class TicketViewSet(viewsets.ModelViewSet):
queryset = Ticket.objects.all()
serializer_class = TicketSerializer
def retrieve(self, request, pk=None):
queryset = Ticket.objects.all()
ticket = get_object_or_404(queryset, name=pk)
serializer = TicketSerializer(ticket)
return Response(serializer.data)
|
# -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404
from rest_framework import viewsets
from rest_framework.response import Response
from apps.broadcasts.models import Broadcast, Host, Raid, Series
from apps.games.models import Game
from apps.subscribers.models import Ticket
from .serializers import (BroadcastSerializer, GameSerializer, HostSerializer,
RaidSerializer, SeriesSerializer, TicketSerializer)
class BroadcastViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Broadcast.objects.all()
serializer_class = BroadcastSerializer
class HostViewSet(viewsets.ModelViewSet):
queryset = Host.objects.all()
serializer_class = HostSerializer
class RaidViewSet(viewsets.ModelViewSet):
queryset = Raid.objects.all()
serializer_class = RaidSerializer
class TicketViewSet(viewsets.ModelViewSet):
queryset = Ticket.objects.order_by('-updated')
serializer_class = TicketSerializer
def retrieve(self, request, pk=None):
queryset = Ticket.objects.all()
ticket = get_object_or_404(queryset, name=pk)
serializer = TicketSerializer(ticket)
return Response(serializer.data)
|
Order the tickets correctly in the API.
|
Order the tickets correctly in the API.
|
Python
|
apache-2.0
|
bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv
|
# -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404
from rest_framework import viewsets
from rest_framework.response import Response
from apps.broadcasts.models import Broadcast, Host, Raid, Series
from apps.games.models import Game
from apps.subscribers.models import Ticket
from .serializers import (BroadcastSerializer, GameSerializer, HostSerializer,
RaidSerializer, SeriesSerializer, TicketSerializer)
class BroadcastViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Broadcast.objects.all()
serializer_class = BroadcastSerializer
class HostViewSet(viewsets.ModelViewSet):
queryset = Host.objects.all()
serializer_class = HostSerializer
class RaidViewSet(viewsets.ModelViewSet):
queryset = Raid.objects.all()
serializer_class = RaidSerializer
class TicketViewSet(viewsets.ModelViewSet):
queryset = Ticket.objects.all()
serializer_class = TicketSerializer
def retrieve(self, request, pk=None):
queryset = Ticket.objects.all()
ticket = get_object_or_404(queryset, name=pk)
serializer = TicketSerializer(ticket)
return Response(serializer.data)
Order the tickets correctly in the API.
|
# -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404
from rest_framework import viewsets
from rest_framework.response import Response
from apps.broadcasts.models import Broadcast, Host, Raid, Series
from apps.games.models import Game
from apps.subscribers.models import Ticket
from .serializers import (BroadcastSerializer, GameSerializer, HostSerializer,
RaidSerializer, SeriesSerializer, TicketSerializer)
class BroadcastViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Broadcast.objects.all()
serializer_class = BroadcastSerializer
class HostViewSet(viewsets.ModelViewSet):
queryset = Host.objects.all()
serializer_class = HostSerializer
class RaidViewSet(viewsets.ModelViewSet):
queryset = Raid.objects.all()
serializer_class = RaidSerializer
class TicketViewSet(viewsets.ModelViewSet):
queryset = Ticket.objects.order_by('-updated')
serializer_class = TicketSerializer
def retrieve(self, request, pk=None):
queryset = Ticket.objects.all()
ticket = get_object_or_404(queryset, name=pk)
serializer = TicketSerializer(ticket)
return Response(serializer.data)
|
<commit_before># -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404
from rest_framework import viewsets
from rest_framework.response import Response
from apps.broadcasts.models import Broadcast, Host, Raid, Series
from apps.games.models import Game
from apps.subscribers.models import Ticket
from .serializers import (BroadcastSerializer, GameSerializer, HostSerializer,
RaidSerializer, SeriesSerializer, TicketSerializer)
class BroadcastViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Broadcast.objects.all()
serializer_class = BroadcastSerializer
class HostViewSet(viewsets.ModelViewSet):
queryset = Host.objects.all()
serializer_class = HostSerializer
class RaidViewSet(viewsets.ModelViewSet):
queryset = Raid.objects.all()
serializer_class = RaidSerializer
class TicketViewSet(viewsets.ModelViewSet):
queryset = Ticket.objects.all()
serializer_class = TicketSerializer
def retrieve(self, request, pk=None):
queryset = Ticket.objects.all()
ticket = get_object_or_404(queryset, name=pk)
serializer = TicketSerializer(ticket)
return Response(serializer.data)
<commit_msg>Order the tickets correctly in the API.<commit_after>
|
# -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404
from rest_framework import viewsets
from rest_framework.response import Response
from apps.broadcasts.models import Broadcast, Host, Raid, Series
from apps.games.models import Game
from apps.subscribers.models import Ticket
from .serializers import (BroadcastSerializer, GameSerializer, HostSerializer,
RaidSerializer, SeriesSerializer, TicketSerializer)
class BroadcastViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Broadcast.objects.all()
serializer_class = BroadcastSerializer
class HostViewSet(viewsets.ModelViewSet):
queryset = Host.objects.all()
serializer_class = HostSerializer
class RaidViewSet(viewsets.ModelViewSet):
queryset = Raid.objects.all()
serializer_class = RaidSerializer
class TicketViewSet(viewsets.ModelViewSet):
queryset = Ticket.objects.order_by('-updated')
serializer_class = TicketSerializer
def retrieve(self, request, pk=None):
queryset = Ticket.objects.all()
ticket = get_object_or_404(queryset, name=pk)
serializer = TicketSerializer(ticket)
return Response(serializer.data)
|
# -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404
from rest_framework import viewsets
from rest_framework.response import Response
from apps.broadcasts.models import Broadcast, Host, Raid, Series
from apps.games.models import Game
from apps.subscribers.models import Ticket
from .serializers import (BroadcastSerializer, GameSerializer, HostSerializer,
RaidSerializer, SeriesSerializer, TicketSerializer)
class BroadcastViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Broadcast.objects.all()
serializer_class = BroadcastSerializer
class HostViewSet(viewsets.ModelViewSet):
queryset = Host.objects.all()
serializer_class = HostSerializer
class RaidViewSet(viewsets.ModelViewSet):
queryset = Raid.objects.all()
serializer_class = RaidSerializer
class TicketViewSet(viewsets.ModelViewSet):
queryset = Ticket.objects.all()
serializer_class = TicketSerializer
def retrieve(self, request, pk=None):
queryset = Ticket.objects.all()
ticket = get_object_or_404(queryset, name=pk)
serializer = TicketSerializer(ticket)
return Response(serializer.data)
Order the tickets correctly in the API.# -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404
from rest_framework import viewsets
from rest_framework.response import Response
from apps.broadcasts.models import Broadcast, Host, Raid, Series
from apps.games.models import Game
from apps.subscribers.models import Ticket
from .serializers import (BroadcastSerializer, GameSerializer, HostSerializer,
RaidSerializer, SeriesSerializer, TicketSerializer)
class BroadcastViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Broadcast.objects.all()
serializer_class = BroadcastSerializer
class HostViewSet(viewsets.ModelViewSet):
queryset = Host.objects.all()
serializer_class = HostSerializer
class RaidViewSet(viewsets.ModelViewSet):
queryset = Raid.objects.all()
serializer_class = RaidSerializer
class TicketViewSet(viewsets.ModelViewSet):
queryset = Ticket.objects.order_by('-updated')
serializer_class = TicketSerializer
def retrieve(self, request, pk=None):
queryset = Ticket.objects.all()
ticket = get_object_or_404(queryset, name=pk)
serializer = TicketSerializer(ticket)
return Response(serializer.data)
|
<commit_before># -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404
from rest_framework import viewsets
from rest_framework.response import Response
from apps.broadcasts.models import Broadcast, Host, Raid, Series
from apps.games.models import Game
from apps.subscribers.models import Ticket
from .serializers import (BroadcastSerializer, GameSerializer, HostSerializer,
RaidSerializer, SeriesSerializer, TicketSerializer)
class BroadcastViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Broadcast.objects.all()
serializer_class = BroadcastSerializer
class HostViewSet(viewsets.ModelViewSet):
queryset = Host.objects.all()
serializer_class = HostSerializer
class RaidViewSet(viewsets.ModelViewSet):
queryset = Raid.objects.all()
serializer_class = RaidSerializer
class TicketViewSet(viewsets.ModelViewSet):
queryset = Ticket.objects.all()
serializer_class = TicketSerializer
def retrieve(self, request, pk=None):
queryset = Ticket.objects.all()
ticket = get_object_or_404(queryset, name=pk)
serializer = TicketSerializer(ticket)
return Response(serializer.data)
<commit_msg>Order the tickets correctly in the API.<commit_after># -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404
from rest_framework import viewsets
from rest_framework.response import Response
from apps.broadcasts.models import Broadcast, Host, Raid, Series
from apps.games.models import Game
from apps.subscribers.models import Ticket
from .serializers import (BroadcastSerializer, GameSerializer, HostSerializer,
RaidSerializer, SeriesSerializer, TicketSerializer)
class BroadcastViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Broadcast.objects.all()
serializer_class = BroadcastSerializer
class HostViewSet(viewsets.ModelViewSet):
queryset = Host.objects.all()
serializer_class = HostSerializer
class RaidViewSet(viewsets.ModelViewSet):
queryset = Raid.objects.all()
serializer_class = RaidSerializer
class TicketViewSet(viewsets.ModelViewSet):
queryset = Ticket.objects.order_by('-updated')
serializer_class = TicketSerializer
def retrieve(self, request, pk=None):
queryset = Ticket.objects.all()
ticket = get_object_or_404(queryset, name=pk)
serializer = TicketSerializer(ticket)
return Response(serializer.data)
|
1477d3e94f088399f15bb13fd399d3c33af9c55a
|
backend/breach/tests/base.py
|
backend/breach/tests/base.py
|
from django.test import TestCase
from breach.models import SampleSet, Victim, Target, Round
class RuptureTestCase(TestCase):
def setUp(self):
target = Target.objects.create(
endpoint='https://di.uoa.gr/?breach=%s',
prefix='test',
alphabet='0123456789'
)
self.victim = Victim.objects.create(
target=target,
sourceip='192.168.10.140',
snifferendpoint='http://localhost/'
)
round = Round.objects.create(
victim=self.victim,
amount=1,
knownsecret='testsecret',
knownalphabet='01'
)
self.samplesets = [
SampleSet.objects.create(
round=round,
candidatealphabet='0',
data='bigbigbigbigbigbig'
),
SampleSet.objects.create(
round=round,
candidatealphabet='1',
data='small'
)
]
# Balance checking
self.balance_victim = Victim.objects.create(
target=target,
sourceip='192.168.10.141',
snifferendpoint='http://localhost/'
)
|
from django.test import TestCase
from breach.models import SampleSet, Victim, Target, Round
class RuptureTestCase(TestCase):
def setUp(self):
target = Target.objects.create(
endpoint='https://di.uoa.gr/?breach=%s',
prefix='test',
alphabet='0123456789'
)
self.victim = Victim.objects.create(
target=target,
sourceip='192.168.10.140',
snifferendpoint='http://localhost/'
)
round = Round.objects.create(
victim=self.victim,
amount=1,
knownsecret='testsecret',
knownalphabet='01'
)
self.samplesets = [
SampleSet.objects.create(
round=round,
candidatealphabet='0',
data='bigbigbigbigbigbig'
),
SampleSet.objects.create(
round=round,
candidatealphabet='1',
data='small'
)
]
# Balance checking
self.balance_victim = Victim.objects.create(
target=target,
sourceip='192.168.10.141',
snifferendpoint='http://localhost/'
)
balance_round = Round.objects.create(
victim=self.balance_victim,
amount=1,
knownsecret='testsecret',
knownalphabet='0123',
roundcardinality=3
)
|
Add balance checking test round
|
Add balance checking test round
|
Python
|
mit
|
dimriou/rupture,esarafianou/rupture,esarafianou/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dimkarakostas/rupture,esarafianou/rupture,dionyziz/rupture,dionyziz/rupture,dimriou/rupture,dimkarakostas/rupture,dionyziz/rupture,dionyziz/rupture,dionyziz/rupture,dimkarakostas/rupture,esarafianou/rupture,dimriou/rupture,dimriou/rupture,dimriou/rupture
|
from django.test import TestCase
from breach.models import SampleSet, Victim, Target, Round
class RuptureTestCase(TestCase):
def setUp(self):
target = Target.objects.create(
endpoint='https://di.uoa.gr/?breach=%s',
prefix='test',
alphabet='0123456789'
)
self.victim = Victim.objects.create(
target=target,
sourceip='192.168.10.140',
snifferendpoint='http://localhost/'
)
round = Round.objects.create(
victim=self.victim,
amount=1,
knownsecret='testsecret',
knownalphabet='01'
)
self.samplesets = [
SampleSet.objects.create(
round=round,
candidatealphabet='0',
data='bigbigbigbigbigbig'
),
SampleSet.objects.create(
round=round,
candidatealphabet='1',
data='small'
)
]
# Balance checking
self.balance_victim = Victim.objects.create(
target=target,
sourceip='192.168.10.141',
snifferendpoint='http://localhost/'
)
Add balance checking test round
|
from django.test import TestCase
from breach.models import SampleSet, Victim, Target, Round
class RuptureTestCase(TestCase):
def setUp(self):
target = Target.objects.create(
endpoint='https://di.uoa.gr/?breach=%s',
prefix='test',
alphabet='0123456789'
)
self.victim = Victim.objects.create(
target=target,
sourceip='192.168.10.140',
snifferendpoint='http://localhost/'
)
round = Round.objects.create(
victim=self.victim,
amount=1,
knownsecret='testsecret',
knownalphabet='01'
)
self.samplesets = [
SampleSet.objects.create(
round=round,
candidatealphabet='0',
data='bigbigbigbigbigbig'
),
SampleSet.objects.create(
round=round,
candidatealphabet='1',
data='small'
)
]
# Balance checking
self.balance_victim = Victim.objects.create(
target=target,
sourceip='192.168.10.141',
snifferendpoint='http://localhost/'
)
balance_round = Round.objects.create(
victim=self.balance_victim,
amount=1,
knownsecret='testsecret',
knownalphabet='0123',
roundcardinality=3
)
|
<commit_before>from django.test import TestCase
from breach.models import SampleSet, Victim, Target, Round
class RuptureTestCase(TestCase):
def setUp(self):
target = Target.objects.create(
endpoint='https://di.uoa.gr/?breach=%s',
prefix='test',
alphabet='0123456789'
)
self.victim = Victim.objects.create(
target=target,
sourceip='192.168.10.140',
snifferendpoint='http://localhost/'
)
round = Round.objects.create(
victim=self.victim,
amount=1,
knownsecret='testsecret',
knownalphabet='01'
)
self.samplesets = [
SampleSet.objects.create(
round=round,
candidatealphabet='0',
data='bigbigbigbigbigbig'
),
SampleSet.objects.create(
round=round,
candidatealphabet='1',
data='small'
)
]
# Balance checking
self.balance_victim = Victim.objects.create(
target=target,
sourceip='192.168.10.141',
snifferendpoint='http://localhost/'
)
<commit_msg>Add balance checking test round<commit_after>
|
from django.test import TestCase
from breach.models import SampleSet, Victim, Target, Round
class RuptureTestCase(TestCase):
def setUp(self):
target = Target.objects.create(
endpoint='https://di.uoa.gr/?breach=%s',
prefix='test',
alphabet='0123456789'
)
self.victim = Victim.objects.create(
target=target,
sourceip='192.168.10.140',
snifferendpoint='http://localhost/'
)
round = Round.objects.create(
victim=self.victim,
amount=1,
knownsecret='testsecret',
knownalphabet='01'
)
self.samplesets = [
SampleSet.objects.create(
round=round,
candidatealphabet='0',
data='bigbigbigbigbigbig'
),
SampleSet.objects.create(
round=round,
candidatealphabet='1',
data='small'
)
]
# Balance checking
self.balance_victim = Victim.objects.create(
target=target,
sourceip='192.168.10.141',
snifferendpoint='http://localhost/'
)
balance_round = Round.objects.create(
victim=self.balance_victim,
amount=1,
knownsecret='testsecret',
knownalphabet='0123',
roundcardinality=3
)
|
from django.test import TestCase
from breach.models import SampleSet, Victim, Target, Round
class RuptureTestCase(TestCase):
def setUp(self):
target = Target.objects.create(
endpoint='https://di.uoa.gr/?breach=%s',
prefix='test',
alphabet='0123456789'
)
self.victim = Victim.objects.create(
target=target,
sourceip='192.168.10.140',
snifferendpoint='http://localhost/'
)
round = Round.objects.create(
victim=self.victim,
amount=1,
knownsecret='testsecret',
knownalphabet='01'
)
self.samplesets = [
SampleSet.objects.create(
round=round,
candidatealphabet='0',
data='bigbigbigbigbigbig'
),
SampleSet.objects.create(
round=round,
candidatealphabet='1',
data='small'
)
]
# Balance checking
self.balance_victim = Victim.objects.create(
target=target,
sourceip='192.168.10.141',
snifferendpoint='http://localhost/'
)
Add balance checking test roundfrom django.test import TestCase
from breach.models import SampleSet, Victim, Target, Round
class RuptureTestCase(TestCase):
def setUp(self):
target = Target.objects.create(
endpoint='https://di.uoa.gr/?breach=%s',
prefix='test',
alphabet='0123456789'
)
self.victim = Victim.objects.create(
target=target,
sourceip='192.168.10.140',
snifferendpoint='http://localhost/'
)
round = Round.objects.create(
victim=self.victim,
amount=1,
knownsecret='testsecret',
knownalphabet='01'
)
self.samplesets = [
SampleSet.objects.create(
round=round,
candidatealphabet='0',
data='bigbigbigbigbigbig'
),
SampleSet.objects.create(
round=round,
candidatealphabet='1',
data='small'
)
]
# Balance checking
self.balance_victim = Victim.objects.create(
target=target,
sourceip='192.168.10.141',
snifferendpoint='http://localhost/'
)
balance_round = Round.objects.create(
victim=self.balance_victim,
amount=1,
knownsecret='testsecret',
knownalphabet='0123',
roundcardinality=3
)
|
<commit_before>from django.test import TestCase
from breach.models import SampleSet, Victim, Target, Round
class RuptureTestCase(TestCase):
def setUp(self):
target = Target.objects.create(
endpoint='https://di.uoa.gr/?breach=%s',
prefix='test',
alphabet='0123456789'
)
self.victim = Victim.objects.create(
target=target,
sourceip='192.168.10.140',
snifferendpoint='http://localhost/'
)
round = Round.objects.create(
victim=self.victim,
amount=1,
knownsecret='testsecret',
knownalphabet='01'
)
self.samplesets = [
SampleSet.objects.create(
round=round,
candidatealphabet='0',
data='bigbigbigbigbigbig'
),
SampleSet.objects.create(
round=round,
candidatealphabet='1',
data='small'
)
]
# Balance checking
self.balance_victim = Victim.objects.create(
target=target,
sourceip='192.168.10.141',
snifferendpoint='http://localhost/'
)
<commit_msg>Add balance checking test round<commit_after>from django.test import TestCase
from breach.models import SampleSet, Victim, Target, Round
class RuptureTestCase(TestCase):
def setUp(self):
target = Target.objects.create(
endpoint='https://di.uoa.gr/?breach=%s',
prefix='test',
alphabet='0123456789'
)
self.victim = Victim.objects.create(
target=target,
sourceip='192.168.10.140',
snifferendpoint='http://localhost/'
)
round = Round.objects.create(
victim=self.victim,
amount=1,
knownsecret='testsecret',
knownalphabet='01'
)
self.samplesets = [
SampleSet.objects.create(
round=round,
candidatealphabet='0',
data='bigbigbigbigbigbig'
),
SampleSet.objects.create(
round=round,
candidatealphabet='1',
data='small'
)
]
# Balance checking
self.balance_victim = Victim.objects.create(
target=target,
sourceip='192.168.10.141',
snifferendpoint='http://localhost/'
)
balance_round = Round.objects.create(
victim=self.balance_victim,
amount=1,
knownsecret='testsecret',
knownalphabet='0123',
roundcardinality=3
)
|
0aa3af24533a0aa605d05bd034a0bfdcc55c2993
|
backend/conferences/types.py
|
backend/conferences/types.py
|
import graphene
from .models import Conference
from graphene_django import DjangoObjectType
from tickets.types import TicketType
class ConferenceType(DjangoObjectType):
tickets = graphene.List(graphene.NonNull(TicketType))
def resolve_tickets(self, info):
return self.tickets.all()
class Meta:
model = Conference
only_fields = ('id', 'start', 'end', 'name', 'slug')
|
import graphene
from .models import Conference
from graphene_django import DjangoObjectType
from tickets.types import TicketType
class ConferenceType(DjangoObjectType):
tickets = graphene.List(graphene.NonNull(TicketType))
def resolve_tickets(self, info):
return self.tickets.all()
class Meta:
model = Conference
only_fields = (
'id',
'name',
'slug',
'start',
'end',
'cfp_start',
'cfp_end',
'voting_start',
'voting_end',
'refund_start',
'refund_end'
)
|
Add dates to Conference GraphQL type
|
Add dates to Conference GraphQL type
|
Python
|
mit
|
patrick91/pycon,patrick91/pycon
|
import graphene
from .models import Conference
from graphene_django import DjangoObjectType
from tickets.types import TicketType
class ConferenceType(DjangoObjectType):
tickets = graphene.List(graphene.NonNull(TicketType))
def resolve_tickets(self, info):
return self.tickets.all()
class Meta:
model = Conference
only_fields = ('id', 'start', 'end', 'name', 'slug')
Add dates to Conference GraphQL type
|
import graphene
from .models import Conference
from graphene_django import DjangoObjectType
from tickets.types import TicketType
class ConferenceType(DjangoObjectType):
tickets = graphene.List(graphene.NonNull(TicketType))
def resolve_tickets(self, info):
return self.tickets.all()
class Meta:
model = Conference
only_fields = (
'id',
'name',
'slug',
'start',
'end',
'cfp_start',
'cfp_end',
'voting_start',
'voting_end',
'refund_start',
'refund_end'
)
|
<commit_before>import graphene
from .models import Conference
from graphene_django import DjangoObjectType
from tickets.types import TicketType
class ConferenceType(DjangoObjectType):
tickets = graphene.List(graphene.NonNull(TicketType))
def resolve_tickets(self, info):
return self.tickets.all()
class Meta:
model = Conference
only_fields = ('id', 'start', 'end', 'name', 'slug')
<commit_msg>Add dates to Conference GraphQL type<commit_after>
|
import graphene
from .models import Conference
from graphene_django import DjangoObjectType
from tickets.types import TicketType
class ConferenceType(DjangoObjectType):
tickets = graphene.List(graphene.NonNull(TicketType))
def resolve_tickets(self, info):
return self.tickets.all()
class Meta:
model = Conference
only_fields = (
'id',
'name',
'slug',
'start',
'end',
'cfp_start',
'cfp_end',
'voting_start',
'voting_end',
'refund_start',
'refund_end'
)
|
import graphene
from .models import Conference
from graphene_django import DjangoObjectType
from tickets.types import TicketType
class ConferenceType(DjangoObjectType):
tickets = graphene.List(graphene.NonNull(TicketType))
def resolve_tickets(self, info):
return self.tickets.all()
class Meta:
model = Conference
only_fields = ('id', 'start', 'end', 'name', 'slug')
Add dates to Conference GraphQL typeimport graphene
from .models import Conference
from graphene_django import DjangoObjectType
from tickets.types import TicketType
class ConferenceType(DjangoObjectType):
tickets = graphene.List(graphene.NonNull(TicketType))
def resolve_tickets(self, info):
return self.tickets.all()
class Meta:
model = Conference
only_fields = (
'id',
'name',
'slug',
'start',
'end',
'cfp_start',
'cfp_end',
'voting_start',
'voting_end',
'refund_start',
'refund_end'
)
|
<commit_before>import graphene
from .models import Conference
from graphene_django import DjangoObjectType
from tickets.types import TicketType
class ConferenceType(DjangoObjectType):
tickets = graphene.List(graphene.NonNull(TicketType))
def resolve_tickets(self, info):
return self.tickets.all()
class Meta:
model = Conference
only_fields = ('id', 'start', 'end', 'name', 'slug')
<commit_msg>Add dates to Conference GraphQL type<commit_after>import graphene
from .models import Conference
from graphene_django import DjangoObjectType
from tickets.types import TicketType
class ConferenceType(DjangoObjectType):
tickets = graphene.List(graphene.NonNull(TicketType))
def resolve_tickets(self, info):
return self.tickets.all()
class Meta:
model = Conference
only_fields = (
'id',
'name',
'slug',
'start',
'end',
'cfp_start',
'cfp_end',
'voting_start',
'voting_end',
'refund_start',
'refund_end'
)
|
457f2daeb087ab06d7cb738cb69268bad29d11f4
|
examples/mhs_atmosphere/mhs_atmosphere_plot.py
|
examples/mhs_atmosphere/mhs_atmosphere_plot.py
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 9 12:52:31 2015
@author: stuart
"""
import os
import glob
import yt
model = 'spruit'
datadir = os.path.expanduser('~/mhs_atmosphere/'+model+'/')
files = glob.glob(datadir+'/*')
files.sort()
print(files)
ds = yt.load(files[0])
slc = yt.SlicePlot(ds, normal='y', fields='density_bg')
slc.save('~/yt.png')
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 9 12:52:31 2015
@author: stuart
"""
import os
import glob
import yt
model = 'spruit'
datadir = os.path.expanduser('~/mhs_atmosphere/'+model+'/')
files = glob.glob(datadir+'/*')
files.sort()
print(files)
ds = yt.load(files[0])
# uncomment for axis swapping for normal='y'
ds.coordinates.x_axis = {0: 2, 1: 0, 2: 1, 'x': 2, 'y': 0, 'z': 1}
ds.coordinates.y_axis = {0: 1, 1: 2, 2: 0, 'x': 1, 'y': 2, 'z': 0}
slc = yt.SlicePlot(ds, normal='y', fields='density_bg')
slc.save('~/yt.png')
|
Add in axes swapping for normal='y'
|
Add in axes swapping for normal='y'
|
Python
|
bsd-2-clause
|
SWAT-Sheffield/pysac,Cadair/pysac
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 9 12:52:31 2015
@author: stuart
"""
import os
import glob
import yt
model = 'spruit'
datadir = os.path.expanduser('~/mhs_atmosphere/'+model+'/')
files = glob.glob(datadir+'/*')
files.sort()
print(files)
ds = yt.load(files[0])
slc = yt.SlicePlot(ds, normal='y', fields='density_bg')
slc.save('~/yt.png')Add in axes swapping for normal='y'
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 9 12:52:31 2015
@author: stuart
"""
import os
import glob
import yt
model = 'spruit'
datadir = os.path.expanduser('~/mhs_atmosphere/'+model+'/')
files = glob.glob(datadir+'/*')
files.sort()
print(files)
ds = yt.load(files[0])
# uncomment for axis swapping for normal='y'
ds.coordinates.x_axis = {0: 2, 1: 0, 2: 1, 'x': 2, 'y': 0, 'z': 1}
ds.coordinates.y_axis = {0: 1, 1: 2, 2: 0, 'x': 1, 'y': 2, 'z': 0}
slc = yt.SlicePlot(ds, normal='y', fields='density_bg')
slc.save('~/yt.png')
|
<commit_before># -*- coding: utf-8 -*-
"""
Created on Fri Jan 9 12:52:31 2015
@author: stuart
"""
import os
import glob
import yt
model = 'spruit'
datadir = os.path.expanduser('~/mhs_atmosphere/'+model+'/')
files = glob.glob(datadir+'/*')
files.sort()
print(files)
ds = yt.load(files[0])
slc = yt.SlicePlot(ds, normal='y', fields='density_bg')
slc.save('~/yt.png')<commit_msg>Add in axes swapping for normal='y'<commit_after>
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 9 12:52:31 2015
@author: stuart
"""
import os
import glob
import yt
model = 'spruit'
datadir = os.path.expanduser('~/mhs_atmosphere/'+model+'/')
files = glob.glob(datadir+'/*')
files.sort()
print(files)
ds = yt.load(files[0])
# uncomment for axis swapping for normal='y'
ds.coordinates.x_axis = {0: 2, 1: 0, 2: 1, 'x': 2, 'y': 0, 'z': 1}
ds.coordinates.y_axis = {0: 1, 1: 2, 2: 0, 'x': 1, 'y': 2, 'z': 0}
slc = yt.SlicePlot(ds, normal='y', fields='density_bg')
slc.save('~/yt.png')
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 9 12:52:31 2015
@author: stuart
"""
import os
import glob
import yt
model = 'spruit'
datadir = os.path.expanduser('~/mhs_atmosphere/'+model+'/')
files = glob.glob(datadir+'/*')
files.sort()
print(files)
ds = yt.load(files[0])
slc = yt.SlicePlot(ds, normal='y', fields='density_bg')
slc.save('~/yt.png')Add in axes swapping for normal='y'# -*- coding: utf-8 -*-
"""
Created on Fri Jan 9 12:52:31 2015
@author: stuart
"""
import os
import glob
import yt
model = 'spruit'
datadir = os.path.expanduser('~/mhs_atmosphere/'+model+'/')
files = glob.glob(datadir+'/*')
files.sort()
print(files)
ds = yt.load(files[0])
# uncomment for axis swapping for normal='y'
ds.coordinates.x_axis = {0: 2, 1: 0, 2: 1, 'x': 2, 'y': 0, 'z': 1}
ds.coordinates.y_axis = {0: 1, 1: 2, 2: 0, 'x': 1, 'y': 2, 'z': 0}
slc = yt.SlicePlot(ds, normal='y', fields='density_bg')
slc.save('~/yt.png')
|
<commit_before># -*- coding: utf-8 -*-
"""
Created on Fri Jan 9 12:52:31 2015
@author: stuart
"""
import os
import glob
import yt
model = 'spruit'
datadir = os.path.expanduser('~/mhs_atmosphere/'+model+'/')
files = glob.glob(datadir+'/*')
files.sort()
print(files)
ds = yt.load(files[0])
slc = yt.SlicePlot(ds, normal='y', fields='density_bg')
slc.save('~/yt.png')<commit_msg>Add in axes swapping for normal='y'<commit_after># -*- coding: utf-8 -*-
"""
Created on Fri Jan 9 12:52:31 2015
@author: stuart
"""
import os
import glob
import yt
model = 'spruit'
datadir = os.path.expanduser('~/mhs_atmosphere/'+model+'/')
files = glob.glob(datadir+'/*')
files.sort()
print(files)
ds = yt.load(files[0])
# uncomment for axis swapping for normal='y'
ds.coordinates.x_axis = {0: 2, 1: 0, 2: 1, 'x': 2, 'y': 0, 'z': 1}
ds.coordinates.y_axis = {0: 1, 1: 2, 2: 0, 'x': 1, 'y': 2, 'z': 0}
slc = yt.SlicePlot(ds, normal='y', fields='density_bg')
slc.save('~/yt.png')
|
a3c2f22819271adb7f08d18a54af863e5ca75c51
|
test/test_api.py
|
test/test_api.py
|
# -*- coding: utf-8 -*-
import pytest
import warthog.api
import warthog.exceptions
@pytest.fixture
def exports():
return set([item for item in dir(warthog.api) if not item.startswith('_')])
def test_public_exports(exports):
declared = set(warthog.api.__all__)
assert exports == declared, 'Exports and __all__ members should match'
def test_all_exceptions_imported(exports):
errors = set([item for item in dir(warthog.exceptions) if item.endswith('Error')])
intersection = errors.intersection(exports)
assert intersection == errors, "All available errors should be in warthog.api"
|
# -*- coding: utf-8 -*-
import pytest
import warthog.api
import warthog.exceptions
@pytest.fixture
def exports():
return set([item for item in dir(warthog.api) if not item.startswith('_')])
def test_public_exports(exports):
declared = set(warthog.api.__all__)
assert exports == declared, 'Exports and __all__ members should match'
def test_all_exceptions_imported(exports):
errors = set([item for item in dir(warthog.exceptions) if item.endswith('Error') or item.endswith('Warning')])
intersection = errors.intersection(exports)
assert intersection == errors, "All available errors should be in warthog.api"
|
Add potential to include warnings in warthog.exceptions
|
Add potential to include warnings in warthog.exceptions
|
Python
|
mit
|
smarter-travel-media/warthog
|
# -*- coding: utf-8 -*-
import pytest
import warthog.api
import warthog.exceptions
@pytest.fixture
def exports():
return set([item for item in dir(warthog.api) if not item.startswith('_')])
def test_public_exports(exports):
declared = set(warthog.api.__all__)
assert exports == declared, 'Exports and __all__ members should match'
def test_all_exceptions_imported(exports):
errors = set([item for item in dir(warthog.exceptions) if item.endswith('Error')])
intersection = errors.intersection(exports)
assert intersection == errors, "All available errors should be in warthog.api"
Add potential to include warnings in warthog.exceptions
|
# -*- coding: utf-8 -*-
import pytest
import warthog.api
import warthog.exceptions
@pytest.fixture
def exports():
return set([item for item in dir(warthog.api) if not item.startswith('_')])
def test_public_exports(exports):
declared = set(warthog.api.__all__)
assert exports == declared, 'Exports and __all__ members should match'
def test_all_exceptions_imported(exports):
errors = set([item for item in dir(warthog.exceptions) if item.endswith('Error') or item.endswith('Warning')])
intersection = errors.intersection(exports)
assert intersection == errors, "All available errors should be in warthog.api"
|
<commit_before># -*- coding: utf-8 -*-
import pytest
import warthog.api
import warthog.exceptions
@pytest.fixture
def exports():
return set([item for item in dir(warthog.api) if not item.startswith('_')])
def test_public_exports(exports):
declared = set(warthog.api.__all__)
assert exports == declared, 'Exports and __all__ members should match'
def test_all_exceptions_imported(exports):
errors = set([item for item in dir(warthog.exceptions) if item.endswith('Error')])
intersection = errors.intersection(exports)
assert intersection == errors, "All available errors should be in warthog.api"
<commit_msg>Add potential to include warnings in warthog.exceptions<commit_after>
|
# -*- coding: utf-8 -*-
import pytest
import warthog.api
import warthog.exceptions
@pytest.fixture
def exports():
return set([item for item in dir(warthog.api) if not item.startswith('_')])
def test_public_exports(exports):
declared = set(warthog.api.__all__)
assert exports == declared, 'Exports and __all__ members should match'
def test_all_exceptions_imported(exports):
errors = set([item for item in dir(warthog.exceptions) if item.endswith('Error') or item.endswith('Warning')])
intersection = errors.intersection(exports)
assert intersection == errors, "All available errors should be in warthog.api"
|
# -*- coding: utf-8 -*-
import pytest
import warthog.api
import warthog.exceptions
@pytest.fixture
def exports():
return set([item for item in dir(warthog.api) if not item.startswith('_')])
def test_public_exports(exports):
declared = set(warthog.api.__all__)
assert exports == declared, 'Exports and __all__ members should match'
def test_all_exceptions_imported(exports):
errors = set([item for item in dir(warthog.exceptions) if item.endswith('Error')])
intersection = errors.intersection(exports)
assert intersection == errors, "All available errors should be in warthog.api"
Add potential to include warnings in warthog.exceptions# -*- coding: utf-8 -*-
import pytest
import warthog.api
import warthog.exceptions
@pytest.fixture
def exports():
return set([item for item in dir(warthog.api) if not item.startswith('_')])
def test_public_exports(exports):
declared = set(warthog.api.__all__)
assert exports == declared, 'Exports and __all__ members should match'
def test_all_exceptions_imported(exports):
errors = set([item for item in dir(warthog.exceptions) if item.endswith('Error') or item.endswith('Warning')])
intersection = errors.intersection(exports)
assert intersection == errors, "All available errors should be in warthog.api"
|
<commit_before># -*- coding: utf-8 -*-
import pytest
import warthog.api
import warthog.exceptions
@pytest.fixture
def exports():
return set([item for item in dir(warthog.api) if not item.startswith('_')])
def test_public_exports(exports):
declared = set(warthog.api.__all__)
assert exports == declared, 'Exports and __all__ members should match'
def test_all_exceptions_imported(exports):
errors = set([item for item in dir(warthog.exceptions) if item.endswith('Error')])
intersection = errors.intersection(exports)
assert intersection == errors, "All available errors should be in warthog.api"
<commit_msg>Add potential to include warnings in warthog.exceptions<commit_after># -*- coding: utf-8 -*-
import pytest
import warthog.api
import warthog.exceptions
@pytest.fixture
def exports():
return set([item for item in dir(warthog.api) if not item.startswith('_')])
def test_public_exports(exports):
declared = set(warthog.api.__all__)
assert exports == declared, 'Exports and __all__ members should match'
def test_all_exceptions_imported(exports):
errors = set([item for item in dir(warthog.exceptions) if item.endswith('Error') or item.endswith('Warning')])
intersection = errors.intersection(exports)
assert intersection == errors, "All available errors should be in warthog.api"
|
3c1a9a2db94a094446e9037a65acc7da9bb5586a
|
myname.py
|
myname.py
|
"""Little module to find the path of a Cosmo box simulation"""
import os.path as path
base=path.expanduser("~/data/Cosmo/")
def get_name(sim, ff=True):
"""Get the directory for a simulation"""
halo = "Cosmo"+str(sim)+"_V6"
if ff:
halo=path.join(halo,"L25n512/output")
else:
halo=path.join(halo,"L25n256")
return path.join(base, halo)
|
"""Little module to find the path of a Cosmo box simulation"""
import os.path as path
base=path.expanduser("~/data/Cosmo/")
def get_name(sim, ff=True, box=25):
"""Get the directory for a simulation"""
halo = "Cosmo"+str(sim)+"_V6"
if ff:
halo=path.join(halo,"L"+str(box)+"n512/output")
else:
halo=path.join(halo,"L"+str(box)+"256")
return path.join(base, halo)
|
Allow loading of different box sizes
|
Allow loading of different box sizes
|
Python
|
mit
|
sbird/vw_spectra
|
"""Little module to find the path of a Cosmo box simulation"""
import os.path as path
base=path.expanduser("~/data/Cosmo/")
def get_name(sim, ff=True):
"""Get the directory for a simulation"""
halo = "Cosmo"+str(sim)+"_V6"
if ff:
halo=path.join(halo,"L25n512/output")
else:
halo=path.join(halo,"L25n256")
return path.join(base, halo)
Allow loading of different box sizes
|
"""Little module to find the path of a Cosmo box simulation"""
import os.path as path
base=path.expanduser("~/data/Cosmo/")
def get_name(sim, ff=True, box=25):
"""Get the directory for a simulation"""
halo = "Cosmo"+str(sim)+"_V6"
if ff:
halo=path.join(halo,"L"+str(box)+"n512/output")
else:
halo=path.join(halo,"L"+str(box)+"256")
return path.join(base, halo)
|
<commit_before>"""Little module to find the path of a Cosmo box simulation"""
import os.path as path
base=path.expanduser("~/data/Cosmo/")
def get_name(sim, ff=True):
"""Get the directory for a simulation"""
halo = "Cosmo"+str(sim)+"_V6"
if ff:
halo=path.join(halo,"L25n512/output")
else:
halo=path.join(halo,"L25n256")
return path.join(base, halo)
<commit_msg>Allow loading of different box sizes<commit_after>
|
"""Little module to find the path of a Cosmo box simulation"""
import os.path as path
base=path.expanduser("~/data/Cosmo/")
def get_name(sim, ff=True, box=25):
"""Get the directory for a simulation"""
halo = "Cosmo"+str(sim)+"_V6"
if ff:
halo=path.join(halo,"L"+str(box)+"n512/output")
else:
halo=path.join(halo,"L"+str(box)+"256")
return path.join(base, halo)
|
"""Little module to find the path of a Cosmo box simulation"""
import os.path as path
base=path.expanduser("~/data/Cosmo/")
def get_name(sim, ff=True):
"""Get the directory for a simulation"""
halo = "Cosmo"+str(sim)+"_V6"
if ff:
halo=path.join(halo,"L25n512/output")
else:
halo=path.join(halo,"L25n256")
return path.join(base, halo)
Allow loading of different box sizes"""Little module to find the path of a Cosmo box simulation"""
import os.path as path
base=path.expanduser("~/data/Cosmo/")
def get_name(sim, ff=True, box=25):
"""Get the directory for a simulation"""
halo = "Cosmo"+str(sim)+"_V6"
if ff:
halo=path.join(halo,"L"+str(box)+"n512/output")
else:
halo=path.join(halo,"L"+str(box)+"256")
return path.join(base, halo)
|
<commit_before>"""Little module to find the path of a Cosmo box simulation"""
import os.path as path
base=path.expanduser("~/data/Cosmo/")
def get_name(sim, ff=True):
"""Get the directory for a simulation"""
halo = "Cosmo"+str(sim)+"_V6"
if ff:
halo=path.join(halo,"L25n512/output")
else:
halo=path.join(halo,"L25n256")
return path.join(base, halo)
<commit_msg>Allow loading of different box sizes<commit_after>"""Little module to find the path of a Cosmo box simulation"""
import os.path as path
base=path.expanduser("~/data/Cosmo/")
def get_name(sim, ff=True, box=25):
"""Get the directory for a simulation"""
halo = "Cosmo"+str(sim)+"_V6"
if ff:
halo=path.join(halo,"L"+str(box)+"n512/output")
else:
halo=path.join(halo,"L"+str(box)+"256")
return path.join(base, halo)
|
9fb1e795cd2489e2889041018ff5a357afba0221
|
test_collectr.py
|
test_collectr.py
|
# -*- coding: utf-8 -*-
"""
test_collectr
-------------
Some functions to test the collectr library.
:copyright: (c) 2013 Cory Benfield
:license: MIT License, for details see LICENSE.
"""
import unittest
import collectr
class CollectrTest(unittest.TestCase):
"""
Tests for the collectr library.
"""
def setUp(self):
self.dir = collectr.StaticDir('test/fixtures/dirB')
def tearDown(self):
self.dir = None
def test_enumerate_files(self):
result = ['test/fixtures/dirA/css/css1.css',
'test/fixtures/dirA/css/css2.css',
'test/fixtures/dirA/js/script1.js',
'test/fixtures/dirA/js/script2.js']
files = self.dir.enumerate_files('test/fixtures/dirA')
self.assertEqual(files, result)
def test_enumerate_files_with_filter(self):
result = ['test/fixtures/dirB/img/img1.jpg',
'test/fixtures/dirB/img/img3.tiff']
self.dir.ignore = ['.*\.png']
files = self.dir.enumerate_files('test/fixtures/dirB')
self.assertEqual(files, result)
if __name__ == '__main__':
unittest.main()
|
# -*- coding: utf-8 -*-
"""
test_collectr
-------------
Some functions to test the collectr library.
:copyright: (c) 2013 Cory Benfield
:license: MIT License, for details see LICENSE.
"""
import unittest
import collectr
class CollectrTest(unittest.TestCase):
"""
Tests for the collectr library.
"""
def setUp(self):
self.dir = collectr.StaticDir('test/fixtures/dirB')
def tearDown(self):
self.dir = None
try: # Delete the files if they exist, otherwise mask failure.
self.old_call('rm -rf test/fixtures/dirB/css')
self.old_call('rm -rf test/fixtures/dirB/js')
except OSError:
pass
def test_enumerate_files(self):
result = ['test/fixtures/dirA/css/css1.css',
'test/fixtures/dirA/css/css2.css',
'test/fixtures/dirA/js/script1.js',
'test/fixtures/dirA/js/script2.js']
files = self.dir.enumerate_files('test/fixtures/dirA')
self.assertEqual(files, result)
def test_enumerate_files_with_filter(self):
result = ['test/fixtures/dirB/img/img1.jpg',
'test/fixtures/dirB/img/img3.tiff']
self.dir.ignore = ['.*\.png']
files = self.dir.enumerate_files('test/fixtures/dirB')
self.assertEqual(files, result)
if __name__ == '__main__':
unittest.main()
|
Delete any files that get moved.
|
Delete any files that get moved.
|
Python
|
mit
|
Lukasa/collectr,Lukasa/collectr
|
# -*- coding: utf-8 -*-
"""
test_collectr
-------------
Some functions to test the collectr library.
:copyright: (c) 2013 Cory Benfield
:license: MIT License, for details see LICENSE.
"""
import unittest
import collectr
class CollectrTest(unittest.TestCase):
"""
Tests for the collectr library.
"""
def setUp(self):
self.dir = collectr.StaticDir('test/fixtures/dirB')
def tearDown(self):
self.dir = None
def test_enumerate_files(self):
result = ['test/fixtures/dirA/css/css1.css',
'test/fixtures/dirA/css/css2.css',
'test/fixtures/dirA/js/script1.js',
'test/fixtures/dirA/js/script2.js']
files = self.dir.enumerate_files('test/fixtures/dirA')
self.assertEqual(files, result)
def test_enumerate_files_with_filter(self):
result = ['test/fixtures/dirB/img/img1.jpg',
'test/fixtures/dirB/img/img3.tiff']
self.dir.ignore = ['.*\.png']
files = self.dir.enumerate_files('test/fixtures/dirB')
self.assertEqual(files, result)
if __name__ == '__main__':
unittest.main()
Delete any files that get moved.
|
# -*- coding: utf-8 -*-
"""
test_collectr
-------------
Some functions to test the collectr library.
:copyright: (c) 2013 Cory Benfield
:license: MIT License, for details see LICENSE.
"""
import unittest
import collectr
class CollectrTest(unittest.TestCase):
"""
Tests for the collectr library.
"""
def setUp(self):
self.dir = collectr.StaticDir('test/fixtures/dirB')
def tearDown(self):
self.dir = None
try: # Delete the files if they exist, otherwise mask failure.
self.old_call('rm -rf test/fixtures/dirB/css')
self.old_call('rm -rf test/fixtures/dirB/js')
except OSError:
pass
def test_enumerate_files(self):
result = ['test/fixtures/dirA/css/css1.css',
'test/fixtures/dirA/css/css2.css',
'test/fixtures/dirA/js/script1.js',
'test/fixtures/dirA/js/script2.js']
files = self.dir.enumerate_files('test/fixtures/dirA')
self.assertEqual(files, result)
def test_enumerate_files_with_filter(self):
result = ['test/fixtures/dirB/img/img1.jpg',
'test/fixtures/dirB/img/img3.tiff']
self.dir.ignore = ['.*\.png']
files = self.dir.enumerate_files('test/fixtures/dirB')
self.assertEqual(files, result)
if __name__ == '__main__':
unittest.main()
|
<commit_before># -*- coding: utf-8 -*-
"""
test_collectr
-------------
Some functions to test the collectr library.
:copyright: (c) 2013 Cory Benfield
:license: MIT License, for details see LICENSE.
"""
import unittest
import collectr
class CollectrTest(unittest.TestCase):
"""
Tests for the collectr library.
"""
def setUp(self):
self.dir = collectr.StaticDir('test/fixtures/dirB')
def tearDown(self):
self.dir = None
def test_enumerate_files(self):
result = ['test/fixtures/dirA/css/css1.css',
'test/fixtures/dirA/css/css2.css',
'test/fixtures/dirA/js/script1.js',
'test/fixtures/dirA/js/script2.js']
files = self.dir.enumerate_files('test/fixtures/dirA')
self.assertEqual(files, result)
def test_enumerate_files_with_filter(self):
result = ['test/fixtures/dirB/img/img1.jpg',
'test/fixtures/dirB/img/img3.tiff']
self.dir.ignore = ['.*\.png']
files = self.dir.enumerate_files('test/fixtures/dirB')
self.assertEqual(files, result)
if __name__ == '__main__':
unittest.main()
<commit_msg>Delete any files that get moved.<commit_after>
|
# -*- coding: utf-8 -*-
"""
test_collectr
-------------
Some functions to test the collectr library.
:copyright: (c) 2013 Cory Benfield
:license: MIT License, for details see LICENSE.
"""
import unittest
import collectr
class CollectrTest(unittest.TestCase):
"""
Tests for the collectr library.
"""
def setUp(self):
self.dir = collectr.StaticDir('test/fixtures/dirB')
def tearDown(self):
self.dir = None
try: # Delete the files if they exist, otherwise mask failure.
self.old_call('rm -rf test/fixtures/dirB/css')
self.old_call('rm -rf test/fixtures/dirB/js')
except OSError:
pass
def test_enumerate_files(self):
result = ['test/fixtures/dirA/css/css1.css',
'test/fixtures/dirA/css/css2.css',
'test/fixtures/dirA/js/script1.js',
'test/fixtures/dirA/js/script2.js']
files = self.dir.enumerate_files('test/fixtures/dirA')
self.assertEqual(files, result)
def test_enumerate_files_with_filter(self):
result = ['test/fixtures/dirB/img/img1.jpg',
'test/fixtures/dirB/img/img3.tiff']
self.dir.ignore = ['.*\.png']
files = self.dir.enumerate_files('test/fixtures/dirB')
self.assertEqual(files, result)
if __name__ == '__main__':
unittest.main()
|
# -*- coding: utf-8 -*-
"""
test_collectr
-------------
Some functions to test the collectr library.
:copyright: (c) 2013 Cory Benfield
:license: MIT License, for details see LICENSE.
"""
import unittest
import collectr
class CollectrTest(unittest.TestCase):
"""
Tests for the collectr library.
"""
def setUp(self):
self.dir = collectr.StaticDir('test/fixtures/dirB')
def tearDown(self):
self.dir = None
def test_enumerate_files(self):
result = ['test/fixtures/dirA/css/css1.css',
'test/fixtures/dirA/css/css2.css',
'test/fixtures/dirA/js/script1.js',
'test/fixtures/dirA/js/script2.js']
files = self.dir.enumerate_files('test/fixtures/dirA')
self.assertEqual(files, result)
def test_enumerate_files_with_filter(self):
result = ['test/fixtures/dirB/img/img1.jpg',
'test/fixtures/dirB/img/img3.tiff']
self.dir.ignore = ['.*\.png']
files = self.dir.enumerate_files('test/fixtures/dirB')
self.assertEqual(files, result)
if __name__ == '__main__':
unittest.main()
Delete any files that get moved.# -*- coding: utf-8 -*-
"""
test_collectr
-------------
Some functions to test the collectr library.
:copyright: (c) 2013 Cory Benfield
:license: MIT License, for details see LICENSE.
"""
import unittest
import collectr
class CollectrTest(unittest.TestCase):
"""
Tests for the collectr library.
"""
def setUp(self):
self.dir = collectr.StaticDir('test/fixtures/dirB')
def tearDown(self):
self.dir = None
try: # Delete the files if they exist, otherwise mask failure.
self.old_call('rm -rf test/fixtures/dirB/css')
self.old_call('rm -rf test/fixtures/dirB/js')
except OSError:
pass
def test_enumerate_files(self):
result = ['test/fixtures/dirA/css/css1.css',
'test/fixtures/dirA/css/css2.css',
'test/fixtures/dirA/js/script1.js',
'test/fixtures/dirA/js/script2.js']
files = self.dir.enumerate_files('test/fixtures/dirA')
self.assertEqual(files, result)
def test_enumerate_files_with_filter(self):
result = ['test/fixtures/dirB/img/img1.jpg',
'test/fixtures/dirB/img/img3.tiff']
self.dir.ignore = ['.*\.png']
files = self.dir.enumerate_files('test/fixtures/dirB')
self.assertEqual(files, result)
if __name__ == '__main__':
unittest.main()
|
<commit_before># -*- coding: utf-8 -*-
"""
test_collectr
-------------
Some functions to test the collectr library.
:copyright: (c) 2013 Cory Benfield
:license: MIT License, for details see LICENSE.
"""
import unittest
import collectr
class CollectrTest(unittest.TestCase):
"""
Tests for the collectr library.
"""
def setUp(self):
self.dir = collectr.StaticDir('test/fixtures/dirB')
def tearDown(self):
self.dir = None
def test_enumerate_files(self):
result = ['test/fixtures/dirA/css/css1.css',
'test/fixtures/dirA/css/css2.css',
'test/fixtures/dirA/js/script1.js',
'test/fixtures/dirA/js/script2.js']
files = self.dir.enumerate_files('test/fixtures/dirA')
self.assertEqual(files, result)
def test_enumerate_files_with_filter(self):
result = ['test/fixtures/dirB/img/img1.jpg',
'test/fixtures/dirB/img/img3.tiff']
self.dir.ignore = ['.*\.png']
files = self.dir.enumerate_files('test/fixtures/dirB')
self.assertEqual(files, result)
if __name__ == '__main__':
unittest.main()
<commit_msg>Delete any files that get moved.<commit_after># -*- coding: utf-8 -*-
"""
test_collectr
-------------
Some functions to test the collectr library.
:copyright: (c) 2013 Cory Benfield
:license: MIT License, for details see LICENSE.
"""
import unittest
import collectr
class CollectrTest(unittest.TestCase):
"""
Tests for the collectr library.
"""
def setUp(self):
self.dir = collectr.StaticDir('test/fixtures/dirB')
def tearDown(self):
self.dir = None
try: # Delete the files if they exist, otherwise mask failure.
self.old_call('rm -rf test/fixtures/dirB/css')
self.old_call('rm -rf test/fixtures/dirB/js')
except OSError:
pass
def test_enumerate_files(self):
result = ['test/fixtures/dirA/css/css1.css',
'test/fixtures/dirA/css/css2.css',
'test/fixtures/dirA/js/script1.js',
'test/fixtures/dirA/js/script2.js']
files = self.dir.enumerate_files('test/fixtures/dirA')
self.assertEqual(files, result)
def test_enumerate_files_with_filter(self):
result = ['test/fixtures/dirB/img/img1.jpg',
'test/fixtures/dirB/img/img3.tiff']
self.dir.ignore = ['.*\.png']
files = self.dir.enumerate_files('test/fixtures/dirB')
self.assertEqual(files, result)
if __name__ == '__main__':
unittest.main()
|
c3f94790e8d4d7bca68eb86d1172c9f69f1c070c
|
tests/support.py
|
tests/support.py
|
import os
def open_file(filename):
''' Load a file from the fixtures directory. '''
path = 'fixtures/' + filename
if ('tests' in os.listdir('.')):
path = 'tests/' + path
return open(path, mode='rb')
|
import os
def open_file(filename, mode='rb'):
''' Load a file from the fixtures directory. '''
path = 'fixtures/' + filename
if ('tests' in os.listdir('.')):
path = 'tests/' + path
return open(path, mode=mode)
|
Support opening files as text streams on tests
|
Support opening files as text streams on tests
|
Python
|
mit
|
jaraco/ofxparse,rdsteed/ofxparse,udibr/ofxparse,jseutter/ofxparse
|
import os
def open_file(filename):
''' Load a file from the fixtures directory. '''
path = 'fixtures/' + filename
if ('tests' in os.listdir('.')):
path = 'tests/' + path
return open(path, mode='rb')
Support opening files as text streams on tests
|
import os
def open_file(filename, mode='rb'):
''' Load a file from the fixtures directory. '''
path = 'fixtures/' + filename
if ('tests' in os.listdir('.')):
path = 'tests/' + path
return open(path, mode=mode)
|
<commit_before>import os
def open_file(filename):
''' Load a file from the fixtures directory. '''
path = 'fixtures/' + filename
if ('tests' in os.listdir('.')):
path = 'tests/' + path
return open(path, mode='rb')
<commit_msg>Support opening files as text streams on tests<commit_after>
|
import os
def open_file(filename, mode='rb'):
''' Load a file from the fixtures directory. '''
path = 'fixtures/' + filename
if ('tests' in os.listdir('.')):
path = 'tests/' + path
return open(path, mode=mode)
|
import os
def open_file(filename):
''' Load a file from the fixtures directory. '''
path = 'fixtures/' + filename
if ('tests' in os.listdir('.')):
path = 'tests/' + path
return open(path, mode='rb')
Support opening files as text streams on testsimport os
def open_file(filename, mode='rb'):
''' Load a file from the fixtures directory. '''
path = 'fixtures/' + filename
if ('tests' in os.listdir('.')):
path = 'tests/' + path
return open(path, mode=mode)
|
<commit_before>import os
def open_file(filename):
''' Load a file from the fixtures directory. '''
path = 'fixtures/' + filename
if ('tests' in os.listdir('.')):
path = 'tests/' + path
return open(path, mode='rb')
<commit_msg>Support opening files as text streams on tests<commit_after>import os
def open_file(filename, mode='rb'):
''' Load a file from the fixtures directory. '''
path = 'fixtures/' + filename
if ('tests' in os.listdir('.')):
path = 'tests/' + path
return open(path, mode=mode)
|
8932d0717bf57c86b81b6744353d6387821b8b15
|
wsgi/setup.py
|
wsgi/setup.py
|
import subprocess
import sys
import setup_util
import os
def start(args):
subprocess.Popen("gunicorn hello:app -b 0.0.0.0:8080 -w " + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
return 0
def stop():
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if 'gunicorn' in line:
try:
pid = int(line.split(None, 2)[1])
os.kill(pid, 9)
except OSError:
pass
return 0
|
import subprocess
import sys
import setup_util
import os
def start(args):
subprocess.Popen('gunicorn hello:app --worker-class="egg:meinheld#gunicorn_worker" -b 0.0.0.0:8080 -w '
+ str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
return 0
def stop():
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if 'gunicorn' in line:
try:
pid = int(line.split(None, 2)[1])
os.kill(pid, 9)
except OSError:
pass
return 0
|
Use meinheld worker (same as other Python Frameworks)
|
wsgi: Use meinheld worker (same as other Python Frameworks)
|
Python
|
bsd-3-clause
|
jamming/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,zloster/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,sgml/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,leafo/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,sgml/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,joshk/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,actframework/FrameworkBenchmarks,doom369/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,joshk/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,denkab/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,zloster/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,zloster/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,sxend/FrameworkBenchmarks,jamming/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,herloct/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,grob/FrameworkBenchmarks,grob/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,khellang/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,herloct/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,actframework/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,zapov/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,doom369/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,sgml/FrameworkBenchmarks,denkab/FrameworkBenchmarks,testn/FrameworkBenchmarks,denkab/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,testn/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,Verber/FrameworkBenchmarks,zloster/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,torhve/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,grob/FrameworkBenchmarks,testn/FrameworkBenchmarks,Verber/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,methane/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,testn/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,Verber/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,zloster/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,dmacd/FB-try1,kellabyte/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,actframework/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,zapov/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,zloster/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,dmacd/FB-try1,alubbe/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,grob/FrameworkBenchmarks,zloster/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,Verber/FrameworkBenchmarks,denkab/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,testn/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,valyala/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,torhve/FrameworkBenchmarks,valyala/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,joshk/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,denkab/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,dmacd/FB-try1,valyala/FrameworkBenchmarks,doom369/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,herloct/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,jamming/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,jamming/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,denkab/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,zapov/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,denkab/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,testn/FrameworkBenchmarks,sxend/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,doom369/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,methane/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,khellang/FrameworkBenchmarks,khellang/FrameworkBenchmarks,grob/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,methane/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,khellang/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,dmacd/FB-try1,sanjoydesk/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,sxend/FrameworkBenchmarks,testn/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,grob/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,herloct/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,herloct/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,torhve/FrameworkBenchmarks,herloct/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,zapov/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,leafo/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,zloster/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,Verber/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,sxend/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,methane/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,zloster/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,Verber/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,joshk/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,torhve/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,actframework/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,sxend/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,jamming/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,sgml/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,leafo/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,methane/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,herloct/FrameworkBenchmarks,sxend/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,testn/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,herloct/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,doom369/FrameworkBenchmarks,sxend/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,grob/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,actframework/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,sgml/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,herloct/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,actframework/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,sxend/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,zloster/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,Verber/FrameworkBenchmarks,sgml/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,doom369/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,testn/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Verber/FrameworkBenchmarks,grob/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,herloct/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,methane/FrameworkBenchmarks,Verber/FrameworkBenchmarks,denkab/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,khellang/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,valyala/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,zapov/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,testn/FrameworkBenchmarks,testn/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,torhve/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,zapov/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,khellang/FrameworkBenchmarks,methane/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,leafo/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,khellang/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,khellang/FrameworkBenchmarks,dmacd/FB-try1,martin-g/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jamming/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,actframework/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,joshk/FrameworkBenchmarks,denkab/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,khellang/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,leafo/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,dmacd/FB-try1,kostya-sh/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,khellang/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,methane/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,grob/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,torhve/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,sgml/FrameworkBenchmarks,sgml/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,grob/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,joshk/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,herloct/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,Verber/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,torhve/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,leafo/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,sgml/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,actframework/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,valyala/FrameworkBenchmarks,doom369/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,jamming/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,valyala/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,grob/FrameworkBenchmarks,khellang/FrameworkBenchmarks,torhve/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,zloster/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,zapov/FrameworkBenchmarks,doom369/FrameworkBenchmarks,doom369/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,sxend/FrameworkBenchmarks,zapov/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,zloster/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,joshk/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,doom369/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,doom369/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,valyala/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,zapov/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,methane/FrameworkBenchmarks,sxend/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,torhve/FrameworkBenchmarks,sxend/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,grob/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,actframework/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,actframework/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,dmacd/FB-try1,Synchro/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,khellang/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jamming/FrameworkBenchmarks,sgml/FrameworkBenchmarks,doom369/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,grob/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,methane/FrameworkBenchmarks,doom369/FrameworkBenchmarks,denkab/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,jamming/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,leafo/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,methane/FrameworkBenchmarks,Verber/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,sgml/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,dmacd/FB-try1,jaguililla/FrameworkBenchmarks,joshk/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,zapov/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,herloct/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,sxend/FrameworkBenchmarks,actframework/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,sxend/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,denkab/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,doom369/FrameworkBenchmarks,Verber/FrameworkBenchmarks,sxend/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,actframework/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,joshk/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,valyala/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,Verber/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,sgml/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,actframework/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,khellang/FrameworkBenchmarks,jamming/FrameworkBenchmarks,zloster/FrameworkBenchmarks,zloster/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,actframework/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,zapov/FrameworkBenchmarks,doom369/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,joshk/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,testn/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,denkab/FrameworkBenchmarks,methane/FrameworkBenchmarks,torhve/FrameworkBenchmarks,valyala/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,valyala/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,dmacd/FB-try1,leafo/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,dmacd/FB-try1,fabianmurariu/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,dmacd/FB-try1,jetty-project/FrameworkBenchmarks,leafo/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,valyala/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,ratpack/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,zloster/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,jamming/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,doom369/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,herloct/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,actframework/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,khellang/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,valyala/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,leafo/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,testn/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,denkab/FrameworkBenchmarks,actframework/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,seem-sky/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,methane/FrameworkBenchmarks,joshk/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,torhve/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,julienschmidt/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,dmacd/FB-try1,sxend/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,sgml/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,Verber/FrameworkBenchmarks,zloster/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,methane/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,testn/FrameworkBenchmarks,joshk/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,zapov/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,herloct/FrameworkBenchmarks,herloct/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jamming/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,joshk/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,valyala/FrameworkBenchmarks,sxend/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,torhve/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,joshk/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,sgml/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,denkab/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,jamming/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,valyala/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,leafo/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,leafo/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,jamming/FrameworkBenchmarks,grob/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks
|
import subprocess
import sys
import setup_util
import os
def start(args):
subprocess.Popen("gunicorn hello:app -b 0.0.0.0:8080 -w " + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
return 0
def stop():
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if 'gunicorn' in line:
try:
pid = int(line.split(None, 2)[1])
os.kill(pid, 9)
except OSError:
pass
return 0wsgi: Use meinheld worker (same as other Python Frameworks)
|
import subprocess
import sys
import setup_util
import os
def start(args):
subprocess.Popen('gunicorn hello:app --worker-class="egg:meinheld#gunicorn_worker" -b 0.0.0.0:8080 -w '
+ str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
return 0
def stop():
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if 'gunicorn' in line:
try:
pid = int(line.split(None, 2)[1])
os.kill(pid, 9)
except OSError:
pass
return 0
|
<commit_before>
import subprocess
import sys
import setup_util
import os
def start(args):
subprocess.Popen("gunicorn hello:app -b 0.0.0.0:8080 -w " + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
return 0
def stop():
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if 'gunicorn' in line:
try:
pid = int(line.split(None, 2)[1])
os.kill(pid, 9)
except OSError:
pass
return 0<commit_msg>wsgi: Use meinheld worker (same as other Python Frameworks)<commit_after>
|
import subprocess
import sys
import setup_util
import os
def start(args):
subprocess.Popen('gunicorn hello:app --worker-class="egg:meinheld#gunicorn_worker" -b 0.0.0.0:8080 -w '
+ str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
return 0
def stop():
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if 'gunicorn' in line:
try:
pid = int(line.split(None, 2)[1])
os.kill(pid, 9)
except OSError:
pass
return 0
|
import subprocess
import sys
import setup_util
import os
def start(args):
subprocess.Popen("gunicorn hello:app -b 0.0.0.0:8080 -w " + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
return 0
def stop():
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if 'gunicorn' in line:
try:
pid = int(line.split(None, 2)[1])
os.kill(pid, 9)
except OSError:
pass
return 0wsgi: Use meinheld worker (same as other Python Frameworks)
import subprocess
import sys
import setup_util
import os
def start(args):
subprocess.Popen('gunicorn hello:app --worker-class="egg:meinheld#gunicorn_worker" -b 0.0.0.0:8080 -w '
+ str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
return 0
def stop():
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if 'gunicorn' in line:
try:
pid = int(line.split(None, 2)[1])
os.kill(pid, 9)
except OSError:
pass
return 0
|
<commit_before>
import subprocess
import sys
import setup_util
import os
def start(args):
subprocess.Popen("gunicorn hello:app -b 0.0.0.0:8080 -w " + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
return 0
def stop():
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if 'gunicorn' in line:
try:
pid = int(line.split(None, 2)[1])
os.kill(pid, 9)
except OSError:
pass
return 0<commit_msg>wsgi: Use meinheld worker (same as other Python Frameworks)<commit_after>
import subprocess
import sys
import setup_util
import os
def start(args):
subprocess.Popen('gunicorn hello:app --worker-class="egg:meinheld#gunicorn_worker" -b 0.0.0.0:8080 -w '
+ str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
return 0
def stop():
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if 'gunicorn' in line:
try:
pid = int(line.split(None, 2)[1])
os.kill(pid, 9)
except OSError:
pass
return 0
|
0e68b94d4d5f204dfe9596ddbd3444e906011183
|
sumy/document/_paragraph.py
|
sumy/document/_paragraph.py
|
# -*- coding: utf8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from itertools import chain
from .._compat import unicode_compatible
from ..utils import cached_property
from ._sentence import Sentence
@unicode_compatible
class Paragraph(object):
def __init__(self, sentences):
for sentence in sentences:
if not isinstance(sentence, Sentence):
raise TypeError("Only instances of class 'Sentence' are allowed.")
self._sentences = tuple(sentences)
@cached_property
def sentences(self):
return tuple(s for s in self._sentences if not s.is_heading)
@cached_property
def headings(self):
return tuple(s for s in self._sentences if s.is_heading)
@cached_property
def words(self):
return tuple(chain(*(s.words for s in self._sentences)))
def __unicode__(self):
return "<Paragraph with %d headings & %d sentences>" % (
len(self.headings),
len(self.sentences),
)
def __repr__(self):
return self.__str__()
|
# -*- coding: utf8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from itertools import chain
from .._compat import unicode_compatible
from ..utils import cached_property
from ._sentence import Sentence
@unicode_compatible
class Paragraph(object):
def __init__(self, sentences):
sentences = tuple(sentences)
for sentence in sentences:
if not isinstance(sentence, Sentence):
raise TypeError("Only instances of class 'Sentence' are allowed.")
self._sentences = sentences
@cached_property
def sentences(self):
return tuple(s for s in self._sentences if not s.is_heading)
@cached_property
def headings(self):
return tuple(s for s in self._sentences if s.is_heading)
@cached_property
def words(self):
return tuple(chain(*(s.words for s in self._sentences)))
def __unicode__(self):
return "<Paragraph with %d headings & %d sentences>" % (
len(self.headings),
len(self.sentences),
)
def __repr__(self):
return self.__str__()
|
Allow using iterable of sentences in 'Paragraph'
|
Allow using iterable of sentences in 'Paragraph'
|
Python
|
apache-2.0
|
miso-belica/sumy,miso-belica/sumy
|
# -*- coding: utf8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from itertools import chain
from .._compat import unicode_compatible
from ..utils import cached_property
from ._sentence import Sentence
@unicode_compatible
class Paragraph(object):
def __init__(self, sentences):
for sentence in sentences:
if not isinstance(sentence, Sentence):
raise TypeError("Only instances of class 'Sentence' are allowed.")
self._sentences = tuple(sentences)
@cached_property
def sentences(self):
return tuple(s for s in self._sentences if not s.is_heading)
@cached_property
def headings(self):
return tuple(s for s in self._sentences if s.is_heading)
@cached_property
def words(self):
return tuple(chain(*(s.words for s in self._sentences)))
def __unicode__(self):
return "<Paragraph with %d headings & %d sentences>" % (
len(self.headings),
len(self.sentences),
)
def __repr__(self):
return self.__str__()
Allow using iterable of sentences in 'Paragraph'
|
# -*- coding: utf8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from itertools import chain
from .._compat import unicode_compatible
from ..utils import cached_property
from ._sentence import Sentence
@unicode_compatible
class Paragraph(object):
def __init__(self, sentences):
sentences = tuple(sentences)
for sentence in sentences:
if not isinstance(sentence, Sentence):
raise TypeError("Only instances of class 'Sentence' are allowed.")
self._sentences = sentences
@cached_property
def sentences(self):
return tuple(s for s in self._sentences if not s.is_heading)
@cached_property
def headings(self):
return tuple(s for s in self._sentences if s.is_heading)
@cached_property
def words(self):
return tuple(chain(*(s.words for s in self._sentences)))
def __unicode__(self):
return "<Paragraph with %d headings & %d sentences>" % (
len(self.headings),
len(self.sentences),
)
def __repr__(self):
return self.__str__()
|
<commit_before># -*- coding: utf8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from itertools import chain
from .._compat import unicode_compatible
from ..utils import cached_property
from ._sentence import Sentence
@unicode_compatible
class Paragraph(object):
def __init__(self, sentences):
for sentence in sentences:
if not isinstance(sentence, Sentence):
raise TypeError("Only instances of class 'Sentence' are allowed.")
self._sentences = tuple(sentences)
@cached_property
def sentences(self):
return tuple(s for s in self._sentences if not s.is_heading)
@cached_property
def headings(self):
return tuple(s for s in self._sentences if s.is_heading)
@cached_property
def words(self):
return tuple(chain(*(s.words for s in self._sentences)))
def __unicode__(self):
return "<Paragraph with %d headings & %d sentences>" % (
len(self.headings),
len(self.sentences),
)
def __repr__(self):
return self.__str__()
<commit_msg>Allow using iterable of sentences in 'Paragraph'<commit_after>
|
# -*- coding: utf8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from itertools import chain
from .._compat import unicode_compatible
from ..utils import cached_property
from ._sentence import Sentence
@unicode_compatible
class Paragraph(object):
def __init__(self, sentences):
sentences = tuple(sentences)
for sentence in sentences:
if not isinstance(sentence, Sentence):
raise TypeError("Only instances of class 'Sentence' are allowed.")
self._sentences = sentences
@cached_property
def sentences(self):
return tuple(s for s in self._sentences if not s.is_heading)
@cached_property
def headings(self):
return tuple(s for s in self._sentences if s.is_heading)
@cached_property
def words(self):
return tuple(chain(*(s.words for s in self._sentences)))
def __unicode__(self):
return "<Paragraph with %d headings & %d sentences>" % (
len(self.headings),
len(self.sentences),
)
def __repr__(self):
return self.__str__()
|
# -*- coding: utf8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from itertools import chain
from .._compat import unicode_compatible
from ..utils import cached_property
from ._sentence import Sentence
@unicode_compatible
class Paragraph(object):
def __init__(self, sentences):
for sentence in sentences:
if not isinstance(sentence, Sentence):
raise TypeError("Only instances of class 'Sentence' are allowed.")
self._sentences = tuple(sentences)
@cached_property
def sentences(self):
return tuple(s for s in self._sentences if not s.is_heading)
@cached_property
def headings(self):
return tuple(s for s in self._sentences if s.is_heading)
@cached_property
def words(self):
return tuple(chain(*(s.words for s in self._sentences)))
def __unicode__(self):
return "<Paragraph with %d headings & %d sentences>" % (
len(self.headings),
len(self.sentences),
)
def __repr__(self):
return self.__str__()
Allow using iterable of sentences in 'Paragraph'# -*- coding: utf8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from itertools import chain
from .._compat import unicode_compatible
from ..utils import cached_property
from ._sentence import Sentence
@unicode_compatible
class Paragraph(object):
def __init__(self, sentences):
sentences = tuple(sentences)
for sentence in sentences:
if not isinstance(sentence, Sentence):
raise TypeError("Only instances of class 'Sentence' are allowed.")
self._sentences = sentences
@cached_property
def sentences(self):
return tuple(s for s in self._sentences if not s.is_heading)
@cached_property
def headings(self):
return tuple(s for s in self._sentences if s.is_heading)
@cached_property
def words(self):
return tuple(chain(*(s.words for s in self._sentences)))
def __unicode__(self):
return "<Paragraph with %d headings & %d sentences>" % (
len(self.headings),
len(self.sentences),
)
def __repr__(self):
return self.__str__()
|
<commit_before># -*- coding: utf8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from itertools import chain
from .._compat import unicode_compatible
from ..utils import cached_property
from ._sentence import Sentence
@unicode_compatible
class Paragraph(object):
def __init__(self, sentences):
for sentence in sentences:
if not isinstance(sentence, Sentence):
raise TypeError("Only instances of class 'Sentence' are allowed.")
self._sentences = tuple(sentences)
@cached_property
def sentences(self):
return tuple(s for s in self._sentences if not s.is_heading)
@cached_property
def headings(self):
return tuple(s for s in self._sentences if s.is_heading)
@cached_property
def words(self):
return tuple(chain(*(s.words for s in self._sentences)))
def __unicode__(self):
return "<Paragraph with %d headings & %d sentences>" % (
len(self.headings),
len(self.sentences),
)
def __repr__(self):
return self.__str__()
<commit_msg>Allow using iterable of sentences in 'Paragraph'<commit_after># -*- coding: utf8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from itertools import chain
from .._compat import unicode_compatible
from ..utils import cached_property
from ._sentence import Sentence
@unicode_compatible
class Paragraph(object):
def __init__(self, sentences):
sentences = tuple(sentences)
for sentence in sentences:
if not isinstance(sentence, Sentence):
raise TypeError("Only instances of class 'Sentence' are allowed.")
self._sentences = sentences
@cached_property
def sentences(self):
return tuple(s for s in self._sentences if not s.is_heading)
@cached_property
def headings(self):
return tuple(s for s in self._sentences if s.is_heading)
@cached_property
def words(self):
return tuple(chain(*(s.words for s in self._sentences)))
def __unicode__(self):
return "<Paragraph with %d headings & %d sentences>" % (
len(self.headings),
len(self.sentences),
)
def __repr__(self):
return self.__str__()
|
9abe33697b13ef5a544e3ea51e3f7674eb5f31cf
|
update_config.py
|
update_config.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Rodrigo Ramírez Norambuena <a@rodrigoramirez.com>
#
from libs.qpanel import utils
import sys
if __name__ == '__main__':
sections = ['general', 'manager', 'rename']
file_config = sys.argv[1].strip()
file_template = sys.argv[2].strip()
utils.unified_configs(file_config, file_template, sections)
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Rodrigo Ramírez Norambuena <a@rodrigoramirez.com>
#
from libs.qpanel import utils
import sys
if __name__ == '__main__':
sections = ['general', 'manager', 'rename', 'users']
file_config = sys.argv[1].strip()
file_template = sys.argv[2].strip()
utils.unified_configs(file_config, file_template, sections)
|
Add missing section into script to migrate configs
|
Add missing section into script to migrate configs
|
Python
|
mit
|
skazancev/qpanel,roramirez/qpanel,skazancev/qpanel,skazancev/qpanel,skazancev/qpanel,roramirez/qpanel,roramirez/qpanel,roramirez/qpanel
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Rodrigo Ramírez Norambuena <a@rodrigoramirez.com>
#
from libs.qpanel import utils
import sys
if __name__ == '__main__':
sections = ['general', 'manager', 'rename']
file_config = sys.argv[1].strip()
file_template = sys.argv[2].strip()
utils.unified_configs(file_config, file_template, sections)
Add missing section into script to migrate configs
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Rodrigo Ramírez Norambuena <a@rodrigoramirez.com>
#
from libs.qpanel import utils
import sys
if __name__ == '__main__':
sections = ['general', 'manager', 'rename', 'users']
file_config = sys.argv[1].strip()
file_template = sys.argv[2].strip()
utils.unified_configs(file_config, file_template, sections)
|
<commit_before># -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Rodrigo Ramírez Norambuena <a@rodrigoramirez.com>
#
from libs.qpanel import utils
import sys
if __name__ == '__main__':
sections = ['general', 'manager', 'rename']
file_config = sys.argv[1].strip()
file_template = sys.argv[2].strip()
utils.unified_configs(file_config, file_template, sections)
<commit_msg>Add missing section into script to migrate configs<commit_after>
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Rodrigo Ramírez Norambuena <a@rodrigoramirez.com>
#
from libs.qpanel import utils
import sys
if __name__ == '__main__':
sections = ['general', 'manager', 'rename', 'users']
file_config = sys.argv[1].strip()
file_template = sys.argv[2].strip()
utils.unified_configs(file_config, file_template, sections)
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Rodrigo Ramírez Norambuena <a@rodrigoramirez.com>
#
from libs.qpanel import utils
import sys
if __name__ == '__main__':
sections = ['general', 'manager', 'rename']
file_config = sys.argv[1].strip()
file_template = sys.argv[2].strip()
utils.unified_configs(file_config, file_template, sections)
Add missing section into script to migrate configs# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Rodrigo Ramírez Norambuena <a@rodrigoramirez.com>
#
from libs.qpanel import utils
import sys
if __name__ == '__main__':
sections = ['general', 'manager', 'rename', 'users']
file_config = sys.argv[1].strip()
file_template = sys.argv[2].strip()
utils.unified_configs(file_config, file_template, sections)
|
<commit_before># -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Rodrigo Ramírez Norambuena <a@rodrigoramirez.com>
#
from libs.qpanel import utils
import sys
if __name__ == '__main__':
sections = ['general', 'manager', 'rename']
file_config = sys.argv[1].strip()
file_template = sys.argv[2].strip()
utils.unified_configs(file_config, file_template, sections)
<commit_msg>Add missing section into script to migrate configs<commit_after># -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Rodrigo Ramírez Norambuena <a@rodrigoramirez.com>
#
from libs.qpanel import utils
import sys
if __name__ == '__main__':
sections = ['general', 'manager', 'rename', 'users']
file_config = sys.argv[1].strip()
file_template = sys.argv[2].strip()
utils.unified_configs(file_config, file_template, sections)
|
63edb57a89be453db63da003877a54d9d4974161
|
jprops2bash.py
|
jprops2bash.py
|
#!/usr/bin/env python
import collections
import sys
import jprops
def do_replacements(s, mappings):
for old, new in mappings.items():
s = s.replace(old, new)
return s
def key_transform(key):
key = do_replacements(key, {'.': '_',
':': '_',
'-': '_'})
return key.upper()
def value_transform(value):
return do_replacements(value, {"\n": "\\n",
"'": """'"'"'"""})
def jprops2bash(fh, key_transform=key_transform, value_transform=value_transform):
props_dict = jprops.load_properties(fh, collections.OrderedDict)
for key, value in props_dict.items():
key = key_transform(key)
value = value_transform(value)
yield """{key}='{value}'""".format(key=key, value=value)
def main():
for line in jprops2bash(sys.stdin):
print(line)
if __name__ == '__main__':
sys.exit(main())
|
#!/usr/bin/env python
import collections
import sys
import jprops
def do_replacements(s, mappings):
for old, new in mappings.items():
s = s.replace(old, new)
return s
def key_transform(key):
key = do_replacements(key, {'.': '_',
':': '_',
'-': '_'})
return key.upper()
def value_transform(value):
return do_replacements(value, {"\n": "\\n",
"'": """'"'"'"""})
def jprops2bash(fh, key_transform=key_transform, value_transform=value_transform):
props_dict = jprops.load_properties(fh, collections.OrderedDict)
for key, value in props_dict.items():
key = key_transform(key)
value = value_transform(value)
yield """export {key}='{value}'""".format(key=key, value=value)
def main():
for line in jprops2bash(sys.stdin):
print(line)
if __name__ == '__main__':
sys.exit(main())
|
Add `export` to emitted lines
|
Add `export` to emitted lines
|
Python
|
mit
|
msabramo/jprops2bash
|
#!/usr/bin/env python
import collections
import sys
import jprops
def do_replacements(s, mappings):
for old, new in mappings.items():
s = s.replace(old, new)
return s
def key_transform(key):
key = do_replacements(key, {'.': '_',
':': '_',
'-': '_'})
return key.upper()
def value_transform(value):
return do_replacements(value, {"\n": "\\n",
"'": """'"'"'"""})
def jprops2bash(fh, key_transform=key_transform, value_transform=value_transform):
props_dict = jprops.load_properties(fh, collections.OrderedDict)
for key, value in props_dict.items():
key = key_transform(key)
value = value_transform(value)
yield """{key}='{value}'""".format(key=key, value=value)
def main():
for line in jprops2bash(sys.stdin):
print(line)
if __name__ == '__main__':
sys.exit(main())
Add `export` to emitted lines
|
#!/usr/bin/env python
import collections
import sys
import jprops
def do_replacements(s, mappings):
for old, new in mappings.items():
s = s.replace(old, new)
return s
def key_transform(key):
key = do_replacements(key, {'.': '_',
':': '_',
'-': '_'})
return key.upper()
def value_transform(value):
return do_replacements(value, {"\n": "\\n",
"'": """'"'"'"""})
def jprops2bash(fh, key_transform=key_transform, value_transform=value_transform):
props_dict = jprops.load_properties(fh, collections.OrderedDict)
for key, value in props_dict.items():
key = key_transform(key)
value = value_transform(value)
yield """export {key}='{value}'""".format(key=key, value=value)
def main():
for line in jprops2bash(sys.stdin):
print(line)
if __name__ == '__main__':
sys.exit(main())
|
<commit_before>#!/usr/bin/env python
import collections
import sys
import jprops
def do_replacements(s, mappings):
for old, new in mappings.items():
s = s.replace(old, new)
return s
def key_transform(key):
key = do_replacements(key, {'.': '_',
':': '_',
'-': '_'})
return key.upper()
def value_transform(value):
return do_replacements(value, {"\n": "\\n",
"'": """'"'"'"""})
def jprops2bash(fh, key_transform=key_transform, value_transform=value_transform):
props_dict = jprops.load_properties(fh, collections.OrderedDict)
for key, value in props_dict.items():
key = key_transform(key)
value = value_transform(value)
yield """{key}='{value}'""".format(key=key, value=value)
def main():
for line in jprops2bash(sys.stdin):
print(line)
if __name__ == '__main__':
sys.exit(main())
<commit_msg>Add `export` to emitted lines<commit_after>
|
#!/usr/bin/env python
import collections
import sys
import jprops
def do_replacements(s, mappings):
for old, new in mappings.items():
s = s.replace(old, new)
return s
def key_transform(key):
key = do_replacements(key, {'.': '_',
':': '_',
'-': '_'})
return key.upper()
def value_transform(value):
return do_replacements(value, {"\n": "\\n",
"'": """'"'"'"""})
def jprops2bash(fh, key_transform=key_transform, value_transform=value_transform):
props_dict = jprops.load_properties(fh, collections.OrderedDict)
for key, value in props_dict.items():
key = key_transform(key)
value = value_transform(value)
yield """export {key}='{value}'""".format(key=key, value=value)
def main():
for line in jprops2bash(sys.stdin):
print(line)
if __name__ == '__main__':
sys.exit(main())
|
#!/usr/bin/env python
import collections
import sys
import jprops
def do_replacements(s, mappings):
for old, new in mappings.items():
s = s.replace(old, new)
return s
def key_transform(key):
key = do_replacements(key, {'.': '_',
':': '_',
'-': '_'})
return key.upper()
def value_transform(value):
return do_replacements(value, {"\n": "\\n",
"'": """'"'"'"""})
def jprops2bash(fh, key_transform=key_transform, value_transform=value_transform):
props_dict = jprops.load_properties(fh, collections.OrderedDict)
for key, value in props_dict.items():
key = key_transform(key)
value = value_transform(value)
yield """{key}='{value}'""".format(key=key, value=value)
def main():
for line in jprops2bash(sys.stdin):
print(line)
if __name__ == '__main__':
sys.exit(main())
Add `export` to emitted lines#!/usr/bin/env python
import collections
import sys
import jprops
def do_replacements(s, mappings):
for old, new in mappings.items():
s = s.replace(old, new)
return s
def key_transform(key):
key = do_replacements(key, {'.': '_',
':': '_',
'-': '_'})
return key.upper()
def value_transform(value):
return do_replacements(value, {"\n": "\\n",
"'": """'"'"'"""})
def jprops2bash(fh, key_transform=key_transform, value_transform=value_transform):
props_dict = jprops.load_properties(fh, collections.OrderedDict)
for key, value in props_dict.items():
key = key_transform(key)
value = value_transform(value)
yield """export {key}='{value}'""".format(key=key, value=value)
def main():
for line in jprops2bash(sys.stdin):
print(line)
if __name__ == '__main__':
sys.exit(main())
|
<commit_before>#!/usr/bin/env python
import collections
import sys
import jprops
def do_replacements(s, mappings):
for old, new in mappings.items():
s = s.replace(old, new)
return s
def key_transform(key):
key = do_replacements(key, {'.': '_',
':': '_',
'-': '_'})
return key.upper()
def value_transform(value):
return do_replacements(value, {"\n": "\\n",
"'": """'"'"'"""})
def jprops2bash(fh, key_transform=key_transform, value_transform=value_transform):
props_dict = jprops.load_properties(fh, collections.OrderedDict)
for key, value in props_dict.items():
key = key_transform(key)
value = value_transform(value)
yield """{key}='{value}'""".format(key=key, value=value)
def main():
for line in jprops2bash(sys.stdin):
print(line)
if __name__ == '__main__':
sys.exit(main())
<commit_msg>Add `export` to emitted lines<commit_after>#!/usr/bin/env python
import collections
import sys
import jprops
def do_replacements(s, mappings):
for old, new in mappings.items():
s = s.replace(old, new)
return s
def key_transform(key):
key = do_replacements(key, {'.': '_',
':': '_',
'-': '_'})
return key.upper()
def value_transform(value):
return do_replacements(value, {"\n": "\\n",
"'": """'"'"'"""})
def jprops2bash(fh, key_transform=key_transform, value_transform=value_transform):
props_dict = jprops.load_properties(fh, collections.OrderedDict)
for key, value in props_dict.items():
key = key_transform(key)
value = value_transform(value)
yield """export {key}='{value}'""".format(key=key, value=value)
def main():
for line in jprops2bash(sys.stdin):
print(line)
if __name__ == '__main__':
sys.exit(main())
|
01198751bcdf7ded4e5a3144d08cccd9db7856fc
|
helusers/urls.py
|
helusers/urls.py
|
"""URLs module"""
from django.urls import path
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from . import views
app_name = "helusers"
urlpatterns = []
if not settings.LOGOUT_REDIRECT_URL:
raise ImproperlyConfigured(
"You must configure LOGOUT_REDIRECT_URL to use helusers views."
)
urlpatterns.extend(
[
path("logout/", views.LogoutView.as_view(), name="auth_logout"),
path(
"logout/complete/",
views.LogoutCompleteView.as_view(),
name="auth_logout_complete",
),
path("login/", views.LoginView.as_view(), name="auth_login"),
]
)
|
"""URLs module"""
from django.urls import path
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from . import views
app_name = "helusers"
urlpatterns = []
if (
"social_django" in settings.INSTALLED_APPS
and "helusers.tunnistamo_oidc.TunnistamoOIDCAuth"
in settings.AUTHENTICATION_BACKENDS
):
if not settings.LOGOUT_REDIRECT_URL:
raise ImproperlyConfigured(
"You must configure LOGOUT_REDIRECT_URL to use helusers views."
)
urlpatterns.extend(
[
path("logout/", views.LogoutView.as_view(), name="auth_logout"),
path(
"logout/complete/",
views.LogoutCompleteView.as_view(),
name="auth_logout_complete",
),
path("login/", views.LoginView.as_view(), name="auth_login"),
]
)
|
Include social_auth specific URLs only if social_auth is in use
|
Include social_auth specific URLs only if social_auth is in use
|
Python
|
bsd-2-clause
|
City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers
|
"""URLs module"""
from django.urls import path
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from . import views
app_name = "helusers"
urlpatterns = []
if not settings.LOGOUT_REDIRECT_URL:
raise ImproperlyConfigured(
"You must configure LOGOUT_REDIRECT_URL to use helusers views."
)
urlpatterns.extend(
[
path("logout/", views.LogoutView.as_view(), name="auth_logout"),
path(
"logout/complete/",
views.LogoutCompleteView.as_view(),
name="auth_logout_complete",
),
path("login/", views.LoginView.as_view(), name="auth_login"),
]
)
Include social_auth specific URLs only if social_auth is in use
|
"""URLs module"""
from django.urls import path
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from . import views
app_name = "helusers"
urlpatterns = []
if (
"social_django" in settings.INSTALLED_APPS
and "helusers.tunnistamo_oidc.TunnistamoOIDCAuth"
in settings.AUTHENTICATION_BACKENDS
):
if not settings.LOGOUT_REDIRECT_URL:
raise ImproperlyConfigured(
"You must configure LOGOUT_REDIRECT_URL to use helusers views."
)
urlpatterns.extend(
[
path("logout/", views.LogoutView.as_view(), name="auth_logout"),
path(
"logout/complete/",
views.LogoutCompleteView.as_view(),
name="auth_logout_complete",
),
path("login/", views.LoginView.as_view(), name="auth_login"),
]
)
|
<commit_before>"""URLs module"""
from django.urls import path
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from . import views
app_name = "helusers"
urlpatterns = []
if not settings.LOGOUT_REDIRECT_URL:
raise ImproperlyConfigured(
"You must configure LOGOUT_REDIRECT_URL to use helusers views."
)
urlpatterns.extend(
[
path("logout/", views.LogoutView.as_view(), name="auth_logout"),
path(
"logout/complete/",
views.LogoutCompleteView.as_view(),
name="auth_logout_complete",
),
path("login/", views.LoginView.as_view(), name="auth_login"),
]
)
<commit_msg>Include social_auth specific URLs only if social_auth is in use<commit_after>
|
"""URLs module"""
from django.urls import path
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from . import views
app_name = "helusers"
urlpatterns = []
if (
"social_django" in settings.INSTALLED_APPS
and "helusers.tunnistamo_oidc.TunnistamoOIDCAuth"
in settings.AUTHENTICATION_BACKENDS
):
if not settings.LOGOUT_REDIRECT_URL:
raise ImproperlyConfigured(
"You must configure LOGOUT_REDIRECT_URL to use helusers views."
)
urlpatterns.extend(
[
path("logout/", views.LogoutView.as_view(), name="auth_logout"),
path(
"logout/complete/",
views.LogoutCompleteView.as_view(),
name="auth_logout_complete",
),
path("login/", views.LoginView.as_view(), name="auth_login"),
]
)
|
"""URLs module"""
from django.urls import path
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from . import views
app_name = "helusers"
urlpatterns = []
if not settings.LOGOUT_REDIRECT_URL:
raise ImproperlyConfigured(
"You must configure LOGOUT_REDIRECT_URL to use helusers views."
)
urlpatterns.extend(
[
path("logout/", views.LogoutView.as_view(), name="auth_logout"),
path(
"logout/complete/",
views.LogoutCompleteView.as_view(),
name="auth_logout_complete",
),
path("login/", views.LoginView.as_view(), name="auth_login"),
]
)
Include social_auth specific URLs only if social_auth is in use"""URLs module"""
from django.urls import path
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from . import views
app_name = "helusers"
urlpatterns = []
if (
"social_django" in settings.INSTALLED_APPS
and "helusers.tunnistamo_oidc.TunnistamoOIDCAuth"
in settings.AUTHENTICATION_BACKENDS
):
if not settings.LOGOUT_REDIRECT_URL:
raise ImproperlyConfigured(
"You must configure LOGOUT_REDIRECT_URL to use helusers views."
)
urlpatterns.extend(
[
path("logout/", views.LogoutView.as_view(), name="auth_logout"),
path(
"logout/complete/",
views.LogoutCompleteView.as_view(),
name="auth_logout_complete",
),
path("login/", views.LoginView.as_view(), name="auth_login"),
]
)
|
<commit_before>"""URLs module"""
from django.urls import path
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from . import views
app_name = "helusers"
urlpatterns = []
if not settings.LOGOUT_REDIRECT_URL:
raise ImproperlyConfigured(
"You must configure LOGOUT_REDIRECT_URL to use helusers views."
)
urlpatterns.extend(
[
path("logout/", views.LogoutView.as_view(), name="auth_logout"),
path(
"logout/complete/",
views.LogoutCompleteView.as_view(),
name="auth_logout_complete",
),
path("login/", views.LoginView.as_view(), name="auth_login"),
]
)
<commit_msg>Include social_auth specific URLs only if social_auth is in use<commit_after>"""URLs module"""
from django.urls import path
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from . import views
app_name = "helusers"
urlpatterns = []
if (
"social_django" in settings.INSTALLED_APPS
and "helusers.tunnistamo_oidc.TunnistamoOIDCAuth"
in settings.AUTHENTICATION_BACKENDS
):
if not settings.LOGOUT_REDIRECT_URL:
raise ImproperlyConfigured(
"You must configure LOGOUT_REDIRECT_URL to use helusers views."
)
urlpatterns.extend(
[
path("logout/", views.LogoutView.as_view(), name="auth_logout"),
path(
"logout/complete/",
views.LogoutCompleteView.as_view(),
name="auth_logout_complete",
),
path("login/", views.LoginView.as_view(), name="auth_login"),
]
)
|
256409e253939e70652891a94ffd3d30b365ba13
|
docs/extensions/settings.py
|
docs/extensions/settings.py
|
"""Settings for Zinnia documentation"""
from zinnia.xmlrpc import ZINNIA_XMLRPC_METHODS
DATABASES = {'default': {'NAME': ':memory:',
'ENGINE': 'django.db.backends.sqlite3'}}
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY = 'secret-key'
AKISMET_SECRET_API_KEY = 'AKISMET_API_KEY'
TYPEPAD_SECRET_API_KEY = 'TYPEPAD_API_KEY'
BITLY_LOGIN = 'BITLY_LOGIN'
BITLY_API_KEY = 'BITLY_API_KEY'
MOLLOM_PUBLIC_KEY = 'MOLLOM_PUBLIC_KEY'
MOLLOM_PRIVATE_KEY = 'MOLLOM_PRIVATE_KEY'
INSTALLED_APPS = [
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.comments',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.auth',
'django_xmlrpc',
'mptt', 'tagging', 'zinnia']
|
"""Settings for Zinnia documentation"""
from zinnia.xmlrpc import ZINNIA_XMLRPC_METHODS
DATABASES = {'default': {'NAME': ':memory:',
'ENGINE': 'django.db.backends.sqlite3'}}
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY = 'secret-key'
AKISMET_SECRET_API_KEY = 'AKISMET_API_KEY'
TYPEPAD_SECRET_API_KEY = 'TYPEPAD_API_KEY'
BITLY_LOGIN = 'BITLY_LOGIN'
BITLY_API_KEY = 'BITLY_API_KEY'
MOLLOM_PUBLIC_KEY = 'MOLLOM_PUBLIC_KEY'
MOLLOM_PRIVATE_KEY = 'MOLLOM_PRIVATE_KEY'
INSTALLED_APPS = [
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.auth',
'django_comments',
'django_xmlrpc',
'mptt', 'tagging', 'zinnia']
|
Configure the extension to use django_comments
|
Configure the extension to use django_comments
|
Python
|
bsd-3-clause
|
Fantomas42/django-blog-zinnia,ghachey/django-blog-zinnia,dapeng0802/django-blog-zinnia,Fantomas42/django-blog-zinnia,1844144/django-blog-zinnia,marctc/django-blog-zinnia,1844144/django-blog-zinnia,ghachey/django-blog-zinnia,marctc/django-blog-zinnia,marctc/django-blog-zinnia,ZuluPro/django-blog-zinnia,extertioner/django-blog-zinnia,petecummings/django-blog-zinnia,aorzh/django-blog-zinnia,bywbilly/django-blog-zinnia,Maplecroft/django-blog-zinnia,extertioner/django-blog-zinnia,ZuluPro/django-blog-zinnia,Zopieux/django-blog-zinnia,Fantomas42/django-blog-zinnia,petecummings/django-blog-zinnia,extertioner/django-blog-zinnia,1844144/django-blog-zinnia,Maplecroft/django-blog-zinnia,Zopieux/django-blog-zinnia,bywbilly/django-blog-zinnia,ZuluPro/django-blog-zinnia,Maplecroft/django-blog-zinnia,ghachey/django-blog-zinnia,Zopieux/django-blog-zinnia,dapeng0802/django-blog-zinnia,dapeng0802/django-blog-zinnia,aorzh/django-blog-zinnia,bywbilly/django-blog-zinnia,aorzh/django-blog-zinnia,petecummings/django-blog-zinnia
|
"""Settings for Zinnia documentation"""
from zinnia.xmlrpc import ZINNIA_XMLRPC_METHODS
DATABASES = {'default': {'NAME': ':memory:',
'ENGINE': 'django.db.backends.sqlite3'}}
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY = 'secret-key'
AKISMET_SECRET_API_KEY = 'AKISMET_API_KEY'
TYPEPAD_SECRET_API_KEY = 'TYPEPAD_API_KEY'
BITLY_LOGIN = 'BITLY_LOGIN'
BITLY_API_KEY = 'BITLY_API_KEY'
MOLLOM_PUBLIC_KEY = 'MOLLOM_PUBLIC_KEY'
MOLLOM_PRIVATE_KEY = 'MOLLOM_PRIVATE_KEY'
INSTALLED_APPS = [
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.comments',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.auth',
'django_xmlrpc',
'mptt', 'tagging', 'zinnia']
Configure the extension to use django_comments
|
"""Settings for Zinnia documentation"""
from zinnia.xmlrpc import ZINNIA_XMLRPC_METHODS
DATABASES = {'default': {'NAME': ':memory:',
'ENGINE': 'django.db.backends.sqlite3'}}
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY = 'secret-key'
AKISMET_SECRET_API_KEY = 'AKISMET_API_KEY'
TYPEPAD_SECRET_API_KEY = 'TYPEPAD_API_KEY'
BITLY_LOGIN = 'BITLY_LOGIN'
BITLY_API_KEY = 'BITLY_API_KEY'
MOLLOM_PUBLIC_KEY = 'MOLLOM_PUBLIC_KEY'
MOLLOM_PRIVATE_KEY = 'MOLLOM_PRIVATE_KEY'
INSTALLED_APPS = [
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.auth',
'django_comments',
'django_xmlrpc',
'mptt', 'tagging', 'zinnia']
|
<commit_before>"""Settings for Zinnia documentation"""
from zinnia.xmlrpc import ZINNIA_XMLRPC_METHODS
DATABASES = {'default': {'NAME': ':memory:',
'ENGINE': 'django.db.backends.sqlite3'}}
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY = 'secret-key'
AKISMET_SECRET_API_KEY = 'AKISMET_API_KEY'
TYPEPAD_SECRET_API_KEY = 'TYPEPAD_API_KEY'
BITLY_LOGIN = 'BITLY_LOGIN'
BITLY_API_KEY = 'BITLY_API_KEY'
MOLLOM_PUBLIC_KEY = 'MOLLOM_PUBLIC_KEY'
MOLLOM_PRIVATE_KEY = 'MOLLOM_PRIVATE_KEY'
INSTALLED_APPS = [
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.comments',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.auth',
'django_xmlrpc',
'mptt', 'tagging', 'zinnia']
<commit_msg>Configure the extension to use django_comments<commit_after>
|
"""Settings for Zinnia documentation"""
from zinnia.xmlrpc import ZINNIA_XMLRPC_METHODS
DATABASES = {'default': {'NAME': ':memory:',
'ENGINE': 'django.db.backends.sqlite3'}}
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY = 'secret-key'
AKISMET_SECRET_API_KEY = 'AKISMET_API_KEY'
TYPEPAD_SECRET_API_KEY = 'TYPEPAD_API_KEY'
BITLY_LOGIN = 'BITLY_LOGIN'
BITLY_API_KEY = 'BITLY_API_KEY'
MOLLOM_PUBLIC_KEY = 'MOLLOM_PUBLIC_KEY'
MOLLOM_PRIVATE_KEY = 'MOLLOM_PRIVATE_KEY'
INSTALLED_APPS = [
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.auth',
'django_comments',
'django_xmlrpc',
'mptt', 'tagging', 'zinnia']
|
"""Settings for Zinnia documentation"""
from zinnia.xmlrpc import ZINNIA_XMLRPC_METHODS
DATABASES = {'default': {'NAME': ':memory:',
'ENGINE': 'django.db.backends.sqlite3'}}
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY = 'secret-key'
AKISMET_SECRET_API_KEY = 'AKISMET_API_KEY'
TYPEPAD_SECRET_API_KEY = 'TYPEPAD_API_KEY'
BITLY_LOGIN = 'BITLY_LOGIN'
BITLY_API_KEY = 'BITLY_API_KEY'
MOLLOM_PUBLIC_KEY = 'MOLLOM_PUBLIC_KEY'
MOLLOM_PRIVATE_KEY = 'MOLLOM_PRIVATE_KEY'
INSTALLED_APPS = [
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.comments',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.auth',
'django_xmlrpc',
'mptt', 'tagging', 'zinnia']
Configure the extension to use django_comments"""Settings for Zinnia documentation"""
from zinnia.xmlrpc import ZINNIA_XMLRPC_METHODS
DATABASES = {'default': {'NAME': ':memory:',
'ENGINE': 'django.db.backends.sqlite3'}}
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY = 'secret-key'
AKISMET_SECRET_API_KEY = 'AKISMET_API_KEY'
TYPEPAD_SECRET_API_KEY = 'TYPEPAD_API_KEY'
BITLY_LOGIN = 'BITLY_LOGIN'
BITLY_API_KEY = 'BITLY_API_KEY'
MOLLOM_PUBLIC_KEY = 'MOLLOM_PUBLIC_KEY'
MOLLOM_PRIVATE_KEY = 'MOLLOM_PRIVATE_KEY'
INSTALLED_APPS = [
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.auth',
'django_comments',
'django_xmlrpc',
'mptt', 'tagging', 'zinnia']
|
<commit_before>"""Settings for Zinnia documentation"""
from zinnia.xmlrpc import ZINNIA_XMLRPC_METHODS
DATABASES = {'default': {'NAME': ':memory:',
'ENGINE': 'django.db.backends.sqlite3'}}
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY = 'secret-key'
AKISMET_SECRET_API_KEY = 'AKISMET_API_KEY'
TYPEPAD_SECRET_API_KEY = 'TYPEPAD_API_KEY'
BITLY_LOGIN = 'BITLY_LOGIN'
BITLY_API_KEY = 'BITLY_API_KEY'
MOLLOM_PUBLIC_KEY = 'MOLLOM_PUBLIC_KEY'
MOLLOM_PRIVATE_KEY = 'MOLLOM_PRIVATE_KEY'
INSTALLED_APPS = [
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.comments',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.auth',
'django_xmlrpc',
'mptt', 'tagging', 'zinnia']
<commit_msg>Configure the extension to use django_comments<commit_after>"""Settings for Zinnia documentation"""
from zinnia.xmlrpc import ZINNIA_XMLRPC_METHODS
DATABASES = {'default': {'NAME': ':memory:',
'ENGINE': 'django.db.backends.sqlite3'}}
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY = 'secret-key'
AKISMET_SECRET_API_KEY = 'AKISMET_API_KEY'
TYPEPAD_SECRET_API_KEY = 'TYPEPAD_API_KEY'
BITLY_LOGIN = 'BITLY_LOGIN'
BITLY_API_KEY = 'BITLY_API_KEY'
MOLLOM_PUBLIC_KEY = 'MOLLOM_PUBLIC_KEY'
MOLLOM_PRIVATE_KEY = 'MOLLOM_PRIVATE_KEY'
INSTALLED_APPS = [
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.auth',
'django_comments',
'django_xmlrpc',
'mptt', 'tagging', 'zinnia']
|
9beae1debc5a4402cc67362e905f8aa4eef2bfff
|
midonet/utils.py
|
midonet/utils.py
|
# Copyright (C) 2011 Midokura Japan KK
"""
Internal Utility Functions
"""
import logging
import os.path
logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger('midonet.client')
def debug_print(msg, resp, body):
LOG.debug('-' * 10)
LOG.debug("%s :", msg)
LOG.debug("Resp: %s" % resp)
LOG.debug("Body: %s" % body)
LOG.debug('-' * 10)
def get_uuid(response):
return os.path.basename(response['location'])
|
# Copyright (C) 2011 Midokura Japan KK
"""
Internal Utility Functions
"""
import logging
import os.path
logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger('nova...midonet.client')
def debug_print(msg, resp, body):
LOG.debug('-' * 10)
LOG.debug("%s :", msg)
LOG.debug("Resp: %s" % resp)
LOG.debug("Body: %s" % body)
LOG.debug('-' * 10)
def get_uuid(response):
return os.path.basename(response['location'])
|
Change name for nova integration
|
Change name for nova integration
With Nova's logger setting, logger name starting with 'nova' only gets logged.
|
Python
|
apache-2.0
|
midonet/python-midonetclient,midokura/python-midonetclient,midonet/python-midonetclient,midokura/python-midonetclient
|
# Copyright (C) 2011 Midokura Japan KK
"""
Internal Utility Functions
"""
import logging
import os.path
logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger('midonet.client')
def debug_print(msg, resp, body):
LOG.debug('-' * 10)
LOG.debug("%s :", msg)
LOG.debug("Resp: %s" % resp)
LOG.debug("Body: %s" % body)
LOG.debug('-' * 10)
def get_uuid(response):
return os.path.basename(response['location'])
Change name for nova integration
With Nova's logger setting, logger name starting with 'nova' only gets logged.
|
# Copyright (C) 2011 Midokura Japan KK
"""
Internal Utility Functions
"""
import logging
import os.path
logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger('nova...midonet.client')
def debug_print(msg, resp, body):
LOG.debug('-' * 10)
LOG.debug("%s :", msg)
LOG.debug("Resp: %s" % resp)
LOG.debug("Body: %s" % body)
LOG.debug('-' * 10)
def get_uuid(response):
return os.path.basename(response['location'])
|
<commit_before># Copyright (C) 2011 Midokura Japan KK
"""
Internal Utility Functions
"""
import logging
import os.path
logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger('midonet.client')
def debug_print(msg, resp, body):
LOG.debug('-' * 10)
LOG.debug("%s :", msg)
LOG.debug("Resp: %s" % resp)
LOG.debug("Body: %s" % body)
LOG.debug('-' * 10)
def get_uuid(response):
return os.path.basename(response['location'])
<commit_msg>Change name for nova integration
With Nova's logger setting, logger name starting with 'nova' only gets logged.<commit_after>
|
# Copyright (C) 2011 Midokura Japan KK
"""
Internal Utility Functions
"""
import logging
import os.path
logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger('nova...midonet.client')
def debug_print(msg, resp, body):
LOG.debug('-' * 10)
LOG.debug("%s :", msg)
LOG.debug("Resp: %s" % resp)
LOG.debug("Body: %s" % body)
LOG.debug('-' * 10)
def get_uuid(response):
return os.path.basename(response['location'])
|
# Copyright (C) 2011 Midokura Japan KK
"""
Internal Utility Functions
"""
import logging
import os.path
logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger('midonet.client')
def debug_print(msg, resp, body):
LOG.debug('-' * 10)
LOG.debug("%s :", msg)
LOG.debug("Resp: %s" % resp)
LOG.debug("Body: %s" % body)
LOG.debug('-' * 10)
def get_uuid(response):
return os.path.basename(response['location'])
Change name for nova integration
With Nova's logger setting, logger name starting with 'nova' only gets logged.# Copyright (C) 2011 Midokura Japan KK
"""
Internal Utility Functions
"""
import logging
import os.path
logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger('nova...midonet.client')
def debug_print(msg, resp, body):
LOG.debug('-' * 10)
LOG.debug("%s :", msg)
LOG.debug("Resp: %s" % resp)
LOG.debug("Body: %s" % body)
LOG.debug('-' * 10)
def get_uuid(response):
return os.path.basename(response['location'])
|
<commit_before># Copyright (C) 2011 Midokura Japan KK
"""
Internal Utility Functions
"""
import logging
import os.path
logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger('midonet.client')
def debug_print(msg, resp, body):
LOG.debug('-' * 10)
LOG.debug("%s :", msg)
LOG.debug("Resp: %s" % resp)
LOG.debug("Body: %s" % body)
LOG.debug('-' * 10)
def get_uuid(response):
return os.path.basename(response['location'])
<commit_msg>Change name for nova integration
With Nova's logger setting, logger name starting with 'nova' only gets logged.<commit_after># Copyright (C) 2011 Midokura Japan KK
"""
Internal Utility Functions
"""
import logging
import os.path
logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger('nova...midonet.client')
def debug_print(msg, resp, body):
LOG.debug('-' * 10)
LOG.debug("%s :", msg)
LOG.debug("Resp: %s" % resp)
LOG.debug("Body: %s" % body)
LOG.debug('-' * 10)
def get_uuid(response):
return os.path.basename(response['location'])
|
5d13c06d6d213c4dc35f79b14efb945b93da977b
|
neupy/__init__.py
|
neupy/__init__.py
|
"""
NeuPy is the Artificial Neural Network library implemented in Python.
"""
__version__ = '0.3.0.dev1'
|
"""
NeuPy is the Artificial Neural Network library implemented in Python.
"""
__version__ = '0.3.0.b1'
|
Set up v0.3.0 beta 1.
|
Set up v0.3.0 beta 1.
|
Python
|
mit
|
itdxer/neupy,itdxer/neupy,itdxer/neupy,itdxer/neupy
|
"""
NeuPy is the Artificial Neural Network library implemented in Python.
"""
__version__ = '0.3.0.dev1'
Set up v0.3.0 beta 1.
|
"""
NeuPy is the Artificial Neural Network library implemented in Python.
"""
__version__ = '0.3.0.b1'
|
<commit_before>"""
NeuPy is the Artificial Neural Network library implemented in Python.
"""
__version__ = '0.3.0.dev1'
<commit_msg>Set up v0.3.0 beta 1.<commit_after>
|
"""
NeuPy is the Artificial Neural Network library implemented in Python.
"""
__version__ = '0.3.0.b1'
|
"""
NeuPy is the Artificial Neural Network library implemented in Python.
"""
__version__ = '0.3.0.dev1'
Set up v0.3.0 beta 1."""
NeuPy is the Artificial Neural Network library implemented in Python.
"""
__version__ = '0.3.0.b1'
|
<commit_before>"""
NeuPy is the Artificial Neural Network library implemented in Python.
"""
__version__ = '0.3.0.dev1'
<commit_msg>Set up v0.3.0 beta 1.<commit_after>"""
NeuPy is the Artificial Neural Network library implemented in Python.
"""
__version__ = '0.3.0.b1'
|
3701ab7e372d73c2076988954dabff82f0f16557
|
build/adama-app/adama-package/adama/store.py
|
build/adama-app/adama-package/adama/store.py
|
import collections
import pickle
import redis
from .serf import node
class Store(collections.MutableMapping):
def __init__(self, db=0):
host, port = node(role='redis', port=6379)
self._db = redis.StrictRedis(host=host, port=port, db=db)
def __getitem__(self, key):
obj = self._db.get(key)
if obj is None:
raise KeyError('"{}" not found'.format(key))
return pickle.loads(obj)
def __setitem__(self, key, value):
obj = pickle.dumps(value)
self._db.set(key, obj)
def __delitem__(self, key):
self._db.delete(key)
def __iter__(self):
return self._db.scan_iter()
def __len__(self):
return self._db.dbsize()
store = Store()
|
import collections
import pickle
import redis
from .tools import location
class Store(collections.MutableMapping):
def __init__(self, db=0):
host, port = location('redis', 6379)
self._db = redis.StrictRedis(host=host, port=port, db=db)
def __getitem__(self, key):
obj = self._db.get(key)
if obj is None:
raise KeyError('"{}" not found'.format(key))
return pickle.loads(obj)
def __setitem__(self, key, value):
obj = pickle.dumps(value)
self._db.set(key, obj)
def __delitem__(self, key):
self._db.delete(key)
def __iter__(self):
return self._db.scan_iter()
def __len__(self):
return self._db.dbsize()
store = Store()
|
Store is using serfnode service discovery
|
Store is using serfnode service discovery
|
Python
|
mit
|
waltermoreira/adama-app,waltermoreira/adama-app,waltermoreira/adama-app
|
import collections
import pickle
import redis
from .serf import node
class Store(collections.MutableMapping):
def __init__(self, db=0):
host, port = node(role='redis', port=6379)
self._db = redis.StrictRedis(host=host, port=port, db=db)
def __getitem__(self, key):
obj = self._db.get(key)
if obj is None:
raise KeyError('"{}" not found'.format(key))
return pickle.loads(obj)
def __setitem__(self, key, value):
obj = pickle.dumps(value)
self._db.set(key, obj)
def __delitem__(self, key):
self._db.delete(key)
def __iter__(self):
return self._db.scan_iter()
def __len__(self):
return self._db.dbsize()
store = Store()
Store is using serfnode service discovery
|
import collections
import pickle
import redis
from .tools import location
class Store(collections.MutableMapping):
def __init__(self, db=0):
host, port = location('redis', 6379)
self._db = redis.StrictRedis(host=host, port=port, db=db)
def __getitem__(self, key):
obj = self._db.get(key)
if obj is None:
raise KeyError('"{}" not found'.format(key))
return pickle.loads(obj)
def __setitem__(self, key, value):
obj = pickle.dumps(value)
self._db.set(key, obj)
def __delitem__(self, key):
self._db.delete(key)
def __iter__(self):
return self._db.scan_iter()
def __len__(self):
return self._db.dbsize()
store = Store()
|
<commit_before>import collections
import pickle
import redis
from .serf import node
class Store(collections.MutableMapping):
def __init__(self, db=0):
host, port = node(role='redis', port=6379)
self._db = redis.StrictRedis(host=host, port=port, db=db)
def __getitem__(self, key):
obj = self._db.get(key)
if obj is None:
raise KeyError('"{}" not found'.format(key))
return pickle.loads(obj)
def __setitem__(self, key, value):
obj = pickle.dumps(value)
self._db.set(key, obj)
def __delitem__(self, key):
self._db.delete(key)
def __iter__(self):
return self._db.scan_iter()
def __len__(self):
return self._db.dbsize()
store = Store()
<commit_msg>Store is using serfnode service discovery<commit_after>
|
import collections
import pickle
import redis
from .tools import location
class Store(collections.MutableMapping):
def __init__(self, db=0):
host, port = location('redis', 6379)
self._db = redis.StrictRedis(host=host, port=port, db=db)
def __getitem__(self, key):
obj = self._db.get(key)
if obj is None:
raise KeyError('"{}" not found'.format(key))
return pickle.loads(obj)
def __setitem__(self, key, value):
obj = pickle.dumps(value)
self._db.set(key, obj)
def __delitem__(self, key):
self._db.delete(key)
def __iter__(self):
return self._db.scan_iter()
def __len__(self):
return self._db.dbsize()
store = Store()
|
import collections
import pickle
import redis
from .serf import node
class Store(collections.MutableMapping):
def __init__(self, db=0):
host, port = node(role='redis', port=6379)
self._db = redis.StrictRedis(host=host, port=port, db=db)
def __getitem__(self, key):
obj = self._db.get(key)
if obj is None:
raise KeyError('"{}" not found'.format(key))
return pickle.loads(obj)
def __setitem__(self, key, value):
obj = pickle.dumps(value)
self._db.set(key, obj)
def __delitem__(self, key):
self._db.delete(key)
def __iter__(self):
return self._db.scan_iter()
def __len__(self):
return self._db.dbsize()
store = Store()
Store is using serfnode service discoveryimport collections
import pickle
import redis
from .tools import location
class Store(collections.MutableMapping):
def __init__(self, db=0):
host, port = location('redis', 6379)
self._db = redis.StrictRedis(host=host, port=port, db=db)
def __getitem__(self, key):
obj = self._db.get(key)
if obj is None:
raise KeyError('"{}" not found'.format(key))
return pickle.loads(obj)
def __setitem__(self, key, value):
obj = pickle.dumps(value)
self._db.set(key, obj)
def __delitem__(self, key):
self._db.delete(key)
def __iter__(self):
return self._db.scan_iter()
def __len__(self):
return self._db.dbsize()
store = Store()
|
<commit_before>import collections
import pickle
import redis
from .serf import node
class Store(collections.MutableMapping):
def __init__(self, db=0):
host, port = node(role='redis', port=6379)
self._db = redis.StrictRedis(host=host, port=port, db=db)
def __getitem__(self, key):
obj = self._db.get(key)
if obj is None:
raise KeyError('"{}" not found'.format(key))
return pickle.loads(obj)
def __setitem__(self, key, value):
obj = pickle.dumps(value)
self._db.set(key, obj)
def __delitem__(self, key):
self._db.delete(key)
def __iter__(self):
return self._db.scan_iter()
def __len__(self):
return self._db.dbsize()
store = Store()
<commit_msg>Store is using serfnode service discovery<commit_after>import collections
import pickle
import redis
from .tools import location
class Store(collections.MutableMapping):
def __init__(self, db=0):
host, port = location('redis', 6379)
self._db = redis.StrictRedis(host=host, port=port, db=db)
def __getitem__(self, key):
obj = self._db.get(key)
if obj is None:
raise KeyError('"{}" not found'.format(key))
return pickle.loads(obj)
def __setitem__(self, key, value):
obj = pickle.dumps(value)
self._db.set(key, obj)
def __delitem__(self, key):
self._db.delete(key)
def __iter__(self):
return self._db.scan_iter()
def __len__(self):
return self._db.dbsize()
store = Store()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.