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
86f9fb93725da3ccc308d1957a64e932835f1823
server.py
server.py
from fickle import API from fickle.classifier import GenericSVMClassifier backend = GenericSVMClassifier() app = API(__name__, backend) app.run(debug = True)
from fickle import API from fickle.classifier import GenericSVMClassifier backend = GenericSVMClassifier() app = API(__name__, backend) if __name__ == '__main__': host = '0.0.0.0' port = int(os.environ.get('PORT', 5000)) debug = bool(os.environ.get('FICKLE_DEBUG')) app.run(host = host, port = port, debug = debug)
Copy run section from Heroku example
Copy run section from Heroku example
Python
mit
norbert/fickle
from fickle import API from fickle.classifier import GenericSVMClassifier backend = GenericSVMClassifier() app = API(__name__, backend) app.run(debug = True) Copy run section from Heroku example
from fickle import API from fickle.classifier import GenericSVMClassifier backend = GenericSVMClassifier() app = API(__name__, backend) if __name__ == '__main__': host = '0.0.0.0' port = int(os.environ.get('PORT', 5000)) debug = bool(os.environ.get('FICKLE_DEBUG')) app.run(host = host, port = port, debug = debug)
<commit_before>from fickle import API from fickle.classifier import GenericSVMClassifier backend = GenericSVMClassifier() app = API(__name__, backend) app.run(debug = True) <commit_msg>Copy run section from Heroku example<commit_after>
from fickle import API from fickle.classifier import GenericSVMClassifier backend = GenericSVMClassifier() app = API(__name__, backend) if __name__ == '__main__': host = '0.0.0.0' port = int(os.environ.get('PORT', 5000)) debug = bool(os.environ.get('FICKLE_DEBUG')) app.run(host = host, port = port, debug = debug)
from fickle import API from fickle.classifier import GenericSVMClassifier backend = GenericSVMClassifier() app = API(__name__, backend) app.run(debug = True) Copy run section from Heroku examplefrom fickle import API from fickle.classifier import GenericSVMClassifier backend = GenericSVMClassifier() app = API(__name__, backend) if __name__ == '__main__': host = '0.0.0.0' port = int(os.environ.get('PORT', 5000)) debug = bool(os.environ.get('FICKLE_DEBUG')) app.run(host = host, port = port, debug = debug)
<commit_before>from fickle import API from fickle.classifier import GenericSVMClassifier backend = GenericSVMClassifier() app = API(__name__, backend) app.run(debug = True) <commit_msg>Copy run section from Heroku example<commit_after>from fickle import API from fickle.classifier import GenericSVMClassifier backend = GenericSVMClassifier() app = API(__name__, backend) if __name__ == '__main__': host = '0.0.0.0' port = int(os.environ.get('PORT', 5000)) debug = bool(os.environ.get('FICKLE_DEBUG')) app.run(host = host, port = port, debug = debug)
06ef36df365bc54159d1600d53134e8c70ef50c4
spider.py
spider.py
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1']
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca/data/en'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1']
Modify allowable domain to restrict crawling
Modify allowable domain to restrict crawling
Python
mit
MaxLikelihood/CODE
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1'] Modify allowable domain to restrict crawling
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca/data/en'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1']
<commit_before>from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1'] <commit_msg>Modify allowable domain to restrict crawling<commit_after>
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca/data/en'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1']
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1'] Modify allowable domain to restrict crawlingfrom scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca/data/en'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1']
<commit_before>from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1'] <commit_msg>Modify allowable domain to restrict crawling<commit_after>from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca/data/en'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1']
345d7dda5b48633d5532c6a1ad1d94749f528668
pskb_website/__init__.py
pskb_website/__init__.py
import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) # Running on heroku if 'HEROKU' in os.environ: from example_config import HEROKU_ENV_REQUIREMENTS # example_config.py provides a blueprint for which variables to look for in # the environment and set in our app config. for var in HEROKU_ENV_REQUIREMENTS: app.config.setdefault(var, os.environ[var]) else: app.config.from_object(os.environ['APP_SETTINGS']) app.secret_key = app.config['SECRET_KEY'] db = SQLAlchemy(app) import pskb_website.views
import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) # Running on heroku if 'HEROKU' in os.environ: from example_config import HEROKU_ENV_REQUIREMENTS # example_config.py provides a blueprint for which variables to look for in # the environment and set in our app config. for var in HEROKU_ENV_REQUIREMENTS: app.config.setdefault(var, os.environ[var]) if 'DEBUG' in os.environ: app.config.setdefault('debug', True) else: app.config.from_object(os.environ['APP_SETTINGS']) app.secret_key = app.config['SECRET_KEY'] db = SQLAlchemy(app) import pskb_website.views
Add ability to set debug on heroku staging server
Add ability to set debug on heroku staging server
Python
agpl-3.0
paulocheque/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms,pluralsight/guides-cms
import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) # Running on heroku if 'HEROKU' in os.environ: from example_config import HEROKU_ENV_REQUIREMENTS # example_config.py provides a blueprint for which variables to look for in # the environment and set in our app config. for var in HEROKU_ENV_REQUIREMENTS: app.config.setdefault(var, os.environ[var]) else: app.config.from_object(os.environ['APP_SETTINGS']) app.secret_key = app.config['SECRET_KEY'] db = SQLAlchemy(app) import pskb_website.views Add ability to set debug on heroku staging server
import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) # Running on heroku if 'HEROKU' in os.environ: from example_config import HEROKU_ENV_REQUIREMENTS # example_config.py provides a blueprint for which variables to look for in # the environment and set in our app config. for var in HEROKU_ENV_REQUIREMENTS: app.config.setdefault(var, os.environ[var]) if 'DEBUG' in os.environ: app.config.setdefault('debug', True) else: app.config.from_object(os.environ['APP_SETTINGS']) app.secret_key = app.config['SECRET_KEY'] db = SQLAlchemy(app) import pskb_website.views
<commit_before>import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) # Running on heroku if 'HEROKU' in os.environ: from example_config import HEROKU_ENV_REQUIREMENTS # example_config.py provides a blueprint for which variables to look for in # the environment and set in our app config. for var in HEROKU_ENV_REQUIREMENTS: app.config.setdefault(var, os.environ[var]) else: app.config.from_object(os.environ['APP_SETTINGS']) app.secret_key = app.config['SECRET_KEY'] db = SQLAlchemy(app) import pskb_website.views <commit_msg>Add ability to set debug on heroku staging server<commit_after>
import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) # Running on heroku if 'HEROKU' in os.environ: from example_config import HEROKU_ENV_REQUIREMENTS # example_config.py provides a blueprint for which variables to look for in # the environment and set in our app config. for var in HEROKU_ENV_REQUIREMENTS: app.config.setdefault(var, os.environ[var]) if 'DEBUG' in os.environ: app.config.setdefault('debug', True) else: app.config.from_object(os.environ['APP_SETTINGS']) app.secret_key = app.config['SECRET_KEY'] db = SQLAlchemy(app) import pskb_website.views
import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) # Running on heroku if 'HEROKU' in os.environ: from example_config import HEROKU_ENV_REQUIREMENTS # example_config.py provides a blueprint for which variables to look for in # the environment and set in our app config. for var in HEROKU_ENV_REQUIREMENTS: app.config.setdefault(var, os.environ[var]) else: app.config.from_object(os.environ['APP_SETTINGS']) app.secret_key = app.config['SECRET_KEY'] db = SQLAlchemy(app) import pskb_website.views Add ability to set debug on heroku staging serverimport os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) # Running on heroku if 'HEROKU' in os.environ: from example_config import HEROKU_ENV_REQUIREMENTS # example_config.py provides a blueprint for which variables to look for in # the environment and set in our app config. for var in HEROKU_ENV_REQUIREMENTS: app.config.setdefault(var, os.environ[var]) if 'DEBUG' in os.environ: app.config.setdefault('debug', True) else: app.config.from_object(os.environ['APP_SETTINGS']) app.secret_key = app.config['SECRET_KEY'] db = SQLAlchemy(app) import pskb_website.views
<commit_before>import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) # Running on heroku if 'HEROKU' in os.environ: from example_config import HEROKU_ENV_REQUIREMENTS # example_config.py provides a blueprint for which variables to look for in # the environment and set in our app config. for var in HEROKU_ENV_REQUIREMENTS: app.config.setdefault(var, os.environ[var]) else: app.config.from_object(os.environ['APP_SETTINGS']) app.secret_key = app.config['SECRET_KEY'] db = SQLAlchemy(app) import pskb_website.views <commit_msg>Add ability to set debug on heroku staging server<commit_after>import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) # Running on heroku if 'HEROKU' in os.environ: from example_config import HEROKU_ENV_REQUIREMENTS # example_config.py provides a blueprint for which variables to look for in # the environment and set in our app config. for var in HEROKU_ENV_REQUIREMENTS: app.config.setdefault(var, os.environ[var]) if 'DEBUG' in os.environ: app.config.setdefault('debug', True) else: app.config.from_object(os.environ['APP_SETTINGS']) app.secret_key = app.config['SECRET_KEY'] db = SQLAlchemy(app) import pskb_website.views
64ec292206f4690ae6a8e85f4a7e7e9853d55f32
project_template/config/urls.py
project_template/config/urls.py
from django.conf.urls.defaults import patterns, include, url from django.view.generic import TemplateView # ADMIN_BASE is the base URL for your Armstrong admin. It is highly # recommended that you change this to a different URL unless you enforce a # strict password-strength policy for your users. ADMIN_BASE = "admin" # Comment the next two lines out to disnable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', '{{ project_name }}.views.home', name='home'), # url(r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), # Comment the admin/doc line below to disable admin documentation: url(r'^%s/doc/' % ADMIN_BASE, include('django.contrib.admindocs.urls')), # Comment the next line to disable the admin: url(r'^%s/' % ADMIN_BASE, include(admin.site.urls)), # Load the Armstrong "success" page by default url(r'^$', TemplateView.as_view(template_name="index.html")), )
from django.conf.urls.defaults import patterns, include, url from django.views.generic import TemplateView # ADMIN_BASE is the base URL for your Armstrong admin. It is highly # recommended that you change this to a different URL unless you enforce a # strict password-strength policy for your users. ADMIN_BASE = "admin" # Comment the next two lines out to disnable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', '{{ project_name }}.views.home', name='home'), # url(r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), # Comment the admin/doc line below to disable admin documentation: url(r'^%s/doc/' % ADMIN_BASE, include('django.contrib.admindocs.urls')), # Comment the next line to disable the admin: url(r'^%s/' % ADMIN_BASE, include(admin.site.urls)), # Load the Armstrong "success" page by default url(r'^$', TemplateView.as_view(template_name="index.html")), )
Fix typo in import and bump to 0.3.1
Fix typo in import and bump to 0.3.1
Python
apache-2.0
armstrong/armstrong.templates.standard,armstrong/armstrong.templates.standard
from django.conf.urls.defaults import patterns, include, url from django.view.generic import TemplateView # ADMIN_BASE is the base URL for your Armstrong admin. It is highly # recommended that you change this to a different URL unless you enforce a # strict password-strength policy for your users. ADMIN_BASE = "admin" # Comment the next two lines out to disnable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', '{{ project_name }}.views.home', name='home'), # url(r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), # Comment the admin/doc line below to disable admin documentation: url(r'^%s/doc/' % ADMIN_BASE, include('django.contrib.admindocs.urls')), # Comment the next line to disable the admin: url(r'^%s/' % ADMIN_BASE, include(admin.site.urls)), # Load the Armstrong "success" page by default url(r'^$', TemplateView.as_view(template_name="index.html")), ) Fix typo in import and bump to 0.3.1
from django.conf.urls.defaults import patterns, include, url from django.views.generic import TemplateView # ADMIN_BASE is the base URL for your Armstrong admin. It is highly # recommended that you change this to a different URL unless you enforce a # strict password-strength policy for your users. ADMIN_BASE = "admin" # Comment the next two lines out to disnable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', '{{ project_name }}.views.home', name='home'), # url(r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), # Comment the admin/doc line below to disable admin documentation: url(r'^%s/doc/' % ADMIN_BASE, include('django.contrib.admindocs.urls')), # Comment the next line to disable the admin: url(r'^%s/' % ADMIN_BASE, include(admin.site.urls)), # Load the Armstrong "success" page by default url(r'^$', TemplateView.as_view(template_name="index.html")), )
<commit_before>from django.conf.urls.defaults import patterns, include, url from django.view.generic import TemplateView # ADMIN_BASE is the base URL for your Armstrong admin. It is highly # recommended that you change this to a different URL unless you enforce a # strict password-strength policy for your users. ADMIN_BASE = "admin" # Comment the next two lines out to disnable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', '{{ project_name }}.views.home', name='home'), # url(r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), # Comment the admin/doc line below to disable admin documentation: url(r'^%s/doc/' % ADMIN_BASE, include('django.contrib.admindocs.urls')), # Comment the next line to disable the admin: url(r'^%s/' % ADMIN_BASE, include(admin.site.urls)), # Load the Armstrong "success" page by default url(r'^$', TemplateView.as_view(template_name="index.html")), ) <commit_msg>Fix typo in import and bump to 0.3.1<commit_after>
from django.conf.urls.defaults import patterns, include, url from django.views.generic import TemplateView # ADMIN_BASE is the base URL for your Armstrong admin. It is highly # recommended that you change this to a different URL unless you enforce a # strict password-strength policy for your users. ADMIN_BASE = "admin" # Comment the next two lines out to disnable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', '{{ project_name }}.views.home', name='home'), # url(r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), # Comment the admin/doc line below to disable admin documentation: url(r'^%s/doc/' % ADMIN_BASE, include('django.contrib.admindocs.urls')), # Comment the next line to disable the admin: url(r'^%s/' % ADMIN_BASE, include(admin.site.urls)), # Load the Armstrong "success" page by default url(r'^$', TemplateView.as_view(template_name="index.html")), )
from django.conf.urls.defaults import patterns, include, url from django.view.generic import TemplateView # ADMIN_BASE is the base URL for your Armstrong admin. It is highly # recommended that you change this to a different URL unless you enforce a # strict password-strength policy for your users. ADMIN_BASE = "admin" # Comment the next two lines out to disnable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', '{{ project_name }}.views.home', name='home'), # url(r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), # Comment the admin/doc line below to disable admin documentation: url(r'^%s/doc/' % ADMIN_BASE, include('django.contrib.admindocs.urls')), # Comment the next line to disable the admin: url(r'^%s/' % ADMIN_BASE, include(admin.site.urls)), # Load the Armstrong "success" page by default url(r'^$', TemplateView.as_view(template_name="index.html")), ) Fix typo in import and bump to 0.3.1from django.conf.urls.defaults import patterns, include, url from django.views.generic import TemplateView # ADMIN_BASE is the base URL for your Armstrong admin. It is highly # recommended that you change this to a different URL unless you enforce a # strict password-strength policy for your users. ADMIN_BASE = "admin" # Comment the next two lines out to disnable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', '{{ project_name }}.views.home', name='home'), # url(r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), # Comment the admin/doc line below to disable admin documentation: url(r'^%s/doc/' % ADMIN_BASE, include('django.contrib.admindocs.urls')), # Comment the next line to disable the admin: url(r'^%s/' % ADMIN_BASE, include(admin.site.urls)), # Load the Armstrong "success" page by default url(r'^$', TemplateView.as_view(template_name="index.html")), )
<commit_before>from django.conf.urls.defaults import patterns, include, url from django.view.generic import TemplateView # ADMIN_BASE is the base URL for your Armstrong admin. It is highly # recommended that you change this to a different URL unless you enforce a # strict password-strength policy for your users. ADMIN_BASE = "admin" # Comment the next two lines out to disnable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', '{{ project_name }}.views.home', name='home'), # url(r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), # Comment the admin/doc line below to disable admin documentation: url(r'^%s/doc/' % ADMIN_BASE, include('django.contrib.admindocs.urls')), # Comment the next line to disable the admin: url(r'^%s/' % ADMIN_BASE, include(admin.site.urls)), # Load the Armstrong "success" page by default url(r'^$', TemplateView.as_view(template_name="index.html")), ) <commit_msg>Fix typo in import and bump to 0.3.1<commit_after>from django.conf.urls.defaults import patterns, include, url from django.views.generic import TemplateView # ADMIN_BASE is the base URL for your Armstrong admin. It is highly # recommended that you change this to a different URL unless you enforce a # strict password-strength policy for your users. ADMIN_BASE = "admin" # Comment the next two lines out to disnable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', '{{ project_name }}.views.home', name='home'), # url(r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), # Comment the admin/doc line below to disable admin documentation: url(r'^%s/doc/' % ADMIN_BASE, include('django.contrib.admindocs.urls')), # Comment the next line to disable the admin: url(r'^%s/' % ADMIN_BASE, include(admin.site.urls)), # Load the Armstrong "success" page by default url(r'^$', TemplateView.as_view(template_name="index.html")), )
4d06890ae7223a61147da857d8cdfb6c208dfc52
lib/pegasus/python/Pegasus/cli/pegasus-init.py
lib/pegasus/python/Pegasus/cli/pegasus-init.py
#!/usr/bin/env python3 import sys import os import subprocess # Use pegasus-config to find our lib path bin_dir = os.path.normpath(os.path.join(os.path.dirname(sys.argv[0]))) pegasus_config = os.path.join(bin_dir, "pegasus-config") + " --python-dump" exec(subprocess.Popen(pegasus_config, stdout=subprocess.PIPE, shell=True).communicate()[0]) # Insert this directory in our search path os.sys.path.insert(0, pegasus_python_dir) os.sys.path.insert(0, pegasus_python_externals_dir) from Pegasus.init import main main(pegasus_share_dir)
#!/usr/bin/env python3 import os from pathlib import Path from Pegasus.init import main pegasus_share_dir = (Path(os.environ["PEGASUS_HOME"]) / "share" / "pegasus").resolve() main(str(pegasus_share_dir))
Remove call to p-config, as it is handled in p-python-wrapper
Remove call to p-config, as it is handled in p-python-wrapper
Python
apache-2.0
pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus
#!/usr/bin/env python3 import sys import os import subprocess # Use pegasus-config to find our lib path bin_dir = os.path.normpath(os.path.join(os.path.dirname(sys.argv[0]))) pegasus_config = os.path.join(bin_dir, "pegasus-config") + " --python-dump" exec(subprocess.Popen(pegasus_config, stdout=subprocess.PIPE, shell=True).communicate()[0]) # Insert this directory in our search path os.sys.path.insert(0, pegasus_python_dir) os.sys.path.insert(0, pegasus_python_externals_dir) from Pegasus.init import main main(pegasus_share_dir) Remove call to p-config, as it is handled in p-python-wrapper
#!/usr/bin/env python3 import os from pathlib import Path from Pegasus.init import main pegasus_share_dir = (Path(os.environ["PEGASUS_HOME"]) / "share" / "pegasus").resolve() main(str(pegasus_share_dir))
<commit_before>#!/usr/bin/env python3 import sys import os import subprocess # Use pegasus-config to find our lib path bin_dir = os.path.normpath(os.path.join(os.path.dirname(sys.argv[0]))) pegasus_config = os.path.join(bin_dir, "pegasus-config") + " --python-dump" exec(subprocess.Popen(pegasus_config, stdout=subprocess.PIPE, shell=True).communicate()[0]) # Insert this directory in our search path os.sys.path.insert(0, pegasus_python_dir) os.sys.path.insert(0, pegasus_python_externals_dir) from Pegasus.init import main main(pegasus_share_dir) <commit_msg>Remove call to p-config, as it is handled in p-python-wrapper<commit_after>
#!/usr/bin/env python3 import os from pathlib import Path from Pegasus.init import main pegasus_share_dir = (Path(os.environ["PEGASUS_HOME"]) / "share" / "pegasus").resolve() main(str(pegasus_share_dir))
#!/usr/bin/env python3 import sys import os import subprocess # Use pegasus-config to find our lib path bin_dir = os.path.normpath(os.path.join(os.path.dirname(sys.argv[0]))) pegasus_config = os.path.join(bin_dir, "pegasus-config") + " --python-dump" exec(subprocess.Popen(pegasus_config, stdout=subprocess.PIPE, shell=True).communicate()[0]) # Insert this directory in our search path os.sys.path.insert(0, pegasus_python_dir) os.sys.path.insert(0, pegasus_python_externals_dir) from Pegasus.init import main main(pegasus_share_dir) Remove call to p-config, as it is handled in p-python-wrapper#!/usr/bin/env python3 import os from pathlib import Path from Pegasus.init import main pegasus_share_dir = (Path(os.environ["PEGASUS_HOME"]) / "share" / "pegasus").resolve() main(str(pegasus_share_dir))
<commit_before>#!/usr/bin/env python3 import sys import os import subprocess # Use pegasus-config to find our lib path bin_dir = os.path.normpath(os.path.join(os.path.dirname(sys.argv[0]))) pegasus_config = os.path.join(bin_dir, "pegasus-config") + " --python-dump" exec(subprocess.Popen(pegasus_config, stdout=subprocess.PIPE, shell=True).communicate()[0]) # Insert this directory in our search path os.sys.path.insert(0, pegasus_python_dir) os.sys.path.insert(0, pegasus_python_externals_dir) from Pegasus.init import main main(pegasus_share_dir) <commit_msg>Remove call to p-config, as it is handled in p-python-wrapper<commit_after>#!/usr/bin/env python3 import os from pathlib import Path from Pegasus.init import main pegasus_share_dir = (Path(os.environ["PEGASUS_HOME"]) / "share" / "pegasus").resolve() main(str(pegasus_share_dir))
e2efb3855cd7888b778c3c7ff343c2bdcb942ab0
pushmanager/testing/__init__.py
pushmanager/testing/__init__.py
#!/usr/bin/env python import testify # don't want all of testify's modules, just its goodies from testify.__init__ import * from mocksettings import MockedSettings from testservlet import AsyncTestCase from testservlet import ServletTestMixin from testservlet import TemplateTestCase from testdb import * __all__ = [ AsyncTestCase, MockedSettings, testify, ServletTestMixin, TemplateTestCase ]
#!/usr/bin/python # don't want all of testify's modules, just its goodies from testify import TestCase from testify import teardown from testify import class_teardown from testify import class_setup_teardown from testify import setup_teardown from testify import setup from testify import class_setup from testify import assert_equal from testify import assert_exactly_one from testify import assert_dicts_equal from testify import assert_in from testify import assert_is from testify import assert_length from testify import assert_not_equal from testify import assert_not_in from testify import assert_raises from testify import assert_sorted_equal __all__ = [ assert_equal, assert_exactly_one, assert_dicts_equal, assert_in, assert_is, assert_length, assert_not_equal, assert_not_in, assert_raises, assert_sorted_equal, class_setup, class_setup_teardown, class_teardown, setup, setup_teardown, teardown, TestCase, ]
Make pushmanager.testing more explicit in imports
Make pushmanager.testing more explicit in imports
Python
apache-2.0
Yelp/pushmanager,YelpArchive/pushmanager,asottile/pushmanager,Yelp/pushmanager,asottile/pushmanager,YelpArchive/pushmanager,YelpArchive/pushmanager,asottile/pushmanager,Yelp/pushmanager,Yelp/pushmanager,YelpArchive/pushmanager
#!/usr/bin/env python import testify # don't want all of testify's modules, just its goodies from testify.__init__ import * from mocksettings import MockedSettings from testservlet import AsyncTestCase from testservlet import ServletTestMixin from testservlet import TemplateTestCase from testdb import * __all__ = [ AsyncTestCase, MockedSettings, testify, ServletTestMixin, TemplateTestCase ] Make pushmanager.testing more explicit in imports
#!/usr/bin/python # don't want all of testify's modules, just its goodies from testify import TestCase from testify import teardown from testify import class_teardown from testify import class_setup_teardown from testify import setup_teardown from testify import setup from testify import class_setup from testify import assert_equal from testify import assert_exactly_one from testify import assert_dicts_equal from testify import assert_in from testify import assert_is from testify import assert_length from testify import assert_not_equal from testify import assert_not_in from testify import assert_raises from testify import assert_sorted_equal __all__ = [ assert_equal, assert_exactly_one, assert_dicts_equal, assert_in, assert_is, assert_length, assert_not_equal, assert_not_in, assert_raises, assert_sorted_equal, class_setup, class_setup_teardown, class_teardown, setup, setup_teardown, teardown, TestCase, ]
<commit_before>#!/usr/bin/env python import testify # don't want all of testify's modules, just its goodies from testify.__init__ import * from mocksettings import MockedSettings from testservlet import AsyncTestCase from testservlet import ServletTestMixin from testservlet import TemplateTestCase from testdb import * __all__ = [ AsyncTestCase, MockedSettings, testify, ServletTestMixin, TemplateTestCase ] <commit_msg>Make pushmanager.testing more explicit in imports<commit_after>
#!/usr/bin/python # don't want all of testify's modules, just its goodies from testify import TestCase from testify import teardown from testify import class_teardown from testify import class_setup_teardown from testify import setup_teardown from testify import setup from testify import class_setup from testify import assert_equal from testify import assert_exactly_one from testify import assert_dicts_equal from testify import assert_in from testify import assert_is from testify import assert_length from testify import assert_not_equal from testify import assert_not_in from testify import assert_raises from testify import assert_sorted_equal __all__ = [ assert_equal, assert_exactly_one, assert_dicts_equal, assert_in, assert_is, assert_length, assert_not_equal, assert_not_in, assert_raises, assert_sorted_equal, class_setup, class_setup_teardown, class_teardown, setup, setup_teardown, teardown, TestCase, ]
#!/usr/bin/env python import testify # don't want all of testify's modules, just its goodies from testify.__init__ import * from mocksettings import MockedSettings from testservlet import AsyncTestCase from testservlet import ServletTestMixin from testservlet import TemplateTestCase from testdb import * __all__ = [ AsyncTestCase, MockedSettings, testify, ServletTestMixin, TemplateTestCase ] Make pushmanager.testing more explicit in imports#!/usr/bin/python # don't want all of testify's modules, just its goodies from testify import TestCase from testify import teardown from testify import class_teardown from testify import class_setup_teardown from testify import setup_teardown from testify import setup from testify import class_setup from testify import assert_equal from testify import assert_exactly_one from testify import assert_dicts_equal from testify import assert_in from testify import assert_is from testify import assert_length from testify import assert_not_equal from testify import assert_not_in from testify import assert_raises from testify import assert_sorted_equal __all__ = [ assert_equal, assert_exactly_one, assert_dicts_equal, assert_in, assert_is, assert_length, assert_not_equal, assert_not_in, assert_raises, assert_sorted_equal, class_setup, class_setup_teardown, class_teardown, setup, setup_teardown, teardown, TestCase, ]
<commit_before>#!/usr/bin/env python import testify # don't want all of testify's modules, just its goodies from testify.__init__ import * from mocksettings import MockedSettings from testservlet import AsyncTestCase from testservlet import ServletTestMixin from testservlet import TemplateTestCase from testdb import * __all__ = [ AsyncTestCase, MockedSettings, testify, ServletTestMixin, TemplateTestCase ] <commit_msg>Make pushmanager.testing more explicit in imports<commit_after>#!/usr/bin/python # don't want all of testify's modules, just its goodies from testify import TestCase from testify import teardown from testify import class_teardown from testify import class_setup_teardown from testify import setup_teardown from testify import setup from testify import class_setup from testify import assert_equal from testify import assert_exactly_one from testify import assert_dicts_equal from testify import assert_in from testify import assert_is from testify import assert_length from testify import assert_not_equal from testify import assert_not_in from testify import assert_raises from testify import assert_sorted_equal __all__ = [ assert_equal, assert_exactly_one, assert_dicts_equal, assert_in, assert_is, assert_length, assert_not_equal, assert_not_in, assert_raises, assert_sorted_equal, class_setup, class_setup_teardown, class_teardown, setup, setup_teardown, teardown, TestCase, ]
06968396f475cf881adcab06272df6de4f94f3ff
scripts/master/factory/dart/channels.py
scripts/master/factory/dart/channels.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. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.6', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
# 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. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.7', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
Make dart master pull stable from 1.7
Make dart master pull stable from 1.7 Review URL: https://codereview.chromium.org/638823002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@292365 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
# 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. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.6', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c Make dart master pull stable from 1.7 Review URL: https://codereview.chromium.org/638823002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@292365 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. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.7', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
<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. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.6', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c <commit_msg>Make dart master pull stable from 1.7 Review URL: https://codereview.chromium.org/638823002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@292365 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. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.7', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
# 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. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.6', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c Make dart master pull stable from 1.7 Review URL: https://codereview.chromium.org/638823002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@292365 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. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.7', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
<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. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.6', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c <commit_msg>Make dart master pull stable from 1.7 Review URL: https://codereview.chromium.org/638823002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@292365 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. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.7', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
c6a517717083eedffeb7b70bfdf6cbf7049516e4
main.py
main.py
# Import blockmodels file import BlockModels import webapp2, jinja2, os from datetime import * jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) class CST(tzinfo): def utcoffset(self, dt): return timedelta(hours=-6) def tzname(self, dt): return "US/Central" def dst(self, dt): return timedelta(0) cst = CST() class Schedule_Handler(webapp2.RequestHandler): def get(self): schedule = BlockModels.schedule() tlocal = datetime.now(cst) formNow = datetime.strftime(tlocal, "%A, %b %d %I:%M:%S %p") template_values = { 'schedule': schedule, 'localtime': formNow, } template = jinja_environment.get_template('schedule.html') self.response.out.write(template.render(template_values)) app = webapp2.WSGIApplication([ ('/schedule', Schedule_Handler) ], debug=True)
# Import blockmodels file import BlockModels import webapp2, jinja2, os from datetime import * jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) class CST(tzinfo): def utcoffset(self, dt): return timedelta(hours=-6) def tzname(self, dt): return "US/Central" def dst(self, dt): return timedelta(0) cst = CST() class MainHandler(webapp2.RequestHandler): def get(self): template_values = { 'block': block, } template = jinja_environment.get_template('index.html') self.response.out.write(template.render(template_values)) class Schedule_Handler(webapp2.RequestHandler): def get(self): schedule = BlockModels.schedule() tlocal = datetime.now(cst) formNow = datetime.strftime(tlocal, "%A, %b %d %I:%M:%S %p") template_values = { 'schedule': schedule, 'localtime': formNow, } template = jinja_environment.get_template('schedule.html') self.response.out.write(template.render(template_values)) app = webapp2.WSGIApplication([ ('/', MainHandler) ('/schedule', Schedule_Handler) ], debug=True)
Create new Class MainHandler with the template values with the variable block and made it into index.html
Create new Class MainHandler with the template values with the variable block and made it into index.html
Python
mit
shickey/BearStatus,shickey/BearStatus,shickey/BearStatus
# Import blockmodels file import BlockModels import webapp2, jinja2, os from datetime import * jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) class CST(tzinfo): def utcoffset(self, dt): return timedelta(hours=-6) def tzname(self, dt): return "US/Central" def dst(self, dt): return timedelta(0) cst = CST() class Schedule_Handler(webapp2.RequestHandler): def get(self): schedule = BlockModels.schedule() tlocal = datetime.now(cst) formNow = datetime.strftime(tlocal, "%A, %b %d %I:%M:%S %p") template_values = { 'schedule': schedule, 'localtime': formNow, } template = jinja_environment.get_template('schedule.html') self.response.out.write(template.render(template_values)) app = webapp2.WSGIApplication([ ('/schedule', Schedule_Handler) ], debug=True) Create new Class MainHandler with the template values with the variable block and made it into index.html
# Import blockmodels file import BlockModels import webapp2, jinja2, os from datetime import * jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) class CST(tzinfo): def utcoffset(self, dt): return timedelta(hours=-6) def tzname(self, dt): return "US/Central" def dst(self, dt): return timedelta(0) cst = CST() class MainHandler(webapp2.RequestHandler): def get(self): template_values = { 'block': block, } template = jinja_environment.get_template('index.html') self.response.out.write(template.render(template_values)) class Schedule_Handler(webapp2.RequestHandler): def get(self): schedule = BlockModels.schedule() tlocal = datetime.now(cst) formNow = datetime.strftime(tlocal, "%A, %b %d %I:%M:%S %p") template_values = { 'schedule': schedule, 'localtime': formNow, } template = jinja_environment.get_template('schedule.html') self.response.out.write(template.render(template_values)) app = webapp2.WSGIApplication([ ('/', MainHandler) ('/schedule', Schedule_Handler) ], debug=True)
<commit_before># Import blockmodels file import BlockModels import webapp2, jinja2, os from datetime import * jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) class CST(tzinfo): def utcoffset(self, dt): return timedelta(hours=-6) def tzname(self, dt): return "US/Central" def dst(self, dt): return timedelta(0) cst = CST() class Schedule_Handler(webapp2.RequestHandler): def get(self): schedule = BlockModels.schedule() tlocal = datetime.now(cst) formNow = datetime.strftime(tlocal, "%A, %b %d %I:%M:%S %p") template_values = { 'schedule': schedule, 'localtime': formNow, } template = jinja_environment.get_template('schedule.html') self.response.out.write(template.render(template_values)) app = webapp2.WSGIApplication([ ('/schedule', Schedule_Handler) ], debug=True) <commit_msg>Create new Class MainHandler with the template values with the variable block and made it into index.html<commit_after>
# Import blockmodels file import BlockModels import webapp2, jinja2, os from datetime import * jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) class CST(tzinfo): def utcoffset(self, dt): return timedelta(hours=-6) def tzname(self, dt): return "US/Central" def dst(self, dt): return timedelta(0) cst = CST() class MainHandler(webapp2.RequestHandler): def get(self): template_values = { 'block': block, } template = jinja_environment.get_template('index.html') self.response.out.write(template.render(template_values)) class Schedule_Handler(webapp2.RequestHandler): def get(self): schedule = BlockModels.schedule() tlocal = datetime.now(cst) formNow = datetime.strftime(tlocal, "%A, %b %d %I:%M:%S %p") template_values = { 'schedule': schedule, 'localtime': formNow, } template = jinja_environment.get_template('schedule.html') self.response.out.write(template.render(template_values)) app = webapp2.WSGIApplication([ ('/', MainHandler) ('/schedule', Schedule_Handler) ], debug=True)
# Import blockmodels file import BlockModels import webapp2, jinja2, os from datetime import * jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) class CST(tzinfo): def utcoffset(self, dt): return timedelta(hours=-6) def tzname(self, dt): return "US/Central" def dst(self, dt): return timedelta(0) cst = CST() class Schedule_Handler(webapp2.RequestHandler): def get(self): schedule = BlockModels.schedule() tlocal = datetime.now(cst) formNow = datetime.strftime(tlocal, "%A, %b %d %I:%M:%S %p") template_values = { 'schedule': schedule, 'localtime': formNow, } template = jinja_environment.get_template('schedule.html') self.response.out.write(template.render(template_values)) app = webapp2.WSGIApplication([ ('/schedule', Schedule_Handler) ], debug=True) Create new Class MainHandler with the template values with the variable block and made it into index.html# Import blockmodels file import BlockModels import webapp2, jinja2, os from datetime import * jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) class CST(tzinfo): def utcoffset(self, dt): return timedelta(hours=-6) def tzname(self, dt): return "US/Central" def dst(self, dt): return timedelta(0) cst = CST() class MainHandler(webapp2.RequestHandler): def get(self): template_values = { 'block': block, } template = jinja_environment.get_template('index.html') self.response.out.write(template.render(template_values)) class Schedule_Handler(webapp2.RequestHandler): def get(self): schedule = BlockModels.schedule() tlocal = datetime.now(cst) formNow = datetime.strftime(tlocal, "%A, %b %d %I:%M:%S %p") template_values = { 'schedule': schedule, 'localtime': formNow, } template = jinja_environment.get_template('schedule.html') self.response.out.write(template.render(template_values)) app = webapp2.WSGIApplication([ ('/', MainHandler) ('/schedule', Schedule_Handler) ], debug=True)
<commit_before># Import blockmodels file import BlockModels import webapp2, jinja2, os from datetime import * jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) class CST(tzinfo): def utcoffset(self, dt): return timedelta(hours=-6) def tzname(self, dt): return "US/Central" def dst(self, dt): return timedelta(0) cst = CST() class Schedule_Handler(webapp2.RequestHandler): def get(self): schedule = BlockModels.schedule() tlocal = datetime.now(cst) formNow = datetime.strftime(tlocal, "%A, %b %d %I:%M:%S %p") template_values = { 'schedule': schedule, 'localtime': formNow, } template = jinja_environment.get_template('schedule.html') self.response.out.write(template.render(template_values)) app = webapp2.WSGIApplication([ ('/schedule', Schedule_Handler) ], debug=True) <commit_msg>Create new Class MainHandler with the template values with the variable block and made it into index.html<commit_after># Import blockmodels file import BlockModels import webapp2, jinja2, os from datetime import * jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) class CST(tzinfo): def utcoffset(self, dt): return timedelta(hours=-6) def tzname(self, dt): return "US/Central" def dst(self, dt): return timedelta(0) cst = CST() class MainHandler(webapp2.RequestHandler): def get(self): template_values = { 'block': block, } template = jinja_environment.get_template('index.html') self.response.out.write(template.render(template_values)) class Schedule_Handler(webapp2.RequestHandler): def get(self): schedule = BlockModels.schedule() tlocal = datetime.now(cst) formNow = datetime.strftime(tlocal, "%A, %b %d %I:%M:%S %p") template_values = { 'schedule': schedule, 'localtime': formNow, } template = jinja_environment.get_template('schedule.html') self.response.out.write(template.render(template_values)) app = webapp2.WSGIApplication([ ('/', MainHandler) ('/schedule', Schedule_Handler) ], debug=True)
e6f7c6657485b33760e2522afb6b25ba5ed405fd
pyramid_zipkin/zipkin.py
pyramid_zipkin/zipkin.py
# -*- coding: utf-8 -*- from py_zipkin.zipkin import create_http_headers_for_new_span \ as create_headers_for_new_span # pragma: no cover
# -*- coding: utf-8 -*- from py_zipkin.zipkin import create_http_headers_for_new_span # pragma: no cover # Backwards compatibility for places where pyramid_zipkin is unpinned create_headers_for_new_span = create_http_headers_for_new_span # pragma: no cover
Split import into 2 lines to make flake8 happy
Split import into 2 lines to make flake8 happy
Python
apache-2.0
bplotnick/pyramid_zipkin,Yelp/pyramid_zipkin
# -*- coding: utf-8 -*- from py_zipkin.zipkin import create_http_headers_for_new_span \ as create_headers_for_new_span # pragma: no cover Split import into 2 lines to make flake8 happy
# -*- coding: utf-8 -*- from py_zipkin.zipkin import create_http_headers_for_new_span # pragma: no cover # Backwards compatibility for places where pyramid_zipkin is unpinned create_headers_for_new_span = create_http_headers_for_new_span # pragma: no cover
<commit_before># -*- coding: utf-8 -*- from py_zipkin.zipkin import create_http_headers_for_new_span \ as create_headers_for_new_span # pragma: no cover <commit_msg>Split import into 2 lines to make flake8 happy<commit_after>
# -*- coding: utf-8 -*- from py_zipkin.zipkin import create_http_headers_for_new_span # pragma: no cover # Backwards compatibility for places where pyramid_zipkin is unpinned create_headers_for_new_span = create_http_headers_for_new_span # pragma: no cover
# -*- coding: utf-8 -*- from py_zipkin.zipkin import create_http_headers_for_new_span \ as create_headers_for_new_span # pragma: no cover Split import into 2 lines to make flake8 happy# -*- coding: utf-8 -*- from py_zipkin.zipkin import create_http_headers_for_new_span # pragma: no cover # Backwards compatibility for places where pyramid_zipkin is unpinned create_headers_for_new_span = create_http_headers_for_new_span # pragma: no cover
<commit_before># -*- coding: utf-8 -*- from py_zipkin.zipkin import create_http_headers_for_new_span \ as create_headers_for_new_span # pragma: no cover <commit_msg>Split import into 2 lines to make flake8 happy<commit_after># -*- coding: utf-8 -*- from py_zipkin.zipkin import create_http_headers_for_new_span # pragma: no cover # Backwards compatibility for places where pyramid_zipkin is unpinned create_headers_for_new_span = create_http_headers_for_new_span # pragma: no cover
b6c0a85a3199499b607ebb9ecc057434a9ea2fe5
mizani/__init__.py
mizani/__init__.py
from importlib.metadata import version, PackageNotFoundError try: __version__ = version('plotnine') except PackageNotFoundError: # package is not installed pass
from importlib.metadata import version, PackageNotFoundError try: __version__ = version('mizani') except PackageNotFoundError: # package is not installed pass
Fix version number to check for mizani
Fix version number to check for mizani and not plotnine. Copypaste error!
Python
bsd-3-clause
has2k1/mizani,has2k1/mizani
from importlib.metadata import version, PackageNotFoundError try: __version__ = version('plotnine') except PackageNotFoundError: # package is not installed pass Fix version number to check for mizani and not plotnine. Copypaste error!
from importlib.metadata import version, PackageNotFoundError try: __version__ = version('mizani') except PackageNotFoundError: # package is not installed pass
<commit_before>from importlib.metadata import version, PackageNotFoundError try: __version__ = version('plotnine') except PackageNotFoundError: # package is not installed pass <commit_msg>Fix version number to check for mizani and not plotnine. Copypaste error!<commit_after>
from importlib.metadata import version, PackageNotFoundError try: __version__ = version('mizani') except PackageNotFoundError: # package is not installed pass
from importlib.metadata import version, PackageNotFoundError try: __version__ = version('plotnine') except PackageNotFoundError: # package is not installed pass Fix version number to check for mizani and not plotnine. Copypaste error!from importlib.metadata import version, PackageNotFoundError try: __version__ = version('mizani') except PackageNotFoundError: # package is not installed pass
<commit_before>from importlib.metadata import version, PackageNotFoundError try: __version__ = version('plotnine') except PackageNotFoundError: # package is not installed pass <commit_msg>Fix version number to check for mizani and not plotnine. Copypaste error!<commit_after>from importlib.metadata import version, PackageNotFoundError try: __version__ = version('mizani') except PackageNotFoundError: # package is not installed pass
53bed4837805fa304153622689abb7c4c581ec73
registration/__init__.py
registration/__init__.py
from django.utils.version import get_version as django_get_version VERSION = (0, 9, 0, 'beta', 1) def get_version(): return django_get_version(VERSION) # pragma: no cover
VERSION = (0, 9, 0, 'beta', 1) def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.
Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.
Python
bsd-3-clause
Geffersonvivan/django-registration,ei-grad/django-registration,nikolas/django-registration,kinsights/django-registration,alawnchen/django-registration,Geffersonvivan/django-registration,wda-hb/test,arpitremarkable/django-registration,yorkedork/django-registration,maitho/django-registration,percipient/django-registration,wda-hb/test,matejkloska/django-registration,matejkloska/django-registration,tanjunyen/django-registration,rulz/django-registration,ei-grad/django-registration,percipient/django-registration,wy123123/django-registration,torchingloom/django-registration,pando85/django-registration,pando85/django-registration,maitho/django-registration,rulz/django-registration,kazitanvirahsan/django-registration,timgraham/django-registration,kinsights/django-registration,furious-luke/django-registration,imgmix/django-registration,memnonila/django-registration,timgraham/django-registration,allo-/django-registration,nikolas/django-registration,alawnchen/django-registration,sergafts/django-registration,wy123123/django-registration,torchingloom/django-registration,kazitanvirahsan/django-registration,imgmix/django-registration,allo-/django-registration,sergafts/django-registration,PetrDlouhy/django-registration,memnonila/django-registration,mick-t/django-registration,stillmatic/django-registration,PSU-OIT-ARC/django-registration,PSU-OIT-ARC/django-registration,tanjunyen/django-registration,erinspace/django-registration,yorkedork/django-registration,PetrDlouhy/django-registration,furious-luke/django-registration,mick-t/django-registration,arpitremarkable/django-registration,stillmatic/django-registration,erinspace/django-registration
from django.utils.version import get_version as django_get_version VERSION = (0, 9, 0, 'beta', 1) def get_version(): return django_get_version(VERSION) # pragma: no cover Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.
VERSION = (0, 9, 0, 'beta', 1) def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
<commit_before>from django.utils.version import get_version as django_get_version VERSION = (0, 9, 0, 'beta', 1) def get_version(): return django_get_version(VERSION) # pragma: no cover <commit_msg>Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.<commit_after>
VERSION = (0, 9, 0, 'beta', 1) def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
from django.utils.version import get_version as django_get_version VERSION = (0, 9, 0, 'beta', 1) def get_version(): return django_get_version(VERSION) # pragma: no cover Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.VERSION = (0, 9, 0, 'beta', 1) def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
<commit_before>from django.utils.version import get_version as django_get_version VERSION = (0, 9, 0, 'beta', 1) def get_version(): return django_get_version(VERSION) # pragma: no cover <commit_msg>Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.<commit_after>VERSION = (0, 9, 0, 'beta', 1) def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
a1903c3e7d8bd8f7421a9665039ee66e387d19d4
django_bleach/templatetags/bleach_tags.py
django_bleach/templatetags/bleach_tags.py
import bleach from django import template from django.conf import settings from django.utils.safestring import mark_safe register = template.Library() bleach_args = {} possible_settings = { 'BLEACH_ALLOWED_TAGS': 'tags', 'BLEACH_ALLOWED_ATTRIBUTES': 'attributes', 'BLEACH_ALLOWED_STYLES': 'styles', 'BLEACH_STRIP_TAGS': 'strip', 'BLEACH_STRIP_COMMENTS': 'strip_comments', } for setting, kwarg in possible_settings.iteritems(): if hasattr(settings, setting): bleach_args[kwarg] = getattr(settings, setting) def bleach_value(value): bleached_value = bleach.clean(value, **bleach_args) return mark_safe(bleached_value) register.filter('bleach', bleach_value) @register.filter def bleach_linkify(value): return bleach.linkify(value, parse_email=True)
import bleach from django import template from django.conf import settings from django.utils.safestring import mark_safe register = template.Library() bleach_args = {} possible_settings = { 'BLEACH_ALLOWED_TAGS': 'tags', 'BLEACH_ALLOWED_ATTRIBUTES': 'attributes', 'BLEACH_ALLOWED_STYLES': 'styles', 'BLEACH_STRIP_TAGS': 'strip', 'BLEACH_STRIP_COMMENTS': 'strip_comments', } for setting, kwarg in possible_settings.items(): if hasattr(settings, setting): bleach_args[kwarg] = getattr(settings, setting) def bleach_value(value): bleached_value = bleach.clean(value, **bleach_args) return mark_safe(bleached_value) register.filter('bleach', bleach_value) @register.filter def bleach_linkify(value): return bleach.linkify(value, parse_email=True)
Use items() instead of iteritems() for Python 2 and 3 compatibility
Use items() instead of iteritems() for Python 2 and 3 compatibility
Python
bsd-2-clause
python-force/django-bleach
import bleach from django import template from django.conf import settings from django.utils.safestring import mark_safe register = template.Library() bleach_args = {} possible_settings = { 'BLEACH_ALLOWED_TAGS': 'tags', 'BLEACH_ALLOWED_ATTRIBUTES': 'attributes', 'BLEACH_ALLOWED_STYLES': 'styles', 'BLEACH_STRIP_TAGS': 'strip', 'BLEACH_STRIP_COMMENTS': 'strip_comments', } for setting, kwarg in possible_settings.iteritems(): if hasattr(settings, setting): bleach_args[kwarg] = getattr(settings, setting) def bleach_value(value): bleached_value = bleach.clean(value, **bleach_args) return mark_safe(bleached_value) register.filter('bleach', bleach_value) @register.filter def bleach_linkify(value): return bleach.linkify(value, parse_email=True)Use items() instead of iteritems() for Python 2 and 3 compatibility
import bleach from django import template from django.conf import settings from django.utils.safestring import mark_safe register = template.Library() bleach_args = {} possible_settings = { 'BLEACH_ALLOWED_TAGS': 'tags', 'BLEACH_ALLOWED_ATTRIBUTES': 'attributes', 'BLEACH_ALLOWED_STYLES': 'styles', 'BLEACH_STRIP_TAGS': 'strip', 'BLEACH_STRIP_COMMENTS': 'strip_comments', } for setting, kwarg in possible_settings.items(): if hasattr(settings, setting): bleach_args[kwarg] = getattr(settings, setting) def bleach_value(value): bleached_value = bleach.clean(value, **bleach_args) return mark_safe(bleached_value) register.filter('bleach', bleach_value) @register.filter def bleach_linkify(value): return bleach.linkify(value, parse_email=True)
<commit_before>import bleach from django import template from django.conf import settings from django.utils.safestring import mark_safe register = template.Library() bleach_args = {} possible_settings = { 'BLEACH_ALLOWED_TAGS': 'tags', 'BLEACH_ALLOWED_ATTRIBUTES': 'attributes', 'BLEACH_ALLOWED_STYLES': 'styles', 'BLEACH_STRIP_TAGS': 'strip', 'BLEACH_STRIP_COMMENTS': 'strip_comments', } for setting, kwarg in possible_settings.iteritems(): if hasattr(settings, setting): bleach_args[kwarg] = getattr(settings, setting) def bleach_value(value): bleached_value = bleach.clean(value, **bleach_args) return mark_safe(bleached_value) register.filter('bleach', bleach_value) @register.filter def bleach_linkify(value): return bleach.linkify(value, parse_email=True)<commit_msg>Use items() instead of iteritems() for Python 2 and 3 compatibility<commit_after>
import bleach from django import template from django.conf import settings from django.utils.safestring import mark_safe register = template.Library() bleach_args = {} possible_settings = { 'BLEACH_ALLOWED_TAGS': 'tags', 'BLEACH_ALLOWED_ATTRIBUTES': 'attributes', 'BLEACH_ALLOWED_STYLES': 'styles', 'BLEACH_STRIP_TAGS': 'strip', 'BLEACH_STRIP_COMMENTS': 'strip_comments', } for setting, kwarg in possible_settings.items(): if hasattr(settings, setting): bleach_args[kwarg] = getattr(settings, setting) def bleach_value(value): bleached_value = bleach.clean(value, **bleach_args) return mark_safe(bleached_value) register.filter('bleach', bleach_value) @register.filter def bleach_linkify(value): return bleach.linkify(value, parse_email=True)
import bleach from django import template from django.conf import settings from django.utils.safestring import mark_safe register = template.Library() bleach_args = {} possible_settings = { 'BLEACH_ALLOWED_TAGS': 'tags', 'BLEACH_ALLOWED_ATTRIBUTES': 'attributes', 'BLEACH_ALLOWED_STYLES': 'styles', 'BLEACH_STRIP_TAGS': 'strip', 'BLEACH_STRIP_COMMENTS': 'strip_comments', } for setting, kwarg in possible_settings.iteritems(): if hasattr(settings, setting): bleach_args[kwarg] = getattr(settings, setting) def bleach_value(value): bleached_value = bleach.clean(value, **bleach_args) return mark_safe(bleached_value) register.filter('bleach', bleach_value) @register.filter def bleach_linkify(value): return bleach.linkify(value, parse_email=True)Use items() instead of iteritems() for Python 2 and 3 compatibilityimport bleach from django import template from django.conf import settings from django.utils.safestring import mark_safe register = template.Library() bleach_args = {} possible_settings = { 'BLEACH_ALLOWED_TAGS': 'tags', 'BLEACH_ALLOWED_ATTRIBUTES': 'attributes', 'BLEACH_ALLOWED_STYLES': 'styles', 'BLEACH_STRIP_TAGS': 'strip', 'BLEACH_STRIP_COMMENTS': 'strip_comments', } for setting, kwarg in possible_settings.items(): if hasattr(settings, setting): bleach_args[kwarg] = getattr(settings, setting) def bleach_value(value): bleached_value = bleach.clean(value, **bleach_args) return mark_safe(bleached_value) register.filter('bleach', bleach_value) @register.filter def bleach_linkify(value): return bleach.linkify(value, parse_email=True)
<commit_before>import bleach from django import template from django.conf import settings from django.utils.safestring import mark_safe register = template.Library() bleach_args = {} possible_settings = { 'BLEACH_ALLOWED_TAGS': 'tags', 'BLEACH_ALLOWED_ATTRIBUTES': 'attributes', 'BLEACH_ALLOWED_STYLES': 'styles', 'BLEACH_STRIP_TAGS': 'strip', 'BLEACH_STRIP_COMMENTS': 'strip_comments', } for setting, kwarg in possible_settings.iteritems(): if hasattr(settings, setting): bleach_args[kwarg] = getattr(settings, setting) def bleach_value(value): bleached_value = bleach.clean(value, **bleach_args) return mark_safe(bleached_value) register.filter('bleach', bleach_value) @register.filter def bleach_linkify(value): return bleach.linkify(value, parse_email=True)<commit_msg>Use items() instead of iteritems() for Python 2 and 3 compatibility<commit_after>import bleach from django import template from django.conf import settings from django.utils.safestring import mark_safe register = template.Library() bleach_args = {} possible_settings = { 'BLEACH_ALLOWED_TAGS': 'tags', 'BLEACH_ALLOWED_ATTRIBUTES': 'attributes', 'BLEACH_ALLOWED_STYLES': 'styles', 'BLEACH_STRIP_TAGS': 'strip', 'BLEACH_STRIP_COMMENTS': 'strip_comments', } for setting, kwarg in possible_settings.items(): if hasattr(settings, setting): bleach_args[kwarg] = getattr(settings, setting) def bleach_value(value): bleached_value = bleach.clean(value, **bleach_args) return mark_safe(bleached_value) register.filter('bleach', bleach_value) @register.filter def bleach_linkify(value): return bleach.linkify(value, parse_email=True)
b9e61db86efd788f8ee321a3dbfcf09293d92337
speedinfo/conf.py
speedinfo/conf.py
# coding: utf-8 from django.conf import settings DEFAULTS = { "SPEEDINFO_TESTS": False, "SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "is_cached", "SPEEDINFO_STORAGE": None, "SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default", "SPEEDINFO_PROFILING_CONDITIONS": [], "SPEEDINFO_EXCLUDE_URLS": [], "SPEEDINFO_ADMIN_COLUMNS": ( ("View name", "{}", "view_name"), ("HTTP method", "{}", "method"), ("Anonymous calls", "{:.1f}%", "anon_calls_ratio"), ("Cache hits", "{:.1f}%", "cache_hits_ratio"), ("SQL queries per call", "{}", "sql_count_per_call"), ("SQL time", "{:.1f}%", "sql_time_ratio"), ("Total calls", "{}", "total_calls"), ("Time per call", "{:.8f}", "time_per_call"), ("Total time", "{:.4f}", "total_time"), ), } class SpeedinfoSettings: def __init__(self, defaults=None): self.defaults = defaults or DEFAULTS def __getattr__(self, name): if name not in self.defaults: raise AttributeError("Invalid setting: '{}'".format(name)) return getattr(settings, name, self.defaults.get(name)) speedinfo_settings = SpeedinfoSettings()
# coding: utf-8 from django.conf import settings DEFAULTS = { "SPEEDINFO_TESTS": False, "SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "_is_cached", "SPEEDINFO_STORAGE": None, "SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default", "SPEEDINFO_PROFILING_CONDITIONS": [], "SPEEDINFO_EXCLUDE_URLS": [], "SPEEDINFO_ADMIN_COLUMNS": ( ("View name", "{}", "view_name"), ("HTTP method", "{}", "method"), ("Anonymous calls", "{:.1f}%", "anon_calls_ratio"), ("Cache hits", "{:.1f}%", "cache_hits_ratio"), ("SQL queries per call", "{}", "sql_count_per_call"), ("SQL time", "{:.1f}%", "sql_time_ratio"), ("Total calls", "{}", "total_calls"), ("Time per call", "{:.8f}", "time_per_call"), ("Total time", "{:.4f}", "total_time"), ), } class SpeedinfoSettings: def __init__(self, defaults=None): self.defaults = defaults or DEFAULTS def __getattr__(self, name): if name not in self.defaults: raise AttributeError("Invalid setting: '{}'".format(name)) return getattr(settings, name, self.defaults.get(name)) speedinfo_settings = SpeedinfoSettings()
Change SPEEDINFO_CACHED_RESPONSE_ATTR_NAME default value to `_is_cached`
Change SPEEDINFO_CACHED_RESPONSE_ATTR_NAME default value to `_is_cached`
Python
mit
catcombo/django-speedinfo,catcombo/django-speedinfo,catcombo/django-speedinfo
# coding: utf-8 from django.conf import settings DEFAULTS = { "SPEEDINFO_TESTS": False, "SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "is_cached", "SPEEDINFO_STORAGE": None, "SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default", "SPEEDINFO_PROFILING_CONDITIONS": [], "SPEEDINFO_EXCLUDE_URLS": [], "SPEEDINFO_ADMIN_COLUMNS": ( ("View name", "{}", "view_name"), ("HTTP method", "{}", "method"), ("Anonymous calls", "{:.1f}%", "anon_calls_ratio"), ("Cache hits", "{:.1f}%", "cache_hits_ratio"), ("SQL queries per call", "{}", "sql_count_per_call"), ("SQL time", "{:.1f}%", "sql_time_ratio"), ("Total calls", "{}", "total_calls"), ("Time per call", "{:.8f}", "time_per_call"), ("Total time", "{:.4f}", "total_time"), ), } class SpeedinfoSettings: def __init__(self, defaults=None): self.defaults = defaults or DEFAULTS def __getattr__(self, name): if name not in self.defaults: raise AttributeError("Invalid setting: '{}'".format(name)) return getattr(settings, name, self.defaults.get(name)) speedinfo_settings = SpeedinfoSettings() Change SPEEDINFO_CACHED_RESPONSE_ATTR_NAME default value to `_is_cached`
# coding: utf-8 from django.conf import settings DEFAULTS = { "SPEEDINFO_TESTS": False, "SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "_is_cached", "SPEEDINFO_STORAGE": None, "SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default", "SPEEDINFO_PROFILING_CONDITIONS": [], "SPEEDINFO_EXCLUDE_URLS": [], "SPEEDINFO_ADMIN_COLUMNS": ( ("View name", "{}", "view_name"), ("HTTP method", "{}", "method"), ("Anonymous calls", "{:.1f}%", "anon_calls_ratio"), ("Cache hits", "{:.1f}%", "cache_hits_ratio"), ("SQL queries per call", "{}", "sql_count_per_call"), ("SQL time", "{:.1f}%", "sql_time_ratio"), ("Total calls", "{}", "total_calls"), ("Time per call", "{:.8f}", "time_per_call"), ("Total time", "{:.4f}", "total_time"), ), } class SpeedinfoSettings: def __init__(self, defaults=None): self.defaults = defaults or DEFAULTS def __getattr__(self, name): if name not in self.defaults: raise AttributeError("Invalid setting: '{}'".format(name)) return getattr(settings, name, self.defaults.get(name)) speedinfo_settings = SpeedinfoSettings()
<commit_before># coding: utf-8 from django.conf import settings DEFAULTS = { "SPEEDINFO_TESTS": False, "SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "is_cached", "SPEEDINFO_STORAGE": None, "SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default", "SPEEDINFO_PROFILING_CONDITIONS": [], "SPEEDINFO_EXCLUDE_URLS": [], "SPEEDINFO_ADMIN_COLUMNS": ( ("View name", "{}", "view_name"), ("HTTP method", "{}", "method"), ("Anonymous calls", "{:.1f}%", "anon_calls_ratio"), ("Cache hits", "{:.1f}%", "cache_hits_ratio"), ("SQL queries per call", "{}", "sql_count_per_call"), ("SQL time", "{:.1f}%", "sql_time_ratio"), ("Total calls", "{}", "total_calls"), ("Time per call", "{:.8f}", "time_per_call"), ("Total time", "{:.4f}", "total_time"), ), } class SpeedinfoSettings: def __init__(self, defaults=None): self.defaults = defaults or DEFAULTS def __getattr__(self, name): if name not in self.defaults: raise AttributeError("Invalid setting: '{}'".format(name)) return getattr(settings, name, self.defaults.get(name)) speedinfo_settings = SpeedinfoSettings() <commit_msg>Change SPEEDINFO_CACHED_RESPONSE_ATTR_NAME default value to `_is_cached`<commit_after>
# coding: utf-8 from django.conf import settings DEFAULTS = { "SPEEDINFO_TESTS": False, "SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "_is_cached", "SPEEDINFO_STORAGE": None, "SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default", "SPEEDINFO_PROFILING_CONDITIONS": [], "SPEEDINFO_EXCLUDE_URLS": [], "SPEEDINFO_ADMIN_COLUMNS": ( ("View name", "{}", "view_name"), ("HTTP method", "{}", "method"), ("Anonymous calls", "{:.1f}%", "anon_calls_ratio"), ("Cache hits", "{:.1f}%", "cache_hits_ratio"), ("SQL queries per call", "{}", "sql_count_per_call"), ("SQL time", "{:.1f}%", "sql_time_ratio"), ("Total calls", "{}", "total_calls"), ("Time per call", "{:.8f}", "time_per_call"), ("Total time", "{:.4f}", "total_time"), ), } class SpeedinfoSettings: def __init__(self, defaults=None): self.defaults = defaults or DEFAULTS def __getattr__(self, name): if name not in self.defaults: raise AttributeError("Invalid setting: '{}'".format(name)) return getattr(settings, name, self.defaults.get(name)) speedinfo_settings = SpeedinfoSettings()
# coding: utf-8 from django.conf import settings DEFAULTS = { "SPEEDINFO_TESTS": False, "SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "is_cached", "SPEEDINFO_STORAGE": None, "SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default", "SPEEDINFO_PROFILING_CONDITIONS": [], "SPEEDINFO_EXCLUDE_URLS": [], "SPEEDINFO_ADMIN_COLUMNS": ( ("View name", "{}", "view_name"), ("HTTP method", "{}", "method"), ("Anonymous calls", "{:.1f}%", "anon_calls_ratio"), ("Cache hits", "{:.1f}%", "cache_hits_ratio"), ("SQL queries per call", "{}", "sql_count_per_call"), ("SQL time", "{:.1f}%", "sql_time_ratio"), ("Total calls", "{}", "total_calls"), ("Time per call", "{:.8f}", "time_per_call"), ("Total time", "{:.4f}", "total_time"), ), } class SpeedinfoSettings: def __init__(self, defaults=None): self.defaults = defaults or DEFAULTS def __getattr__(self, name): if name not in self.defaults: raise AttributeError("Invalid setting: '{}'".format(name)) return getattr(settings, name, self.defaults.get(name)) speedinfo_settings = SpeedinfoSettings() Change SPEEDINFO_CACHED_RESPONSE_ATTR_NAME default value to `_is_cached`# coding: utf-8 from django.conf import settings DEFAULTS = { "SPEEDINFO_TESTS": False, "SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "_is_cached", "SPEEDINFO_STORAGE": None, "SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default", "SPEEDINFO_PROFILING_CONDITIONS": [], "SPEEDINFO_EXCLUDE_URLS": [], "SPEEDINFO_ADMIN_COLUMNS": ( ("View name", "{}", "view_name"), ("HTTP method", "{}", "method"), ("Anonymous calls", "{:.1f}%", "anon_calls_ratio"), ("Cache hits", "{:.1f}%", "cache_hits_ratio"), ("SQL queries per call", "{}", "sql_count_per_call"), ("SQL time", "{:.1f}%", "sql_time_ratio"), ("Total calls", "{}", "total_calls"), ("Time per call", "{:.8f}", "time_per_call"), ("Total time", "{:.4f}", "total_time"), ), } class SpeedinfoSettings: def __init__(self, defaults=None): self.defaults = defaults or DEFAULTS def __getattr__(self, name): if name not in self.defaults: raise AttributeError("Invalid setting: '{}'".format(name)) return getattr(settings, name, self.defaults.get(name)) speedinfo_settings = SpeedinfoSettings()
<commit_before># coding: utf-8 from django.conf import settings DEFAULTS = { "SPEEDINFO_TESTS": False, "SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "is_cached", "SPEEDINFO_STORAGE": None, "SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default", "SPEEDINFO_PROFILING_CONDITIONS": [], "SPEEDINFO_EXCLUDE_URLS": [], "SPEEDINFO_ADMIN_COLUMNS": ( ("View name", "{}", "view_name"), ("HTTP method", "{}", "method"), ("Anonymous calls", "{:.1f}%", "anon_calls_ratio"), ("Cache hits", "{:.1f}%", "cache_hits_ratio"), ("SQL queries per call", "{}", "sql_count_per_call"), ("SQL time", "{:.1f}%", "sql_time_ratio"), ("Total calls", "{}", "total_calls"), ("Time per call", "{:.8f}", "time_per_call"), ("Total time", "{:.4f}", "total_time"), ), } class SpeedinfoSettings: def __init__(self, defaults=None): self.defaults = defaults or DEFAULTS def __getattr__(self, name): if name not in self.defaults: raise AttributeError("Invalid setting: '{}'".format(name)) return getattr(settings, name, self.defaults.get(name)) speedinfo_settings = SpeedinfoSettings() <commit_msg>Change SPEEDINFO_CACHED_RESPONSE_ATTR_NAME default value to `_is_cached`<commit_after># coding: utf-8 from django.conf import settings DEFAULTS = { "SPEEDINFO_TESTS": False, "SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "_is_cached", "SPEEDINFO_STORAGE": None, "SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default", "SPEEDINFO_PROFILING_CONDITIONS": [], "SPEEDINFO_EXCLUDE_URLS": [], "SPEEDINFO_ADMIN_COLUMNS": ( ("View name", "{}", "view_name"), ("HTTP method", "{}", "method"), ("Anonymous calls", "{:.1f}%", "anon_calls_ratio"), ("Cache hits", "{:.1f}%", "cache_hits_ratio"), ("SQL queries per call", "{}", "sql_count_per_call"), ("SQL time", "{:.1f}%", "sql_time_ratio"), ("Total calls", "{}", "total_calls"), ("Time per call", "{:.8f}", "time_per_call"), ("Total time", "{:.4f}", "total_time"), ), } class SpeedinfoSettings: def __init__(self, defaults=None): self.defaults = defaults or DEFAULTS def __getattr__(self, name): if name not in self.defaults: raise AttributeError("Invalid setting: '{}'".format(name)) return getattr(settings, name, self.defaults.get(name)) speedinfo_settings = SpeedinfoSettings()
ce3fb7643e5c75a1f5fdae77a6667df407cb55b1
interface.py
interface.py
# -*- coding: utf-8 -*- """ Created on Thu Jul 21 13:53:47 2016 @author: mela """
# -*- coding: utf-8 -*- """ Created on Thu Jul 21 13:53:47 2016 @author: mela """ print(adfadsfad);
Test commit on new branch, change to username and email.
Test commit on new branch, change to username and email.
Python
mit
akmelkonian/city-in-purple
# -*- coding: utf-8 -*- """ Created on Thu Jul 21 13:53:47 2016 @author: mela """ Test commit on new branch, change to username and email.
# -*- coding: utf-8 -*- """ Created on Thu Jul 21 13:53:47 2016 @author: mela """ print(adfadsfad);
<commit_before># -*- coding: utf-8 -*- """ Created on Thu Jul 21 13:53:47 2016 @author: mela """ <commit_msg>Test commit on new branch, change to username and email.<commit_after>
# -*- coding: utf-8 -*- """ Created on Thu Jul 21 13:53:47 2016 @author: mela """ print(adfadsfad);
# -*- coding: utf-8 -*- """ Created on Thu Jul 21 13:53:47 2016 @author: mela """ Test commit on new branch, change to username and email.# -*- coding: utf-8 -*- """ Created on Thu Jul 21 13:53:47 2016 @author: mela """ print(adfadsfad);
<commit_before># -*- coding: utf-8 -*- """ Created on Thu Jul 21 13:53:47 2016 @author: mela """ <commit_msg>Test commit on new branch, change to username and email.<commit_after># -*- coding: utf-8 -*- """ Created on Thu Jul 21 13:53:47 2016 @author: mela """ print(adfadsfad);
69fc2eccaa88189fd0de86d11206fa24d1508819
tools/np_suppressions.py
tools/np_suppressions.py
suppressions = [ [ ".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ ".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ ".*/multiarray/common\.", "PyCapsule_Check" ], ]
suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ r".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ r".*/multiarray/common\.", "PyCapsule_Check" ], ]
Add documentation on one assertion, convert RE's to raw strings.
Add documentation on one assertion, convert RE's to raw strings.
Python
bsd-3-clause
teoliphant/numpy-refactor,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,jasonmccampbell/numpy-refactor-sprint,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,jasonmccampbell/numpy-refactor-sprint,teoliphant/numpy-refactor,teoliphant/numpy-refactor
suppressions = [ [ ".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ ".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ ".*/multiarray/common\.", "PyCapsule_Check" ], ] Add documentation on one assertion, convert RE's to raw strings.
suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ r".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ r".*/multiarray/common\.", "PyCapsule_Check" ], ]
<commit_before>suppressions = [ [ ".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ ".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ ".*/multiarray/common\.", "PyCapsule_Check" ], ] <commit_msg>Add documentation on one assertion, convert RE's to raw strings.<commit_after>
suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ r".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ r".*/multiarray/common\.", "PyCapsule_Check" ], ]
suppressions = [ [ ".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ ".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ ".*/multiarray/common\.", "PyCapsule_Check" ], ] Add documentation on one assertion, convert RE's to raw strings.suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ r".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ r".*/multiarray/common\.", "PyCapsule_Check" ], ]
<commit_before>suppressions = [ [ ".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ ".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ ".*/multiarray/common\.", "PyCapsule_Check" ], ] <commit_msg>Add documentation on one assertion, convert RE's to raw strings.<commit_after>suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ r".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ r".*/multiarray/common\.", "PyCapsule_Check" ], ]
ab828ae56d79a280b5330144ace771badbe5eb3f
samples/shopping/main.py
samples/shopping/main.py
#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright 2010 Google Inc. All Rights Reserved. """Simple command-line example for The Google Shopping API. Command-line application that does a search for products. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from apiclient.discovery import build import pprint # Uncomment the next line to get very detailed logging # httplib2.debuglevel = 4 def main(): p = build("shopping", "v1", developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0") res = p.products().list( country='US', source='public', q='logitech revue' ).execute() pprint.pprint(res) if __name__ == '__main__': main()
#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright 2010 Google Inc. All Rights Reserved. """Simple command-line example for The Google Search API for Shopping. Command-line application that does a search for products. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from apiclient.discovery import build import pprint # Uncomment the next line to get very detailed logging # httplib2.debuglevel = 4 def main(): p = build("shopping", "v1", developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0") res = p.products().list( country='US', source='public', q='logitech revue' ).execute() pprint.pprint(res) if __name__ == '__main__': main()
Correct name for the shopping search api
Correct name for the shopping search api
Python
apache-2.0
google/oauth2client,google/oauth2client,googleapis/google-api-python-client,jonparrott/oauth2client,googleapis/oauth2client,googleapis/google-api-python-client,jonparrott/oauth2client,clancychilds/oauth2client,googleapis/oauth2client,clancychilds/oauth2client
#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright 2010 Google Inc. All Rights Reserved. """Simple command-line example for The Google Shopping API. Command-line application that does a search for products. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from apiclient.discovery import build import pprint # Uncomment the next line to get very detailed logging # httplib2.debuglevel = 4 def main(): p = build("shopping", "v1", developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0") res = p.products().list( country='US', source='public', q='logitech revue' ).execute() pprint.pprint(res) if __name__ == '__main__': main() Correct name for the shopping search api
#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright 2010 Google Inc. All Rights Reserved. """Simple command-line example for The Google Search API for Shopping. Command-line application that does a search for products. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from apiclient.discovery import build import pprint # Uncomment the next line to get very detailed logging # httplib2.debuglevel = 4 def main(): p = build("shopping", "v1", developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0") res = p.products().list( country='US', source='public', q='logitech revue' ).execute() pprint.pprint(res) if __name__ == '__main__': main()
<commit_before>#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright 2010 Google Inc. All Rights Reserved. """Simple command-line example for The Google Shopping API. Command-line application that does a search for products. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from apiclient.discovery import build import pprint # Uncomment the next line to get very detailed logging # httplib2.debuglevel = 4 def main(): p = build("shopping", "v1", developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0") res = p.products().list( country='US', source='public', q='logitech revue' ).execute() pprint.pprint(res) if __name__ == '__main__': main() <commit_msg>Correct name for the shopping search api<commit_after>
#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright 2010 Google Inc. All Rights Reserved. """Simple command-line example for The Google Search API for Shopping. Command-line application that does a search for products. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from apiclient.discovery import build import pprint # Uncomment the next line to get very detailed logging # httplib2.debuglevel = 4 def main(): p = build("shopping", "v1", developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0") res = p.products().list( country='US', source='public', q='logitech revue' ).execute() pprint.pprint(res) if __name__ == '__main__': main()
#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright 2010 Google Inc. All Rights Reserved. """Simple command-line example for The Google Shopping API. Command-line application that does a search for products. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from apiclient.discovery import build import pprint # Uncomment the next line to get very detailed logging # httplib2.debuglevel = 4 def main(): p = build("shopping", "v1", developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0") res = p.products().list( country='US', source='public', q='logitech revue' ).execute() pprint.pprint(res) if __name__ == '__main__': main() Correct name for the shopping search api#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright 2010 Google Inc. All Rights Reserved. """Simple command-line example for The Google Search API for Shopping. Command-line application that does a search for products. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from apiclient.discovery import build import pprint # Uncomment the next line to get very detailed logging # httplib2.debuglevel = 4 def main(): p = build("shopping", "v1", developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0") res = p.products().list( country='US', source='public', q='logitech revue' ).execute() pprint.pprint(res) if __name__ == '__main__': main()
<commit_before>#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright 2010 Google Inc. All Rights Reserved. """Simple command-line example for The Google Shopping API. Command-line application that does a search for products. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from apiclient.discovery import build import pprint # Uncomment the next line to get very detailed logging # httplib2.debuglevel = 4 def main(): p = build("shopping", "v1", developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0") res = p.products().list( country='US', source='public', q='logitech revue' ).execute() pprint.pprint(res) if __name__ == '__main__': main() <commit_msg>Correct name for the shopping search api<commit_after>#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright 2010 Google Inc. All Rights Reserved. """Simple command-line example for The Google Search API for Shopping. Command-line application that does a search for products. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from apiclient.discovery import build import pprint # Uncomment the next line to get very detailed logging # httplib2.debuglevel = 4 def main(): p = build("shopping", "v1", developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0") res = p.products().list( country='US', source='public', q='logitech revue' ).execute() pprint.pprint(res) if __name__ == '__main__': main()
e3312c773e9e3ac9b939bc3e0ca6a872dae5cdef
pre_commit_hooks/trailing_whitespace_fixer.py
pre_commit_hooks/trailing_whitespace_fixer.py
from __future__ import print_function import argparse import sys from plumbum import local from pre_commit_hooks.util import entry @entry def fix_trailing_whitespace(argv): parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*', help='Filenames to fix') args = parser.parse_args(argv) bad_whitespace_files = local['grep'][ ('-l', '[[:space:]]$') + tuple(args.filenames) ](retcode=None).strip().splitlines() if bad_whitespace_files: for bad_whitespace_file in bad_whitespace_files: print('Fixing {0}'.format(bad_whitespace_file)) local['sed']['-i', '-e', 's/[[:space:]]*$//', bad_whitespace_file]() return 1 else: return 0 if __name__ == '__main__': sys.exit(fix_trailing_whitespace())
from __future__ import print_function import argparse import fileinput import sys from plumbum import local from pre_commit_hooks.util import entry def _fix_file(filename): for line in fileinput.input([filename], inplace=True): print(line.rstrip()) @entry def fix_trailing_whitespace(argv): parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*', help='Filenames to fix') args = parser.parse_args(argv) bad_whitespace_files = local['grep'][ ('-l', '[[:space:]]$') + tuple(args.filenames) ](retcode=None).strip().splitlines() if bad_whitespace_files: for bad_whitespace_file in bad_whitespace_files: print('Fixing {0}'.format(bad_whitespace_file)) _fix_file(bad_whitespace_file) return 1 else: return 0 if __name__ == '__main__': sys.exit(fix_trailing_whitespace())
Use fileinput instead of sed.
Use fileinput instead of sed.
Python
mit
Coverfox/pre-commit-hooks,Harwood/pre-commit-hooks,bgschiller/pre-commit-hooks,pre-commit/pre-commit-hooks,jordant/pre-commit-hooks,jordant/pre-commit-hooks,chriskuehl/pre-commit-hooks,dupuy/pre-commit-hooks,arahayrabedian/pre-commit-hooks
from __future__ import print_function import argparse import sys from plumbum import local from pre_commit_hooks.util import entry @entry def fix_trailing_whitespace(argv): parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*', help='Filenames to fix') args = parser.parse_args(argv) bad_whitespace_files = local['grep'][ ('-l', '[[:space:]]$') + tuple(args.filenames) ](retcode=None).strip().splitlines() if bad_whitespace_files: for bad_whitespace_file in bad_whitespace_files: print('Fixing {0}'.format(bad_whitespace_file)) local['sed']['-i', '-e', 's/[[:space:]]*$//', bad_whitespace_file]() return 1 else: return 0 if __name__ == '__main__': sys.exit(fix_trailing_whitespace()) Use fileinput instead of sed.
from __future__ import print_function import argparse import fileinput import sys from plumbum import local from pre_commit_hooks.util import entry def _fix_file(filename): for line in fileinput.input([filename], inplace=True): print(line.rstrip()) @entry def fix_trailing_whitespace(argv): parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*', help='Filenames to fix') args = parser.parse_args(argv) bad_whitespace_files = local['grep'][ ('-l', '[[:space:]]$') + tuple(args.filenames) ](retcode=None).strip().splitlines() if bad_whitespace_files: for bad_whitespace_file in bad_whitespace_files: print('Fixing {0}'.format(bad_whitespace_file)) _fix_file(bad_whitespace_file) return 1 else: return 0 if __name__ == '__main__': sys.exit(fix_trailing_whitespace())
<commit_before>from __future__ import print_function import argparse import sys from plumbum import local from pre_commit_hooks.util import entry @entry def fix_trailing_whitespace(argv): parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*', help='Filenames to fix') args = parser.parse_args(argv) bad_whitespace_files = local['grep'][ ('-l', '[[:space:]]$') + tuple(args.filenames) ](retcode=None).strip().splitlines() if bad_whitespace_files: for bad_whitespace_file in bad_whitespace_files: print('Fixing {0}'.format(bad_whitespace_file)) local['sed']['-i', '-e', 's/[[:space:]]*$//', bad_whitespace_file]() return 1 else: return 0 if __name__ == '__main__': sys.exit(fix_trailing_whitespace()) <commit_msg>Use fileinput instead of sed.<commit_after>
from __future__ import print_function import argparse import fileinput import sys from plumbum import local from pre_commit_hooks.util import entry def _fix_file(filename): for line in fileinput.input([filename], inplace=True): print(line.rstrip()) @entry def fix_trailing_whitespace(argv): parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*', help='Filenames to fix') args = parser.parse_args(argv) bad_whitespace_files = local['grep'][ ('-l', '[[:space:]]$') + tuple(args.filenames) ](retcode=None).strip().splitlines() if bad_whitespace_files: for bad_whitespace_file in bad_whitespace_files: print('Fixing {0}'.format(bad_whitespace_file)) _fix_file(bad_whitespace_file) return 1 else: return 0 if __name__ == '__main__': sys.exit(fix_trailing_whitespace())
from __future__ import print_function import argparse import sys from plumbum import local from pre_commit_hooks.util import entry @entry def fix_trailing_whitespace(argv): parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*', help='Filenames to fix') args = parser.parse_args(argv) bad_whitespace_files = local['grep'][ ('-l', '[[:space:]]$') + tuple(args.filenames) ](retcode=None).strip().splitlines() if bad_whitespace_files: for bad_whitespace_file in bad_whitespace_files: print('Fixing {0}'.format(bad_whitespace_file)) local['sed']['-i', '-e', 's/[[:space:]]*$//', bad_whitespace_file]() return 1 else: return 0 if __name__ == '__main__': sys.exit(fix_trailing_whitespace()) Use fileinput instead of sed.from __future__ import print_function import argparse import fileinput import sys from plumbum import local from pre_commit_hooks.util import entry def _fix_file(filename): for line in fileinput.input([filename], inplace=True): print(line.rstrip()) @entry def fix_trailing_whitespace(argv): parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*', help='Filenames to fix') args = parser.parse_args(argv) bad_whitespace_files = local['grep'][ ('-l', '[[:space:]]$') + tuple(args.filenames) ](retcode=None).strip().splitlines() if bad_whitespace_files: for bad_whitespace_file in bad_whitespace_files: print('Fixing {0}'.format(bad_whitespace_file)) _fix_file(bad_whitespace_file) return 1 else: return 0 if __name__ == '__main__': sys.exit(fix_trailing_whitespace())
<commit_before>from __future__ import print_function import argparse import sys from plumbum import local from pre_commit_hooks.util import entry @entry def fix_trailing_whitespace(argv): parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*', help='Filenames to fix') args = parser.parse_args(argv) bad_whitespace_files = local['grep'][ ('-l', '[[:space:]]$') + tuple(args.filenames) ](retcode=None).strip().splitlines() if bad_whitespace_files: for bad_whitespace_file in bad_whitespace_files: print('Fixing {0}'.format(bad_whitespace_file)) local['sed']['-i', '-e', 's/[[:space:]]*$//', bad_whitespace_file]() return 1 else: return 0 if __name__ == '__main__': sys.exit(fix_trailing_whitespace()) <commit_msg>Use fileinput instead of sed.<commit_after>from __future__ import print_function import argparse import fileinput import sys from plumbum import local from pre_commit_hooks.util import entry def _fix_file(filename): for line in fileinput.input([filename], inplace=True): print(line.rstrip()) @entry def fix_trailing_whitespace(argv): parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*', help='Filenames to fix') args = parser.parse_args(argv) bad_whitespace_files = local['grep'][ ('-l', '[[:space:]]$') + tuple(args.filenames) ](retcode=None).strip().splitlines() if bad_whitespace_files: for bad_whitespace_file in bad_whitespace_files: print('Fixing {0}'.format(bad_whitespace_file)) _fix_file(bad_whitespace_file) return 1 else: return 0 if __name__ == '__main__': sys.exit(fix_trailing_whitespace())
705af291a4e7ddbb366671757ca647bcd56b8e24
twitter_api/twitterApi.py
twitter_api/twitterApi.py
#!/usr/bin/env python import twitter class Twitter: def __init__(self): consumer_key = "WXfZoJi7i8TFmrGOK5Y7dVHon" consumer_secret = "EE46ezCkgKwy8GaKOFFCuMMoZbwDprnEXjhVMn7vI7cYaTbdcA" access_key = "867082422885785600-AJ0LdE8vc8uMs21VDv2jrkwkQg9PClG" access_secret = "qor8vV5kGqQ7mJDeW83uKUk2E8MUGqp5biTTswoN4YEt6" encoding = None self.api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token_key=access_key, access_token_secret=access_secret, input_encoding=encoding) def postTweet(self,message): try: status = self.api.PostUpdate(message) except: #TODO clean message and add more exception print 'twitter fail because message too long or encoding problem'
#!/usr/bin/env python import twitter import json class Twitter: def __init__(self): with open('/etc/twitter.json') as data_file: data = json.load(data_file) encoding = None self.api = twitter.Api(consumer_key=data["consumer_key"], consumer_secret=data["consumer_secret"], access_token_key=data["access_key"], access_token_secret=data["access_secret"], input_encoding=encoding) def postTweet(self,message): try: status = self.api.PostUpdate(message) except: #TODO clean message and add more exception print 'twitter fail because message too long or encoding problem'
Use setting file on /etc
Use setting file on /etc
Python
mit
phil-r/chaos,eukaryote31/chaos,phil-r/chaos,chaosbot/Chaos,botchaos/Chaos,mark-i-m/Chaos,mpnordland/chaos,mark-i-m/Chaos,hongaar/chaos,phil-r/chaos,mpnordland/chaos,rudehn/chaos,rudehn/chaos,botchaos/Chaos,Chaosthebot/Chaos,eukaryote31/chaos,g19fanatic/chaos,botchaos/Chaos,g19fanatic/chaos,hongaar/chaos,mpnordland/chaos,chaosbot/Chaos,eamanu/Chaos,eamanu/Chaos,mark-i-m/Chaos,amoffat/Chaos,amoffat/Chaos,eukaryote31/chaos,hongaar/chaos,mark-i-m/Chaos,chaosbot/Chaos,mpnordland/chaos,eamanu/Chaos,eamanu/Chaos,rudehn/chaos,Chaosthebot/Chaos,mark-i-m/Chaos,Chaosthebot/Chaos,Chaosthebot/Chaos,botchaos/Chaos,rudehn/chaos,chaosbot/Chaos,hongaar/chaos,g19fanatic/chaos,amoffat/Chaos,eukaryote31/chaos,eamanu/Chaos,rudehn/chaos,mpnordland/chaos,phil-r/chaos,eukaryote31/chaos,g19fanatic/chaos,g19fanatic/chaos,botchaos/Chaos,phil-r/chaos,amoffat/Chaos,hongaar/chaos,amoffat/Chaos,chaosbot/Chaos,Chaosthebot/Chaos
#!/usr/bin/env python import twitter class Twitter: def __init__(self): consumer_key = "WXfZoJi7i8TFmrGOK5Y7dVHon" consumer_secret = "EE46ezCkgKwy8GaKOFFCuMMoZbwDprnEXjhVMn7vI7cYaTbdcA" access_key = "867082422885785600-AJ0LdE8vc8uMs21VDv2jrkwkQg9PClG" access_secret = "qor8vV5kGqQ7mJDeW83uKUk2E8MUGqp5biTTswoN4YEt6" encoding = None self.api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token_key=access_key, access_token_secret=access_secret, input_encoding=encoding) def postTweet(self,message): try: status = self.api.PostUpdate(message) except: #TODO clean message and add more exception print 'twitter fail because message too long or encoding problem'Use setting file on /etc
#!/usr/bin/env python import twitter import json class Twitter: def __init__(self): with open('/etc/twitter.json') as data_file: data = json.load(data_file) encoding = None self.api = twitter.Api(consumer_key=data["consumer_key"], consumer_secret=data["consumer_secret"], access_token_key=data["access_key"], access_token_secret=data["access_secret"], input_encoding=encoding) def postTweet(self,message): try: status = self.api.PostUpdate(message) except: #TODO clean message and add more exception print 'twitter fail because message too long or encoding problem'
<commit_before>#!/usr/bin/env python import twitter class Twitter: def __init__(self): consumer_key = "WXfZoJi7i8TFmrGOK5Y7dVHon" consumer_secret = "EE46ezCkgKwy8GaKOFFCuMMoZbwDprnEXjhVMn7vI7cYaTbdcA" access_key = "867082422885785600-AJ0LdE8vc8uMs21VDv2jrkwkQg9PClG" access_secret = "qor8vV5kGqQ7mJDeW83uKUk2E8MUGqp5biTTswoN4YEt6" encoding = None self.api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token_key=access_key, access_token_secret=access_secret, input_encoding=encoding) def postTweet(self,message): try: status = self.api.PostUpdate(message) except: #TODO clean message and add more exception print 'twitter fail because message too long or encoding problem'<commit_msg>Use setting file on /etc<commit_after>
#!/usr/bin/env python import twitter import json class Twitter: def __init__(self): with open('/etc/twitter.json') as data_file: data = json.load(data_file) encoding = None self.api = twitter.Api(consumer_key=data["consumer_key"], consumer_secret=data["consumer_secret"], access_token_key=data["access_key"], access_token_secret=data["access_secret"], input_encoding=encoding) def postTweet(self,message): try: status = self.api.PostUpdate(message) except: #TODO clean message and add more exception print 'twitter fail because message too long or encoding problem'
#!/usr/bin/env python import twitter class Twitter: def __init__(self): consumer_key = "WXfZoJi7i8TFmrGOK5Y7dVHon" consumer_secret = "EE46ezCkgKwy8GaKOFFCuMMoZbwDprnEXjhVMn7vI7cYaTbdcA" access_key = "867082422885785600-AJ0LdE8vc8uMs21VDv2jrkwkQg9PClG" access_secret = "qor8vV5kGqQ7mJDeW83uKUk2E8MUGqp5biTTswoN4YEt6" encoding = None self.api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token_key=access_key, access_token_secret=access_secret, input_encoding=encoding) def postTweet(self,message): try: status = self.api.PostUpdate(message) except: #TODO clean message and add more exception print 'twitter fail because message too long or encoding problem'Use setting file on /etc#!/usr/bin/env python import twitter import json class Twitter: def __init__(self): with open('/etc/twitter.json') as data_file: data = json.load(data_file) encoding = None self.api = twitter.Api(consumer_key=data["consumer_key"], consumer_secret=data["consumer_secret"], access_token_key=data["access_key"], access_token_secret=data["access_secret"], input_encoding=encoding) def postTweet(self,message): try: status = self.api.PostUpdate(message) except: #TODO clean message and add more exception print 'twitter fail because message too long or encoding problem'
<commit_before>#!/usr/bin/env python import twitter class Twitter: def __init__(self): consumer_key = "WXfZoJi7i8TFmrGOK5Y7dVHon" consumer_secret = "EE46ezCkgKwy8GaKOFFCuMMoZbwDprnEXjhVMn7vI7cYaTbdcA" access_key = "867082422885785600-AJ0LdE8vc8uMs21VDv2jrkwkQg9PClG" access_secret = "qor8vV5kGqQ7mJDeW83uKUk2E8MUGqp5biTTswoN4YEt6" encoding = None self.api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token_key=access_key, access_token_secret=access_secret, input_encoding=encoding) def postTweet(self,message): try: status = self.api.PostUpdate(message) except: #TODO clean message and add more exception print 'twitter fail because message too long or encoding problem'<commit_msg>Use setting file on /etc<commit_after>#!/usr/bin/env python import twitter import json class Twitter: def __init__(self): with open('/etc/twitter.json') as data_file: data = json.load(data_file) encoding = None self.api = twitter.Api(consumer_key=data["consumer_key"], consumer_secret=data["consumer_secret"], access_token_key=data["access_key"], access_token_secret=data["access_secret"], input_encoding=encoding) def postTweet(self,message): try: status = self.api.PostUpdate(message) except: #TODO clean message and add more exception print 'twitter fail because message too long or encoding problem'
32951dda5a46487a485c949a07f457ae537f07f2
src/encoded/upgrade/bismark_quality_metric.py
src/encoded/upgrade/bismark_quality_metric.py
from contentbase import ( ROOT, upgrade_step, ) @upgrade_step('bismark_quality_metric', '1', '2') def bismark_quality_metric_1_2(value, system): # http://redmine.encodedcc.org/issues/3114 root = system['registry'][ROOT] step_run = root.get_by_uuid(value['step_run']) value['quality_metric_of'] = [str(uuid) for uuid in step_run.get_rev_links('output_files')] @upgrade_step('bismark_quality_metric', '2', '3') def bismark_quality_metric_2_3(value, system): # http://redmine.encodedcc.org/issues/3063 if 'aliases' in value: value['aliases'] = list(set(value['aliases'])) if 'quality_metric_of' in value: value['quality_metric_of'] = list(set(value['quality_metric_of']))
from contentbase import ( CONNECTION, upgrade_step, ) @upgrade_step('bismark_quality_metric', '1', '2') def bismark_quality_metric_1_2(value, system): # http://redmine.encodedcc.org/issues/3114 conn = system['registry'][CONNECTION] step_run = conn.get_by_uuid(value['step_run']) output_files = conn.get_rev_links(step_run.model, 'step_run', 'File') value['quality_metric_of'] = [str(uuid) for uuid in output_files] @upgrade_step('bismark_quality_metric', '2', '3') def bismark_quality_metric_2_3(value, system): # http://redmine.encodedcc.org/issues/3063 if 'aliases' in value: value['aliases'] = list(set(value['aliases'])) if 'quality_metric_of' in value: value['quality_metric_of'] = list(set(value['quality_metric_of']))
Change upgrade step to not use rev link.
Change upgrade step to not use rev link.
Python
mit
4dn-dcic/fourfront,hms-dbmi/fourfront,4dn-dcic/fourfront,T2DREAM/t2dream-portal,hms-dbmi/fourfront,ENCODE-DCC/encoded,T2DREAM/t2dream-portal,T2DREAM/t2dream-portal,ENCODE-DCC/encoded,ENCODE-DCC/snovault,ENCODE-DCC/snovault,ENCODE-DCC/encoded,hms-dbmi/fourfront,4dn-dcic/fourfront,4dn-dcic/fourfront,ENCODE-DCC/snovault,ENCODE-DCC/encoded,ENCODE-DCC/snovault,ENCODE-DCC/snovault,hms-dbmi/fourfront,hms-dbmi/fourfront,T2DREAM/t2dream-portal
from contentbase import ( ROOT, upgrade_step, ) @upgrade_step('bismark_quality_metric', '1', '2') def bismark_quality_metric_1_2(value, system): # http://redmine.encodedcc.org/issues/3114 root = system['registry'][ROOT] step_run = root.get_by_uuid(value['step_run']) value['quality_metric_of'] = [str(uuid) for uuid in step_run.get_rev_links('output_files')] @upgrade_step('bismark_quality_metric', '2', '3') def bismark_quality_metric_2_3(value, system): # http://redmine.encodedcc.org/issues/3063 if 'aliases' in value: value['aliases'] = list(set(value['aliases'])) if 'quality_metric_of' in value: value['quality_metric_of'] = list(set(value['quality_metric_of'])) Change upgrade step to not use rev link.
from contentbase import ( CONNECTION, upgrade_step, ) @upgrade_step('bismark_quality_metric', '1', '2') def bismark_quality_metric_1_2(value, system): # http://redmine.encodedcc.org/issues/3114 conn = system['registry'][CONNECTION] step_run = conn.get_by_uuid(value['step_run']) output_files = conn.get_rev_links(step_run.model, 'step_run', 'File') value['quality_metric_of'] = [str(uuid) for uuid in output_files] @upgrade_step('bismark_quality_metric', '2', '3') def bismark_quality_metric_2_3(value, system): # http://redmine.encodedcc.org/issues/3063 if 'aliases' in value: value['aliases'] = list(set(value['aliases'])) if 'quality_metric_of' in value: value['quality_metric_of'] = list(set(value['quality_metric_of']))
<commit_before>from contentbase import ( ROOT, upgrade_step, ) @upgrade_step('bismark_quality_metric', '1', '2') def bismark_quality_metric_1_2(value, system): # http://redmine.encodedcc.org/issues/3114 root = system['registry'][ROOT] step_run = root.get_by_uuid(value['step_run']) value['quality_metric_of'] = [str(uuid) for uuid in step_run.get_rev_links('output_files')] @upgrade_step('bismark_quality_metric', '2', '3') def bismark_quality_metric_2_3(value, system): # http://redmine.encodedcc.org/issues/3063 if 'aliases' in value: value['aliases'] = list(set(value['aliases'])) if 'quality_metric_of' in value: value['quality_metric_of'] = list(set(value['quality_metric_of'])) <commit_msg>Change upgrade step to not use rev link.<commit_after>
from contentbase import ( CONNECTION, upgrade_step, ) @upgrade_step('bismark_quality_metric', '1', '2') def bismark_quality_metric_1_2(value, system): # http://redmine.encodedcc.org/issues/3114 conn = system['registry'][CONNECTION] step_run = conn.get_by_uuid(value['step_run']) output_files = conn.get_rev_links(step_run.model, 'step_run', 'File') value['quality_metric_of'] = [str(uuid) for uuid in output_files] @upgrade_step('bismark_quality_metric', '2', '3') def bismark_quality_metric_2_3(value, system): # http://redmine.encodedcc.org/issues/3063 if 'aliases' in value: value['aliases'] = list(set(value['aliases'])) if 'quality_metric_of' in value: value['quality_metric_of'] = list(set(value['quality_metric_of']))
from contentbase import ( ROOT, upgrade_step, ) @upgrade_step('bismark_quality_metric', '1', '2') def bismark_quality_metric_1_2(value, system): # http://redmine.encodedcc.org/issues/3114 root = system['registry'][ROOT] step_run = root.get_by_uuid(value['step_run']) value['quality_metric_of'] = [str(uuid) for uuid in step_run.get_rev_links('output_files')] @upgrade_step('bismark_quality_metric', '2', '3') def bismark_quality_metric_2_3(value, system): # http://redmine.encodedcc.org/issues/3063 if 'aliases' in value: value['aliases'] = list(set(value['aliases'])) if 'quality_metric_of' in value: value['quality_metric_of'] = list(set(value['quality_metric_of'])) Change upgrade step to not use rev link.from contentbase import ( CONNECTION, upgrade_step, ) @upgrade_step('bismark_quality_metric', '1', '2') def bismark_quality_metric_1_2(value, system): # http://redmine.encodedcc.org/issues/3114 conn = system['registry'][CONNECTION] step_run = conn.get_by_uuid(value['step_run']) output_files = conn.get_rev_links(step_run.model, 'step_run', 'File') value['quality_metric_of'] = [str(uuid) for uuid in output_files] @upgrade_step('bismark_quality_metric', '2', '3') def bismark_quality_metric_2_3(value, system): # http://redmine.encodedcc.org/issues/3063 if 'aliases' in value: value['aliases'] = list(set(value['aliases'])) if 'quality_metric_of' in value: value['quality_metric_of'] = list(set(value['quality_metric_of']))
<commit_before>from contentbase import ( ROOT, upgrade_step, ) @upgrade_step('bismark_quality_metric', '1', '2') def bismark_quality_metric_1_2(value, system): # http://redmine.encodedcc.org/issues/3114 root = system['registry'][ROOT] step_run = root.get_by_uuid(value['step_run']) value['quality_metric_of'] = [str(uuid) for uuid in step_run.get_rev_links('output_files')] @upgrade_step('bismark_quality_metric', '2', '3') def bismark_quality_metric_2_3(value, system): # http://redmine.encodedcc.org/issues/3063 if 'aliases' in value: value['aliases'] = list(set(value['aliases'])) if 'quality_metric_of' in value: value['quality_metric_of'] = list(set(value['quality_metric_of'])) <commit_msg>Change upgrade step to not use rev link.<commit_after>from contentbase import ( CONNECTION, upgrade_step, ) @upgrade_step('bismark_quality_metric', '1', '2') def bismark_quality_metric_1_2(value, system): # http://redmine.encodedcc.org/issues/3114 conn = system['registry'][CONNECTION] step_run = conn.get_by_uuid(value['step_run']) output_files = conn.get_rev_links(step_run.model, 'step_run', 'File') value['quality_metric_of'] = [str(uuid) for uuid in output_files] @upgrade_step('bismark_quality_metric', '2', '3') def bismark_quality_metric_2_3(value, system): # http://redmine.encodedcc.org/issues/3063 if 'aliases' in value: value['aliases'] = list(set(value['aliases'])) if 'quality_metric_of' in value: value['quality_metric_of'] = list(set(value['quality_metric_of']))
b6a66fa8ecdfbdd196c1d2a776c85ed9b3c1c06d
test/test_configuration.py
test/test_configuration.py
from __future__ import with_statement import os.path import tempfile from nose.tools import * from behave import configuration # one entry of each kind handled TEST_CONFIG='''[behave] outfile=/tmp/spam paths = /absolute/path relative/path tags = @foo,~@bar @zap format=pretty tag-counter stdout_capture=no bogus=spam ''' class TestConfiguration(object): def test_read_file(self): tn = tempfile.mktemp() with open(tn, 'w') as f: f.write(TEST_CONFIG) d = configuration.read_configuration(tn) eq_(d['outfile'], '/tmp/spam') eq_(d['paths'], [ '/absolute/path', os.path.normpath(os.path.join(os.path.dirname(tn), 'relative/path')), ]) eq_(d['format'], ['pretty', 'tag-counter']) eq_(d['tags'], ['@foo,~@bar', '@zap']) eq_(d['stdout_capture'], False) ok_('bogus' not in d)
from __future__ import with_statement import os.path import tempfile from nose.tools import * from behave import configuration # one entry of each kind handled TEST_CONFIG='''[behave] outfile=/tmp/spam paths = /absolute/path relative/path tags = @foo,~@bar @zap format=pretty tag-counter stdout_capture=no bogus=spam ''' class TestConfiguration(object): def test_read_file(self): tn = tempfile.mktemp() with open(tn, 'w') as f: f.write(TEST_CONFIG) d = configuration.read_configuration(tn) eq_(d['outfile'], '/tmp/spam') eq_(d['paths'], [ os.path.normpath('/absolute/path'), # -- WINDOWS-REQUIRES: normpath os.path.normpath(os.path.join(os.path.dirname(tn), 'relative/path')), ]) eq_(d['format'], ['pretty', 'tag-counter']) eq_(d['tags'], ['@foo,~@bar', '@zap']) eq_(d['stdout_capture'], False) ok_('bogus' not in d)
FIX test for Windows platform.
FIX test for Windows platform.
Python
bsd-2-clause
hugeinc/behave-parallel
from __future__ import with_statement import os.path import tempfile from nose.tools import * from behave import configuration # one entry of each kind handled TEST_CONFIG='''[behave] outfile=/tmp/spam paths = /absolute/path relative/path tags = @foo,~@bar @zap format=pretty tag-counter stdout_capture=no bogus=spam ''' class TestConfiguration(object): def test_read_file(self): tn = tempfile.mktemp() with open(tn, 'w') as f: f.write(TEST_CONFIG) d = configuration.read_configuration(tn) eq_(d['outfile'], '/tmp/spam') eq_(d['paths'], [ '/absolute/path', os.path.normpath(os.path.join(os.path.dirname(tn), 'relative/path')), ]) eq_(d['format'], ['pretty', 'tag-counter']) eq_(d['tags'], ['@foo,~@bar', '@zap']) eq_(d['stdout_capture'], False) ok_('bogus' not in d) FIX test for Windows platform.
from __future__ import with_statement import os.path import tempfile from nose.tools import * from behave import configuration # one entry of each kind handled TEST_CONFIG='''[behave] outfile=/tmp/spam paths = /absolute/path relative/path tags = @foo,~@bar @zap format=pretty tag-counter stdout_capture=no bogus=spam ''' class TestConfiguration(object): def test_read_file(self): tn = tempfile.mktemp() with open(tn, 'w') as f: f.write(TEST_CONFIG) d = configuration.read_configuration(tn) eq_(d['outfile'], '/tmp/spam') eq_(d['paths'], [ os.path.normpath('/absolute/path'), # -- WINDOWS-REQUIRES: normpath os.path.normpath(os.path.join(os.path.dirname(tn), 'relative/path')), ]) eq_(d['format'], ['pretty', 'tag-counter']) eq_(d['tags'], ['@foo,~@bar', '@zap']) eq_(d['stdout_capture'], False) ok_('bogus' not in d)
<commit_before>from __future__ import with_statement import os.path import tempfile from nose.tools import * from behave import configuration # one entry of each kind handled TEST_CONFIG='''[behave] outfile=/tmp/spam paths = /absolute/path relative/path tags = @foo,~@bar @zap format=pretty tag-counter stdout_capture=no bogus=spam ''' class TestConfiguration(object): def test_read_file(self): tn = tempfile.mktemp() with open(tn, 'w') as f: f.write(TEST_CONFIG) d = configuration.read_configuration(tn) eq_(d['outfile'], '/tmp/spam') eq_(d['paths'], [ '/absolute/path', os.path.normpath(os.path.join(os.path.dirname(tn), 'relative/path')), ]) eq_(d['format'], ['pretty', 'tag-counter']) eq_(d['tags'], ['@foo,~@bar', '@zap']) eq_(d['stdout_capture'], False) ok_('bogus' not in d) <commit_msg>FIX test for Windows platform.<commit_after>
from __future__ import with_statement import os.path import tempfile from nose.tools import * from behave import configuration # one entry of each kind handled TEST_CONFIG='''[behave] outfile=/tmp/spam paths = /absolute/path relative/path tags = @foo,~@bar @zap format=pretty tag-counter stdout_capture=no bogus=spam ''' class TestConfiguration(object): def test_read_file(self): tn = tempfile.mktemp() with open(tn, 'w') as f: f.write(TEST_CONFIG) d = configuration.read_configuration(tn) eq_(d['outfile'], '/tmp/spam') eq_(d['paths'], [ os.path.normpath('/absolute/path'), # -- WINDOWS-REQUIRES: normpath os.path.normpath(os.path.join(os.path.dirname(tn), 'relative/path')), ]) eq_(d['format'], ['pretty', 'tag-counter']) eq_(d['tags'], ['@foo,~@bar', '@zap']) eq_(d['stdout_capture'], False) ok_('bogus' not in d)
from __future__ import with_statement import os.path import tempfile from nose.tools import * from behave import configuration # one entry of each kind handled TEST_CONFIG='''[behave] outfile=/tmp/spam paths = /absolute/path relative/path tags = @foo,~@bar @zap format=pretty tag-counter stdout_capture=no bogus=spam ''' class TestConfiguration(object): def test_read_file(self): tn = tempfile.mktemp() with open(tn, 'w') as f: f.write(TEST_CONFIG) d = configuration.read_configuration(tn) eq_(d['outfile'], '/tmp/spam') eq_(d['paths'], [ '/absolute/path', os.path.normpath(os.path.join(os.path.dirname(tn), 'relative/path')), ]) eq_(d['format'], ['pretty', 'tag-counter']) eq_(d['tags'], ['@foo,~@bar', '@zap']) eq_(d['stdout_capture'], False) ok_('bogus' not in d) FIX test for Windows platform.from __future__ import with_statement import os.path import tempfile from nose.tools import * from behave import configuration # one entry of each kind handled TEST_CONFIG='''[behave] outfile=/tmp/spam paths = /absolute/path relative/path tags = @foo,~@bar @zap format=pretty tag-counter stdout_capture=no bogus=spam ''' class TestConfiguration(object): def test_read_file(self): tn = tempfile.mktemp() with open(tn, 'w') as f: f.write(TEST_CONFIG) d = configuration.read_configuration(tn) eq_(d['outfile'], '/tmp/spam') eq_(d['paths'], [ os.path.normpath('/absolute/path'), # -- WINDOWS-REQUIRES: normpath os.path.normpath(os.path.join(os.path.dirname(tn), 'relative/path')), ]) eq_(d['format'], ['pretty', 'tag-counter']) eq_(d['tags'], ['@foo,~@bar', '@zap']) eq_(d['stdout_capture'], False) ok_('bogus' not in d)
<commit_before>from __future__ import with_statement import os.path import tempfile from nose.tools import * from behave import configuration # one entry of each kind handled TEST_CONFIG='''[behave] outfile=/tmp/spam paths = /absolute/path relative/path tags = @foo,~@bar @zap format=pretty tag-counter stdout_capture=no bogus=spam ''' class TestConfiguration(object): def test_read_file(self): tn = tempfile.mktemp() with open(tn, 'w') as f: f.write(TEST_CONFIG) d = configuration.read_configuration(tn) eq_(d['outfile'], '/tmp/spam') eq_(d['paths'], [ '/absolute/path', os.path.normpath(os.path.join(os.path.dirname(tn), 'relative/path')), ]) eq_(d['format'], ['pretty', 'tag-counter']) eq_(d['tags'], ['@foo,~@bar', '@zap']) eq_(d['stdout_capture'], False) ok_('bogus' not in d) <commit_msg>FIX test for Windows platform.<commit_after>from __future__ import with_statement import os.path import tempfile from nose.tools import * from behave import configuration # one entry of each kind handled TEST_CONFIG='''[behave] outfile=/tmp/spam paths = /absolute/path relative/path tags = @foo,~@bar @zap format=pretty tag-counter stdout_capture=no bogus=spam ''' class TestConfiguration(object): def test_read_file(self): tn = tempfile.mktemp() with open(tn, 'w') as f: f.write(TEST_CONFIG) d = configuration.read_configuration(tn) eq_(d['outfile'], '/tmp/spam') eq_(d['paths'], [ os.path.normpath('/absolute/path'), # -- WINDOWS-REQUIRES: normpath os.path.normpath(os.path.join(os.path.dirname(tn), 'relative/path')), ]) eq_(d['format'], ['pretty', 'tag-counter']) eq_(d['tags'], ['@foo,~@bar', '@zap']) eq_(d['stdout_capture'], False) ok_('bogus' not in d)
7127489fc85537722c6216ea6af0005604214bdc
txircd/modules/umode_i.py
txircd/modules/umode_i.py
from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel not in recipient.channels and "i" in user.mode: return "" return representation class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "modes": { "uni": InvisibleMode() } } def cleanup(self): self.ircd.removeMode("uni")
from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel.name not in recipient.channels and "i" in user.mode: return "" return representation class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "modes": { "uni": InvisibleMode() } } def cleanup(self): self.ircd.removeMode("uni")
Fix interpretation of parameters for names list modification
Fix interpretation of parameters for names list modification
Python
bsd-3-clause
DesertBus/txircd,ElementalAlchemist/txircd,Heufneutje/txircd
from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel not in recipient.channels and "i" in user.mode: return "" return representation class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "modes": { "uni": InvisibleMode() } } def cleanup(self): self.ircd.removeMode("uni")Fix interpretation of parameters for names list modification
from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel.name not in recipient.channels and "i" in user.mode: return "" return representation class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "modes": { "uni": InvisibleMode() } } def cleanup(self): self.ircd.removeMode("uni")
<commit_before>from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel not in recipient.channels and "i" in user.mode: return "" return representation class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "modes": { "uni": InvisibleMode() } } def cleanup(self): self.ircd.removeMode("uni")<commit_msg>Fix interpretation of parameters for names list modification<commit_after>
from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel.name not in recipient.channels and "i" in user.mode: return "" return representation class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "modes": { "uni": InvisibleMode() } } def cleanup(self): self.ircd.removeMode("uni")
from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel not in recipient.channels and "i" in user.mode: return "" return representation class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "modes": { "uni": InvisibleMode() } } def cleanup(self): self.ircd.removeMode("uni")Fix interpretation of parameters for names list modificationfrom txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel.name not in recipient.channels and "i" in user.mode: return "" return representation class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "modes": { "uni": InvisibleMode() } } def cleanup(self): self.ircd.removeMode("uni")
<commit_before>from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel not in recipient.channels and "i" in user.mode: return "" return representation class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "modes": { "uni": InvisibleMode() } } def cleanup(self): self.ircd.removeMode("uni")<commit_msg>Fix interpretation of parameters for names list modification<commit_after>from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel.name not in recipient.channels and "i" in user.mode: return "" return representation class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "modes": { "uni": InvisibleMode() } } def cleanup(self): self.ircd.removeMode("uni")
b903bcfc893911e0abd313e3cd9ea5c7128024de
MS1/ddp-erlang-style/dna_lib.py
MS1/ddp-erlang-style/dna_lib.py
__author__ = 'mcsquaredjr' import os import socket node_file = os.environ["NODES"] cad_file = os.environ["CAD"] procs_per_nod = os.environ["PROCS_PER_NODE"] itemcount = os.environ["ITEMCOUNT"] ddp = os.environment["DDP"] def my_lines(i): ip = socket.gethostbyname(socket.gethostname()) with open(cad_file, "r") as cad: lines = [] for line in cad: ip_str, port = line.split(":") if ip_str == str(ip): lines.append(line) def chunk_number(i): if i == 0 or i == 1: return 0 else: return i -1 def chunk_count(i): with open(cad_file) as cad: for i, l in enumerate(cad): pass return i + 1 - 2
__author__ = 'mcsquaredjr' import os import socket node_file = os.environ["NODES"] cad_file = os.environ["CAD"] procs_per_nod = os.environ["PROCS_PER_NODE"] itemcount = os.environ["ITEMCOUNT"] ddp = os.environment["DDP"] def my_lines(): ip = socket.gethostbyname(socket.gethostname()) with open(cad_file, "r") as cad: lines = [] for line in cad: ip_str, port = line.split(":") if ip_str == str(ip): lines.append(line) def chunk_number(i): if i == 0 or i == 1: return 0 else: return i - 1 def chunk_count(i): with open(cad_file) as cad: for i, l in enumerate(cad): pass return i + 1 - 2
Add more variables and bug fixes
Add more variables and bug fixes
Python
apache-2.0
SKA-ScienceDataProcessor/RC,SKA-ScienceDataProcessor/RC,SKA-ScienceDataProcessor/RC,SKA-ScienceDataProcessor/RC,SKA-ScienceDataProcessor/RC
__author__ = 'mcsquaredjr' import os import socket node_file = os.environ["NODES"] cad_file = os.environ["CAD"] procs_per_nod = os.environ["PROCS_PER_NODE"] itemcount = os.environ["ITEMCOUNT"] ddp = os.environment["DDP"] def my_lines(i): ip = socket.gethostbyname(socket.gethostname()) with open(cad_file, "r") as cad: lines = [] for line in cad: ip_str, port = line.split(":") if ip_str == str(ip): lines.append(line) def chunk_number(i): if i == 0 or i == 1: return 0 else: return i -1 def chunk_count(i): with open(cad_file) as cad: for i, l in enumerate(cad): pass return i + 1 - 2Add more variables and bug fixes
__author__ = 'mcsquaredjr' import os import socket node_file = os.environ["NODES"] cad_file = os.environ["CAD"] procs_per_nod = os.environ["PROCS_PER_NODE"] itemcount = os.environ["ITEMCOUNT"] ddp = os.environment["DDP"] def my_lines(): ip = socket.gethostbyname(socket.gethostname()) with open(cad_file, "r") as cad: lines = [] for line in cad: ip_str, port = line.split(":") if ip_str == str(ip): lines.append(line) def chunk_number(i): if i == 0 or i == 1: return 0 else: return i - 1 def chunk_count(i): with open(cad_file) as cad: for i, l in enumerate(cad): pass return i + 1 - 2
<commit_before>__author__ = 'mcsquaredjr' import os import socket node_file = os.environ["NODES"] cad_file = os.environ["CAD"] procs_per_nod = os.environ["PROCS_PER_NODE"] itemcount = os.environ["ITEMCOUNT"] ddp = os.environment["DDP"] def my_lines(i): ip = socket.gethostbyname(socket.gethostname()) with open(cad_file, "r") as cad: lines = [] for line in cad: ip_str, port = line.split(":") if ip_str == str(ip): lines.append(line) def chunk_number(i): if i == 0 or i == 1: return 0 else: return i -1 def chunk_count(i): with open(cad_file) as cad: for i, l in enumerate(cad): pass return i + 1 - 2<commit_msg>Add more variables and bug fixes<commit_after>
__author__ = 'mcsquaredjr' import os import socket node_file = os.environ["NODES"] cad_file = os.environ["CAD"] procs_per_nod = os.environ["PROCS_PER_NODE"] itemcount = os.environ["ITEMCOUNT"] ddp = os.environment["DDP"] def my_lines(): ip = socket.gethostbyname(socket.gethostname()) with open(cad_file, "r") as cad: lines = [] for line in cad: ip_str, port = line.split(":") if ip_str == str(ip): lines.append(line) def chunk_number(i): if i == 0 or i == 1: return 0 else: return i - 1 def chunk_count(i): with open(cad_file) as cad: for i, l in enumerate(cad): pass return i + 1 - 2
__author__ = 'mcsquaredjr' import os import socket node_file = os.environ["NODES"] cad_file = os.environ["CAD"] procs_per_nod = os.environ["PROCS_PER_NODE"] itemcount = os.environ["ITEMCOUNT"] ddp = os.environment["DDP"] def my_lines(i): ip = socket.gethostbyname(socket.gethostname()) with open(cad_file, "r") as cad: lines = [] for line in cad: ip_str, port = line.split(":") if ip_str == str(ip): lines.append(line) def chunk_number(i): if i == 0 or i == 1: return 0 else: return i -1 def chunk_count(i): with open(cad_file) as cad: for i, l in enumerate(cad): pass return i + 1 - 2Add more variables and bug fixes__author__ = 'mcsquaredjr' import os import socket node_file = os.environ["NODES"] cad_file = os.environ["CAD"] procs_per_nod = os.environ["PROCS_PER_NODE"] itemcount = os.environ["ITEMCOUNT"] ddp = os.environment["DDP"] def my_lines(): ip = socket.gethostbyname(socket.gethostname()) with open(cad_file, "r") as cad: lines = [] for line in cad: ip_str, port = line.split(":") if ip_str == str(ip): lines.append(line) def chunk_number(i): if i == 0 or i == 1: return 0 else: return i - 1 def chunk_count(i): with open(cad_file) as cad: for i, l in enumerate(cad): pass return i + 1 - 2
<commit_before>__author__ = 'mcsquaredjr' import os import socket node_file = os.environ["NODES"] cad_file = os.environ["CAD"] procs_per_nod = os.environ["PROCS_PER_NODE"] itemcount = os.environ["ITEMCOUNT"] ddp = os.environment["DDP"] def my_lines(i): ip = socket.gethostbyname(socket.gethostname()) with open(cad_file, "r") as cad: lines = [] for line in cad: ip_str, port = line.split(":") if ip_str == str(ip): lines.append(line) def chunk_number(i): if i == 0 or i == 1: return 0 else: return i -1 def chunk_count(i): with open(cad_file) as cad: for i, l in enumerate(cad): pass return i + 1 - 2<commit_msg>Add more variables and bug fixes<commit_after>__author__ = 'mcsquaredjr' import os import socket node_file = os.environ["NODES"] cad_file = os.environ["CAD"] procs_per_nod = os.environ["PROCS_PER_NODE"] itemcount = os.environ["ITEMCOUNT"] ddp = os.environment["DDP"] def my_lines(): ip = socket.gethostbyname(socket.gethostname()) with open(cad_file, "r") as cad: lines = [] for line in cad: ip_str, port = line.split(":") if ip_str == str(ip): lines.append(line) def chunk_number(i): if i == 0 or i == 1: return 0 else: return i - 1 def chunk_count(i): with open(cad_file) as cad: for i, l in enumerate(cad): pass return i + 1 - 2
78c3ad892260e9a89dab533a42f0c8f09f2401ca
src/armet/connectors/django/__init__.py
src/armet/connectors/django/__init__.py
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division __all__ = [ ] def is_available(*capacities): """ Detects if the environment is available for use in the (optionally) specified capacities. """ try: # Attempted import. import django # Now try and use it. from django.conf import settings settings.DEBUG # Detected connector. return True except ImportError: # Failed to import django; or, we don't have a proper settings # file. return False
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division __all__ = [ ] def is_available(*capacities): """ Detects if the environment is available for use in the (optionally) specified capacities. """ try: # Attempted import. import django except ImportError: # Failed to import django return False # Import the exception we might get from django.core.exceptions import ImproperlyConfigured try: # Now try and use it. from django.conf import settings settings.DEBUG # Detected connector. return True except ImproperlyConfigured: # We don't have an available settings file; django is actually in use. return False
Fix is_available method in django; proper exception handling for use checking.
Fix is_available method in django; proper exception handling for use checking.
Python
mit
armet/python-armet
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division __all__ = [ ] def is_available(*capacities): """ Detects if the environment is available for use in the (optionally) specified capacities. """ try: # Attempted import. import django # Now try and use it. from django.conf import settings settings.DEBUG # Detected connector. return True except ImportError: # Failed to import django; or, we don't have a proper settings # file. return False Fix is_available method in django; proper exception handling for use checking.
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division __all__ = [ ] def is_available(*capacities): """ Detects if the environment is available for use in the (optionally) specified capacities. """ try: # Attempted import. import django except ImportError: # Failed to import django return False # Import the exception we might get from django.core.exceptions import ImproperlyConfigured try: # Now try and use it. from django.conf import settings settings.DEBUG # Detected connector. return True except ImproperlyConfigured: # We don't have an available settings file; django is actually in use. return False
<commit_before># -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division __all__ = [ ] def is_available(*capacities): """ Detects if the environment is available for use in the (optionally) specified capacities. """ try: # Attempted import. import django # Now try and use it. from django.conf import settings settings.DEBUG # Detected connector. return True except ImportError: # Failed to import django; or, we don't have a proper settings # file. return False <commit_msg>Fix is_available method in django; proper exception handling for use checking.<commit_after>
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division __all__ = [ ] def is_available(*capacities): """ Detects if the environment is available for use in the (optionally) specified capacities. """ try: # Attempted import. import django except ImportError: # Failed to import django return False # Import the exception we might get from django.core.exceptions import ImproperlyConfigured try: # Now try and use it. from django.conf import settings settings.DEBUG # Detected connector. return True except ImproperlyConfigured: # We don't have an available settings file; django is actually in use. return False
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division __all__ = [ ] def is_available(*capacities): """ Detects if the environment is available for use in the (optionally) specified capacities. """ try: # Attempted import. import django # Now try and use it. from django.conf import settings settings.DEBUG # Detected connector. return True except ImportError: # Failed to import django; or, we don't have a proper settings # file. return False Fix is_available method in django; proper exception handling for use checking.# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division __all__ = [ ] def is_available(*capacities): """ Detects if the environment is available for use in the (optionally) specified capacities. """ try: # Attempted import. import django except ImportError: # Failed to import django return False # Import the exception we might get from django.core.exceptions import ImproperlyConfigured try: # Now try and use it. from django.conf import settings settings.DEBUG # Detected connector. return True except ImproperlyConfigured: # We don't have an available settings file; django is actually in use. return False
<commit_before># -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division __all__ = [ ] def is_available(*capacities): """ Detects if the environment is available for use in the (optionally) specified capacities. """ try: # Attempted import. import django # Now try and use it. from django.conf import settings settings.DEBUG # Detected connector. return True except ImportError: # Failed to import django; or, we don't have a proper settings # file. return False <commit_msg>Fix is_available method in django; proper exception handling for use checking.<commit_after># -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division __all__ = [ ] def is_available(*capacities): """ Detects if the environment is available for use in the (optionally) specified capacities. """ try: # Attempted import. import django except ImportError: # Failed to import django return False # Import the exception we might get from django.core.exceptions import ImproperlyConfigured try: # Now try and use it. from django.conf import settings settings.DEBUG # Detected connector. return True except ImproperlyConfigured: # We don't have an available settings file; django is actually in use. return False
9cea978862a5db98dc2b0a4aad0a19533357b9d2
run_travis_lambdas.py
run_travis_lambdas.py
#!/usr/bin/env python # -*- encoding: utf-8 """ Usage: run_travis_lambdas.py (test|publish) """ import os import subprocess import sys if __name__ == '__main__': try: verb = sys.argv[1] assert verb in ('test', 'publish') except (AssertionError, IndexError): sys.exit(__doc__.strip()) results = {} names = [ n for n in os.environ['TRAVIS_LAMBDAS'].split() if n != '\\' ] for lambda_name in names: print('=== Starting Lambda task for %s ===' % lambda_name) env = os.environ.copy() env['TASK'] = '%s-%s' % (lambda_name, verb) try: subprocess.check_call(['python', 'run_travis_task.py'], env=env) except subprocess.CalledProcessError: outcome = 'FAILED' else: outcome = 'OK' results[lambda_name] = outcome print( '=== Completed Lambda task for %s [%s] ===' % (lambda_name, outcome) ) print('') print('=== SUMMARY ===') for (name, outcome) in sorted(results.items()): print('%s %s' % (name.ljust(30), outcome)) if set(results.values()) == set(['OK']): sys.exit(0) else: sys.exit(1)
#!/usr/bin/env python # -*- encoding: utf-8 """ Usage: run_travis_lambdas.py (test|publish) """ import os import subprocess import sys if __name__ == '__main__': try: verb = sys.argv[1] assert verb in ('test', 'publish') except (AssertionError, IndexError): sys.exit(__doc__.strip()) results = {} names = [ n for n in os.environ['TRAVIS_LAMBDAS'].split() if n != '\\' ] for lambda_name in names: print('=== Starting Lambda task for %s ===' % lambda_name) env = os.environ.copy() env['TASK'] = '%s-%s' % (lambda_name, verb) try: subprocess.check_call(['python3', 'run_travis_task.py'], env=env) except subprocess.CalledProcessError: outcome = 'FAILED' else: outcome = 'OK' results[lambda_name] = outcome print( '=== Completed Lambda task for %s [%s] ===' % (lambda_name, outcome) ) print('') print('=== SUMMARY ===') for (name, outcome) in sorted(results.items()): print('%s %s' % (name.ljust(30), outcome)) if set(results.values()) == set(['OK']): sys.exit(0) else: sys.exit(1)
Make sure we use Python 3 here
Make sure we use Python 3 here
Python
mit
wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api
#!/usr/bin/env python # -*- encoding: utf-8 """ Usage: run_travis_lambdas.py (test|publish) """ import os import subprocess import sys if __name__ == '__main__': try: verb = sys.argv[1] assert verb in ('test', 'publish') except (AssertionError, IndexError): sys.exit(__doc__.strip()) results = {} names = [ n for n in os.environ['TRAVIS_LAMBDAS'].split() if n != '\\' ] for lambda_name in names: print('=== Starting Lambda task for %s ===' % lambda_name) env = os.environ.copy() env['TASK'] = '%s-%s' % (lambda_name, verb) try: subprocess.check_call(['python', 'run_travis_task.py'], env=env) except subprocess.CalledProcessError: outcome = 'FAILED' else: outcome = 'OK' results[lambda_name] = outcome print( '=== Completed Lambda task for %s [%s] ===' % (lambda_name, outcome) ) print('') print('=== SUMMARY ===') for (name, outcome) in sorted(results.items()): print('%s %s' % (name.ljust(30), outcome)) if set(results.values()) == set(['OK']): sys.exit(0) else: sys.exit(1) Make sure we use Python 3 here
#!/usr/bin/env python # -*- encoding: utf-8 """ Usage: run_travis_lambdas.py (test|publish) """ import os import subprocess import sys if __name__ == '__main__': try: verb = sys.argv[1] assert verb in ('test', 'publish') except (AssertionError, IndexError): sys.exit(__doc__.strip()) results = {} names = [ n for n in os.environ['TRAVIS_LAMBDAS'].split() if n != '\\' ] for lambda_name in names: print('=== Starting Lambda task for %s ===' % lambda_name) env = os.environ.copy() env['TASK'] = '%s-%s' % (lambda_name, verb) try: subprocess.check_call(['python3', 'run_travis_task.py'], env=env) except subprocess.CalledProcessError: outcome = 'FAILED' else: outcome = 'OK' results[lambda_name] = outcome print( '=== Completed Lambda task for %s [%s] ===' % (lambda_name, outcome) ) print('') print('=== SUMMARY ===') for (name, outcome) in sorted(results.items()): print('%s %s' % (name.ljust(30), outcome)) if set(results.values()) == set(['OK']): sys.exit(0) else: sys.exit(1)
<commit_before>#!/usr/bin/env python # -*- encoding: utf-8 """ Usage: run_travis_lambdas.py (test|publish) """ import os import subprocess import sys if __name__ == '__main__': try: verb = sys.argv[1] assert verb in ('test', 'publish') except (AssertionError, IndexError): sys.exit(__doc__.strip()) results = {} names = [ n for n in os.environ['TRAVIS_LAMBDAS'].split() if n != '\\' ] for lambda_name in names: print('=== Starting Lambda task for %s ===' % lambda_name) env = os.environ.copy() env['TASK'] = '%s-%s' % (lambda_name, verb) try: subprocess.check_call(['python', 'run_travis_task.py'], env=env) except subprocess.CalledProcessError: outcome = 'FAILED' else: outcome = 'OK' results[lambda_name] = outcome print( '=== Completed Lambda task for %s [%s] ===' % (lambda_name, outcome) ) print('') print('=== SUMMARY ===') for (name, outcome) in sorted(results.items()): print('%s %s' % (name.ljust(30), outcome)) if set(results.values()) == set(['OK']): sys.exit(0) else: sys.exit(1) <commit_msg>Make sure we use Python 3 here<commit_after>
#!/usr/bin/env python # -*- encoding: utf-8 """ Usage: run_travis_lambdas.py (test|publish) """ import os import subprocess import sys if __name__ == '__main__': try: verb = sys.argv[1] assert verb in ('test', 'publish') except (AssertionError, IndexError): sys.exit(__doc__.strip()) results = {} names = [ n for n in os.environ['TRAVIS_LAMBDAS'].split() if n != '\\' ] for lambda_name in names: print('=== Starting Lambda task for %s ===' % lambda_name) env = os.environ.copy() env['TASK'] = '%s-%s' % (lambda_name, verb) try: subprocess.check_call(['python3', 'run_travis_task.py'], env=env) except subprocess.CalledProcessError: outcome = 'FAILED' else: outcome = 'OK' results[lambda_name] = outcome print( '=== Completed Lambda task for %s [%s] ===' % (lambda_name, outcome) ) print('') print('=== SUMMARY ===') for (name, outcome) in sorted(results.items()): print('%s %s' % (name.ljust(30), outcome)) if set(results.values()) == set(['OK']): sys.exit(0) else: sys.exit(1)
#!/usr/bin/env python # -*- encoding: utf-8 """ Usage: run_travis_lambdas.py (test|publish) """ import os import subprocess import sys if __name__ == '__main__': try: verb = sys.argv[1] assert verb in ('test', 'publish') except (AssertionError, IndexError): sys.exit(__doc__.strip()) results = {} names = [ n for n in os.environ['TRAVIS_LAMBDAS'].split() if n != '\\' ] for lambda_name in names: print('=== Starting Lambda task for %s ===' % lambda_name) env = os.environ.copy() env['TASK'] = '%s-%s' % (lambda_name, verb) try: subprocess.check_call(['python', 'run_travis_task.py'], env=env) except subprocess.CalledProcessError: outcome = 'FAILED' else: outcome = 'OK' results[lambda_name] = outcome print( '=== Completed Lambda task for %s [%s] ===' % (lambda_name, outcome) ) print('') print('=== SUMMARY ===') for (name, outcome) in sorted(results.items()): print('%s %s' % (name.ljust(30), outcome)) if set(results.values()) == set(['OK']): sys.exit(0) else: sys.exit(1) Make sure we use Python 3 here#!/usr/bin/env python # -*- encoding: utf-8 """ Usage: run_travis_lambdas.py (test|publish) """ import os import subprocess import sys if __name__ == '__main__': try: verb = sys.argv[1] assert verb in ('test', 'publish') except (AssertionError, IndexError): sys.exit(__doc__.strip()) results = {} names = [ n for n in os.environ['TRAVIS_LAMBDAS'].split() if n != '\\' ] for lambda_name in names: print('=== Starting Lambda task for %s ===' % lambda_name) env = os.environ.copy() env['TASK'] = '%s-%s' % (lambda_name, verb) try: subprocess.check_call(['python3', 'run_travis_task.py'], env=env) except subprocess.CalledProcessError: outcome = 'FAILED' else: outcome = 'OK' results[lambda_name] = outcome print( '=== Completed Lambda task for %s [%s] ===' % (lambda_name, outcome) ) print('') print('=== SUMMARY ===') for (name, outcome) in sorted(results.items()): print('%s %s' % (name.ljust(30), outcome)) if set(results.values()) == set(['OK']): sys.exit(0) else: sys.exit(1)
<commit_before>#!/usr/bin/env python # -*- encoding: utf-8 """ Usage: run_travis_lambdas.py (test|publish) """ import os import subprocess import sys if __name__ == '__main__': try: verb = sys.argv[1] assert verb in ('test', 'publish') except (AssertionError, IndexError): sys.exit(__doc__.strip()) results = {} names = [ n for n in os.environ['TRAVIS_LAMBDAS'].split() if n != '\\' ] for lambda_name in names: print('=== Starting Lambda task for %s ===' % lambda_name) env = os.environ.copy() env['TASK'] = '%s-%s' % (lambda_name, verb) try: subprocess.check_call(['python', 'run_travis_task.py'], env=env) except subprocess.CalledProcessError: outcome = 'FAILED' else: outcome = 'OK' results[lambda_name] = outcome print( '=== Completed Lambda task for %s [%s] ===' % (lambda_name, outcome) ) print('') print('=== SUMMARY ===') for (name, outcome) in sorted(results.items()): print('%s %s' % (name.ljust(30), outcome)) if set(results.values()) == set(['OK']): sys.exit(0) else: sys.exit(1) <commit_msg>Make sure we use Python 3 here<commit_after>#!/usr/bin/env python # -*- encoding: utf-8 """ Usage: run_travis_lambdas.py (test|publish) """ import os import subprocess import sys if __name__ == '__main__': try: verb = sys.argv[1] assert verb in ('test', 'publish') except (AssertionError, IndexError): sys.exit(__doc__.strip()) results = {} names = [ n for n in os.environ['TRAVIS_LAMBDAS'].split() if n != '\\' ] for lambda_name in names: print('=== Starting Lambda task for %s ===' % lambda_name) env = os.environ.copy() env['TASK'] = '%s-%s' % (lambda_name, verb) try: subprocess.check_call(['python3', 'run_travis_task.py'], env=env) except subprocess.CalledProcessError: outcome = 'FAILED' else: outcome = 'OK' results[lambda_name] = outcome print( '=== Completed Lambda task for %s [%s] ===' % (lambda_name, outcome) ) print('') print('=== SUMMARY ===') for (name, outcome) in sorted(results.items()): print('%s %s' % (name.ljust(30), outcome)) if set(results.values()) == set(['OK']): sys.exit(0) else: sys.exit(1)
8c7de9c87412725c325f849f995df3010f36d5b2
openmm/run_test.py
openmm/run_test.py
#!/usr/bin/env python from simtk import openmm # Check major version number assert openmm.Platform.getOpenMMVersion() == '7.0', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion() # Check git hash assert openmm.version.git_revision == '5e86c4f76cb8e40e026cc78cdc452cc378151705', "openmm.version.git_revision = %s" % openmm.version.git_revision
#!/usr/bin/env python from simtk import openmm # Check major version number assert openmm.Platform.getOpenMMVersion() == '7.1', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion() # Check git hash assert openmm.version.git_revision == '1e5b258c0df6ab8b4350fd2c3cbf6c6f7795847c', "openmm.version.git_revision = %s" % openmm.version.git_revision
Update openmm test script to check appropriate version numbers for beta
Update openmm test script to check appropriate version numbers for beta
Python
mit
peastman/conda-recipes,swails/conda-recipes,cwehmeyer/conda-recipes,swails/conda-recipes,jchodera/conda-recipes,omnia-md/conda-recipes,peastman/conda-recipes,swails/conda-recipes,omnia-md/conda-recipes,cwehmeyer/conda-recipes,cwehmeyer/conda-recipes,omnia-md/conda-recipes,jchodera/conda-recipes,jchodera/conda-recipes,peastman/conda-recipes,jchodera/conda-recipes,swails/conda-recipes,cwehmeyer/conda-recipes
#!/usr/bin/env python from simtk import openmm # Check major version number assert openmm.Platform.getOpenMMVersion() == '7.0', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion() # Check git hash assert openmm.version.git_revision == '5e86c4f76cb8e40e026cc78cdc452cc378151705', "openmm.version.git_revision = %s" % openmm.version.git_revision Update openmm test script to check appropriate version numbers for beta
#!/usr/bin/env python from simtk import openmm # Check major version number assert openmm.Platform.getOpenMMVersion() == '7.1', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion() # Check git hash assert openmm.version.git_revision == '1e5b258c0df6ab8b4350fd2c3cbf6c6f7795847c', "openmm.version.git_revision = %s" % openmm.version.git_revision
<commit_before>#!/usr/bin/env python from simtk import openmm # Check major version number assert openmm.Platform.getOpenMMVersion() == '7.0', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion() # Check git hash assert openmm.version.git_revision == '5e86c4f76cb8e40e026cc78cdc452cc378151705', "openmm.version.git_revision = %s" % openmm.version.git_revision <commit_msg>Update openmm test script to check appropriate version numbers for beta<commit_after>
#!/usr/bin/env python from simtk import openmm # Check major version number assert openmm.Platform.getOpenMMVersion() == '7.1', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion() # Check git hash assert openmm.version.git_revision == '1e5b258c0df6ab8b4350fd2c3cbf6c6f7795847c', "openmm.version.git_revision = %s" % openmm.version.git_revision
#!/usr/bin/env python from simtk import openmm # Check major version number assert openmm.Platform.getOpenMMVersion() == '7.0', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion() # Check git hash assert openmm.version.git_revision == '5e86c4f76cb8e40e026cc78cdc452cc378151705', "openmm.version.git_revision = %s" % openmm.version.git_revision Update openmm test script to check appropriate version numbers for beta#!/usr/bin/env python from simtk import openmm # Check major version number assert openmm.Platform.getOpenMMVersion() == '7.1', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion() # Check git hash assert openmm.version.git_revision == '1e5b258c0df6ab8b4350fd2c3cbf6c6f7795847c', "openmm.version.git_revision = %s" % openmm.version.git_revision
<commit_before>#!/usr/bin/env python from simtk import openmm # Check major version number assert openmm.Platform.getOpenMMVersion() == '7.0', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion() # Check git hash assert openmm.version.git_revision == '5e86c4f76cb8e40e026cc78cdc452cc378151705', "openmm.version.git_revision = %s" % openmm.version.git_revision <commit_msg>Update openmm test script to check appropriate version numbers for beta<commit_after>#!/usr/bin/env python from simtk import openmm # Check major version number assert openmm.Platform.getOpenMMVersion() == '7.1', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion() # Check git hash assert openmm.version.git_revision == '1e5b258c0df6ab8b4350fd2c3cbf6c6f7795847c', "openmm.version.git_revision = %s" % openmm.version.git_revision
b36da5a46137fc1d6fdad4a2ffbb62ad8a284046
comics/comics/sequentialart.py
comics/comics/sequentialart.py
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Sequential Art" language = "en" url = "http://www.collectedcurios.com/" start_date = "2005-06-13" rights = "Phillip M. Jackson" class Crawler(CrawlerBase): schedule = "We" time_zone = "Europe/London" def crawl(self, pub_date): page = self.parse_page( "http://www.collectedcurios.com/sequentialart.php" ) url = page.src("img#strip") return CrawlerImage(url)
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Sequential Art" language = "en" url = "http://www.collectedcurios.com/" start_date = "2005-06-13" rights = "Phillip M. Jackson" class Crawler(CrawlerBase): schedule = "We" time_zone = "Europe/London" def crawl(self, pub_date): page = self.parse_page( "http://www.collectedcurios.com/sequentialart.php" ) url = page.src("img.w3-image") return CrawlerImage(url)
Update "Sequential Art" after site change
Update "Sequential Art" after site change
Python
agpl-3.0
datagutten/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,jodal/comics
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Sequential Art" language = "en" url = "http://www.collectedcurios.com/" start_date = "2005-06-13" rights = "Phillip M. Jackson" class Crawler(CrawlerBase): schedule = "We" time_zone = "Europe/London" def crawl(self, pub_date): page = self.parse_page( "http://www.collectedcurios.com/sequentialart.php" ) url = page.src("img#strip") return CrawlerImage(url) Update "Sequential Art" after site change
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Sequential Art" language = "en" url = "http://www.collectedcurios.com/" start_date = "2005-06-13" rights = "Phillip M. Jackson" class Crawler(CrawlerBase): schedule = "We" time_zone = "Europe/London" def crawl(self, pub_date): page = self.parse_page( "http://www.collectedcurios.com/sequentialart.php" ) url = page.src("img.w3-image") return CrawlerImage(url)
<commit_before>from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Sequential Art" language = "en" url = "http://www.collectedcurios.com/" start_date = "2005-06-13" rights = "Phillip M. Jackson" class Crawler(CrawlerBase): schedule = "We" time_zone = "Europe/London" def crawl(self, pub_date): page = self.parse_page( "http://www.collectedcurios.com/sequentialart.php" ) url = page.src("img#strip") return CrawlerImage(url) <commit_msg>Update "Sequential Art" after site change<commit_after>
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Sequential Art" language = "en" url = "http://www.collectedcurios.com/" start_date = "2005-06-13" rights = "Phillip M. Jackson" class Crawler(CrawlerBase): schedule = "We" time_zone = "Europe/London" def crawl(self, pub_date): page = self.parse_page( "http://www.collectedcurios.com/sequentialart.php" ) url = page.src("img.w3-image") return CrawlerImage(url)
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Sequential Art" language = "en" url = "http://www.collectedcurios.com/" start_date = "2005-06-13" rights = "Phillip M. Jackson" class Crawler(CrawlerBase): schedule = "We" time_zone = "Europe/London" def crawl(self, pub_date): page = self.parse_page( "http://www.collectedcurios.com/sequentialart.php" ) url = page.src("img#strip") return CrawlerImage(url) Update "Sequential Art" after site changefrom comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Sequential Art" language = "en" url = "http://www.collectedcurios.com/" start_date = "2005-06-13" rights = "Phillip M. Jackson" class Crawler(CrawlerBase): schedule = "We" time_zone = "Europe/London" def crawl(self, pub_date): page = self.parse_page( "http://www.collectedcurios.com/sequentialart.php" ) url = page.src("img.w3-image") return CrawlerImage(url)
<commit_before>from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Sequential Art" language = "en" url = "http://www.collectedcurios.com/" start_date = "2005-06-13" rights = "Phillip M. Jackson" class Crawler(CrawlerBase): schedule = "We" time_zone = "Europe/London" def crawl(self, pub_date): page = self.parse_page( "http://www.collectedcurios.com/sequentialart.php" ) url = page.src("img#strip") return CrawlerImage(url) <commit_msg>Update "Sequential Art" after site change<commit_after>from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Sequential Art" language = "en" url = "http://www.collectedcurios.com/" start_date = "2005-06-13" rights = "Phillip M. Jackson" class Crawler(CrawlerBase): schedule = "We" time_zone = "Europe/London" def crawl(self, pub_date): page = self.parse_page( "http://www.collectedcurios.com/sequentialart.php" ) url = page.src("img.w3-image") return CrawlerImage(url)
4026ee18f512d445a57413b65b7a29f965ededf4
domino/utils/jupyter.py
domino/utils/jupyter.py
# Author: Álvaro Parafita (parafita.alvaro@gmail.com) """ Utilities for Jupyter Notebooks """ # Add parent folder to path and change dir to it # so that we can access easily to all code and data in that folder import sys import os import os.path def notebook_init(): """ Assuming a project is built in a root folder with a notebooks subfolder where all .ipynb files are located, run this function as the first cell in a notebook to make it think the current folder is the project folder, so all subfolders of the root folder are accessible directly. Also, any imports inside the root folder will be accessible too. """ if os.path.split(os.path.abspath(os.path.curdir))[-1] == 'notebooks': sys.path.append(os.path.abspath(os.path.pardir)) os.chdir(os.path.pardir)
# Author: Álvaro Parafita (parafita.alvaro@gmail.com) """ Utilities for Jupyter Notebooks """ # Add parent folder to path and change dir to it # so that we can access easily to all code and data in that folder import sys import os import os.path def notebook_init(path=os.path.pardir): """ Assuming a project is built in a root folder with a notebooks subfolder where all .ipynb files are located, run this function as the first cell in a notebook to make it think the current folder is the project folder, so all subfolders of the root folder are accessible directly. Also, any imports inside the root folder will be accessible too. """ if os.path.split(os.path.abspath(os.path.curdir))[-1] == 'notebooks': sys.path.append(os.path.abspath(path)) os.chdir(path)
Add path parameter to notebook_init()
Add path parameter to notebook_init()
Python
mit
aparafita/domino
# Author: Álvaro Parafita (parafita.alvaro@gmail.com) """ Utilities for Jupyter Notebooks """ # Add parent folder to path and change dir to it # so that we can access easily to all code and data in that folder import sys import os import os.path def notebook_init(): """ Assuming a project is built in a root folder with a notebooks subfolder where all .ipynb files are located, run this function as the first cell in a notebook to make it think the current folder is the project folder, so all subfolders of the root folder are accessible directly. Also, any imports inside the root folder will be accessible too. """ if os.path.split(os.path.abspath(os.path.curdir))[-1] == 'notebooks': sys.path.append(os.path.abspath(os.path.pardir)) os.chdir(os.path.pardir)Add path parameter to notebook_init()
# Author: Álvaro Parafita (parafita.alvaro@gmail.com) """ Utilities for Jupyter Notebooks """ # Add parent folder to path and change dir to it # so that we can access easily to all code and data in that folder import sys import os import os.path def notebook_init(path=os.path.pardir): """ Assuming a project is built in a root folder with a notebooks subfolder where all .ipynb files are located, run this function as the first cell in a notebook to make it think the current folder is the project folder, so all subfolders of the root folder are accessible directly. Also, any imports inside the root folder will be accessible too. """ if os.path.split(os.path.abspath(os.path.curdir))[-1] == 'notebooks': sys.path.append(os.path.abspath(path)) os.chdir(path)
<commit_before># Author: Álvaro Parafita (parafita.alvaro@gmail.com) """ Utilities for Jupyter Notebooks """ # Add parent folder to path and change dir to it # so that we can access easily to all code and data in that folder import sys import os import os.path def notebook_init(): """ Assuming a project is built in a root folder with a notebooks subfolder where all .ipynb files are located, run this function as the first cell in a notebook to make it think the current folder is the project folder, so all subfolders of the root folder are accessible directly. Also, any imports inside the root folder will be accessible too. """ if os.path.split(os.path.abspath(os.path.curdir))[-1] == 'notebooks': sys.path.append(os.path.abspath(os.path.pardir)) os.chdir(os.path.pardir)<commit_msg>Add path parameter to notebook_init()<commit_after>
# Author: Álvaro Parafita (parafita.alvaro@gmail.com) """ Utilities for Jupyter Notebooks """ # Add parent folder to path and change dir to it # so that we can access easily to all code and data in that folder import sys import os import os.path def notebook_init(path=os.path.pardir): """ Assuming a project is built in a root folder with a notebooks subfolder where all .ipynb files are located, run this function as the first cell in a notebook to make it think the current folder is the project folder, so all subfolders of the root folder are accessible directly. Also, any imports inside the root folder will be accessible too. """ if os.path.split(os.path.abspath(os.path.curdir))[-1] == 'notebooks': sys.path.append(os.path.abspath(path)) os.chdir(path)
# Author: Álvaro Parafita (parafita.alvaro@gmail.com) """ Utilities for Jupyter Notebooks """ # Add parent folder to path and change dir to it # so that we can access easily to all code and data in that folder import sys import os import os.path def notebook_init(): """ Assuming a project is built in a root folder with a notebooks subfolder where all .ipynb files are located, run this function as the first cell in a notebook to make it think the current folder is the project folder, so all subfolders of the root folder are accessible directly. Also, any imports inside the root folder will be accessible too. """ if os.path.split(os.path.abspath(os.path.curdir))[-1] == 'notebooks': sys.path.append(os.path.abspath(os.path.pardir)) os.chdir(os.path.pardir)Add path parameter to notebook_init()# Author: Álvaro Parafita (parafita.alvaro@gmail.com) """ Utilities for Jupyter Notebooks """ # Add parent folder to path and change dir to it # so that we can access easily to all code and data in that folder import sys import os import os.path def notebook_init(path=os.path.pardir): """ Assuming a project is built in a root folder with a notebooks subfolder where all .ipynb files are located, run this function as the first cell in a notebook to make it think the current folder is the project folder, so all subfolders of the root folder are accessible directly. Also, any imports inside the root folder will be accessible too. """ if os.path.split(os.path.abspath(os.path.curdir))[-1] == 'notebooks': sys.path.append(os.path.abspath(path)) os.chdir(path)
<commit_before># Author: Álvaro Parafita (parafita.alvaro@gmail.com) """ Utilities for Jupyter Notebooks """ # Add parent folder to path and change dir to it # so that we can access easily to all code and data in that folder import sys import os import os.path def notebook_init(): """ Assuming a project is built in a root folder with a notebooks subfolder where all .ipynb files are located, run this function as the first cell in a notebook to make it think the current folder is the project folder, so all subfolders of the root folder are accessible directly. Also, any imports inside the root folder will be accessible too. """ if os.path.split(os.path.abspath(os.path.curdir))[-1] == 'notebooks': sys.path.append(os.path.abspath(os.path.pardir)) os.chdir(os.path.pardir)<commit_msg>Add path parameter to notebook_init()<commit_after># Author: Álvaro Parafita (parafita.alvaro@gmail.com) """ Utilities for Jupyter Notebooks """ # Add parent folder to path and change dir to it # so that we can access easily to all code and data in that folder import sys import os import os.path def notebook_init(path=os.path.pardir): """ Assuming a project is built in a root folder with a notebooks subfolder where all .ipynb files are located, run this function as the first cell in a notebook to make it think the current folder is the project folder, so all subfolders of the root folder are accessible directly. Also, any imports inside the root folder will be accessible too. """ if os.path.split(os.path.abspath(os.path.curdir))[-1] == 'notebooks': sys.path.append(os.path.abspath(path)) os.chdir(path)
8a4897fc9cb0192ed91f4e63dbe2da37f4d3ec69
xerox/__init__.py
xerox/__init__.py
from .core import * import sys def main(): """ Entry point for cli. """ if sys.argv[1:]: # called with input arguments copy(' '.join(sys.argv[1:])) elif not sys.stdin.isatty(): # piped in input copy('\n'.join(sys.stdin.readlines())) else: # paste output print(paste())
from .core import * import sys import os def main(): """ Entry point for cli. """ if sys.argv[1:]: # called with input arguments copy(' '.join(sys.argv[1:])) elif not sys.stdin.isatty(): # piped in input copy(''.join(sys.stdin.readlines()).rstrip(os.linesep)) else: # paste output print(paste())
Join lines without newline and remove trailing newline
Join lines without newline and remove trailing newline
Python
mit
kennethreitz/xerox
from .core import * import sys def main(): """ Entry point for cli. """ if sys.argv[1:]: # called with input arguments copy(' '.join(sys.argv[1:])) elif not sys.stdin.isatty(): # piped in input copy('\n'.join(sys.stdin.readlines())) else: # paste output print(paste()) Join lines without newline and remove trailing newline
from .core import * import sys import os def main(): """ Entry point for cli. """ if sys.argv[1:]: # called with input arguments copy(' '.join(sys.argv[1:])) elif not sys.stdin.isatty(): # piped in input copy(''.join(sys.stdin.readlines()).rstrip(os.linesep)) else: # paste output print(paste())
<commit_before>from .core import * import sys def main(): """ Entry point for cli. """ if sys.argv[1:]: # called with input arguments copy(' '.join(sys.argv[1:])) elif not sys.stdin.isatty(): # piped in input copy('\n'.join(sys.stdin.readlines())) else: # paste output print(paste()) <commit_msg>Join lines without newline and remove trailing newline<commit_after>
from .core import * import sys import os def main(): """ Entry point for cli. """ if sys.argv[1:]: # called with input arguments copy(' '.join(sys.argv[1:])) elif not sys.stdin.isatty(): # piped in input copy(''.join(sys.stdin.readlines()).rstrip(os.linesep)) else: # paste output print(paste())
from .core import * import sys def main(): """ Entry point for cli. """ if sys.argv[1:]: # called with input arguments copy(' '.join(sys.argv[1:])) elif not sys.stdin.isatty(): # piped in input copy('\n'.join(sys.stdin.readlines())) else: # paste output print(paste()) Join lines without newline and remove trailing newlinefrom .core import * import sys import os def main(): """ Entry point for cli. """ if sys.argv[1:]: # called with input arguments copy(' '.join(sys.argv[1:])) elif not sys.stdin.isatty(): # piped in input copy(''.join(sys.stdin.readlines()).rstrip(os.linesep)) else: # paste output print(paste())
<commit_before>from .core import * import sys def main(): """ Entry point for cli. """ if sys.argv[1:]: # called with input arguments copy(' '.join(sys.argv[1:])) elif not sys.stdin.isatty(): # piped in input copy('\n'.join(sys.stdin.readlines())) else: # paste output print(paste()) <commit_msg>Join lines without newline and remove trailing newline<commit_after>from .core import * import sys import os def main(): """ Entry point for cli. """ if sys.argv[1:]: # called with input arguments copy(' '.join(sys.argv[1:])) elif not sys.stdin.isatty(): # piped in input copy(''.join(sys.stdin.readlines()).rstrip(os.linesep)) else: # paste output print(paste())
61f06da13bef77f576a0c2dea77febf0d2d4b6fb
subl.py
subl.py
from .dependencies import dependencies dependencies.load() import sublime, sublime_plugin from sublime import Region import subl_source_kitten # Sublime Text will will call `on_query_completions` itself class SublCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): offset = locations[0] file = view.file_name() if not file.endswith(".swift"): return None project_directory = view.window().folders()[0] text = view.substr(Region(0, view.size())) suggestions = subl_source_kitten.complete(offset, file, project_directory, text) return (suggestions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
from .dependencies import dependencies dependencies.load() import sublime, sublime_plugin from sublime import Region import subl_source_kitten # Sublime Text will will call `on_query_completions` itself class SublCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): offset = locations[0] file = view.file_name() if file != None and not file.endswith(".swift"): return None project_directory = view.window().folders()[0] text = view.substr(Region(0, view.size())) suggestions = subl_source_kitten.complete(offset, file, project_directory, text) return (suggestions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
Allow autocomplete on non-persisted swift files
Allow autocomplete on non-persisted swift files
Python
mit
Dan2552/SourceKittenSubl,Dan2552/SourceKittenSubl,Dan2552/SourceKittenSubl
from .dependencies import dependencies dependencies.load() import sublime, sublime_plugin from sublime import Region import subl_source_kitten # Sublime Text will will call `on_query_completions` itself class SublCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): offset = locations[0] file = view.file_name() if not file.endswith(".swift"): return None project_directory = view.window().folders()[0] text = view.substr(Region(0, view.size())) suggestions = subl_source_kitten.complete(offset, file, project_directory, text) return (suggestions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS) Allow autocomplete on non-persisted swift files
from .dependencies import dependencies dependencies.load() import sublime, sublime_plugin from sublime import Region import subl_source_kitten # Sublime Text will will call `on_query_completions` itself class SublCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): offset = locations[0] file = view.file_name() if file != None and not file.endswith(".swift"): return None project_directory = view.window().folders()[0] text = view.substr(Region(0, view.size())) suggestions = subl_source_kitten.complete(offset, file, project_directory, text) return (suggestions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
<commit_before>from .dependencies import dependencies dependencies.load() import sublime, sublime_plugin from sublime import Region import subl_source_kitten # Sublime Text will will call `on_query_completions` itself class SublCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): offset = locations[0] file = view.file_name() if not file.endswith(".swift"): return None project_directory = view.window().folders()[0] text = view.substr(Region(0, view.size())) suggestions = subl_source_kitten.complete(offset, file, project_directory, text) return (suggestions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS) <commit_msg>Allow autocomplete on non-persisted swift files<commit_after>
from .dependencies import dependencies dependencies.load() import sublime, sublime_plugin from sublime import Region import subl_source_kitten # Sublime Text will will call `on_query_completions` itself class SublCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): offset = locations[0] file = view.file_name() if file != None and not file.endswith(".swift"): return None project_directory = view.window().folders()[0] text = view.substr(Region(0, view.size())) suggestions = subl_source_kitten.complete(offset, file, project_directory, text) return (suggestions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
from .dependencies import dependencies dependencies.load() import sublime, sublime_plugin from sublime import Region import subl_source_kitten # Sublime Text will will call `on_query_completions` itself class SublCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): offset = locations[0] file = view.file_name() if not file.endswith(".swift"): return None project_directory = view.window().folders()[0] text = view.substr(Region(0, view.size())) suggestions = subl_source_kitten.complete(offset, file, project_directory, text) return (suggestions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS) Allow autocomplete on non-persisted swift filesfrom .dependencies import dependencies dependencies.load() import sublime, sublime_plugin from sublime import Region import subl_source_kitten # Sublime Text will will call `on_query_completions` itself class SublCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): offset = locations[0] file = view.file_name() if file != None and not file.endswith(".swift"): return None project_directory = view.window().folders()[0] text = view.substr(Region(0, view.size())) suggestions = subl_source_kitten.complete(offset, file, project_directory, text) return (suggestions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
<commit_before>from .dependencies import dependencies dependencies.load() import sublime, sublime_plugin from sublime import Region import subl_source_kitten # Sublime Text will will call `on_query_completions` itself class SublCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): offset = locations[0] file = view.file_name() if not file.endswith(".swift"): return None project_directory = view.window().folders()[0] text = view.substr(Region(0, view.size())) suggestions = subl_source_kitten.complete(offset, file, project_directory, text) return (suggestions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS) <commit_msg>Allow autocomplete on non-persisted swift files<commit_after>from .dependencies import dependencies dependencies.load() import sublime, sublime_plugin from sublime import Region import subl_source_kitten # Sublime Text will will call `on_query_completions` itself class SublCompletions(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): offset = locations[0] file = view.file_name() if file != None and not file.endswith(".swift"): return None project_directory = view.window().folders()[0] text = view.substr(Region(0, view.size())) suggestions = subl_source_kitten.complete(offset, file, project_directory, text) return (suggestions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
8178bf161d39976405690d68d9ffe6c4dfd9d705
web/view_athena/views.py
web/view_athena/views.py
from django.shortcuts import render from elasticsearch import Elasticsearch from django.http import HttpResponse def search(request): if request.method == 'GET': term = request.GET.get('term_search') if term == None: term = "" response = search_term(term) pages = [] for hit in response['hits']['hits']: x = {'source': hit["_source"], 'highlight': hit["highlight"]["text"][0]} pages.append(x) return render(request, 'view_athena/index.html', {'pages':pages,'term_search':term}) def search_term(term): es = Elasticsearch() res = es.search(index="athena", body={"query": {"bool": {"should": [ { "match": { "title": "\"" + str(term) + "\"" }}, { "match": { "text": "\"" + str(term) + "\"" }}, { "match": { "description": "\"" + str(term) + "\"" }}]}},"highlight": {"fields" : {"text" : {}}}}) return res
from django.shortcuts import render from elasticsearch import Elasticsearch from django.http import HttpResponse def search(request): if request.method == 'GET': term = request.GET.get('term_search') if term == None: term = "" response = search_term(term) pages = [] for hit in response['hits']['hits']: x = {'source': hit["_source"], 'highlight': hit["highlight"]["text"][0]} pages.append(x) return render(request, 'view_athena/index.html', {'pages':pages,'term_search':term}) def search_term(term): es = Elasticsearch() res = es.search(index="athena", body={"query": {"bool": {"should": [ { "match_phrase": { "title": "\"" + str(term) + "\"" }}, { "match_phrase": { "text": "\"" + str(term) + "\"" }}, { "match_phrase": { "description": "\"" + str(term) + "\"" }}]}},"highlight": {"fields" : {"text" : {}}}}) return res
Update 'search_term' functon. Add 'match_phrase' function.
Update 'search_term' functon. Add 'match_phrase' function.
Python
mit
pattyvader/athena,pattyvader/athena,pattyvader/athena
from django.shortcuts import render from elasticsearch import Elasticsearch from django.http import HttpResponse def search(request): if request.method == 'GET': term = request.GET.get('term_search') if term == None: term = "" response = search_term(term) pages = [] for hit in response['hits']['hits']: x = {'source': hit["_source"], 'highlight': hit["highlight"]["text"][0]} pages.append(x) return render(request, 'view_athena/index.html', {'pages':pages,'term_search':term}) def search_term(term): es = Elasticsearch() res = es.search(index="athena", body={"query": {"bool": {"should": [ { "match": { "title": "\"" + str(term) + "\"" }}, { "match": { "text": "\"" + str(term) + "\"" }}, { "match": { "description": "\"" + str(term) + "\"" }}]}},"highlight": {"fields" : {"text" : {}}}}) return res Update 'search_term' functon. Add 'match_phrase' function.
from django.shortcuts import render from elasticsearch import Elasticsearch from django.http import HttpResponse def search(request): if request.method == 'GET': term = request.GET.get('term_search') if term == None: term = "" response = search_term(term) pages = [] for hit in response['hits']['hits']: x = {'source': hit["_source"], 'highlight': hit["highlight"]["text"][0]} pages.append(x) return render(request, 'view_athena/index.html', {'pages':pages,'term_search':term}) def search_term(term): es = Elasticsearch() res = es.search(index="athena", body={"query": {"bool": {"should": [ { "match_phrase": { "title": "\"" + str(term) + "\"" }}, { "match_phrase": { "text": "\"" + str(term) + "\"" }}, { "match_phrase": { "description": "\"" + str(term) + "\"" }}]}},"highlight": {"fields" : {"text" : {}}}}) return res
<commit_before>from django.shortcuts import render from elasticsearch import Elasticsearch from django.http import HttpResponse def search(request): if request.method == 'GET': term = request.GET.get('term_search') if term == None: term = "" response = search_term(term) pages = [] for hit in response['hits']['hits']: x = {'source': hit["_source"], 'highlight': hit["highlight"]["text"][0]} pages.append(x) return render(request, 'view_athena/index.html', {'pages':pages,'term_search':term}) def search_term(term): es = Elasticsearch() res = es.search(index="athena", body={"query": {"bool": {"should": [ { "match": { "title": "\"" + str(term) + "\"" }}, { "match": { "text": "\"" + str(term) + "\"" }}, { "match": { "description": "\"" + str(term) + "\"" }}]}},"highlight": {"fields" : {"text" : {}}}}) return res <commit_msg>Update 'search_term' functon. Add 'match_phrase' function.<commit_after>
from django.shortcuts import render from elasticsearch import Elasticsearch from django.http import HttpResponse def search(request): if request.method == 'GET': term = request.GET.get('term_search') if term == None: term = "" response = search_term(term) pages = [] for hit in response['hits']['hits']: x = {'source': hit["_source"], 'highlight': hit["highlight"]["text"][0]} pages.append(x) return render(request, 'view_athena/index.html', {'pages':pages,'term_search':term}) def search_term(term): es = Elasticsearch() res = es.search(index="athena", body={"query": {"bool": {"should": [ { "match_phrase": { "title": "\"" + str(term) + "\"" }}, { "match_phrase": { "text": "\"" + str(term) + "\"" }}, { "match_phrase": { "description": "\"" + str(term) + "\"" }}]}},"highlight": {"fields" : {"text" : {}}}}) return res
from django.shortcuts import render from elasticsearch import Elasticsearch from django.http import HttpResponse def search(request): if request.method == 'GET': term = request.GET.get('term_search') if term == None: term = "" response = search_term(term) pages = [] for hit in response['hits']['hits']: x = {'source': hit["_source"], 'highlight': hit["highlight"]["text"][0]} pages.append(x) return render(request, 'view_athena/index.html', {'pages':pages,'term_search':term}) def search_term(term): es = Elasticsearch() res = es.search(index="athena", body={"query": {"bool": {"should": [ { "match": { "title": "\"" + str(term) + "\"" }}, { "match": { "text": "\"" + str(term) + "\"" }}, { "match": { "description": "\"" + str(term) + "\"" }}]}},"highlight": {"fields" : {"text" : {}}}}) return res Update 'search_term' functon. Add 'match_phrase' function.from django.shortcuts import render from elasticsearch import Elasticsearch from django.http import HttpResponse def search(request): if request.method == 'GET': term = request.GET.get('term_search') if term == None: term = "" response = search_term(term) pages = [] for hit in response['hits']['hits']: x = {'source': hit["_source"], 'highlight': hit["highlight"]["text"][0]} pages.append(x) return render(request, 'view_athena/index.html', {'pages':pages,'term_search':term}) def search_term(term): es = Elasticsearch() res = es.search(index="athena", body={"query": {"bool": {"should": [ { "match_phrase": { "title": "\"" + str(term) + "\"" }}, { "match_phrase": { "text": "\"" + str(term) + "\"" }}, { "match_phrase": { "description": "\"" + str(term) + "\"" }}]}},"highlight": {"fields" : {"text" : {}}}}) return res
<commit_before>from django.shortcuts import render from elasticsearch import Elasticsearch from django.http import HttpResponse def search(request): if request.method == 'GET': term = request.GET.get('term_search') if term == None: term = "" response = search_term(term) pages = [] for hit in response['hits']['hits']: x = {'source': hit["_source"], 'highlight': hit["highlight"]["text"][0]} pages.append(x) return render(request, 'view_athena/index.html', {'pages':pages,'term_search':term}) def search_term(term): es = Elasticsearch() res = es.search(index="athena", body={"query": {"bool": {"should": [ { "match": { "title": "\"" + str(term) + "\"" }}, { "match": { "text": "\"" + str(term) + "\"" }}, { "match": { "description": "\"" + str(term) + "\"" }}]}},"highlight": {"fields" : {"text" : {}}}}) return res <commit_msg>Update 'search_term' functon. Add 'match_phrase' function.<commit_after>from django.shortcuts import render from elasticsearch import Elasticsearch from django.http import HttpResponse def search(request): if request.method == 'GET': term = request.GET.get('term_search') if term == None: term = "" response = search_term(term) pages = [] for hit in response['hits']['hits']: x = {'source': hit["_source"], 'highlight': hit["highlight"]["text"][0]} pages.append(x) return render(request, 'view_athena/index.html', {'pages':pages,'term_search':term}) def search_term(term): es = Elasticsearch() res = es.search(index="athena", body={"query": {"bool": {"should": [ { "match_phrase": { "title": "\"" + str(term) + "\"" }}, { "match_phrase": { "text": "\"" + str(term) + "\"" }}, { "match_phrase": { "description": "\"" + str(term) + "\"" }}]}},"highlight": {"fields" : {"text" : {}}}}) return res
82954f3df7e3b8f0a4cb921e40f351938451221d
cd/lambdas/pipeline-fail-notification/lambda_function.py
cd/lambdas/pipeline-fail-notification/lambda_function.py
# Invoked by: CloudWatch Events # Returns: Error or status message # # Triggered periodically to check if the CD CodePipeline has failed, and # publishes a notification import boto3 import traceback import json import os from datetime import datetime, timedelta code_pipeline = boto3.client('codepipeline') sns = boto3.client('sns') def post_notification(action_state): topic_arn = os.environ['CODEPIPELINE_FAILURES_TOPIC_ARN'] message = json.dumps(action_state) sns.publish(TopicArn=topic_arn, Message=message) def lambda_handler(event, context): try: print('Checking pipeline state...') period_start = datetime.now() - timedelta(seconds=60) pipeline_name = os.environ['PIPELINE_NAME'] pipeline_state = code_pipeline.get_pipeline_state(name=pipeline_name) for stage_state in pipeline_state['stageStates']: for action_state in stage_state['actionStates']: exec = action_state['latestExecution'] if execution['lastStatusChange'] > period_start: if execution['status'] == 'Failed': post_notification(action_state) return '...Done' except Exception as e: print('Function failed due to exception.') print(e) traceback.print_exc() put_job_failure(job, 'Function exception: ' + str(e))
# Invoked by: CloudWatch Events # Returns: Error or status message # # Triggered periodically to check if the CD CodePipeline has failed, and # publishes a notification import boto3 import traceback import json import os from datetime import datetime, timedelta code_pipeline = boto3.client('codepipeline') sns = boto3.client('sns') def post_notification(action_state): topic_arn = os.environ['CODEPIPELINE_FAILURES_TOPIC_ARN'] message = json.dumps(action_state) sns.publish(TopicArn=topic_arn, Message=message) def lambda_handler(event, context): try: print('Checking pipeline state...') pipeline_name = os.environ['PIPELINE_NAME'] pipeline_state = code_pipeline.get_pipeline_state(name=pipeline_name) for stage_state in pipeline_state['stageStates']: for action_state in stage_state['actionStates']: if 'latestExecution' in action_state: execution = action_state['latestExecution'] timezone = execution['lastStatusChange'].tzinfo period_start = datetime.now(timezone) - timedelta(seconds=60) if execution['lastStatusChange'] > period_start: if execution['status'] == 'Failed': post_notification(action_state) return '...Done' except Exception as e: print('Function failed due to exception.') print(e) traceback.print_exc()
Fix CD fail lambda python
Fix CD fail lambda python
Python
mit
PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure
# Invoked by: CloudWatch Events # Returns: Error or status message # # Triggered periodically to check if the CD CodePipeline has failed, and # publishes a notification import boto3 import traceback import json import os from datetime import datetime, timedelta code_pipeline = boto3.client('codepipeline') sns = boto3.client('sns') def post_notification(action_state): topic_arn = os.environ['CODEPIPELINE_FAILURES_TOPIC_ARN'] message = json.dumps(action_state) sns.publish(TopicArn=topic_arn, Message=message) def lambda_handler(event, context): try: print('Checking pipeline state...') period_start = datetime.now() - timedelta(seconds=60) pipeline_name = os.environ['PIPELINE_NAME'] pipeline_state = code_pipeline.get_pipeline_state(name=pipeline_name) for stage_state in pipeline_state['stageStates']: for action_state in stage_state['actionStates']: exec = action_state['latestExecution'] if execution['lastStatusChange'] > period_start: if execution['status'] == 'Failed': post_notification(action_state) return '...Done' except Exception as e: print('Function failed due to exception.') print(e) traceback.print_exc() put_job_failure(job, 'Function exception: ' + str(e)) Fix CD fail lambda python
# Invoked by: CloudWatch Events # Returns: Error or status message # # Triggered periodically to check if the CD CodePipeline has failed, and # publishes a notification import boto3 import traceback import json import os from datetime import datetime, timedelta code_pipeline = boto3.client('codepipeline') sns = boto3.client('sns') def post_notification(action_state): topic_arn = os.environ['CODEPIPELINE_FAILURES_TOPIC_ARN'] message = json.dumps(action_state) sns.publish(TopicArn=topic_arn, Message=message) def lambda_handler(event, context): try: print('Checking pipeline state...') pipeline_name = os.environ['PIPELINE_NAME'] pipeline_state = code_pipeline.get_pipeline_state(name=pipeline_name) for stage_state in pipeline_state['stageStates']: for action_state in stage_state['actionStates']: if 'latestExecution' in action_state: execution = action_state['latestExecution'] timezone = execution['lastStatusChange'].tzinfo period_start = datetime.now(timezone) - timedelta(seconds=60) if execution['lastStatusChange'] > period_start: if execution['status'] == 'Failed': post_notification(action_state) return '...Done' except Exception as e: print('Function failed due to exception.') print(e) traceback.print_exc()
<commit_before># Invoked by: CloudWatch Events # Returns: Error or status message # # Triggered periodically to check if the CD CodePipeline has failed, and # publishes a notification import boto3 import traceback import json import os from datetime import datetime, timedelta code_pipeline = boto3.client('codepipeline') sns = boto3.client('sns') def post_notification(action_state): topic_arn = os.environ['CODEPIPELINE_FAILURES_TOPIC_ARN'] message = json.dumps(action_state) sns.publish(TopicArn=topic_arn, Message=message) def lambda_handler(event, context): try: print('Checking pipeline state...') period_start = datetime.now() - timedelta(seconds=60) pipeline_name = os.environ['PIPELINE_NAME'] pipeline_state = code_pipeline.get_pipeline_state(name=pipeline_name) for stage_state in pipeline_state['stageStates']: for action_state in stage_state['actionStates']: exec = action_state['latestExecution'] if execution['lastStatusChange'] > period_start: if execution['status'] == 'Failed': post_notification(action_state) return '...Done' except Exception as e: print('Function failed due to exception.') print(e) traceback.print_exc() put_job_failure(job, 'Function exception: ' + str(e)) <commit_msg>Fix CD fail lambda python<commit_after>
# Invoked by: CloudWatch Events # Returns: Error or status message # # Triggered periodically to check if the CD CodePipeline has failed, and # publishes a notification import boto3 import traceback import json import os from datetime import datetime, timedelta code_pipeline = boto3.client('codepipeline') sns = boto3.client('sns') def post_notification(action_state): topic_arn = os.environ['CODEPIPELINE_FAILURES_TOPIC_ARN'] message = json.dumps(action_state) sns.publish(TopicArn=topic_arn, Message=message) def lambda_handler(event, context): try: print('Checking pipeline state...') pipeline_name = os.environ['PIPELINE_NAME'] pipeline_state = code_pipeline.get_pipeline_state(name=pipeline_name) for stage_state in pipeline_state['stageStates']: for action_state in stage_state['actionStates']: if 'latestExecution' in action_state: execution = action_state['latestExecution'] timezone = execution['lastStatusChange'].tzinfo period_start = datetime.now(timezone) - timedelta(seconds=60) if execution['lastStatusChange'] > period_start: if execution['status'] == 'Failed': post_notification(action_state) return '...Done' except Exception as e: print('Function failed due to exception.') print(e) traceback.print_exc()
# Invoked by: CloudWatch Events # Returns: Error or status message # # Triggered periodically to check if the CD CodePipeline has failed, and # publishes a notification import boto3 import traceback import json import os from datetime import datetime, timedelta code_pipeline = boto3.client('codepipeline') sns = boto3.client('sns') def post_notification(action_state): topic_arn = os.environ['CODEPIPELINE_FAILURES_TOPIC_ARN'] message = json.dumps(action_state) sns.publish(TopicArn=topic_arn, Message=message) def lambda_handler(event, context): try: print('Checking pipeline state...') period_start = datetime.now() - timedelta(seconds=60) pipeline_name = os.environ['PIPELINE_NAME'] pipeline_state = code_pipeline.get_pipeline_state(name=pipeline_name) for stage_state in pipeline_state['stageStates']: for action_state in stage_state['actionStates']: exec = action_state['latestExecution'] if execution['lastStatusChange'] > period_start: if execution['status'] == 'Failed': post_notification(action_state) return '...Done' except Exception as e: print('Function failed due to exception.') print(e) traceback.print_exc() put_job_failure(job, 'Function exception: ' + str(e)) Fix CD fail lambda python# Invoked by: CloudWatch Events # Returns: Error or status message # # Triggered periodically to check if the CD CodePipeline has failed, and # publishes a notification import boto3 import traceback import json import os from datetime import datetime, timedelta code_pipeline = boto3.client('codepipeline') sns = boto3.client('sns') def post_notification(action_state): topic_arn = os.environ['CODEPIPELINE_FAILURES_TOPIC_ARN'] message = json.dumps(action_state) sns.publish(TopicArn=topic_arn, Message=message) def lambda_handler(event, context): try: print('Checking pipeline state...') pipeline_name = os.environ['PIPELINE_NAME'] pipeline_state = code_pipeline.get_pipeline_state(name=pipeline_name) for stage_state in pipeline_state['stageStates']: for action_state in stage_state['actionStates']: if 'latestExecution' in action_state: execution = action_state['latestExecution'] timezone = execution['lastStatusChange'].tzinfo period_start = datetime.now(timezone) - timedelta(seconds=60) if execution['lastStatusChange'] > period_start: if execution['status'] == 'Failed': post_notification(action_state) return '...Done' except Exception as e: print('Function failed due to exception.') print(e) traceback.print_exc()
<commit_before># Invoked by: CloudWatch Events # Returns: Error or status message # # Triggered periodically to check if the CD CodePipeline has failed, and # publishes a notification import boto3 import traceback import json import os from datetime import datetime, timedelta code_pipeline = boto3.client('codepipeline') sns = boto3.client('sns') def post_notification(action_state): topic_arn = os.environ['CODEPIPELINE_FAILURES_TOPIC_ARN'] message = json.dumps(action_state) sns.publish(TopicArn=topic_arn, Message=message) def lambda_handler(event, context): try: print('Checking pipeline state...') period_start = datetime.now() - timedelta(seconds=60) pipeline_name = os.environ['PIPELINE_NAME'] pipeline_state = code_pipeline.get_pipeline_state(name=pipeline_name) for stage_state in pipeline_state['stageStates']: for action_state in stage_state['actionStates']: exec = action_state['latestExecution'] if execution['lastStatusChange'] > period_start: if execution['status'] == 'Failed': post_notification(action_state) return '...Done' except Exception as e: print('Function failed due to exception.') print(e) traceback.print_exc() put_job_failure(job, 'Function exception: ' + str(e)) <commit_msg>Fix CD fail lambda python<commit_after># Invoked by: CloudWatch Events # Returns: Error or status message # # Triggered periodically to check if the CD CodePipeline has failed, and # publishes a notification import boto3 import traceback import json import os from datetime import datetime, timedelta code_pipeline = boto3.client('codepipeline') sns = boto3.client('sns') def post_notification(action_state): topic_arn = os.environ['CODEPIPELINE_FAILURES_TOPIC_ARN'] message = json.dumps(action_state) sns.publish(TopicArn=topic_arn, Message=message) def lambda_handler(event, context): try: print('Checking pipeline state...') pipeline_name = os.environ['PIPELINE_NAME'] pipeline_state = code_pipeline.get_pipeline_state(name=pipeline_name) for stage_state in pipeline_state['stageStates']: for action_state in stage_state['actionStates']: if 'latestExecution' in action_state: execution = action_state['latestExecution'] timezone = execution['lastStatusChange'].tzinfo period_start = datetime.now(timezone) - timedelta(seconds=60) if execution['lastStatusChange'] > period_start: if execution['status'] == 'Failed': post_notification(action_state) return '...Done' except Exception as e: print('Function failed due to exception.') print(e) traceback.print_exc()
0fda3b2dc23c99bca856336504b961841faa1e51
dashing/utils.py
dashing/utils.py
from django.conf.urls import url from .views import Dashboard class Router(object): def __init__(self): self.registry = [] def register(self, widget, basename, **parameters): """ Register a widget, URL basename and any optional URL parameters. Parameters are passed as keyword arguments, i.e. >>> router.register(MyWidget, 'mywidget', my_parameter="[A-Z0-9]+") This would be the equivalent of manually adding the following to urlpatterns: >>> url(r"^widgets/mywidget/(P<my_parameter>[A-Z0-9]+)/?", MyWidget.as_view(), "widget_mywidget") """ self.registry.append((widget, basename, parameters)) def get_urls(self): urlpatterns = [ url(r'^$', Dashboard.as_view(), name='dashboard'), ] for widget, basename, parameters in self.registry: urlpatterns += [ url(r'/'.join(( r'^widgets/{}'.format(basename), r'/'.join((r'(P<{}>{})'.format(parameter, regex) for parameter, regex in parameters.items())), )), widget.as_view(), name='widget_{}'.format(basename)), ] return urlpatterns @property def urls(self): return self.get_urls() router = Router()
from django.conf.urls import url from .views import Dashboard class Router(object): def __init__(self): self.registry = [] def register(self, widget, basename, **parameters): """ Register a widget, URL basename and any optional URL parameters. Parameters are passed as keyword arguments, i.e. >>> router.register(MyWidget, 'mywidget', my_parameter="[A-Z0-9]+") This would be the equivalent of manually adding the following to urlpatterns: >>> url(r"^widgets/mywidget/(P<my_parameter>[A-Z0-9]+)/?", MyWidget.as_view(), "widget_mywidget") """ self.registry.append((widget, basename, parameters)) def get_urls(self): urlpatterns = [ url(r'^$', Dashboard.as_view(), name='dashboard'), ] for widget, basename, parameters in self.registry: urlpatterns += [ url(r'/'.join(( r'^widgets/{}'.format(basename), r'/'.join((r'(?P<{}>{})'.format(parameter, regex) for parameter, regex in parameters.items())), )), widget.as_view(), name='widget_{}'.format(basename)), ] return urlpatterns @property def urls(self): return self.get_urls() router = Router()
Fix typo in named group regex
Fix typo in named group regex
Python
bsd-3-clause
talpor/django-dashing,swiftstack/django-dashing,talpor/django-dashing,quevedin/django-dashing,mverteuil/django-dashing,luto/django-dashing,quevedin/django-dashing,swiftstack/django-dashing,swiftstack/django-dashing,torstenfeld/django-dashing,torstenfeld/django-dashing,torstenfeld/django-dashing,mverteuil/django-dashing,luto/django-dashing,quevedin/django-dashing,luto/django-dashing,talpor/django-dashing,mverteuil/django-dashing
from django.conf.urls import url from .views import Dashboard class Router(object): def __init__(self): self.registry = [] def register(self, widget, basename, **parameters): """ Register a widget, URL basename and any optional URL parameters. Parameters are passed as keyword arguments, i.e. >>> router.register(MyWidget, 'mywidget', my_parameter="[A-Z0-9]+") This would be the equivalent of manually adding the following to urlpatterns: >>> url(r"^widgets/mywidget/(P<my_parameter>[A-Z0-9]+)/?", MyWidget.as_view(), "widget_mywidget") """ self.registry.append((widget, basename, parameters)) def get_urls(self): urlpatterns = [ url(r'^$', Dashboard.as_view(), name='dashboard'), ] for widget, basename, parameters in self.registry: urlpatterns += [ url(r'/'.join(( r'^widgets/{}'.format(basename), r'/'.join((r'(P<{}>{})'.format(parameter, regex) for parameter, regex in parameters.items())), )), widget.as_view(), name='widget_{}'.format(basename)), ] return urlpatterns @property def urls(self): return self.get_urls() router = Router() Fix typo in named group regex
from django.conf.urls import url from .views import Dashboard class Router(object): def __init__(self): self.registry = [] def register(self, widget, basename, **parameters): """ Register a widget, URL basename and any optional URL parameters. Parameters are passed as keyword arguments, i.e. >>> router.register(MyWidget, 'mywidget', my_parameter="[A-Z0-9]+") This would be the equivalent of manually adding the following to urlpatterns: >>> url(r"^widgets/mywidget/(P<my_parameter>[A-Z0-9]+)/?", MyWidget.as_view(), "widget_mywidget") """ self.registry.append((widget, basename, parameters)) def get_urls(self): urlpatterns = [ url(r'^$', Dashboard.as_view(), name='dashboard'), ] for widget, basename, parameters in self.registry: urlpatterns += [ url(r'/'.join(( r'^widgets/{}'.format(basename), r'/'.join((r'(?P<{}>{})'.format(parameter, regex) for parameter, regex in parameters.items())), )), widget.as_view(), name='widget_{}'.format(basename)), ] return urlpatterns @property def urls(self): return self.get_urls() router = Router()
<commit_before>from django.conf.urls import url from .views import Dashboard class Router(object): def __init__(self): self.registry = [] def register(self, widget, basename, **parameters): """ Register a widget, URL basename and any optional URL parameters. Parameters are passed as keyword arguments, i.e. >>> router.register(MyWidget, 'mywidget', my_parameter="[A-Z0-9]+") This would be the equivalent of manually adding the following to urlpatterns: >>> url(r"^widgets/mywidget/(P<my_parameter>[A-Z0-9]+)/?", MyWidget.as_view(), "widget_mywidget") """ self.registry.append((widget, basename, parameters)) def get_urls(self): urlpatterns = [ url(r'^$', Dashboard.as_view(), name='dashboard'), ] for widget, basename, parameters in self.registry: urlpatterns += [ url(r'/'.join(( r'^widgets/{}'.format(basename), r'/'.join((r'(P<{}>{})'.format(parameter, regex) for parameter, regex in parameters.items())), )), widget.as_view(), name='widget_{}'.format(basename)), ] return urlpatterns @property def urls(self): return self.get_urls() router = Router() <commit_msg>Fix typo in named group regex<commit_after>
from django.conf.urls import url from .views import Dashboard class Router(object): def __init__(self): self.registry = [] def register(self, widget, basename, **parameters): """ Register a widget, URL basename and any optional URL parameters. Parameters are passed as keyword arguments, i.e. >>> router.register(MyWidget, 'mywidget', my_parameter="[A-Z0-9]+") This would be the equivalent of manually adding the following to urlpatterns: >>> url(r"^widgets/mywidget/(P<my_parameter>[A-Z0-9]+)/?", MyWidget.as_view(), "widget_mywidget") """ self.registry.append((widget, basename, parameters)) def get_urls(self): urlpatterns = [ url(r'^$', Dashboard.as_view(), name='dashboard'), ] for widget, basename, parameters in self.registry: urlpatterns += [ url(r'/'.join(( r'^widgets/{}'.format(basename), r'/'.join((r'(?P<{}>{})'.format(parameter, regex) for parameter, regex in parameters.items())), )), widget.as_view(), name='widget_{}'.format(basename)), ] return urlpatterns @property def urls(self): return self.get_urls() router = Router()
from django.conf.urls import url from .views import Dashboard class Router(object): def __init__(self): self.registry = [] def register(self, widget, basename, **parameters): """ Register a widget, URL basename and any optional URL parameters. Parameters are passed as keyword arguments, i.e. >>> router.register(MyWidget, 'mywidget', my_parameter="[A-Z0-9]+") This would be the equivalent of manually adding the following to urlpatterns: >>> url(r"^widgets/mywidget/(P<my_parameter>[A-Z0-9]+)/?", MyWidget.as_view(), "widget_mywidget") """ self.registry.append((widget, basename, parameters)) def get_urls(self): urlpatterns = [ url(r'^$', Dashboard.as_view(), name='dashboard'), ] for widget, basename, parameters in self.registry: urlpatterns += [ url(r'/'.join(( r'^widgets/{}'.format(basename), r'/'.join((r'(P<{}>{})'.format(parameter, regex) for parameter, regex in parameters.items())), )), widget.as_view(), name='widget_{}'.format(basename)), ] return urlpatterns @property def urls(self): return self.get_urls() router = Router() Fix typo in named group regexfrom django.conf.urls import url from .views import Dashboard class Router(object): def __init__(self): self.registry = [] def register(self, widget, basename, **parameters): """ Register a widget, URL basename and any optional URL parameters. Parameters are passed as keyword arguments, i.e. >>> router.register(MyWidget, 'mywidget', my_parameter="[A-Z0-9]+") This would be the equivalent of manually adding the following to urlpatterns: >>> url(r"^widgets/mywidget/(P<my_parameter>[A-Z0-9]+)/?", MyWidget.as_view(), "widget_mywidget") """ self.registry.append((widget, basename, parameters)) def get_urls(self): urlpatterns = [ url(r'^$', Dashboard.as_view(), name='dashboard'), ] for widget, basename, parameters in self.registry: urlpatterns += [ url(r'/'.join(( r'^widgets/{}'.format(basename), r'/'.join((r'(?P<{}>{})'.format(parameter, regex) for parameter, regex in parameters.items())), )), widget.as_view(), name='widget_{}'.format(basename)), ] return urlpatterns @property def urls(self): return self.get_urls() router = Router()
<commit_before>from django.conf.urls import url from .views import Dashboard class Router(object): def __init__(self): self.registry = [] def register(self, widget, basename, **parameters): """ Register a widget, URL basename and any optional URL parameters. Parameters are passed as keyword arguments, i.e. >>> router.register(MyWidget, 'mywidget', my_parameter="[A-Z0-9]+") This would be the equivalent of manually adding the following to urlpatterns: >>> url(r"^widgets/mywidget/(P<my_parameter>[A-Z0-9]+)/?", MyWidget.as_view(), "widget_mywidget") """ self.registry.append((widget, basename, parameters)) def get_urls(self): urlpatterns = [ url(r'^$', Dashboard.as_view(), name='dashboard'), ] for widget, basename, parameters in self.registry: urlpatterns += [ url(r'/'.join(( r'^widgets/{}'.format(basename), r'/'.join((r'(P<{}>{})'.format(parameter, regex) for parameter, regex in parameters.items())), )), widget.as_view(), name='widget_{}'.format(basename)), ] return urlpatterns @property def urls(self): return self.get_urls() router = Router() <commit_msg>Fix typo in named group regex<commit_after>from django.conf.urls import url from .views import Dashboard class Router(object): def __init__(self): self.registry = [] def register(self, widget, basename, **parameters): """ Register a widget, URL basename and any optional URL parameters. Parameters are passed as keyword arguments, i.e. >>> router.register(MyWidget, 'mywidget', my_parameter="[A-Z0-9]+") This would be the equivalent of manually adding the following to urlpatterns: >>> url(r"^widgets/mywidget/(P<my_parameter>[A-Z0-9]+)/?", MyWidget.as_view(), "widget_mywidget") """ self.registry.append((widget, basename, parameters)) def get_urls(self): urlpatterns = [ url(r'^$', Dashboard.as_view(), name='dashboard'), ] for widget, basename, parameters in self.registry: urlpatterns += [ url(r'/'.join(( r'^widgets/{}'.format(basename), r'/'.join((r'(?P<{}>{})'.format(parameter, regex) for parameter, regex in parameters.items())), )), widget.as_view(), name='widget_{}'.format(basename)), ] return urlpatterns @property def urls(self): return self.get_urls() router = Router()
daf580996210b562d78264db1e74a698d9937c40
__init__.py
__init__.py
from __future__ import absolute_import, division, print_function import logging import sys import warnings if sys.version_info.major == 2: warnings.warn( "Python 2 is no longer fully supported. Please consider using the DIALS 2.2 release branch. " "For more information on Python 2.7 support please go to https://github.com/dials/dials/issues/1175.", DeprecationWarning, ) logging.getLogger("dials").addHandler(logging.NullHandler()) # Intercept easy_mp exceptions to extract stack traces before they are lost at # the libtbx process boundary/the easy_mp API. In the case of a subprocess # crash we print the subprocess stack trace, which will be most useful for # debugging parallelized sections of DIALS code. import libtbx.scheduling.stacktrace as _lss def _stacktrace_tracer(error, trace, intercepted_call=_lss.set_last_exception): """Intercepts and prints ephemeral stacktraces.""" if error and trace: logging.getLogger("dials").error( "\n\neasy_mp crash detected; subprocess trace: ----\n%s%s\n%s\n\n", "".join(trace), error, "-" * 46, ) return intercepted_call(error, trace) if _lss.set_last_exception.__doc__ != _stacktrace_tracer.__doc__: # ensure function is only redirected once _lss.set_last_exception = _stacktrace_tracer
from __future__ import absolute_import, division, print_function import logging import sys import warnings if sys.version_info.major == 2: warnings.warn( "Python 2 is no longer fully supported. Please consider using the DIALS 2.2 release branch. " "For more information on Python 2.7 support please go to https://github.com/dials/dials/issues/1175.", UserWarning, ) logging.getLogger("dials").addHandler(logging.NullHandler()) # Intercept easy_mp exceptions to extract stack traces before they are lost at # the libtbx process boundary/the easy_mp API. In the case of a subprocess # crash we print the subprocess stack trace, which will be most useful for # debugging parallelized sections of DIALS code. import libtbx.scheduling.stacktrace as _lss def _stacktrace_tracer(error, trace, intercepted_call=_lss.set_last_exception): """Intercepts and prints ephemeral stacktraces.""" if error and trace: logging.getLogger("dials").error( "\n\neasy_mp crash detected; subprocess trace: ----\n%s%s\n%s\n\n", "".join(trace), error, "-" * 46, ) return intercepted_call(error, trace) if _lss.set_last_exception.__doc__ != _stacktrace_tracer.__doc__: # ensure function is only redirected once _lss.set_last_exception = _stacktrace_tracer
Make anyone importing DIALS aware of !2.7 support
Make anyone importing DIALS aware of !2.7 support Warning is only shown on first import, and can be silenced in Python 2.7 with import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") import dials cf. #1175
Python
bsd-3-clause
dials/dials,dials/dials,dials/dials,dials/dials,dials/dials
from __future__ import absolute_import, division, print_function import logging import sys import warnings if sys.version_info.major == 2: warnings.warn( "Python 2 is no longer fully supported. Please consider using the DIALS 2.2 release branch. " "For more information on Python 2.7 support please go to https://github.com/dials/dials/issues/1175.", DeprecationWarning, ) logging.getLogger("dials").addHandler(logging.NullHandler()) # Intercept easy_mp exceptions to extract stack traces before they are lost at # the libtbx process boundary/the easy_mp API. In the case of a subprocess # crash we print the subprocess stack trace, which will be most useful for # debugging parallelized sections of DIALS code. import libtbx.scheduling.stacktrace as _lss def _stacktrace_tracer(error, trace, intercepted_call=_lss.set_last_exception): """Intercepts and prints ephemeral stacktraces.""" if error and trace: logging.getLogger("dials").error( "\n\neasy_mp crash detected; subprocess trace: ----\n%s%s\n%s\n\n", "".join(trace), error, "-" * 46, ) return intercepted_call(error, trace) if _lss.set_last_exception.__doc__ != _stacktrace_tracer.__doc__: # ensure function is only redirected once _lss.set_last_exception = _stacktrace_tracer Make anyone importing DIALS aware of !2.7 support Warning is only shown on first import, and can be silenced in Python 2.7 with import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") import dials cf. #1175
from __future__ import absolute_import, division, print_function import logging import sys import warnings if sys.version_info.major == 2: warnings.warn( "Python 2 is no longer fully supported. Please consider using the DIALS 2.2 release branch. " "For more information on Python 2.7 support please go to https://github.com/dials/dials/issues/1175.", UserWarning, ) logging.getLogger("dials").addHandler(logging.NullHandler()) # Intercept easy_mp exceptions to extract stack traces before they are lost at # the libtbx process boundary/the easy_mp API. In the case of a subprocess # crash we print the subprocess stack trace, which will be most useful for # debugging parallelized sections of DIALS code. import libtbx.scheduling.stacktrace as _lss def _stacktrace_tracer(error, trace, intercepted_call=_lss.set_last_exception): """Intercepts and prints ephemeral stacktraces.""" if error and trace: logging.getLogger("dials").error( "\n\neasy_mp crash detected; subprocess trace: ----\n%s%s\n%s\n\n", "".join(trace), error, "-" * 46, ) return intercepted_call(error, trace) if _lss.set_last_exception.__doc__ != _stacktrace_tracer.__doc__: # ensure function is only redirected once _lss.set_last_exception = _stacktrace_tracer
<commit_before>from __future__ import absolute_import, division, print_function import logging import sys import warnings if sys.version_info.major == 2: warnings.warn( "Python 2 is no longer fully supported. Please consider using the DIALS 2.2 release branch. " "For more information on Python 2.7 support please go to https://github.com/dials/dials/issues/1175.", DeprecationWarning, ) logging.getLogger("dials").addHandler(logging.NullHandler()) # Intercept easy_mp exceptions to extract stack traces before they are lost at # the libtbx process boundary/the easy_mp API. In the case of a subprocess # crash we print the subprocess stack trace, which will be most useful for # debugging parallelized sections of DIALS code. import libtbx.scheduling.stacktrace as _lss def _stacktrace_tracer(error, trace, intercepted_call=_lss.set_last_exception): """Intercepts and prints ephemeral stacktraces.""" if error and trace: logging.getLogger("dials").error( "\n\neasy_mp crash detected; subprocess trace: ----\n%s%s\n%s\n\n", "".join(trace), error, "-" * 46, ) return intercepted_call(error, trace) if _lss.set_last_exception.__doc__ != _stacktrace_tracer.__doc__: # ensure function is only redirected once _lss.set_last_exception = _stacktrace_tracer <commit_msg>Make anyone importing DIALS aware of !2.7 support Warning is only shown on first import, and can be silenced in Python 2.7 with import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") import dials cf. #1175<commit_after>
from __future__ import absolute_import, division, print_function import logging import sys import warnings if sys.version_info.major == 2: warnings.warn( "Python 2 is no longer fully supported. Please consider using the DIALS 2.2 release branch. " "For more information on Python 2.7 support please go to https://github.com/dials/dials/issues/1175.", UserWarning, ) logging.getLogger("dials").addHandler(logging.NullHandler()) # Intercept easy_mp exceptions to extract stack traces before they are lost at # the libtbx process boundary/the easy_mp API. In the case of a subprocess # crash we print the subprocess stack trace, which will be most useful for # debugging parallelized sections of DIALS code. import libtbx.scheduling.stacktrace as _lss def _stacktrace_tracer(error, trace, intercepted_call=_lss.set_last_exception): """Intercepts and prints ephemeral stacktraces.""" if error and trace: logging.getLogger("dials").error( "\n\neasy_mp crash detected; subprocess trace: ----\n%s%s\n%s\n\n", "".join(trace), error, "-" * 46, ) return intercepted_call(error, trace) if _lss.set_last_exception.__doc__ != _stacktrace_tracer.__doc__: # ensure function is only redirected once _lss.set_last_exception = _stacktrace_tracer
from __future__ import absolute_import, division, print_function import logging import sys import warnings if sys.version_info.major == 2: warnings.warn( "Python 2 is no longer fully supported. Please consider using the DIALS 2.2 release branch. " "For more information on Python 2.7 support please go to https://github.com/dials/dials/issues/1175.", DeprecationWarning, ) logging.getLogger("dials").addHandler(logging.NullHandler()) # Intercept easy_mp exceptions to extract stack traces before they are lost at # the libtbx process boundary/the easy_mp API. In the case of a subprocess # crash we print the subprocess stack trace, which will be most useful for # debugging parallelized sections of DIALS code. import libtbx.scheduling.stacktrace as _lss def _stacktrace_tracer(error, trace, intercepted_call=_lss.set_last_exception): """Intercepts and prints ephemeral stacktraces.""" if error and trace: logging.getLogger("dials").error( "\n\neasy_mp crash detected; subprocess trace: ----\n%s%s\n%s\n\n", "".join(trace), error, "-" * 46, ) return intercepted_call(error, trace) if _lss.set_last_exception.__doc__ != _stacktrace_tracer.__doc__: # ensure function is only redirected once _lss.set_last_exception = _stacktrace_tracer Make anyone importing DIALS aware of !2.7 support Warning is only shown on first import, and can be silenced in Python 2.7 with import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") import dials cf. #1175from __future__ import absolute_import, division, print_function import logging import sys import warnings if sys.version_info.major == 2: warnings.warn( "Python 2 is no longer fully supported. Please consider using the DIALS 2.2 release branch. " "For more information on Python 2.7 support please go to https://github.com/dials/dials/issues/1175.", UserWarning, ) logging.getLogger("dials").addHandler(logging.NullHandler()) # Intercept easy_mp exceptions to extract stack traces before they are lost at # the libtbx process boundary/the easy_mp API. In the case of a subprocess # crash we print the subprocess stack trace, which will be most useful for # debugging parallelized sections of DIALS code. import libtbx.scheduling.stacktrace as _lss def _stacktrace_tracer(error, trace, intercepted_call=_lss.set_last_exception): """Intercepts and prints ephemeral stacktraces.""" if error and trace: logging.getLogger("dials").error( "\n\neasy_mp crash detected; subprocess trace: ----\n%s%s\n%s\n\n", "".join(trace), error, "-" * 46, ) return intercepted_call(error, trace) if _lss.set_last_exception.__doc__ != _stacktrace_tracer.__doc__: # ensure function is only redirected once _lss.set_last_exception = _stacktrace_tracer
<commit_before>from __future__ import absolute_import, division, print_function import logging import sys import warnings if sys.version_info.major == 2: warnings.warn( "Python 2 is no longer fully supported. Please consider using the DIALS 2.2 release branch. " "For more information on Python 2.7 support please go to https://github.com/dials/dials/issues/1175.", DeprecationWarning, ) logging.getLogger("dials").addHandler(logging.NullHandler()) # Intercept easy_mp exceptions to extract stack traces before they are lost at # the libtbx process boundary/the easy_mp API. In the case of a subprocess # crash we print the subprocess stack trace, which will be most useful for # debugging parallelized sections of DIALS code. import libtbx.scheduling.stacktrace as _lss def _stacktrace_tracer(error, trace, intercepted_call=_lss.set_last_exception): """Intercepts and prints ephemeral stacktraces.""" if error and trace: logging.getLogger("dials").error( "\n\neasy_mp crash detected; subprocess trace: ----\n%s%s\n%s\n\n", "".join(trace), error, "-" * 46, ) return intercepted_call(error, trace) if _lss.set_last_exception.__doc__ != _stacktrace_tracer.__doc__: # ensure function is only redirected once _lss.set_last_exception = _stacktrace_tracer <commit_msg>Make anyone importing DIALS aware of !2.7 support Warning is only shown on first import, and can be silenced in Python 2.7 with import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") import dials cf. #1175<commit_after>from __future__ import absolute_import, division, print_function import logging import sys import warnings if sys.version_info.major == 2: warnings.warn( "Python 2 is no longer fully supported. Please consider using the DIALS 2.2 release branch. " "For more information on Python 2.7 support please go to https://github.com/dials/dials/issues/1175.", UserWarning, ) logging.getLogger("dials").addHandler(logging.NullHandler()) # Intercept easy_mp exceptions to extract stack traces before they are lost at # the libtbx process boundary/the easy_mp API. In the case of a subprocess # crash we print the subprocess stack trace, which will be most useful for # debugging parallelized sections of DIALS code. import libtbx.scheduling.stacktrace as _lss def _stacktrace_tracer(error, trace, intercepted_call=_lss.set_last_exception): """Intercepts and prints ephemeral stacktraces.""" if error and trace: logging.getLogger("dials").error( "\n\neasy_mp crash detected; subprocess trace: ----\n%s%s\n%s\n\n", "".join(trace), error, "-" * 46, ) return intercepted_call(error, trace) if _lss.set_last_exception.__doc__ != _stacktrace_tracer.__doc__: # ensure function is only redirected once _lss.set_last_exception = _stacktrace_tracer
3c603b177713e8266eb4881d5d325c148d3fb6c1
__init__.py
__init__.py
# -*- coding: utf-8 -*- __about__ = """ This project comes with the bare minimum set of applications and templates to get you started. It includes no extra tabs, only the profile and notices tabs are included by default. From here you can add any extra functionality and applications that you would like. """
# -*- coding: utf-8 -*- __about__ = """ Django Packages is a directory of reusable apps, sites, tools, and more for your Django projects. """
Update to be about Django, not 2010-era Pinax.
Update to be about Django, not 2010-era Pinax.
Python
mit
pydanny/djangopackages,pydanny/djangopackages,QLGu/djangopackages,nanuxbe/djangopackages,nanuxbe/djangopackages,QLGu/djangopackages,pydanny/djangopackages,QLGu/djangopackages,nanuxbe/djangopackages
# -*- coding: utf-8 -*- __about__ = """ This project comes with the bare minimum set of applications and templates to get you started. It includes no extra tabs, only the profile and notices tabs are included by default. From here you can add any extra functionality and applications that you would like. """ Update to be about Django, not 2010-era Pinax.
# -*- coding: utf-8 -*- __about__ = """ Django Packages is a directory of reusable apps, sites, tools, and more for your Django projects. """
<commit_before># -*- coding: utf-8 -*- __about__ = """ This project comes with the bare minimum set of applications and templates to get you started. It includes no extra tabs, only the profile and notices tabs are included by default. From here you can add any extra functionality and applications that you would like. """ <commit_msg>Update to be about Django, not 2010-era Pinax.<commit_after>
# -*- coding: utf-8 -*- __about__ = """ Django Packages is a directory of reusable apps, sites, tools, and more for your Django projects. """
# -*- coding: utf-8 -*- __about__ = """ This project comes with the bare minimum set of applications and templates to get you started. It includes no extra tabs, only the profile and notices tabs are included by default. From here you can add any extra functionality and applications that you would like. """ Update to be about Django, not 2010-era Pinax.# -*- coding: utf-8 -*- __about__ = """ Django Packages is a directory of reusable apps, sites, tools, and more for your Django projects. """
<commit_before># -*- coding: utf-8 -*- __about__ = """ This project comes with the bare minimum set of applications and templates to get you started. It includes no extra tabs, only the profile and notices tabs are included by default. From here you can add any extra functionality and applications that you would like. """ <commit_msg>Update to be about Django, not 2010-era Pinax.<commit_after># -*- coding: utf-8 -*- __about__ = """ Django Packages is a directory of reusable apps, sites, tools, and more for your Django projects. """
59f878ed07dadf0ebc4a8f5fd23412ef21288b2a
__init__.py
__init__.py
import os from flask import Flask, render_template, url_for app = Flask(__name__) @app.route('/') def homepage(): viewer = 'clinician' description = 'This is the clinician version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/patient') def patientpage(): viewer = 'patient' description = 'This is the patient version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/about') def aboutpage(): viewer = 'about' return render_template('about.html', viewer=viewer) if __name__ == '__main__': port = int(os.environ.get('PORT', 5010)) app.run(host='0.0.0.0', port=port) app.run(debug=True)
from __future__ import print_function import os from flask import Flask, render_template, url_for app = Flask(__name__) @app.route('/') def homepage(): viewer = 'clinician' description = 'This is the clinician version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/patient') def patientpage(): viewer = 'patient' description = 'This is the patient version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/about') def aboutpage(): viewer = 'about' return render_template('about.html', viewer=viewer) if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port, debug=True, use_reloader=True)
Fix debugger start up issue + Add python3 print syntax
Fix debugger start up issue + Add python3 print syntax
Python
mit
daviszhou/ascvd-webapp,daviszhou/ascvd-webapp,daviszhou/ascvd-webapp
import os from flask import Flask, render_template, url_for app = Flask(__name__) @app.route('/') def homepage(): viewer = 'clinician' description = 'This is the clinician version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/patient') def patientpage(): viewer = 'patient' description = 'This is the patient version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/about') def aboutpage(): viewer = 'about' return render_template('about.html', viewer=viewer) if __name__ == '__main__': port = int(os.environ.get('PORT', 5010)) app.run(host='0.0.0.0', port=port) app.run(debug=True)Fix debugger start up issue + Add python3 print syntax
from __future__ import print_function import os from flask import Flask, render_template, url_for app = Flask(__name__) @app.route('/') def homepage(): viewer = 'clinician' description = 'This is the clinician version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/patient') def patientpage(): viewer = 'patient' description = 'This is the patient version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/about') def aboutpage(): viewer = 'about' return render_template('about.html', viewer=viewer) if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port, debug=True, use_reloader=True)
<commit_before>import os from flask import Flask, render_template, url_for app = Flask(__name__) @app.route('/') def homepage(): viewer = 'clinician' description = 'This is the clinician version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/patient') def patientpage(): viewer = 'patient' description = 'This is the patient version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/about') def aboutpage(): viewer = 'about' return render_template('about.html', viewer=viewer) if __name__ == '__main__': port = int(os.environ.get('PORT', 5010)) app.run(host='0.0.0.0', port=port) app.run(debug=True)<commit_msg>Fix debugger start up issue + Add python3 print syntax<commit_after>
from __future__ import print_function import os from flask import Flask, render_template, url_for app = Flask(__name__) @app.route('/') def homepage(): viewer = 'clinician' description = 'This is the clinician version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/patient') def patientpage(): viewer = 'patient' description = 'This is the patient version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/about') def aboutpage(): viewer = 'about' return render_template('about.html', viewer=viewer) if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port, debug=True, use_reloader=True)
import os from flask import Flask, render_template, url_for app = Flask(__name__) @app.route('/') def homepage(): viewer = 'clinician' description = 'This is the clinician version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/patient') def patientpage(): viewer = 'patient' description = 'This is the patient version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/about') def aboutpage(): viewer = 'about' return render_template('about.html', viewer=viewer) if __name__ == '__main__': port = int(os.environ.get('PORT', 5010)) app.run(host='0.0.0.0', port=port) app.run(debug=True)Fix debugger start up issue + Add python3 print syntaxfrom __future__ import print_function import os from flask import Flask, render_template, url_for app = Flask(__name__) @app.route('/') def homepage(): viewer = 'clinician' description = 'This is the clinician version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/patient') def patientpage(): viewer = 'patient' description = 'This is the patient version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/about') def aboutpage(): viewer = 'about' return render_template('about.html', viewer=viewer) if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port, debug=True, use_reloader=True)
<commit_before>import os from flask import Flask, render_template, url_for app = Flask(__name__) @app.route('/') def homepage(): viewer = 'clinician' description = 'This is the clinician version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/patient') def patientpage(): viewer = 'patient' description = 'This is the patient version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/about') def aboutpage(): viewer = 'about' return render_template('about.html', viewer=viewer) if __name__ == '__main__': port = int(os.environ.get('PORT', 5010)) app.run(host='0.0.0.0', port=port) app.run(debug=True)<commit_msg>Fix debugger start up issue + Add python3 print syntax<commit_after>from __future__ import print_function import os from flask import Flask, render_template, url_for app = Flask(__name__) @app.route('/') def homepage(): viewer = 'clinician' description = 'This is the clinician version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/patient') def patientpage(): viewer = 'patient' description = 'This is the patient version.' return render_template('index.html', viewer=viewer, description=description) @app.route('/about') def aboutpage(): viewer = 'about' return render_template('about.html', viewer=viewer) if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port, debug=True, use_reloader=True)
db078d7332acf3032346b6642061c6f72c5dce1b
wooey/migrations/0028_add_script_subparser.py
wooey/migrations/0028_add_script_subparser.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2017-04-25 09:25 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import wooey.models.mixins def createParsers(apps, schema_editor): ScriptParameter = apps.get_model('wooey', 'ScriptParameter') ScriptParser = apps.get_model('wooey', 'ScriptParser') for param in ScriptParameter.objects.all(): script_version = param.script_version.last() parser, created = ScriptParser.objects.get_or_create(script_version=script_version) param.parser = parser param.save() class Migration(migrations.Migration): dependencies = [ ('wooey', '0027_parameter_order'), ] operations = [ migrations.CreateModel( name='ScriptParser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=255, default='')), ('script_version', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptVersion')), ], bases=(wooey.models.mixins.WooeyPy2Mixin, models.Model), ), migrations.AddField( model_name='scriptparameter', name='parser', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptParser'), preserve_default=False, ), migrations.RunPython(createParsers), ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2017-04-25 09:25 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import wooey.models.mixins class Migration(migrations.Migration): dependencies = [ ('wooey', '0027_parameter_order'), ] operations = [ migrations.CreateModel( name='ScriptParser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=255, default='')), ('script_version', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptVersion')), ], bases=(wooey.models.mixins.WooeyPy2Mixin, models.Model), ), migrations.AddField( model_name='scriptparameter', name='parser', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptParser'), preserve_default=False, ), ]
Remove runpython to create subparers in 0028
Remove runpython to create subparers in 0028
Python
bsd-3-clause
wooey/Wooey,wooey/Wooey,wooey/Wooey,wooey/Wooey
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2017-04-25 09:25 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import wooey.models.mixins def createParsers(apps, schema_editor): ScriptParameter = apps.get_model('wooey', 'ScriptParameter') ScriptParser = apps.get_model('wooey', 'ScriptParser') for param in ScriptParameter.objects.all(): script_version = param.script_version.last() parser, created = ScriptParser.objects.get_or_create(script_version=script_version) param.parser = parser param.save() class Migration(migrations.Migration): dependencies = [ ('wooey', '0027_parameter_order'), ] operations = [ migrations.CreateModel( name='ScriptParser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=255, default='')), ('script_version', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptVersion')), ], bases=(wooey.models.mixins.WooeyPy2Mixin, models.Model), ), migrations.AddField( model_name='scriptparameter', name='parser', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptParser'), preserve_default=False, ), migrations.RunPython(createParsers), ] Remove runpython to create subparers in 0028
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2017-04-25 09:25 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import wooey.models.mixins class Migration(migrations.Migration): dependencies = [ ('wooey', '0027_parameter_order'), ] operations = [ migrations.CreateModel( name='ScriptParser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=255, default='')), ('script_version', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptVersion')), ], bases=(wooey.models.mixins.WooeyPy2Mixin, models.Model), ), migrations.AddField( model_name='scriptparameter', name='parser', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptParser'), preserve_default=False, ), ]
<commit_before># -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2017-04-25 09:25 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import wooey.models.mixins def createParsers(apps, schema_editor): ScriptParameter = apps.get_model('wooey', 'ScriptParameter') ScriptParser = apps.get_model('wooey', 'ScriptParser') for param in ScriptParameter.objects.all(): script_version = param.script_version.last() parser, created = ScriptParser.objects.get_or_create(script_version=script_version) param.parser = parser param.save() class Migration(migrations.Migration): dependencies = [ ('wooey', '0027_parameter_order'), ] operations = [ migrations.CreateModel( name='ScriptParser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=255, default='')), ('script_version', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptVersion')), ], bases=(wooey.models.mixins.WooeyPy2Mixin, models.Model), ), migrations.AddField( model_name='scriptparameter', name='parser', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptParser'), preserve_default=False, ), migrations.RunPython(createParsers), ] <commit_msg>Remove runpython to create subparers in 0028<commit_after>
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2017-04-25 09:25 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import wooey.models.mixins class Migration(migrations.Migration): dependencies = [ ('wooey', '0027_parameter_order'), ] operations = [ migrations.CreateModel( name='ScriptParser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=255, default='')), ('script_version', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptVersion')), ], bases=(wooey.models.mixins.WooeyPy2Mixin, models.Model), ), migrations.AddField( model_name='scriptparameter', name='parser', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptParser'), preserve_default=False, ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2017-04-25 09:25 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import wooey.models.mixins def createParsers(apps, schema_editor): ScriptParameter = apps.get_model('wooey', 'ScriptParameter') ScriptParser = apps.get_model('wooey', 'ScriptParser') for param in ScriptParameter.objects.all(): script_version = param.script_version.last() parser, created = ScriptParser.objects.get_or_create(script_version=script_version) param.parser = parser param.save() class Migration(migrations.Migration): dependencies = [ ('wooey', '0027_parameter_order'), ] operations = [ migrations.CreateModel( name='ScriptParser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=255, default='')), ('script_version', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptVersion')), ], bases=(wooey.models.mixins.WooeyPy2Mixin, models.Model), ), migrations.AddField( model_name='scriptparameter', name='parser', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptParser'), preserve_default=False, ), migrations.RunPython(createParsers), ] Remove runpython to create subparers in 0028# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2017-04-25 09:25 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import wooey.models.mixins class Migration(migrations.Migration): dependencies = [ ('wooey', '0027_parameter_order'), ] operations = [ migrations.CreateModel( name='ScriptParser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=255, default='')), ('script_version', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptVersion')), ], bases=(wooey.models.mixins.WooeyPy2Mixin, models.Model), ), migrations.AddField( model_name='scriptparameter', name='parser', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptParser'), preserve_default=False, ), ]
<commit_before># -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2017-04-25 09:25 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import wooey.models.mixins def createParsers(apps, schema_editor): ScriptParameter = apps.get_model('wooey', 'ScriptParameter') ScriptParser = apps.get_model('wooey', 'ScriptParser') for param in ScriptParameter.objects.all(): script_version = param.script_version.last() parser, created = ScriptParser.objects.get_or_create(script_version=script_version) param.parser = parser param.save() class Migration(migrations.Migration): dependencies = [ ('wooey', '0027_parameter_order'), ] operations = [ migrations.CreateModel( name='ScriptParser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=255, default='')), ('script_version', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptVersion')), ], bases=(wooey.models.mixins.WooeyPy2Mixin, models.Model), ), migrations.AddField( model_name='scriptparameter', name='parser', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptParser'), preserve_default=False, ), migrations.RunPython(createParsers), ] <commit_msg>Remove runpython to create subparers in 0028<commit_after># -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2017-04-25 09:25 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import wooey.models.mixins class Migration(migrations.Migration): dependencies = [ ('wooey', '0027_parameter_order'), ] operations = [ migrations.CreateModel( name='ScriptParser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=255, default='')), ('script_version', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptVersion')), ], bases=(wooey.models.mixins.WooeyPy2Mixin, models.Model), ), migrations.AddField( model_name='scriptparameter', name='parser', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptParser'), preserve_default=False, ), ]
a9059f075bc1bb48422a3aba564a38071b1acf9f
selectable/forms/base.py
selectable/forms/base.py
from django import forms from django.conf import settings __all__ = ('BaseLookupForm', ) class BaseLookupForm(forms.Form): term = forms.CharField(required=False) limit = forms.IntegerField(required=False, min_value=1) def clean_limit(self): "Ensure given limit is less than default if defined" limit = self.cleaned_data.get('limit', None) if (settings.SELECTABLE_MAX_LIMIT is not None and (not limit or limit > settings.SELECTABLE_MAX_LIMIT)): limit = settings.SELECTABLE_MAX_LIMIT return limit
from django import forms from django.conf import settings __all__ = ('BaseLookupForm', ) class BaseLookupForm(forms.Form): term = forms.CharField(required=False) limit = forms.IntegerField(required=False, min_value=1) page = forms.IntegerField(required=False, min_value=1) def clean_limit(self): "Ensure given limit is less than default if defined" limit = self.cleaned_data.get('limit', None) if (settings.SELECTABLE_MAX_LIMIT is not None and (not limit or limit > settings.SELECTABLE_MAX_LIMIT)): limit = settings.SELECTABLE_MAX_LIMIT return limit def clean_page(self): "Return the first page if no page or invalid number is given." return self.cleaned_data.get('page', 1) or 1
Move page cleaning logic to the form.
Move page cleaning logic to the form. --HG-- branch : result-refactor
Python
bsd-2-clause
mlavin/django-selectable,makinacorpus/django-selectable,affan2/django-selectable,affan2/django-selectable,mlavin/django-selectable,affan2/django-selectable,mlavin/django-selectable,makinacorpus/django-selectable
from django import forms from django.conf import settings __all__ = ('BaseLookupForm', ) class BaseLookupForm(forms.Form): term = forms.CharField(required=False) limit = forms.IntegerField(required=False, min_value=1) def clean_limit(self): "Ensure given limit is less than default if defined" limit = self.cleaned_data.get('limit', None) if (settings.SELECTABLE_MAX_LIMIT is not None and (not limit or limit > settings.SELECTABLE_MAX_LIMIT)): limit = settings.SELECTABLE_MAX_LIMIT return limit Move page cleaning logic to the form. --HG-- branch : result-refactor
from django import forms from django.conf import settings __all__ = ('BaseLookupForm', ) class BaseLookupForm(forms.Form): term = forms.CharField(required=False) limit = forms.IntegerField(required=False, min_value=1) page = forms.IntegerField(required=False, min_value=1) def clean_limit(self): "Ensure given limit is less than default if defined" limit = self.cleaned_data.get('limit', None) if (settings.SELECTABLE_MAX_LIMIT is not None and (not limit or limit > settings.SELECTABLE_MAX_LIMIT)): limit = settings.SELECTABLE_MAX_LIMIT return limit def clean_page(self): "Return the first page if no page or invalid number is given." return self.cleaned_data.get('page', 1) or 1
<commit_before>from django import forms from django.conf import settings __all__ = ('BaseLookupForm', ) class BaseLookupForm(forms.Form): term = forms.CharField(required=False) limit = forms.IntegerField(required=False, min_value=1) def clean_limit(self): "Ensure given limit is less than default if defined" limit = self.cleaned_data.get('limit', None) if (settings.SELECTABLE_MAX_LIMIT is not None and (not limit or limit > settings.SELECTABLE_MAX_LIMIT)): limit = settings.SELECTABLE_MAX_LIMIT return limit <commit_msg>Move page cleaning logic to the form. --HG-- branch : result-refactor<commit_after>
from django import forms from django.conf import settings __all__ = ('BaseLookupForm', ) class BaseLookupForm(forms.Form): term = forms.CharField(required=False) limit = forms.IntegerField(required=False, min_value=1) page = forms.IntegerField(required=False, min_value=1) def clean_limit(self): "Ensure given limit is less than default if defined" limit = self.cleaned_data.get('limit', None) if (settings.SELECTABLE_MAX_LIMIT is not None and (not limit or limit > settings.SELECTABLE_MAX_LIMIT)): limit = settings.SELECTABLE_MAX_LIMIT return limit def clean_page(self): "Return the first page if no page or invalid number is given." return self.cleaned_data.get('page', 1) or 1
from django import forms from django.conf import settings __all__ = ('BaseLookupForm', ) class BaseLookupForm(forms.Form): term = forms.CharField(required=False) limit = forms.IntegerField(required=False, min_value=1) def clean_limit(self): "Ensure given limit is less than default if defined" limit = self.cleaned_data.get('limit', None) if (settings.SELECTABLE_MAX_LIMIT is not None and (not limit or limit > settings.SELECTABLE_MAX_LIMIT)): limit = settings.SELECTABLE_MAX_LIMIT return limit Move page cleaning logic to the form. --HG-- branch : result-refactorfrom django import forms from django.conf import settings __all__ = ('BaseLookupForm', ) class BaseLookupForm(forms.Form): term = forms.CharField(required=False) limit = forms.IntegerField(required=False, min_value=1) page = forms.IntegerField(required=False, min_value=1) def clean_limit(self): "Ensure given limit is less than default if defined" limit = self.cleaned_data.get('limit', None) if (settings.SELECTABLE_MAX_LIMIT is not None and (not limit or limit > settings.SELECTABLE_MAX_LIMIT)): limit = settings.SELECTABLE_MAX_LIMIT return limit def clean_page(self): "Return the first page if no page or invalid number is given." return self.cleaned_data.get('page', 1) or 1
<commit_before>from django import forms from django.conf import settings __all__ = ('BaseLookupForm', ) class BaseLookupForm(forms.Form): term = forms.CharField(required=False) limit = forms.IntegerField(required=False, min_value=1) def clean_limit(self): "Ensure given limit is less than default if defined" limit = self.cleaned_data.get('limit', None) if (settings.SELECTABLE_MAX_LIMIT is not None and (not limit or limit > settings.SELECTABLE_MAX_LIMIT)): limit = settings.SELECTABLE_MAX_LIMIT return limit <commit_msg>Move page cleaning logic to the form. --HG-- branch : result-refactor<commit_after>from django import forms from django.conf import settings __all__ = ('BaseLookupForm', ) class BaseLookupForm(forms.Form): term = forms.CharField(required=False) limit = forms.IntegerField(required=False, min_value=1) page = forms.IntegerField(required=False, min_value=1) def clean_limit(self): "Ensure given limit is less than default if defined" limit = self.cleaned_data.get('limit', None) if (settings.SELECTABLE_MAX_LIMIT is not None and (not limit or limit > settings.SELECTABLE_MAX_LIMIT)): limit = settings.SELECTABLE_MAX_LIMIT return limit def clean_page(self): "Return the first page if no page or invalid number is given." return self.cleaned_data.get('page', 1) or 1
e4509d98e1aeb8a053bb4589eb6806d3e554af5e
topics/lemmatize_folder.py
topics/lemmatize_folder.py
import os import sys import re import subprocess def lemmatize( text ): text = text.encode('utf8') text = re.sub( '[\.,?!:;]' , '' , text ) out = subprocess.check_output( 'module load finnish-process; echo "' + text + '" | finnish-process', shell = True) lemma = '' for line in out.split('\n'): line = line.strip() line = line.split('\t') if len( line ) >= 2: lemma += line[1] + ' ' return lemma ## folder usecase path = sys.argv[1] for file in os.listdir( path ): text = open( path + file ) text = text.readlines() text = map( lambda x: x.strip(), text ) text = ' '.join( text ) lemma = lemmatize( text ) fo = open( path + file + '.lemma', 'w' ) fo.write( lemma ) fo.close()
import os import sys import re import subprocess def lemmatize( text ): text = text.encode('utf8') text = re.sub( '[\.,?!:;]' , '' , text ) out = subprocess.check_output( 'module load finnish-process; echo "' + text + '" | finnish-process', shell = True) lemma = '' for line in out.split('\n'): line = line.strip() line = line.split('\t') if len( line ) >= 2: lemma += line[1] + ' ' return lemma ## read a file and lemmatize it def file( path ): text = open( path ) text = text.readlines() text = map( lambda x: x.strip(), text ) text = ' '.join( text ) lemma = lemmatize( text ) fo = open( path + file + '.lemma', 'w' ) fo.write( lemma ) fo.close() ## read every file in folder and fix based on that def folder( path ): for file in os.listdir( path ): file( path + file ) if '__name__' == '__main__': ## take as many parameters as needed for item in sys.argv[1:]: if( os.path.isdir( item ) ): folder( item ) else: file( item )
Add possibility to lemmatize a folder or a file
Add possibility to lemmatize a folder or a file
Python
mit
HIIT/digivaalit-2015,HIIT/digivaalit-2015,HIIT/digivaalit-2015
import os import sys import re import subprocess def lemmatize( text ): text = text.encode('utf8') text = re.sub( '[\.,?!:;]' , '' , text ) out = subprocess.check_output( 'module load finnish-process; echo "' + text + '" | finnish-process', shell = True) lemma = '' for line in out.split('\n'): line = line.strip() line = line.split('\t') if len( line ) >= 2: lemma += line[1] + ' ' return lemma ## folder usecase path = sys.argv[1] for file in os.listdir( path ): text = open( path + file ) text = text.readlines() text = map( lambda x: x.strip(), text ) text = ' '.join( text ) lemma = lemmatize( text ) fo = open( path + file + '.lemma', 'w' ) fo.write( lemma ) fo.close() Add possibility to lemmatize a folder or a file
import os import sys import re import subprocess def lemmatize( text ): text = text.encode('utf8') text = re.sub( '[\.,?!:;]' , '' , text ) out = subprocess.check_output( 'module load finnish-process; echo "' + text + '" | finnish-process', shell = True) lemma = '' for line in out.split('\n'): line = line.strip() line = line.split('\t') if len( line ) >= 2: lemma += line[1] + ' ' return lemma ## read a file and lemmatize it def file( path ): text = open( path ) text = text.readlines() text = map( lambda x: x.strip(), text ) text = ' '.join( text ) lemma = lemmatize( text ) fo = open( path + file + '.lemma', 'w' ) fo.write( lemma ) fo.close() ## read every file in folder and fix based on that def folder( path ): for file in os.listdir( path ): file( path + file ) if '__name__' == '__main__': ## take as many parameters as needed for item in sys.argv[1:]: if( os.path.isdir( item ) ): folder( item ) else: file( item )
<commit_before>import os import sys import re import subprocess def lemmatize( text ): text = text.encode('utf8') text = re.sub( '[\.,?!:;]' , '' , text ) out = subprocess.check_output( 'module load finnish-process; echo "' + text + '" | finnish-process', shell = True) lemma = '' for line in out.split('\n'): line = line.strip() line = line.split('\t') if len( line ) >= 2: lemma += line[1] + ' ' return lemma ## folder usecase path = sys.argv[1] for file in os.listdir( path ): text = open( path + file ) text = text.readlines() text = map( lambda x: x.strip(), text ) text = ' '.join( text ) lemma = lemmatize( text ) fo = open( path + file + '.lemma', 'w' ) fo.write( lemma ) fo.close() <commit_msg>Add possibility to lemmatize a folder or a file<commit_after>
import os import sys import re import subprocess def lemmatize( text ): text = text.encode('utf8') text = re.sub( '[\.,?!:;]' , '' , text ) out = subprocess.check_output( 'module load finnish-process; echo "' + text + '" | finnish-process', shell = True) lemma = '' for line in out.split('\n'): line = line.strip() line = line.split('\t') if len( line ) >= 2: lemma += line[1] + ' ' return lemma ## read a file and lemmatize it def file( path ): text = open( path ) text = text.readlines() text = map( lambda x: x.strip(), text ) text = ' '.join( text ) lemma = lemmatize( text ) fo = open( path + file + '.lemma', 'w' ) fo.write( lemma ) fo.close() ## read every file in folder and fix based on that def folder( path ): for file in os.listdir( path ): file( path + file ) if '__name__' == '__main__': ## take as many parameters as needed for item in sys.argv[1:]: if( os.path.isdir( item ) ): folder( item ) else: file( item )
import os import sys import re import subprocess def lemmatize( text ): text = text.encode('utf8') text = re.sub( '[\.,?!:;]' , '' , text ) out = subprocess.check_output( 'module load finnish-process; echo "' + text + '" | finnish-process', shell = True) lemma = '' for line in out.split('\n'): line = line.strip() line = line.split('\t') if len( line ) >= 2: lemma += line[1] + ' ' return lemma ## folder usecase path = sys.argv[1] for file in os.listdir( path ): text = open( path + file ) text = text.readlines() text = map( lambda x: x.strip(), text ) text = ' '.join( text ) lemma = lemmatize( text ) fo = open( path + file + '.lemma', 'w' ) fo.write( lemma ) fo.close() Add possibility to lemmatize a folder or a fileimport os import sys import re import subprocess def lemmatize( text ): text = text.encode('utf8') text = re.sub( '[\.,?!:;]' , '' , text ) out = subprocess.check_output( 'module load finnish-process; echo "' + text + '" | finnish-process', shell = True) lemma = '' for line in out.split('\n'): line = line.strip() line = line.split('\t') if len( line ) >= 2: lemma += line[1] + ' ' return lemma ## read a file and lemmatize it def file( path ): text = open( path ) text = text.readlines() text = map( lambda x: x.strip(), text ) text = ' '.join( text ) lemma = lemmatize( text ) fo = open( path + file + '.lemma', 'w' ) fo.write( lemma ) fo.close() ## read every file in folder and fix based on that def folder( path ): for file in os.listdir( path ): file( path + file ) if '__name__' == '__main__': ## take as many parameters as needed for item in sys.argv[1:]: if( os.path.isdir( item ) ): folder( item ) else: file( item )
<commit_before>import os import sys import re import subprocess def lemmatize( text ): text = text.encode('utf8') text = re.sub( '[\.,?!:;]' , '' , text ) out = subprocess.check_output( 'module load finnish-process; echo "' + text + '" | finnish-process', shell = True) lemma = '' for line in out.split('\n'): line = line.strip() line = line.split('\t') if len( line ) >= 2: lemma += line[1] + ' ' return lemma ## folder usecase path = sys.argv[1] for file in os.listdir( path ): text = open( path + file ) text = text.readlines() text = map( lambda x: x.strip(), text ) text = ' '.join( text ) lemma = lemmatize( text ) fo = open( path + file + '.lemma', 'w' ) fo.write( lemma ) fo.close() <commit_msg>Add possibility to lemmatize a folder or a file<commit_after>import os import sys import re import subprocess def lemmatize( text ): text = text.encode('utf8') text = re.sub( '[\.,?!:;]' , '' , text ) out = subprocess.check_output( 'module load finnish-process; echo "' + text + '" | finnish-process', shell = True) lemma = '' for line in out.split('\n'): line = line.strip() line = line.split('\t') if len( line ) >= 2: lemma += line[1] + ' ' return lemma ## read a file and lemmatize it def file( path ): text = open( path ) text = text.readlines() text = map( lambda x: x.strip(), text ) text = ' '.join( text ) lemma = lemmatize( text ) fo = open( path + file + '.lemma', 'w' ) fo.write( lemma ) fo.close() ## read every file in folder and fix based on that def folder( path ): for file in os.listdir( path ): file( path + file ) if '__name__' == '__main__': ## take as many parameters as needed for item in sys.argv[1:]: if( os.path.isdir( item ) ): folder( item ) else: file( item )
793dd2c1ec3d503b8d4325d44bd34b121273144c
jesusmtnez/python/koans/koans/triangle.py
jesusmtnez/python/koans/koans/triangle.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Triangle Project Code. # Triangle analyzes the lengths of the sides of a triangle # (represented by a, b and c) and returns the type of triangle. # # It returns: # 'equilateral' if all sides are equal # 'isosceles' if exactly 2 sides are equal # 'scalene' if no sides are equal # # The tests for this method can be found in # about_triangle_project.py # and # about_triangle_project_2.py # def triangle(a, b, c): # DELETE 'PASS' AND WRITE THIS CODE pass # Error class used in part 2. No need to change this code. class TriangleError(Exception): pass
#!/usr/bin/env python # -*- coding: utf-8 -*- # Triangle Project Code. # Triangle analyzes the lengths of the sides of a triangle # (represented by a, b and c) and returns the type of triangle. # # It returns: # 'equilateral' if all sides are equal # 'isosceles' if exactly 2 sides are equal # 'scalene' if no sides are equal # # The tests for this method can be found in # about_triangle_project.py # and # about_triangle_project_2.py # def triangle(a, b, c): # DELETE 'PASS' AND WRITE THIS CODE # pass if a == b == c: return 'equilateral' elif a == b or a == c or b == c: return 'isosceles' else: return 'scalene' # Error class used in part 2. No need to change this code. class TriangleError(Exception): pass
Complete 'About Triangle Project' koans
[Python] Complete 'About Triangle Project' koans
Python
mit
JesusMtnez/devexperto-challenge,JesusMtnez/devexperto-challenge
#!/usr/bin/env python # -*- coding: utf-8 -*- # Triangle Project Code. # Triangle analyzes the lengths of the sides of a triangle # (represented by a, b and c) and returns the type of triangle. # # It returns: # 'equilateral' if all sides are equal # 'isosceles' if exactly 2 sides are equal # 'scalene' if no sides are equal # # The tests for this method can be found in # about_triangle_project.py # and # about_triangle_project_2.py # def triangle(a, b, c): # DELETE 'PASS' AND WRITE THIS CODE pass # Error class used in part 2. No need to change this code. class TriangleError(Exception): pass [Python] Complete 'About Triangle Project' koans
#!/usr/bin/env python # -*- coding: utf-8 -*- # Triangle Project Code. # Triangle analyzes the lengths of the sides of a triangle # (represented by a, b and c) and returns the type of triangle. # # It returns: # 'equilateral' if all sides are equal # 'isosceles' if exactly 2 sides are equal # 'scalene' if no sides are equal # # The tests for this method can be found in # about_triangle_project.py # and # about_triangle_project_2.py # def triangle(a, b, c): # DELETE 'PASS' AND WRITE THIS CODE # pass if a == b == c: return 'equilateral' elif a == b or a == c or b == c: return 'isosceles' else: return 'scalene' # Error class used in part 2. No need to change this code. class TriangleError(Exception): pass
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- # Triangle Project Code. # Triangle analyzes the lengths of the sides of a triangle # (represented by a, b and c) and returns the type of triangle. # # It returns: # 'equilateral' if all sides are equal # 'isosceles' if exactly 2 sides are equal # 'scalene' if no sides are equal # # The tests for this method can be found in # about_triangle_project.py # and # about_triangle_project_2.py # def triangle(a, b, c): # DELETE 'PASS' AND WRITE THIS CODE pass # Error class used in part 2. No need to change this code. class TriangleError(Exception): pass <commit_msg>[Python] Complete 'About Triangle Project' koans<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- # Triangle Project Code. # Triangle analyzes the lengths of the sides of a triangle # (represented by a, b and c) and returns the type of triangle. # # It returns: # 'equilateral' if all sides are equal # 'isosceles' if exactly 2 sides are equal # 'scalene' if no sides are equal # # The tests for this method can be found in # about_triangle_project.py # and # about_triangle_project_2.py # def triangle(a, b, c): # DELETE 'PASS' AND WRITE THIS CODE # pass if a == b == c: return 'equilateral' elif a == b or a == c or b == c: return 'isosceles' else: return 'scalene' # Error class used in part 2. No need to change this code. class TriangleError(Exception): pass
#!/usr/bin/env python # -*- coding: utf-8 -*- # Triangle Project Code. # Triangle analyzes the lengths of the sides of a triangle # (represented by a, b and c) and returns the type of triangle. # # It returns: # 'equilateral' if all sides are equal # 'isosceles' if exactly 2 sides are equal # 'scalene' if no sides are equal # # The tests for this method can be found in # about_triangle_project.py # and # about_triangle_project_2.py # def triangle(a, b, c): # DELETE 'PASS' AND WRITE THIS CODE pass # Error class used in part 2. No need to change this code. class TriangleError(Exception): pass [Python] Complete 'About Triangle Project' koans#!/usr/bin/env python # -*- coding: utf-8 -*- # Triangle Project Code. # Triangle analyzes the lengths of the sides of a triangle # (represented by a, b and c) and returns the type of triangle. # # It returns: # 'equilateral' if all sides are equal # 'isosceles' if exactly 2 sides are equal # 'scalene' if no sides are equal # # The tests for this method can be found in # about_triangle_project.py # and # about_triangle_project_2.py # def triangle(a, b, c): # DELETE 'PASS' AND WRITE THIS CODE # pass if a == b == c: return 'equilateral' elif a == b or a == c or b == c: return 'isosceles' else: return 'scalene' # Error class used in part 2. No need to change this code. class TriangleError(Exception): pass
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- # Triangle Project Code. # Triangle analyzes the lengths of the sides of a triangle # (represented by a, b and c) and returns the type of triangle. # # It returns: # 'equilateral' if all sides are equal # 'isosceles' if exactly 2 sides are equal # 'scalene' if no sides are equal # # The tests for this method can be found in # about_triangle_project.py # and # about_triangle_project_2.py # def triangle(a, b, c): # DELETE 'PASS' AND WRITE THIS CODE pass # Error class used in part 2. No need to change this code. class TriangleError(Exception): pass <commit_msg>[Python] Complete 'About Triangle Project' koans<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- # Triangle Project Code. # Triangle analyzes the lengths of the sides of a triangle # (represented by a, b and c) and returns the type of triangle. # # It returns: # 'equilateral' if all sides are equal # 'isosceles' if exactly 2 sides are equal # 'scalene' if no sides are equal # # The tests for this method can be found in # about_triangle_project.py # and # about_triangle_project_2.py # def triangle(a, b, c): # DELETE 'PASS' AND WRITE THIS CODE # pass if a == b == c: return 'equilateral' elif a == b or a == c or b == c: return 'isosceles' else: return 'scalene' # Error class used in part 2. No need to change this code. class TriangleError(Exception): pass
31b70c6b08eedc1773d4993e9d9d420d84197b49
corehq/apps/domain/__init__.py
corehq/apps/domain/__init__.py
from django.conf import settings from corehq.preindex import ExtraPreindexPlugin ExtraPreindexPlugin.register('domain', __file__, ( settings.NEW_DOMAINS_DB, settings.NEW_USERS_GROUPS_DB, settings.NEW_FIXTURES_DB, 'meta', )) SHARED_DOMAIN = "<shared>" UNKNOWN_DOMAIN = "<unknown>"
SHARED_DOMAIN = "<shared>" UNKNOWN_DOMAIN = "<unknown>"
Remove domain design doc from irrelevant couch dbs
Remove domain design doc from irrelevant couch dbs It used to contain views that were relevant to users, fixtures, and meta dbs, but these have since been removed. Currently all views in the domain design doc emit absolutely nothing in those domains
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from django.conf import settings from corehq.preindex import ExtraPreindexPlugin ExtraPreindexPlugin.register('domain', __file__, ( settings.NEW_DOMAINS_DB, settings.NEW_USERS_GROUPS_DB, settings.NEW_FIXTURES_DB, 'meta', )) SHARED_DOMAIN = "<shared>" UNKNOWN_DOMAIN = "<unknown>" Remove domain design doc from irrelevant couch dbs It used to contain views that were relevant to users, fixtures, and meta dbs, but these have since been removed. Currently all views in the domain design doc emit absolutely nothing in those domains
SHARED_DOMAIN = "<shared>" UNKNOWN_DOMAIN = "<unknown>"
<commit_before>from django.conf import settings from corehq.preindex import ExtraPreindexPlugin ExtraPreindexPlugin.register('domain', __file__, ( settings.NEW_DOMAINS_DB, settings.NEW_USERS_GROUPS_DB, settings.NEW_FIXTURES_DB, 'meta', )) SHARED_DOMAIN = "<shared>" UNKNOWN_DOMAIN = "<unknown>" <commit_msg>Remove domain design doc from irrelevant couch dbs It used to contain views that were relevant to users, fixtures, and meta dbs, but these have since been removed. Currently all views in the domain design doc emit absolutely nothing in those domains<commit_after>
SHARED_DOMAIN = "<shared>" UNKNOWN_DOMAIN = "<unknown>"
from django.conf import settings from corehq.preindex import ExtraPreindexPlugin ExtraPreindexPlugin.register('domain', __file__, ( settings.NEW_DOMAINS_DB, settings.NEW_USERS_GROUPS_DB, settings.NEW_FIXTURES_DB, 'meta', )) SHARED_DOMAIN = "<shared>" UNKNOWN_DOMAIN = "<unknown>" Remove domain design doc from irrelevant couch dbs It used to contain views that were relevant to users, fixtures, and meta dbs, but these have since been removed. Currently all views in the domain design doc emit absolutely nothing in those domainsSHARED_DOMAIN = "<shared>" UNKNOWN_DOMAIN = "<unknown>"
<commit_before>from django.conf import settings from corehq.preindex import ExtraPreindexPlugin ExtraPreindexPlugin.register('domain', __file__, ( settings.NEW_DOMAINS_DB, settings.NEW_USERS_GROUPS_DB, settings.NEW_FIXTURES_DB, 'meta', )) SHARED_DOMAIN = "<shared>" UNKNOWN_DOMAIN = "<unknown>" <commit_msg>Remove domain design doc from irrelevant couch dbs It used to contain views that were relevant to users, fixtures, and meta dbs, but these have since been removed. Currently all views in the domain design doc emit absolutely nothing in those domains<commit_after>SHARED_DOMAIN = "<shared>" UNKNOWN_DOMAIN = "<unknown>"
818985feafcb0ce2b90dccaa41f6443c27bc1090
django_enumfield/tests/test_validators.py
django_enumfield/tests/test_validators.py
import unittest from django.db import models from django_enumfield.exceptions import InvalidStatusOperationError from django_enumfield.tests.models import BeerStyle, Person, PersonStatus from django_enumfield.validators import validate_available_choice class ValidatorTest(unittest.TestCase): def test_validate_available_choice_1(self): """Test passing a value non convertable to an int raises an InvalidStatusOperationError """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, *(BeerStyle, "Not an int") ) def test_validate_available_choice_2(self): """Test passing an int as a string validation """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, BeerStyle, str(BeerStyle.LAGER.value), ) def test_validate_available_choice_3(self): """Test passing an int validation """ self.assertIsNone(validate_available_choice(BeerStyle, BeerStyle.LAGER)) def test_validate_by_setting(self): person = Person() with self.assertRaises(InvalidStatusOperationError): person.status = PersonStatus.UNBORN with self.assertRaises(InvalidStatusOperationError): person.status = models.NOT_PROVIDED
import unittest from django.db import models from django_enumfield.exceptions import InvalidStatusOperationError from django_enumfield.tests.models import BeerStyle, Person, PersonStatus from django_enumfield.validators import validate_available_choice class ValidatorTest(unittest.TestCase): def test_validate_available_choice_1(self): """Test passing a value non convertible to an int raises an InvalidStatusOperationError """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, *(BeerStyle, "Not an int") ) def test_validate_available_choice_2(self): """Test passing an int as a string validation """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, BeerStyle, str(BeerStyle.LAGER.value), ) def test_validate_available_choice_3(self): """Test passing an int validation """ self.assertIsNone(validate_available_choice(BeerStyle, BeerStyle.LAGER)) def test_validate_by_setting(self): person = Person() with self.assertRaises(InvalidStatusOperationError): person.status = PersonStatus.UNBORN with self.assertRaises(InvalidStatusOperationError): person.status = models.NOT_PROVIDED
Fix simple typo, convertable -> convertible
docs: Fix simple typo, convertable -> convertible There is a small typo in django_enumfield/tests/test_validators.py. Should read `convertible` rather than `convertable`.
Python
mit
5monkeys/django-enumfield
import unittest from django.db import models from django_enumfield.exceptions import InvalidStatusOperationError from django_enumfield.tests.models import BeerStyle, Person, PersonStatus from django_enumfield.validators import validate_available_choice class ValidatorTest(unittest.TestCase): def test_validate_available_choice_1(self): """Test passing a value non convertable to an int raises an InvalidStatusOperationError """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, *(BeerStyle, "Not an int") ) def test_validate_available_choice_2(self): """Test passing an int as a string validation """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, BeerStyle, str(BeerStyle.LAGER.value), ) def test_validate_available_choice_3(self): """Test passing an int validation """ self.assertIsNone(validate_available_choice(BeerStyle, BeerStyle.LAGER)) def test_validate_by_setting(self): person = Person() with self.assertRaises(InvalidStatusOperationError): person.status = PersonStatus.UNBORN with self.assertRaises(InvalidStatusOperationError): person.status = models.NOT_PROVIDED docs: Fix simple typo, convertable -> convertible There is a small typo in django_enumfield/tests/test_validators.py. Should read `convertible` rather than `convertable`.
import unittest from django.db import models from django_enumfield.exceptions import InvalidStatusOperationError from django_enumfield.tests.models import BeerStyle, Person, PersonStatus from django_enumfield.validators import validate_available_choice class ValidatorTest(unittest.TestCase): def test_validate_available_choice_1(self): """Test passing a value non convertible to an int raises an InvalidStatusOperationError """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, *(BeerStyle, "Not an int") ) def test_validate_available_choice_2(self): """Test passing an int as a string validation """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, BeerStyle, str(BeerStyle.LAGER.value), ) def test_validate_available_choice_3(self): """Test passing an int validation """ self.assertIsNone(validate_available_choice(BeerStyle, BeerStyle.LAGER)) def test_validate_by_setting(self): person = Person() with self.assertRaises(InvalidStatusOperationError): person.status = PersonStatus.UNBORN with self.assertRaises(InvalidStatusOperationError): person.status = models.NOT_PROVIDED
<commit_before>import unittest from django.db import models from django_enumfield.exceptions import InvalidStatusOperationError from django_enumfield.tests.models import BeerStyle, Person, PersonStatus from django_enumfield.validators import validate_available_choice class ValidatorTest(unittest.TestCase): def test_validate_available_choice_1(self): """Test passing a value non convertable to an int raises an InvalidStatusOperationError """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, *(BeerStyle, "Not an int") ) def test_validate_available_choice_2(self): """Test passing an int as a string validation """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, BeerStyle, str(BeerStyle.LAGER.value), ) def test_validate_available_choice_3(self): """Test passing an int validation """ self.assertIsNone(validate_available_choice(BeerStyle, BeerStyle.LAGER)) def test_validate_by_setting(self): person = Person() with self.assertRaises(InvalidStatusOperationError): person.status = PersonStatus.UNBORN with self.assertRaises(InvalidStatusOperationError): person.status = models.NOT_PROVIDED <commit_msg>docs: Fix simple typo, convertable -> convertible There is a small typo in django_enumfield/tests/test_validators.py. Should read `convertible` rather than `convertable`.<commit_after>
import unittest from django.db import models from django_enumfield.exceptions import InvalidStatusOperationError from django_enumfield.tests.models import BeerStyle, Person, PersonStatus from django_enumfield.validators import validate_available_choice class ValidatorTest(unittest.TestCase): def test_validate_available_choice_1(self): """Test passing a value non convertible to an int raises an InvalidStatusOperationError """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, *(BeerStyle, "Not an int") ) def test_validate_available_choice_2(self): """Test passing an int as a string validation """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, BeerStyle, str(BeerStyle.LAGER.value), ) def test_validate_available_choice_3(self): """Test passing an int validation """ self.assertIsNone(validate_available_choice(BeerStyle, BeerStyle.LAGER)) def test_validate_by_setting(self): person = Person() with self.assertRaises(InvalidStatusOperationError): person.status = PersonStatus.UNBORN with self.assertRaises(InvalidStatusOperationError): person.status = models.NOT_PROVIDED
import unittest from django.db import models from django_enumfield.exceptions import InvalidStatusOperationError from django_enumfield.tests.models import BeerStyle, Person, PersonStatus from django_enumfield.validators import validate_available_choice class ValidatorTest(unittest.TestCase): def test_validate_available_choice_1(self): """Test passing a value non convertable to an int raises an InvalidStatusOperationError """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, *(BeerStyle, "Not an int") ) def test_validate_available_choice_2(self): """Test passing an int as a string validation """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, BeerStyle, str(BeerStyle.LAGER.value), ) def test_validate_available_choice_3(self): """Test passing an int validation """ self.assertIsNone(validate_available_choice(BeerStyle, BeerStyle.LAGER)) def test_validate_by_setting(self): person = Person() with self.assertRaises(InvalidStatusOperationError): person.status = PersonStatus.UNBORN with self.assertRaises(InvalidStatusOperationError): person.status = models.NOT_PROVIDED docs: Fix simple typo, convertable -> convertible There is a small typo in django_enumfield/tests/test_validators.py. Should read `convertible` rather than `convertable`.import unittest from django.db import models from django_enumfield.exceptions import InvalidStatusOperationError from django_enumfield.tests.models import BeerStyle, Person, PersonStatus from django_enumfield.validators import validate_available_choice class ValidatorTest(unittest.TestCase): def test_validate_available_choice_1(self): """Test passing a value non convertible to an int raises an InvalidStatusOperationError """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, *(BeerStyle, "Not an int") ) def test_validate_available_choice_2(self): """Test passing an int as a string validation """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, BeerStyle, str(BeerStyle.LAGER.value), ) def test_validate_available_choice_3(self): """Test passing an int validation """ self.assertIsNone(validate_available_choice(BeerStyle, BeerStyle.LAGER)) def test_validate_by_setting(self): person = Person() with self.assertRaises(InvalidStatusOperationError): person.status = PersonStatus.UNBORN with self.assertRaises(InvalidStatusOperationError): person.status = models.NOT_PROVIDED
<commit_before>import unittest from django.db import models from django_enumfield.exceptions import InvalidStatusOperationError from django_enumfield.tests.models import BeerStyle, Person, PersonStatus from django_enumfield.validators import validate_available_choice class ValidatorTest(unittest.TestCase): def test_validate_available_choice_1(self): """Test passing a value non convertable to an int raises an InvalidStatusOperationError """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, *(BeerStyle, "Not an int") ) def test_validate_available_choice_2(self): """Test passing an int as a string validation """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, BeerStyle, str(BeerStyle.LAGER.value), ) def test_validate_available_choice_3(self): """Test passing an int validation """ self.assertIsNone(validate_available_choice(BeerStyle, BeerStyle.LAGER)) def test_validate_by_setting(self): person = Person() with self.assertRaises(InvalidStatusOperationError): person.status = PersonStatus.UNBORN with self.assertRaises(InvalidStatusOperationError): person.status = models.NOT_PROVIDED <commit_msg>docs: Fix simple typo, convertable -> convertible There is a small typo in django_enumfield/tests/test_validators.py. Should read `convertible` rather than `convertable`.<commit_after>import unittest from django.db import models from django_enumfield.exceptions import InvalidStatusOperationError from django_enumfield.tests.models import BeerStyle, Person, PersonStatus from django_enumfield.validators import validate_available_choice class ValidatorTest(unittest.TestCase): def test_validate_available_choice_1(self): """Test passing a value non convertible to an int raises an InvalidStatusOperationError """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, *(BeerStyle, "Not an int") ) def test_validate_available_choice_2(self): """Test passing an int as a string validation """ self.assertRaises( InvalidStatusOperationError, validate_available_choice, BeerStyle, str(BeerStyle.LAGER.value), ) def test_validate_available_choice_3(self): """Test passing an int validation """ self.assertIsNone(validate_available_choice(BeerStyle, BeerStyle.LAGER)) def test_validate_by_setting(self): person = Person() with self.assertRaises(InvalidStatusOperationError): person.status = PersonStatus.UNBORN with self.assertRaises(InvalidStatusOperationError): person.status = models.NOT_PROVIDED
b8594bbe5375e20503d641dde8c4c0ef2cd85d3e
spec_cleaner/fileutils.py
spec_cleaner/fileutils.py
# vim: set ts=4 sw=4 et: coding=UTF-8 import os from .rpmexception import RpmException class FileUtils(object): """ Class working with file operations. Read/write.. """ # file variable f = None def open_datafile(self, name): """ Function to open data files. Used all around so kept glob here for importing. """ try: _file = open('{0}/../data/{1}'.format(os.path.dirname(os.path.realpath(__file__)), name), 'r') except IOError: # the .. is appended as we are in spec_cleaner sub_folder try: _file = open('/usr/share/spec-cleaner/{0}'.format(name), 'r') except IOError as error: raise RpmException(error.strerror) self.f = _file def open(self, name, mode): """ Function to open regular files with exception handling. """ try: _file = open(name, mode) except IOError as error: raise RpmException(error.strerror) self.f = _file def close(self): """ Just wrapper for closing the file """ if self.f: self.f.close() self.f = None def __del__(self): self.close() self.f = None
# vim: set ts=4 sw=4 et: coding=UTF-8 import os from .rpmexception import RpmException class FileUtils(object): """ Class working with file operations. Read/write.. """ # file variable f = None def open_datafile(self, name): """ Function to open data files. Used all around so kept glob here for importing. """ try: # the .. is appended as we are in spec_cleaner sub_folder _file = open('{0}/../data/{1}'.format(os.path.dirname(os.path.realpath(__file__)), name), 'r') except IOError: # try venv structure try: _file = open('{0}/../usr/share/spec-cleaner/{1}'.format( os.path.dirname(os.path.realpath(__file__)), name), 'r') except IOError as error: # try system dir try: _file = open('/usr/share/spec-cleaner/{0}'.format(name), 'r') except IOError as error: raise RpmException(error.strerror) self.f = _file def open(self, name, mode): """ Function to open regular files with exception handling. """ try: _file = open(name, mode) except IOError as error: raise RpmException(error.strerror) self.f = _file def close(self): """ Just wrapper for closing the file """ if self.f: self.f.close() self.f = None def __del__(self): self.close() self.f = None
Check an extra possible data dir when installing in a venv
Check an extra possible data dir when installing in a venv When installing spec-cleaner in a virtual env, the data files (i.e. "excludes-bracketing.txt") are available in a different directory. Also check this directory. Fixes #128
Python
bsd-3-clause
plusky/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner
# vim: set ts=4 sw=4 et: coding=UTF-8 import os from .rpmexception import RpmException class FileUtils(object): """ Class working with file operations. Read/write.. """ # file variable f = None def open_datafile(self, name): """ Function to open data files. Used all around so kept glob here for importing. """ try: _file = open('{0}/../data/{1}'.format(os.path.dirname(os.path.realpath(__file__)), name), 'r') except IOError: # the .. is appended as we are in spec_cleaner sub_folder try: _file = open('/usr/share/spec-cleaner/{0}'.format(name), 'r') except IOError as error: raise RpmException(error.strerror) self.f = _file def open(self, name, mode): """ Function to open regular files with exception handling. """ try: _file = open(name, mode) except IOError as error: raise RpmException(error.strerror) self.f = _file def close(self): """ Just wrapper for closing the file """ if self.f: self.f.close() self.f = None def __del__(self): self.close() self.f = None Check an extra possible data dir when installing in a venv When installing spec-cleaner in a virtual env, the data files (i.e. "excludes-bracketing.txt") are available in a different directory. Also check this directory. Fixes #128
# vim: set ts=4 sw=4 et: coding=UTF-8 import os from .rpmexception import RpmException class FileUtils(object): """ Class working with file operations. Read/write.. """ # file variable f = None def open_datafile(self, name): """ Function to open data files. Used all around so kept glob here for importing. """ try: # the .. is appended as we are in spec_cleaner sub_folder _file = open('{0}/../data/{1}'.format(os.path.dirname(os.path.realpath(__file__)), name), 'r') except IOError: # try venv structure try: _file = open('{0}/../usr/share/spec-cleaner/{1}'.format( os.path.dirname(os.path.realpath(__file__)), name), 'r') except IOError as error: # try system dir try: _file = open('/usr/share/spec-cleaner/{0}'.format(name), 'r') except IOError as error: raise RpmException(error.strerror) self.f = _file def open(self, name, mode): """ Function to open regular files with exception handling. """ try: _file = open(name, mode) except IOError as error: raise RpmException(error.strerror) self.f = _file def close(self): """ Just wrapper for closing the file """ if self.f: self.f.close() self.f = None def __del__(self): self.close() self.f = None
<commit_before># vim: set ts=4 sw=4 et: coding=UTF-8 import os from .rpmexception import RpmException class FileUtils(object): """ Class working with file operations. Read/write.. """ # file variable f = None def open_datafile(self, name): """ Function to open data files. Used all around so kept glob here for importing. """ try: _file = open('{0}/../data/{1}'.format(os.path.dirname(os.path.realpath(__file__)), name), 'r') except IOError: # the .. is appended as we are in spec_cleaner sub_folder try: _file = open('/usr/share/spec-cleaner/{0}'.format(name), 'r') except IOError as error: raise RpmException(error.strerror) self.f = _file def open(self, name, mode): """ Function to open regular files with exception handling. """ try: _file = open(name, mode) except IOError as error: raise RpmException(error.strerror) self.f = _file def close(self): """ Just wrapper for closing the file """ if self.f: self.f.close() self.f = None def __del__(self): self.close() self.f = None <commit_msg>Check an extra possible data dir when installing in a venv When installing spec-cleaner in a virtual env, the data files (i.e. "excludes-bracketing.txt") are available in a different directory. Also check this directory. Fixes #128<commit_after>
# vim: set ts=4 sw=4 et: coding=UTF-8 import os from .rpmexception import RpmException class FileUtils(object): """ Class working with file operations. Read/write.. """ # file variable f = None def open_datafile(self, name): """ Function to open data files. Used all around so kept glob here for importing. """ try: # the .. is appended as we are in spec_cleaner sub_folder _file = open('{0}/../data/{1}'.format(os.path.dirname(os.path.realpath(__file__)), name), 'r') except IOError: # try venv structure try: _file = open('{0}/../usr/share/spec-cleaner/{1}'.format( os.path.dirname(os.path.realpath(__file__)), name), 'r') except IOError as error: # try system dir try: _file = open('/usr/share/spec-cleaner/{0}'.format(name), 'r') except IOError as error: raise RpmException(error.strerror) self.f = _file def open(self, name, mode): """ Function to open regular files with exception handling. """ try: _file = open(name, mode) except IOError as error: raise RpmException(error.strerror) self.f = _file def close(self): """ Just wrapper for closing the file """ if self.f: self.f.close() self.f = None def __del__(self): self.close() self.f = None
# vim: set ts=4 sw=4 et: coding=UTF-8 import os from .rpmexception import RpmException class FileUtils(object): """ Class working with file operations. Read/write.. """ # file variable f = None def open_datafile(self, name): """ Function to open data files. Used all around so kept glob here for importing. """ try: _file = open('{0}/../data/{1}'.format(os.path.dirname(os.path.realpath(__file__)), name), 'r') except IOError: # the .. is appended as we are in spec_cleaner sub_folder try: _file = open('/usr/share/spec-cleaner/{0}'.format(name), 'r') except IOError as error: raise RpmException(error.strerror) self.f = _file def open(self, name, mode): """ Function to open regular files with exception handling. """ try: _file = open(name, mode) except IOError as error: raise RpmException(error.strerror) self.f = _file def close(self): """ Just wrapper for closing the file """ if self.f: self.f.close() self.f = None def __del__(self): self.close() self.f = None Check an extra possible data dir when installing in a venv When installing spec-cleaner in a virtual env, the data files (i.e. "excludes-bracketing.txt") are available in a different directory. Also check this directory. Fixes #128# vim: set ts=4 sw=4 et: coding=UTF-8 import os from .rpmexception import RpmException class FileUtils(object): """ Class working with file operations. Read/write.. """ # file variable f = None def open_datafile(self, name): """ Function to open data files. Used all around so kept glob here for importing. """ try: # the .. is appended as we are in spec_cleaner sub_folder _file = open('{0}/../data/{1}'.format(os.path.dirname(os.path.realpath(__file__)), name), 'r') except IOError: # try venv structure try: _file = open('{0}/../usr/share/spec-cleaner/{1}'.format( os.path.dirname(os.path.realpath(__file__)), name), 'r') except IOError as error: # try system dir try: _file = open('/usr/share/spec-cleaner/{0}'.format(name), 'r') except IOError as error: raise RpmException(error.strerror) self.f = _file def open(self, name, mode): """ Function to open regular files with exception handling. """ try: _file = open(name, mode) except IOError as error: raise RpmException(error.strerror) self.f = _file def close(self): """ Just wrapper for closing the file """ if self.f: self.f.close() self.f = None def __del__(self): self.close() self.f = None
<commit_before># vim: set ts=4 sw=4 et: coding=UTF-8 import os from .rpmexception import RpmException class FileUtils(object): """ Class working with file operations. Read/write.. """ # file variable f = None def open_datafile(self, name): """ Function to open data files. Used all around so kept glob here for importing. """ try: _file = open('{0}/../data/{1}'.format(os.path.dirname(os.path.realpath(__file__)), name), 'r') except IOError: # the .. is appended as we are in spec_cleaner sub_folder try: _file = open('/usr/share/spec-cleaner/{0}'.format(name), 'r') except IOError as error: raise RpmException(error.strerror) self.f = _file def open(self, name, mode): """ Function to open regular files with exception handling. """ try: _file = open(name, mode) except IOError as error: raise RpmException(error.strerror) self.f = _file def close(self): """ Just wrapper for closing the file """ if self.f: self.f.close() self.f = None def __del__(self): self.close() self.f = None <commit_msg>Check an extra possible data dir when installing in a venv When installing spec-cleaner in a virtual env, the data files (i.e. "excludes-bracketing.txt") are available in a different directory. Also check this directory. Fixes #128<commit_after># vim: set ts=4 sw=4 et: coding=UTF-8 import os from .rpmexception import RpmException class FileUtils(object): """ Class working with file operations. Read/write.. """ # file variable f = None def open_datafile(self, name): """ Function to open data files. Used all around so kept glob here for importing. """ try: # the .. is appended as we are in spec_cleaner sub_folder _file = open('{0}/../data/{1}'.format(os.path.dirname(os.path.realpath(__file__)), name), 'r') except IOError: # try venv structure try: _file = open('{0}/../usr/share/spec-cleaner/{1}'.format( os.path.dirname(os.path.realpath(__file__)), name), 'r') except IOError as error: # try system dir try: _file = open('/usr/share/spec-cleaner/{0}'.format(name), 'r') except IOError as error: raise RpmException(error.strerror) self.f = _file def open(self, name, mode): """ Function to open regular files with exception handling. """ try: _file = open(name, mode) except IOError as error: raise RpmException(error.strerror) self.f = _file def close(self): """ Just wrapper for closing the file """ if self.f: self.f.close() self.f = None def __del__(self): self.close() self.f = None
7ab08a4524e7ed4dd0d465a7ad68e7802beebd2f
libs/globalvars.py
libs/globalvars.py
import os import re import sublime from .logger import * # get the directory path to this file; LIBS_DIR = os.path.dirname(os.path.abspath(__file__)) PLUGIN_DIR = os.path.dirname(LIBS_DIR) PACKAGES_DIR = os.path.dirname(PLUGIN_DIR) PLUGIN_NAME = os.path.basename(PLUGIN_DIR) # only Sublime Text 3 build after 3072 support tooltip TOOLTIP_SUPPORT = int(sublime.version()) >= 3072 # determine if the host is sublime text 2 IS_ST2 = int(sublime.version()) < 3000 # detect if quick info is available for symbol SUBLIME_WORD_MASK = 515 # set logging levels LOG_FILE_LEVEL = logging.WARN LOG_CONSOLE_LEVEL = logging.DEBUG NON_BLANK_LINE_PATTERN = re.compile("[\S]+") VALID_COMPLETION_ID_PATTERN = re.compile("[a-zA-Z_$\.][\w$\.]*\Z") # idle time length in millisecond IDLE_TIME_LENGTH = 20
import os import re import sublime from .logger import * # get the directory path to this file; LIBS_DIR = os.path.dirname(os.path.abspath(__file__)) PLUGIN_DIR = os.path.dirname(LIBS_DIR) PACKAGES_DIR = os.path.dirname(PLUGIN_DIR) PLUGIN_NAME = os.path.basename(PLUGIN_DIR) # only Sublime Text 3 build after 3072 support tooltip TOOLTIP_SUPPORT = int(sublime.version()) >= 3072 # determine if the host is sublime text 2 IS_ST2 = int(sublime.version()) < 3000 # detect if quick info is available for symbol SUBLIME_WORD_MASK = 515 # set logging levels LOG_FILE_LEVEL = logging.WARN LOG_CONSOLE_LEVEL = logging.WARN NON_BLANK_LINE_PATTERN = re.compile("[\S]+") VALID_COMPLETION_ID_PATTERN = re.compile("[a-zA-Z_$\.][\w$\.]*\Z") # idle time length in millisecond IDLE_TIME_LENGTH = 20
Change the console log level back to WARN
Change the console log level back to WARN
Python
apache-2.0
zhengbli/TypeScript-Sublime-Plugin,fongandrew/TypeScript-Sublime-JSX-Plugin,hoanhtien/TypeScript-Sublime-Plugin,Microsoft/TypeScript-Sublime-Plugin,hoanhtien/TypeScript-Sublime-Plugin,Microsoft/TypeScript-Sublime-Plugin,RyanCavanaugh/TypeScript-Sublime-Plugin,Microsoft/TypeScript-Sublime-Plugin,zhengbli/TypeScript-Sublime-Plugin,RyanCavanaugh/TypeScript-Sublime-Plugin,kungfusheep/TypeScript-Sublime-Plugin,hoanhtien/TypeScript-Sublime-Plugin,kungfusheep/TypeScript-Sublime-Plugin,kungfusheep/TypeScript-Sublime-Plugin,fongandrew/TypeScript-Sublime-JSX-Plugin,zhengbli/TypeScript-Sublime-Plugin,RyanCavanaugh/TypeScript-Sublime-Plugin,fongandrew/TypeScript-Sublime-JSX-Plugin
import os import re import sublime from .logger import * # get the directory path to this file; LIBS_DIR = os.path.dirname(os.path.abspath(__file__)) PLUGIN_DIR = os.path.dirname(LIBS_DIR) PACKAGES_DIR = os.path.dirname(PLUGIN_DIR) PLUGIN_NAME = os.path.basename(PLUGIN_DIR) # only Sublime Text 3 build after 3072 support tooltip TOOLTIP_SUPPORT = int(sublime.version()) >= 3072 # determine if the host is sublime text 2 IS_ST2 = int(sublime.version()) < 3000 # detect if quick info is available for symbol SUBLIME_WORD_MASK = 515 # set logging levels LOG_FILE_LEVEL = logging.WARN LOG_CONSOLE_LEVEL = logging.DEBUG NON_BLANK_LINE_PATTERN = re.compile("[\S]+") VALID_COMPLETION_ID_PATTERN = re.compile("[a-zA-Z_$\.][\w$\.]*\Z") # idle time length in millisecond IDLE_TIME_LENGTH = 20Change the console log level back to WARN
import os import re import sublime from .logger import * # get the directory path to this file; LIBS_DIR = os.path.dirname(os.path.abspath(__file__)) PLUGIN_DIR = os.path.dirname(LIBS_DIR) PACKAGES_DIR = os.path.dirname(PLUGIN_DIR) PLUGIN_NAME = os.path.basename(PLUGIN_DIR) # only Sublime Text 3 build after 3072 support tooltip TOOLTIP_SUPPORT = int(sublime.version()) >= 3072 # determine if the host is sublime text 2 IS_ST2 = int(sublime.version()) < 3000 # detect if quick info is available for symbol SUBLIME_WORD_MASK = 515 # set logging levels LOG_FILE_LEVEL = logging.WARN LOG_CONSOLE_LEVEL = logging.WARN NON_BLANK_LINE_PATTERN = re.compile("[\S]+") VALID_COMPLETION_ID_PATTERN = re.compile("[a-zA-Z_$\.][\w$\.]*\Z") # idle time length in millisecond IDLE_TIME_LENGTH = 20
<commit_before>import os import re import sublime from .logger import * # get the directory path to this file; LIBS_DIR = os.path.dirname(os.path.abspath(__file__)) PLUGIN_DIR = os.path.dirname(LIBS_DIR) PACKAGES_DIR = os.path.dirname(PLUGIN_DIR) PLUGIN_NAME = os.path.basename(PLUGIN_DIR) # only Sublime Text 3 build after 3072 support tooltip TOOLTIP_SUPPORT = int(sublime.version()) >= 3072 # determine if the host is sublime text 2 IS_ST2 = int(sublime.version()) < 3000 # detect if quick info is available for symbol SUBLIME_WORD_MASK = 515 # set logging levels LOG_FILE_LEVEL = logging.WARN LOG_CONSOLE_LEVEL = logging.DEBUG NON_BLANK_LINE_PATTERN = re.compile("[\S]+") VALID_COMPLETION_ID_PATTERN = re.compile("[a-zA-Z_$\.][\w$\.]*\Z") # idle time length in millisecond IDLE_TIME_LENGTH = 20<commit_msg>Change the console log level back to WARN<commit_after>
import os import re import sublime from .logger import * # get the directory path to this file; LIBS_DIR = os.path.dirname(os.path.abspath(__file__)) PLUGIN_DIR = os.path.dirname(LIBS_DIR) PACKAGES_DIR = os.path.dirname(PLUGIN_DIR) PLUGIN_NAME = os.path.basename(PLUGIN_DIR) # only Sublime Text 3 build after 3072 support tooltip TOOLTIP_SUPPORT = int(sublime.version()) >= 3072 # determine if the host is sublime text 2 IS_ST2 = int(sublime.version()) < 3000 # detect if quick info is available for symbol SUBLIME_WORD_MASK = 515 # set logging levels LOG_FILE_LEVEL = logging.WARN LOG_CONSOLE_LEVEL = logging.WARN NON_BLANK_LINE_PATTERN = re.compile("[\S]+") VALID_COMPLETION_ID_PATTERN = re.compile("[a-zA-Z_$\.][\w$\.]*\Z") # idle time length in millisecond IDLE_TIME_LENGTH = 20
import os import re import sublime from .logger import * # get the directory path to this file; LIBS_DIR = os.path.dirname(os.path.abspath(__file__)) PLUGIN_DIR = os.path.dirname(LIBS_DIR) PACKAGES_DIR = os.path.dirname(PLUGIN_DIR) PLUGIN_NAME = os.path.basename(PLUGIN_DIR) # only Sublime Text 3 build after 3072 support tooltip TOOLTIP_SUPPORT = int(sublime.version()) >= 3072 # determine if the host is sublime text 2 IS_ST2 = int(sublime.version()) < 3000 # detect if quick info is available for symbol SUBLIME_WORD_MASK = 515 # set logging levels LOG_FILE_LEVEL = logging.WARN LOG_CONSOLE_LEVEL = logging.DEBUG NON_BLANK_LINE_PATTERN = re.compile("[\S]+") VALID_COMPLETION_ID_PATTERN = re.compile("[a-zA-Z_$\.][\w$\.]*\Z") # idle time length in millisecond IDLE_TIME_LENGTH = 20Change the console log level back to WARNimport os import re import sublime from .logger import * # get the directory path to this file; LIBS_DIR = os.path.dirname(os.path.abspath(__file__)) PLUGIN_DIR = os.path.dirname(LIBS_DIR) PACKAGES_DIR = os.path.dirname(PLUGIN_DIR) PLUGIN_NAME = os.path.basename(PLUGIN_DIR) # only Sublime Text 3 build after 3072 support tooltip TOOLTIP_SUPPORT = int(sublime.version()) >= 3072 # determine if the host is sublime text 2 IS_ST2 = int(sublime.version()) < 3000 # detect if quick info is available for symbol SUBLIME_WORD_MASK = 515 # set logging levels LOG_FILE_LEVEL = logging.WARN LOG_CONSOLE_LEVEL = logging.WARN NON_BLANK_LINE_PATTERN = re.compile("[\S]+") VALID_COMPLETION_ID_PATTERN = re.compile("[a-zA-Z_$\.][\w$\.]*\Z") # idle time length in millisecond IDLE_TIME_LENGTH = 20
<commit_before>import os import re import sublime from .logger import * # get the directory path to this file; LIBS_DIR = os.path.dirname(os.path.abspath(__file__)) PLUGIN_DIR = os.path.dirname(LIBS_DIR) PACKAGES_DIR = os.path.dirname(PLUGIN_DIR) PLUGIN_NAME = os.path.basename(PLUGIN_DIR) # only Sublime Text 3 build after 3072 support tooltip TOOLTIP_SUPPORT = int(sublime.version()) >= 3072 # determine if the host is sublime text 2 IS_ST2 = int(sublime.version()) < 3000 # detect if quick info is available for symbol SUBLIME_WORD_MASK = 515 # set logging levels LOG_FILE_LEVEL = logging.WARN LOG_CONSOLE_LEVEL = logging.DEBUG NON_BLANK_LINE_PATTERN = re.compile("[\S]+") VALID_COMPLETION_ID_PATTERN = re.compile("[a-zA-Z_$\.][\w$\.]*\Z") # idle time length in millisecond IDLE_TIME_LENGTH = 20<commit_msg>Change the console log level back to WARN<commit_after>import os import re import sublime from .logger import * # get the directory path to this file; LIBS_DIR = os.path.dirname(os.path.abspath(__file__)) PLUGIN_DIR = os.path.dirname(LIBS_DIR) PACKAGES_DIR = os.path.dirname(PLUGIN_DIR) PLUGIN_NAME = os.path.basename(PLUGIN_DIR) # only Sublime Text 3 build after 3072 support tooltip TOOLTIP_SUPPORT = int(sublime.version()) >= 3072 # determine if the host is sublime text 2 IS_ST2 = int(sublime.version()) < 3000 # detect if quick info is available for symbol SUBLIME_WORD_MASK = 515 # set logging levels LOG_FILE_LEVEL = logging.WARN LOG_CONSOLE_LEVEL = logging.WARN NON_BLANK_LINE_PATTERN = re.compile("[\S]+") VALID_COMPLETION_ID_PATTERN = re.compile("[a-zA-Z_$\.][\w$\.]*\Z") # idle time length in millisecond IDLE_TIME_LENGTH = 20
e0707619ca9192544a912b91993f0de5c507d7d7
stutuz/__init__.py
stutuz/__init__.py
#-*- coding:utf-8 -*- from __future__ import division from __future__ import absolute_import from __future__ import with_statement from __future__ import print_function from __future__ import unicode_literals from logbook import Logger, NestedSetup from flask import Flask from flaskext.genshi import Genshi from flaskext.zodb import ZODB, PersistentMapping logger = Logger(__name__) genshi = Genshi() db = ZODB() @db.init def set_defaults(root): if 'languages' not in root: root['languages'] = PersistentMapping({'eng': 'English', 'jbo': 'Lojban'}) def create_app(config=None): app = Flask(__name__) app.config.from_object('stutuz.configs') if config is not None: app.config.from_object(config) app.config.from_envvar('STUTUZ_CONFIG', silent=True) handlers = app.config.get('LOGBOOK_HANDLERS') with NestedSetup(handlers): for extension in genshi, db: extension.init_app(app) for middleware in app.config.get('MIDDLEWARES', ()): app.wsgi_app = middleware(app.wsgi_app) return app
#-*- coding:utf-8 -*- from __future__ import division from __future__ import absolute_import from __future__ import with_statement from __future__ import print_function from __future__ import unicode_literals from logbook import Logger, NestedSetup from flask import Flask from flaskext.genshi import Genshi from flaskext.zodb import ZODB, PersistentMapping from stutuz.models import Users logger = Logger(__name__) genshi = Genshi() db = ZODB() @db.init def set_defaults(root): if 'languages' not in root: root['languages'] = PersistentMapping({'eng': 'English', 'jbo': 'Lojban'}) if 'users' not in root: root['users'] = Users() def create_app(config=None): app = Flask(__name__) app.config.from_object('stutuz.configs') if config is not None: app.config.from_object(config) app.config.from_envvar('STUTUZ_CONFIG', silent=True) handlers = app.config.get('LOGBOOK_HANDLERS') with NestedSetup(handlers): for extension in genshi, db: extension.init_app(app) for middleware in app.config.get('MIDDLEWARES', ()): app.wsgi_app = middleware(app.wsgi_app) return app
Make a default empty users list
Make a default empty users list
Python
bsd-2-clause
dag/stutuz
#-*- coding:utf-8 -*- from __future__ import division from __future__ import absolute_import from __future__ import with_statement from __future__ import print_function from __future__ import unicode_literals from logbook import Logger, NestedSetup from flask import Flask from flaskext.genshi import Genshi from flaskext.zodb import ZODB, PersistentMapping logger = Logger(__name__) genshi = Genshi() db = ZODB() @db.init def set_defaults(root): if 'languages' not in root: root['languages'] = PersistentMapping({'eng': 'English', 'jbo': 'Lojban'}) def create_app(config=None): app = Flask(__name__) app.config.from_object('stutuz.configs') if config is not None: app.config.from_object(config) app.config.from_envvar('STUTUZ_CONFIG', silent=True) handlers = app.config.get('LOGBOOK_HANDLERS') with NestedSetup(handlers): for extension in genshi, db: extension.init_app(app) for middleware in app.config.get('MIDDLEWARES', ()): app.wsgi_app = middleware(app.wsgi_app) return app Make a default empty users list
#-*- coding:utf-8 -*- from __future__ import division from __future__ import absolute_import from __future__ import with_statement from __future__ import print_function from __future__ import unicode_literals from logbook import Logger, NestedSetup from flask import Flask from flaskext.genshi import Genshi from flaskext.zodb import ZODB, PersistentMapping from stutuz.models import Users logger = Logger(__name__) genshi = Genshi() db = ZODB() @db.init def set_defaults(root): if 'languages' not in root: root['languages'] = PersistentMapping({'eng': 'English', 'jbo': 'Lojban'}) if 'users' not in root: root['users'] = Users() def create_app(config=None): app = Flask(__name__) app.config.from_object('stutuz.configs') if config is not None: app.config.from_object(config) app.config.from_envvar('STUTUZ_CONFIG', silent=True) handlers = app.config.get('LOGBOOK_HANDLERS') with NestedSetup(handlers): for extension in genshi, db: extension.init_app(app) for middleware in app.config.get('MIDDLEWARES', ()): app.wsgi_app = middleware(app.wsgi_app) return app
<commit_before>#-*- coding:utf-8 -*- from __future__ import division from __future__ import absolute_import from __future__ import with_statement from __future__ import print_function from __future__ import unicode_literals from logbook import Logger, NestedSetup from flask import Flask from flaskext.genshi import Genshi from flaskext.zodb import ZODB, PersistentMapping logger = Logger(__name__) genshi = Genshi() db = ZODB() @db.init def set_defaults(root): if 'languages' not in root: root['languages'] = PersistentMapping({'eng': 'English', 'jbo': 'Lojban'}) def create_app(config=None): app = Flask(__name__) app.config.from_object('stutuz.configs') if config is not None: app.config.from_object(config) app.config.from_envvar('STUTUZ_CONFIG', silent=True) handlers = app.config.get('LOGBOOK_HANDLERS') with NestedSetup(handlers): for extension in genshi, db: extension.init_app(app) for middleware in app.config.get('MIDDLEWARES', ()): app.wsgi_app = middleware(app.wsgi_app) return app <commit_msg>Make a default empty users list<commit_after>
#-*- coding:utf-8 -*- from __future__ import division from __future__ import absolute_import from __future__ import with_statement from __future__ import print_function from __future__ import unicode_literals from logbook import Logger, NestedSetup from flask import Flask from flaskext.genshi import Genshi from flaskext.zodb import ZODB, PersistentMapping from stutuz.models import Users logger = Logger(__name__) genshi = Genshi() db = ZODB() @db.init def set_defaults(root): if 'languages' not in root: root['languages'] = PersistentMapping({'eng': 'English', 'jbo': 'Lojban'}) if 'users' not in root: root['users'] = Users() def create_app(config=None): app = Flask(__name__) app.config.from_object('stutuz.configs') if config is not None: app.config.from_object(config) app.config.from_envvar('STUTUZ_CONFIG', silent=True) handlers = app.config.get('LOGBOOK_HANDLERS') with NestedSetup(handlers): for extension in genshi, db: extension.init_app(app) for middleware in app.config.get('MIDDLEWARES', ()): app.wsgi_app = middleware(app.wsgi_app) return app
#-*- coding:utf-8 -*- from __future__ import division from __future__ import absolute_import from __future__ import with_statement from __future__ import print_function from __future__ import unicode_literals from logbook import Logger, NestedSetup from flask import Flask from flaskext.genshi import Genshi from flaskext.zodb import ZODB, PersistentMapping logger = Logger(__name__) genshi = Genshi() db = ZODB() @db.init def set_defaults(root): if 'languages' not in root: root['languages'] = PersistentMapping({'eng': 'English', 'jbo': 'Lojban'}) def create_app(config=None): app = Flask(__name__) app.config.from_object('stutuz.configs') if config is not None: app.config.from_object(config) app.config.from_envvar('STUTUZ_CONFIG', silent=True) handlers = app.config.get('LOGBOOK_HANDLERS') with NestedSetup(handlers): for extension in genshi, db: extension.init_app(app) for middleware in app.config.get('MIDDLEWARES', ()): app.wsgi_app = middleware(app.wsgi_app) return app Make a default empty users list#-*- coding:utf-8 -*- from __future__ import division from __future__ import absolute_import from __future__ import with_statement from __future__ import print_function from __future__ import unicode_literals from logbook import Logger, NestedSetup from flask import Flask from flaskext.genshi import Genshi from flaskext.zodb import ZODB, PersistentMapping from stutuz.models import Users logger = Logger(__name__) genshi = Genshi() db = ZODB() @db.init def set_defaults(root): if 'languages' not in root: root['languages'] = PersistentMapping({'eng': 'English', 'jbo': 'Lojban'}) if 'users' not in root: root['users'] = Users() def create_app(config=None): app = Flask(__name__) app.config.from_object('stutuz.configs') if config is not None: app.config.from_object(config) app.config.from_envvar('STUTUZ_CONFIG', silent=True) handlers = app.config.get('LOGBOOK_HANDLERS') with NestedSetup(handlers): for extension in genshi, db: extension.init_app(app) for middleware in app.config.get('MIDDLEWARES', ()): app.wsgi_app = middleware(app.wsgi_app) return app
<commit_before>#-*- coding:utf-8 -*- from __future__ import division from __future__ import absolute_import from __future__ import with_statement from __future__ import print_function from __future__ import unicode_literals from logbook import Logger, NestedSetup from flask import Flask from flaskext.genshi import Genshi from flaskext.zodb import ZODB, PersistentMapping logger = Logger(__name__) genshi = Genshi() db = ZODB() @db.init def set_defaults(root): if 'languages' not in root: root['languages'] = PersistentMapping({'eng': 'English', 'jbo': 'Lojban'}) def create_app(config=None): app = Flask(__name__) app.config.from_object('stutuz.configs') if config is not None: app.config.from_object(config) app.config.from_envvar('STUTUZ_CONFIG', silent=True) handlers = app.config.get('LOGBOOK_HANDLERS') with NestedSetup(handlers): for extension in genshi, db: extension.init_app(app) for middleware in app.config.get('MIDDLEWARES', ()): app.wsgi_app = middleware(app.wsgi_app) return app <commit_msg>Make a default empty users list<commit_after>#-*- coding:utf-8 -*- from __future__ import division from __future__ import absolute_import from __future__ import with_statement from __future__ import print_function from __future__ import unicode_literals from logbook import Logger, NestedSetup from flask import Flask from flaskext.genshi import Genshi from flaskext.zodb import ZODB, PersistentMapping from stutuz.models import Users logger = Logger(__name__) genshi = Genshi() db = ZODB() @db.init def set_defaults(root): if 'languages' not in root: root['languages'] = PersistentMapping({'eng': 'English', 'jbo': 'Lojban'}) if 'users' not in root: root['users'] = Users() def create_app(config=None): app = Flask(__name__) app.config.from_object('stutuz.configs') if config is not None: app.config.from_object(config) app.config.from_envvar('STUTUZ_CONFIG', silent=True) handlers = app.config.get('LOGBOOK_HANDLERS') with NestedSetup(handlers): for extension in genshi, db: extension.init_app(app) for middleware in app.config.get('MIDDLEWARES', ()): app.wsgi_app = middleware(app.wsgi_app) return app
295285a0a13207dac276da6e3b41e2057a7efee8
test/tests/constant_damper_test/constant_damper_test.py
test/tests/constant_damper_test/constant_damper_test.py
import tools def testdirichlet(dofs=0, np=0, n_threads=0): tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads)
import tools def testdamper(dofs=0, np=0, n_threads=0): tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads) # Make sure the damping causes 8 NL steps def testverifydamping(dofs=0, np=0, n_threads=0): tools.executeAppExpectError(__file__,'constant_damper_test.i','NL step\s+8')
Verify additional steps in damping problem
Verify additional steps in damping problem r4199
Python
lgpl-2.1
jinmm1992/moose,stimpsonsg/moose,andrsd/moose,mellis13/moose,jinmm1992/moose,permcody/moose,liuwenf/moose,harterj/moose,jhbradley/moose,nuclear-wizard/moose,jhbradley/moose,adamLange/moose,roystgnr/moose,SudiptaBiswas/moose,katyhuff/moose,harterj/moose,roystgnr/moose,zzyfisherman/moose,roystgnr/moose,jasondhales/moose,katyhuff/moose,lindsayad/moose,dschwen/moose,jasondhales/moose,shanestafford/moose,cpritam/moose,raghavaggarwal/moose,andrsd/moose,bwspenc/moose,backmari/moose,joshua-cogliati-inl/moose,waxmanr/moose,milljm/moose,capitalaslash/moose,bwspenc/moose,zzyfisherman/moose,danielru/moose,apc-llc/moose,liuwenf/moose,yipenggao/moose,roystgnr/moose,markr622/moose,YaqiWang/moose,waxmanr/moose,idaholab/moose,capitalaslash/moose,jiangwen84/moose,milljm/moose,danielru/moose,YaqiWang/moose,adamLange/moose,jiangwen84/moose,lindsayad/moose,bwspenc/moose,jasondhales/moose,permcody/moose,sapitts/moose,backmari/moose,nuclear-wizard/moose,tonkmr/moose,jbair34/moose,sapitts/moose,markr622/moose,laagesen/moose,WilkAndy/moose,jinmm1992/moose,jbair34/moose,markr622/moose,mellis13/moose,stimpsonsg/moose,jiangwen84/moose,Chuban/moose,harterj/moose,zzyfisherman/moose,tonkmr/moose,WilkAndy/moose,waxmanr/moose,giopastor/moose,Chuban/moose,joshua-cogliati-inl/moose,xy515258/moose,bwspenc/moose,shanestafford/moose,markr622/moose,tonkmr/moose,giopastor/moose,andrsd/moose,danielru/moose,cpritam/moose,idaholab/moose,dschwen/moose,stimpsonsg/moose,katyhuff/moose,tonkmr/moose,WilkAndy/moose,Chuban/moose,laagesen/moose,idaholab/moose,shanestafford/moose,dschwen/moose,lindsayad/moose,adamLange/moose,wgapl/moose,zzyfisherman/moose,backmari/moose,danielru/moose,apc-llc/moose,tonkmr/moose,sapitts/moose,jessecarterMOOSE/moose,cpritam/moose,laagesen/moose,milljm/moose,waxmanr/moose,SudiptaBiswas/moose,shanestafford/moose,backmari/moose,mellis13/moose,raghavaggarwal/moose,friedmud/moose,cpritam/moose,SudiptaBiswas/moose,xy515258/moose,milljm/moose,WilkAndy/moose,jessecarterMOOSE/moose,stimpsonsg/moose,friedmud/moose,wgapl/moose,jinmm1992/moose,laagesen/moose,YaqiWang/moose,friedmud/moose,jbair34/moose,dschwen/moose,yipenggao/moose,jhbradley/moose,wgapl/moose,yipenggao/moose,liuwenf/moose,Chuban/moose,roystgnr/moose,idaholab/moose,nuclear-wizard/moose,SudiptaBiswas/moose,mellis13/moose,kasra83/moose,shanestafford/moose,jessecarterMOOSE/moose,liuwenf/moose,jasondhales/moose,jhbradley/moose,cpritam/moose,xy515258/moose,wgapl/moose,WilkAndy/moose,cpritam/moose,WilkAndy/moose,dschwen/moose,shanestafford/moose,zzyfisherman/moose,raghavaggarwal/moose,nuclear-wizard/moose,zzyfisherman/moose,friedmud/moose,roystgnr/moose,permcody/moose,sapitts/moose,lindsayad/moose,jiangwen84/moose,jbair34/moose,giopastor/moose,tonkmr/moose,capitalaslash/moose,YaqiWang/moose,laagesen/moose,jessecarterMOOSE/moose,joshua-cogliati-inl/moose,milljm/moose,giopastor/moose,sapitts/moose,raghavaggarwal/moose,bwspenc/moose,andrsd/moose,idaholab/moose,liuwenf/moose,kasra83/moose,permcody/moose,apc-llc/moose,xy515258/moose,roystgnr/moose,kasra83/moose,jessecarterMOOSE/moose,lindsayad/moose,kasra83/moose,liuwenf/moose,harterj/moose,capitalaslash/moose,yipenggao/moose,harterj/moose,katyhuff/moose,apc-llc/moose,joshua-cogliati-inl/moose,andrsd/moose,adamLange/moose,SudiptaBiswas/moose
import tools def testdirichlet(dofs=0, np=0, n_threads=0): tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads) Verify additional steps in damping problem r4199
import tools def testdamper(dofs=0, np=0, n_threads=0): tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads) # Make sure the damping causes 8 NL steps def testverifydamping(dofs=0, np=0, n_threads=0): tools.executeAppExpectError(__file__,'constant_damper_test.i','NL step\s+8')
<commit_before>import tools def testdirichlet(dofs=0, np=0, n_threads=0): tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads) <commit_msg>Verify additional steps in damping problem r4199<commit_after>
import tools def testdamper(dofs=0, np=0, n_threads=0): tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads) # Make sure the damping causes 8 NL steps def testverifydamping(dofs=0, np=0, n_threads=0): tools.executeAppExpectError(__file__,'constant_damper_test.i','NL step\s+8')
import tools def testdirichlet(dofs=0, np=0, n_threads=0): tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads) Verify additional steps in damping problem r4199import tools def testdamper(dofs=0, np=0, n_threads=0): tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads) # Make sure the damping causes 8 NL steps def testverifydamping(dofs=0, np=0, n_threads=0): tools.executeAppExpectError(__file__,'constant_damper_test.i','NL step\s+8')
<commit_before>import tools def testdirichlet(dofs=0, np=0, n_threads=0): tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads) <commit_msg>Verify additional steps in damping problem r4199<commit_after>import tools def testdamper(dofs=0, np=0, n_threads=0): tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads) # Make sure the damping causes 8 NL steps def testverifydamping(dofs=0, np=0, n_threads=0): tools.executeAppExpectError(__file__,'constant_damper_test.i','NL step\s+8')
d1ab1b7e7edf74f89274e48718fac0b6ac6d191d
dthm4kaiako/config/__init__.py
dthm4kaiako/config/__init__.py
"""Configuration for Django system.""" __version__ = "0.14.0" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] )
"""Configuration for Django system.""" __version__ = "0.14.1" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] )
Increment version number to 0.14.1
Increment version number to 0.14.1
Python
mit
uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers
"""Configuration for Django system.""" __version__ = "0.14.0" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] ) Increment version number to 0.14.1
"""Configuration for Django system.""" __version__ = "0.14.1" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] )
<commit_before>"""Configuration for Django system.""" __version__ = "0.14.0" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] ) <commit_msg>Increment version number to 0.14.1<commit_after>
"""Configuration for Django system.""" __version__ = "0.14.1" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] )
"""Configuration for Django system.""" __version__ = "0.14.0" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] ) Increment version number to 0.14.1"""Configuration for Django system.""" __version__ = "0.14.1" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] )
<commit_before>"""Configuration for Django system.""" __version__ = "0.14.0" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] ) <commit_msg>Increment version number to 0.14.1<commit_after>"""Configuration for Django system.""" __version__ = "0.14.1" __version_info__ = tuple( [ int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split(".") ] )
dab9d4e071bef5e0a771fa5a0eb7be81819bb68c
user_profile/urls.py
user_profile/urls.py
from django.conf.urls import include, url from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.ViewView.as_view(), name='profile_own_view'), url(r'^edit/', views.EditView.as_view(), name='profile_edit'), url(r'^view/', views.ViewView.as_view(), name='profile_own_view'), url(r'^view/(?P<user_name>\d+)/$', views.ViewView.as_view(), name='profile_view'), ]
from django.conf.urls import include, url from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.ViewView.as_view(), name='profile_own_view'), url(r'^edit/', views.EditView.as_view(), name='profile_edit'), url(r'^view/', views.ViewView.as_view(), name='profile_own_view'), url(r'^view/(?P<username>[a-zA-Z0-9_-]+)/$', views.ViewView.as_view(), name='profile_view'), ]
Fix user name url pattern
Fix user name url pattern
Python
mit
DeWaster/Tviserrys,DeWaster/Tviserrys
from django.conf.urls import include, url from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.ViewView.as_view(), name='profile_own_view'), url(r'^edit/', views.EditView.as_view(), name='profile_edit'), url(r'^view/', views.ViewView.as_view(), name='profile_own_view'), url(r'^view/(?P<user_name>\d+)/$', views.ViewView.as_view(), name='profile_view'), ] Fix user name url pattern
from django.conf.urls import include, url from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.ViewView.as_view(), name='profile_own_view'), url(r'^edit/', views.EditView.as_view(), name='profile_edit'), url(r'^view/', views.ViewView.as_view(), name='profile_own_view'), url(r'^view/(?P<username>[a-zA-Z0-9_-]+)/$', views.ViewView.as_view(), name='profile_view'), ]
<commit_before>from django.conf.urls import include, url from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.ViewView.as_view(), name='profile_own_view'), url(r'^edit/', views.EditView.as_view(), name='profile_edit'), url(r'^view/', views.ViewView.as_view(), name='profile_own_view'), url(r'^view/(?P<user_name>\d+)/$', views.ViewView.as_view(), name='profile_view'), ] <commit_msg>Fix user name url pattern<commit_after>
from django.conf.urls import include, url from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.ViewView.as_view(), name='profile_own_view'), url(r'^edit/', views.EditView.as_view(), name='profile_edit'), url(r'^view/', views.ViewView.as_view(), name='profile_own_view'), url(r'^view/(?P<username>[a-zA-Z0-9_-]+)/$', views.ViewView.as_view(), name='profile_view'), ]
from django.conf.urls import include, url from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.ViewView.as_view(), name='profile_own_view'), url(r'^edit/', views.EditView.as_view(), name='profile_edit'), url(r'^view/', views.ViewView.as_view(), name='profile_own_view'), url(r'^view/(?P<user_name>\d+)/$', views.ViewView.as_view(), name='profile_view'), ] Fix user name url patternfrom django.conf.urls import include, url from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.ViewView.as_view(), name='profile_own_view'), url(r'^edit/', views.EditView.as_view(), name='profile_edit'), url(r'^view/', views.ViewView.as_view(), name='profile_own_view'), url(r'^view/(?P<username>[a-zA-Z0-9_-]+)/$', views.ViewView.as_view(), name='profile_view'), ]
<commit_before>from django.conf.urls import include, url from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.ViewView.as_view(), name='profile_own_view'), url(r'^edit/', views.EditView.as_view(), name='profile_edit'), url(r'^view/', views.ViewView.as_view(), name='profile_own_view'), url(r'^view/(?P<user_name>\d+)/$', views.ViewView.as_view(), name='profile_view'), ] <commit_msg>Fix user name url pattern<commit_after>from django.conf.urls import include, url from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.ViewView.as_view(), name='profile_own_view'), url(r'^edit/', views.EditView.as_view(), name='profile_edit'), url(r'^view/', views.ViewView.as_view(), name='profile_own_view'), url(r'^view/(?P<username>[a-zA-Z0-9_-]+)/$', views.ViewView.as_view(), name='profile_view'), ]
bb2249998637c8c56cb8b7cd119c1d8d132e522e
viewer_examples/plugins/canny_simple.py
viewer_examples/plugins/canny_simple.py
from skimage import data from skimage.filter import canny from skimage.viewer import ImageViewer from skimage.viewer.widgets import Slider from skimage.viewer.plugins.overlayplugin import OverlayPlugin image = data.camera() # Note: ImageViewer must be called before Plugin b/c it starts the event loop. viewer = ImageViewer(image) # You can create a UI for a filter just by passing a filter function... plugin = OverlayPlugin(image_filter=canny) # ... and adding widgets to adjust parameter values. plugin += Slider('sigma', 0, 5, update_on='release') plugin += Slider('low threshold', 0, 255, update_on='release') plugin += Slider('high threshold', 0, 255, update_on='release') # Finally, attach the plugin to the image viewer. viewer += plugin viewer.show()
from skimage import data from skimage.filter import canny from skimage.viewer import ImageViewer from skimage.viewer.widgets import Slider from skimage.viewer.widgets.history import SaveButtons from skimage.viewer.plugins.overlayplugin import OverlayPlugin image = data.camera() # You can create a UI for a filter just by passing a filter function... plugin = OverlayPlugin(image_filter=canny) # ... and adding widgets to adjust parameter values. plugin += Slider('sigma', 0, 5, update_on='release') plugin += Slider('low threshold', 0, 255, update_on='release') plugin += Slider('high threshold', 0, 255, update_on='release') # ... and we can also add buttons to save the overlay: plugin += SaveButtons(name='Save overlay to:') # Finally, attach the plugin to an image viewer. viewer = ImageViewer(image) viewer += plugin viewer.show()
Add save buttons to viewer example.
Add save buttons to viewer example.
Python
bsd-3-clause
jwiggins/scikit-image,WarrenWeckesser/scikits-image,rjeli/scikit-image,almarklein/scikit-image,michaelaye/scikit-image,newville/scikit-image,Britefury/scikit-image,blink1073/scikit-image,pratapvardhan/scikit-image,ClinicalGraphics/scikit-image,pratapvardhan/scikit-image,dpshelio/scikit-image,chintak/scikit-image,almarklein/scikit-image,paalge/scikit-image,keflavich/scikit-image,michaelpacer/scikit-image,bennlich/scikit-image,paalge/scikit-image,chintak/scikit-image,bsipocz/scikit-image,chriscrosscutler/scikit-image,SamHames/scikit-image,juliusbierk/scikit-image,WarrenWeckesser/scikits-image,SamHames/scikit-image,warmspringwinds/scikit-image,Britefury/scikit-image,michaelaye/scikit-image,ajaybhat/scikit-image,robintw/scikit-image,dpshelio/scikit-image,SamHames/scikit-image,ofgulban/scikit-image,ClinicalGraphics/scikit-image,michaelpacer/scikit-image,ofgulban/scikit-image,Midafi/scikit-image,chintak/scikit-image,emon10005/scikit-image,rjeli/scikit-image,almarklein/scikit-image,emon10005/scikit-image,Midafi/scikit-image,ofgulban/scikit-image,oew1v07/scikit-image,keflavich/scikit-image,vighneshbirodkar/scikit-image,oew1v07/scikit-image,chintak/scikit-image,jwiggins/scikit-image,Hiyorimi/scikit-image,bennlich/scikit-image,rjeli/scikit-image,newville/scikit-image,paalge/scikit-image,almarklein/scikit-image,juliusbierk/scikit-image,youprofit/scikit-image,vighneshbirodkar/scikit-image,SamHames/scikit-image,GaZ3ll3/scikit-image,vighneshbirodkar/scikit-image,ajaybhat/scikit-image,robintw/scikit-image,warmspringwinds/scikit-image,GaZ3ll3/scikit-image,Hiyorimi/scikit-image,blink1073/scikit-image,chriscrosscutler/scikit-image,youprofit/scikit-image,bsipocz/scikit-image
from skimage import data from skimage.filter import canny from skimage.viewer import ImageViewer from skimage.viewer.widgets import Slider from skimage.viewer.plugins.overlayplugin import OverlayPlugin image = data.camera() # Note: ImageViewer must be called before Plugin b/c it starts the event loop. viewer = ImageViewer(image) # You can create a UI for a filter just by passing a filter function... plugin = OverlayPlugin(image_filter=canny) # ... and adding widgets to adjust parameter values. plugin += Slider('sigma', 0, 5, update_on='release') plugin += Slider('low threshold', 0, 255, update_on='release') plugin += Slider('high threshold', 0, 255, update_on='release') # Finally, attach the plugin to the image viewer. viewer += plugin viewer.show() Add save buttons to viewer example.
from skimage import data from skimage.filter import canny from skimage.viewer import ImageViewer from skimage.viewer.widgets import Slider from skimage.viewer.widgets.history import SaveButtons from skimage.viewer.plugins.overlayplugin import OverlayPlugin image = data.camera() # You can create a UI for a filter just by passing a filter function... plugin = OverlayPlugin(image_filter=canny) # ... and adding widgets to adjust parameter values. plugin += Slider('sigma', 0, 5, update_on='release') plugin += Slider('low threshold', 0, 255, update_on='release') plugin += Slider('high threshold', 0, 255, update_on='release') # ... and we can also add buttons to save the overlay: plugin += SaveButtons(name='Save overlay to:') # Finally, attach the plugin to an image viewer. viewer = ImageViewer(image) viewer += plugin viewer.show()
<commit_before>from skimage import data from skimage.filter import canny from skimage.viewer import ImageViewer from skimage.viewer.widgets import Slider from skimage.viewer.plugins.overlayplugin import OverlayPlugin image = data.camera() # Note: ImageViewer must be called before Plugin b/c it starts the event loop. viewer = ImageViewer(image) # You can create a UI for a filter just by passing a filter function... plugin = OverlayPlugin(image_filter=canny) # ... and adding widgets to adjust parameter values. plugin += Slider('sigma', 0, 5, update_on='release') plugin += Slider('low threshold', 0, 255, update_on='release') plugin += Slider('high threshold', 0, 255, update_on='release') # Finally, attach the plugin to the image viewer. viewer += plugin viewer.show() <commit_msg>Add save buttons to viewer example.<commit_after>
from skimage import data from skimage.filter import canny from skimage.viewer import ImageViewer from skimage.viewer.widgets import Slider from skimage.viewer.widgets.history import SaveButtons from skimage.viewer.plugins.overlayplugin import OverlayPlugin image = data.camera() # You can create a UI for a filter just by passing a filter function... plugin = OverlayPlugin(image_filter=canny) # ... and adding widgets to adjust parameter values. plugin += Slider('sigma', 0, 5, update_on='release') plugin += Slider('low threshold', 0, 255, update_on='release') plugin += Slider('high threshold', 0, 255, update_on='release') # ... and we can also add buttons to save the overlay: plugin += SaveButtons(name='Save overlay to:') # Finally, attach the plugin to an image viewer. viewer = ImageViewer(image) viewer += plugin viewer.show()
from skimage import data from skimage.filter import canny from skimage.viewer import ImageViewer from skimage.viewer.widgets import Slider from skimage.viewer.plugins.overlayplugin import OverlayPlugin image = data.camera() # Note: ImageViewer must be called before Plugin b/c it starts the event loop. viewer = ImageViewer(image) # You can create a UI for a filter just by passing a filter function... plugin = OverlayPlugin(image_filter=canny) # ... and adding widgets to adjust parameter values. plugin += Slider('sigma', 0, 5, update_on='release') plugin += Slider('low threshold', 0, 255, update_on='release') plugin += Slider('high threshold', 0, 255, update_on='release') # Finally, attach the plugin to the image viewer. viewer += plugin viewer.show() Add save buttons to viewer example.from skimage import data from skimage.filter import canny from skimage.viewer import ImageViewer from skimage.viewer.widgets import Slider from skimage.viewer.widgets.history import SaveButtons from skimage.viewer.plugins.overlayplugin import OverlayPlugin image = data.camera() # You can create a UI for a filter just by passing a filter function... plugin = OverlayPlugin(image_filter=canny) # ... and adding widgets to adjust parameter values. plugin += Slider('sigma', 0, 5, update_on='release') plugin += Slider('low threshold', 0, 255, update_on='release') plugin += Slider('high threshold', 0, 255, update_on='release') # ... and we can also add buttons to save the overlay: plugin += SaveButtons(name='Save overlay to:') # Finally, attach the plugin to an image viewer. viewer = ImageViewer(image) viewer += plugin viewer.show()
<commit_before>from skimage import data from skimage.filter import canny from skimage.viewer import ImageViewer from skimage.viewer.widgets import Slider from skimage.viewer.plugins.overlayplugin import OverlayPlugin image = data.camera() # Note: ImageViewer must be called before Plugin b/c it starts the event loop. viewer = ImageViewer(image) # You can create a UI for a filter just by passing a filter function... plugin = OverlayPlugin(image_filter=canny) # ... and adding widgets to adjust parameter values. plugin += Slider('sigma', 0, 5, update_on='release') plugin += Slider('low threshold', 0, 255, update_on='release') plugin += Slider('high threshold', 0, 255, update_on='release') # Finally, attach the plugin to the image viewer. viewer += plugin viewer.show() <commit_msg>Add save buttons to viewer example.<commit_after>from skimage import data from skimage.filter import canny from skimage.viewer import ImageViewer from skimage.viewer.widgets import Slider from skimage.viewer.widgets.history import SaveButtons from skimage.viewer.plugins.overlayplugin import OverlayPlugin image = data.camera() # You can create a UI for a filter just by passing a filter function... plugin = OverlayPlugin(image_filter=canny) # ... and adding widgets to adjust parameter values. plugin += Slider('sigma', 0, 5, update_on='release') plugin += Slider('low threshold', 0, 255, update_on='release') plugin += Slider('high threshold', 0, 255, update_on='release') # ... and we can also add buttons to save the overlay: plugin += SaveButtons(name='Save overlay to:') # Finally, attach the plugin to an image viewer. viewer = ImageViewer(image) viewer += plugin viewer.show()
7cf867e9ee7a3764b3168cd9671f6de0d0b1b090
numpy/distutils/command/install_clib.py
numpy/distutils/command/install_clib.py
import os from distutils.core import Command from numpy.distutils.misc_util import get_cmd class install_clib(Command): description = "Command to install installable C libraries" user_options = [] def initialize_options(self): self.install_dir = None self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'install_dir')) def run (self): # We need the compiler to get the library name -> filename association from distutils.ccompiler import new_compiler compiler = new_compiler(compiler=None) compiler.customize(self.distribution) build_dir = get_cmd("build_clib").build_clib for l in self.distribution.installed_libraries: target_dir = os.path.join(self.install_dir, l.target_dir) name = compiler.library_filename(l.name) source = os.path.join(build_dir, name) self.mkpath(target_dir) self.outfiles.append(self.copy_file(source, target_dir)[0]) def get_outputs(self): return self.outfiles
import os from distutils.core import Command from distutils.ccompiler import new_compiler from numpy.distutils.misc_util import get_cmd class install_clib(Command): description = "Command to install installable C libraries" user_options = [] def initialize_options(self): self.install_dir = None self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'install_dir')) def run (self): # We need the compiler to get the library name -> filename association compiler = new_compiler(compiler=None) compiler.customize(self.distribution) build_dir = get_cmd("build_clib").build_clib for l in self.distribution.installed_libraries: target_dir = os.path.join(self.install_dir, l.target_dir) name = compiler.library_filename(l.name) source = os.path.join(build_dir, name) self.mkpath(target_dir) self.outfiles.append(self.copy_file(source, target_dir)[0]) def get_outputs(self): return self.outfiles
Move import at the top of module.
Move import at the top of module. git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@7278 94b884b6-d6fd-0310-90d3-974f1d3f35e1
Python
bsd-3-clause
teoliphant/numpy-refactor,illume/numpy3k,Ademan/NumPy-GSoC,Ademan/NumPy-GSoC,teoliphant/numpy-refactor,chadnetzer/numpy-gaurdro,Ademan/NumPy-GSoC,jasonmccampbell/numpy-refactor-sprint,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,illume/numpy3k,teoliphant/numpy-refactor,chadnetzer/numpy-gaurdro,illume/numpy3k,chadnetzer/numpy-gaurdro,jasonmccampbell/numpy-refactor-sprint,illume/numpy3k,teoliphant/numpy-refactor,Ademan/NumPy-GSoC,jasonmccampbell/numpy-refactor-sprint,chadnetzer/numpy-gaurdro
import os from distutils.core import Command from numpy.distutils.misc_util import get_cmd class install_clib(Command): description = "Command to install installable C libraries" user_options = [] def initialize_options(self): self.install_dir = None self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'install_dir')) def run (self): # We need the compiler to get the library name -> filename association from distutils.ccompiler import new_compiler compiler = new_compiler(compiler=None) compiler.customize(self.distribution) build_dir = get_cmd("build_clib").build_clib for l in self.distribution.installed_libraries: target_dir = os.path.join(self.install_dir, l.target_dir) name = compiler.library_filename(l.name) source = os.path.join(build_dir, name) self.mkpath(target_dir) self.outfiles.append(self.copy_file(source, target_dir)[0]) def get_outputs(self): return self.outfiles Move import at the top of module. git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@7278 94b884b6-d6fd-0310-90d3-974f1d3f35e1
import os from distutils.core import Command from distutils.ccompiler import new_compiler from numpy.distutils.misc_util import get_cmd class install_clib(Command): description = "Command to install installable C libraries" user_options = [] def initialize_options(self): self.install_dir = None self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'install_dir')) def run (self): # We need the compiler to get the library name -> filename association compiler = new_compiler(compiler=None) compiler.customize(self.distribution) build_dir = get_cmd("build_clib").build_clib for l in self.distribution.installed_libraries: target_dir = os.path.join(self.install_dir, l.target_dir) name = compiler.library_filename(l.name) source = os.path.join(build_dir, name) self.mkpath(target_dir) self.outfiles.append(self.copy_file(source, target_dir)[0]) def get_outputs(self): return self.outfiles
<commit_before>import os from distutils.core import Command from numpy.distutils.misc_util import get_cmd class install_clib(Command): description = "Command to install installable C libraries" user_options = [] def initialize_options(self): self.install_dir = None self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'install_dir')) def run (self): # We need the compiler to get the library name -> filename association from distutils.ccompiler import new_compiler compiler = new_compiler(compiler=None) compiler.customize(self.distribution) build_dir = get_cmd("build_clib").build_clib for l in self.distribution.installed_libraries: target_dir = os.path.join(self.install_dir, l.target_dir) name = compiler.library_filename(l.name) source = os.path.join(build_dir, name) self.mkpath(target_dir) self.outfiles.append(self.copy_file(source, target_dir)[0]) def get_outputs(self): return self.outfiles <commit_msg>Move import at the top of module. git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@7278 94b884b6-d6fd-0310-90d3-974f1d3f35e1<commit_after>
import os from distutils.core import Command from distutils.ccompiler import new_compiler from numpy.distutils.misc_util import get_cmd class install_clib(Command): description = "Command to install installable C libraries" user_options = [] def initialize_options(self): self.install_dir = None self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'install_dir')) def run (self): # We need the compiler to get the library name -> filename association compiler = new_compiler(compiler=None) compiler.customize(self.distribution) build_dir = get_cmd("build_clib").build_clib for l in self.distribution.installed_libraries: target_dir = os.path.join(self.install_dir, l.target_dir) name = compiler.library_filename(l.name) source = os.path.join(build_dir, name) self.mkpath(target_dir) self.outfiles.append(self.copy_file(source, target_dir)[0]) def get_outputs(self): return self.outfiles
import os from distutils.core import Command from numpy.distutils.misc_util import get_cmd class install_clib(Command): description = "Command to install installable C libraries" user_options = [] def initialize_options(self): self.install_dir = None self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'install_dir')) def run (self): # We need the compiler to get the library name -> filename association from distutils.ccompiler import new_compiler compiler = new_compiler(compiler=None) compiler.customize(self.distribution) build_dir = get_cmd("build_clib").build_clib for l in self.distribution.installed_libraries: target_dir = os.path.join(self.install_dir, l.target_dir) name = compiler.library_filename(l.name) source = os.path.join(build_dir, name) self.mkpath(target_dir) self.outfiles.append(self.copy_file(source, target_dir)[0]) def get_outputs(self): return self.outfiles Move import at the top of module. git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@7278 94b884b6-d6fd-0310-90d3-974f1d3f35e1import os from distutils.core import Command from distutils.ccompiler import new_compiler from numpy.distutils.misc_util import get_cmd class install_clib(Command): description = "Command to install installable C libraries" user_options = [] def initialize_options(self): self.install_dir = None self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'install_dir')) def run (self): # We need the compiler to get the library name -> filename association compiler = new_compiler(compiler=None) compiler.customize(self.distribution) build_dir = get_cmd("build_clib").build_clib for l in self.distribution.installed_libraries: target_dir = os.path.join(self.install_dir, l.target_dir) name = compiler.library_filename(l.name) source = os.path.join(build_dir, name) self.mkpath(target_dir) self.outfiles.append(self.copy_file(source, target_dir)[0]) def get_outputs(self): return self.outfiles
<commit_before>import os from distutils.core import Command from numpy.distutils.misc_util import get_cmd class install_clib(Command): description = "Command to install installable C libraries" user_options = [] def initialize_options(self): self.install_dir = None self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'install_dir')) def run (self): # We need the compiler to get the library name -> filename association from distutils.ccompiler import new_compiler compiler = new_compiler(compiler=None) compiler.customize(self.distribution) build_dir = get_cmd("build_clib").build_clib for l in self.distribution.installed_libraries: target_dir = os.path.join(self.install_dir, l.target_dir) name = compiler.library_filename(l.name) source = os.path.join(build_dir, name) self.mkpath(target_dir) self.outfiles.append(self.copy_file(source, target_dir)[0]) def get_outputs(self): return self.outfiles <commit_msg>Move import at the top of module. git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@7278 94b884b6-d6fd-0310-90d3-974f1d3f35e1<commit_after>import os from distutils.core import Command from distutils.ccompiler import new_compiler from numpy.distutils.misc_util import get_cmd class install_clib(Command): description = "Command to install installable C libraries" user_options = [] def initialize_options(self): self.install_dir = None self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'install_dir')) def run (self): # We need the compiler to get the library name -> filename association compiler = new_compiler(compiler=None) compiler.customize(self.distribution) build_dir = get_cmd("build_clib").build_clib for l in self.distribution.installed_libraries: target_dir = os.path.join(self.install_dir, l.target_dir) name = compiler.library_filename(l.name) source = os.path.join(build_dir, name) self.mkpath(target_dir) self.outfiles.append(self.copy_file(source, target_dir)[0]) def get_outputs(self): return self.outfiles
7ca3b7f294b954dcd95880c938709240b268766f
test_url_runner.py
test_url_runner.py
#!/usr/bin/env python import unittest # This line is important so flake8 must ignore this one from app import views # flake8: noqa from app import mulungwishi_app class URLTest(unittest.TestCase): def setUp(self): self.client = mulungwishi_app.test_client() self.client.testing = True def test_invalid_url_page_not_found(self): result = self.client.get('/page/not/found') self.assertEqual(result.status_code, 404) def test_invalid_query(self): result = self.client.get('/query?no_content') self.assertEqual(result.status_code, 400) def test_invalid_query_empty(self): result = self.client.get('/query?content') self.assertEqual(result.status_code, 400) def test_invalid_query_none(self): result = self.client.get('/query?') self.assertEqual(result.status_code, 400) def test_valid_url(self): result = self.client.get('/') self.assertEqual(result.status_code, 200) def test_valid_query(self): result = self.client.get('/query?content=farmer_sms') self.assertEqual(result.status_code, 200)
#!/usr/bin/env python import unittest # This line is important so flake8 must ignore this one from app import views # flake8: noqa from app import mulungwishi_app class URLTest(unittest.TestCase): def setUp(self): self.client = mulungwishi_app.test_client() self.client.testing = True def test_invalid_url_page_not_found(self): result = self.client.get('/page/not/found') self.assertEqual(result.status_code, 404) def test_invalid_query(self): result = self.client.get('/query?no_content') self.assertEqual(result.status_code, 400) def test_invalid_query_empty(self): result = self.client.get('/query?content') self.assertEqual(result.status_code, 400) def test_invalid_query_no_value_assigned(self): result = self.client.get('/query?content=') self.assertEqual(result.status_code, 400) def test_invalid_query_none(self): result = self.client.get('/query?') self.assertEqual(result.status_code, 400) def test_valid_url(self): result = self.client.get('/') self.assertEqual(result.status_code, 200) def test_valid_query(self): result = self.client.get('/query?content=farmer_sms') self.assertEqual(result.status_code, 200)
Add test for empty content string on query
Add test for empty content string on query
Python
mit
engagespark/public-webhooks,engagespark/mulungwishi-webhook,engagespark/mulungwishi-webhook,admiral96/public-webhooks,engagespark/public-webhooks,admiral96/public-webhooks,admiral96/mulungwishi-webhook,admiral96/mulungwishi-webhook
#!/usr/bin/env python import unittest # This line is important so flake8 must ignore this one from app import views # flake8: noqa from app import mulungwishi_app class URLTest(unittest.TestCase): def setUp(self): self.client = mulungwishi_app.test_client() self.client.testing = True def test_invalid_url_page_not_found(self): result = self.client.get('/page/not/found') self.assertEqual(result.status_code, 404) def test_invalid_query(self): result = self.client.get('/query?no_content') self.assertEqual(result.status_code, 400) def test_invalid_query_empty(self): result = self.client.get('/query?content') self.assertEqual(result.status_code, 400) def test_invalid_query_none(self): result = self.client.get('/query?') self.assertEqual(result.status_code, 400) def test_valid_url(self): result = self.client.get('/') self.assertEqual(result.status_code, 200) def test_valid_query(self): result = self.client.get('/query?content=farmer_sms') self.assertEqual(result.status_code, 200) Add test for empty content string on query
#!/usr/bin/env python import unittest # This line is important so flake8 must ignore this one from app import views # flake8: noqa from app import mulungwishi_app class URLTest(unittest.TestCase): def setUp(self): self.client = mulungwishi_app.test_client() self.client.testing = True def test_invalid_url_page_not_found(self): result = self.client.get('/page/not/found') self.assertEqual(result.status_code, 404) def test_invalid_query(self): result = self.client.get('/query?no_content') self.assertEqual(result.status_code, 400) def test_invalid_query_empty(self): result = self.client.get('/query?content') self.assertEqual(result.status_code, 400) def test_invalid_query_no_value_assigned(self): result = self.client.get('/query?content=') self.assertEqual(result.status_code, 400) def test_invalid_query_none(self): result = self.client.get('/query?') self.assertEqual(result.status_code, 400) def test_valid_url(self): result = self.client.get('/') self.assertEqual(result.status_code, 200) def test_valid_query(self): result = self.client.get('/query?content=farmer_sms') self.assertEqual(result.status_code, 200)
<commit_before>#!/usr/bin/env python import unittest # This line is important so flake8 must ignore this one from app import views # flake8: noqa from app import mulungwishi_app class URLTest(unittest.TestCase): def setUp(self): self.client = mulungwishi_app.test_client() self.client.testing = True def test_invalid_url_page_not_found(self): result = self.client.get('/page/not/found') self.assertEqual(result.status_code, 404) def test_invalid_query(self): result = self.client.get('/query?no_content') self.assertEqual(result.status_code, 400) def test_invalid_query_empty(self): result = self.client.get('/query?content') self.assertEqual(result.status_code, 400) def test_invalid_query_none(self): result = self.client.get('/query?') self.assertEqual(result.status_code, 400) def test_valid_url(self): result = self.client.get('/') self.assertEqual(result.status_code, 200) def test_valid_query(self): result = self.client.get('/query?content=farmer_sms') self.assertEqual(result.status_code, 200) <commit_msg>Add test for empty content string on query<commit_after>
#!/usr/bin/env python import unittest # This line is important so flake8 must ignore this one from app import views # flake8: noqa from app import mulungwishi_app class URLTest(unittest.TestCase): def setUp(self): self.client = mulungwishi_app.test_client() self.client.testing = True def test_invalid_url_page_not_found(self): result = self.client.get('/page/not/found') self.assertEqual(result.status_code, 404) def test_invalid_query(self): result = self.client.get('/query?no_content') self.assertEqual(result.status_code, 400) def test_invalid_query_empty(self): result = self.client.get('/query?content') self.assertEqual(result.status_code, 400) def test_invalid_query_no_value_assigned(self): result = self.client.get('/query?content=') self.assertEqual(result.status_code, 400) def test_invalid_query_none(self): result = self.client.get('/query?') self.assertEqual(result.status_code, 400) def test_valid_url(self): result = self.client.get('/') self.assertEqual(result.status_code, 200) def test_valid_query(self): result = self.client.get('/query?content=farmer_sms') self.assertEqual(result.status_code, 200)
#!/usr/bin/env python import unittest # This line is important so flake8 must ignore this one from app import views # flake8: noqa from app import mulungwishi_app class URLTest(unittest.TestCase): def setUp(self): self.client = mulungwishi_app.test_client() self.client.testing = True def test_invalid_url_page_not_found(self): result = self.client.get('/page/not/found') self.assertEqual(result.status_code, 404) def test_invalid_query(self): result = self.client.get('/query?no_content') self.assertEqual(result.status_code, 400) def test_invalid_query_empty(self): result = self.client.get('/query?content') self.assertEqual(result.status_code, 400) def test_invalid_query_none(self): result = self.client.get('/query?') self.assertEqual(result.status_code, 400) def test_valid_url(self): result = self.client.get('/') self.assertEqual(result.status_code, 200) def test_valid_query(self): result = self.client.get('/query?content=farmer_sms') self.assertEqual(result.status_code, 200) Add test for empty content string on query#!/usr/bin/env python import unittest # This line is important so flake8 must ignore this one from app import views # flake8: noqa from app import mulungwishi_app class URLTest(unittest.TestCase): def setUp(self): self.client = mulungwishi_app.test_client() self.client.testing = True def test_invalid_url_page_not_found(self): result = self.client.get('/page/not/found') self.assertEqual(result.status_code, 404) def test_invalid_query(self): result = self.client.get('/query?no_content') self.assertEqual(result.status_code, 400) def test_invalid_query_empty(self): result = self.client.get('/query?content') self.assertEqual(result.status_code, 400) def test_invalid_query_no_value_assigned(self): result = self.client.get('/query?content=') self.assertEqual(result.status_code, 400) def test_invalid_query_none(self): result = self.client.get('/query?') self.assertEqual(result.status_code, 400) def test_valid_url(self): result = self.client.get('/') self.assertEqual(result.status_code, 200) def test_valid_query(self): result = self.client.get('/query?content=farmer_sms') self.assertEqual(result.status_code, 200)
<commit_before>#!/usr/bin/env python import unittest # This line is important so flake8 must ignore this one from app import views # flake8: noqa from app import mulungwishi_app class URLTest(unittest.TestCase): def setUp(self): self.client = mulungwishi_app.test_client() self.client.testing = True def test_invalid_url_page_not_found(self): result = self.client.get('/page/not/found') self.assertEqual(result.status_code, 404) def test_invalid_query(self): result = self.client.get('/query?no_content') self.assertEqual(result.status_code, 400) def test_invalid_query_empty(self): result = self.client.get('/query?content') self.assertEqual(result.status_code, 400) def test_invalid_query_none(self): result = self.client.get('/query?') self.assertEqual(result.status_code, 400) def test_valid_url(self): result = self.client.get('/') self.assertEqual(result.status_code, 200) def test_valid_query(self): result = self.client.get('/query?content=farmer_sms') self.assertEqual(result.status_code, 200) <commit_msg>Add test for empty content string on query<commit_after>#!/usr/bin/env python import unittest # This line is important so flake8 must ignore this one from app import views # flake8: noqa from app import mulungwishi_app class URLTest(unittest.TestCase): def setUp(self): self.client = mulungwishi_app.test_client() self.client.testing = True def test_invalid_url_page_not_found(self): result = self.client.get('/page/not/found') self.assertEqual(result.status_code, 404) def test_invalid_query(self): result = self.client.get('/query?no_content') self.assertEqual(result.status_code, 400) def test_invalid_query_empty(self): result = self.client.get('/query?content') self.assertEqual(result.status_code, 400) def test_invalid_query_no_value_assigned(self): result = self.client.get('/query?content=') self.assertEqual(result.status_code, 400) def test_invalid_query_none(self): result = self.client.get('/query?') self.assertEqual(result.status_code, 400) def test_valid_url(self): result = self.client.get('/') self.assertEqual(result.status_code, 200) def test_valid_query(self): result = self.client.get('/query?content=farmer_sms') self.assertEqual(result.status_code, 200)
fdc7f2c88e72af6e6493a70dad7673c9dbfcbde2
opps/images/templatetags/images_tags.py
opps/images/templatetags/images_tags.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} new['flip'] = image.flip new['flop'] = image.flop if image.halign != "": new['halign'] = image.halign if image.valign != "": new['valign'] = image.valign new['fit_in'] = image.fit_in new['smart'] = image.smart if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: new['crop'] = ((image.crop_x1, image.crop_y1), (image.crop_x2, image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs)
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} new['flip'] = image.flip new['flop'] = image.flop """ if image.halign != "": new['halign'] = image.halign if image.valign != "": new['valign'] = image.valign """ new['fit_in'] = image.fit_in new['smart'] = image.smart if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: new['crop'] = ((image.crop_x1, image.crop_y1), (image.crop_x2, image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs)
Remove halign and valign on image_obj
Remove halign and valign on image_obj
Python
mit
opps/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,jeanmask/opps,opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,opps/opps,williamroot/opps,jeanmask/opps,williamroot/opps,williamroot/opps,opps/opps,jeanmask/opps
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} new['flip'] = image.flip new['flop'] = image.flop if image.halign != "": new['halign'] = image.halign if image.valign != "": new['valign'] = image.valign new['fit_in'] = image.fit_in new['smart'] = image.smart if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: new['crop'] = ((image.crop_x1, image.crop_y1), (image.crop_x2, image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs) Remove halign and valign on image_obj
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} new['flip'] = image.flip new['flop'] = image.flop """ if image.halign != "": new['halign'] = image.halign if image.valign != "": new['valign'] = image.valign """ new['fit_in'] = image.fit_in new['smart'] = image.smart if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: new['crop'] = ((image.crop_x1, image.crop_y1), (image.crop_x2, image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} new['flip'] = image.flip new['flop'] = image.flop if image.halign != "": new['halign'] = image.halign if image.valign != "": new['valign'] = image.valign new['fit_in'] = image.fit_in new['smart'] = image.smart if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: new['crop'] = ((image.crop_x1, image.crop_y1), (image.crop_x2, image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs) <commit_msg>Remove halign and valign on image_obj<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} new['flip'] = image.flip new['flop'] = image.flop """ if image.halign != "": new['halign'] = image.halign if image.valign != "": new['valign'] = image.valign """ new['fit_in'] = image.fit_in new['smart'] = image.smart if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: new['crop'] = ((image.crop_x1, image.crop_y1), (image.crop_x2, image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs)
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} new['flip'] = image.flip new['flop'] = image.flop if image.halign != "": new['halign'] = image.halign if image.valign != "": new['valign'] = image.valign new['fit_in'] = image.fit_in new['smart'] = image.smart if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: new['crop'] = ((image.crop_x1, image.crop_y1), (image.crop_x2, image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs) Remove halign and valign on image_obj#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} new['flip'] = image.flip new['flop'] = image.flop """ if image.halign != "": new['halign'] = image.halign if image.valign != "": new['valign'] = image.valign """ new['fit_in'] = image.fit_in new['smart'] = image.smart if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: new['crop'] = ((image.crop_x1, image.crop_y1), (image.crop_x2, image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} new['flip'] = image.flip new['flop'] = image.flop if image.halign != "": new['halign'] = image.halign if image.valign != "": new['valign'] = image.valign new['fit_in'] = image.fit_in new['smart'] = image.smart if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: new['crop'] = ((image.crop_x1, image.crop_y1), (image.crop_x2, image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs) <commit_msg>Remove halign and valign on image_obj<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} new['flip'] = image.flip new['flop'] = image.flop """ if image.halign != "": new['halign'] = image.halign if image.valign != "": new['valign'] = image.valign """ new['fit_in'] = image.fit_in new['smart'] = image.smart if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: new['crop'] = ((image.crop_x1, image.crop_y1), (image.crop_x2, image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs)
7aca9e8cb526e721b88958ddfeac492e667041c3
breakpad.py
breakpad.py
# Copyright (c) 2009 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. """Breakpad for Python. Sends a notification when a process stops on an exception.""" import atexit import getpass import urllib import traceback import sys def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'): print 'Do you want to send a crash report [y/N]? ', if sys.stdin.read(1).lower() == 'y': try: params = { 'args': sys.argv, 'stack': stack, 'user': getpass.getuser(), } request = urllib.urlopen(url, urllib.urlencode(params)) print request.read() request.close() except IOError: print('There was a failure while trying to send the stack trace. Too bad.') #@atexit.register def CheckForException(): if 'test' in sys.modules['__main__'].__file__: # Probably a unit test. return last_tb = getattr(sys, 'last_traceback', None) if last_tb: SendStack(''.join(traceback.format_tb(last_tb)))
# Copyright (c) 2009 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. """Breakpad for Python. Sends a notification when a process stops on an exception.""" import atexit import getpass import urllib import traceback import socket import sys def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'): print 'Do you want to send a crash report [y/N]? ', if sys.stdin.read(1).lower() != 'y': return print 'Sending crash report ...' try: params = { 'args': sys.argv, 'stack': stack, 'user': getpass.getuser(), } request = urllib.urlopen(url, urllib.urlencode(params)) print request.read() request.close() except IOError: print('There was a failure while trying to send the stack trace. Too bad.') def CheckForException(): last_tb = getattr(sys, 'last_traceback', None) if last_tb: SendStack(''.join(traceback.format_tb(last_tb))) if (not 'test' in sys.modules['__main__'].__file__ and socket.gethostname().endswith('.google.com')): # Skip unit tests and we don't want anything from non-googler. atexit.register(CheckForException)
Add a check so non-google employee don't send crash dumps.
Add a check so non-google employee don't send crash dumps. Add a warning message in case the check ever fail. Review URL: http://codereview.chromium.org/460044 git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@33700 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
smikes/depot_tools,kromain/chromium-tools,coreos/depot_tools,Neozaru/depot_tools,G-P-S/depot_tools,fracting/depot_tools,kaiix/depot_tools,liaorubei/depot_tools,withtone/depot_tools,smikes/depot_tools,npe9/depot_tools,Neozaru/depot_tools,Phonebooth/depot_tools,cybertk/depot_tools,smikes/depot_tools,duanwujie/depot_tools,azureplus/chromium_depot_tools,kromain/chromium-tools,duanwujie/depot_tools,hsharsha/depot_tools,cpanelli/-git-clone-https-chromium.googlesource.com-chromium-tools-depot_tools,SuYiling/chrome_depot_tools,Midrya/chromium,CoherentLabs/depot_tools,fracting/depot_tools,xuyuhan/depot_tools,sarvex/depot-tools,airtimemedia/depot_tools,eatbyte/depot_tools,SuYiling/chrome_depot_tools,xuyuhan/depot_tools,eatbyte/depot_tools,eatbyte/depot_tools,jankeromnes/depot_tools,chinmaygarde/depot_tools,disigma/depot_tools,npe9/depot_tools,duanwujie/depot_tools,disigma/depot_tools,cybertk/depot_tools,jankeromnes/depot_tools,npe9/depot_tools,hsharsha/depot_tools,Neozaru/depot_tools,Chilledheart/depot_tools,chinmaygarde/depot_tools,cpanelli/-git-clone-https-chromium.googlesource.com-chromium-tools-depot_tools,chinmaygarde/depot_tools,kromain/chromium-tools,jankeromnes/depot_tools,azunite/chrome_build,withtone/depot_tools,disigma/depot_tools,coreos/depot_tools,Neozaru/depot_tools,fanjunwei/depot_tools,yetu/repotools,primiano/depot_tools,jankeromnes/depot_tools,sarvex/depot-tools,Phonebooth/depot_tools,liaorubei/depot_tools,duongbaoduy/gtools,fanjunwei/depot_tools,Phonebooth/depot_tools,azunite/chrome_build,gcodetogit/depot_tools,primiano/depot_tools,mlufei/depot_tools,azureplus/chromium_depot_tools,sarvex/depot-tools,xuyuhan/depot_tools,smikes/depot_tools,kaiix/depot_tools,Phonebooth/depot_tools,airtimemedia/depot_tools,kromain/chromium-tools,Chilledheart/depot_tools,gcodetogit/depot_tools,primiano/depot_tools,HackFisher/depot_tools,liaorubei/depot_tools,duongbaoduy/gtools,airtimemedia/depot_tools,coreos/depot_tools,HackFisher/depot_tools,aleonliao/depot_tools,G-P-S/depot_tools,Midrya/chromium,fanjunwei/depot_tools,yetu/repotools,aleonliao/depot_tools,HackFisher/depot_tools,Chilledheart/depot_tools,jankeromnes/depot_tools,Neozaru/depot_tools,G-P-S/depot_tools,coreos/depot_tools,npe9/depot_tools,jankeromnes/depot_tools,xuyuhan/depot_tools,mlufei/depot_tools,hsharsha/depot_tools,michalliu/chromium-depot_tools,liaorubei/depot_tools,smikes/depot_tools,Chilledheart/depot_tools,mlufei/depot_tools,cpanelli/-git-clone-https-chromium.googlesource.com-chromium-tools-depot_tools,coreos/depot_tools,gcodetogit/depot_tools,withtone/depot_tools,azureplus/chromium_depot_tools,michalliu/chromium-depot_tools,cybertk/depot_tools,michalliu/chromium-depot_tools,HackFisher/depot_tools,yetu/repotools,G-P-S/depot_tools,duongbaoduy/gtools,ajohnson23/depot_tools,kaiix/depot_tools,ajohnson23/depot_tools,cybertk/depot_tools,fanjunwei/depot_tools,eatbyte/depot_tools,coreos/depot_tools,fracting/depot_tools,michalliu/chromium-depot_tools,SuYiling/chrome_depot_tools,airtimemedia/depot_tools,Chilledheart/depot_tools,Midrya/chromium,cybertk/depot_tools,ajohnson23/depot_tools,sarvex/depot-tools,azunite/chrome_build,aleonliao/depot_tools,jankeromnes/depot_tools,CoherentLabs/depot_tools
# Copyright (c) 2009 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. """Breakpad for Python. Sends a notification when a process stops on an exception.""" import atexit import getpass import urllib import traceback import sys def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'): print 'Do you want to send a crash report [y/N]? ', if sys.stdin.read(1).lower() == 'y': try: params = { 'args': sys.argv, 'stack': stack, 'user': getpass.getuser(), } request = urllib.urlopen(url, urllib.urlencode(params)) print request.read() request.close() except IOError: print('There was a failure while trying to send the stack trace. Too bad.') #@atexit.register def CheckForException(): if 'test' in sys.modules['__main__'].__file__: # Probably a unit test. return last_tb = getattr(sys, 'last_traceback', None) if last_tb: SendStack(''.join(traceback.format_tb(last_tb))) Add a check so non-google employee don't send crash dumps. Add a warning message in case the check ever fail. Review URL: http://codereview.chromium.org/460044 git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@33700 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright (c) 2009 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. """Breakpad for Python. Sends a notification when a process stops on an exception.""" import atexit import getpass import urllib import traceback import socket import sys def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'): print 'Do you want to send a crash report [y/N]? ', if sys.stdin.read(1).lower() != 'y': return print 'Sending crash report ...' try: params = { 'args': sys.argv, 'stack': stack, 'user': getpass.getuser(), } request = urllib.urlopen(url, urllib.urlencode(params)) print request.read() request.close() except IOError: print('There was a failure while trying to send the stack trace. Too bad.') def CheckForException(): last_tb = getattr(sys, 'last_traceback', None) if last_tb: SendStack(''.join(traceback.format_tb(last_tb))) if (not 'test' in sys.modules['__main__'].__file__ and socket.gethostname().endswith('.google.com')): # Skip unit tests and we don't want anything from non-googler. atexit.register(CheckForException)
<commit_before># Copyright (c) 2009 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. """Breakpad for Python. Sends a notification when a process stops on an exception.""" import atexit import getpass import urllib import traceback import sys def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'): print 'Do you want to send a crash report [y/N]? ', if sys.stdin.read(1).lower() == 'y': try: params = { 'args': sys.argv, 'stack': stack, 'user': getpass.getuser(), } request = urllib.urlopen(url, urllib.urlencode(params)) print request.read() request.close() except IOError: print('There was a failure while trying to send the stack trace. Too bad.') #@atexit.register def CheckForException(): if 'test' in sys.modules['__main__'].__file__: # Probably a unit test. return last_tb = getattr(sys, 'last_traceback', None) if last_tb: SendStack(''.join(traceback.format_tb(last_tb))) <commit_msg>Add a check so non-google employee don't send crash dumps. Add a warning message in case the check ever fail. Review URL: http://codereview.chromium.org/460044 git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@33700 0039d316-1c4b-4281-b951-d872f2087c98<commit_after>
# Copyright (c) 2009 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. """Breakpad for Python. Sends a notification when a process stops on an exception.""" import atexit import getpass import urllib import traceback import socket import sys def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'): print 'Do you want to send a crash report [y/N]? ', if sys.stdin.read(1).lower() != 'y': return print 'Sending crash report ...' try: params = { 'args': sys.argv, 'stack': stack, 'user': getpass.getuser(), } request = urllib.urlopen(url, urllib.urlencode(params)) print request.read() request.close() except IOError: print('There was a failure while trying to send the stack trace. Too bad.') def CheckForException(): last_tb = getattr(sys, 'last_traceback', None) if last_tb: SendStack(''.join(traceback.format_tb(last_tb))) if (not 'test' in sys.modules['__main__'].__file__ and socket.gethostname().endswith('.google.com')): # Skip unit tests and we don't want anything from non-googler. atexit.register(CheckForException)
# Copyright (c) 2009 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. """Breakpad for Python. Sends a notification when a process stops on an exception.""" import atexit import getpass import urllib import traceback import sys def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'): print 'Do you want to send a crash report [y/N]? ', if sys.stdin.read(1).lower() == 'y': try: params = { 'args': sys.argv, 'stack': stack, 'user': getpass.getuser(), } request = urllib.urlopen(url, urllib.urlencode(params)) print request.read() request.close() except IOError: print('There was a failure while trying to send the stack trace. Too bad.') #@atexit.register def CheckForException(): if 'test' in sys.modules['__main__'].__file__: # Probably a unit test. return last_tb = getattr(sys, 'last_traceback', None) if last_tb: SendStack(''.join(traceback.format_tb(last_tb))) Add a check so non-google employee don't send crash dumps. Add a warning message in case the check ever fail. Review URL: http://codereview.chromium.org/460044 git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@33700 0039d316-1c4b-4281-b951-d872f2087c98# Copyright (c) 2009 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. """Breakpad for Python. Sends a notification when a process stops on an exception.""" import atexit import getpass import urllib import traceback import socket import sys def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'): print 'Do you want to send a crash report [y/N]? ', if sys.stdin.read(1).lower() != 'y': return print 'Sending crash report ...' try: params = { 'args': sys.argv, 'stack': stack, 'user': getpass.getuser(), } request = urllib.urlopen(url, urllib.urlencode(params)) print request.read() request.close() except IOError: print('There was a failure while trying to send the stack trace. Too bad.') def CheckForException(): last_tb = getattr(sys, 'last_traceback', None) if last_tb: SendStack(''.join(traceback.format_tb(last_tb))) if (not 'test' in sys.modules['__main__'].__file__ and socket.gethostname().endswith('.google.com')): # Skip unit tests and we don't want anything from non-googler. atexit.register(CheckForException)
<commit_before># Copyright (c) 2009 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. """Breakpad for Python. Sends a notification when a process stops on an exception.""" import atexit import getpass import urllib import traceback import sys def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'): print 'Do you want to send a crash report [y/N]? ', if sys.stdin.read(1).lower() == 'y': try: params = { 'args': sys.argv, 'stack': stack, 'user': getpass.getuser(), } request = urllib.urlopen(url, urllib.urlencode(params)) print request.read() request.close() except IOError: print('There was a failure while trying to send the stack trace. Too bad.') #@atexit.register def CheckForException(): if 'test' in sys.modules['__main__'].__file__: # Probably a unit test. return last_tb = getattr(sys, 'last_traceback', None) if last_tb: SendStack(''.join(traceback.format_tb(last_tb))) <commit_msg>Add a check so non-google employee don't send crash dumps. Add a warning message in case the check ever fail. Review URL: http://codereview.chromium.org/460044 git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@33700 0039d316-1c4b-4281-b951-d872f2087c98<commit_after># Copyright (c) 2009 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. """Breakpad for Python. Sends a notification when a process stops on an exception.""" import atexit import getpass import urllib import traceback import socket import sys def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'): print 'Do you want to send a crash report [y/N]? ', if sys.stdin.read(1).lower() != 'y': return print 'Sending crash report ...' try: params = { 'args': sys.argv, 'stack': stack, 'user': getpass.getuser(), } request = urllib.urlopen(url, urllib.urlencode(params)) print request.read() request.close() except IOError: print('There was a failure while trying to send the stack trace. Too bad.') def CheckForException(): last_tb = getattr(sys, 'last_traceback', None) if last_tb: SendStack(''.join(traceback.format_tb(last_tb))) if (not 'test' in sys.modules['__main__'].__file__ and socket.gethostname().endswith('.google.com')): # Skip unit tests and we don't want anything from non-googler. atexit.register(CheckForException)
a37288cb47ea7b5d547c7ed6b7b5aa28a6d9b583
workflowmax/api.py
workflowmax/api.py
from .endpoints import ENDPOINTS from .managers import Manager class WorkflowMax: """An ORM-like interface to the WorkflowMax API""" def __init__(self, credentials): self.credentials = credentials for k, v in ENDPOINTS.items(): setattr(self, v['plural'], Manager(k, credentials)) def __repr__(self): return '%s:\n %s' % (self.__class__.__name__, '\n '.join( v['plural'] for v in ENDPOINTS.values() ))
from .credentials import Credentials from .endpoints import ENDPOINTS from .managers import Manager class WorkflowMax: """An ORM-like interface to the WorkflowMax API""" def __init__(self, credentials): if not isinstance(credentials, Credentials): raise TypeError( 'Expected a Credentials instance, got %s.' % ( type(credentials).__name__, ) ) self.credentials = credentials for k, v in ENDPOINTS.items(): setattr(self, v['plural'], Manager(k, credentials)) def __repr__(self): return '%s:\n %s' % (self.__class__.__name__, '\n '.join( sorted(v['plural'] for v in ENDPOINTS.values()) ))
Check credentials; sort repr output
Check credentials; sort repr output
Python
bsd-3-clause
ABASystems/pyworkflowmax
from .endpoints import ENDPOINTS from .managers import Manager class WorkflowMax: """An ORM-like interface to the WorkflowMax API""" def __init__(self, credentials): self.credentials = credentials for k, v in ENDPOINTS.items(): setattr(self, v['plural'], Manager(k, credentials)) def __repr__(self): return '%s:\n %s' % (self.__class__.__name__, '\n '.join( v['plural'] for v in ENDPOINTS.values() )) Check credentials; sort repr output
from .credentials import Credentials from .endpoints import ENDPOINTS from .managers import Manager class WorkflowMax: """An ORM-like interface to the WorkflowMax API""" def __init__(self, credentials): if not isinstance(credentials, Credentials): raise TypeError( 'Expected a Credentials instance, got %s.' % ( type(credentials).__name__, ) ) self.credentials = credentials for k, v in ENDPOINTS.items(): setattr(self, v['plural'], Manager(k, credentials)) def __repr__(self): return '%s:\n %s' % (self.__class__.__name__, '\n '.join( sorted(v['plural'] for v in ENDPOINTS.values()) ))
<commit_before>from .endpoints import ENDPOINTS from .managers import Manager class WorkflowMax: """An ORM-like interface to the WorkflowMax API""" def __init__(self, credentials): self.credentials = credentials for k, v in ENDPOINTS.items(): setattr(self, v['plural'], Manager(k, credentials)) def __repr__(self): return '%s:\n %s' % (self.__class__.__name__, '\n '.join( v['plural'] for v in ENDPOINTS.values() )) <commit_msg>Check credentials; sort repr output<commit_after>
from .credentials import Credentials from .endpoints import ENDPOINTS from .managers import Manager class WorkflowMax: """An ORM-like interface to the WorkflowMax API""" def __init__(self, credentials): if not isinstance(credentials, Credentials): raise TypeError( 'Expected a Credentials instance, got %s.' % ( type(credentials).__name__, ) ) self.credentials = credentials for k, v in ENDPOINTS.items(): setattr(self, v['plural'], Manager(k, credentials)) def __repr__(self): return '%s:\n %s' % (self.__class__.__name__, '\n '.join( sorted(v['plural'] for v in ENDPOINTS.values()) ))
from .endpoints import ENDPOINTS from .managers import Manager class WorkflowMax: """An ORM-like interface to the WorkflowMax API""" def __init__(self, credentials): self.credentials = credentials for k, v in ENDPOINTS.items(): setattr(self, v['plural'], Manager(k, credentials)) def __repr__(self): return '%s:\n %s' % (self.__class__.__name__, '\n '.join( v['plural'] for v in ENDPOINTS.values() )) Check credentials; sort repr outputfrom .credentials import Credentials from .endpoints import ENDPOINTS from .managers import Manager class WorkflowMax: """An ORM-like interface to the WorkflowMax API""" def __init__(self, credentials): if not isinstance(credentials, Credentials): raise TypeError( 'Expected a Credentials instance, got %s.' % ( type(credentials).__name__, ) ) self.credentials = credentials for k, v in ENDPOINTS.items(): setattr(self, v['plural'], Manager(k, credentials)) def __repr__(self): return '%s:\n %s' % (self.__class__.__name__, '\n '.join( sorted(v['plural'] for v in ENDPOINTS.values()) ))
<commit_before>from .endpoints import ENDPOINTS from .managers import Manager class WorkflowMax: """An ORM-like interface to the WorkflowMax API""" def __init__(self, credentials): self.credentials = credentials for k, v in ENDPOINTS.items(): setattr(self, v['plural'], Manager(k, credentials)) def __repr__(self): return '%s:\n %s' % (self.__class__.__name__, '\n '.join( v['plural'] for v in ENDPOINTS.values() )) <commit_msg>Check credentials; sort repr output<commit_after>from .credentials import Credentials from .endpoints import ENDPOINTS from .managers import Manager class WorkflowMax: """An ORM-like interface to the WorkflowMax API""" def __init__(self, credentials): if not isinstance(credentials, Credentials): raise TypeError( 'Expected a Credentials instance, got %s.' % ( type(credentials).__name__, ) ) self.credentials = credentials for k, v in ENDPOINTS.items(): setattr(self, v['plural'], Manager(k, credentials)) def __repr__(self): return '%s:\n %s' % (self.__class__.__name__, '\n '.join( sorted(v['plural'] for v in ENDPOINTS.values()) ))
190463fb4538654a62b440fc92041383f8b15957
helusers/migrations/0001_add_ad_groups.py
helusers/migrations/0001_add_ad_groups.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-05-12 08:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0001_initial'), ] operations = [ migrations.CreateModel( name='ADGroup', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(db_index=True, max_length=200)), ('display_name', models.CharField(max_length=200)), ], ), migrations.CreateModel( name='ADGroupMapping', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ad_group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='groups', to='helusers.ADGroup')), ('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ad_groups', to='auth.Group')), ], options={ 'verbose_name': 'AD Group Mapping', }, ), migrations.AlterUniqueTogether( name='adgroupmapping', unique_together=set([('group', 'ad_group')]), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-05-12 08:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0001_initial'), ] operations = [ migrations.CreateModel( name='ADGroup', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(db_index=True, max_length=200)), ('display_name', models.CharField(max_length=200)), ], ), migrations.CreateModel( name='ADGroupMapping', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ad_group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='groups', to='helusers.ADGroup')), ('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ad_groups', to='auth.Group')), ], options={ 'verbose_name': 'AD group mapping', 'verbose_name_plural': 'AD group mappings' }, ), migrations.AlterUniqueTogether( name='adgroupmapping', unique_together=set([('group', 'ad_group')]), ), ]
Fix migration for model verbose name changes
Fix migration for model verbose name changes
Python
bsd-2-clause
City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-05-12 08:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0001_initial'), ] operations = [ migrations.CreateModel( name='ADGroup', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(db_index=True, max_length=200)), ('display_name', models.CharField(max_length=200)), ], ), migrations.CreateModel( name='ADGroupMapping', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ad_group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='groups', to='helusers.ADGroup')), ('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ad_groups', to='auth.Group')), ], options={ 'verbose_name': 'AD Group Mapping', }, ), migrations.AlterUniqueTogether( name='adgroupmapping', unique_together=set([('group', 'ad_group')]), ), ] Fix migration for model verbose name changes
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-05-12 08:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0001_initial'), ] operations = [ migrations.CreateModel( name='ADGroup', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(db_index=True, max_length=200)), ('display_name', models.CharField(max_length=200)), ], ), migrations.CreateModel( name='ADGroupMapping', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ad_group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='groups', to='helusers.ADGroup')), ('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ad_groups', to='auth.Group')), ], options={ 'verbose_name': 'AD group mapping', 'verbose_name_plural': 'AD group mappings' }, ), migrations.AlterUniqueTogether( name='adgroupmapping', unique_together=set([('group', 'ad_group')]), ), ]
<commit_before># -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-05-12 08:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0001_initial'), ] operations = [ migrations.CreateModel( name='ADGroup', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(db_index=True, max_length=200)), ('display_name', models.CharField(max_length=200)), ], ), migrations.CreateModel( name='ADGroupMapping', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ad_group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='groups', to='helusers.ADGroup')), ('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ad_groups', to='auth.Group')), ], options={ 'verbose_name': 'AD Group Mapping', }, ), migrations.AlterUniqueTogether( name='adgroupmapping', unique_together=set([('group', 'ad_group')]), ), ] <commit_msg>Fix migration for model verbose name changes<commit_after>
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-05-12 08:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0001_initial'), ] operations = [ migrations.CreateModel( name='ADGroup', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(db_index=True, max_length=200)), ('display_name', models.CharField(max_length=200)), ], ), migrations.CreateModel( name='ADGroupMapping', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ad_group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='groups', to='helusers.ADGroup')), ('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ad_groups', to='auth.Group')), ], options={ 'verbose_name': 'AD group mapping', 'verbose_name_plural': 'AD group mappings' }, ), migrations.AlterUniqueTogether( name='adgroupmapping', unique_together=set([('group', 'ad_group')]), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-05-12 08:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0001_initial'), ] operations = [ migrations.CreateModel( name='ADGroup', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(db_index=True, max_length=200)), ('display_name', models.CharField(max_length=200)), ], ), migrations.CreateModel( name='ADGroupMapping', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ad_group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='groups', to='helusers.ADGroup')), ('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ad_groups', to='auth.Group')), ], options={ 'verbose_name': 'AD Group Mapping', }, ), migrations.AlterUniqueTogether( name='adgroupmapping', unique_together=set([('group', 'ad_group')]), ), ] Fix migration for model verbose name changes# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-05-12 08:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0001_initial'), ] operations = [ migrations.CreateModel( name='ADGroup', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(db_index=True, max_length=200)), ('display_name', models.CharField(max_length=200)), ], ), migrations.CreateModel( name='ADGroupMapping', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ad_group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='groups', to='helusers.ADGroup')), ('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ad_groups', to='auth.Group')), ], options={ 'verbose_name': 'AD group mapping', 'verbose_name_plural': 'AD group mappings' }, ), migrations.AlterUniqueTogether( name='adgroupmapping', unique_together=set([('group', 'ad_group')]), ), ]
<commit_before># -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-05-12 08:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0001_initial'), ] operations = [ migrations.CreateModel( name='ADGroup', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(db_index=True, max_length=200)), ('display_name', models.CharField(max_length=200)), ], ), migrations.CreateModel( name='ADGroupMapping', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ad_group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='groups', to='helusers.ADGroup')), ('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ad_groups', to='auth.Group')), ], options={ 'verbose_name': 'AD Group Mapping', }, ), migrations.AlterUniqueTogether( name='adgroupmapping', unique_together=set([('group', 'ad_group')]), ), ] <commit_msg>Fix migration for model verbose name changes<commit_after># -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-05-12 08:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0001_initial'), ] operations = [ migrations.CreateModel( name='ADGroup', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(db_index=True, max_length=200)), ('display_name', models.CharField(max_length=200)), ], ), migrations.CreateModel( name='ADGroupMapping', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ad_group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='groups', to='helusers.ADGroup')), ('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ad_groups', to='auth.Group')), ], options={ 'verbose_name': 'AD group mapping', 'verbose_name_plural': 'AD group mappings' }, ), migrations.AlterUniqueTogether( name='adgroupmapping', unique_together=set([('group', 'ad_group')]), ), ]
083a8d4f301da2ad665a3fefd13a4381417b1205
imageutils/normalization/tests/test_ui.py
imageutils/normalization/tests/test_ui.py
import numpy as np from numpy.testing import assert_allclose from ..ui import scale_image DATA = np.array([0, 1., 2.]) DATASCL = 0.5 * DATA class TestImageScaling(object): def test_linear(self): """Test linear scaling.""" img = scale_image(DATA, scale='linear') assert_allclose(img, DATASCL, atol=0, rtol=1.e-5) def test_sqrt(self): """Test sqrt scaling.""" img = scale_image(DATA, scale='sqrt') assert_allclose(img, np.sqrt(DATASCL), atol=0, rtol=1.e-5) def test_power(self): """Test power scaling.""" power = 3.0 img = scale_image(DATA, scale='power', power=power) assert_allclose(img, DATASCL**power, atol=0, rtol=1.e-5) def test_log(self): """Test log10 scaling.""" img = scale_image(DATA, scale='log') ref = np.log10(1000 * DATASCL + 1.0) / np.log10(1001.0) assert_allclose(img, ref, atol=0, rtol=1.e-5)
import numpy as np from numpy.testing import assert_allclose from ..ui import scale_image DATA = np.array([0, 1., 2.]) DATASCL = 0.5 * DATA class TestImageScaling(object): def test_linear(self): """Test linear scaling.""" img = scale_image(DATA, scale='linear') assert_allclose(img, DATASCL, atol=0, rtol=1.e-5) def test_sqrt(self): """Test sqrt scaling.""" img = scale_image(DATA, scale='sqrt') assert_allclose(img, np.sqrt(DATASCL), atol=0, rtol=1.e-5) def test_power(self): """Test power scaling.""" power = 3.0 img = scale_image(DATA, scale='power', power=power) assert_allclose(img, DATASCL**power, atol=0, rtol=1.e-5) def test_log(self): """Test log10 scaling.""" img = scale_image(DATA, scale='log') ref = np.log10(1000 * DATASCL + 1.0) / np.log10(1001.0) assert_allclose(img, ref, atol=0, rtol=1.e-5) def test_asinh(self): """Test asinh scaling.""" a = 0.1 img = scale_image(DATA, scale='asinh', asinh_a=a) ref = np.arcsinh(DATASCL / a) / np.arcsinh(1. / a) assert_allclose(img, ref, atol=0, rtol=1.e-5)
Add test for asinh in scale_image
Add test for asinh in scale_image
Python
bsd-3-clause
mhvk/astropy,saimn/astropy,aleksandr-bakanov/astropy,pllim/astropy,astropy/astropy,tbabej/astropy,AustereCuriosity/astropy,StuartLittlefair/astropy,stargaser/astropy,dhomeier/astropy,dhomeier/astropy,MSeifert04/astropy,kelle/astropy,saimn/astropy,lpsinger/astropy,DougBurke/astropy,DougBurke/astropy,kelle/astropy,mhvk/astropy,aleksandr-bakanov/astropy,StuartLittlefair/astropy,tbabej/astropy,funbaker/astropy,tbabej/astropy,bsipocz/astropy,larrybradley/astropy,lpsinger/astropy,stargaser/astropy,pllim/astropy,StuartLittlefair/astropy,MSeifert04/astropy,bsipocz/astropy,bsipocz/astropy,joergdietrich/astropy,stargaser/astropy,larrybradley/astropy,astropy/astropy,MSeifert04/astropy,pllim/astropy,joergdietrich/astropy,mhvk/astropy,funbaker/astropy,kelle/astropy,funbaker/astropy,stargaser/astropy,AustereCuriosity/astropy,dhomeier/astropy,saimn/astropy,joergdietrich/astropy,tbabej/astropy,saimn/astropy,funbaker/astropy,bsipocz/astropy,AustereCuriosity/astropy,AustereCuriosity/astropy,lpsinger/astropy,joergdietrich/astropy,larrybradley/astropy,mhvk/astropy,astropy/astropy,lpsinger/astropy,kelle/astropy,tbabej/astropy,AustereCuriosity/astropy,pllim/astropy,MSeifert04/astropy,saimn/astropy,larrybradley/astropy,lpsinger/astropy,dhomeier/astropy,larrybradley/astropy,joergdietrich/astropy,astropy/astropy,astropy/astropy,pllim/astropy,DougBurke/astropy,aleksandr-bakanov/astropy,StuartLittlefair/astropy,DougBurke/astropy,kelle/astropy,aleksandr-bakanov/astropy,StuartLittlefair/astropy,dhomeier/astropy,mhvk/astropy
import numpy as np from numpy.testing import assert_allclose from ..ui import scale_image DATA = np.array([0, 1., 2.]) DATASCL = 0.5 * DATA class TestImageScaling(object): def test_linear(self): """Test linear scaling.""" img = scale_image(DATA, scale='linear') assert_allclose(img, DATASCL, atol=0, rtol=1.e-5) def test_sqrt(self): """Test sqrt scaling.""" img = scale_image(DATA, scale='sqrt') assert_allclose(img, np.sqrt(DATASCL), atol=0, rtol=1.e-5) def test_power(self): """Test power scaling.""" power = 3.0 img = scale_image(DATA, scale='power', power=power) assert_allclose(img, DATASCL**power, atol=0, rtol=1.e-5) def test_log(self): """Test log10 scaling.""" img = scale_image(DATA, scale='log') ref = np.log10(1000 * DATASCL + 1.0) / np.log10(1001.0) assert_allclose(img, ref, atol=0, rtol=1.e-5) Add test for asinh in scale_image
import numpy as np from numpy.testing import assert_allclose from ..ui import scale_image DATA = np.array([0, 1., 2.]) DATASCL = 0.5 * DATA class TestImageScaling(object): def test_linear(self): """Test linear scaling.""" img = scale_image(DATA, scale='linear') assert_allclose(img, DATASCL, atol=0, rtol=1.e-5) def test_sqrt(self): """Test sqrt scaling.""" img = scale_image(DATA, scale='sqrt') assert_allclose(img, np.sqrt(DATASCL), atol=0, rtol=1.e-5) def test_power(self): """Test power scaling.""" power = 3.0 img = scale_image(DATA, scale='power', power=power) assert_allclose(img, DATASCL**power, atol=0, rtol=1.e-5) def test_log(self): """Test log10 scaling.""" img = scale_image(DATA, scale='log') ref = np.log10(1000 * DATASCL + 1.0) / np.log10(1001.0) assert_allclose(img, ref, atol=0, rtol=1.e-5) def test_asinh(self): """Test asinh scaling.""" a = 0.1 img = scale_image(DATA, scale='asinh', asinh_a=a) ref = np.arcsinh(DATASCL / a) / np.arcsinh(1. / a) assert_allclose(img, ref, atol=0, rtol=1.e-5)
<commit_before>import numpy as np from numpy.testing import assert_allclose from ..ui import scale_image DATA = np.array([0, 1., 2.]) DATASCL = 0.5 * DATA class TestImageScaling(object): def test_linear(self): """Test linear scaling.""" img = scale_image(DATA, scale='linear') assert_allclose(img, DATASCL, atol=0, rtol=1.e-5) def test_sqrt(self): """Test sqrt scaling.""" img = scale_image(DATA, scale='sqrt') assert_allclose(img, np.sqrt(DATASCL), atol=0, rtol=1.e-5) def test_power(self): """Test power scaling.""" power = 3.0 img = scale_image(DATA, scale='power', power=power) assert_allclose(img, DATASCL**power, atol=0, rtol=1.e-5) def test_log(self): """Test log10 scaling.""" img = scale_image(DATA, scale='log') ref = np.log10(1000 * DATASCL + 1.0) / np.log10(1001.0) assert_allclose(img, ref, atol=0, rtol=1.e-5) <commit_msg>Add test for asinh in scale_image<commit_after>
import numpy as np from numpy.testing import assert_allclose from ..ui import scale_image DATA = np.array([0, 1., 2.]) DATASCL = 0.5 * DATA class TestImageScaling(object): def test_linear(self): """Test linear scaling.""" img = scale_image(DATA, scale='linear') assert_allclose(img, DATASCL, atol=0, rtol=1.e-5) def test_sqrt(self): """Test sqrt scaling.""" img = scale_image(DATA, scale='sqrt') assert_allclose(img, np.sqrt(DATASCL), atol=0, rtol=1.e-5) def test_power(self): """Test power scaling.""" power = 3.0 img = scale_image(DATA, scale='power', power=power) assert_allclose(img, DATASCL**power, atol=0, rtol=1.e-5) def test_log(self): """Test log10 scaling.""" img = scale_image(DATA, scale='log') ref = np.log10(1000 * DATASCL + 1.0) / np.log10(1001.0) assert_allclose(img, ref, atol=0, rtol=1.e-5) def test_asinh(self): """Test asinh scaling.""" a = 0.1 img = scale_image(DATA, scale='asinh', asinh_a=a) ref = np.arcsinh(DATASCL / a) / np.arcsinh(1. / a) assert_allclose(img, ref, atol=0, rtol=1.e-5)
import numpy as np from numpy.testing import assert_allclose from ..ui import scale_image DATA = np.array([0, 1., 2.]) DATASCL = 0.5 * DATA class TestImageScaling(object): def test_linear(self): """Test linear scaling.""" img = scale_image(DATA, scale='linear') assert_allclose(img, DATASCL, atol=0, rtol=1.e-5) def test_sqrt(self): """Test sqrt scaling.""" img = scale_image(DATA, scale='sqrt') assert_allclose(img, np.sqrt(DATASCL), atol=0, rtol=1.e-5) def test_power(self): """Test power scaling.""" power = 3.0 img = scale_image(DATA, scale='power', power=power) assert_allclose(img, DATASCL**power, atol=0, rtol=1.e-5) def test_log(self): """Test log10 scaling.""" img = scale_image(DATA, scale='log') ref = np.log10(1000 * DATASCL + 1.0) / np.log10(1001.0) assert_allclose(img, ref, atol=0, rtol=1.e-5) Add test for asinh in scale_imageimport numpy as np from numpy.testing import assert_allclose from ..ui import scale_image DATA = np.array([0, 1., 2.]) DATASCL = 0.5 * DATA class TestImageScaling(object): def test_linear(self): """Test linear scaling.""" img = scale_image(DATA, scale='linear') assert_allclose(img, DATASCL, atol=0, rtol=1.e-5) def test_sqrt(self): """Test sqrt scaling.""" img = scale_image(DATA, scale='sqrt') assert_allclose(img, np.sqrt(DATASCL), atol=0, rtol=1.e-5) def test_power(self): """Test power scaling.""" power = 3.0 img = scale_image(DATA, scale='power', power=power) assert_allclose(img, DATASCL**power, atol=0, rtol=1.e-5) def test_log(self): """Test log10 scaling.""" img = scale_image(DATA, scale='log') ref = np.log10(1000 * DATASCL + 1.0) / np.log10(1001.0) assert_allclose(img, ref, atol=0, rtol=1.e-5) def test_asinh(self): """Test asinh scaling.""" a = 0.1 img = scale_image(DATA, scale='asinh', asinh_a=a) ref = np.arcsinh(DATASCL / a) / np.arcsinh(1. / a) assert_allclose(img, ref, atol=0, rtol=1.e-5)
<commit_before>import numpy as np from numpy.testing import assert_allclose from ..ui import scale_image DATA = np.array([0, 1., 2.]) DATASCL = 0.5 * DATA class TestImageScaling(object): def test_linear(self): """Test linear scaling.""" img = scale_image(DATA, scale='linear') assert_allclose(img, DATASCL, atol=0, rtol=1.e-5) def test_sqrt(self): """Test sqrt scaling.""" img = scale_image(DATA, scale='sqrt') assert_allclose(img, np.sqrt(DATASCL), atol=0, rtol=1.e-5) def test_power(self): """Test power scaling.""" power = 3.0 img = scale_image(DATA, scale='power', power=power) assert_allclose(img, DATASCL**power, atol=0, rtol=1.e-5) def test_log(self): """Test log10 scaling.""" img = scale_image(DATA, scale='log') ref = np.log10(1000 * DATASCL + 1.0) / np.log10(1001.0) assert_allclose(img, ref, atol=0, rtol=1.e-5) <commit_msg>Add test for asinh in scale_image<commit_after>import numpy as np from numpy.testing import assert_allclose from ..ui import scale_image DATA = np.array([0, 1., 2.]) DATASCL = 0.5 * DATA class TestImageScaling(object): def test_linear(self): """Test linear scaling.""" img = scale_image(DATA, scale='linear') assert_allclose(img, DATASCL, atol=0, rtol=1.e-5) def test_sqrt(self): """Test sqrt scaling.""" img = scale_image(DATA, scale='sqrt') assert_allclose(img, np.sqrt(DATASCL), atol=0, rtol=1.e-5) def test_power(self): """Test power scaling.""" power = 3.0 img = scale_image(DATA, scale='power', power=power) assert_allclose(img, DATASCL**power, atol=0, rtol=1.e-5) def test_log(self): """Test log10 scaling.""" img = scale_image(DATA, scale='log') ref = np.log10(1000 * DATASCL + 1.0) / np.log10(1001.0) assert_allclose(img, ref, atol=0, rtol=1.e-5) def test_asinh(self): """Test asinh scaling.""" a = 0.1 img = scale_image(DATA, scale='asinh', asinh_a=a) ref = np.arcsinh(DATASCL / a) / np.arcsinh(1. / a) assert_allclose(img, ref, atol=0, rtol=1.e-5)
e94ab19902cebff55c2aead9697423c9c94e478f
scripts/indices.py
scripts/indices.py
# Indices that need to be added manually: # # invoke shell --no-transaction from pymongo import ASCENDING, DESCENDING db['nodelog'].create_index([ ('__backrefs.logged.node.logs', ASCENDING), ]) db['user'].create_index([ ('emails', ASCENDING), ]) db['user'].create_index([ ('emails', ASCENDING), ('username', ASCENDING), ]) db['node'].create_index([ ('is_deleted', ASCENDING), ('is_collection', ASCENDING), ('is_public', ASCENDING), ('institution_id', ASCENDING), ('is_registration', ASCENDING), ('contributors', ASCENDING), ]) db['node'].create_index([ ('tags', ASCENDING), ('is_public', ASCENDING), ('is_deleted', ASCENDING), ('institution_id', ASCENDING), ])
# Indices that need to be added manually: # # invoke shell --no-transaction from pymongo import ASCENDING, DESCENDING db['user'].create_index([ ('emails', ASCENDING), ]) db['user'].create_index([ ('emails', ASCENDING), ('username', ASCENDING), ]) db['node'].create_index([ ('is_deleted', ASCENDING), ('is_collection', ASCENDING), ('is_public', ASCENDING), ('institution_id', ASCENDING), ('is_registration', ASCENDING), ('contributors', ASCENDING), ]) db['node'].create_index([ ('tags', ASCENDING), ('is_public', ASCENDING), ('is_deleted', ASCENDING), ('institution_id', ASCENDING), ])
Remove index on field that no longer exists
Remove index on field that no longer exists [skip ci]
Python
apache-2.0
samchrisinger/osf.io,Johnetordoff/osf.io,hmoco/osf.io,crcresearch/osf.io,wearpants/osf.io,Nesiehr/osf.io,SSJohns/osf.io,amyshi188/osf.io,erinspace/osf.io,acshi/osf.io,amyshi188/osf.io,DanielSBrown/osf.io,kwierman/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,doublebits/osf.io,hmoco/osf.io,chrisseto/osf.io,SSJohns/osf.io,laurenrevere/osf.io,jnayak1/osf.io,chrisseto/osf.io,monikagrabowska/osf.io,emetsger/osf.io,adlius/osf.io,mattclark/osf.io,RomanZWang/osf.io,chennan47/osf.io,saradbowman/osf.io,SSJohns/osf.io,hmoco/osf.io,acshi/osf.io,wearpants/osf.io,erinspace/osf.io,acshi/osf.io,kch8qx/osf.io,baylee-d/osf.io,saradbowman/osf.io,kch8qx/osf.io,wearpants/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,abought/osf.io,RomanZWang/osf.io,HalcyonChimera/osf.io,leb2dg/osf.io,DanielSBrown/osf.io,laurenrevere/osf.io,baylee-d/osf.io,cslzchen/osf.io,mluke93/osf.io,zachjanicki/osf.io,leb2dg/osf.io,zamattiac/osf.io,kwierman/osf.io,baylee-d/osf.io,crcresearch/osf.io,mluke93/osf.io,mfraezz/osf.io,felliott/osf.io,amyshi188/osf.io,monikagrabowska/osf.io,TomHeatwole/osf.io,erinspace/osf.io,acshi/osf.io,chennan47/osf.io,acshi/osf.io,emetsger/osf.io,alexschiller/osf.io,DanielSBrown/osf.io,amyshi188/osf.io,TomBaxter/osf.io,leb2dg/osf.io,rdhyee/osf.io,alexschiller/osf.io,mluo613/osf.io,mluo613/osf.io,Nesiehr/osf.io,CenterForOpenScience/osf.io,binoculars/osf.io,samchrisinger/osf.io,mattclark/osf.io,mfraezz/osf.io,aaxelb/osf.io,chennan47/osf.io,brianjgeiger/osf.io,chrisseto/osf.io,binoculars/osf.io,alexschiller/osf.io,abought/osf.io,mluo613/osf.io,jnayak1/osf.io,HalcyonChimera/osf.io,icereval/osf.io,jnayak1/osf.io,mfraezz/osf.io,kch8qx/osf.io,kch8qx/osf.io,RomanZWang/osf.io,CenterForOpenScience/osf.io,aaxelb/osf.io,abought/osf.io,zamattiac/osf.io,cslzchen/osf.io,brianjgeiger/osf.io,leb2dg/osf.io,caneruguz/osf.io,SSJohns/osf.io,wearpants/osf.io,icereval/osf.io,pattisdr/osf.io,adlius/osf.io,caneruguz/osf.io,zachjanicki/osf.io,alexschiller/osf.io,abought/osf.io,caneruguz/osf.io,adlius/osf.io,samchrisinger/osf.io,kwierman/osf.io,caseyrollins/osf.io,hmoco/osf.io,aaxelb/osf.io,mfraezz/osf.io,zamattiac/osf.io,HalcyonChimera/osf.io,TomBaxter/osf.io,doublebits/osf.io,rdhyee/osf.io,RomanZWang/osf.io,jnayak1/osf.io,emetsger/osf.io,doublebits/osf.io,aaxelb/osf.io,caneruguz/osf.io,caseyrollins/osf.io,binoculars/osf.io,brianjgeiger/osf.io,cwisecarver/osf.io,TomBaxter/osf.io,zachjanicki/osf.io,kch8qx/osf.io,Johnetordoff/osf.io,monikagrabowska/osf.io,felliott/osf.io,cslzchen/osf.io,mattclark/osf.io,doublebits/osf.io,sloria/osf.io,rdhyee/osf.io,caseyrollins/osf.io,mluke93/osf.io,sloria/osf.io,Johnetordoff/osf.io,zachjanicki/osf.io,mluo613/osf.io,mluo613/osf.io,sloria/osf.io,felliott/osf.io,felliott/osf.io,kwierman/osf.io,zamattiac/osf.io,CenterForOpenScience/osf.io,monikagrabowska/osf.io,cwisecarver/osf.io,monikagrabowska/osf.io,Nesiehr/osf.io,mluke93/osf.io,adlius/osf.io,doublebits/osf.io,DanielSBrown/osf.io,emetsger/osf.io,TomHeatwole/osf.io,TomHeatwole/osf.io,icereval/osf.io,brianjgeiger/osf.io,cwisecarver/osf.io,Nesiehr/osf.io,rdhyee/osf.io,crcresearch/osf.io,samchrisinger/osf.io,cwisecarver/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,laurenrevere/osf.io,pattisdr/osf.io,alexschiller/osf.io,TomHeatwole/osf.io,RomanZWang/osf.io
# Indices that need to be added manually: # # invoke shell --no-transaction from pymongo import ASCENDING, DESCENDING db['nodelog'].create_index([ ('__backrefs.logged.node.logs', ASCENDING), ]) db['user'].create_index([ ('emails', ASCENDING), ]) db['user'].create_index([ ('emails', ASCENDING), ('username', ASCENDING), ]) db['node'].create_index([ ('is_deleted', ASCENDING), ('is_collection', ASCENDING), ('is_public', ASCENDING), ('institution_id', ASCENDING), ('is_registration', ASCENDING), ('contributors', ASCENDING), ]) db['node'].create_index([ ('tags', ASCENDING), ('is_public', ASCENDING), ('is_deleted', ASCENDING), ('institution_id', ASCENDING), ]) Remove index on field that no longer exists [skip ci]
# Indices that need to be added manually: # # invoke shell --no-transaction from pymongo import ASCENDING, DESCENDING db['user'].create_index([ ('emails', ASCENDING), ]) db['user'].create_index([ ('emails', ASCENDING), ('username', ASCENDING), ]) db['node'].create_index([ ('is_deleted', ASCENDING), ('is_collection', ASCENDING), ('is_public', ASCENDING), ('institution_id', ASCENDING), ('is_registration', ASCENDING), ('contributors', ASCENDING), ]) db['node'].create_index([ ('tags', ASCENDING), ('is_public', ASCENDING), ('is_deleted', ASCENDING), ('institution_id', ASCENDING), ])
<commit_before># Indices that need to be added manually: # # invoke shell --no-transaction from pymongo import ASCENDING, DESCENDING db['nodelog'].create_index([ ('__backrefs.logged.node.logs', ASCENDING), ]) db['user'].create_index([ ('emails', ASCENDING), ]) db['user'].create_index([ ('emails', ASCENDING), ('username', ASCENDING), ]) db['node'].create_index([ ('is_deleted', ASCENDING), ('is_collection', ASCENDING), ('is_public', ASCENDING), ('institution_id', ASCENDING), ('is_registration', ASCENDING), ('contributors', ASCENDING), ]) db['node'].create_index([ ('tags', ASCENDING), ('is_public', ASCENDING), ('is_deleted', ASCENDING), ('institution_id', ASCENDING), ]) <commit_msg>Remove index on field that no longer exists [skip ci]<commit_after>
# Indices that need to be added manually: # # invoke shell --no-transaction from pymongo import ASCENDING, DESCENDING db['user'].create_index([ ('emails', ASCENDING), ]) db['user'].create_index([ ('emails', ASCENDING), ('username', ASCENDING), ]) db['node'].create_index([ ('is_deleted', ASCENDING), ('is_collection', ASCENDING), ('is_public', ASCENDING), ('institution_id', ASCENDING), ('is_registration', ASCENDING), ('contributors', ASCENDING), ]) db['node'].create_index([ ('tags', ASCENDING), ('is_public', ASCENDING), ('is_deleted', ASCENDING), ('institution_id', ASCENDING), ])
# Indices that need to be added manually: # # invoke shell --no-transaction from pymongo import ASCENDING, DESCENDING db['nodelog'].create_index([ ('__backrefs.logged.node.logs', ASCENDING), ]) db['user'].create_index([ ('emails', ASCENDING), ]) db['user'].create_index([ ('emails', ASCENDING), ('username', ASCENDING), ]) db['node'].create_index([ ('is_deleted', ASCENDING), ('is_collection', ASCENDING), ('is_public', ASCENDING), ('institution_id', ASCENDING), ('is_registration', ASCENDING), ('contributors', ASCENDING), ]) db['node'].create_index([ ('tags', ASCENDING), ('is_public', ASCENDING), ('is_deleted', ASCENDING), ('institution_id', ASCENDING), ]) Remove index on field that no longer exists [skip ci]# Indices that need to be added manually: # # invoke shell --no-transaction from pymongo import ASCENDING, DESCENDING db['user'].create_index([ ('emails', ASCENDING), ]) db['user'].create_index([ ('emails', ASCENDING), ('username', ASCENDING), ]) db['node'].create_index([ ('is_deleted', ASCENDING), ('is_collection', ASCENDING), ('is_public', ASCENDING), ('institution_id', ASCENDING), ('is_registration', ASCENDING), ('contributors', ASCENDING), ]) db['node'].create_index([ ('tags', ASCENDING), ('is_public', ASCENDING), ('is_deleted', ASCENDING), ('institution_id', ASCENDING), ])
<commit_before># Indices that need to be added manually: # # invoke shell --no-transaction from pymongo import ASCENDING, DESCENDING db['nodelog'].create_index([ ('__backrefs.logged.node.logs', ASCENDING), ]) db['user'].create_index([ ('emails', ASCENDING), ]) db['user'].create_index([ ('emails', ASCENDING), ('username', ASCENDING), ]) db['node'].create_index([ ('is_deleted', ASCENDING), ('is_collection', ASCENDING), ('is_public', ASCENDING), ('institution_id', ASCENDING), ('is_registration', ASCENDING), ('contributors', ASCENDING), ]) db['node'].create_index([ ('tags', ASCENDING), ('is_public', ASCENDING), ('is_deleted', ASCENDING), ('institution_id', ASCENDING), ]) <commit_msg>Remove index on field that no longer exists [skip ci]<commit_after># Indices that need to be added manually: # # invoke shell --no-transaction from pymongo import ASCENDING, DESCENDING db['user'].create_index([ ('emails', ASCENDING), ]) db['user'].create_index([ ('emails', ASCENDING), ('username', ASCENDING), ]) db['node'].create_index([ ('is_deleted', ASCENDING), ('is_collection', ASCENDING), ('is_public', ASCENDING), ('institution_id', ASCENDING), ('is_registration', ASCENDING), ('contributors', ASCENDING), ]) db['node'].create_index([ ('tags', ASCENDING), ('is_public', ASCENDING), ('is_deleted', ASCENDING), ('institution_id', ASCENDING), ])
4e7fb558ba6411a33e0e1a2feeffad4d8647e17d
scipy/fftpack/__init__.py
scipy/fftpack/__init__.py
# # fftpack - Discrete Fourier Transform algorithms. # # Created: Pearu Peterson, August,September 2002 from info import __all__,__doc__ from fftpack_version import fftpack_version as __version__ from basic import * from pseudo_diffs import * from helper import * from numpy.dual import register_func for k in ['fft', 'ifft', 'fftn', 'ifftn', 'fft2', 'ifft2']: register_func(k, eval(k)) del k, register_func from numpy.testing import Tester test = Tester().test bench = Tester().bench
# # fftpack - Discrete Fourier Transform algorithms. # # Created: Pearu Peterson, August,September 2002 from info import __all__,__doc__ from fftpack_version import fftpack_version as __version__ from basic import * from pseudo_diffs import * from helper import * from numpy.dual import register_func for k in ['fft', 'ifft', 'fftn', 'ifftn', 'fft2', 'ifft2']: register_func(k, eval(k)) del k, register_func from realtransforms import * __all__.extend(['dct', 'idct']) from numpy.testing import Tester test = Tester().test bench = Tester().bench
Add dct and idct in scipy.fftpack namespace.
Add dct and idct in scipy.fftpack namespace.
Python
bsd-3-clause
felipebetancur/scipy,piyush0609/scipy,mgaitan/scipy,Eric89GXL/scipy,vanpact/scipy,pschella/scipy,piyush0609/scipy,arokem/scipy,njwilson23/scipy,vberaudi/scipy,grlee77/scipy,minhlongdo/scipy,ales-erjavec/scipy,argriffing/scipy,rgommers/scipy,maniteja123/scipy,ilayn/scipy,endolith/scipy,endolith/scipy,petebachant/scipy,zaxliu/scipy,nvoron23/scipy,mortada/scipy,person142/scipy,behzadnouri/scipy,andyfaff/scipy,piyush0609/scipy,anntzer/scipy,jjhelmus/scipy,andyfaff/scipy,lhilt/scipy,pyramania/scipy,rmcgibbo/scipy,giorgiop/scipy,apbard/scipy,ChanderG/scipy,grlee77/scipy,newemailjdm/scipy,dch312/scipy,e-q/scipy,Newman101/scipy,kalvdans/scipy,fredrikw/scipy,mikebenfield/scipy,mdhaber/scipy,Stefan-Endres/scipy,zerothi/scipy,surhudm/scipy,sonnyhu/scipy,mdhaber/scipy,petebachant/scipy,gfyoung/scipy,WarrenWeckesser/scipy,larsmans/scipy,jjhelmus/scipy,jor-/scipy,vberaudi/scipy,nonhermitian/scipy,grlee77/scipy,woodscn/scipy,efiring/scipy,niknow/scipy,gdooper/scipy,rgommers/scipy,rgommers/scipy,giorgiop/scipy,jamestwebber/scipy,kleskjr/scipy,haudren/scipy,dch312/scipy,FRidh/scipy,woodscn/scipy,futurulus/scipy,endolith/scipy,mgaitan/scipy,rgommers/scipy,ogrisel/scipy,andyfaff/scipy,njwilson23/scipy,lukauskas/scipy,raoulbq/scipy,lhilt/scipy,dominicelse/scipy,cpaulik/scipy,FRidh/scipy,zxsted/scipy,sriki18/scipy,lukauskas/scipy,jamestwebber/scipy,anielsen001/scipy,befelix/scipy,kalvdans/scipy,vberaudi/scipy,trankmichael/scipy,chatcannon/scipy,cpaulik/scipy,gertingold/scipy,raoulbq/scipy,jseabold/scipy,aeklant/scipy,Eric89GXL/scipy,tylerjereddy/scipy,jjhelmus/scipy,perimosocordiae/scipy,newemailjdm/scipy,scipy/scipy,ChanderG/scipy,haudren/scipy,Srisai85/scipy,Stefan-Endres/scipy,vhaasteren/scipy,jakevdp/scipy,WarrenWeckesser/scipy,apbard/scipy,WillieMaddox/scipy,jsilter/scipy,jor-/scipy,sauliusl/scipy,piyush0609/scipy,andim/scipy,larsmans/scipy,petebachant/scipy,matthewalbani/scipy,kalvdans/scipy,larsmans/scipy,jakevdp/scipy,cpaulik/scipy,njwilson23/scipy,newemailjdm/scipy,sriki18/scipy,ndchorley/scipy,lukauskas/scipy,juliantaylor/scipy,minhlongdo/scipy,teoliphant/scipy,teoliphant/scipy,trankmichael/scipy,vigna/scipy,jseabold/scipy,jor-/scipy,ortylp/scipy,aarchiba/scipy,aman-iitj/scipy,mhogg/scipy,mgaitan/scipy,andyfaff/scipy,Eric89GXL/scipy,vigna/scipy,jor-/scipy,Dapid/scipy,Kamp9/scipy,bkendzior/scipy,sonnyhu/scipy,piyush0609/scipy,sauliusl/scipy,mikebenfield/scipy,arokem/scipy,ales-erjavec/scipy,zerothi/scipy,nmayorov/scipy,rgommers/scipy,chatcannon/scipy,arokem/scipy,nonhermitian/scipy,efiring/scipy,pbrod/scipy,fredrikw/scipy,mortada/scipy,ogrisel/scipy,larsmans/scipy,mtrbean/scipy,petebachant/scipy,vigna/scipy,pizzathief/scipy,futurulus/scipy,niknow/scipy,pschella/scipy,Srisai85/scipy,rmcgibbo/scipy,Kamp9/scipy,jonycgn/scipy,Stefan-Endres/scipy,chatcannon/scipy,pizzathief/scipy,jonycgn/scipy,Newman101/scipy,argriffing/scipy,ndchorley/scipy,jamestwebber/scipy,richardotis/scipy,mingwpy/scipy,maniteja123/scipy,ilayn/scipy,vhaasteren/scipy,dominicelse/scipy,fernand/scipy,Dapid/scipy,cpaulik/scipy,richardotis/scipy,gertingold/scipy,pizzathief/scipy,mortada/scipy,ales-erjavec/scipy,felipebetancur/scipy,niknow/scipy,Gillu13/scipy,mdhaber/scipy,pyramania/scipy,mikebenfield/scipy,jonycgn/scipy,zaxliu/scipy,anntzer/scipy,fernand/scipy,pbrod/scipy,scipy/scipy,Dapid/scipy,sriki18/scipy,gef756/scipy,mhogg/scipy,pnedunuri/scipy,scipy/scipy,trankmichael/scipy,surhudm/scipy,juliantaylor/scipy,ortylp/scipy,sauliusl/scipy,Shaswat27/scipy,sonnyhu/scipy,dominicelse/scipy,matthew-brett/scipy,sonnyhu/scipy,jor-/scipy,anielsen001/scipy,befelix/scipy,witcxc/scipy,Shaswat27/scipy,trankmichael/scipy,aman-iitj/scipy,haudren/scipy,zerothi/scipy,giorgiop/scipy,jonycgn/scipy,piyush0609/scipy,Newman101/scipy,Dapid/scipy,witcxc/scipy,mtrbean/scipy,mdhaber/scipy,efiring/scipy,Shaswat27/scipy,mortonjt/scipy,matthew-brett/scipy,kleskjr/scipy,kleskjr/scipy,Kamp9/scipy,Stefan-Endres/scipy,fernand/scipy,dominicelse/scipy,dch312/scipy,Stefan-Endres/scipy,vanpact/scipy,richardotis/scipy,vhaasteren/scipy,vanpact/scipy,maniteja123/scipy,dominicelse/scipy,anntzer/scipy,mingwpy/scipy,nonhermitian/scipy,ilayn/scipy,Srisai85/scipy,sauliusl/scipy,mortada/scipy,argriffing/scipy,efiring/scipy,behzadnouri/scipy,matthew-brett/scipy,lhilt/scipy,jsilter/scipy,aman-iitj/scipy,zerothi/scipy,Newman101/scipy,Kamp9/scipy,e-q/scipy,jseabold/scipy,pyramania/scipy,jamestwebber/scipy,larsmans/scipy,Srisai85/scipy,gef756/scipy,surhudm/scipy,mtrbean/scipy,mikebenfield/scipy,pnedunuri/scipy,ChanderG/scipy,vberaudi/scipy,surhudm/scipy,fernand/scipy,aeklant/scipy,Kamp9/scipy,giorgiop/scipy,andim/scipy,matthewalbani/scipy,sauliusl/scipy,argriffing/scipy,hainm/scipy,haudren/scipy,surhudm/scipy,teoliphant/scipy,mortonjt/scipy,josephcslater/scipy,mhogg/scipy,rmcgibbo/scipy,gfyoung/scipy,jonycgn/scipy,aarchiba/scipy,Newman101/scipy,Stefan-Endres/scipy,perimosocordiae/scipy,matthew-brett/scipy,maniteja123/scipy,gef756/scipy,mikebenfield/scipy,gertingold/scipy,futurulus/scipy,jamestwebber/scipy,haudren/scipy,vhaasteren/scipy,maniteja123/scipy,giorgiop/scipy,fredrikw/scipy,nmayorov/scipy,jonycgn/scipy,aarchiba/scipy,ilayn/scipy,surhudm/scipy,njwilson23/scipy,njwilson23/scipy,WarrenWeckesser/scipy,vanpact/scipy,maniteja123/scipy,e-q/scipy,rmcgibbo/scipy,trankmichael/scipy,mingwpy/scipy,Gillu13/scipy,tylerjereddy/scipy,ortylp/scipy,person142/scipy,behzadnouri/scipy,arokem/scipy,ilayn/scipy,ChanderG/scipy,jsilter/scipy,witcxc/scipy,futurulus/scipy,aman-iitj/scipy,hainm/scipy,jsilter/scipy,perimosocordiae/scipy,endolith/scipy,WillieMaddox/scipy,WarrenWeckesser/scipy,raoulbq/scipy,cpaulik/scipy,person142/scipy,sargas/scipy,anielsen001/scipy,sargas/scipy,nmayorov/scipy,pnedunuri/scipy,ogrisel/scipy,zerothi/scipy,sargas/scipy,mhogg/scipy,argriffing/scipy,Eric89GXL/scipy,gef756/scipy,befelix/scipy,felipebetancur/scipy,anielsen001/scipy,befelix/scipy,mortada/scipy,WillieMaddox/scipy,andim/scipy,ales-erjavec/scipy,gfyoung/scipy,pschella/scipy,zxsted/scipy,teoliphant/scipy,kleskjr/scipy,vhaasteren/scipy,person142/scipy,jakevdp/scipy,jseabold/scipy,zerothi/scipy,mtrbean/scipy,bkendzior/scipy,sonnyhu/scipy,jseabold/scipy,josephcslater/scipy,josephcslater/scipy,Dapid/scipy,jjhelmus/scipy,argriffing/scipy,juliantaylor/scipy,FRidh/scipy,hainm/scipy,vigna/scipy,trankmichael/scipy,dch312/scipy,mtrbean/scipy,nonhermitian/scipy,efiring/scipy,jseabold/scipy,aarchiba/scipy,chatcannon/scipy,Shaswat27/scipy,gdooper/scipy,raoulbq/scipy,anielsen001/scipy,scipy/scipy,mortonjt/scipy,Gillu13/scipy,rmcgibbo/scipy,pbrod/scipy,hainm/scipy,gef756/scipy,zaxliu/scipy,vhaasteren/scipy,fredrikw/scipy,gdooper/scipy,njwilson23/scipy,anntzer/scipy,gertingold/scipy,efiring/scipy,lhilt/scipy,gfyoung/scipy,nvoron23/scipy,jsilter/scipy,matthewalbani/scipy,minhlongdo/scipy,tylerjereddy/scipy,josephcslater/scipy,woodscn/scipy,aeklant/scipy,aman-iitj/scipy,minhlongdo/scipy,kalvdans/scipy,josephcslater/scipy,lukauskas/scipy,maciejkula/scipy,anielsen001/scipy,andyfaff/scipy,nvoron23/scipy,perimosocordiae/scipy,behzadnouri/scipy,niknow/scipy,jakevdp/scipy,chatcannon/scipy,mortonjt/scipy,mgaitan/scipy,nmayorov/scipy,FRidh/scipy,Eric89GXL/scipy,arokem/scipy,petebachant/scipy,mgaitan/scipy,pnedunuri/scipy,Shaswat27/scipy,behzadnouri/scipy,ChanderG/scipy,pyramania/scipy,matthew-brett/scipy,Gillu13/scipy,maciejkula/scipy,pyramania/scipy,ortylp/scipy,bkendzior/scipy,mortonjt/scipy,felipebetancur/scipy,vberaudi/scipy,gef756/scipy,niknow/scipy,zxsted/scipy,sriki18/scipy,andim/scipy,witcxc/scipy,e-q/scipy,richardotis/scipy,giorgiop/scipy,mortada/scipy,ortylp/scipy,apbard/scipy,juliantaylor/scipy,witcxc/scipy,niknow/scipy,perimosocordiae/scipy,richardotis/scipy,mhogg/scipy,matthewalbani/scipy,cpaulik/scipy,futurulus/scipy,pbrod/scipy,nvoron23/scipy,pizzathief/scipy,felipebetancur/scipy,petebachant/scipy,vanpact/scipy,sauliusl/scipy,dch312/scipy,jjhelmus/scipy,pschella/scipy,rmcgibbo/scipy,hainm/scipy,e-q/scipy,ndchorley/scipy,woodscn/scipy,nmayorov/scipy,woodscn/scipy,sargas/scipy,person142/scipy,ogrisel/scipy,newemailjdm/scipy,gdooper/scipy,apbard/scipy,jakevdp/scipy,sriki18/scipy,sonnyhu/scipy,ndchorley/scipy,Gillu13/scipy,endolith/scipy,aeklant/scipy,andyfaff/scipy,WillieMaddox/scipy,newemailjdm/scipy,zxsted/scipy,WarrenWeckesser/scipy,richardotis/scipy,juliantaylor/scipy,fernand/scipy,grlee77/scipy,mingwpy/scipy,fredrikw/scipy,mgaitan/scipy,zaxliu/scipy,behzadnouri/scipy,FRidh/scipy,aman-iitj/scipy,sriki18/scipy,sargas/scipy,aeklant/scipy,mdhaber/scipy,scipy/scipy,pnedunuri/scipy,tylerjereddy/scipy,pnedunuri/scipy,pbrod/scipy,mhogg/scipy,newemailjdm/scipy,Newman101/scipy,chatcannon/scipy,zxsted/scipy,Shaswat27/scipy,ilayn/scipy,WillieMaddox/scipy,pschella/scipy,FRidh/scipy,hainm/scipy,lukauskas/scipy,minhlongdo/scipy,zxsted/scipy,WarrenWeckesser/scipy,pbrod/scipy,Srisai85/scipy,anntzer/scipy,nonhermitian/scipy,Gillu13/scipy,ChanderG/scipy,maciejkula/scipy,aarchiba/scipy,kleskjr/scipy,larsmans/scipy,minhlongdo/scipy,lukauskas/scipy,perimosocordiae/scipy,andim/scipy,bkendzior/scipy,ales-erjavec/scipy,ortylp/scipy,fredrikw/scipy,matthewalbani/scipy,woodscn/scipy,felipebetancur/scipy,ndchorley/scipy,mtrbean/scipy,gdooper/scipy,lhilt/scipy,maciejkula/scipy,Kamp9/scipy,mingwpy/scipy,anntzer/scipy,andim/scipy,WillieMaddox/scipy,befelix/scipy,mdhaber/scipy,pizzathief/scipy,grlee77/scipy,nvoron23/scipy,zaxliu/scipy,futurulus/scipy,haudren/scipy,scipy/scipy,fernand/scipy,vigna/scipy,vberaudi/scipy,gertingold/scipy,nvoron23/scipy,teoliphant/scipy,ogrisel/scipy,kleskjr/scipy,Eric89GXL/scipy,mingwpy/scipy,raoulbq/scipy,tylerjereddy/scipy,zaxliu/scipy,apbard/scipy,raoulbq/scipy,gfyoung/scipy,Dapid/scipy,bkendzior/scipy,mortonjt/scipy,maciejkula/scipy,Srisai85/scipy,ales-erjavec/scipy,endolith/scipy,kalvdans/scipy,vanpact/scipy,ndchorley/scipy
# # fftpack - Discrete Fourier Transform algorithms. # # Created: Pearu Peterson, August,September 2002 from info import __all__,__doc__ from fftpack_version import fftpack_version as __version__ from basic import * from pseudo_diffs import * from helper import * from numpy.dual import register_func for k in ['fft', 'ifft', 'fftn', 'ifftn', 'fft2', 'ifft2']: register_func(k, eval(k)) del k, register_func from numpy.testing import Tester test = Tester().test bench = Tester().bench Add dct and idct in scipy.fftpack namespace.
# # fftpack - Discrete Fourier Transform algorithms. # # Created: Pearu Peterson, August,September 2002 from info import __all__,__doc__ from fftpack_version import fftpack_version as __version__ from basic import * from pseudo_diffs import * from helper import * from numpy.dual import register_func for k in ['fft', 'ifft', 'fftn', 'ifftn', 'fft2', 'ifft2']: register_func(k, eval(k)) del k, register_func from realtransforms import * __all__.extend(['dct', 'idct']) from numpy.testing import Tester test = Tester().test bench = Tester().bench
<commit_before># # fftpack - Discrete Fourier Transform algorithms. # # Created: Pearu Peterson, August,September 2002 from info import __all__,__doc__ from fftpack_version import fftpack_version as __version__ from basic import * from pseudo_diffs import * from helper import * from numpy.dual import register_func for k in ['fft', 'ifft', 'fftn', 'ifftn', 'fft2', 'ifft2']: register_func(k, eval(k)) del k, register_func from numpy.testing import Tester test = Tester().test bench = Tester().bench <commit_msg>Add dct and idct in scipy.fftpack namespace.<commit_after>
# # fftpack - Discrete Fourier Transform algorithms. # # Created: Pearu Peterson, August,September 2002 from info import __all__,__doc__ from fftpack_version import fftpack_version as __version__ from basic import * from pseudo_diffs import * from helper import * from numpy.dual import register_func for k in ['fft', 'ifft', 'fftn', 'ifftn', 'fft2', 'ifft2']: register_func(k, eval(k)) del k, register_func from realtransforms import * __all__.extend(['dct', 'idct']) from numpy.testing import Tester test = Tester().test bench = Tester().bench
# # fftpack - Discrete Fourier Transform algorithms. # # Created: Pearu Peterson, August,September 2002 from info import __all__,__doc__ from fftpack_version import fftpack_version as __version__ from basic import * from pseudo_diffs import * from helper import * from numpy.dual import register_func for k in ['fft', 'ifft', 'fftn', 'ifftn', 'fft2', 'ifft2']: register_func(k, eval(k)) del k, register_func from numpy.testing import Tester test = Tester().test bench = Tester().bench Add dct and idct in scipy.fftpack namespace.# # fftpack - Discrete Fourier Transform algorithms. # # Created: Pearu Peterson, August,September 2002 from info import __all__,__doc__ from fftpack_version import fftpack_version as __version__ from basic import * from pseudo_diffs import * from helper import * from numpy.dual import register_func for k in ['fft', 'ifft', 'fftn', 'ifftn', 'fft2', 'ifft2']: register_func(k, eval(k)) del k, register_func from realtransforms import * __all__.extend(['dct', 'idct']) from numpy.testing import Tester test = Tester().test bench = Tester().bench
<commit_before># # fftpack - Discrete Fourier Transform algorithms. # # Created: Pearu Peterson, August,September 2002 from info import __all__,__doc__ from fftpack_version import fftpack_version as __version__ from basic import * from pseudo_diffs import * from helper import * from numpy.dual import register_func for k in ['fft', 'ifft', 'fftn', 'ifftn', 'fft2', 'ifft2']: register_func(k, eval(k)) del k, register_func from numpy.testing import Tester test = Tester().test bench = Tester().bench <commit_msg>Add dct and idct in scipy.fftpack namespace.<commit_after># # fftpack - Discrete Fourier Transform algorithms. # # Created: Pearu Peterson, August,September 2002 from info import __all__,__doc__ from fftpack_version import fftpack_version as __version__ from basic import * from pseudo_diffs import * from helper import * from numpy.dual import register_func for k in ['fft', 'ifft', 'fftn', 'ifftn', 'fft2', 'ifft2']: register_func(k, eval(k)) del k, register_func from realtransforms import * __all__.extend(['dct', 'idct']) from numpy.testing import Tester test = Tester().test bench = Tester().bench
ad934e49a43a8340af9d52bbac86bede45d0e84d
aero/adapters/brew.py
aero/adapters/brew.py
# -*- coding: utf-8 -*- __author__ = 'nickl-' from aero.__version__ import __version__ from .base import BaseAdapter class Brew(BaseAdapter): """ Homebrew adapter. """ def search(self, query): response = self.command(['search', query])[0] if 'No formula found' not in response and 'Error:' not in response: return dict([( self.package_name(line), '\n'.join(map( lambda k: k[0] if len(k) < 2 else k[0] + ': ' + k[1], self.search_info(line) )) ) for line in response.splitlines() if line]) return {} def search_info(self, query): info = self.info(query) return filter( None, [ info[0], info[1] if len(info) > 1 else None, info[2] if len(info) > 2 else None, ] ) def info(self, query): if '/' in query: self.command(['tap', '/'.join(query.split('/')[:-1])]) response = self.command(['info', query])[0] if 'Error:' not in response: response = response.replace(query + ': ', 'version: ') return [line.split(': ', 1) for line in response.splitlines() if 'homebrew' not in line] return [['No info available']] def install(self, query): self.shell(['install', query]) return {}
# -*- coding: utf-8 -*- __author__ = 'nickl-' from aero.__version__ import __version__ from .base import BaseAdapter class Brew(BaseAdapter): """ Homebrew adapter. """ def search(self, query): response = self.command(['search', query])[0] if 'No formula found' not in response and 'Error:' not in response: return dict([( self.package_name(line), self.search_info(self.package_name(line)) ) for line in response.splitlines() if line]) return {} def search_info(self, query): response = self._execute_command('aero', ['info', query], False)[0] from re import split lines = response.splitlines() idx = lines.index(' ________________________________________ __________________________________________________ ') return '\n'.join([''.join(split('\x1b.*?m', l)).replace(' : ', '').strip() for l in response.splitlines()[idx+1:idx+4]]) def info(self, query): if '/' in query: self.command(['tap', '/'.join(query.split('/')[:-1])]) response = self.command(['info', query])[0] if 'Error:' not in response: response = response.replace(query + ': ', 'version: ') return [line.split(': ', 1) for line in response.splitlines() if 'homebrew' not in line] return [['No info available']] def install(self, query): self.shell(['install', query]) return {}
Use aero info instead for caching info
Use aero info instead for caching info Brew requires brew info for additional information. If we instead call aero info we can at least cache the info calls for later.
Python
bsd-3-clause
Aeronautics/aero
# -*- coding: utf-8 -*- __author__ = 'nickl-' from aero.__version__ import __version__ from .base import BaseAdapter class Brew(BaseAdapter): """ Homebrew adapter. """ def search(self, query): response = self.command(['search', query])[0] if 'No formula found' not in response and 'Error:' not in response: return dict([( self.package_name(line), '\n'.join(map( lambda k: k[0] if len(k) < 2 else k[0] + ': ' + k[1], self.search_info(line) )) ) for line in response.splitlines() if line]) return {} def search_info(self, query): info = self.info(query) return filter( None, [ info[0], info[1] if len(info) > 1 else None, info[2] if len(info) > 2 else None, ] ) def info(self, query): if '/' in query: self.command(['tap', '/'.join(query.split('/')[:-1])]) response = self.command(['info', query])[0] if 'Error:' not in response: response = response.replace(query + ': ', 'version: ') return [line.split(': ', 1) for line in response.splitlines() if 'homebrew' not in line] return [['No info available']] def install(self, query): self.shell(['install', query]) return {} Use aero info instead for caching info Brew requires brew info for additional information. If we instead call aero info we can at least cache the info calls for later.
# -*- coding: utf-8 -*- __author__ = 'nickl-' from aero.__version__ import __version__ from .base import BaseAdapter class Brew(BaseAdapter): """ Homebrew adapter. """ def search(self, query): response = self.command(['search', query])[0] if 'No formula found' not in response and 'Error:' not in response: return dict([( self.package_name(line), self.search_info(self.package_name(line)) ) for line in response.splitlines() if line]) return {} def search_info(self, query): response = self._execute_command('aero', ['info', query], False)[0] from re import split lines = response.splitlines() idx = lines.index(' ________________________________________ __________________________________________________ ') return '\n'.join([''.join(split('\x1b.*?m', l)).replace(' : ', '').strip() for l in response.splitlines()[idx+1:idx+4]]) def info(self, query): if '/' in query: self.command(['tap', '/'.join(query.split('/')[:-1])]) response = self.command(['info', query])[0] if 'Error:' not in response: response = response.replace(query + ': ', 'version: ') return [line.split(': ', 1) for line in response.splitlines() if 'homebrew' not in line] return [['No info available']] def install(self, query): self.shell(['install', query]) return {}
<commit_before># -*- coding: utf-8 -*- __author__ = 'nickl-' from aero.__version__ import __version__ from .base import BaseAdapter class Brew(BaseAdapter): """ Homebrew adapter. """ def search(self, query): response = self.command(['search', query])[0] if 'No formula found' not in response and 'Error:' not in response: return dict([( self.package_name(line), '\n'.join(map( lambda k: k[0] if len(k) < 2 else k[0] + ': ' + k[1], self.search_info(line) )) ) for line in response.splitlines() if line]) return {} def search_info(self, query): info = self.info(query) return filter( None, [ info[0], info[1] if len(info) > 1 else None, info[2] if len(info) > 2 else None, ] ) def info(self, query): if '/' in query: self.command(['tap', '/'.join(query.split('/')[:-1])]) response = self.command(['info', query])[0] if 'Error:' not in response: response = response.replace(query + ': ', 'version: ') return [line.split(': ', 1) for line in response.splitlines() if 'homebrew' not in line] return [['No info available']] def install(self, query): self.shell(['install', query]) return {} <commit_msg>Use aero info instead for caching info Brew requires brew info for additional information. If we instead call aero info we can at least cache the info calls for later.<commit_after>
# -*- coding: utf-8 -*- __author__ = 'nickl-' from aero.__version__ import __version__ from .base import BaseAdapter class Brew(BaseAdapter): """ Homebrew adapter. """ def search(self, query): response = self.command(['search', query])[0] if 'No formula found' not in response and 'Error:' not in response: return dict([( self.package_name(line), self.search_info(self.package_name(line)) ) for line in response.splitlines() if line]) return {} def search_info(self, query): response = self._execute_command('aero', ['info', query], False)[0] from re import split lines = response.splitlines() idx = lines.index(' ________________________________________ __________________________________________________ ') return '\n'.join([''.join(split('\x1b.*?m', l)).replace(' : ', '').strip() for l in response.splitlines()[idx+1:idx+4]]) def info(self, query): if '/' in query: self.command(['tap', '/'.join(query.split('/')[:-1])]) response = self.command(['info', query])[0] if 'Error:' not in response: response = response.replace(query + ': ', 'version: ') return [line.split(': ', 1) for line in response.splitlines() if 'homebrew' not in line] return [['No info available']] def install(self, query): self.shell(['install', query]) return {}
# -*- coding: utf-8 -*- __author__ = 'nickl-' from aero.__version__ import __version__ from .base import BaseAdapter class Brew(BaseAdapter): """ Homebrew adapter. """ def search(self, query): response = self.command(['search', query])[0] if 'No formula found' not in response and 'Error:' not in response: return dict([( self.package_name(line), '\n'.join(map( lambda k: k[0] if len(k) < 2 else k[0] + ': ' + k[1], self.search_info(line) )) ) for line in response.splitlines() if line]) return {} def search_info(self, query): info = self.info(query) return filter( None, [ info[0], info[1] if len(info) > 1 else None, info[2] if len(info) > 2 else None, ] ) def info(self, query): if '/' in query: self.command(['tap', '/'.join(query.split('/')[:-1])]) response = self.command(['info', query])[0] if 'Error:' not in response: response = response.replace(query + ': ', 'version: ') return [line.split(': ', 1) for line in response.splitlines() if 'homebrew' not in line] return [['No info available']] def install(self, query): self.shell(['install', query]) return {} Use aero info instead for caching info Brew requires brew info for additional information. If we instead call aero info we can at least cache the info calls for later.# -*- coding: utf-8 -*- __author__ = 'nickl-' from aero.__version__ import __version__ from .base import BaseAdapter class Brew(BaseAdapter): """ Homebrew adapter. """ def search(self, query): response = self.command(['search', query])[0] if 'No formula found' not in response and 'Error:' not in response: return dict([( self.package_name(line), self.search_info(self.package_name(line)) ) for line in response.splitlines() if line]) return {} def search_info(self, query): response = self._execute_command('aero', ['info', query], False)[0] from re import split lines = response.splitlines() idx = lines.index(' ________________________________________ __________________________________________________ ') return '\n'.join([''.join(split('\x1b.*?m', l)).replace(' : ', '').strip() for l in response.splitlines()[idx+1:idx+4]]) def info(self, query): if '/' in query: self.command(['tap', '/'.join(query.split('/')[:-1])]) response = self.command(['info', query])[0] if 'Error:' not in response: response = response.replace(query + ': ', 'version: ') return [line.split(': ', 1) for line in response.splitlines() if 'homebrew' not in line] return [['No info available']] def install(self, query): self.shell(['install', query]) return {}
<commit_before># -*- coding: utf-8 -*- __author__ = 'nickl-' from aero.__version__ import __version__ from .base import BaseAdapter class Brew(BaseAdapter): """ Homebrew adapter. """ def search(self, query): response = self.command(['search', query])[0] if 'No formula found' not in response and 'Error:' not in response: return dict([( self.package_name(line), '\n'.join(map( lambda k: k[0] if len(k) < 2 else k[0] + ': ' + k[1], self.search_info(line) )) ) for line in response.splitlines() if line]) return {} def search_info(self, query): info = self.info(query) return filter( None, [ info[0], info[1] if len(info) > 1 else None, info[2] if len(info) > 2 else None, ] ) def info(self, query): if '/' in query: self.command(['tap', '/'.join(query.split('/')[:-1])]) response = self.command(['info', query])[0] if 'Error:' not in response: response = response.replace(query + ': ', 'version: ') return [line.split(': ', 1) for line in response.splitlines() if 'homebrew' not in line] return [['No info available']] def install(self, query): self.shell(['install', query]) return {} <commit_msg>Use aero info instead for caching info Brew requires brew info for additional information. If we instead call aero info we can at least cache the info calls for later.<commit_after># -*- coding: utf-8 -*- __author__ = 'nickl-' from aero.__version__ import __version__ from .base import BaseAdapter class Brew(BaseAdapter): """ Homebrew adapter. """ def search(self, query): response = self.command(['search', query])[0] if 'No formula found' not in response and 'Error:' not in response: return dict([( self.package_name(line), self.search_info(self.package_name(line)) ) for line in response.splitlines() if line]) return {} def search_info(self, query): response = self._execute_command('aero', ['info', query], False)[0] from re import split lines = response.splitlines() idx = lines.index(' ________________________________________ __________________________________________________ ') return '\n'.join([''.join(split('\x1b.*?m', l)).replace(' : ', '').strip() for l in response.splitlines()[idx+1:idx+4]]) def info(self, query): if '/' in query: self.command(['tap', '/'.join(query.split('/')[:-1])]) response = self.command(['info', query])[0] if 'Error:' not in response: response = response.replace(query + ': ', 'version: ') return [line.split(': ', 1) for line in response.splitlines() if 'homebrew' not in line] return [['No info available']] def install(self, query): self.shell(['install', query]) return {}
42d1ac59a1e35d8efd4785939696adbdbf39e1d2
alg_insertion_sort.py
alg_insertion_sort.py
from __future__ import absolute_import from __future__ import print_function from __future__ import division def insertion_sort(a_list): """Insertion Sort algortihm. Time complexity: O(n^2). """ gen = ((i, v) for i, v in enumerate(a_list) if i > 0) for (i, v) in gen: key = i while key > 0 and a_list[key - 1] > v: a_list[key] = a_list[key - 1] key -= 1 a_list[key] = v def main(): a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] insertion_sort(a_list) print(a_list) if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import print_function from __future__ import division def insertion_sort(a_list): """Insertion Sort algortihm. Time complexity: O(n^2). Although its complexity is bigger than the ones with O(n*logn), one advantage is the sorting happens in place. """ gen = ((i, v) for i, v in enumerate(a_list) if i > 0) for (i, v) in gen: key = i while key > 0 and a_list[key - 1] > v: a_list[key] = a_list[key - 1] key -= 1 a_list[key] = v def main(): a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] insertion_sort(a_list) print(a_list) if __name__ == '__main__': main()
Revise docstring by adding advantage
Revise docstring by adding advantage
Python
bsd-2-clause
bowen0701/algorithms_data_structures
from __future__ import absolute_import from __future__ import print_function from __future__ import division def insertion_sort(a_list): """Insertion Sort algortihm. Time complexity: O(n^2). """ gen = ((i, v) for i, v in enumerate(a_list) if i > 0) for (i, v) in gen: key = i while key > 0 and a_list[key - 1] > v: a_list[key] = a_list[key - 1] key -= 1 a_list[key] = v def main(): a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] insertion_sort(a_list) print(a_list) if __name__ == '__main__': main() Revise docstring by adding advantage
from __future__ import absolute_import from __future__ import print_function from __future__ import division def insertion_sort(a_list): """Insertion Sort algortihm. Time complexity: O(n^2). Although its complexity is bigger than the ones with O(n*logn), one advantage is the sorting happens in place. """ gen = ((i, v) for i, v in enumerate(a_list) if i > 0) for (i, v) in gen: key = i while key > 0 and a_list[key - 1] > v: a_list[key] = a_list[key - 1] key -= 1 a_list[key] = v def main(): a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] insertion_sort(a_list) print(a_list) if __name__ == '__main__': main()
<commit_before>from __future__ import absolute_import from __future__ import print_function from __future__ import division def insertion_sort(a_list): """Insertion Sort algortihm. Time complexity: O(n^2). """ gen = ((i, v) for i, v in enumerate(a_list) if i > 0) for (i, v) in gen: key = i while key > 0 and a_list[key - 1] > v: a_list[key] = a_list[key - 1] key -= 1 a_list[key] = v def main(): a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] insertion_sort(a_list) print(a_list) if __name__ == '__main__': main() <commit_msg>Revise docstring by adding advantage<commit_after>
from __future__ import absolute_import from __future__ import print_function from __future__ import division def insertion_sort(a_list): """Insertion Sort algortihm. Time complexity: O(n^2). Although its complexity is bigger than the ones with O(n*logn), one advantage is the sorting happens in place. """ gen = ((i, v) for i, v in enumerate(a_list) if i > 0) for (i, v) in gen: key = i while key > 0 and a_list[key - 1] > v: a_list[key] = a_list[key - 1] key -= 1 a_list[key] = v def main(): a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] insertion_sort(a_list) print(a_list) if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import print_function from __future__ import division def insertion_sort(a_list): """Insertion Sort algortihm. Time complexity: O(n^2). """ gen = ((i, v) for i, v in enumerate(a_list) if i > 0) for (i, v) in gen: key = i while key > 0 and a_list[key - 1] > v: a_list[key] = a_list[key - 1] key -= 1 a_list[key] = v def main(): a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] insertion_sort(a_list) print(a_list) if __name__ == '__main__': main() Revise docstring by adding advantagefrom __future__ import absolute_import from __future__ import print_function from __future__ import division def insertion_sort(a_list): """Insertion Sort algortihm. Time complexity: O(n^2). Although its complexity is bigger than the ones with O(n*logn), one advantage is the sorting happens in place. """ gen = ((i, v) for i, v in enumerate(a_list) if i > 0) for (i, v) in gen: key = i while key > 0 and a_list[key - 1] > v: a_list[key] = a_list[key - 1] key -= 1 a_list[key] = v def main(): a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] insertion_sort(a_list) print(a_list) if __name__ == '__main__': main()
<commit_before>from __future__ import absolute_import from __future__ import print_function from __future__ import division def insertion_sort(a_list): """Insertion Sort algortihm. Time complexity: O(n^2). """ gen = ((i, v) for i, v in enumerate(a_list) if i > 0) for (i, v) in gen: key = i while key > 0 and a_list[key - 1] > v: a_list[key] = a_list[key - 1] key -= 1 a_list[key] = v def main(): a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] insertion_sort(a_list) print(a_list) if __name__ == '__main__': main() <commit_msg>Revise docstring by adding advantage<commit_after>from __future__ import absolute_import from __future__ import print_function from __future__ import division def insertion_sort(a_list): """Insertion Sort algortihm. Time complexity: O(n^2). Although its complexity is bigger than the ones with O(n*logn), one advantage is the sorting happens in place. """ gen = ((i, v) for i, v in enumerate(a_list) if i > 0) for (i, v) in gen: key = i while key > 0 and a_list[key - 1] > v: a_list[key] = a_list[key - 1] key -= 1 a_list[key] = v def main(): a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] insertion_sort(a_list) print(a_list) if __name__ == '__main__': main()
2fdb78366fd8e785ec1c613fa4d2f87064217101
organizer/views.py
organizer/views.py
from django.http.response import HttpResponse from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request): # slug = ? tag = Tag.objects.get(slug__iexact=slug) return HttpResponse()
from django.http.response import HttpResponse from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request): # slug = ? tag = Tag.objects.get(slug__iexact=slug) template = loader.get_template( 'organizer/tag_detail.html') context = Context({'tag': tag}) return HttpResponse(template.render(context))
Tag Detail: load and render template.
Ch05: Tag Detail: load and render template.
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
from django.http.response import HttpResponse from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request): # slug = ? tag = Tag.objects.get(slug__iexact=slug) return HttpResponse() Ch05: Tag Detail: load and render template.
from django.http.response import HttpResponse from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request): # slug = ? tag = Tag.objects.get(slug__iexact=slug) template = loader.get_template( 'organizer/tag_detail.html') context = Context({'tag': tag}) return HttpResponse(template.render(context))
<commit_before>from django.http.response import HttpResponse from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request): # slug = ? tag = Tag.objects.get(slug__iexact=slug) return HttpResponse() <commit_msg>Ch05: Tag Detail: load and render template.<commit_after>
from django.http.response import HttpResponse from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request): # slug = ? tag = Tag.objects.get(slug__iexact=slug) template = loader.get_template( 'organizer/tag_detail.html') context = Context({'tag': tag}) return HttpResponse(template.render(context))
from django.http.response import HttpResponse from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request): # slug = ? tag = Tag.objects.get(slug__iexact=slug) return HttpResponse() Ch05: Tag Detail: load and render template.from django.http.response import HttpResponse from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request): # slug = ? tag = Tag.objects.get(slug__iexact=slug) template = loader.get_template( 'organizer/tag_detail.html') context = Context({'tag': tag}) return HttpResponse(template.render(context))
<commit_before>from django.http.response import HttpResponse from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request): # slug = ? tag = Tag.objects.get(slug__iexact=slug) return HttpResponse() <commit_msg>Ch05: Tag Detail: load and render template.<commit_after>from django.http.response import HttpResponse from django.template import Context, loader from .models import Tag def homepage(request): tag_list = Tag.objects.all() template = loader.get_template( 'organizer/tag_list.html') context = Context({'tag_list': tag_list}) output = template.render(context) return HttpResponse(output) def tag_detail(request): # slug = ? tag = Tag.objects.get(slug__iexact=slug) template = loader.get_template( 'organizer/tag_detail.html') context = Context({'tag': tag}) return HttpResponse(template.render(context))
b1242e9f84afb331f4a3426abeba8e5d27a563c7
wafer/talks/admin.py
wafer/talks/admin.py
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from wafer.talks.models import TalkType, Talk, TalkUrl class ScheduleListFilter(admin.SimpleListFilter): title = _('in schedule') parameter_name = 'schedule' def lookups(self, request, model_admin): return ( ('in', _('Allocated to schedule')), ('out', _('Not allocated')), ) def queryset(self, request, queryset): if self.value() == 'in': return queryset.filter(scheduleitem__isnull=False) return queryset.filter(scheduleitem__isnull=True) class TalkUrlInline(admin.TabularInline): model = TalkUrl class TalkAdmin(admin.ModelAdmin): list_display = ('title', 'get_author_name', 'get_author_contact', 'talk_type', 'get_in_schedule', 'status') list_editable = ('status',) list_filter = ('status', 'talk_type', ScheduleListFilter) inlines = [ TalkUrlInline, ] admin.site.register(Talk, TalkAdmin) admin.site.register(TalkType) admin.site.register(TalkUrl)
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from wafer.talks.models import TalkType, Talk, TalkUrl class ScheduleListFilter(admin.SimpleListFilter): title = _('in schedule') parameter_name = 'schedule' def lookups(self, request, model_admin): return ( ('in', _('Allocated to schedule')), ('out', _('Not allocated')), ) def queryset(self, request, queryset): if self.value() == 'in': return queryset.filter(scheduleitem__isnull=False) elif self.value() == 'out': return queryset.filter(scheduleitem__isnull=True) return queryset class TalkUrlInline(admin.TabularInline): model = TalkUrl class TalkAdmin(admin.ModelAdmin): list_display = ('title', 'get_author_name', 'get_author_contact', 'talk_type', 'get_in_schedule', 'status') list_editable = ('status',) list_filter = ('status', 'talk_type', ScheduleListFilter) inlines = [ TalkUrlInline, ] admin.site.register(Talk, TalkAdmin) admin.site.register(TalkType) admin.site.register(TalkUrl)
Fix logic error in schedule filter
Fix logic error in schedule filter
Python
isc
CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CarlFK/wafer,CTPUG/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from wafer.talks.models import TalkType, Talk, TalkUrl class ScheduleListFilter(admin.SimpleListFilter): title = _('in schedule') parameter_name = 'schedule' def lookups(self, request, model_admin): return ( ('in', _('Allocated to schedule')), ('out', _('Not allocated')), ) def queryset(self, request, queryset): if self.value() == 'in': return queryset.filter(scheduleitem__isnull=False) return queryset.filter(scheduleitem__isnull=True) class TalkUrlInline(admin.TabularInline): model = TalkUrl class TalkAdmin(admin.ModelAdmin): list_display = ('title', 'get_author_name', 'get_author_contact', 'talk_type', 'get_in_schedule', 'status') list_editable = ('status',) list_filter = ('status', 'talk_type', ScheduleListFilter) inlines = [ TalkUrlInline, ] admin.site.register(Talk, TalkAdmin) admin.site.register(TalkType) admin.site.register(TalkUrl) Fix logic error in schedule filter
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from wafer.talks.models import TalkType, Talk, TalkUrl class ScheduleListFilter(admin.SimpleListFilter): title = _('in schedule') parameter_name = 'schedule' def lookups(self, request, model_admin): return ( ('in', _('Allocated to schedule')), ('out', _('Not allocated')), ) def queryset(self, request, queryset): if self.value() == 'in': return queryset.filter(scheduleitem__isnull=False) elif self.value() == 'out': return queryset.filter(scheduleitem__isnull=True) return queryset class TalkUrlInline(admin.TabularInline): model = TalkUrl class TalkAdmin(admin.ModelAdmin): list_display = ('title', 'get_author_name', 'get_author_contact', 'talk_type', 'get_in_schedule', 'status') list_editable = ('status',) list_filter = ('status', 'talk_type', ScheduleListFilter) inlines = [ TalkUrlInline, ] admin.site.register(Talk, TalkAdmin) admin.site.register(TalkType) admin.site.register(TalkUrl)
<commit_before>from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from wafer.talks.models import TalkType, Talk, TalkUrl class ScheduleListFilter(admin.SimpleListFilter): title = _('in schedule') parameter_name = 'schedule' def lookups(self, request, model_admin): return ( ('in', _('Allocated to schedule')), ('out', _('Not allocated')), ) def queryset(self, request, queryset): if self.value() == 'in': return queryset.filter(scheduleitem__isnull=False) return queryset.filter(scheduleitem__isnull=True) class TalkUrlInline(admin.TabularInline): model = TalkUrl class TalkAdmin(admin.ModelAdmin): list_display = ('title', 'get_author_name', 'get_author_contact', 'talk_type', 'get_in_schedule', 'status') list_editable = ('status',) list_filter = ('status', 'talk_type', ScheduleListFilter) inlines = [ TalkUrlInline, ] admin.site.register(Talk, TalkAdmin) admin.site.register(TalkType) admin.site.register(TalkUrl) <commit_msg>Fix logic error in schedule filter<commit_after>
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from wafer.talks.models import TalkType, Talk, TalkUrl class ScheduleListFilter(admin.SimpleListFilter): title = _('in schedule') parameter_name = 'schedule' def lookups(self, request, model_admin): return ( ('in', _('Allocated to schedule')), ('out', _('Not allocated')), ) def queryset(self, request, queryset): if self.value() == 'in': return queryset.filter(scheduleitem__isnull=False) elif self.value() == 'out': return queryset.filter(scheduleitem__isnull=True) return queryset class TalkUrlInline(admin.TabularInline): model = TalkUrl class TalkAdmin(admin.ModelAdmin): list_display = ('title', 'get_author_name', 'get_author_contact', 'talk_type', 'get_in_schedule', 'status') list_editable = ('status',) list_filter = ('status', 'talk_type', ScheduleListFilter) inlines = [ TalkUrlInline, ] admin.site.register(Talk, TalkAdmin) admin.site.register(TalkType) admin.site.register(TalkUrl)
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from wafer.talks.models import TalkType, Talk, TalkUrl class ScheduleListFilter(admin.SimpleListFilter): title = _('in schedule') parameter_name = 'schedule' def lookups(self, request, model_admin): return ( ('in', _('Allocated to schedule')), ('out', _('Not allocated')), ) def queryset(self, request, queryset): if self.value() == 'in': return queryset.filter(scheduleitem__isnull=False) return queryset.filter(scheduleitem__isnull=True) class TalkUrlInline(admin.TabularInline): model = TalkUrl class TalkAdmin(admin.ModelAdmin): list_display = ('title', 'get_author_name', 'get_author_contact', 'talk_type', 'get_in_schedule', 'status') list_editable = ('status',) list_filter = ('status', 'talk_type', ScheduleListFilter) inlines = [ TalkUrlInline, ] admin.site.register(Talk, TalkAdmin) admin.site.register(TalkType) admin.site.register(TalkUrl) Fix logic error in schedule filterfrom django.contrib import admin from django.utils.translation import ugettext_lazy as _ from wafer.talks.models import TalkType, Talk, TalkUrl class ScheduleListFilter(admin.SimpleListFilter): title = _('in schedule') parameter_name = 'schedule' def lookups(self, request, model_admin): return ( ('in', _('Allocated to schedule')), ('out', _('Not allocated')), ) def queryset(self, request, queryset): if self.value() == 'in': return queryset.filter(scheduleitem__isnull=False) elif self.value() == 'out': return queryset.filter(scheduleitem__isnull=True) return queryset class TalkUrlInline(admin.TabularInline): model = TalkUrl class TalkAdmin(admin.ModelAdmin): list_display = ('title', 'get_author_name', 'get_author_contact', 'talk_type', 'get_in_schedule', 'status') list_editable = ('status',) list_filter = ('status', 'talk_type', ScheduleListFilter) inlines = [ TalkUrlInline, ] admin.site.register(Talk, TalkAdmin) admin.site.register(TalkType) admin.site.register(TalkUrl)
<commit_before>from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from wafer.talks.models import TalkType, Talk, TalkUrl class ScheduleListFilter(admin.SimpleListFilter): title = _('in schedule') parameter_name = 'schedule' def lookups(self, request, model_admin): return ( ('in', _('Allocated to schedule')), ('out', _('Not allocated')), ) def queryset(self, request, queryset): if self.value() == 'in': return queryset.filter(scheduleitem__isnull=False) return queryset.filter(scheduleitem__isnull=True) class TalkUrlInline(admin.TabularInline): model = TalkUrl class TalkAdmin(admin.ModelAdmin): list_display = ('title', 'get_author_name', 'get_author_contact', 'talk_type', 'get_in_schedule', 'status') list_editable = ('status',) list_filter = ('status', 'talk_type', ScheduleListFilter) inlines = [ TalkUrlInline, ] admin.site.register(Talk, TalkAdmin) admin.site.register(TalkType) admin.site.register(TalkUrl) <commit_msg>Fix logic error in schedule filter<commit_after>from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from wafer.talks.models import TalkType, Talk, TalkUrl class ScheduleListFilter(admin.SimpleListFilter): title = _('in schedule') parameter_name = 'schedule' def lookups(self, request, model_admin): return ( ('in', _('Allocated to schedule')), ('out', _('Not allocated')), ) def queryset(self, request, queryset): if self.value() == 'in': return queryset.filter(scheduleitem__isnull=False) elif self.value() == 'out': return queryset.filter(scheduleitem__isnull=True) return queryset class TalkUrlInline(admin.TabularInline): model = TalkUrl class TalkAdmin(admin.ModelAdmin): list_display = ('title', 'get_author_name', 'get_author_contact', 'talk_type', 'get_in_schedule', 'status') list_editable = ('status',) list_filter = ('status', 'talk_type', ScheduleListFilter) inlines = [ TalkUrlInline, ] admin.site.register(Talk, TalkAdmin) admin.site.register(TalkType) admin.site.register(TalkUrl)
40dc1250bf73b54dfcf04c7a82c452a731aa363c
tests/unit/blocks/test_two_column_layout_block.py
tests/unit/blocks/test_two_column_layout_block.py
import mock from django.test import TestCase from django.template import RequestContext from fancypages.models import Container from fancypages.models.blocks import TwoColumnLayoutBlock from fancypages.test import factories class TestTwoColumnLayoutBlock(TestCase): def setUp(self): super(TestTwoColumnLayoutBlock, self).setUp() self.user = factories.UserFactory.build() self.request_context = RequestContext(mock.MagicMock()) self.request_context['user'] = self.user def test_generates_two_empty_containers_when_rendered(self): container = Container.objects.create(name='test-container') block = TwoColumnLayoutBlock.objects.create(container=container) self.assertEquals(block.containers.count(), 0) renderer = block.get_renderer_class()(block, self.request_context) block_html = renderer.render() self.assertEquals(block.containers.count(), 2)
import mock from django.test import TestCase from django.template import RequestContext from fancypages.models import Container from fancypages.models.blocks import TwoColumnLayoutBlock from fancypages.test import factories class TestTwoColumnLayoutBlock(TestCase): def setUp(self): super(TestTwoColumnLayoutBlock, self).setUp() self.user = factories.UserFactory.build() self.request = mock.Mock() self.request.META = {} self.request_context = RequestContext(self.request, {}) self.request_context['user'] = self.user def test_generates_two_empty_containers_when_rendered(self): container = Container.objects.create(name='test-container') block = TwoColumnLayoutBlock.objects.create(container=container) self.assertEquals(block.containers.count(), 0) renderer = block.get_renderer_class()(block, self.request_context) renderer.render() self.assertEquals(block.containers.count(), 2)
Fix mock of request for block rendering
Fix mock of request for block rendering
Python
bsd-3-clause
socradev/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages
import mock from django.test import TestCase from django.template import RequestContext from fancypages.models import Container from fancypages.models.blocks import TwoColumnLayoutBlock from fancypages.test import factories class TestTwoColumnLayoutBlock(TestCase): def setUp(self): super(TestTwoColumnLayoutBlock, self).setUp() self.user = factories.UserFactory.build() self.request_context = RequestContext(mock.MagicMock()) self.request_context['user'] = self.user def test_generates_two_empty_containers_when_rendered(self): container = Container.objects.create(name='test-container') block = TwoColumnLayoutBlock.objects.create(container=container) self.assertEquals(block.containers.count(), 0) renderer = block.get_renderer_class()(block, self.request_context) block_html = renderer.render() self.assertEquals(block.containers.count(), 2) Fix mock of request for block rendering
import mock from django.test import TestCase from django.template import RequestContext from fancypages.models import Container from fancypages.models.blocks import TwoColumnLayoutBlock from fancypages.test import factories class TestTwoColumnLayoutBlock(TestCase): def setUp(self): super(TestTwoColumnLayoutBlock, self).setUp() self.user = factories.UserFactory.build() self.request = mock.Mock() self.request.META = {} self.request_context = RequestContext(self.request, {}) self.request_context['user'] = self.user def test_generates_two_empty_containers_when_rendered(self): container = Container.objects.create(name='test-container') block = TwoColumnLayoutBlock.objects.create(container=container) self.assertEquals(block.containers.count(), 0) renderer = block.get_renderer_class()(block, self.request_context) renderer.render() self.assertEquals(block.containers.count(), 2)
<commit_before>import mock from django.test import TestCase from django.template import RequestContext from fancypages.models import Container from fancypages.models.blocks import TwoColumnLayoutBlock from fancypages.test import factories class TestTwoColumnLayoutBlock(TestCase): def setUp(self): super(TestTwoColumnLayoutBlock, self).setUp() self.user = factories.UserFactory.build() self.request_context = RequestContext(mock.MagicMock()) self.request_context['user'] = self.user def test_generates_two_empty_containers_when_rendered(self): container = Container.objects.create(name='test-container') block = TwoColumnLayoutBlock.objects.create(container=container) self.assertEquals(block.containers.count(), 0) renderer = block.get_renderer_class()(block, self.request_context) block_html = renderer.render() self.assertEquals(block.containers.count(), 2) <commit_msg>Fix mock of request for block rendering<commit_after>
import mock from django.test import TestCase from django.template import RequestContext from fancypages.models import Container from fancypages.models.blocks import TwoColumnLayoutBlock from fancypages.test import factories class TestTwoColumnLayoutBlock(TestCase): def setUp(self): super(TestTwoColumnLayoutBlock, self).setUp() self.user = factories.UserFactory.build() self.request = mock.Mock() self.request.META = {} self.request_context = RequestContext(self.request, {}) self.request_context['user'] = self.user def test_generates_two_empty_containers_when_rendered(self): container = Container.objects.create(name='test-container') block = TwoColumnLayoutBlock.objects.create(container=container) self.assertEquals(block.containers.count(), 0) renderer = block.get_renderer_class()(block, self.request_context) renderer.render() self.assertEquals(block.containers.count(), 2)
import mock from django.test import TestCase from django.template import RequestContext from fancypages.models import Container from fancypages.models.blocks import TwoColumnLayoutBlock from fancypages.test import factories class TestTwoColumnLayoutBlock(TestCase): def setUp(self): super(TestTwoColumnLayoutBlock, self).setUp() self.user = factories.UserFactory.build() self.request_context = RequestContext(mock.MagicMock()) self.request_context['user'] = self.user def test_generates_two_empty_containers_when_rendered(self): container = Container.objects.create(name='test-container') block = TwoColumnLayoutBlock.objects.create(container=container) self.assertEquals(block.containers.count(), 0) renderer = block.get_renderer_class()(block, self.request_context) block_html = renderer.render() self.assertEquals(block.containers.count(), 2) Fix mock of request for block renderingimport mock from django.test import TestCase from django.template import RequestContext from fancypages.models import Container from fancypages.models.blocks import TwoColumnLayoutBlock from fancypages.test import factories class TestTwoColumnLayoutBlock(TestCase): def setUp(self): super(TestTwoColumnLayoutBlock, self).setUp() self.user = factories.UserFactory.build() self.request = mock.Mock() self.request.META = {} self.request_context = RequestContext(self.request, {}) self.request_context['user'] = self.user def test_generates_two_empty_containers_when_rendered(self): container = Container.objects.create(name='test-container') block = TwoColumnLayoutBlock.objects.create(container=container) self.assertEquals(block.containers.count(), 0) renderer = block.get_renderer_class()(block, self.request_context) renderer.render() self.assertEquals(block.containers.count(), 2)
<commit_before>import mock from django.test import TestCase from django.template import RequestContext from fancypages.models import Container from fancypages.models.blocks import TwoColumnLayoutBlock from fancypages.test import factories class TestTwoColumnLayoutBlock(TestCase): def setUp(self): super(TestTwoColumnLayoutBlock, self).setUp() self.user = factories.UserFactory.build() self.request_context = RequestContext(mock.MagicMock()) self.request_context['user'] = self.user def test_generates_two_empty_containers_when_rendered(self): container = Container.objects.create(name='test-container') block = TwoColumnLayoutBlock.objects.create(container=container) self.assertEquals(block.containers.count(), 0) renderer = block.get_renderer_class()(block, self.request_context) block_html = renderer.render() self.assertEquals(block.containers.count(), 2) <commit_msg>Fix mock of request for block rendering<commit_after>import mock from django.test import TestCase from django.template import RequestContext from fancypages.models import Container from fancypages.models.blocks import TwoColumnLayoutBlock from fancypages.test import factories class TestTwoColumnLayoutBlock(TestCase): def setUp(self): super(TestTwoColumnLayoutBlock, self).setUp() self.user = factories.UserFactory.build() self.request = mock.Mock() self.request.META = {} self.request_context = RequestContext(self.request, {}) self.request_context['user'] = self.user def test_generates_two_empty_containers_when_rendered(self): container = Container.objects.create(name='test-container') block = TwoColumnLayoutBlock.objects.create(container=container) self.assertEquals(block.containers.count(), 0) renderer = block.get_renderer_class()(block, self.request_context) renderer.render() self.assertEquals(block.containers.count(), 2)
42f5854b7a9c97b95418d02cb055fc1a751ad112
apps/fund/serializers.py
apps/fund/serializers.py
from apps.projects.serializers import ProjectSmallSerializer from rest_framework import serializers from rest_framework import relations from rest_framework import fields from .models import Donation, Order, OrderItem class DonationSerializer(serializers.ModelSerializer): project = relations.PrimaryKeyRelatedField(source='project') status = fields.Field() class Meta: model = Donation fields = ('id', 'project', 'amount', 'status') class OrderItemSerializer(serializers.ModelSerializer): amount = fields.Field(source='amount') type = fields.Field(source='type') # TODO: At conditional serializers for Donation or Voucher here on source='item' class Meta: model = OrderItem fields = ('amount', 'type')
from rest_framework import serializers from rest_framework import relations from rest_framework import fields from .models import Donation, Order, OrderItem class DonationSerializer(serializers.ModelSerializer): project = relations.PrimaryKeyRelatedField(source='project') status = fields.Field() class Meta: model = Donation fields = ('id', 'project', 'amount', 'status') class OrderItemSerializer(serializers.ModelSerializer): amount = fields.Field(source='amount') type = fields.Field(source='type') # TODO: At conditional serializers for Donation or Voucher here on source='item' class Meta: model = OrderItem fields = ('amount', 'type')
Fix bug in sund serializer
Fix bug in sund serializer
Python
bsd-3-clause
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
from apps.projects.serializers import ProjectSmallSerializer from rest_framework import serializers from rest_framework import relations from rest_framework import fields from .models import Donation, Order, OrderItem class DonationSerializer(serializers.ModelSerializer): project = relations.PrimaryKeyRelatedField(source='project') status = fields.Field() class Meta: model = Donation fields = ('id', 'project', 'amount', 'status') class OrderItemSerializer(serializers.ModelSerializer): amount = fields.Field(source='amount') type = fields.Field(source='type') # TODO: At conditional serializers for Donation or Voucher here on source='item' class Meta: model = OrderItem fields = ('amount', 'type')Fix bug in sund serializer
from rest_framework import serializers from rest_framework import relations from rest_framework import fields from .models import Donation, Order, OrderItem class DonationSerializer(serializers.ModelSerializer): project = relations.PrimaryKeyRelatedField(source='project') status = fields.Field() class Meta: model = Donation fields = ('id', 'project', 'amount', 'status') class OrderItemSerializer(serializers.ModelSerializer): amount = fields.Field(source='amount') type = fields.Field(source='type') # TODO: At conditional serializers for Donation or Voucher here on source='item' class Meta: model = OrderItem fields = ('amount', 'type')
<commit_before>from apps.projects.serializers import ProjectSmallSerializer from rest_framework import serializers from rest_framework import relations from rest_framework import fields from .models import Donation, Order, OrderItem class DonationSerializer(serializers.ModelSerializer): project = relations.PrimaryKeyRelatedField(source='project') status = fields.Field() class Meta: model = Donation fields = ('id', 'project', 'amount', 'status') class OrderItemSerializer(serializers.ModelSerializer): amount = fields.Field(source='amount') type = fields.Field(source='type') # TODO: At conditional serializers for Donation or Voucher here on source='item' class Meta: model = OrderItem fields = ('amount', 'type')<commit_msg>Fix bug in sund serializer<commit_after>
from rest_framework import serializers from rest_framework import relations from rest_framework import fields from .models import Donation, Order, OrderItem class DonationSerializer(serializers.ModelSerializer): project = relations.PrimaryKeyRelatedField(source='project') status = fields.Field() class Meta: model = Donation fields = ('id', 'project', 'amount', 'status') class OrderItemSerializer(serializers.ModelSerializer): amount = fields.Field(source='amount') type = fields.Field(source='type') # TODO: At conditional serializers for Donation or Voucher here on source='item' class Meta: model = OrderItem fields = ('amount', 'type')
from apps.projects.serializers import ProjectSmallSerializer from rest_framework import serializers from rest_framework import relations from rest_framework import fields from .models import Donation, Order, OrderItem class DonationSerializer(serializers.ModelSerializer): project = relations.PrimaryKeyRelatedField(source='project') status = fields.Field() class Meta: model = Donation fields = ('id', 'project', 'amount', 'status') class OrderItemSerializer(serializers.ModelSerializer): amount = fields.Field(source='amount') type = fields.Field(source='type') # TODO: At conditional serializers for Donation or Voucher here on source='item' class Meta: model = OrderItem fields = ('amount', 'type')Fix bug in sund serializerfrom rest_framework import serializers from rest_framework import relations from rest_framework import fields from .models import Donation, Order, OrderItem class DonationSerializer(serializers.ModelSerializer): project = relations.PrimaryKeyRelatedField(source='project') status = fields.Field() class Meta: model = Donation fields = ('id', 'project', 'amount', 'status') class OrderItemSerializer(serializers.ModelSerializer): amount = fields.Field(source='amount') type = fields.Field(source='type') # TODO: At conditional serializers for Donation or Voucher here on source='item' class Meta: model = OrderItem fields = ('amount', 'type')
<commit_before>from apps.projects.serializers import ProjectSmallSerializer from rest_framework import serializers from rest_framework import relations from rest_framework import fields from .models import Donation, Order, OrderItem class DonationSerializer(serializers.ModelSerializer): project = relations.PrimaryKeyRelatedField(source='project') status = fields.Field() class Meta: model = Donation fields = ('id', 'project', 'amount', 'status') class OrderItemSerializer(serializers.ModelSerializer): amount = fields.Field(source='amount') type = fields.Field(source='type') # TODO: At conditional serializers for Donation or Voucher here on source='item' class Meta: model = OrderItem fields = ('amount', 'type')<commit_msg>Fix bug in sund serializer<commit_after>from rest_framework import serializers from rest_framework import relations from rest_framework import fields from .models import Donation, Order, OrderItem class DonationSerializer(serializers.ModelSerializer): project = relations.PrimaryKeyRelatedField(source='project') status = fields.Field() class Meta: model = Donation fields = ('id', 'project', 'amount', 'status') class OrderItemSerializer(serializers.ModelSerializer): amount = fields.Field(source='amount') type = fields.Field(source='type') # TODO: At conditional serializers for Donation or Voucher here on source='item' class Meta: model = OrderItem fields = ('amount', 'type')
c18bcd5af7e0b1506ca28cd33a3c939efee80d00
openfisca_web_api/loader/entities.py
openfisca_web_api/loader/entities.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function, division, absolute_import from openfisca_core.commons import to_unicode def build_entities(tax_benefit_system): entities = { entity.key: build_entity(entity) for entity in tax_benefit_system.entities } return entities def build_entity(entity): entity_formated = { 'plural': entity.plural, 'description': to_unicode(entity.doc) } if hasattr(entity, 'roles'): entity_formated['roles'] = \ { role.key: build_role(role) for role in entity.roles } return entity_formated def build_role(role): role_formated = { 'plural': role.plural, 'description': role.doc } if role.max: role_formated['max'] = role.max if role.subroles: role_formated['max'] = len(role.subroles) role_formated['mandatory'] = True if role_formated.get('max') else False return role_formated
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function, division, absolute_import from openfisca_core.commons import to_unicode def build_entities(tax_benefit_system): entities = { entity.key: build_entity(entity) for entity in tax_benefit_system.entities } return entities def build_entity(entity): formatted_entity = { 'plural': entity.plural, 'description': to_unicode(entity.label), 'documentation': to_unicode(entity.doc) } if hasattr(entity, 'roles'): formatted_entity['roles'] = { role.key: build_role(role) for role in entity.roles } return formatted_entity def build_role(role): formatted_role = { 'plural': role.plural, 'description': role.doc } if role.max: formatted_role['max'] = role.max if role.subroles: formatted_role['max'] = len(role.subroles) formatted_role['mandatory'] = True if formatted_role.get('max') else False return formatted_role
Make variable names more explicit
Make variable names more explicit
Python
agpl-3.0
openfisca/openfisca-core,openfisca/openfisca-core
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function, division, absolute_import from openfisca_core.commons import to_unicode def build_entities(tax_benefit_system): entities = { entity.key: build_entity(entity) for entity in tax_benefit_system.entities } return entities def build_entity(entity): entity_formated = { 'plural': entity.plural, 'description': to_unicode(entity.doc) } if hasattr(entity, 'roles'): entity_formated['roles'] = \ { role.key: build_role(role) for role in entity.roles } return entity_formated def build_role(role): role_formated = { 'plural': role.plural, 'description': role.doc } if role.max: role_formated['max'] = role.max if role.subroles: role_formated['max'] = len(role.subroles) role_formated['mandatory'] = True if role_formated.get('max') else False return role_formated Make variable names more explicit
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function, division, absolute_import from openfisca_core.commons import to_unicode def build_entities(tax_benefit_system): entities = { entity.key: build_entity(entity) for entity in tax_benefit_system.entities } return entities def build_entity(entity): formatted_entity = { 'plural': entity.plural, 'description': to_unicode(entity.label), 'documentation': to_unicode(entity.doc) } if hasattr(entity, 'roles'): formatted_entity['roles'] = { role.key: build_role(role) for role in entity.roles } return formatted_entity def build_role(role): formatted_role = { 'plural': role.plural, 'description': role.doc } if role.max: formatted_role['max'] = role.max if role.subroles: formatted_role['max'] = len(role.subroles) formatted_role['mandatory'] = True if formatted_role.get('max') else False return formatted_role
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function, division, absolute_import from openfisca_core.commons import to_unicode def build_entities(tax_benefit_system): entities = { entity.key: build_entity(entity) for entity in tax_benefit_system.entities } return entities def build_entity(entity): entity_formated = { 'plural': entity.plural, 'description': to_unicode(entity.doc) } if hasattr(entity, 'roles'): entity_formated['roles'] = \ { role.key: build_role(role) for role in entity.roles } return entity_formated def build_role(role): role_formated = { 'plural': role.plural, 'description': role.doc } if role.max: role_formated['max'] = role.max if role.subroles: role_formated['max'] = len(role.subroles) role_formated['mandatory'] = True if role_formated.get('max') else False return role_formated <commit_msg>Make variable names more explicit<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function, division, absolute_import from openfisca_core.commons import to_unicode def build_entities(tax_benefit_system): entities = { entity.key: build_entity(entity) for entity in tax_benefit_system.entities } return entities def build_entity(entity): formatted_entity = { 'plural': entity.plural, 'description': to_unicode(entity.label), 'documentation': to_unicode(entity.doc) } if hasattr(entity, 'roles'): formatted_entity['roles'] = { role.key: build_role(role) for role in entity.roles } return formatted_entity def build_role(role): formatted_role = { 'plural': role.plural, 'description': role.doc } if role.max: formatted_role['max'] = role.max if role.subroles: formatted_role['max'] = len(role.subroles) formatted_role['mandatory'] = True if formatted_role.get('max') else False return formatted_role
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function, division, absolute_import from openfisca_core.commons import to_unicode def build_entities(tax_benefit_system): entities = { entity.key: build_entity(entity) for entity in tax_benefit_system.entities } return entities def build_entity(entity): entity_formated = { 'plural': entity.plural, 'description': to_unicode(entity.doc) } if hasattr(entity, 'roles'): entity_formated['roles'] = \ { role.key: build_role(role) for role in entity.roles } return entity_formated def build_role(role): role_formated = { 'plural': role.plural, 'description': role.doc } if role.max: role_formated['max'] = role.max if role.subroles: role_formated['max'] = len(role.subroles) role_formated['mandatory'] = True if role_formated.get('max') else False return role_formated Make variable names more explicit# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function, division, absolute_import from openfisca_core.commons import to_unicode def build_entities(tax_benefit_system): entities = { entity.key: build_entity(entity) for entity in tax_benefit_system.entities } return entities def build_entity(entity): formatted_entity = { 'plural': entity.plural, 'description': to_unicode(entity.label), 'documentation': to_unicode(entity.doc) } if hasattr(entity, 'roles'): formatted_entity['roles'] = { role.key: build_role(role) for role in entity.roles } return formatted_entity def build_role(role): formatted_role = { 'plural': role.plural, 'description': role.doc } if role.max: formatted_role['max'] = role.max if role.subroles: formatted_role['max'] = len(role.subroles) formatted_role['mandatory'] = True if formatted_role.get('max') else False return formatted_role
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function, division, absolute_import from openfisca_core.commons import to_unicode def build_entities(tax_benefit_system): entities = { entity.key: build_entity(entity) for entity in tax_benefit_system.entities } return entities def build_entity(entity): entity_formated = { 'plural': entity.plural, 'description': to_unicode(entity.doc) } if hasattr(entity, 'roles'): entity_formated['roles'] = \ { role.key: build_role(role) for role in entity.roles } return entity_formated def build_role(role): role_formated = { 'plural': role.plural, 'description': role.doc } if role.max: role_formated['max'] = role.max if role.subroles: role_formated['max'] = len(role.subroles) role_formated['mandatory'] = True if role_formated.get('max') else False return role_formated <commit_msg>Make variable names more explicit<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function, division, absolute_import from openfisca_core.commons import to_unicode def build_entities(tax_benefit_system): entities = { entity.key: build_entity(entity) for entity in tax_benefit_system.entities } return entities def build_entity(entity): formatted_entity = { 'plural': entity.plural, 'description': to_unicode(entity.label), 'documentation': to_unicode(entity.doc) } if hasattr(entity, 'roles'): formatted_entity['roles'] = { role.key: build_role(role) for role in entity.roles } return formatted_entity def build_role(role): formatted_role = { 'plural': role.plural, 'description': role.doc } if role.max: formatted_role['max'] = role.max if role.subroles: formatted_role['max'] = len(role.subroles) formatted_role['mandatory'] = True if formatted_role.get('max') else False return formatted_role
2c3c52a2ecdb4271cea4e8ec31410ef48be3c728
admin/manage.py
admin/manage.py
from mailu import manager, db from mailu.admin import models from passlib import hash @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain_name, password): """ Create an admin user """ domain = models.Domain.query.get(domain_name) if not domain: domain = models.Domain(name=domain_name) db.session.add(domain) user = models.User( localpart=localpart, domain=domain, global_admin=True, password=hash.sha512_crypt.encrypt(password) ) db.session.add(user) db.session.commit() if __name__ == "__main__": manager.run()
from mailu import manager, db from mailu.admin import models from passlib import hash @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain_name, password): """ Create an admin user """ domain = models.Domain.query.get(domain_name) if not domain: domain = models.Domain(name=domain_name) db.session.add(domain) user = models.User( localpart=localpart, domain=domain, global_admin=True, password=hash.sha512_crypt.encrypt(password) ) db.session.add(user) db.session.commit() @manager.command def user(localpart, domain_name, password): """ Create an user """ domain = models.Domain.query.get(domain_name) if not domain: domain = models.Domain(name=domain_name) db.session.add(domain) user = models.User( localpart=localpart, domain=domain, global_admin=False, password=hash.sha512_crypt.encrypt(password) ) db.session.add(user) db.session.commit() if __name__ == "__main__": manager.run()
Add method to create a normal user
Add method to create a normal user
Python
mit
kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io
from mailu import manager, db from mailu.admin import models from passlib import hash @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain_name, password): """ Create an admin user """ domain = models.Domain.query.get(domain_name) if not domain: domain = models.Domain(name=domain_name) db.session.add(domain) user = models.User( localpart=localpart, domain=domain, global_admin=True, password=hash.sha512_crypt.encrypt(password) ) db.session.add(user) db.session.commit() if __name__ == "__main__": manager.run() Add method to create a normal user
from mailu import manager, db from mailu.admin import models from passlib import hash @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain_name, password): """ Create an admin user """ domain = models.Domain.query.get(domain_name) if not domain: domain = models.Domain(name=domain_name) db.session.add(domain) user = models.User( localpart=localpart, domain=domain, global_admin=True, password=hash.sha512_crypt.encrypt(password) ) db.session.add(user) db.session.commit() @manager.command def user(localpart, domain_name, password): """ Create an user """ domain = models.Domain.query.get(domain_name) if not domain: domain = models.Domain(name=domain_name) db.session.add(domain) user = models.User( localpart=localpart, domain=domain, global_admin=False, password=hash.sha512_crypt.encrypt(password) ) db.session.add(user) db.session.commit() if __name__ == "__main__": manager.run()
<commit_before>from mailu import manager, db from mailu.admin import models from passlib import hash @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain_name, password): """ Create an admin user """ domain = models.Domain.query.get(domain_name) if not domain: domain = models.Domain(name=domain_name) db.session.add(domain) user = models.User( localpart=localpart, domain=domain, global_admin=True, password=hash.sha512_crypt.encrypt(password) ) db.session.add(user) db.session.commit() if __name__ == "__main__": manager.run() <commit_msg>Add method to create a normal user<commit_after>
from mailu import manager, db from mailu.admin import models from passlib import hash @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain_name, password): """ Create an admin user """ domain = models.Domain.query.get(domain_name) if not domain: domain = models.Domain(name=domain_name) db.session.add(domain) user = models.User( localpart=localpart, domain=domain, global_admin=True, password=hash.sha512_crypt.encrypt(password) ) db.session.add(user) db.session.commit() @manager.command def user(localpart, domain_name, password): """ Create an user """ domain = models.Domain.query.get(domain_name) if not domain: domain = models.Domain(name=domain_name) db.session.add(domain) user = models.User( localpart=localpart, domain=domain, global_admin=False, password=hash.sha512_crypt.encrypt(password) ) db.session.add(user) db.session.commit() if __name__ == "__main__": manager.run()
from mailu import manager, db from mailu.admin import models from passlib import hash @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain_name, password): """ Create an admin user """ domain = models.Domain.query.get(domain_name) if not domain: domain = models.Domain(name=domain_name) db.session.add(domain) user = models.User( localpart=localpart, domain=domain, global_admin=True, password=hash.sha512_crypt.encrypt(password) ) db.session.add(user) db.session.commit() if __name__ == "__main__": manager.run() Add method to create a normal userfrom mailu import manager, db from mailu.admin import models from passlib import hash @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain_name, password): """ Create an admin user """ domain = models.Domain.query.get(domain_name) if not domain: domain = models.Domain(name=domain_name) db.session.add(domain) user = models.User( localpart=localpart, domain=domain, global_admin=True, password=hash.sha512_crypt.encrypt(password) ) db.session.add(user) db.session.commit() @manager.command def user(localpart, domain_name, password): """ Create an user """ domain = models.Domain.query.get(domain_name) if not domain: domain = models.Domain(name=domain_name) db.session.add(domain) user = models.User( localpart=localpart, domain=domain, global_admin=False, password=hash.sha512_crypt.encrypt(password) ) db.session.add(user) db.session.commit() if __name__ == "__main__": manager.run()
<commit_before>from mailu import manager, db from mailu.admin import models from passlib import hash @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain_name, password): """ Create an admin user """ domain = models.Domain.query.get(domain_name) if not domain: domain = models.Domain(name=domain_name) db.session.add(domain) user = models.User( localpart=localpart, domain=domain, global_admin=True, password=hash.sha512_crypt.encrypt(password) ) db.session.add(user) db.session.commit() if __name__ == "__main__": manager.run() <commit_msg>Add method to create a normal user<commit_after>from mailu import manager, db from mailu.admin import models from passlib import hash @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain_name, password): """ Create an admin user """ domain = models.Domain.query.get(domain_name) if not domain: domain = models.Domain(name=domain_name) db.session.add(domain) user = models.User( localpart=localpart, domain=domain, global_admin=True, password=hash.sha512_crypt.encrypt(password) ) db.session.add(user) db.session.commit() @manager.command def user(localpart, domain_name, password): """ Create an user """ domain = models.Domain.query.get(domain_name) if not domain: domain = models.Domain(name=domain_name) db.session.add(domain) user = models.User( localpart=localpart, domain=domain, global_admin=False, password=hash.sha512_crypt.encrypt(password) ) db.session.add(user) db.session.commit() if __name__ == "__main__": manager.run()
375c55a085dce451146a10b66b3c2d54a9919ed4
pipelines/toast_example_dist.py
pipelines/toast_example_dist.py
import toast # Split COMM_WORLD into groups of 4 processes each cm = toast.Comm(world=MPI.COMM_WORLD, groupsize=4) # Create the distributed data object dd = toast.Data(comm=cm) # Each process group appends some observations. # For this example, each observation is going to have the same # number of samples, and the same list of detectors. We just # use the base TOD class, which contains the data directly as # numpy arrays. obs_samples = 100 obs_dets = ['detA', 'detB', 'detC'] for i in range(10): tod = TOD(mpicomm=cm.comm_group, detectors=obs_dets, samples=obs_samples) ob = {} ob['id'] = '{}'.format(i) ob['tod'] = tod ob['intervals'] = None ob['baselines'] = None ob['noise'] = None dd.obs.append(ob) # Now at the end we have 4 process groups, each of which is assigned # 10 observations. Each of these observations has 3 detectors and 100 # samples. So the Data object contains a total of 40 observations and # 12000 samples.
import mpi4py.MPI as MPI import toast # Split COMM_WORLD into groups of 4 processes each cm = toast.Comm(world=MPI.COMM_WORLD, groupsize=4) # Create the distributed data object dd = toast.Data(comm=cm) # Each process group appends some observations. # For this example, each observation is going to have the same # number of samples, and the same list of detectors. We just # use the base TOD class, which contains the data directly as # numpy arrays. obs_samples = 100 obs_dets = ['detA', 'detB', 'detC'] for i in range(10): tod = TOD(mpicomm=cm.comm_group, detectors=obs_dets, samples=obs_samples) ob = {} ob['id'] = '{}'.format(i) ob['tod'] = tod ob['intervals'] = None ob['baselines'] = None ob['noise'] = None dd.obs.append(ob) # Now at the end we have 4 process groups, each of which is assigned # 10 observations. Each of these observations has 3 detectors and 100 # samples. So the Data object contains a total of 40 observations and # 12000 samples.
Fix typo, even though this example is not used for anything.
Fix typo, even though this example is not used for anything.
Python
bsd-2-clause
tskisner/pytoast,tskisner/pytoast
import toast # Split COMM_WORLD into groups of 4 processes each cm = toast.Comm(world=MPI.COMM_WORLD, groupsize=4) # Create the distributed data object dd = toast.Data(comm=cm) # Each process group appends some observations. # For this example, each observation is going to have the same # number of samples, and the same list of detectors. We just # use the base TOD class, which contains the data directly as # numpy arrays. obs_samples = 100 obs_dets = ['detA', 'detB', 'detC'] for i in range(10): tod = TOD(mpicomm=cm.comm_group, detectors=obs_dets, samples=obs_samples) ob = {} ob['id'] = '{}'.format(i) ob['tod'] = tod ob['intervals'] = None ob['baselines'] = None ob['noise'] = None dd.obs.append(ob) # Now at the end we have 4 process groups, each of which is assigned # 10 observations. Each of these observations has 3 detectors and 100 # samples. So the Data object contains a total of 40 observations and # 12000 samples. Fix typo, even though this example is not used for anything.
import mpi4py.MPI as MPI import toast # Split COMM_WORLD into groups of 4 processes each cm = toast.Comm(world=MPI.COMM_WORLD, groupsize=4) # Create the distributed data object dd = toast.Data(comm=cm) # Each process group appends some observations. # For this example, each observation is going to have the same # number of samples, and the same list of detectors. We just # use the base TOD class, which contains the data directly as # numpy arrays. obs_samples = 100 obs_dets = ['detA', 'detB', 'detC'] for i in range(10): tod = TOD(mpicomm=cm.comm_group, detectors=obs_dets, samples=obs_samples) ob = {} ob['id'] = '{}'.format(i) ob['tod'] = tod ob['intervals'] = None ob['baselines'] = None ob['noise'] = None dd.obs.append(ob) # Now at the end we have 4 process groups, each of which is assigned # 10 observations. Each of these observations has 3 detectors and 100 # samples. So the Data object contains a total of 40 observations and # 12000 samples.
<commit_before> import toast # Split COMM_WORLD into groups of 4 processes each cm = toast.Comm(world=MPI.COMM_WORLD, groupsize=4) # Create the distributed data object dd = toast.Data(comm=cm) # Each process group appends some observations. # For this example, each observation is going to have the same # number of samples, and the same list of detectors. We just # use the base TOD class, which contains the data directly as # numpy arrays. obs_samples = 100 obs_dets = ['detA', 'detB', 'detC'] for i in range(10): tod = TOD(mpicomm=cm.comm_group, detectors=obs_dets, samples=obs_samples) ob = {} ob['id'] = '{}'.format(i) ob['tod'] = tod ob['intervals'] = None ob['baselines'] = None ob['noise'] = None dd.obs.append(ob) # Now at the end we have 4 process groups, each of which is assigned # 10 observations. Each of these observations has 3 detectors and 100 # samples. So the Data object contains a total of 40 observations and # 12000 samples. <commit_msg>Fix typo, even though this example is not used for anything.<commit_after>
import mpi4py.MPI as MPI import toast # Split COMM_WORLD into groups of 4 processes each cm = toast.Comm(world=MPI.COMM_WORLD, groupsize=4) # Create the distributed data object dd = toast.Data(comm=cm) # Each process group appends some observations. # For this example, each observation is going to have the same # number of samples, and the same list of detectors. We just # use the base TOD class, which contains the data directly as # numpy arrays. obs_samples = 100 obs_dets = ['detA', 'detB', 'detC'] for i in range(10): tod = TOD(mpicomm=cm.comm_group, detectors=obs_dets, samples=obs_samples) ob = {} ob['id'] = '{}'.format(i) ob['tod'] = tod ob['intervals'] = None ob['baselines'] = None ob['noise'] = None dd.obs.append(ob) # Now at the end we have 4 process groups, each of which is assigned # 10 observations. Each of these observations has 3 detectors and 100 # samples. So the Data object contains a total of 40 observations and # 12000 samples.
import toast # Split COMM_WORLD into groups of 4 processes each cm = toast.Comm(world=MPI.COMM_WORLD, groupsize=4) # Create the distributed data object dd = toast.Data(comm=cm) # Each process group appends some observations. # For this example, each observation is going to have the same # number of samples, and the same list of detectors. We just # use the base TOD class, which contains the data directly as # numpy arrays. obs_samples = 100 obs_dets = ['detA', 'detB', 'detC'] for i in range(10): tod = TOD(mpicomm=cm.comm_group, detectors=obs_dets, samples=obs_samples) ob = {} ob['id'] = '{}'.format(i) ob['tod'] = tod ob['intervals'] = None ob['baselines'] = None ob['noise'] = None dd.obs.append(ob) # Now at the end we have 4 process groups, each of which is assigned # 10 observations. Each of these observations has 3 detectors and 100 # samples. So the Data object contains a total of 40 observations and # 12000 samples. Fix typo, even though this example is not used for anything. import mpi4py.MPI as MPI import toast # Split COMM_WORLD into groups of 4 processes each cm = toast.Comm(world=MPI.COMM_WORLD, groupsize=4) # Create the distributed data object dd = toast.Data(comm=cm) # Each process group appends some observations. # For this example, each observation is going to have the same # number of samples, and the same list of detectors. We just # use the base TOD class, which contains the data directly as # numpy arrays. obs_samples = 100 obs_dets = ['detA', 'detB', 'detC'] for i in range(10): tod = TOD(mpicomm=cm.comm_group, detectors=obs_dets, samples=obs_samples) ob = {} ob['id'] = '{}'.format(i) ob['tod'] = tod ob['intervals'] = None ob['baselines'] = None ob['noise'] = None dd.obs.append(ob) # Now at the end we have 4 process groups, each of which is assigned # 10 observations. Each of these observations has 3 detectors and 100 # samples. So the Data object contains a total of 40 observations and # 12000 samples.
<commit_before> import toast # Split COMM_WORLD into groups of 4 processes each cm = toast.Comm(world=MPI.COMM_WORLD, groupsize=4) # Create the distributed data object dd = toast.Data(comm=cm) # Each process group appends some observations. # For this example, each observation is going to have the same # number of samples, and the same list of detectors. We just # use the base TOD class, which contains the data directly as # numpy arrays. obs_samples = 100 obs_dets = ['detA', 'detB', 'detC'] for i in range(10): tod = TOD(mpicomm=cm.comm_group, detectors=obs_dets, samples=obs_samples) ob = {} ob['id'] = '{}'.format(i) ob['tod'] = tod ob['intervals'] = None ob['baselines'] = None ob['noise'] = None dd.obs.append(ob) # Now at the end we have 4 process groups, each of which is assigned # 10 observations. Each of these observations has 3 detectors and 100 # samples. So the Data object contains a total of 40 observations and # 12000 samples. <commit_msg>Fix typo, even though this example is not used for anything.<commit_after> import mpi4py.MPI as MPI import toast # Split COMM_WORLD into groups of 4 processes each cm = toast.Comm(world=MPI.COMM_WORLD, groupsize=4) # Create the distributed data object dd = toast.Data(comm=cm) # Each process group appends some observations. # For this example, each observation is going to have the same # number of samples, and the same list of detectors. We just # use the base TOD class, which contains the data directly as # numpy arrays. obs_samples = 100 obs_dets = ['detA', 'detB', 'detC'] for i in range(10): tod = TOD(mpicomm=cm.comm_group, detectors=obs_dets, samples=obs_samples) ob = {} ob['id'] = '{}'.format(i) ob['tod'] = tod ob['intervals'] = None ob['baselines'] = None ob['noise'] = None dd.obs.append(ob) # Now at the end we have 4 process groups, each of which is assigned # 10 observations. Each of these observations has 3 detectors and 100 # samples. So the Data object contains a total of 40 observations and # 12000 samples.
f5d07cbefa185d88cdc1bddc4338d6e0ef1e2648
porick/lib/auth.py
porick/lib/auth.py
import bcrypt import hashlib from pylons import response, request, url, config from pylons import tmpl_context as c from pylons.controllers.util import redirect import porick.lib.helpers as h from porick.model import db, User def authenticate(username, password): user = db.query(User).filter(User.username == username).first() if not user: return False if bcrypt.hashpw(password, config['PASSWORD_SALT']) == user.password: set_auth_cookie(user) return True return False def authorize(): if not c.logged_in: redirect(url(controller='account', action='login', redirect_url=url.current(), warn='true')) def set_auth_cookie(user): auth = hashlib.md5('%s:%s:%s' % (config['COOKIE_SECRET'], user.username, user.level)).hexdigest() response.set_cookie('auth', auth, max_age=2592000) response.set_cookie('username', user.username, max_age=2592000) response.set_cookie('level', str(user.level), max_age=2592000) def clear_cookies(): response.delete_cookie('auth') response.delete_cookie('username')
import bcrypt import hashlib from pylons import response, request, url, config from pylons import tmpl_context as c from pylons.controllers.util import redirect import porick.lib.helpers as h from porick.model import db, User def authenticate(username, password): user = db.query(User).filter(User.username == username).first() if not user: return False elif bcrypt.hashpw(password, config['PASSWORD_SALT']) == user.password: set_auth_cookie(user) return True else: clear_cookies() return False def authorize(): if not c.logged_in: redirect(url(controller='account', action='login', redirect_url=url.current(), warn='true')) def set_auth_cookie(user): auth = hashlib.md5('%s:%s:%s' % (config['COOKIE_SECRET'], user.username, user.level)).hexdigest() response.set_cookie('auth', auth, max_age=2592000) response.set_cookie('username', user.username, max_age=2592000) response.set_cookie('level', str(user.level), max_age=2592000) def clear_cookies(): response.delete_cookie('auth') response.delete_cookie('username')
Clear cookies if someone's got dodgy cookie info
Clear cookies if someone's got dodgy cookie info
Python
apache-2.0
kopf/porick,kopf/porick,kopf/porick
import bcrypt import hashlib from pylons import response, request, url, config from pylons import tmpl_context as c from pylons.controllers.util import redirect import porick.lib.helpers as h from porick.model import db, User def authenticate(username, password): user = db.query(User).filter(User.username == username).first() if not user: return False if bcrypt.hashpw(password, config['PASSWORD_SALT']) == user.password: set_auth_cookie(user) return True return False def authorize(): if not c.logged_in: redirect(url(controller='account', action='login', redirect_url=url.current(), warn='true')) def set_auth_cookie(user): auth = hashlib.md5('%s:%s:%s' % (config['COOKIE_SECRET'], user.username, user.level)).hexdigest() response.set_cookie('auth', auth, max_age=2592000) response.set_cookie('username', user.username, max_age=2592000) response.set_cookie('level', str(user.level), max_age=2592000) def clear_cookies(): response.delete_cookie('auth') response.delete_cookie('username') Clear cookies if someone's got dodgy cookie info
import bcrypt import hashlib from pylons import response, request, url, config from pylons import tmpl_context as c from pylons.controllers.util import redirect import porick.lib.helpers as h from porick.model import db, User def authenticate(username, password): user = db.query(User).filter(User.username == username).first() if not user: return False elif bcrypt.hashpw(password, config['PASSWORD_SALT']) == user.password: set_auth_cookie(user) return True else: clear_cookies() return False def authorize(): if not c.logged_in: redirect(url(controller='account', action='login', redirect_url=url.current(), warn='true')) def set_auth_cookie(user): auth = hashlib.md5('%s:%s:%s' % (config['COOKIE_SECRET'], user.username, user.level)).hexdigest() response.set_cookie('auth', auth, max_age=2592000) response.set_cookie('username', user.username, max_age=2592000) response.set_cookie('level', str(user.level), max_age=2592000) def clear_cookies(): response.delete_cookie('auth') response.delete_cookie('username')
<commit_before>import bcrypt import hashlib from pylons import response, request, url, config from pylons import tmpl_context as c from pylons.controllers.util import redirect import porick.lib.helpers as h from porick.model import db, User def authenticate(username, password): user = db.query(User).filter(User.username == username).first() if not user: return False if bcrypt.hashpw(password, config['PASSWORD_SALT']) == user.password: set_auth_cookie(user) return True return False def authorize(): if not c.logged_in: redirect(url(controller='account', action='login', redirect_url=url.current(), warn='true')) def set_auth_cookie(user): auth = hashlib.md5('%s:%s:%s' % (config['COOKIE_SECRET'], user.username, user.level)).hexdigest() response.set_cookie('auth', auth, max_age=2592000) response.set_cookie('username', user.username, max_age=2592000) response.set_cookie('level', str(user.level), max_age=2592000) def clear_cookies(): response.delete_cookie('auth') response.delete_cookie('username') <commit_msg>Clear cookies if someone's got dodgy cookie info<commit_after>
import bcrypt import hashlib from pylons import response, request, url, config from pylons import tmpl_context as c from pylons.controllers.util import redirect import porick.lib.helpers as h from porick.model import db, User def authenticate(username, password): user = db.query(User).filter(User.username == username).first() if not user: return False elif bcrypt.hashpw(password, config['PASSWORD_SALT']) == user.password: set_auth_cookie(user) return True else: clear_cookies() return False def authorize(): if not c.logged_in: redirect(url(controller='account', action='login', redirect_url=url.current(), warn='true')) def set_auth_cookie(user): auth = hashlib.md5('%s:%s:%s' % (config['COOKIE_SECRET'], user.username, user.level)).hexdigest() response.set_cookie('auth', auth, max_age=2592000) response.set_cookie('username', user.username, max_age=2592000) response.set_cookie('level', str(user.level), max_age=2592000) def clear_cookies(): response.delete_cookie('auth') response.delete_cookie('username')
import bcrypt import hashlib from pylons import response, request, url, config from pylons import tmpl_context as c from pylons.controllers.util import redirect import porick.lib.helpers as h from porick.model import db, User def authenticate(username, password): user = db.query(User).filter(User.username == username).first() if not user: return False if bcrypt.hashpw(password, config['PASSWORD_SALT']) == user.password: set_auth_cookie(user) return True return False def authorize(): if not c.logged_in: redirect(url(controller='account', action='login', redirect_url=url.current(), warn='true')) def set_auth_cookie(user): auth = hashlib.md5('%s:%s:%s' % (config['COOKIE_SECRET'], user.username, user.level)).hexdigest() response.set_cookie('auth', auth, max_age=2592000) response.set_cookie('username', user.username, max_age=2592000) response.set_cookie('level', str(user.level), max_age=2592000) def clear_cookies(): response.delete_cookie('auth') response.delete_cookie('username') Clear cookies if someone's got dodgy cookie infoimport bcrypt import hashlib from pylons import response, request, url, config from pylons import tmpl_context as c from pylons.controllers.util import redirect import porick.lib.helpers as h from porick.model import db, User def authenticate(username, password): user = db.query(User).filter(User.username == username).first() if not user: return False elif bcrypt.hashpw(password, config['PASSWORD_SALT']) == user.password: set_auth_cookie(user) return True else: clear_cookies() return False def authorize(): if not c.logged_in: redirect(url(controller='account', action='login', redirect_url=url.current(), warn='true')) def set_auth_cookie(user): auth = hashlib.md5('%s:%s:%s' % (config['COOKIE_SECRET'], user.username, user.level)).hexdigest() response.set_cookie('auth', auth, max_age=2592000) response.set_cookie('username', user.username, max_age=2592000) response.set_cookie('level', str(user.level), max_age=2592000) def clear_cookies(): response.delete_cookie('auth') response.delete_cookie('username')
<commit_before>import bcrypt import hashlib from pylons import response, request, url, config from pylons import tmpl_context as c from pylons.controllers.util import redirect import porick.lib.helpers as h from porick.model import db, User def authenticate(username, password): user = db.query(User).filter(User.username == username).first() if not user: return False if bcrypt.hashpw(password, config['PASSWORD_SALT']) == user.password: set_auth_cookie(user) return True return False def authorize(): if not c.logged_in: redirect(url(controller='account', action='login', redirect_url=url.current(), warn='true')) def set_auth_cookie(user): auth = hashlib.md5('%s:%s:%s' % (config['COOKIE_SECRET'], user.username, user.level)).hexdigest() response.set_cookie('auth', auth, max_age=2592000) response.set_cookie('username', user.username, max_age=2592000) response.set_cookie('level', str(user.level), max_age=2592000) def clear_cookies(): response.delete_cookie('auth') response.delete_cookie('username') <commit_msg>Clear cookies if someone's got dodgy cookie info<commit_after>import bcrypt import hashlib from pylons import response, request, url, config from pylons import tmpl_context as c from pylons.controllers.util import redirect import porick.lib.helpers as h from porick.model import db, User def authenticate(username, password): user = db.query(User).filter(User.username == username).first() if not user: return False elif bcrypt.hashpw(password, config['PASSWORD_SALT']) == user.password: set_auth_cookie(user) return True else: clear_cookies() return False def authorize(): if not c.logged_in: redirect(url(controller='account', action='login', redirect_url=url.current(), warn='true')) def set_auth_cookie(user): auth = hashlib.md5('%s:%s:%s' % (config['COOKIE_SECRET'], user.username, user.level)).hexdigest() response.set_cookie('auth', auth, max_age=2592000) response.set_cookie('username', user.username, max_age=2592000) response.set_cookie('level', str(user.level), max_age=2592000) def clear_cookies(): response.delete_cookie('auth') response.delete_cookie('username')
8ab4b4be97ca026946b30cba7fce64bb30edd28d
fskintra.py
fskintra.py
#! /usr/bin/env python # # # import skoleintra.config import skoleintra.pgContactLists import skoleintra.pgDialogue import skoleintra.pgDocuments import skoleintra.pgFrontpage import skoleintra.pgWeekplans import skoleintra.schildren SKOLEBESTYELSE_NAME = 'Skolebestyrelsen' cnames = skoleintra.schildren.skoleGetChildren() if cnames.count(SKOLEBESTYELSE_NAME): print 'Ignorerer ['+SKOLEBESTYELSE_NAME+']' cnames.remove(SKOLEBESTYELSE_NAME) for cname in cnames: skoleintra.schildren.skoleSelectChild(cname) skoleintra.pgContactLists.skoleContactLists() skoleintra.pgFrontpage.skoleFrontpage() skoleintra.pgDialogue.skoleDialogue() skoleintra.pgDocuments.skoleDocuments() skoleintra.pgWeekplans.skoleWeekplans()
#! /usr/bin/env python # # # import skoleintra.config import skoleintra.pgContactLists import skoleintra.pgDialogue import skoleintra.pgDocuments import skoleintra.pgFrontpage import skoleintra.pgWeekplans import skoleintra.schildren SKOLEBESTYELSE_NAME = 'Skolebestyrelsen' cnames = skoleintra.schildren.skoleGetChildren() if cnames.count(SKOLEBESTYELSE_NAME): config.log(u'Ignorerer ['+SKOLEBESTYELSE_NAME+']') cnames.remove(SKOLEBESTYELSE_NAME) for cname in cnames: skoleintra.schildren.skoleSelectChild(cname) skoleintra.pgContactLists.skoleContactLists() skoleintra.pgFrontpage.skoleFrontpage() skoleintra.pgDialogue.skoleDialogue() skoleintra.pgDocuments.skoleDocuments() skoleintra.pgWeekplans.skoleWeekplans()
Use config.log for print added in last commit
Use config.log for print added in last commit
Python
bsd-2-clause
bennyslbs/fskintra
#! /usr/bin/env python # # # import skoleintra.config import skoleintra.pgContactLists import skoleintra.pgDialogue import skoleintra.pgDocuments import skoleintra.pgFrontpage import skoleintra.pgWeekplans import skoleintra.schildren SKOLEBESTYELSE_NAME = 'Skolebestyrelsen' cnames = skoleintra.schildren.skoleGetChildren() if cnames.count(SKOLEBESTYELSE_NAME): print 'Ignorerer ['+SKOLEBESTYELSE_NAME+']' cnames.remove(SKOLEBESTYELSE_NAME) for cname in cnames: skoleintra.schildren.skoleSelectChild(cname) skoleintra.pgContactLists.skoleContactLists() skoleintra.pgFrontpage.skoleFrontpage() skoleintra.pgDialogue.skoleDialogue() skoleintra.pgDocuments.skoleDocuments() skoleintra.pgWeekplans.skoleWeekplans() Use config.log for print added in last commit
#! /usr/bin/env python # # # import skoleintra.config import skoleintra.pgContactLists import skoleintra.pgDialogue import skoleintra.pgDocuments import skoleintra.pgFrontpage import skoleintra.pgWeekplans import skoleintra.schildren SKOLEBESTYELSE_NAME = 'Skolebestyrelsen' cnames = skoleintra.schildren.skoleGetChildren() if cnames.count(SKOLEBESTYELSE_NAME): config.log(u'Ignorerer ['+SKOLEBESTYELSE_NAME+']') cnames.remove(SKOLEBESTYELSE_NAME) for cname in cnames: skoleintra.schildren.skoleSelectChild(cname) skoleintra.pgContactLists.skoleContactLists() skoleintra.pgFrontpage.skoleFrontpage() skoleintra.pgDialogue.skoleDialogue() skoleintra.pgDocuments.skoleDocuments() skoleintra.pgWeekplans.skoleWeekplans()
<commit_before>#! /usr/bin/env python # # # import skoleintra.config import skoleintra.pgContactLists import skoleintra.pgDialogue import skoleintra.pgDocuments import skoleintra.pgFrontpage import skoleintra.pgWeekplans import skoleintra.schildren SKOLEBESTYELSE_NAME = 'Skolebestyrelsen' cnames = skoleintra.schildren.skoleGetChildren() if cnames.count(SKOLEBESTYELSE_NAME): print 'Ignorerer ['+SKOLEBESTYELSE_NAME+']' cnames.remove(SKOLEBESTYELSE_NAME) for cname in cnames: skoleintra.schildren.skoleSelectChild(cname) skoleintra.pgContactLists.skoleContactLists() skoleintra.pgFrontpage.skoleFrontpage() skoleintra.pgDialogue.skoleDialogue() skoleintra.pgDocuments.skoleDocuments() skoleintra.pgWeekplans.skoleWeekplans() <commit_msg>Use config.log for print added in last commit<commit_after>
#! /usr/bin/env python # # # import skoleintra.config import skoleintra.pgContactLists import skoleintra.pgDialogue import skoleintra.pgDocuments import skoleintra.pgFrontpage import skoleintra.pgWeekplans import skoleintra.schildren SKOLEBESTYELSE_NAME = 'Skolebestyrelsen' cnames = skoleintra.schildren.skoleGetChildren() if cnames.count(SKOLEBESTYELSE_NAME): config.log(u'Ignorerer ['+SKOLEBESTYELSE_NAME+']') cnames.remove(SKOLEBESTYELSE_NAME) for cname in cnames: skoleintra.schildren.skoleSelectChild(cname) skoleintra.pgContactLists.skoleContactLists() skoleintra.pgFrontpage.skoleFrontpage() skoleintra.pgDialogue.skoleDialogue() skoleintra.pgDocuments.skoleDocuments() skoleintra.pgWeekplans.skoleWeekplans()
#! /usr/bin/env python # # # import skoleintra.config import skoleintra.pgContactLists import skoleintra.pgDialogue import skoleintra.pgDocuments import skoleintra.pgFrontpage import skoleintra.pgWeekplans import skoleintra.schildren SKOLEBESTYELSE_NAME = 'Skolebestyrelsen' cnames = skoleintra.schildren.skoleGetChildren() if cnames.count(SKOLEBESTYELSE_NAME): print 'Ignorerer ['+SKOLEBESTYELSE_NAME+']' cnames.remove(SKOLEBESTYELSE_NAME) for cname in cnames: skoleintra.schildren.skoleSelectChild(cname) skoleintra.pgContactLists.skoleContactLists() skoleintra.pgFrontpage.skoleFrontpage() skoleintra.pgDialogue.skoleDialogue() skoleintra.pgDocuments.skoleDocuments() skoleintra.pgWeekplans.skoleWeekplans() Use config.log for print added in last commit#! /usr/bin/env python # # # import skoleintra.config import skoleintra.pgContactLists import skoleintra.pgDialogue import skoleintra.pgDocuments import skoleintra.pgFrontpage import skoleintra.pgWeekplans import skoleintra.schildren SKOLEBESTYELSE_NAME = 'Skolebestyrelsen' cnames = skoleintra.schildren.skoleGetChildren() if cnames.count(SKOLEBESTYELSE_NAME): config.log(u'Ignorerer ['+SKOLEBESTYELSE_NAME+']') cnames.remove(SKOLEBESTYELSE_NAME) for cname in cnames: skoleintra.schildren.skoleSelectChild(cname) skoleintra.pgContactLists.skoleContactLists() skoleintra.pgFrontpage.skoleFrontpage() skoleintra.pgDialogue.skoleDialogue() skoleintra.pgDocuments.skoleDocuments() skoleintra.pgWeekplans.skoleWeekplans()
<commit_before>#! /usr/bin/env python # # # import skoleintra.config import skoleintra.pgContactLists import skoleintra.pgDialogue import skoleintra.pgDocuments import skoleintra.pgFrontpage import skoleintra.pgWeekplans import skoleintra.schildren SKOLEBESTYELSE_NAME = 'Skolebestyrelsen' cnames = skoleintra.schildren.skoleGetChildren() if cnames.count(SKOLEBESTYELSE_NAME): print 'Ignorerer ['+SKOLEBESTYELSE_NAME+']' cnames.remove(SKOLEBESTYELSE_NAME) for cname in cnames: skoleintra.schildren.skoleSelectChild(cname) skoleintra.pgContactLists.skoleContactLists() skoleintra.pgFrontpage.skoleFrontpage() skoleintra.pgDialogue.skoleDialogue() skoleintra.pgDocuments.skoleDocuments() skoleintra.pgWeekplans.skoleWeekplans() <commit_msg>Use config.log for print added in last commit<commit_after>#! /usr/bin/env python # # # import skoleintra.config import skoleintra.pgContactLists import skoleintra.pgDialogue import skoleintra.pgDocuments import skoleintra.pgFrontpage import skoleintra.pgWeekplans import skoleintra.schildren SKOLEBESTYELSE_NAME = 'Skolebestyrelsen' cnames = skoleintra.schildren.skoleGetChildren() if cnames.count(SKOLEBESTYELSE_NAME): config.log(u'Ignorerer ['+SKOLEBESTYELSE_NAME+']') cnames.remove(SKOLEBESTYELSE_NAME) for cname in cnames: skoleintra.schildren.skoleSelectChild(cname) skoleintra.pgContactLists.skoleContactLists() skoleintra.pgFrontpage.skoleFrontpage() skoleintra.pgDialogue.skoleDialogue() skoleintra.pgDocuments.skoleDocuments() skoleintra.pgWeekplans.skoleWeekplans()
e21ca71d5bf19ec0feaab9dbf8caf25173152aec
projects/models.py
projects/models.py
# -*- encoding:utf-8 -*- from django.db import models class Project(models.Model): STATUS = ( ('unrevised', u'Неразгледан'), ('returned', u'Върнат за корекция'), ('pending', u'Предстои да бъде разгледан на СИС'), ('approved', u'Разгледан и одобрен на СИС'), ('rejected', u'Разгледан и неодобрен на СИС')) user = models.ForeignKey('members.User') name = models.CharField(max_length=100) flp = models.ForeignKey('members.User', related_name='flp') team = models.ManyToManyField('members.User', related_name='team') description = models.TextField() targets = models.TextField() tasks = models.TextField() target_group = models.TextField() schedule = models.TextField() resources = models.TextField() finance_description = models.TextField() partners = models.TextField(blank=True, null=True) files = models.ManyToManyField('attachments.Attachment') status = models.CharField(max_length=50, choices=STATUS, default='unrevised') date = models.DateField(blank=True, null=True) def __unicode__(self): return self.name
# -*- encoding:utf-8 -*- from django.db import models class Project(models.Model): STATUS = ( ('unrevised', u'Неразгледан'), ('returned', u'Върнат за корекция'), ('pending', u'Предстои да бъде разгледан на СИС'), ('approved', u'Разгледан и одобрен на СИС'), ('rejected', u'Разгледан и неодобрен на СИС')) user = models.ForeignKey('members.User') name = models.CharField(max_length=100) flp = models.ForeignKey('members.User', related_name='flp') team = models.ManyToManyField('members.User', related_name='team') description = models.TextField() targets = models.TextField() tasks = models.TextField() target_group = models.TextField() schedule = models.TextField() resources = models.TextField() finance_description = models.TextField() partners = models.TextField(blank=True, null=True) files = models.ManyToManyField('attachments.Attachment') status = models.CharField(max_length=50, choices=STATUS, default='unrevised') discussed_at = models.DateField(blank=True, null=True) def __unicode__(self): return self.name
Rename the date field related to the project status
Rename the date field related to the project status
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
# -*- encoding:utf-8 -*- from django.db import models class Project(models.Model): STATUS = ( ('unrevised', u'Неразгледан'), ('returned', u'Върнат за корекция'), ('pending', u'Предстои да бъде разгледан на СИС'), ('approved', u'Разгледан и одобрен на СИС'), ('rejected', u'Разгледан и неодобрен на СИС')) user = models.ForeignKey('members.User') name = models.CharField(max_length=100) flp = models.ForeignKey('members.User', related_name='flp') team = models.ManyToManyField('members.User', related_name='team') description = models.TextField() targets = models.TextField() tasks = models.TextField() target_group = models.TextField() schedule = models.TextField() resources = models.TextField() finance_description = models.TextField() partners = models.TextField(blank=True, null=True) files = models.ManyToManyField('attachments.Attachment') status = models.CharField(max_length=50, choices=STATUS, default='unrevised') date = models.DateField(blank=True, null=True) def __unicode__(self): return self.nameRename the date field related to the project status
# -*- encoding:utf-8 -*- from django.db import models class Project(models.Model): STATUS = ( ('unrevised', u'Неразгледан'), ('returned', u'Върнат за корекция'), ('pending', u'Предстои да бъде разгледан на СИС'), ('approved', u'Разгледан и одобрен на СИС'), ('rejected', u'Разгледан и неодобрен на СИС')) user = models.ForeignKey('members.User') name = models.CharField(max_length=100) flp = models.ForeignKey('members.User', related_name='flp') team = models.ManyToManyField('members.User', related_name='team') description = models.TextField() targets = models.TextField() tasks = models.TextField() target_group = models.TextField() schedule = models.TextField() resources = models.TextField() finance_description = models.TextField() partners = models.TextField(blank=True, null=True) files = models.ManyToManyField('attachments.Attachment') status = models.CharField(max_length=50, choices=STATUS, default='unrevised') discussed_at = models.DateField(blank=True, null=True) def __unicode__(self): return self.name
<commit_before># -*- encoding:utf-8 -*- from django.db import models class Project(models.Model): STATUS = ( ('unrevised', u'Неразгледан'), ('returned', u'Върнат за корекция'), ('pending', u'Предстои да бъде разгледан на СИС'), ('approved', u'Разгледан и одобрен на СИС'), ('rejected', u'Разгледан и неодобрен на СИС')) user = models.ForeignKey('members.User') name = models.CharField(max_length=100) flp = models.ForeignKey('members.User', related_name='flp') team = models.ManyToManyField('members.User', related_name='team') description = models.TextField() targets = models.TextField() tasks = models.TextField() target_group = models.TextField() schedule = models.TextField() resources = models.TextField() finance_description = models.TextField() partners = models.TextField(blank=True, null=True) files = models.ManyToManyField('attachments.Attachment') status = models.CharField(max_length=50, choices=STATUS, default='unrevised') date = models.DateField(blank=True, null=True) def __unicode__(self): return self.name<commit_msg>Rename the date field related to the project status<commit_after>
# -*- encoding:utf-8 -*- from django.db import models class Project(models.Model): STATUS = ( ('unrevised', u'Неразгледан'), ('returned', u'Върнат за корекция'), ('pending', u'Предстои да бъде разгледан на СИС'), ('approved', u'Разгледан и одобрен на СИС'), ('rejected', u'Разгледан и неодобрен на СИС')) user = models.ForeignKey('members.User') name = models.CharField(max_length=100) flp = models.ForeignKey('members.User', related_name='flp') team = models.ManyToManyField('members.User', related_name='team') description = models.TextField() targets = models.TextField() tasks = models.TextField() target_group = models.TextField() schedule = models.TextField() resources = models.TextField() finance_description = models.TextField() partners = models.TextField(blank=True, null=True) files = models.ManyToManyField('attachments.Attachment') status = models.CharField(max_length=50, choices=STATUS, default='unrevised') discussed_at = models.DateField(blank=True, null=True) def __unicode__(self): return self.name
# -*- encoding:utf-8 -*- from django.db import models class Project(models.Model): STATUS = ( ('unrevised', u'Неразгледан'), ('returned', u'Върнат за корекция'), ('pending', u'Предстои да бъде разгледан на СИС'), ('approved', u'Разгледан и одобрен на СИС'), ('rejected', u'Разгледан и неодобрен на СИС')) user = models.ForeignKey('members.User') name = models.CharField(max_length=100) flp = models.ForeignKey('members.User', related_name='flp') team = models.ManyToManyField('members.User', related_name='team') description = models.TextField() targets = models.TextField() tasks = models.TextField() target_group = models.TextField() schedule = models.TextField() resources = models.TextField() finance_description = models.TextField() partners = models.TextField(blank=True, null=True) files = models.ManyToManyField('attachments.Attachment') status = models.CharField(max_length=50, choices=STATUS, default='unrevised') date = models.DateField(blank=True, null=True) def __unicode__(self): return self.nameRename the date field related to the project status# -*- encoding:utf-8 -*- from django.db import models class Project(models.Model): STATUS = ( ('unrevised', u'Неразгледан'), ('returned', u'Върнат за корекция'), ('pending', u'Предстои да бъде разгледан на СИС'), ('approved', u'Разгледан и одобрен на СИС'), ('rejected', u'Разгледан и неодобрен на СИС')) user = models.ForeignKey('members.User') name = models.CharField(max_length=100) flp = models.ForeignKey('members.User', related_name='flp') team = models.ManyToManyField('members.User', related_name='team') description = models.TextField() targets = models.TextField() tasks = models.TextField() target_group = models.TextField() schedule = models.TextField() resources = models.TextField() finance_description = models.TextField() partners = models.TextField(blank=True, null=True) files = models.ManyToManyField('attachments.Attachment') status = models.CharField(max_length=50, choices=STATUS, default='unrevised') discussed_at = models.DateField(blank=True, null=True) def __unicode__(self): return self.name
<commit_before># -*- encoding:utf-8 -*- from django.db import models class Project(models.Model): STATUS = ( ('unrevised', u'Неразгледан'), ('returned', u'Върнат за корекция'), ('pending', u'Предстои да бъде разгледан на СИС'), ('approved', u'Разгледан и одобрен на СИС'), ('rejected', u'Разгледан и неодобрен на СИС')) user = models.ForeignKey('members.User') name = models.CharField(max_length=100) flp = models.ForeignKey('members.User', related_name='flp') team = models.ManyToManyField('members.User', related_name='team') description = models.TextField() targets = models.TextField() tasks = models.TextField() target_group = models.TextField() schedule = models.TextField() resources = models.TextField() finance_description = models.TextField() partners = models.TextField(blank=True, null=True) files = models.ManyToManyField('attachments.Attachment') status = models.CharField(max_length=50, choices=STATUS, default='unrevised') date = models.DateField(blank=True, null=True) def __unicode__(self): return self.name<commit_msg>Rename the date field related to the project status<commit_after># -*- encoding:utf-8 -*- from django.db import models class Project(models.Model): STATUS = ( ('unrevised', u'Неразгледан'), ('returned', u'Върнат за корекция'), ('pending', u'Предстои да бъде разгледан на СИС'), ('approved', u'Разгледан и одобрен на СИС'), ('rejected', u'Разгледан и неодобрен на СИС')) user = models.ForeignKey('members.User') name = models.CharField(max_length=100) flp = models.ForeignKey('members.User', related_name='flp') team = models.ManyToManyField('members.User', related_name='team') description = models.TextField() targets = models.TextField() tasks = models.TextField() target_group = models.TextField() schedule = models.TextField() resources = models.TextField() finance_description = models.TextField() partners = models.TextField(blank=True, null=True) files = models.ManyToManyField('attachments.Attachment') status = models.CharField(max_length=50, choices=STATUS, default='unrevised') discussed_at = models.DateField(blank=True, null=True) def __unicode__(self): return self.name
c9b97f6d1148378d1ba7189a1838ea03e240de40
pycron/__init__.py
pycron/__init__.py
from datetime import datetime def _parse_arg(value, target, maximum): if value == '*': return True if '/' in value: value, interval = value.split('/') if value != '*': raise ValueError interval = int(interval) if interval not in range(0, maximum + 1): raise ValueError return target % int(interval) == 0 if int(value) == target: return True return False def is_now(s): ''' A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time. @input: cron-like string @output: boolean of result ''' now = datetime.now() minute, hour, dom, month, dow = s.split(' ') return _parse_arg(minute, now.minute, 30) \ and _parse_arg(hour, now.hour, 12) \ and _parse_arg(dom, now.day, 14) \ and _parse_arg(month, now.month, 6) \ and _parse_arg(dow, now.weekday(), 3)
from datetime import datetime def _parse_arg(value, target, maximum): if value == '*': return True if ',' in value: if '*' in value: raise ValueError values = filter(None, [int(x.strip()) for x in value.split(',')]) if target in values: return True return False if '/' in value: value, interval = value.split('/') if value != '*': raise ValueError interval = int(interval) if interval not in range(0, maximum + 1): raise ValueError return target % int(interval) == 0 if int(value) == target: return True return False def is_now(s): ''' A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time. @input: cron-like string (minute, hour, day of month, month, day of week) @output: boolean of result ''' now = datetime.now() minute, hour, dom, month, dow = s.split(' ') return _parse_arg(minute, now.minute, 30) \ and _parse_arg(hour, now.hour, 12) \ and _parse_arg(dom, now.day, 14) \ and _parse_arg(month, now.month, 6) \ and _parse_arg(dow, now.weekday(), 3)
Add parsing for list of numbers.
Add parsing for list of numbers.
Python
mit
kipe/pycron
from datetime import datetime def _parse_arg(value, target, maximum): if value == '*': return True if '/' in value: value, interval = value.split('/') if value != '*': raise ValueError interval = int(interval) if interval not in range(0, maximum + 1): raise ValueError return target % int(interval) == 0 if int(value) == target: return True return False def is_now(s): ''' A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time. @input: cron-like string @output: boolean of result ''' now = datetime.now() minute, hour, dom, month, dow = s.split(' ') return _parse_arg(minute, now.minute, 30) \ and _parse_arg(hour, now.hour, 12) \ and _parse_arg(dom, now.day, 14) \ and _parse_arg(month, now.month, 6) \ and _parse_arg(dow, now.weekday(), 3) Add parsing for list of numbers.
from datetime import datetime def _parse_arg(value, target, maximum): if value == '*': return True if ',' in value: if '*' in value: raise ValueError values = filter(None, [int(x.strip()) for x in value.split(',')]) if target in values: return True return False if '/' in value: value, interval = value.split('/') if value != '*': raise ValueError interval = int(interval) if interval not in range(0, maximum + 1): raise ValueError return target % int(interval) == 0 if int(value) == target: return True return False def is_now(s): ''' A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time. @input: cron-like string (minute, hour, day of month, month, day of week) @output: boolean of result ''' now = datetime.now() minute, hour, dom, month, dow = s.split(' ') return _parse_arg(minute, now.minute, 30) \ and _parse_arg(hour, now.hour, 12) \ and _parse_arg(dom, now.day, 14) \ and _parse_arg(month, now.month, 6) \ and _parse_arg(dow, now.weekday(), 3)
<commit_before>from datetime import datetime def _parse_arg(value, target, maximum): if value == '*': return True if '/' in value: value, interval = value.split('/') if value != '*': raise ValueError interval = int(interval) if interval not in range(0, maximum + 1): raise ValueError return target % int(interval) == 0 if int(value) == target: return True return False def is_now(s): ''' A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time. @input: cron-like string @output: boolean of result ''' now = datetime.now() minute, hour, dom, month, dow = s.split(' ') return _parse_arg(minute, now.minute, 30) \ and _parse_arg(hour, now.hour, 12) \ and _parse_arg(dom, now.day, 14) \ and _parse_arg(month, now.month, 6) \ and _parse_arg(dow, now.weekday(), 3) <commit_msg>Add parsing for list of numbers.<commit_after>
from datetime import datetime def _parse_arg(value, target, maximum): if value == '*': return True if ',' in value: if '*' in value: raise ValueError values = filter(None, [int(x.strip()) for x in value.split(',')]) if target in values: return True return False if '/' in value: value, interval = value.split('/') if value != '*': raise ValueError interval = int(interval) if interval not in range(0, maximum + 1): raise ValueError return target % int(interval) == 0 if int(value) == target: return True return False def is_now(s): ''' A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time. @input: cron-like string (minute, hour, day of month, month, day of week) @output: boolean of result ''' now = datetime.now() minute, hour, dom, month, dow = s.split(' ') return _parse_arg(minute, now.minute, 30) \ and _parse_arg(hour, now.hour, 12) \ and _parse_arg(dom, now.day, 14) \ and _parse_arg(month, now.month, 6) \ and _parse_arg(dow, now.weekday(), 3)
from datetime import datetime def _parse_arg(value, target, maximum): if value == '*': return True if '/' in value: value, interval = value.split('/') if value != '*': raise ValueError interval = int(interval) if interval not in range(0, maximum + 1): raise ValueError return target % int(interval) == 0 if int(value) == target: return True return False def is_now(s): ''' A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time. @input: cron-like string @output: boolean of result ''' now = datetime.now() minute, hour, dom, month, dow = s.split(' ') return _parse_arg(minute, now.minute, 30) \ and _parse_arg(hour, now.hour, 12) \ and _parse_arg(dom, now.day, 14) \ and _parse_arg(month, now.month, 6) \ and _parse_arg(dow, now.weekday(), 3) Add parsing for list of numbers.from datetime import datetime def _parse_arg(value, target, maximum): if value == '*': return True if ',' in value: if '*' in value: raise ValueError values = filter(None, [int(x.strip()) for x in value.split(',')]) if target in values: return True return False if '/' in value: value, interval = value.split('/') if value != '*': raise ValueError interval = int(interval) if interval not in range(0, maximum + 1): raise ValueError return target % int(interval) == 0 if int(value) == target: return True return False def is_now(s): ''' A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time. @input: cron-like string (minute, hour, day of month, month, day of week) @output: boolean of result ''' now = datetime.now() minute, hour, dom, month, dow = s.split(' ') return _parse_arg(minute, now.minute, 30) \ and _parse_arg(hour, now.hour, 12) \ and _parse_arg(dom, now.day, 14) \ and _parse_arg(month, now.month, 6) \ and _parse_arg(dow, now.weekday(), 3)
<commit_before>from datetime import datetime def _parse_arg(value, target, maximum): if value == '*': return True if '/' in value: value, interval = value.split('/') if value != '*': raise ValueError interval = int(interval) if interval not in range(0, maximum + 1): raise ValueError return target % int(interval) == 0 if int(value) == target: return True return False def is_now(s): ''' A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time. @input: cron-like string @output: boolean of result ''' now = datetime.now() minute, hour, dom, month, dow = s.split(' ') return _parse_arg(minute, now.minute, 30) \ and _parse_arg(hour, now.hour, 12) \ and _parse_arg(dom, now.day, 14) \ and _parse_arg(month, now.month, 6) \ and _parse_arg(dow, now.weekday(), 3) <commit_msg>Add parsing for list of numbers.<commit_after>from datetime import datetime def _parse_arg(value, target, maximum): if value == '*': return True if ',' in value: if '*' in value: raise ValueError values = filter(None, [int(x.strip()) for x in value.split(',')]) if target in values: return True return False if '/' in value: value, interval = value.split('/') if value != '*': raise ValueError interval = int(interval) if interval not in range(0, maximum + 1): raise ValueError return target % int(interval) == 0 if int(value) == target: return True return False def is_now(s): ''' A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time. @input: cron-like string (minute, hour, day of month, month, day of week) @output: boolean of result ''' now = datetime.now() minute, hour, dom, month, dow = s.split(' ') return _parse_arg(minute, now.minute, 30) \ and _parse_arg(hour, now.hour, 12) \ and _parse_arg(dom, now.day, 14) \ and _parse_arg(month, now.month, 6) \ and _parse_arg(dow, now.weekday(), 3)
2c09716430f90f8bac00ff5a1490693578960495
q_and_a/apps/questions/api/resources.py
q_and_a/apps/questions/api/resources.py
from tastypie.resources import ModelResource from questions.models import Answer class AnswerResource(ModelResource): class Meta: queryset = Answer.objects.all() allowed_methods = ['get']
import json from tastypie.resources import ModelResource from questions.models import Answer from django.core.serializers.json import DjangoJSONEncoder from tastypie.serializers import Serializer # From the Tastypie Cookbook: Pretty-printed JSON Serialization # http://django-tastypie.readthedocs.org/en/latest/cookbook.html#pretty-printed-json-serialization class PrettyJSONSerializer(Serializer): json_indent = 2 def to_json(self, data, options=None): options = options or {} data = self.to_simple(data, options) return json.dumps(data, cls=DjangoJSONEncoder, sort_keys=True, ensure_ascii=False, indent=self.json_indent) class AnswerResource(ModelResource): class Meta: queryset = Answer.objects.all() allowed_methods = ['get'] serializer = PrettyJSONSerializer()
Switch to pretty printing JSON for the API.
Switch to pretty printing JSON for the API.
Python
bsd-3-clause
DemocracyClub/candidate_questions,DemocracyClub/candidate_questions,DemocracyClub/candidate_questions
from tastypie.resources import ModelResource from questions.models import Answer class AnswerResource(ModelResource): class Meta: queryset = Answer.objects.all() allowed_methods = ['get'] Switch to pretty printing JSON for the API.
import json from tastypie.resources import ModelResource from questions.models import Answer from django.core.serializers.json import DjangoJSONEncoder from tastypie.serializers import Serializer # From the Tastypie Cookbook: Pretty-printed JSON Serialization # http://django-tastypie.readthedocs.org/en/latest/cookbook.html#pretty-printed-json-serialization class PrettyJSONSerializer(Serializer): json_indent = 2 def to_json(self, data, options=None): options = options or {} data = self.to_simple(data, options) return json.dumps(data, cls=DjangoJSONEncoder, sort_keys=True, ensure_ascii=False, indent=self.json_indent) class AnswerResource(ModelResource): class Meta: queryset = Answer.objects.all() allowed_methods = ['get'] serializer = PrettyJSONSerializer()
<commit_before>from tastypie.resources import ModelResource from questions.models import Answer class AnswerResource(ModelResource): class Meta: queryset = Answer.objects.all() allowed_methods = ['get'] <commit_msg>Switch to pretty printing JSON for the API.<commit_after>
import json from tastypie.resources import ModelResource from questions.models import Answer from django.core.serializers.json import DjangoJSONEncoder from tastypie.serializers import Serializer # From the Tastypie Cookbook: Pretty-printed JSON Serialization # http://django-tastypie.readthedocs.org/en/latest/cookbook.html#pretty-printed-json-serialization class PrettyJSONSerializer(Serializer): json_indent = 2 def to_json(self, data, options=None): options = options or {} data = self.to_simple(data, options) return json.dumps(data, cls=DjangoJSONEncoder, sort_keys=True, ensure_ascii=False, indent=self.json_indent) class AnswerResource(ModelResource): class Meta: queryset = Answer.objects.all() allowed_methods = ['get'] serializer = PrettyJSONSerializer()
from tastypie.resources import ModelResource from questions.models import Answer class AnswerResource(ModelResource): class Meta: queryset = Answer.objects.all() allowed_methods = ['get'] Switch to pretty printing JSON for the API.import json from tastypie.resources import ModelResource from questions.models import Answer from django.core.serializers.json import DjangoJSONEncoder from tastypie.serializers import Serializer # From the Tastypie Cookbook: Pretty-printed JSON Serialization # http://django-tastypie.readthedocs.org/en/latest/cookbook.html#pretty-printed-json-serialization class PrettyJSONSerializer(Serializer): json_indent = 2 def to_json(self, data, options=None): options = options or {} data = self.to_simple(data, options) return json.dumps(data, cls=DjangoJSONEncoder, sort_keys=True, ensure_ascii=False, indent=self.json_indent) class AnswerResource(ModelResource): class Meta: queryset = Answer.objects.all() allowed_methods = ['get'] serializer = PrettyJSONSerializer()
<commit_before>from tastypie.resources import ModelResource from questions.models import Answer class AnswerResource(ModelResource): class Meta: queryset = Answer.objects.all() allowed_methods = ['get'] <commit_msg>Switch to pretty printing JSON for the API.<commit_after>import json from tastypie.resources import ModelResource from questions.models import Answer from django.core.serializers.json import DjangoJSONEncoder from tastypie.serializers import Serializer # From the Tastypie Cookbook: Pretty-printed JSON Serialization # http://django-tastypie.readthedocs.org/en/latest/cookbook.html#pretty-printed-json-serialization class PrettyJSONSerializer(Serializer): json_indent = 2 def to_json(self, data, options=None): options = options or {} data = self.to_simple(data, options) return json.dumps(data, cls=DjangoJSONEncoder, sort_keys=True, ensure_ascii=False, indent=self.json_indent) class AnswerResource(ModelResource): class Meta: queryset = Answer.objects.all() allowed_methods = ['get'] serializer = PrettyJSONSerializer()
02ab421105754e6ec258bc7c48b794bcb8ad95ec
HOME/.ipython/profile_default/ipython_config.py
HOME/.ipython/profile_default/ipython_config.py
c.TerminalIPythonApp.display_banner = False c.TerminalInteractiveShell.confirm_exit = False c.TerminalInteractiveShell.highlighting_style = "monokai" c.TerminalInteractiveShell.term_title = False
c.TerminalIPythonApp.display_banner = False c.TerminalInteractiveShell.confirm_exit = False c.TerminalInteractiveShell.highlighting_style = "monokai" c.TerminalInteractiveShell.term_title = False import logging logging.getLogger('parso').level = logging.WARN
Fix spammy logging during IPython tab complete
Fix spammy logging during IPython tab complete https://github.com/ipython/ipython/issues/10946
Python
mit
kbd/setup,kbd/setup,kbd/setup,kbd/setup,kbd/setup
c.TerminalIPythonApp.display_banner = False c.TerminalInteractiveShell.confirm_exit = False c.TerminalInteractiveShell.highlighting_style = "monokai" c.TerminalInteractiveShell.term_title = False Fix spammy logging during IPython tab complete https://github.com/ipython/ipython/issues/10946
c.TerminalIPythonApp.display_banner = False c.TerminalInteractiveShell.confirm_exit = False c.TerminalInteractiveShell.highlighting_style = "monokai" c.TerminalInteractiveShell.term_title = False import logging logging.getLogger('parso').level = logging.WARN
<commit_before>c.TerminalIPythonApp.display_banner = False c.TerminalInteractiveShell.confirm_exit = False c.TerminalInteractiveShell.highlighting_style = "monokai" c.TerminalInteractiveShell.term_title = False <commit_msg>Fix spammy logging during IPython tab complete https://github.com/ipython/ipython/issues/10946<commit_after>
c.TerminalIPythonApp.display_banner = False c.TerminalInteractiveShell.confirm_exit = False c.TerminalInteractiveShell.highlighting_style = "monokai" c.TerminalInteractiveShell.term_title = False import logging logging.getLogger('parso').level = logging.WARN
c.TerminalIPythonApp.display_banner = False c.TerminalInteractiveShell.confirm_exit = False c.TerminalInteractiveShell.highlighting_style = "monokai" c.TerminalInteractiveShell.term_title = False Fix spammy logging during IPython tab complete https://github.com/ipython/ipython/issues/10946c.TerminalIPythonApp.display_banner = False c.TerminalInteractiveShell.confirm_exit = False c.TerminalInteractiveShell.highlighting_style = "monokai" c.TerminalInteractiveShell.term_title = False import logging logging.getLogger('parso').level = logging.WARN
<commit_before>c.TerminalIPythonApp.display_banner = False c.TerminalInteractiveShell.confirm_exit = False c.TerminalInteractiveShell.highlighting_style = "monokai" c.TerminalInteractiveShell.term_title = False <commit_msg>Fix spammy logging during IPython tab complete https://github.com/ipython/ipython/issues/10946<commit_after>c.TerminalIPythonApp.display_banner = False c.TerminalInteractiveShell.confirm_exit = False c.TerminalInteractiveShell.highlighting_style = "monokai" c.TerminalInteractiveShell.term_title = False import logging logging.getLogger('parso').level = logging.WARN
770f1a5d83a8450e9a16942d1260483f7b1401cd
sauce/model/news.py
sauce/model/news.py
# -*- coding: utf-8 -*- '''News model module @author: moschlar ''' from datetime import datetime from sqlalchemy import ForeignKey, Column from sqlalchemy.types import Integer, Unicode, DateTime, Boolean from sqlalchemy.orm import relationship, backref from sqlalchemy.sql import desc from sauce.model import DeclarativeBase class NewsItem(DeclarativeBase): '''A NewsItem''' __tablename__ = 'newsitems' id = Column(Integer, primary_key=True) date = Column(DateTime, default=datetime.now) subject = Column(Unicode(255), nullable=False) message = Column(Unicode(65536)) event_id = Column(Integer, ForeignKey('events.id')) event = relationship('Event', backref=backref('news', order_by=desc(date)) ) '''If event == None, NewsItem is to be displayed on front page instead of event page''' user_id = Column(Integer, ForeignKey('users.id'), nullable=False) user = relationship('User', #backref=backref('news', # cascade='all, delete-orphan') ) '''The User that wrote the NewsItem''' public = Column(Boolean, nullable=False, default=False) __mapper_args__ = {'order_by': desc(date)}
# -*- coding: utf-8 -*- '''News model module @author: moschlar ''' from datetime import datetime from sqlalchemy import ForeignKey, Column from sqlalchemy.types import Integer, Unicode, DateTime, Boolean from sqlalchemy.orm import relationship, backref from sqlalchemy.sql import desc from sauce.model import DeclarativeBase class NewsItem(DeclarativeBase): '''A NewsItem''' __tablename__ = 'newsitems' id = Column(Integer, primary_key=True) date = Column(DateTime, default=datetime.now) subject = Column(Unicode(255), nullable=False) message = Column(Unicode(65536)) event_id = Column(Integer, ForeignKey('events.id')) event = relationship('Event', backref=backref('news', order_by=desc(date)) ) '''If event == None, NewsItem is to be displayed on front page instead of event page''' user_id = Column(Integer, ForeignKey('users.id'), nullable=False) user = relationship('User', #backref=backref('news', # cascade='all, delete-orphan') ) '''The User that wrote the NewsItem''' public = Column(Boolean, nullable=False, default=False) __mapper_args__ = {'order_by': desc(date)} def __unicode__(self): return u'NewsItem %d "%s"' % (self.id or '', self.subject)
Add unicode repr to NewsItem
Add unicode repr to NewsItem
Python
agpl-3.0
moschlar/SAUCE,moschlar/SAUCE,moschlar/SAUCE,moschlar/SAUCE
# -*- coding: utf-8 -*- '''News model module @author: moschlar ''' from datetime import datetime from sqlalchemy import ForeignKey, Column from sqlalchemy.types import Integer, Unicode, DateTime, Boolean from sqlalchemy.orm import relationship, backref from sqlalchemy.sql import desc from sauce.model import DeclarativeBase class NewsItem(DeclarativeBase): '''A NewsItem''' __tablename__ = 'newsitems' id = Column(Integer, primary_key=True) date = Column(DateTime, default=datetime.now) subject = Column(Unicode(255), nullable=False) message = Column(Unicode(65536)) event_id = Column(Integer, ForeignKey('events.id')) event = relationship('Event', backref=backref('news', order_by=desc(date)) ) '''If event == None, NewsItem is to be displayed on front page instead of event page''' user_id = Column(Integer, ForeignKey('users.id'), nullable=False) user = relationship('User', #backref=backref('news', # cascade='all, delete-orphan') ) '''The User that wrote the NewsItem''' public = Column(Boolean, nullable=False, default=False) __mapper_args__ = {'order_by': desc(date)} Add unicode repr to NewsItem
# -*- coding: utf-8 -*- '''News model module @author: moschlar ''' from datetime import datetime from sqlalchemy import ForeignKey, Column from sqlalchemy.types import Integer, Unicode, DateTime, Boolean from sqlalchemy.orm import relationship, backref from sqlalchemy.sql import desc from sauce.model import DeclarativeBase class NewsItem(DeclarativeBase): '''A NewsItem''' __tablename__ = 'newsitems' id = Column(Integer, primary_key=True) date = Column(DateTime, default=datetime.now) subject = Column(Unicode(255), nullable=False) message = Column(Unicode(65536)) event_id = Column(Integer, ForeignKey('events.id')) event = relationship('Event', backref=backref('news', order_by=desc(date)) ) '''If event == None, NewsItem is to be displayed on front page instead of event page''' user_id = Column(Integer, ForeignKey('users.id'), nullable=False) user = relationship('User', #backref=backref('news', # cascade='all, delete-orphan') ) '''The User that wrote the NewsItem''' public = Column(Boolean, nullable=False, default=False) __mapper_args__ = {'order_by': desc(date)} def __unicode__(self): return u'NewsItem %d "%s"' % (self.id or '', self.subject)
<commit_before># -*- coding: utf-8 -*- '''News model module @author: moschlar ''' from datetime import datetime from sqlalchemy import ForeignKey, Column from sqlalchemy.types import Integer, Unicode, DateTime, Boolean from sqlalchemy.orm import relationship, backref from sqlalchemy.sql import desc from sauce.model import DeclarativeBase class NewsItem(DeclarativeBase): '''A NewsItem''' __tablename__ = 'newsitems' id = Column(Integer, primary_key=True) date = Column(DateTime, default=datetime.now) subject = Column(Unicode(255), nullable=False) message = Column(Unicode(65536)) event_id = Column(Integer, ForeignKey('events.id')) event = relationship('Event', backref=backref('news', order_by=desc(date)) ) '''If event == None, NewsItem is to be displayed on front page instead of event page''' user_id = Column(Integer, ForeignKey('users.id'), nullable=False) user = relationship('User', #backref=backref('news', # cascade='all, delete-orphan') ) '''The User that wrote the NewsItem''' public = Column(Boolean, nullable=False, default=False) __mapper_args__ = {'order_by': desc(date)} <commit_msg>Add unicode repr to NewsItem<commit_after>
# -*- coding: utf-8 -*- '''News model module @author: moschlar ''' from datetime import datetime from sqlalchemy import ForeignKey, Column from sqlalchemy.types import Integer, Unicode, DateTime, Boolean from sqlalchemy.orm import relationship, backref from sqlalchemy.sql import desc from sauce.model import DeclarativeBase class NewsItem(DeclarativeBase): '''A NewsItem''' __tablename__ = 'newsitems' id = Column(Integer, primary_key=True) date = Column(DateTime, default=datetime.now) subject = Column(Unicode(255), nullable=False) message = Column(Unicode(65536)) event_id = Column(Integer, ForeignKey('events.id')) event = relationship('Event', backref=backref('news', order_by=desc(date)) ) '''If event == None, NewsItem is to be displayed on front page instead of event page''' user_id = Column(Integer, ForeignKey('users.id'), nullable=False) user = relationship('User', #backref=backref('news', # cascade='all, delete-orphan') ) '''The User that wrote the NewsItem''' public = Column(Boolean, nullable=False, default=False) __mapper_args__ = {'order_by': desc(date)} def __unicode__(self): return u'NewsItem %d "%s"' % (self.id or '', self.subject)
# -*- coding: utf-8 -*- '''News model module @author: moschlar ''' from datetime import datetime from sqlalchemy import ForeignKey, Column from sqlalchemy.types import Integer, Unicode, DateTime, Boolean from sqlalchemy.orm import relationship, backref from sqlalchemy.sql import desc from sauce.model import DeclarativeBase class NewsItem(DeclarativeBase): '''A NewsItem''' __tablename__ = 'newsitems' id = Column(Integer, primary_key=True) date = Column(DateTime, default=datetime.now) subject = Column(Unicode(255), nullable=False) message = Column(Unicode(65536)) event_id = Column(Integer, ForeignKey('events.id')) event = relationship('Event', backref=backref('news', order_by=desc(date)) ) '''If event == None, NewsItem is to be displayed on front page instead of event page''' user_id = Column(Integer, ForeignKey('users.id'), nullable=False) user = relationship('User', #backref=backref('news', # cascade='all, delete-orphan') ) '''The User that wrote the NewsItem''' public = Column(Boolean, nullable=False, default=False) __mapper_args__ = {'order_by': desc(date)} Add unicode repr to NewsItem# -*- coding: utf-8 -*- '''News model module @author: moschlar ''' from datetime import datetime from sqlalchemy import ForeignKey, Column from sqlalchemy.types import Integer, Unicode, DateTime, Boolean from sqlalchemy.orm import relationship, backref from sqlalchemy.sql import desc from sauce.model import DeclarativeBase class NewsItem(DeclarativeBase): '''A NewsItem''' __tablename__ = 'newsitems' id = Column(Integer, primary_key=True) date = Column(DateTime, default=datetime.now) subject = Column(Unicode(255), nullable=False) message = Column(Unicode(65536)) event_id = Column(Integer, ForeignKey('events.id')) event = relationship('Event', backref=backref('news', order_by=desc(date)) ) '''If event == None, NewsItem is to be displayed on front page instead of event page''' user_id = Column(Integer, ForeignKey('users.id'), nullable=False) user = relationship('User', #backref=backref('news', # cascade='all, delete-orphan') ) '''The User that wrote the NewsItem''' public = Column(Boolean, nullable=False, default=False) __mapper_args__ = {'order_by': desc(date)} def __unicode__(self): return u'NewsItem %d "%s"' % (self.id or '', self.subject)
<commit_before># -*- coding: utf-8 -*- '''News model module @author: moschlar ''' from datetime import datetime from sqlalchemy import ForeignKey, Column from sqlalchemy.types import Integer, Unicode, DateTime, Boolean from sqlalchemy.orm import relationship, backref from sqlalchemy.sql import desc from sauce.model import DeclarativeBase class NewsItem(DeclarativeBase): '''A NewsItem''' __tablename__ = 'newsitems' id = Column(Integer, primary_key=True) date = Column(DateTime, default=datetime.now) subject = Column(Unicode(255), nullable=False) message = Column(Unicode(65536)) event_id = Column(Integer, ForeignKey('events.id')) event = relationship('Event', backref=backref('news', order_by=desc(date)) ) '''If event == None, NewsItem is to be displayed on front page instead of event page''' user_id = Column(Integer, ForeignKey('users.id'), nullable=False) user = relationship('User', #backref=backref('news', # cascade='all, delete-orphan') ) '''The User that wrote the NewsItem''' public = Column(Boolean, nullable=False, default=False) __mapper_args__ = {'order_by': desc(date)} <commit_msg>Add unicode repr to NewsItem<commit_after># -*- coding: utf-8 -*- '''News model module @author: moschlar ''' from datetime import datetime from sqlalchemy import ForeignKey, Column from sqlalchemy.types import Integer, Unicode, DateTime, Boolean from sqlalchemy.orm import relationship, backref from sqlalchemy.sql import desc from sauce.model import DeclarativeBase class NewsItem(DeclarativeBase): '''A NewsItem''' __tablename__ = 'newsitems' id = Column(Integer, primary_key=True) date = Column(DateTime, default=datetime.now) subject = Column(Unicode(255), nullable=False) message = Column(Unicode(65536)) event_id = Column(Integer, ForeignKey('events.id')) event = relationship('Event', backref=backref('news', order_by=desc(date)) ) '''If event == None, NewsItem is to be displayed on front page instead of event page''' user_id = Column(Integer, ForeignKey('users.id'), nullable=False) user = relationship('User', #backref=backref('news', # cascade='all, delete-orphan') ) '''The User that wrote the NewsItem''' public = Column(Boolean, nullable=False, default=False) __mapper_args__ = {'order_by': desc(date)} def __unicode__(self): return u'NewsItem %d "%s"' % (self.id or '', self.subject)
5db2ee20fbe8ecdf1d432fd23c21702233f1bba7
recharges/tasks.py
recharges/tasks.py
from celery.task import Task from celery.utils.log import get_task_logger import requests logger = get_task_logger(__name__) class Hotsocket_Login(Task): """ Task to get the username and password varified then produce a token """ name = "gopherairtime.recharges.tasks.hotsocket_login" def run(self, **kwargs): """ Returns the token """ l = self.get_logger(**kwargs) l.info("Logging into hotsocket") auth = {'username': 'trial_acc_1212', 'password': 'tr14l_l1k3m00n', 'as_json': True} r = requests.post("http://api.hotsocket.co.za:8080/test/login",data=auth) result = r.json() return result["response"]["token"] hotsocket_login = Hotsocket_Login()
import requests from django.conf import settings from celery.task import Task from celery.utils.log import get_task_logger from .models import Account logger = get_task_logger(__name__) class Hotsocket_Login(Task): """ Task to get the username and password varified then produce a token """ name = "gopherairtime.recharges.tasks.hotsocket_login" def run(self, **kwargs): """ Returns the token """ l = self.get_logger(**kwargs) l.info("Logging into hotsocket") auth = {'username': 'trial_acc_1212', 'password': 'tr14l_l1k3m00n', 'as_json': True} r = requests.post("%s/login" % settings.HOTSOCKET_API_ENDPOINT, data=auth) result = r.json() token = result["response"]["token"] account = Account() account.token = token account.save() return True hotsocket_login = Hotsocket_Login()
Refactor the task for getting token to store it in DB
Refactor the task for getting token to store it in DB
Python
bsd-3-clause
westerncapelabs/gopherairtime,westerncapelabs/gopherairtime
from celery.task import Task from celery.utils.log import get_task_logger import requests logger = get_task_logger(__name__) class Hotsocket_Login(Task): """ Task to get the username and password varified then produce a token """ name = "gopherairtime.recharges.tasks.hotsocket_login" def run(self, **kwargs): """ Returns the token """ l = self.get_logger(**kwargs) l.info("Logging into hotsocket") auth = {'username': 'trial_acc_1212', 'password': 'tr14l_l1k3m00n', 'as_json': True} r = requests.post("http://api.hotsocket.co.za:8080/test/login",data=auth) result = r.json() return result["response"]["token"] hotsocket_login = Hotsocket_Login() Refactor the task for getting token to store it in DB
import requests from django.conf import settings from celery.task import Task from celery.utils.log import get_task_logger from .models import Account logger = get_task_logger(__name__) class Hotsocket_Login(Task): """ Task to get the username and password varified then produce a token """ name = "gopherairtime.recharges.tasks.hotsocket_login" def run(self, **kwargs): """ Returns the token """ l = self.get_logger(**kwargs) l.info("Logging into hotsocket") auth = {'username': 'trial_acc_1212', 'password': 'tr14l_l1k3m00n', 'as_json': True} r = requests.post("%s/login" % settings.HOTSOCKET_API_ENDPOINT, data=auth) result = r.json() token = result["response"]["token"] account = Account() account.token = token account.save() return True hotsocket_login = Hotsocket_Login()
<commit_before>from celery.task import Task from celery.utils.log import get_task_logger import requests logger = get_task_logger(__name__) class Hotsocket_Login(Task): """ Task to get the username and password varified then produce a token """ name = "gopherairtime.recharges.tasks.hotsocket_login" def run(self, **kwargs): """ Returns the token """ l = self.get_logger(**kwargs) l.info("Logging into hotsocket") auth = {'username': 'trial_acc_1212', 'password': 'tr14l_l1k3m00n', 'as_json': True} r = requests.post("http://api.hotsocket.co.za:8080/test/login",data=auth) result = r.json() return result["response"]["token"] hotsocket_login = Hotsocket_Login() <commit_msg>Refactor the task for getting token to store it in DB<commit_after>
import requests from django.conf import settings from celery.task import Task from celery.utils.log import get_task_logger from .models import Account logger = get_task_logger(__name__) class Hotsocket_Login(Task): """ Task to get the username and password varified then produce a token """ name = "gopherairtime.recharges.tasks.hotsocket_login" def run(self, **kwargs): """ Returns the token """ l = self.get_logger(**kwargs) l.info("Logging into hotsocket") auth = {'username': 'trial_acc_1212', 'password': 'tr14l_l1k3m00n', 'as_json': True} r = requests.post("%s/login" % settings.HOTSOCKET_API_ENDPOINT, data=auth) result = r.json() token = result["response"]["token"] account = Account() account.token = token account.save() return True hotsocket_login = Hotsocket_Login()
from celery.task import Task from celery.utils.log import get_task_logger import requests logger = get_task_logger(__name__) class Hotsocket_Login(Task): """ Task to get the username and password varified then produce a token """ name = "gopherairtime.recharges.tasks.hotsocket_login" def run(self, **kwargs): """ Returns the token """ l = self.get_logger(**kwargs) l.info("Logging into hotsocket") auth = {'username': 'trial_acc_1212', 'password': 'tr14l_l1k3m00n', 'as_json': True} r = requests.post("http://api.hotsocket.co.za:8080/test/login",data=auth) result = r.json() return result["response"]["token"] hotsocket_login = Hotsocket_Login() Refactor the task for getting token to store it in DBimport requests from django.conf import settings from celery.task import Task from celery.utils.log import get_task_logger from .models import Account logger = get_task_logger(__name__) class Hotsocket_Login(Task): """ Task to get the username and password varified then produce a token """ name = "gopherairtime.recharges.tasks.hotsocket_login" def run(self, **kwargs): """ Returns the token """ l = self.get_logger(**kwargs) l.info("Logging into hotsocket") auth = {'username': 'trial_acc_1212', 'password': 'tr14l_l1k3m00n', 'as_json': True} r = requests.post("%s/login" % settings.HOTSOCKET_API_ENDPOINT, data=auth) result = r.json() token = result["response"]["token"] account = Account() account.token = token account.save() return True hotsocket_login = Hotsocket_Login()
<commit_before>from celery.task import Task from celery.utils.log import get_task_logger import requests logger = get_task_logger(__name__) class Hotsocket_Login(Task): """ Task to get the username and password varified then produce a token """ name = "gopherairtime.recharges.tasks.hotsocket_login" def run(self, **kwargs): """ Returns the token """ l = self.get_logger(**kwargs) l.info("Logging into hotsocket") auth = {'username': 'trial_acc_1212', 'password': 'tr14l_l1k3m00n', 'as_json': True} r = requests.post("http://api.hotsocket.co.za:8080/test/login",data=auth) result = r.json() return result["response"]["token"] hotsocket_login = Hotsocket_Login() <commit_msg>Refactor the task for getting token to store it in DB<commit_after>import requests from django.conf import settings from celery.task import Task from celery.utils.log import get_task_logger from .models import Account logger = get_task_logger(__name__) class Hotsocket_Login(Task): """ Task to get the username and password varified then produce a token """ name = "gopherairtime.recharges.tasks.hotsocket_login" def run(self, **kwargs): """ Returns the token """ l = self.get_logger(**kwargs) l.info("Logging into hotsocket") auth = {'username': 'trial_acc_1212', 'password': 'tr14l_l1k3m00n', 'as_json': True} r = requests.post("%s/login" % settings.HOTSOCKET_API_ENDPOINT, data=auth) result = r.json() token = result["response"]["token"] account = Account() account.token = token account.save() return True hotsocket_login = Hotsocket_Login()
4d1455614beea6b751715fbd0a0547bbe3dea018
wagtailstartproject/project_template/tests/middleware.py
wagtailstartproject/project_template/tests/middleware.py
try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object class PageStatusMiddleware(MiddlewareMixin): """Add the response status code as a meta tag in the head of all pages Note: Only enable this middleware for (Selenium) tests """ def process_response(self, request, response): # Only do this for HTML pages # (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8') if 'html' in response['Content-Type'].lower(): response.content = response.content.replace( '</head>', '<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code), 1 ) return response
try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object class PageStatusMiddleware(MiddlewareMixin): """Add the response status code as a meta tag in the head of all pages Note: Only enable this middleware for (Selenium) tests """ def process_response(self, request, response): # Only do this for HTML pages # (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8') if 'html' in response['Content-Type'].lower(): response.content = response.content.replace( b'</head>', bytes('<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code), encoding='ascii'), 1 ) return response
Update PageStatusMiddleware for use with Python 3
Update PageStatusMiddleware for use with Python 3
Python
mit
leukeleu/wagtail-startproject,leukeleu/wagtail-startproject
try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object class PageStatusMiddleware(MiddlewareMixin): """Add the response status code as a meta tag in the head of all pages Note: Only enable this middleware for (Selenium) tests """ def process_response(self, request, response): # Only do this for HTML pages # (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8') if 'html' in response['Content-Type'].lower(): response.content = response.content.replace( '</head>', '<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code), 1 ) return response Update PageStatusMiddleware for use with Python 3
try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object class PageStatusMiddleware(MiddlewareMixin): """Add the response status code as a meta tag in the head of all pages Note: Only enable this middleware for (Selenium) tests """ def process_response(self, request, response): # Only do this for HTML pages # (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8') if 'html' in response['Content-Type'].lower(): response.content = response.content.replace( b'</head>', bytes('<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code), encoding='ascii'), 1 ) return response
<commit_before>try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object class PageStatusMiddleware(MiddlewareMixin): """Add the response status code as a meta tag in the head of all pages Note: Only enable this middleware for (Selenium) tests """ def process_response(self, request, response): # Only do this for HTML pages # (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8') if 'html' in response['Content-Type'].lower(): response.content = response.content.replace( '</head>', '<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code), 1 ) return response <commit_msg>Update PageStatusMiddleware for use with Python 3<commit_after>
try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object class PageStatusMiddleware(MiddlewareMixin): """Add the response status code as a meta tag in the head of all pages Note: Only enable this middleware for (Selenium) tests """ def process_response(self, request, response): # Only do this for HTML pages # (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8') if 'html' in response['Content-Type'].lower(): response.content = response.content.replace( b'</head>', bytes('<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code), encoding='ascii'), 1 ) return response
try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object class PageStatusMiddleware(MiddlewareMixin): """Add the response status code as a meta tag in the head of all pages Note: Only enable this middleware for (Selenium) tests """ def process_response(self, request, response): # Only do this for HTML pages # (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8') if 'html' in response['Content-Type'].lower(): response.content = response.content.replace( '</head>', '<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code), 1 ) return response Update PageStatusMiddleware for use with Python 3try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object class PageStatusMiddleware(MiddlewareMixin): """Add the response status code as a meta tag in the head of all pages Note: Only enable this middleware for (Selenium) tests """ def process_response(self, request, response): # Only do this for HTML pages # (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8') if 'html' in response['Content-Type'].lower(): response.content = response.content.replace( b'</head>', bytes('<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code), encoding='ascii'), 1 ) return response
<commit_before>try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object class PageStatusMiddleware(MiddlewareMixin): """Add the response status code as a meta tag in the head of all pages Note: Only enable this middleware for (Selenium) tests """ def process_response(self, request, response): # Only do this for HTML pages # (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8') if 'html' in response['Content-Type'].lower(): response.content = response.content.replace( '</head>', '<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code), 1 ) return response <commit_msg>Update PageStatusMiddleware for use with Python 3<commit_after>try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object class PageStatusMiddleware(MiddlewareMixin): """Add the response status code as a meta tag in the head of all pages Note: Only enable this middleware for (Selenium) tests """ def process_response(self, request, response): # Only do this for HTML pages # (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8') if 'html' in response['Content-Type'].lower(): response.content = response.content.replace( b'</head>', bytes('<meta name="status_code" content="{status_code}" /></head>'.format(status_code=response.status_code), encoding='ascii'), 1 ) return response
17cb875c0f7788d108e6f78cf12d8924d02bdccf
setup-user-theme.py
setup-user-theme.py
#!/usr/bin/python # FIXME Need to handle the case when symlinks already exists import os theme_dir = os.path.expanduser('~/.themes/olpc/gtk-2.0') engine_dir = os.path.expanduser('~/.gtk-2.0/engines') src_dir = os.path.abspath(os.path.dirname(__file__)) if not os.path.exists(theme_dir): try: os.makedirs(theme_dir) except OSError, exc: if exc[0] == 17: # File exists pass os.symlink(os.path.join(src_dir, 'gtk-engine/theme/gtkrc'), os.path.join(theme_dir, 'gtkrc')) engine_dest = os.path.join(engine_dir, 'libolpc.so') if not os.path.exists(engine_dest): try: os.makedirs(engine_dir) except OSError, exc: if exc[0] == 17: # File exists pass engine_src = os.path.join(src_dir, 'gtk-engine/src/.libs/libolpc.so') os.symlink(engine_src, engine_dest)
#!/usr/bin/python # FIXME Need to handle the case when symlinks already exists import os theme_dir = os.path.expanduser('~/.themes/olpc/gtk-2.0') gtkrc_dest = os.path.join(theme_dir, 'gtkrc') engine_dir = os.path.expanduser('~/.gtk-2.0/engines') engine_dest = os.path.join(engine_dir, 'libolpc.so') src_dir = os.path.abspath(os.path.dirname(__file__)) if not os.path.exists(theme_dir): try: os.makedirs(theme_dir) except OSError, exc: if exc[0] == 17: # File exists pass try: os.unlink(gtkrc_dest) except OSError, exc: pass os.symlink(os.path.join(src_dir, 'gtk-engine/theme/gtkrc'), gtkrc_dest) if not os.path.exists(engine_dest): try: os.makedirs(engine_dir) except OSError, exc: if exc[0] == 17: # File exists pass engine_src = os.path.join(src_dir, 'gtk-engine/src/.libs/libolpc.so') try: os.unlink(engine_dest) except OSError, exc: pass os.symlink(engine_src, engine_dest)
Deal with existing symlinks and add more error checking
Deal with existing symlinks and add more error checking
Python
lgpl-2.1
samdroid-apps/sugar-artwork,samdroid-apps/sugar-artwork,gusDuarte/sugar-artwork,i5o/sugar-artwork,gusDuarte/sugar-artwork,gusDuarte/sugar-artwork,godiard/sugar-artwork,sugarlabs/sugar-artwork,tchx84/debian-pkg-sugar-artwork,i5o/sugar-artwork,godiard/sugar-artwork,tchx84/debian-pkg-sugar-artwork,gusDuarte/sugar-artwork,ceibal-tatu/sugar-artwork,i5o/sugar-artwork,ceibal-tatu/sugar-artwork,sugarlabs/sugar-artwork,godiard/sugar-artwork,ceibal-tatu/sugar-artwork,samdroid-apps/sugar-artwork,sugarlabs/sugar-artwork,tchx84/debian-pkg-sugar-artwork
#!/usr/bin/python # FIXME Need to handle the case when symlinks already exists import os theme_dir = os.path.expanduser('~/.themes/olpc/gtk-2.0') engine_dir = os.path.expanduser('~/.gtk-2.0/engines') src_dir = os.path.abspath(os.path.dirname(__file__)) if not os.path.exists(theme_dir): try: os.makedirs(theme_dir) except OSError, exc: if exc[0] == 17: # File exists pass os.symlink(os.path.join(src_dir, 'gtk-engine/theme/gtkrc'), os.path.join(theme_dir, 'gtkrc')) engine_dest = os.path.join(engine_dir, 'libolpc.so') if not os.path.exists(engine_dest): try: os.makedirs(engine_dir) except OSError, exc: if exc[0] == 17: # File exists pass engine_src = os.path.join(src_dir, 'gtk-engine/src/.libs/libolpc.so') os.symlink(engine_src, engine_dest) Deal with existing symlinks and add more error checking
#!/usr/bin/python # FIXME Need to handle the case when symlinks already exists import os theme_dir = os.path.expanduser('~/.themes/olpc/gtk-2.0') gtkrc_dest = os.path.join(theme_dir, 'gtkrc') engine_dir = os.path.expanduser('~/.gtk-2.0/engines') engine_dest = os.path.join(engine_dir, 'libolpc.so') src_dir = os.path.abspath(os.path.dirname(__file__)) if not os.path.exists(theme_dir): try: os.makedirs(theme_dir) except OSError, exc: if exc[0] == 17: # File exists pass try: os.unlink(gtkrc_dest) except OSError, exc: pass os.symlink(os.path.join(src_dir, 'gtk-engine/theme/gtkrc'), gtkrc_dest) if not os.path.exists(engine_dest): try: os.makedirs(engine_dir) except OSError, exc: if exc[0] == 17: # File exists pass engine_src = os.path.join(src_dir, 'gtk-engine/src/.libs/libolpc.so') try: os.unlink(engine_dest) except OSError, exc: pass os.symlink(engine_src, engine_dest)
<commit_before>#!/usr/bin/python # FIXME Need to handle the case when symlinks already exists import os theme_dir = os.path.expanduser('~/.themes/olpc/gtk-2.0') engine_dir = os.path.expanduser('~/.gtk-2.0/engines') src_dir = os.path.abspath(os.path.dirname(__file__)) if not os.path.exists(theme_dir): try: os.makedirs(theme_dir) except OSError, exc: if exc[0] == 17: # File exists pass os.symlink(os.path.join(src_dir, 'gtk-engine/theme/gtkrc'), os.path.join(theme_dir, 'gtkrc')) engine_dest = os.path.join(engine_dir, 'libolpc.so') if not os.path.exists(engine_dest): try: os.makedirs(engine_dir) except OSError, exc: if exc[0] == 17: # File exists pass engine_src = os.path.join(src_dir, 'gtk-engine/src/.libs/libolpc.so') os.symlink(engine_src, engine_dest) <commit_msg>Deal with existing symlinks and add more error checking<commit_after>
#!/usr/bin/python # FIXME Need to handle the case when symlinks already exists import os theme_dir = os.path.expanduser('~/.themes/olpc/gtk-2.0') gtkrc_dest = os.path.join(theme_dir, 'gtkrc') engine_dir = os.path.expanduser('~/.gtk-2.0/engines') engine_dest = os.path.join(engine_dir, 'libolpc.so') src_dir = os.path.abspath(os.path.dirname(__file__)) if not os.path.exists(theme_dir): try: os.makedirs(theme_dir) except OSError, exc: if exc[0] == 17: # File exists pass try: os.unlink(gtkrc_dest) except OSError, exc: pass os.symlink(os.path.join(src_dir, 'gtk-engine/theme/gtkrc'), gtkrc_dest) if not os.path.exists(engine_dest): try: os.makedirs(engine_dir) except OSError, exc: if exc[0] == 17: # File exists pass engine_src = os.path.join(src_dir, 'gtk-engine/src/.libs/libolpc.so') try: os.unlink(engine_dest) except OSError, exc: pass os.symlink(engine_src, engine_dest)
#!/usr/bin/python # FIXME Need to handle the case when symlinks already exists import os theme_dir = os.path.expanduser('~/.themes/olpc/gtk-2.0') engine_dir = os.path.expanduser('~/.gtk-2.0/engines') src_dir = os.path.abspath(os.path.dirname(__file__)) if not os.path.exists(theme_dir): try: os.makedirs(theme_dir) except OSError, exc: if exc[0] == 17: # File exists pass os.symlink(os.path.join(src_dir, 'gtk-engine/theme/gtkrc'), os.path.join(theme_dir, 'gtkrc')) engine_dest = os.path.join(engine_dir, 'libolpc.so') if not os.path.exists(engine_dest): try: os.makedirs(engine_dir) except OSError, exc: if exc[0] == 17: # File exists pass engine_src = os.path.join(src_dir, 'gtk-engine/src/.libs/libolpc.so') os.symlink(engine_src, engine_dest) Deal with existing symlinks and add more error checking#!/usr/bin/python # FIXME Need to handle the case when symlinks already exists import os theme_dir = os.path.expanduser('~/.themes/olpc/gtk-2.0') gtkrc_dest = os.path.join(theme_dir, 'gtkrc') engine_dir = os.path.expanduser('~/.gtk-2.0/engines') engine_dest = os.path.join(engine_dir, 'libolpc.so') src_dir = os.path.abspath(os.path.dirname(__file__)) if not os.path.exists(theme_dir): try: os.makedirs(theme_dir) except OSError, exc: if exc[0] == 17: # File exists pass try: os.unlink(gtkrc_dest) except OSError, exc: pass os.symlink(os.path.join(src_dir, 'gtk-engine/theme/gtkrc'), gtkrc_dest) if not os.path.exists(engine_dest): try: os.makedirs(engine_dir) except OSError, exc: if exc[0] == 17: # File exists pass engine_src = os.path.join(src_dir, 'gtk-engine/src/.libs/libolpc.so') try: os.unlink(engine_dest) except OSError, exc: pass os.symlink(engine_src, engine_dest)
<commit_before>#!/usr/bin/python # FIXME Need to handle the case when symlinks already exists import os theme_dir = os.path.expanduser('~/.themes/olpc/gtk-2.0') engine_dir = os.path.expanduser('~/.gtk-2.0/engines') src_dir = os.path.abspath(os.path.dirname(__file__)) if not os.path.exists(theme_dir): try: os.makedirs(theme_dir) except OSError, exc: if exc[0] == 17: # File exists pass os.symlink(os.path.join(src_dir, 'gtk-engine/theme/gtkrc'), os.path.join(theme_dir, 'gtkrc')) engine_dest = os.path.join(engine_dir, 'libolpc.so') if not os.path.exists(engine_dest): try: os.makedirs(engine_dir) except OSError, exc: if exc[0] == 17: # File exists pass engine_src = os.path.join(src_dir, 'gtk-engine/src/.libs/libolpc.so') os.symlink(engine_src, engine_dest) <commit_msg>Deal with existing symlinks and add more error checking<commit_after>#!/usr/bin/python # FIXME Need to handle the case when symlinks already exists import os theme_dir = os.path.expanduser('~/.themes/olpc/gtk-2.0') gtkrc_dest = os.path.join(theme_dir, 'gtkrc') engine_dir = os.path.expanduser('~/.gtk-2.0/engines') engine_dest = os.path.join(engine_dir, 'libolpc.so') src_dir = os.path.abspath(os.path.dirname(__file__)) if not os.path.exists(theme_dir): try: os.makedirs(theme_dir) except OSError, exc: if exc[0] == 17: # File exists pass try: os.unlink(gtkrc_dest) except OSError, exc: pass os.symlink(os.path.join(src_dir, 'gtk-engine/theme/gtkrc'), gtkrc_dest) if not os.path.exists(engine_dest): try: os.makedirs(engine_dir) except OSError, exc: if exc[0] == 17: # File exists pass engine_src = os.path.join(src_dir, 'gtk-engine/src/.libs/libolpc.so') try: os.unlink(engine_dest) except OSError, exc: pass os.symlink(engine_src, engine_dest)
db566a81186a600543ca1c04951c174ef24388f4
slash_bot/config.py
slash_bot/config.py
# coding: utf-8 """ Created on 2016-08-23 @author: naoey """ VERSION = "0.0.3" BOT_PREFIX = ":" PATHS = { "logs_dir": "./../logs/", "database": "./../slash_bot.db", "discord_creds": "./../private/discord.json", "rito_creds": "./../private/rito.json", "assets": "./../assets/", } MODULES = { "League of Legends": { "location": "games.lol", "class": "LeagueOfLegends", "active": True, "prefix": "lol", "config": { "static_refresh_interval": { "value": "604800", "description": "The time interval in seconds before refreshing static data" } } }, "osu!": { "location": "games.osu.Osu", "class": "Osu", "active": False, "prefix": "osu", "config": {}, }, "MyAnimeList": { "location": "anime.mal.MyAnimeList", "class": "MyAnimeList", "active": False, "prefix": "mal", "config": {}, }, } API_LIMITS = { "riot": { "10": "10", "600": "500", } } GLOBAL = { } DISCORD_STATUS_ITER = [ "procrastination \(^-^)/", ]
# coding: utf-8 """ Created on 2016-08-23 @author: naoey """ VERSION = "0.0.3" BOT_PREFIX = "," PATHS = { "logs_dir": "./../logs/", "database": "./../slash_bot.db", "discord_creds": "./../private/discord.json", "rito_creds": "./../private/rito.json", "assets": "./../assets/", } MODULES = { "League of Legends": { "location": "games.lol", "class": "LeagueOfLegends", "active": True, "prefix": "lol", "config": { "static_refresh_interval": { "value": "604800", "description": "The time interval in seconds before refreshing static data" } } }, "osu!": { "location": "games.osu.Osu", "class": "Osu", "active": False, "prefix": "osu", "config": {}, }, "MyAnimeList": { "location": "anime.mal.MyAnimeList", "class": "MyAnimeList", "active": False, "prefix": "mal", "config": {}, }, } API_LIMITS = { "riot": { "10": "10", "600": "500", } } GLOBAL = { } DISCORD_STATUS_ITER = [ "procrastination \(^-^)/", ]
Fix stupid git app committing unwanted stuff~
Fix stupid git app committing unwanted stuff~
Python
mit
naoey/slash-bot,naoey/slash-bot
# coding: utf-8 """ Created on 2016-08-23 @author: naoey """ VERSION = "0.0.3" BOT_PREFIX = ":" PATHS = { "logs_dir": "./../logs/", "database": "./../slash_bot.db", "discord_creds": "./../private/discord.json", "rito_creds": "./../private/rito.json", "assets": "./../assets/", } MODULES = { "League of Legends": { "location": "games.lol", "class": "LeagueOfLegends", "active": True, "prefix": "lol", "config": { "static_refresh_interval": { "value": "604800", "description": "The time interval in seconds before refreshing static data" } } }, "osu!": { "location": "games.osu.Osu", "class": "Osu", "active": False, "prefix": "osu", "config": {}, }, "MyAnimeList": { "location": "anime.mal.MyAnimeList", "class": "MyAnimeList", "active": False, "prefix": "mal", "config": {}, }, } API_LIMITS = { "riot": { "10": "10", "600": "500", } } GLOBAL = { } DISCORD_STATUS_ITER = [ "procrastination \(^-^)/", ] Fix stupid git app committing unwanted stuff~
# coding: utf-8 """ Created on 2016-08-23 @author: naoey """ VERSION = "0.0.3" BOT_PREFIX = "," PATHS = { "logs_dir": "./../logs/", "database": "./../slash_bot.db", "discord_creds": "./../private/discord.json", "rito_creds": "./../private/rito.json", "assets": "./../assets/", } MODULES = { "League of Legends": { "location": "games.lol", "class": "LeagueOfLegends", "active": True, "prefix": "lol", "config": { "static_refresh_interval": { "value": "604800", "description": "The time interval in seconds before refreshing static data" } } }, "osu!": { "location": "games.osu.Osu", "class": "Osu", "active": False, "prefix": "osu", "config": {}, }, "MyAnimeList": { "location": "anime.mal.MyAnimeList", "class": "MyAnimeList", "active": False, "prefix": "mal", "config": {}, }, } API_LIMITS = { "riot": { "10": "10", "600": "500", } } GLOBAL = { } DISCORD_STATUS_ITER = [ "procrastination \(^-^)/", ]
<commit_before># coding: utf-8 """ Created on 2016-08-23 @author: naoey """ VERSION = "0.0.3" BOT_PREFIX = ":" PATHS = { "logs_dir": "./../logs/", "database": "./../slash_bot.db", "discord_creds": "./../private/discord.json", "rito_creds": "./../private/rito.json", "assets": "./../assets/", } MODULES = { "League of Legends": { "location": "games.lol", "class": "LeagueOfLegends", "active": True, "prefix": "lol", "config": { "static_refresh_interval": { "value": "604800", "description": "The time interval in seconds before refreshing static data" } } }, "osu!": { "location": "games.osu.Osu", "class": "Osu", "active": False, "prefix": "osu", "config": {}, }, "MyAnimeList": { "location": "anime.mal.MyAnimeList", "class": "MyAnimeList", "active": False, "prefix": "mal", "config": {}, }, } API_LIMITS = { "riot": { "10": "10", "600": "500", } } GLOBAL = { } DISCORD_STATUS_ITER = [ "procrastination \(^-^)/", ] <commit_msg>Fix stupid git app committing unwanted stuff~<commit_after>
# coding: utf-8 """ Created on 2016-08-23 @author: naoey """ VERSION = "0.0.3" BOT_PREFIX = "," PATHS = { "logs_dir": "./../logs/", "database": "./../slash_bot.db", "discord_creds": "./../private/discord.json", "rito_creds": "./../private/rito.json", "assets": "./../assets/", } MODULES = { "League of Legends": { "location": "games.lol", "class": "LeagueOfLegends", "active": True, "prefix": "lol", "config": { "static_refresh_interval": { "value": "604800", "description": "The time interval in seconds before refreshing static data" } } }, "osu!": { "location": "games.osu.Osu", "class": "Osu", "active": False, "prefix": "osu", "config": {}, }, "MyAnimeList": { "location": "anime.mal.MyAnimeList", "class": "MyAnimeList", "active": False, "prefix": "mal", "config": {}, }, } API_LIMITS = { "riot": { "10": "10", "600": "500", } } GLOBAL = { } DISCORD_STATUS_ITER = [ "procrastination \(^-^)/", ]
# coding: utf-8 """ Created on 2016-08-23 @author: naoey """ VERSION = "0.0.3" BOT_PREFIX = ":" PATHS = { "logs_dir": "./../logs/", "database": "./../slash_bot.db", "discord_creds": "./../private/discord.json", "rito_creds": "./../private/rito.json", "assets": "./../assets/", } MODULES = { "League of Legends": { "location": "games.lol", "class": "LeagueOfLegends", "active": True, "prefix": "lol", "config": { "static_refresh_interval": { "value": "604800", "description": "The time interval in seconds before refreshing static data" } } }, "osu!": { "location": "games.osu.Osu", "class": "Osu", "active": False, "prefix": "osu", "config": {}, }, "MyAnimeList": { "location": "anime.mal.MyAnimeList", "class": "MyAnimeList", "active": False, "prefix": "mal", "config": {}, }, } API_LIMITS = { "riot": { "10": "10", "600": "500", } } GLOBAL = { } DISCORD_STATUS_ITER = [ "procrastination \(^-^)/", ] Fix stupid git app committing unwanted stuff~# coding: utf-8 """ Created on 2016-08-23 @author: naoey """ VERSION = "0.0.3" BOT_PREFIX = "," PATHS = { "logs_dir": "./../logs/", "database": "./../slash_bot.db", "discord_creds": "./../private/discord.json", "rito_creds": "./../private/rito.json", "assets": "./../assets/", } MODULES = { "League of Legends": { "location": "games.lol", "class": "LeagueOfLegends", "active": True, "prefix": "lol", "config": { "static_refresh_interval": { "value": "604800", "description": "The time interval in seconds before refreshing static data" } } }, "osu!": { "location": "games.osu.Osu", "class": "Osu", "active": False, "prefix": "osu", "config": {}, }, "MyAnimeList": { "location": "anime.mal.MyAnimeList", "class": "MyAnimeList", "active": False, "prefix": "mal", "config": {}, }, } API_LIMITS = { "riot": { "10": "10", "600": "500", } } GLOBAL = { } DISCORD_STATUS_ITER = [ "procrastination \(^-^)/", ]
<commit_before># coding: utf-8 """ Created on 2016-08-23 @author: naoey """ VERSION = "0.0.3" BOT_PREFIX = ":" PATHS = { "logs_dir": "./../logs/", "database": "./../slash_bot.db", "discord_creds": "./../private/discord.json", "rito_creds": "./../private/rito.json", "assets": "./../assets/", } MODULES = { "League of Legends": { "location": "games.lol", "class": "LeagueOfLegends", "active": True, "prefix": "lol", "config": { "static_refresh_interval": { "value": "604800", "description": "The time interval in seconds before refreshing static data" } } }, "osu!": { "location": "games.osu.Osu", "class": "Osu", "active": False, "prefix": "osu", "config": {}, }, "MyAnimeList": { "location": "anime.mal.MyAnimeList", "class": "MyAnimeList", "active": False, "prefix": "mal", "config": {}, }, } API_LIMITS = { "riot": { "10": "10", "600": "500", } } GLOBAL = { } DISCORD_STATUS_ITER = [ "procrastination \(^-^)/", ] <commit_msg>Fix stupid git app committing unwanted stuff~<commit_after># coding: utf-8 """ Created on 2016-08-23 @author: naoey """ VERSION = "0.0.3" BOT_PREFIX = "," PATHS = { "logs_dir": "./../logs/", "database": "./../slash_bot.db", "discord_creds": "./../private/discord.json", "rito_creds": "./../private/rito.json", "assets": "./../assets/", } MODULES = { "League of Legends": { "location": "games.lol", "class": "LeagueOfLegends", "active": True, "prefix": "lol", "config": { "static_refresh_interval": { "value": "604800", "description": "The time interval in seconds before refreshing static data" } } }, "osu!": { "location": "games.osu.Osu", "class": "Osu", "active": False, "prefix": "osu", "config": {}, }, "MyAnimeList": { "location": "anime.mal.MyAnimeList", "class": "MyAnimeList", "active": False, "prefix": "mal", "config": {}, }, } API_LIMITS = { "riot": { "10": "10", "600": "500", } } GLOBAL = { } DISCORD_STATUS_ITER = [ "procrastination \(^-^)/", ]
50b9194b0f6c45abc0513b1172fbbaada180c38a
astropy/io/vo/__init__.py
astropy/io/vo/__init__.py
from __future__ import division, absolute_import # If we're in the source directory, don't import anything, since that # requires 2to3 to be run. from astropy import setup_helpers if setup_helpers.is_in_build_mode(): pass else: del setup_helpers from .table import parse, parse_single_table from .exceptions import VOWarning, VOTableChangeWarning, \ VOTableSpecWarning, UnimplementedWarning, IOWarning, \ VOTableSpecError
from __future__ import division, absolute_import # If we're in the source directory, don't import anything, since that # requires 2to3 to be run. from astropy import setup_helpers if setup_helpers.is_in_build_mode(): pass else: del setup_helpers from .table import parse, parse_single_table from .exceptions import (VOWarning, VOTableChangeWarning, VOTableSpecWarning, UnimplementedWarning, IOWarning, VOTableSpecError)
Use parentheses instead of \ for multi-line import.
Use parentheses instead of \ for multi-line import.
Python
bsd-3-clause
AustereCuriosity/astropy,StuartLittlefair/astropy,MSeifert04/astropy,larrybradley/astropy,kelle/astropy,aleksandr-bakanov/astropy,lpsinger/astropy,tbabej/astropy,kelle/astropy,mhvk/astropy,kelle/astropy,mhvk/astropy,lpsinger/astropy,AustereCuriosity/astropy,bsipocz/astropy,DougBurke/astropy,larrybradley/astropy,AustereCuriosity/astropy,MSeifert04/astropy,dhomeier/astropy,DougBurke/astropy,bsipocz/astropy,lpsinger/astropy,stargaser/astropy,dhomeier/astropy,saimn/astropy,saimn/astropy,astropy/astropy,StuartLittlefair/astropy,MSeifert04/astropy,funbaker/astropy,funbaker/astropy,aleksandr-bakanov/astropy,kelle/astropy,tbabej/astropy,funbaker/astropy,saimn/astropy,astropy/astropy,StuartLittlefair/astropy,larrybradley/astropy,astropy/astropy,MSeifert04/astropy,funbaker/astropy,DougBurke/astropy,dhomeier/astropy,astropy/astropy,StuartLittlefair/astropy,joergdietrich/astropy,pllim/astropy,stargaser/astropy,joergdietrich/astropy,tbabej/astropy,larrybradley/astropy,dhomeier/astropy,DougBurke/astropy,mhvk/astropy,lpsinger/astropy,aleksandr-bakanov/astropy,astropy/astropy,tbabej/astropy,AustereCuriosity/astropy,joergdietrich/astropy,AustereCuriosity/astropy,saimn/astropy,stargaser/astropy,saimn/astropy,bsipocz/astropy,tbabej/astropy,stargaser/astropy,joergdietrich/astropy,pllim/astropy,pllim/astropy,pllim/astropy,joergdietrich/astropy,mhvk/astropy,mhvk/astropy,kelle/astropy,StuartLittlefair/astropy,larrybradley/astropy,dhomeier/astropy,aleksandr-bakanov/astropy,lpsinger/astropy,pllim/astropy,bsipocz/astropy
from __future__ import division, absolute_import # If we're in the source directory, don't import anything, since that # requires 2to3 to be run. from astropy import setup_helpers if setup_helpers.is_in_build_mode(): pass else: del setup_helpers from .table import parse, parse_single_table from .exceptions import VOWarning, VOTableChangeWarning, \ VOTableSpecWarning, UnimplementedWarning, IOWarning, \ VOTableSpecError Use parentheses instead of \ for multi-line import.
from __future__ import division, absolute_import # If we're in the source directory, don't import anything, since that # requires 2to3 to be run. from astropy import setup_helpers if setup_helpers.is_in_build_mode(): pass else: del setup_helpers from .table import parse, parse_single_table from .exceptions import (VOWarning, VOTableChangeWarning, VOTableSpecWarning, UnimplementedWarning, IOWarning, VOTableSpecError)
<commit_before>from __future__ import division, absolute_import # If we're in the source directory, don't import anything, since that # requires 2to3 to be run. from astropy import setup_helpers if setup_helpers.is_in_build_mode(): pass else: del setup_helpers from .table import parse, parse_single_table from .exceptions import VOWarning, VOTableChangeWarning, \ VOTableSpecWarning, UnimplementedWarning, IOWarning, \ VOTableSpecError <commit_msg>Use parentheses instead of \ for multi-line import.<commit_after>
from __future__ import division, absolute_import # If we're in the source directory, don't import anything, since that # requires 2to3 to be run. from astropy import setup_helpers if setup_helpers.is_in_build_mode(): pass else: del setup_helpers from .table import parse, parse_single_table from .exceptions import (VOWarning, VOTableChangeWarning, VOTableSpecWarning, UnimplementedWarning, IOWarning, VOTableSpecError)
from __future__ import division, absolute_import # If we're in the source directory, don't import anything, since that # requires 2to3 to be run. from astropy import setup_helpers if setup_helpers.is_in_build_mode(): pass else: del setup_helpers from .table import parse, parse_single_table from .exceptions import VOWarning, VOTableChangeWarning, \ VOTableSpecWarning, UnimplementedWarning, IOWarning, \ VOTableSpecError Use parentheses instead of \ for multi-line import.from __future__ import division, absolute_import # If we're in the source directory, don't import anything, since that # requires 2to3 to be run. from astropy import setup_helpers if setup_helpers.is_in_build_mode(): pass else: del setup_helpers from .table import parse, parse_single_table from .exceptions import (VOWarning, VOTableChangeWarning, VOTableSpecWarning, UnimplementedWarning, IOWarning, VOTableSpecError)
<commit_before>from __future__ import division, absolute_import # If we're in the source directory, don't import anything, since that # requires 2to3 to be run. from astropy import setup_helpers if setup_helpers.is_in_build_mode(): pass else: del setup_helpers from .table import parse, parse_single_table from .exceptions import VOWarning, VOTableChangeWarning, \ VOTableSpecWarning, UnimplementedWarning, IOWarning, \ VOTableSpecError <commit_msg>Use parentheses instead of \ for multi-line import.<commit_after>from __future__ import division, absolute_import # If we're in the source directory, don't import anything, since that # requires 2to3 to be run. from astropy import setup_helpers if setup_helpers.is_in_build_mode(): pass else: del setup_helpers from .table import parse, parse_single_table from .exceptions import (VOWarning, VOTableChangeWarning, VOTableSpecWarning, UnimplementedWarning, IOWarning, VOTableSpecError)
32820375c4552a9648612ea0dddfbf524e672c0e
virtool/indexes/models.py
virtool/indexes/models.py
import enum from sqlalchemy import Column, Integer, String, Enum from virtool.pg.utils import Base, SQLEnum class IndexType(str, SQLEnum): """ Enumerated type for index file types """ json = "json" fasta = "fasta" bowtie2 = "bowtie2" class IndexFile(Base): """ SQL model to store new index files """ __tablename__ = "index_files" id = Column(Integer, primary_key=True) name = Column(String) reference = Column(String) type = Column(Enum(IndexType)) size = Column(Integer) def __repr__(self): return f"<IndexFile(id={self.id}, name={self.name}, reference={self.reference}, type={self.type}, " \ f"size={self.size} "
import enum from sqlalchemy import Column, Integer, String, Enum from virtool.pg.utils import Base, SQLEnum class IndexType(str, SQLEnum): """ Enumerated type for index file types """ json = "json" fasta = "fasta" bowtie2 = "bowtie2" class IndexFile(Base): """ SQL model to store new index files """ __tablename__ = "index_files" id = Column(Integer, primary_key=True) name = Column(String) index = Column(String) type = Column(Enum(IndexType)) size = Column(Integer) def __repr__(self): return f"<IndexFile(id={self.id}, name={self.name}, index={self.index}, type={self.type}, " \ f"size={self.size} "
Update IndexFile model to have 'index' column instead of 'reference'
Update IndexFile model to have 'index' column instead of 'reference'
Python
mit
virtool/virtool,igboyes/virtool,igboyes/virtool,virtool/virtool
import enum from sqlalchemy import Column, Integer, String, Enum from virtool.pg.utils import Base, SQLEnum class IndexType(str, SQLEnum): """ Enumerated type for index file types """ json = "json" fasta = "fasta" bowtie2 = "bowtie2" class IndexFile(Base): """ SQL model to store new index files """ __tablename__ = "index_files" id = Column(Integer, primary_key=True) name = Column(String) reference = Column(String) type = Column(Enum(IndexType)) size = Column(Integer) def __repr__(self): return f"<IndexFile(id={self.id}, name={self.name}, reference={self.reference}, type={self.type}, " \ f"size={self.size} " Update IndexFile model to have 'index' column instead of 'reference'
import enum from sqlalchemy import Column, Integer, String, Enum from virtool.pg.utils import Base, SQLEnum class IndexType(str, SQLEnum): """ Enumerated type for index file types """ json = "json" fasta = "fasta" bowtie2 = "bowtie2" class IndexFile(Base): """ SQL model to store new index files """ __tablename__ = "index_files" id = Column(Integer, primary_key=True) name = Column(String) index = Column(String) type = Column(Enum(IndexType)) size = Column(Integer) def __repr__(self): return f"<IndexFile(id={self.id}, name={self.name}, index={self.index}, type={self.type}, " \ f"size={self.size} "
<commit_before>import enum from sqlalchemy import Column, Integer, String, Enum from virtool.pg.utils import Base, SQLEnum class IndexType(str, SQLEnum): """ Enumerated type for index file types """ json = "json" fasta = "fasta" bowtie2 = "bowtie2" class IndexFile(Base): """ SQL model to store new index files """ __tablename__ = "index_files" id = Column(Integer, primary_key=True) name = Column(String) reference = Column(String) type = Column(Enum(IndexType)) size = Column(Integer) def __repr__(self): return f"<IndexFile(id={self.id}, name={self.name}, reference={self.reference}, type={self.type}, " \ f"size={self.size} " <commit_msg>Update IndexFile model to have 'index' column instead of 'reference'<commit_after>
import enum from sqlalchemy import Column, Integer, String, Enum from virtool.pg.utils import Base, SQLEnum class IndexType(str, SQLEnum): """ Enumerated type for index file types """ json = "json" fasta = "fasta" bowtie2 = "bowtie2" class IndexFile(Base): """ SQL model to store new index files """ __tablename__ = "index_files" id = Column(Integer, primary_key=True) name = Column(String) index = Column(String) type = Column(Enum(IndexType)) size = Column(Integer) def __repr__(self): return f"<IndexFile(id={self.id}, name={self.name}, index={self.index}, type={self.type}, " \ f"size={self.size} "
import enum from sqlalchemy import Column, Integer, String, Enum from virtool.pg.utils import Base, SQLEnum class IndexType(str, SQLEnum): """ Enumerated type for index file types """ json = "json" fasta = "fasta" bowtie2 = "bowtie2" class IndexFile(Base): """ SQL model to store new index files """ __tablename__ = "index_files" id = Column(Integer, primary_key=True) name = Column(String) reference = Column(String) type = Column(Enum(IndexType)) size = Column(Integer) def __repr__(self): return f"<IndexFile(id={self.id}, name={self.name}, reference={self.reference}, type={self.type}, " \ f"size={self.size} " Update IndexFile model to have 'index' column instead of 'reference'import enum from sqlalchemy import Column, Integer, String, Enum from virtool.pg.utils import Base, SQLEnum class IndexType(str, SQLEnum): """ Enumerated type for index file types """ json = "json" fasta = "fasta" bowtie2 = "bowtie2" class IndexFile(Base): """ SQL model to store new index files """ __tablename__ = "index_files" id = Column(Integer, primary_key=True) name = Column(String) index = Column(String) type = Column(Enum(IndexType)) size = Column(Integer) def __repr__(self): return f"<IndexFile(id={self.id}, name={self.name}, index={self.index}, type={self.type}, " \ f"size={self.size} "
<commit_before>import enum from sqlalchemy import Column, Integer, String, Enum from virtool.pg.utils import Base, SQLEnum class IndexType(str, SQLEnum): """ Enumerated type for index file types """ json = "json" fasta = "fasta" bowtie2 = "bowtie2" class IndexFile(Base): """ SQL model to store new index files """ __tablename__ = "index_files" id = Column(Integer, primary_key=True) name = Column(String) reference = Column(String) type = Column(Enum(IndexType)) size = Column(Integer) def __repr__(self): return f"<IndexFile(id={self.id}, name={self.name}, reference={self.reference}, type={self.type}, " \ f"size={self.size} " <commit_msg>Update IndexFile model to have 'index' column instead of 'reference'<commit_after>import enum from sqlalchemy import Column, Integer, String, Enum from virtool.pg.utils import Base, SQLEnum class IndexType(str, SQLEnum): """ Enumerated type for index file types """ json = "json" fasta = "fasta" bowtie2 = "bowtie2" class IndexFile(Base): """ SQL model to store new index files """ __tablename__ = "index_files" id = Column(Integer, primary_key=True) name = Column(String) index = Column(String) type = Column(Enum(IndexType)) size = Column(Integer) def __repr__(self): return f"<IndexFile(id={self.id}, name={self.name}, index={self.index}, type={self.type}, " \ f"size={self.size} "
a68f7ea6a9335a54762bfecf7b8f0a186bab8ed8
detectron2/projects/__init__.py
detectron2/projects/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. import importlib from pathlib import Path _PROJECTS = { "point_rend": "PointRend", "deeplab": "DeepLab", "panoptic_deeplab": "Panoptic-DeepLab", } _PROJECT_ROOT = Path(__file__).parent.parent.parent / "projects" if _PROJECT_ROOT.is_dir(): # This is true only for in-place installation (pip install -e, setup.py develop), # where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230 class _D2ProjectsFinder(importlib.abc.MetaPathFinder): def find_spec(self, name, path, target=None): if not name.startswith("detectron2.projects."): return project_name = name.split(".")[-1] project_dir = _PROJECTS.get(project_name) if not project_dir: return target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py" if not target_file.is_file(): return return importlib.util.spec_from_file_location(name, target_file) import sys sys.meta_path.append(_D2ProjectsFinder())
# Copyright (c) Facebook, Inc. and its affiliates. import importlib from pathlib import Path _PROJECTS = { "point_rend": "PointRend", "deeplab": "DeepLab", "panoptic_deeplab": "Panoptic-DeepLab", } _PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent / "projects" if _PROJECT_ROOT.is_dir(): # This is true only for in-place installation (pip install -e, setup.py develop), # where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230 class _D2ProjectsFinder(importlib.abc.MetaPathFinder): def find_spec(self, name, path, target=None): if not name.startswith("detectron2.projects."): return project_name = name.split(".")[-1] project_dir = _PROJECTS.get(project_name) if not project_dir: return target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py" if not target_file.is_file(): return return importlib.util.spec_from_file_location(name, target_file) import sys sys.meta_path.append(_D2ProjectsFinder())
Resolve path in case it involves a symlink
Resolve path in case it involves a symlink Reviewed By: ppwwyyxx Differential Revision: D27823003 fbshipit-source-id: 67e6905f3c5c7bb1f593ee004160b195925f6d39
Python
apache-2.0
facebookresearch/detectron2,facebookresearch/detectron2,facebookresearch/detectron2
# Copyright (c) Facebook, Inc. and its affiliates. import importlib from pathlib import Path _PROJECTS = { "point_rend": "PointRend", "deeplab": "DeepLab", "panoptic_deeplab": "Panoptic-DeepLab", } _PROJECT_ROOT = Path(__file__).parent.parent.parent / "projects" if _PROJECT_ROOT.is_dir(): # This is true only for in-place installation (pip install -e, setup.py develop), # where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230 class _D2ProjectsFinder(importlib.abc.MetaPathFinder): def find_spec(self, name, path, target=None): if not name.startswith("detectron2.projects."): return project_name = name.split(".")[-1] project_dir = _PROJECTS.get(project_name) if not project_dir: return target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py" if not target_file.is_file(): return return importlib.util.spec_from_file_location(name, target_file) import sys sys.meta_path.append(_D2ProjectsFinder()) Resolve path in case it involves a symlink Reviewed By: ppwwyyxx Differential Revision: D27823003 fbshipit-source-id: 67e6905f3c5c7bb1f593ee004160b195925f6d39
# Copyright (c) Facebook, Inc. and its affiliates. import importlib from pathlib import Path _PROJECTS = { "point_rend": "PointRend", "deeplab": "DeepLab", "panoptic_deeplab": "Panoptic-DeepLab", } _PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent / "projects" if _PROJECT_ROOT.is_dir(): # This is true only for in-place installation (pip install -e, setup.py develop), # where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230 class _D2ProjectsFinder(importlib.abc.MetaPathFinder): def find_spec(self, name, path, target=None): if not name.startswith("detectron2.projects."): return project_name = name.split(".")[-1] project_dir = _PROJECTS.get(project_name) if not project_dir: return target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py" if not target_file.is_file(): return return importlib.util.spec_from_file_location(name, target_file) import sys sys.meta_path.append(_D2ProjectsFinder())
<commit_before># Copyright (c) Facebook, Inc. and its affiliates. import importlib from pathlib import Path _PROJECTS = { "point_rend": "PointRend", "deeplab": "DeepLab", "panoptic_deeplab": "Panoptic-DeepLab", } _PROJECT_ROOT = Path(__file__).parent.parent.parent / "projects" if _PROJECT_ROOT.is_dir(): # This is true only for in-place installation (pip install -e, setup.py develop), # where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230 class _D2ProjectsFinder(importlib.abc.MetaPathFinder): def find_spec(self, name, path, target=None): if not name.startswith("detectron2.projects."): return project_name = name.split(".")[-1] project_dir = _PROJECTS.get(project_name) if not project_dir: return target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py" if not target_file.is_file(): return return importlib.util.spec_from_file_location(name, target_file) import sys sys.meta_path.append(_D2ProjectsFinder()) <commit_msg>Resolve path in case it involves a symlink Reviewed By: ppwwyyxx Differential Revision: D27823003 fbshipit-source-id: 67e6905f3c5c7bb1f593ee004160b195925f6d39<commit_after>
# Copyright (c) Facebook, Inc. and its affiliates. import importlib from pathlib import Path _PROJECTS = { "point_rend": "PointRend", "deeplab": "DeepLab", "panoptic_deeplab": "Panoptic-DeepLab", } _PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent / "projects" if _PROJECT_ROOT.is_dir(): # This is true only for in-place installation (pip install -e, setup.py develop), # where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230 class _D2ProjectsFinder(importlib.abc.MetaPathFinder): def find_spec(self, name, path, target=None): if not name.startswith("detectron2.projects."): return project_name = name.split(".")[-1] project_dir = _PROJECTS.get(project_name) if not project_dir: return target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py" if not target_file.is_file(): return return importlib.util.spec_from_file_location(name, target_file) import sys sys.meta_path.append(_D2ProjectsFinder())
# Copyright (c) Facebook, Inc. and its affiliates. import importlib from pathlib import Path _PROJECTS = { "point_rend": "PointRend", "deeplab": "DeepLab", "panoptic_deeplab": "Panoptic-DeepLab", } _PROJECT_ROOT = Path(__file__).parent.parent.parent / "projects" if _PROJECT_ROOT.is_dir(): # This is true only for in-place installation (pip install -e, setup.py develop), # where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230 class _D2ProjectsFinder(importlib.abc.MetaPathFinder): def find_spec(self, name, path, target=None): if not name.startswith("detectron2.projects."): return project_name = name.split(".")[-1] project_dir = _PROJECTS.get(project_name) if not project_dir: return target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py" if not target_file.is_file(): return return importlib.util.spec_from_file_location(name, target_file) import sys sys.meta_path.append(_D2ProjectsFinder()) Resolve path in case it involves a symlink Reviewed By: ppwwyyxx Differential Revision: D27823003 fbshipit-source-id: 67e6905f3c5c7bb1f593ee004160b195925f6d39# Copyright (c) Facebook, Inc. and its affiliates. import importlib from pathlib import Path _PROJECTS = { "point_rend": "PointRend", "deeplab": "DeepLab", "panoptic_deeplab": "Panoptic-DeepLab", } _PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent / "projects" if _PROJECT_ROOT.is_dir(): # This is true only for in-place installation (pip install -e, setup.py develop), # where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230 class _D2ProjectsFinder(importlib.abc.MetaPathFinder): def find_spec(self, name, path, target=None): if not name.startswith("detectron2.projects."): return project_name = name.split(".")[-1] project_dir = _PROJECTS.get(project_name) if not project_dir: return target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py" if not target_file.is_file(): return return importlib.util.spec_from_file_location(name, target_file) import sys sys.meta_path.append(_D2ProjectsFinder())
<commit_before># Copyright (c) Facebook, Inc. and its affiliates. import importlib from pathlib import Path _PROJECTS = { "point_rend": "PointRend", "deeplab": "DeepLab", "panoptic_deeplab": "Panoptic-DeepLab", } _PROJECT_ROOT = Path(__file__).parent.parent.parent / "projects" if _PROJECT_ROOT.is_dir(): # This is true only for in-place installation (pip install -e, setup.py develop), # where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230 class _D2ProjectsFinder(importlib.abc.MetaPathFinder): def find_spec(self, name, path, target=None): if not name.startswith("detectron2.projects."): return project_name = name.split(".")[-1] project_dir = _PROJECTS.get(project_name) if not project_dir: return target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py" if not target_file.is_file(): return return importlib.util.spec_from_file_location(name, target_file) import sys sys.meta_path.append(_D2ProjectsFinder()) <commit_msg>Resolve path in case it involves a symlink Reviewed By: ppwwyyxx Differential Revision: D27823003 fbshipit-source-id: 67e6905f3c5c7bb1f593ee004160b195925f6d39<commit_after># Copyright (c) Facebook, Inc. and its affiliates. import importlib from pathlib import Path _PROJECTS = { "point_rend": "PointRend", "deeplab": "DeepLab", "panoptic_deeplab": "Panoptic-DeepLab", } _PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent / "projects" if _PROJECT_ROOT.is_dir(): # This is true only for in-place installation (pip install -e, setup.py develop), # where setup(package_dir=) does not work: https://github.com/pypa/setuptools/issues/230 class _D2ProjectsFinder(importlib.abc.MetaPathFinder): def find_spec(self, name, path, target=None): if not name.startswith("detectron2.projects."): return project_name = name.split(".")[-1] project_dir = _PROJECTS.get(project_name) if not project_dir: return target_file = _PROJECT_ROOT / f"{project_dir}/{project_name}/__init__.py" if not target_file.is_file(): return return importlib.util.spec_from_file_location(name, target_file) import sys sys.meta_path.append(_D2ProjectsFinder())
5fabf1513ff22b404e43de54c14b8f92e5f674e7
senlin/tests/tempest/api/profiles/test_profile_delete.py
senlin/tests/tempest/api/profiles/test_profile_delete.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.lib import decorators from senlin.tests.tempest.api import base from senlin.tests.tempest.common import constants class TestProfileDelete(base.BaseSenlinTest): @classmethod def resource_setup(cls): super(TestProfileDelete, cls).resource_setup() # Create profile cls.profile = cls.create_profile(constants.spec_nova_server) @decorators.idempotent_id('ea3c1b9e-5ed7-4d63-84ce-2032c3bc6d27') def test_delete_policy(self): # Verify resp of policy delete API res = self.client.delete_obj('profiles', self.profile['id']) self.assertEqual(204, res['status']) self.assertIsNone(res['body'])
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.lib import decorators from senlin.tests.tempest.api import base from senlin.tests.tempest.common import constants class TestProfileDelete(base.BaseSenlinTest): @classmethod def resource_setup(cls): super(TestProfileDelete, cls).resource_setup() # Create profile cls.profile = cls.create_profile(constants.spec_nova_server) @decorators.idempotent_id('ea3c1b9e-5ed7-4d63-84ce-2032c3bc6d27') def test_delete_profile(self): # Verify resp of profile delete API res = self.client.delete_obj('profiles', self.profile['id']) self.assertEqual(204, res['status']) self.assertIsNone(res['body'])
Fix typos in tempest API tests for profile_delete
Fix typos in tempest API tests for profile_delete This patch fixes typos in tempest API tests for profile_delete. Change-Id: Ic6aa696f59621a5340d6cf67be76e830bbd30e67
Python
apache-2.0
stackforge/senlin,openstack/senlin,openstack/senlin,stackforge/senlin,openstack/senlin
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.lib import decorators from senlin.tests.tempest.api import base from senlin.tests.tempest.common import constants class TestProfileDelete(base.BaseSenlinTest): @classmethod def resource_setup(cls): super(TestProfileDelete, cls).resource_setup() # Create profile cls.profile = cls.create_profile(constants.spec_nova_server) @decorators.idempotent_id('ea3c1b9e-5ed7-4d63-84ce-2032c3bc6d27') def test_delete_policy(self): # Verify resp of policy delete API res = self.client.delete_obj('profiles', self.profile['id']) self.assertEqual(204, res['status']) self.assertIsNone(res['body']) Fix typos in tempest API tests for profile_delete This patch fixes typos in tempest API tests for profile_delete. Change-Id: Ic6aa696f59621a5340d6cf67be76e830bbd30e67
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.lib import decorators from senlin.tests.tempest.api import base from senlin.tests.tempest.common import constants class TestProfileDelete(base.BaseSenlinTest): @classmethod def resource_setup(cls): super(TestProfileDelete, cls).resource_setup() # Create profile cls.profile = cls.create_profile(constants.spec_nova_server) @decorators.idempotent_id('ea3c1b9e-5ed7-4d63-84ce-2032c3bc6d27') def test_delete_profile(self): # Verify resp of profile delete API res = self.client.delete_obj('profiles', self.profile['id']) self.assertEqual(204, res['status']) self.assertIsNone(res['body'])
<commit_before># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.lib import decorators from senlin.tests.tempest.api import base from senlin.tests.tempest.common import constants class TestProfileDelete(base.BaseSenlinTest): @classmethod def resource_setup(cls): super(TestProfileDelete, cls).resource_setup() # Create profile cls.profile = cls.create_profile(constants.spec_nova_server) @decorators.idempotent_id('ea3c1b9e-5ed7-4d63-84ce-2032c3bc6d27') def test_delete_policy(self): # Verify resp of policy delete API res = self.client.delete_obj('profiles', self.profile['id']) self.assertEqual(204, res['status']) self.assertIsNone(res['body']) <commit_msg>Fix typos in tempest API tests for profile_delete This patch fixes typos in tempest API tests for profile_delete. Change-Id: Ic6aa696f59621a5340d6cf67be76e830bbd30e67<commit_after>
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.lib import decorators from senlin.tests.tempest.api import base from senlin.tests.tempest.common import constants class TestProfileDelete(base.BaseSenlinTest): @classmethod def resource_setup(cls): super(TestProfileDelete, cls).resource_setup() # Create profile cls.profile = cls.create_profile(constants.spec_nova_server) @decorators.idempotent_id('ea3c1b9e-5ed7-4d63-84ce-2032c3bc6d27') def test_delete_profile(self): # Verify resp of profile delete API res = self.client.delete_obj('profiles', self.profile['id']) self.assertEqual(204, res['status']) self.assertIsNone(res['body'])
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.lib import decorators from senlin.tests.tempest.api import base from senlin.tests.tempest.common import constants class TestProfileDelete(base.BaseSenlinTest): @classmethod def resource_setup(cls): super(TestProfileDelete, cls).resource_setup() # Create profile cls.profile = cls.create_profile(constants.spec_nova_server) @decorators.idempotent_id('ea3c1b9e-5ed7-4d63-84ce-2032c3bc6d27') def test_delete_policy(self): # Verify resp of policy delete API res = self.client.delete_obj('profiles', self.profile['id']) self.assertEqual(204, res['status']) self.assertIsNone(res['body']) Fix typos in tempest API tests for profile_delete This patch fixes typos in tempest API tests for profile_delete. Change-Id: Ic6aa696f59621a5340d6cf67be76e830bbd30e67# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.lib import decorators from senlin.tests.tempest.api import base from senlin.tests.tempest.common import constants class TestProfileDelete(base.BaseSenlinTest): @classmethod def resource_setup(cls): super(TestProfileDelete, cls).resource_setup() # Create profile cls.profile = cls.create_profile(constants.spec_nova_server) @decorators.idempotent_id('ea3c1b9e-5ed7-4d63-84ce-2032c3bc6d27') def test_delete_profile(self): # Verify resp of profile delete API res = self.client.delete_obj('profiles', self.profile['id']) self.assertEqual(204, res['status']) self.assertIsNone(res['body'])
<commit_before># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.lib import decorators from senlin.tests.tempest.api import base from senlin.tests.tempest.common import constants class TestProfileDelete(base.BaseSenlinTest): @classmethod def resource_setup(cls): super(TestProfileDelete, cls).resource_setup() # Create profile cls.profile = cls.create_profile(constants.spec_nova_server) @decorators.idempotent_id('ea3c1b9e-5ed7-4d63-84ce-2032c3bc6d27') def test_delete_policy(self): # Verify resp of policy delete API res = self.client.delete_obj('profiles', self.profile['id']) self.assertEqual(204, res['status']) self.assertIsNone(res['body']) <commit_msg>Fix typos in tempest API tests for profile_delete This patch fixes typos in tempest API tests for profile_delete. Change-Id: Ic6aa696f59621a5340d6cf67be76e830bbd30e67<commit_after># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.lib import decorators from senlin.tests.tempest.api import base from senlin.tests.tempest.common import constants class TestProfileDelete(base.BaseSenlinTest): @classmethod def resource_setup(cls): super(TestProfileDelete, cls).resource_setup() # Create profile cls.profile = cls.create_profile(constants.spec_nova_server) @decorators.idempotent_id('ea3c1b9e-5ed7-4d63-84ce-2032c3bc6d27') def test_delete_profile(self): # Verify resp of profile delete API res = self.client.delete_obj('profiles', self.profile['id']) self.assertEqual(204, res['status']) self.assertIsNone(res['body'])
9d0c9c385e0a1a1f66fa1e0481048bd590e91b8e
airflow/contrib/example_dags/__init__.py
airflow/contrib/example_dags/__init__.py
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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.
Add license to Contrib Example DAG Init file
[AIRFLOW-XXX] Add license to Contrib Example DAG Init file
Python
apache-2.0
owlabs/incubator-airflow,owlabs/incubator-airflow,owlabs/incubator-airflow,owlabs/incubator-airflow
[AIRFLOW-XXX] Add license to Contrib Example DAG Init file
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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.
<commit_before><commit_msg>[AIRFLOW-XXX] Add license to Contrib Example DAG Init file<commit_after>
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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.
[AIRFLOW-XXX] Add license to Contrib Example DAG Init file# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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.
<commit_before><commit_msg>[AIRFLOW-XXX] Add license to Contrib Example DAG Init file<commit_after># -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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.
f1eb55a147c4cc160decbfbcde190b7e8a2d3be6
clot/torrent/backbone.py
clot/torrent/backbone.py
"""This module implements the torrent's underlying storage.""" from .. import bencode class Backbone: # pylint: disable=too-few-public-methods """Torrent file low-level contents.""" def __init__(self, raw_bytes, file_path=None): """Initialize self.""" self.raw_bytes = raw_bytes self.data = bencode.decode(raw_bytes, keytostr=True) if not isinstance(self.data, dict): raise ValueError(f'expected top-level dictionary instead of {type(self.data)}') self.file_path = file_path def save_as(self, file_path, *, overwrite=False): """Write the torrent to a file and remember the new path and contents on success.""" raw_bytes = bencode.encode(self.data) with open(file_path, 'wb' if overwrite else 'xb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes self.file_path = file_path def save(self): """Write the torrent to the file from which it was previously loaded or saved to.""" if self.file_path is None: raise Exception('expected a torrent loaded from file') raw_bytes = bencode.encode(self.data) with open(self.file_path, 'wb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes
"""This module implements the torrent's underlying storage.""" from .. import bencode class Backbone: """Torrent file low-level contents.""" def __init__(self, raw_bytes, file_path=None): """Initialize self.""" self.raw_bytes = raw_bytes self.data = bencode.decode(raw_bytes, keytostr=True) if not isinstance(self.data, dict): raise ValueError(f'expected top-level dictionary instead of {type(self.data)}') self.file_path = file_path def save_as(self, file_path, *, overwrite=False): """Write the torrent to a file and remember the new path and contents on success.""" raw_bytes = bencode.encode(self.data) with open(file_path, 'wb' if overwrite else 'xb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes self.file_path = file_path def save(self): """Write the torrent to the file from which it was previously loaded or saved to.""" if self.file_path is None: raise Exception('expected a torrent loaded from file') raw_bytes = bencode.encode(self.data) with open(self.file_path, 'wb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes
Remove no longer needed pylint pragma
Remove no longer needed pylint pragma
Python
mit
elliptical/bencode
"""This module implements the torrent's underlying storage.""" from .. import bencode class Backbone: # pylint: disable=too-few-public-methods """Torrent file low-level contents.""" def __init__(self, raw_bytes, file_path=None): """Initialize self.""" self.raw_bytes = raw_bytes self.data = bencode.decode(raw_bytes, keytostr=True) if not isinstance(self.data, dict): raise ValueError(f'expected top-level dictionary instead of {type(self.data)}') self.file_path = file_path def save_as(self, file_path, *, overwrite=False): """Write the torrent to a file and remember the new path and contents on success.""" raw_bytes = bencode.encode(self.data) with open(file_path, 'wb' if overwrite else 'xb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes self.file_path = file_path def save(self): """Write the torrent to the file from which it was previously loaded or saved to.""" if self.file_path is None: raise Exception('expected a torrent loaded from file') raw_bytes = bencode.encode(self.data) with open(self.file_path, 'wb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes Remove no longer needed pylint pragma
"""This module implements the torrent's underlying storage.""" from .. import bencode class Backbone: """Torrent file low-level contents.""" def __init__(self, raw_bytes, file_path=None): """Initialize self.""" self.raw_bytes = raw_bytes self.data = bencode.decode(raw_bytes, keytostr=True) if not isinstance(self.data, dict): raise ValueError(f'expected top-level dictionary instead of {type(self.data)}') self.file_path = file_path def save_as(self, file_path, *, overwrite=False): """Write the torrent to a file and remember the new path and contents on success.""" raw_bytes = bencode.encode(self.data) with open(file_path, 'wb' if overwrite else 'xb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes self.file_path = file_path def save(self): """Write the torrent to the file from which it was previously loaded or saved to.""" if self.file_path is None: raise Exception('expected a torrent loaded from file') raw_bytes = bencode.encode(self.data) with open(self.file_path, 'wb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes
<commit_before>"""This module implements the torrent's underlying storage.""" from .. import bencode class Backbone: # pylint: disable=too-few-public-methods """Torrent file low-level contents.""" def __init__(self, raw_bytes, file_path=None): """Initialize self.""" self.raw_bytes = raw_bytes self.data = bencode.decode(raw_bytes, keytostr=True) if not isinstance(self.data, dict): raise ValueError(f'expected top-level dictionary instead of {type(self.data)}') self.file_path = file_path def save_as(self, file_path, *, overwrite=False): """Write the torrent to a file and remember the new path and contents on success.""" raw_bytes = bencode.encode(self.data) with open(file_path, 'wb' if overwrite else 'xb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes self.file_path = file_path def save(self): """Write the torrent to the file from which it was previously loaded or saved to.""" if self.file_path is None: raise Exception('expected a torrent loaded from file') raw_bytes = bencode.encode(self.data) with open(self.file_path, 'wb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes <commit_msg>Remove no longer needed pylint pragma<commit_after>
"""This module implements the torrent's underlying storage.""" from .. import bencode class Backbone: """Torrent file low-level contents.""" def __init__(self, raw_bytes, file_path=None): """Initialize self.""" self.raw_bytes = raw_bytes self.data = bencode.decode(raw_bytes, keytostr=True) if not isinstance(self.data, dict): raise ValueError(f'expected top-level dictionary instead of {type(self.data)}') self.file_path = file_path def save_as(self, file_path, *, overwrite=False): """Write the torrent to a file and remember the new path and contents on success.""" raw_bytes = bencode.encode(self.data) with open(file_path, 'wb' if overwrite else 'xb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes self.file_path = file_path def save(self): """Write the torrent to the file from which it was previously loaded or saved to.""" if self.file_path is None: raise Exception('expected a torrent loaded from file') raw_bytes = bencode.encode(self.data) with open(self.file_path, 'wb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes
"""This module implements the torrent's underlying storage.""" from .. import bencode class Backbone: # pylint: disable=too-few-public-methods """Torrent file low-level contents.""" def __init__(self, raw_bytes, file_path=None): """Initialize self.""" self.raw_bytes = raw_bytes self.data = bencode.decode(raw_bytes, keytostr=True) if not isinstance(self.data, dict): raise ValueError(f'expected top-level dictionary instead of {type(self.data)}') self.file_path = file_path def save_as(self, file_path, *, overwrite=False): """Write the torrent to a file and remember the new path and contents on success.""" raw_bytes = bencode.encode(self.data) with open(file_path, 'wb' if overwrite else 'xb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes self.file_path = file_path def save(self): """Write the torrent to the file from which it was previously loaded or saved to.""" if self.file_path is None: raise Exception('expected a torrent loaded from file') raw_bytes = bencode.encode(self.data) with open(self.file_path, 'wb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes Remove no longer needed pylint pragma"""This module implements the torrent's underlying storage.""" from .. import bencode class Backbone: """Torrent file low-level contents.""" def __init__(self, raw_bytes, file_path=None): """Initialize self.""" self.raw_bytes = raw_bytes self.data = bencode.decode(raw_bytes, keytostr=True) if not isinstance(self.data, dict): raise ValueError(f'expected top-level dictionary instead of {type(self.data)}') self.file_path = file_path def save_as(self, file_path, *, overwrite=False): """Write the torrent to a file and remember the new path and contents on success.""" raw_bytes = bencode.encode(self.data) with open(file_path, 'wb' if overwrite else 'xb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes self.file_path = file_path def save(self): """Write the torrent to the file from which it was previously loaded or saved to.""" if self.file_path is None: raise Exception('expected a torrent loaded from file') raw_bytes = bencode.encode(self.data) with open(self.file_path, 'wb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes
<commit_before>"""This module implements the torrent's underlying storage.""" from .. import bencode class Backbone: # pylint: disable=too-few-public-methods """Torrent file low-level contents.""" def __init__(self, raw_bytes, file_path=None): """Initialize self.""" self.raw_bytes = raw_bytes self.data = bencode.decode(raw_bytes, keytostr=True) if not isinstance(self.data, dict): raise ValueError(f'expected top-level dictionary instead of {type(self.data)}') self.file_path = file_path def save_as(self, file_path, *, overwrite=False): """Write the torrent to a file and remember the new path and contents on success.""" raw_bytes = bencode.encode(self.data) with open(file_path, 'wb' if overwrite else 'xb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes self.file_path = file_path def save(self): """Write the torrent to the file from which it was previously loaded or saved to.""" if self.file_path is None: raise Exception('expected a torrent loaded from file') raw_bytes = bencode.encode(self.data) with open(self.file_path, 'wb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes <commit_msg>Remove no longer needed pylint pragma<commit_after>"""This module implements the torrent's underlying storage.""" from .. import bencode class Backbone: """Torrent file low-level contents.""" def __init__(self, raw_bytes, file_path=None): """Initialize self.""" self.raw_bytes = raw_bytes self.data = bencode.decode(raw_bytes, keytostr=True) if not isinstance(self.data, dict): raise ValueError(f'expected top-level dictionary instead of {type(self.data)}') self.file_path = file_path def save_as(self, file_path, *, overwrite=False): """Write the torrent to a file and remember the new path and contents on success.""" raw_bytes = bencode.encode(self.data) with open(file_path, 'wb' if overwrite else 'xb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes self.file_path = file_path def save(self): """Write the torrent to the file from which it was previously loaded or saved to.""" if self.file_path is None: raise Exception('expected a torrent loaded from file') raw_bytes = bencode.encode(self.data) with open(self.file_path, 'wb') as file: file.write(raw_bytes) self.raw_bytes = raw_bytes
d5c59c018ba7558a9d21370d7eb58ab590779cf1
plugins/autojoin/plugin_tests/autojoin_test.py
plugins/autojoin/plugin_tests/autojoin_test.py
from tests import base def setUpModule(): base.enabledPlugins.append('autojoin') base.startServer() def tearDownModule(): base.stopServer() class AutoJoinTest(base.TestCase): def setUp(self): base.TestCase.setUp(self)
from girder.constants import AccessType from tests import base import json def setUpModule(): base.enabledPlugins.append('autojoin') base.startServer() def tearDownModule(): base.stopServer() class AutoJoinTest(base.TestCase): def setUp(self): base.TestCase.setUp(self) self.users = [self.model('user').createUser( 'usr%s' % num, 'passwd', 'tst', 'usr', 'u%s@u.com' % num) for num in [0, 1]] def testCuration(self): admin, user = self.users # create some groups g1 = self.model('group').createGroup('g1', admin) g2 = self.model('group').createGroup('g2', admin) g3 = self.model('group').createGroup('g3', admin) # set auto join rules rules = [ { 'pattern': '@kitware.com', 'groupId': str(g1['_id']), 'level': AccessType.ADMIN }, { 'pattern': '@example.com', 'groupId': str(g2['_id']), 'level': AccessType.READ }, { 'pattern': '@example.com', 'groupId': str(g3['_id']), 'level': AccessType.WRITE }, ] params = { 'list': json.dumps([{'key': 'autojoin', 'value': rules}]) } resp = self.request( '/system/setting', user=admin, method='PUT', params=params) self.assertStatusOk(resp) # create users user1 = self.model('user').createUser( 'user1', 'password', 'John', 'Doe', 'user1@example.com') user2 = self.model('user').createUser( 'user2', 'password', 'John', 'Doe', 'user2@kitware.com') user3 = self.model('user').createUser( 'user3', 'password', 'John', 'Doe', 'user3@kitware.co') # check correct groups were joined self.assertEqual(user1['groups'], [g2['_id'], g3['_id']]) self.assertEqual(user2['groups'], [g1['_id']]) self.assertEqual(user3['groups'], []) # check correct access levels g1 = self.model('group').load(g1['_id'], force=True) g2 = self.model('group').load(g2['_id'], force=True) g3 = self.model('group').load(g3['_id'], force=True) self.assertTrue( {u'id': user2['_id'], u'level': AccessType.ADMIN} in g1['access']['users']) self.assertTrue( {u'id': user1['_id'], u'level': AccessType.WRITE} in g3['access']['users'])
Add server tests for auto join plugin
Add server tests for auto join plugin
Python
apache-2.0
kotfic/girder,kotfic/girder,adsorensen/girder,jbeezley/girder,data-exp-lab/girder,girder/girder,sutartmelson/girder,Kitware/girder,girder/girder,sutartmelson/girder,jbeezley/girder,RafaelPalomar/girder,girder/girder,adsorensen/girder,RafaelPalomar/girder,manthey/girder,manthey/girder,data-exp-lab/girder,RafaelPalomar/girder,Kitware/girder,RafaelPalomar/girder,manthey/girder,Kitware/girder,data-exp-lab/girder,sutartmelson/girder,data-exp-lab/girder,kotfic/girder,girder/girder,jbeezley/girder,manthey/girder,adsorensen/girder,Xarthisius/girder,kotfic/girder,Kitware/girder,adsorensen/girder,data-exp-lab/girder,RafaelPalomar/girder,jbeezley/girder,Xarthisius/girder,sutartmelson/girder,Xarthisius/girder,adsorensen/girder,kotfic/girder,Xarthisius/girder,sutartmelson/girder,Xarthisius/girder
from tests import base def setUpModule(): base.enabledPlugins.append('autojoin') base.startServer() def tearDownModule(): base.stopServer() class AutoJoinTest(base.TestCase): def setUp(self): base.TestCase.setUp(self) Add server tests for auto join plugin
from girder.constants import AccessType from tests import base import json def setUpModule(): base.enabledPlugins.append('autojoin') base.startServer() def tearDownModule(): base.stopServer() class AutoJoinTest(base.TestCase): def setUp(self): base.TestCase.setUp(self) self.users = [self.model('user').createUser( 'usr%s' % num, 'passwd', 'tst', 'usr', 'u%s@u.com' % num) for num in [0, 1]] def testCuration(self): admin, user = self.users # create some groups g1 = self.model('group').createGroup('g1', admin) g2 = self.model('group').createGroup('g2', admin) g3 = self.model('group').createGroup('g3', admin) # set auto join rules rules = [ { 'pattern': '@kitware.com', 'groupId': str(g1['_id']), 'level': AccessType.ADMIN }, { 'pattern': '@example.com', 'groupId': str(g2['_id']), 'level': AccessType.READ }, { 'pattern': '@example.com', 'groupId': str(g3['_id']), 'level': AccessType.WRITE }, ] params = { 'list': json.dumps([{'key': 'autojoin', 'value': rules}]) } resp = self.request( '/system/setting', user=admin, method='PUT', params=params) self.assertStatusOk(resp) # create users user1 = self.model('user').createUser( 'user1', 'password', 'John', 'Doe', 'user1@example.com') user2 = self.model('user').createUser( 'user2', 'password', 'John', 'Doe', 'user2@kitware.com') user3 = self.model('user').createUser( 'user3', 'password', 'John', 'Doe', 'user3@kitware.co') # check correct groups were joined self.assertEqual(user1['groups'], [g2['_id'], g3['_id']]) self.assertEqual(user2['groups'], [g1['_id']]) self.assertEqual(user3['groups'], []) # check correct access levels g1 = self.model('group').load(g1['_id'], force=True) g2 = self.model('group').load(g2['_id'], force=True) g3 = self.model('group').load(g3['_id'], force=True) self.assertTrue( {u'id': user2['_id'], u'level': AccessType.ADMIN} in g1['access']['users']) self.assertTrue( {u'id': user1['_id'], u'level': AccessType.WRITE} in g3['access']['users'])
<commit_before>from tests import base def setUpModule(): base.enabledPlugins.append('autojoin') base.startServer() def tearDownModule(): base.stopServer() class AutoJoinTest(base.TestCase): def setUp(self): base.TestCase.setUp(self) <commit_msg>Add server tests for auto join plugin<commit_after>
from girder.constants import AccessType from tests import base import json def setUpModule(): base.enabledPlugins.append('autojoin') base.startServer() def tearDownModule(): base.stopServer() class AutoJoinTest(base.TestCase): def setUp(self): base.TestCase.setUp(self) self.users = [self.model('user').createUser( 'usr%s' % num, 'passwd', 'tst', 'usr', 'u%s@u.com' % num) for num in [0, 1]] def testCuration(self): admin, user = self.users # create some groups g1 = self.model('group').createGroup('g1', admin) g2 = self.model('group').createGroup('g2', admin) g3 = self.model('group').createGroup('g3', admin) # set auto join rules rules = [ { 'pattern': '@kitware.com', 'groupId': str(g1['_id']), 'level': AccessType.ADMIN }, { 'pattern': '@example.com', 'groupId': str(g2['_id']), 'level': AccessType.READ }, { 'pattern': '@example.com', 'groupId': str(g3['_id']), 'level': AccessType.WRITE }, ] params = { 'list': json.dumps([{'key': 'autojoin', 'value': rules}]) } resp = self.request( '/system/setting', user=admin, method='PUT', params=params) self.assertStatusOk(resp) # create users user1 = self.model('user').createUser( 'user1', 'password', 'John', 'Doe', 'user1@example.com') user2 = self.model('user').createUser( 'user2', 'password', 'John', 'Doe', 'user2@kitware.com') user3 = self.model('user').createUser( 'user3', 'password', 'John', 'Doe', 'user3@kitware.co') # check correct groups were joined self.assertEqual(user1['groups'], [g2['_id'], g3['_id']]) self.assertEqual(user2['groups'], [g1['_id']]) self.assertEqual(user3['groups'], []) # check correct access levels g1 = self.model('group').load(g1['_id'], force=True) g2 = self.model('group').load(g2['_id'], force=True) g3 = self.model('group').load(g3['_id'], force=True) self.assertTrue( {u'id': user2['_id'], u'level': AccessType.ADMIN} in g1['access']['users']) self.assertTrue( {u'id': user1['_id'], u'level': AccessType.WRITE} in g3['access']['users'])
from tests import base def setUpModule(): base.enabledPlugins.append('autojoin') base.startServer() def tearDownModule(): base.stopServer() class AutoJoinTest(base.TestCase): def setUp(self): base.TestCase.setUp(self) Add server tests for auto join pluginfrom girder.constants import AccessType from tests import base import json def setUpModule(): base.enabledPlugins.append('autojoin') base.startServer() def tearDownModule(): base.stopServer() class AutoJoinTest(base.TestCase): def setUp(self): base.TestCase.setUp(self) self.users = [self.model('user').createUser( 'usr%s' % num, 'passwd', 'tst', 'usr', 'u%s@u.com' % num) for num in [0, 1]] def testCuration(self): admin, user = self.users # create some groups g1 = self.model('group').createGroup('g1', admin) g2 = self.model('group').createGroup('g2', admin) g3 = self.model('group').createGroup('g3', admin) # set auto join rules rules = [ { 'pattern': '@kitware.com', 'groupId': str(g1['_id']), 'level': AccessType.ADMIN }, { 'pattern': '@example.com', 'groupId': str(g2['_id']), 'level': AccessType.READ }, { 'pattern': '@example.com', 'groupId': str(g3['_id']), 'level': AccessType.WRITE }, ] params = { 'list': json.dumps([{'key': 'autojoin', 'value': rules}]) } resp = self.request( '/system/setting', user=admin, method='PUT', params=params) self.assertStatusOk(resp) # create users user1 = self.model('user').createUser( 'user1', 'password', 'John', 'Doe', 'user1@example.com') user2 = self.model('user').createUser( 'user2', 'password', 'John', 'Doe', 'user2@kitware.com') user3 = self.model('user').createUser( 'user3', 'password', 'John', 'Doe', 'user3@kitware.co') # check correct groups were joined self.assertEqual(user1['groups'], [g2['_id'], g3['_id']]) self.assertEqual(user2['groups'], [g1['_id']]) self.assertEqual(user3['groups'], []) # check correct access levels g1 = self.model('group').load(g1['_id'], force=True) g2 = self.model('group').load(g2['_id'], force=True) g3 = self.model('group').load(g3['_id'], force=True) self.assertTrue( {u'id': user2['_id'], u'level': AccessType.ADMIN} in g1['access']['users']) self.assertTrue( {u'id': user1['_id'], u'level': AccessType.WRITE} in g3['access']['users'])
<commit_before>from tests import base def setUpModule(): base.enabledPlugins.append('autojoin') base.startServer() def tearDownModule(): base.stopServer() class AutoJoinTest(base.TestCase): def setUp(self): base.TestCase.setUp(self) <commit_msg>Add server tests for auto join plugin<commit_after>from girder.constants import AccessType from tests import base import json def setUpModule(): base.enabledPlugins.append('autojoin') base.startServer() def tearDownModule(): base.stopServer() class AutoJoinTest(base.TestCase): def setUp(self): base.TestCase.setUp(self) self.users = [self.model('user').createUser( 'usr%s' % num, 'passwd', 'tst', 'usr', 'u%s@u.com' % num) for num in [0, 1]] def testCuration(self): admin, user = self.users # create some groups g1 = self.model('group').createGroup('g1', admin) g2 = self.model('group').createGroup('g2', admin) g3 = self.model('group').createGroup('g3', admin) # set auto join rules rules = [ { 'pattern': '@kitware.com', 'groupId': str(g1['_id']), 'level': AccessType.ADMIN }, { 'pattern': '@example.com', 'groupId': str(g2['_id']), 'level': AccessType.READ }, { 'pattern': '@example.com', 'groupId': str(g3['_id']), 'level': AccessType.WRITE }, ] params = { 'list': json.dumps([{'key': 'autojoin', 'value': rules}]) } resp = self.request( '/system/setting', user=admin, method='PUT', params=params) self.assertStatusOk(resp) # create users user1 = self.model('user').createUser( 'user1', 'password', 'John', 'Doe', 'user1@example.com') user2 = self.model('user').createUser( 'user2', 'password', 'John', 'Doe', 'user2@kitware.com') user3 = self.model('user').createUser( 'user3', 'password', 'John', 'Doe', 'user3@kitware.co') # check correct groups were joined self.assertEqual(user1['groups'], [g2['_id'], g3['_id']]) self.assertEqual(user2['groups'], [g1['_id']]) self.assertEqual(user3['groups'], []) # check correct access levels g1 = self.model('group').load(g1['_id'], force=True) g2 = self.model('group').load(g2['_id'], force=True) g3 = self.model('group').load(g3['_id'], force=True) self.assertTrue( {u'id': user2['_id'], u'level': AccessType.ADMIN} in g1['access']['users']) self.assertTrue( {u'id': user1['_id'], u'level': AccessType.WRITE} in g3['access']['users'])
6ba29917003ea2f4a91434de57751762898dddce
tests/test_main.py
tests/test_main.py
import unittest import time from Arduino import Arduino """ A collection of some basic tests for the Arduino library. Extensive coverage is a bit difficult, since a positive test involves actually connecting and issuing commands to a live Arduino, hosting any hardware required to test a particular function. But a core of basic communication tests should at least be maintained here. """ class TestBasics(unittest.TestCase): _ = raw_input('Plug in Arduino board w/LED at pin 13, reset, then press enter') board = Arduino('9600') def test_find(self): """ Tests auto-connection/board detection """ self.assertIsNotNone(self.board.port) if __name__ == '__main__': unittest.main()
import unittest import time """ A collection of some basic tests for the Arduino library. Extensive coverage is a bit difficult, since a positive test involves actually connecting and issuing commands to a live Arduino, hosting any hardware required to test a particular function. But a core of basic communication tests should at least be maintained here. """ class TestBasics(unittest.TestCase): def test_find(self): """ Tests auto-connection/board detection. """ raw_input( 'Plug in Arduino board w/LED at pin 13, reset, then press enter') from Arduino import Arduino board = None try: # This will trigger automatic port resolution. board = Arduino(9600) finally: if board: board.close() def test_open(self): """ Tests connecting to an explicit port. """ port = raw_input( 'Plug in Arduino board w/LED at pin 13, reset.\n'\ 'Enter the port where the Arduino is connected, then press enter:') from Arduino import Arduino board = None try: board = Arduino(9600, port=port) finally: if board: board.close() if __name__ == '__main__': unittest.main()
Add another test to explicitly connect to a serial port.
Add another test to explicitly connect to a serial port.
Python
mit
bopo/Python-Arduino-Command-API,thearn/Python-Arduino-Command-API,ianjosephwilson/Python-Arduino-Command-API
import unittest import time from Arduino import Arduino """ A collection of some basic tests for the Arduino library. Extensive coverage is a bit difficult, since a positive test involves actually connecting and issuing commands to a live Arduino, hosting any hardware required to test a particular function. But a core of basic communication tests should at least be maintained here. """ class TestBasics(unittest.TestCase): _ = raw_input('Plug in Arduino board w/LED at pin 13, reset, then press enter') board = Arduino('9600') def test_find(self): """ Tests auto-connection/board detection """ self.assertIsNotNone(self.board.port) if __name__ == '__main__': unittest.main() Add another test to explicitly connect to a serial port.
import unittest import time """ A collection of some basic tests for the Arduino library. Extensive coverage is a bit difficult, since a positive test involves actually connecting and issuing commands to a live Arduino, hosting any hardware required to test a particular function. But a core of basic communication tests should at least be maintained here. """ class TestBasics(unittest.TestCase): def test_find(self): """ Tests auto-connection/board detection. """ raw_input( 'Plug in Arduino board w/LED at pin 13, reset, then press enter') from Arduino import Arduino board = None try: # This will trigger automatic port resolution. board = Arduino(9600) finally: if board: board.close() def test_open(self): """ Tests connecting to an explicit port. """ port = raw_input( 'Plug in Arduino board w/LED at pin 13, reset.\n'\ 'Enter the port where the Arduino is connected, then press enter:') from Arduino import Arduino board = None try: board = Arduino(9600, port=port) finally: if board: board.close() if __name__ == '__main__': unittest.main()
<commit_before>import unittest import time from Arduino import Arduino """ A collection of some basic tests for the Arduino library. Extensive coverage is a bit difficult, since a positive test involves actually connecting and issuing commands to a live Arduino, hosting any hardware required to test a particular function. But a core of basic communication tests should at least be maintained here. """ class TestBasics(unittest.TestCase): _ = raw_input('Plug in Arduino board w/LED at pin 13, reset, then press enter') board = Arduino('9600') def test_find(self): """ Tests auto-connection/board detection """ self.assertIsNotNone(self.board.port) if __name__ == '__main__': unittest.main() <commit_msg>Add another test to explicitly connect to a serial port.<commit_after>
import unittest import time """ A collection of some basic tests for the Arduino library. Extensive coverage is a bit difficult, since a positive test involves actually connecting and issuing commands to a live Arduino, hosting any hardware required to test a particular function. But a core of basic communication tests should at least be maintained here. """ class TestBasics(unittest.TestCase): def test_find(self): """ Tests auto-connection/board detection. """ raw_input( 'Plug in Arduino board w/LED at pin 13, reset, then press enter') from Arduino import Arduino board = None try: # This will trigger automatic port resolution. board = Arduino(9600) finally: if board: board.close() def test_open(self): """ Tests connecting to an explicit port. """ port = raw_input( 'Plug in Arduino board w/LED at pin 13, reset.\n'\ 'Enter the port where the Arduino is connected, then press enter:') from Arduino import Arduino board = None try: board = Arduino(9600, port=port) finally: if board: board.close() if __name__ == '__main__': unittest.main()
import unittest import time from Arduino import Arduino """ A collection of some basic tests for the Arduino library. Extensive coverage is a bit difficult, since a positive test involves actually connecting and issuing commands to a live Arduino, hosting any hardware required to test a particular function. But a core of basic communication tests should at least be maintained here. """ class TestBasics(unittest.TestCase): _ = raw_input('Plug in Arduino board w/LED at pin 13, reset, then press enter') board = Arduino('9600') def test_find(self): """ Tests auto-connection/board detection """ self.assertIsNotNone(self.board.port) if __name__ == '__main__': unittest.main() Add another test to explicitly connect to a serial port.import unittest import time """ A collection of some basic tests for the Arduino library. Extensive coverage is a bit difficult, since a positive test involves actually connecting and issuing commands to a live Arduino, hosting any hardware required to test a particular function. But a core of basic communication tests should at least be maintained here. """ class TestBasics(unittest.TestCase): def test_find(self): """ Tests auto-connection/board detection. """ raw_input( 'Plug in Arduino board w/LED at pin 13, reset, then press enter') from Arduino import Arduino board = None try: # This will trigger automatic port resolution. board = Arduino(9600) finally: if board: board.close() def test_open(self): """ Tests connecting to an explicit port. """ port = raw_input( 'Plug in Arduino board w/LED at pin 13, reset.\n'\ 'Enter the port where the Arduino is connected, then press enter:') from Arduino import Arduino board = None try: board = Arduino(9600, port=port) finally: if board: board.close() if __name__ == '__main__': unittest.main()
<commit_before>import unittest import time from Arduino import Arduino """ A collection of some basic tests for the Arduino library. Extensive coverage is a bit difficult, since a positive test involves actually connecting and issuing commands to a live Arduino, hosting any hardware required to test a particular function. But a core of basic communication tests should at least be maintained here. """ class TestBasics(unittest.TestCase): _ = raw_input('Plug in Arduino board w/LED at pin 13, reset, then press enter') board = Arduino('9600') def test_find(self): """ Tests auto-connection/board detection """ self.assertIsNotNone(self.board.port) if __name__ == '__main__': unittest.main() <commit_msg>Add another test to explicitly connect to a serial port.<commit_after>import unittest import time """ A collection of some basic tests for the Arduino library. Extensive coverage is a bit difficult, since a positive test involves actually connecting and issuing commands to a live Arduino, hosting any hardware required to test a particular function. But a core of basic communication tests should at least be maintained here. """ class TestBasics(unittest.TestCase): def test_find(self): """ Tests auto-connection/board detection. """ raw_input( 'Plug in Arduino board w/LED at pin 13, reset, then press enter') from Arduino import Arduino board = None try: # This will trigger automatic port resolution. board = Arduino(9600) finally: if board: board.close() def test_open(self): """ Tests connecting to an explicit port. """ port = raw_input( 'Plug in Arduino board w/LED at pin 13, reset.\n'\ 'Enter the port where the Arduino is connected, then press enter:') from Arduino import Arduino board = None try: board = Arduino(9600, port=port) finally: if board: board.close() if __name__ == '__main__': unittest.main()
2eb07ae9b98c36dc94e143003a7c44c7fbfb54f7
stronghold/middleware.py
stronghold/middleware.py
from django.contrib.auth.decorators import login_required from stronghold import conf, utils class LoginRequiredMiddleware(object): """ Force all views to use login required View is deemed to be public if the @public decorator is applied to the view View is also deemed to be Public if listed in in django settings in the STRONGHOLD_PUBLIC_URLS dictionary each url in STRONGHOLD_PUBLIC_URLS must be a valid regex """ def __init__(self, *args, **kwargs): self.public_view_urls = getattr(conf, 'STRONGHOLD_PUBLIC_URLS', ()) def process_view(self, request, view_func, view_args, view_kwargs): # if request is authenticated, dont process it if request.user.is_authenticated(): return None # if its a public view, don't process it if utils.is_view_func_public(view_func): return None # if this view matches a whitelisted regex, don't process it if any(view_url.match(request.path_info) for view_url in self.public_view_urls): return None return login_required(view_func)(request, *view_args, **view_kwargs)
from django.contrib.auth.decorators import login_required from stronghold import conf, utils class LoginRequiredMiddleware(object): """ Force all views to use login required View is deemed to be public if the @public decorator is applied to the view View is also deemed to be Public if listed in in django settings in the STRONGHOLD_PUBLIC_URLS dictionary each url in STRONGHOLD_PUBLIC_URLS must be a valid regex """ def __init__(self, *args, **kwargs): self.public_view_urls = getattr(conf, 'STRONGHOLD_PUBLIC_URLS', ()) def process_view(self, request, view_func, view_args, view_kwargs): if request.user.is_authenticated() or utils.is_view_func_public(view_func) \ or self.is_public_url(request.path_info): return None return login_required(view_func)(request, *view_args, **view_kwargs) def is_public_url(self, url): return any(public_url.match(url) for public_url in self.public_view_urls)
Refactor away unnecessary multiple return None
Refactor away unnecessary multiple return None
Python
mit
SunilMohanAdapa/django-stronghold,SunilMohanAdapa/django-stronghold,mgrouchy/django-stronghold
from django.contrib.auth.decorators import login_required from stronghold import conf, utils class LoginRequiredMiddleware(object): """ Force all views to use login required View is deemed to be public if the @public decorator is applied to the view View is also deemed to be Public if listed in in django settings in the STRONGHOLD_PUBLIC_URLS dictionary each url in STRONGHOLD_PUBLIC_URLS must be a valid regex """ def __init__(self, *args, **kwargs): self.public_view_urls = getattr(conf, 'STRONGHOLD_PUBLIC_URLS', ()) def process_view(self, request, view_func, view_args, view_kwargs): # if request is authenticated, dont process it if request.user.is_authenticated(): return None # if its a public view, don't process it if utils.is_view_func_public(view_func): return None # if this view matches a whitelisted regex, don't process it if any(view_url.match(request.path_info) for view_url in self.public_view_urls): return None return login_required(view_func)(request, *view_args, **view_kwargs) Refactor away unnecessary multiple return None
from django.contrib.auth.decorators import login_required from stronghold import conf, utils class LoginRequiredMiddleware(object): """ Force all views to use login required View is deemed to be public if the @public decorator is applied to the view View is also deemed to be Public if listed in in django settings in the STRONGHOLD_PUBLIC_URLS dictionary each url in STRONGHOLD_PUBLIC_URLS must be a valid regex """ def __init__(self, *args, **kwargs): self.public_view_urls = getattr(conf, 'STRONGHOLD_PUBLIC_URLS', ()) def process_view(self, request, view_func, view_args, view_kwargs): if request.user.is_authenticated() or utils.is_view_func_public(view_func) \ or self.is_public_url(request.path_info): return None return login_required(view_func)(request, *view_args, **view_kwargs) def is_public_url(self, url): return any(public_url.match(url) for public_url in self.public_view_urls)
<commit_before>from django.contrib.auth.decorators import login_required from stronghold import conf, utils class LoginRequiredMiddleware(object): """ Force all views to use login required View is deemed to be public if the @public decorator is applied to the view View is also deemed to be Public if listed in in django settings in the STRONGHOLD_PUBLIC_URLS dictionary each url in STRONGHOLD_PUBLIC_URLS must be a valid regex """ def __init__(self, *args, **kwargs): self.public_view_urls = getattr(conf, 'STRONGHOLD_PUBLIC_URLS', ()) def process_view(self, request, view_func, view_args, view_kwargs): # if request is authenticated, dont process it if request.user.is_authenticated(): return None # if its a public view, don't process it if utils.is_view_func_public(view_func): return None # if this view matches a whitelisted regex, don't process it if any(view_url.match(request.path_info) for view_url in self.public_view_urls): return None return login_required(view_func)(request, *view_args, **view_kwargs) <commit_msg>Refactor away unnecessary multiple return None<commit_after>
from django.contrib.auth.decorators import login_required from stronghold import conf, utils class LoginRequiredMiddleware(object): """ Force all views to use login required View is deemed to be public if the @public decorator is applied to the view View is also deemed to be Public if listed in in django settings in the STRONGHOLD_PUBLIC_URLS dictionary each url in STRONGHOLD_PUBLIC_URLS must be a valid regex """ def __init__(self, *args, **kwargs): self.public_view_urls = getattr(conf, 'STRONGHOLD_PUBLIC_URLS', ()) def process_view(self, request, view_func, view_args, view_kwargs): if request.user.is_authenticated() or utils.is_view_func_public(view_func) \ or self.is_public_url(request.path_info): return None return login_required(view_func)(request, *view_args, **view_kwargs) def is_public_url(self, url): return any(public_url.match(url) for public_url in self.public_view_urls)
from django.contrib.auth.decorators import login_required from stronghold import conf, utils class LoginRequiredMiddleware(object): """ Force all views to use login required View is deemed to be public if the @public decorator is applied to the view View is also deemed to be Public if listed in in django settings in the STRONGHOLD_PUBLIC_URLS dictionary each url in STRONGHOLD_PUBLIC_URLS must be a valid regex """ def __init__(self, *args, **kwargs): self.public_view_urls = getattr(conf, 'STRONGHOLD_PUBLIC_URLS', ()) def process_view(self, request, view_func, view_args, view_kwargs): # if request is authenticated, dont process it if request.user.is_authenticated(): return None # if its a public view, don't process it if utils.is_view_func_public(view_func): return None # if this view matches a whitelisted regex, don't process it if any(view_url.match(request.path_info) for view_url in self.public_view_urls): return None return login_required(view_func)(request, *view_args, **view_kwargs) Refactor away unnecessary multiple return Nonefrom django.contrib.auth.decorators import login_required from stronghold import conf, utils class LoginRequiredMiddleware(object): """ Force all views to use login required View is deemed to be public if the @public decorator is applied to the view View is also deemed to be Public if listed in in django settings in the STRONGHOLD_PUBLIC_URLS dictionary each url in STRONGHOLD_PUBLIC_URLS must be a valid regex """ def __init__(self, *args, **kwargs): self.public_view_urls = getattr(conf, 'STRONGHOLD_PUBLIC_URLS', ()) def process_view(self, request, view_func, view_args, view_kwargs): if request.user.is_authenticated() or utils.is_view_func_public(view_func) \ or self.is_public_url(request.path_info): return None return login_required(view_func)(request, *view_args, **view_kwargs) def is_public_url(self, url): return any(public_url.match(url) for public_url in self.public_view_urls)
<commit_before>from django.contrib.auth.decorators import login_required from stronghold import conf, utils class LoginRequiredMiddleware(object): """ Force all views to use login required View is deemed to be public if the @public decorator is applied to the view View is also deemed to be Public if listed in in django settings in the STRONGHOLD_PUBLIC_URLS dictionary each url in STRONGHOLD_PUBLIC_URLS must be a valid regex """ def __init__(self, *args, **kwargs): self.public_view_urls = getattr(conf, 'STRONGHOLD_PUBLIC_URLS', ()) def process_view(self, request, view_func, view_args, view_kwargs): # if request is authenticated, dont process it if request.user.is_authenticated(): return None # if its a public view, don't process it if utils.is_view_func_public(view_func): return None # if this view matches a whitelisted regex, don't process it if any(view_url.match(request.path_info) for view_url in self.public_view_urls): return None return login_required(view_func)(request, *view_args, **view_kwargs) <commit_msg>Refactor away unnecessary multiple return None<commit_after>from django.contrib.auth.decorators import login_required from stronghold import conf, utils class LoginRequiredMiddleware(object): """ Force all views to use login required View is deemed to be public if the @public decorator is applied to the view View is also deemed to be Public if listed in in django settings in the STRONGHOLD_PUBLIC_URLS dictionary each url in STRONGHOLD_PUBLIC_URLS must be a valid regex """ def __init__(self, *args, **kwargs): self.public_view_urls = getattr(conf, 'STRONGHOLD_PUBLIC_URLS', ()) def process_view(self, request, view_func, view_args, view_kwargs): if request.user.is_authenticated() or utils.is_view_func_public(view_func) \ or self.is_public_url(request.path_info): return None return login_required(view_func)(request, *view_args, **view_kwargs) def is_public_url(self, url): return any(public_url.match(url) for public_url in self.public_view_urls)
33de32fe26085b4616d561fab5a9ce91ac56451e
arxiv_vanity/papers/migrations/0017_auto_20180619_1657.py
arxiv_vanity/papers/migrations/0017_auto_20180619_1657.py
# Generated by Django 2.0.6 on 2018-06-19 16:57 from django.db import migrations def generate_arxiv_ids(apps, schema_editor): SourceFile = apps.get_model('papers', 'SourceFile') for sf in SourceFile.objects.all(): if not sf.arxiv_id: sf.arxiv_id = sf.file.name.rsplit('.', 1)[0] sf.save() class Migration(migrations.Migration): dependencies = [ ('papers', '0016_auto_20180619_1655'), ] operations = [ migrations.RunPython(generate_arxiv_ids), ]
# Generated by Django 2.0.6 on 2018-06-19 16:57 from django.db import migrations def generate_arxiv_ids(apps, schema_editor): SourceFile = apps.get_model('papers', 'SourceFile') for sf in SourceFile.objects.iterator(): if not sf.arxiv_id: sf.arxiv_id = sf.file.name.rsplit('.', 1)[0] sf.save() class Migration(migrations.Migration): dependencies = [ ('papers', '0016_auto_20180619_1655'), ] operations = [ migrations.RunPython(generate_arxiv_ids), ]
Use iterator in migration to reduce memory
Use iterator in migration to reduce memory
Python
apache-2.0
arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity
# Generated by Django 2.0.6 on 2018-06-19 16:57 from django.db import migrations def generate_arxiv_ids(apps, schema_editor): SourceFile = apps.get_model('papers', 'SourceFile') for sf in SourceFile.objects.all(): if not sf.arxiv_id: sf.arxiv_id = sf.file.name.rsplit('.', 1)[0] sf.save() class Migration(migrations.Migration): dependencies = [ ('papers', '0016_auto_20180619_1655'), ] operations = [ migrations.RunPython(generate_arxiv_ids), ] Use iterator in migration to reduce memory
# Generated by Django 2.0.6 on 2018-06-19 16:57 from django.db import migrations def generate_arxiv_ids(apps, schema_editor): SourceFile = apps.get_model('papers', 'SourceFile') for sf in SourceFile.objects.iterator(): if not sf.arxiv_id: sf.arxiv_id = sf.file.name.rsplit('.', 1)[0] sf.save() class Migration(migrations.Migration): dependencies = [ ('papers', '0016_auto_20180619_1655'), ] operations = [ migrations.RunPython(generate_arxiv_ids), ]
<commit_before># Generated by Django 2.0.6 on 2018-06-19 16:57 from django.db import migrations def generate_arxiv_ids(apps, schema_editor): SourceFile = apps.get_model('papers', 'SourceFile') for sf in SourceFile.objects.all(): if not sf.arxiv_id: sf.arxiv_id = sf.file.name.rsplit('.', 1)[0] sf.save() class Migration(migrations.Migration): dependencies = [ ('papers', '0016_auto_20180619_1655'), ] operations = [ migrations.RunPython(generate_arxiv_ids), ] <commit_msg>Use iterator in migration to reduce memory<commit_after>
# Generated by Django 2.0.6 on 2018-06-19 16:57 from django.db import migrations def generate_arxiv_ids(apps, schema_editor): SourceFile = apps.get_model('papers', 'SourceFile') for sf in SourceFile.objects.iterator(): if not sf.arxiv_id: sf.arxiv_id = sf.file.name.rsplit('.', 1)[0] sf.save() class Migration(migrations.Migration): dependencies = [ ('papers', '0016_auto_20180619_1655'), ] operations = [ migrations.RunPython(generate_arxiv_ids), ]
# Generated by Django 2.0.6 on 2018-06-19 16:57 from django.db import migrations def generate_arxiv_ids(apps, schema_editor): SourceFile = apps.get_model('papers', 'SourceFile') for sf in SourceFile.objects.all(): if not sf.arxiv_id: sf.arxiv_id = sf.file.name.rsplit('.', 1)[0] sf.save() class Migration(migrations.Migration): dependencies = [ ('papers', '0016_auto_20180619_1655'), ] operations = [ migrations.RunPython(generate_arxiv_ids), ] Use iterator in migration to reduce memory# Generated by Django 2.0.6 on 2018-06-19 16:57 from django.db import migrations def generate_arxiv_ids(apps, schema_editor): SourceFile = apps.get_model('papers', 'SourceFile') for sf in SourceFile.objects.iterator(): if not sf.arxiv_id: sf.arxiv_id = sf.file.name.rsplit('.', 1)[0] sf.save() class Migration(migrations.Migration): dependencies = [ ('papers', '0016_auto_20180619_1655'), ] operations = [ migrations.RunPython(generate_arxiv_ids), ]
<commit_before># Generated by Django 2.0.6 on 2018-06-19 16:57 from django.db import migrations def generate_arxiv_ids(apps, schema_editor): SourceFile = apps.get_model('papers', 'SourceFile') for sf in SourceFile.objects.all(): if not sf.arxiv_id: sf.arxiv_id = sf.file.name.rsplit('.', 1)[0] sf.save() class Migration(migrations.Migration): dependencies = [ ('papers', '0016_auto_20180619_1655'), ] operations = [ migrations.RunPython(generate_arxiv_ids), ] <commit_msg>Use iterator in migration to reduce memory<commit_after># Generated by Django 2.0.6 on 2018-06-19 16:57 from django.db import migrations def generate_arxiv_ids(apps, schema_editor): SourceFile = apps.get_model('papers', 'SourceFile') for sf in SourceFile.objects.iterator(): if not sf.arxiv_id: sf.arxiv_id = sf.file.name.rsplit('.', 1)[0] sf.save() class Migration(migrations.Migration): dependencies = [ ('papers', '0016_auto_20180619_1655'), ] operations = [ migrations.RunPython(generate_arxiv_ids), ]
e81aeb401f7a9eacb31bed364594ffe3fb21dfcc
conftest.py
conftest.py
from django.conf import settings import base64 import os import os.path def pytest_configure(config): if not settings.configured: os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server' test_db = os.environ.get('DB', 'sqlite') if test_db == 'mysql': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sentry', 'USER': 'root', }) elif test_db == 'postgres': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres', 'NAME': 'sentry', 'OPTIONS': { 'autocommit': True, } }) elif test_db == 'sqlite': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }) # Compressors is not fast, disable it in tests. settings.COMPRESS_ENABLED = False # override a few things with our test specifics settings.INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + ( 'tests', ) settings.SENTRY_KEY = base64.b64encode(os.urandom(40)) settings.SENTRY_PUBLIC = False
from django.conf import settings import base64 import os import os.path def pytest_configure(config): if not settings.configured: os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server' test_db = os.environ.get('DB', 'sqlite') if test_db == 'mysql': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sentry', 'USER': 'root', }) elif test_db == 'postgres': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres', 'NAME': 'sentry', 'OPTIONS': { 'autocommit': True, } }) elif test_db == 'sqlite': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }) # Compressors is not fast, disable it in tests. settings.COMPRESS_ENABLED = False # override a few things with our test specifics settings.INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + ( 'tests', ) settings.SENTRY_KEY = base64.b64encode(os.urandom(40)) settings.SENTRY_PUBLIC = False # This speeds up the tests considerably, pbkdf2 is by design, slow. settings.PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.MD5PasswordHasher', ]
Improve test performance by using the md5 hasher for tests.
Improve test performance by using the md5 hasher for tests.
Python
bsd-3-clause
gg7/sentry,mvaled/sentry,felixbuenemann/sentry,NickPresta/sentry,Kryz/sentry,imankulov/sentry,argonemyth/sentry,kevinastone/sentry,fuziontech/sentry,BuildingLink/sentry,Kryz/sentry,fotinakis/sentry,llonchj/sentry,korealerts1/sentry,camilonova/sentry,BuildingLink/sentry,zenefits/sentry,beni55/sentry,kevinlondon/sentry,pauloschilling/sentry,boneyao/sentry,looker/sentry,jokey2k/sentry,ewdurbin/sentry,zenefits/sentry,mvaled/sentry,songyi199111/sentry,hongliang5623/sentry,JamesMura/sentry,korealerts1/sentry,Natim/sentry,BayanGroup/sentry,ifduyue/sentry,korealerts1/sentry,gencer/sentry,BuildingLink/sentry,fotinakis/sentry,zenefits/sentry,rdio/sentry,llonchj/sentry,Kryz/sentry,BuildingLink/sentry,mvaled/sentry,JackDanger/sentry,alexm92/sentry,felixbuenemann/sentry,jean/sentry,jokey2k/sentry,fuziontech/sentry,TedaLIEz/sentry,beeftornado/sentry,drcapulet/sentry,looker/sentry,vperron/sentry,jean/sentry,imankulov/sentry,boneyao/sentry,vperron/sentry,TedaLIEz/sentry,gencer/sentry,SilentCircle/sentry,songyi199111/sentry,JamesMura/sentry,ifduyue/sentry,looker/sentry,daevaorn/sentry,wujuguang/sentry,daevaorn/sentry,pauloschilling/sentry,gencer/sentry,looker/sentry,hongliang5623/sentry,SilentCircle/sentry,looker/sentry,jean/sentry,ngonzalvez/sentry,NickPresta/sentry,BuildingLink/sentry,felixbuenemann/sentry,camilonova/sentry,argonemyth/sentry,llonchj/sentry,nicholasserra/sentry,mvaled/sentry,camilonova/sentry,drcapulet/sentry,SilentCircle/sentry,beeftornado/sentry,NickPresta/sentry,ewdurbin/sentry,JamesMura/sentry,rdio/sentry,JackDanger/sentry,TedaLIEz/sentry,wong2/sentry,gencer/sentry,rdio/sentry,ifduyue/sentry,Natim/sentry,BayanGroup/sentry,mitsuhiko/sentry,vperron/sentry,wujuguang/sentry,daevaorn/sentry,ngonzalvez/sentry,ifduyue/sentry,kevinastone/sentry,nicholasserra/sentry,wong2/sentry,JTCunning/sentry,JamesMura/sentry,gencer/sentry,alexm92/sentry,pauloschilling/sentry,JTCunning/sentry,daevaorn/sentry,1tush/sentry,rdio/sentry,kevinastone/sentry,mvaled/sentry,SilentCircle/sentry,kevinlondon/sentry,zenefits/sentry,Natim/sentry,kevinlondon/sentry,beni55/sentry,ewdurbin/sentry,boneyao/sentry,alexm92/sentry,gg7/sentry,JamesMura/sentry,drcapulet/sentry,wujuguang/sentry,gg7/sentry,fotinakis/sentry,imankulov/sentry,zenefits/sentry,BayanGroup/sentry,mitsuhiko/sentry,songyi199111/sentry,jean/sentry,hongliang5623/sentry,1tush/sentry,nicholasserra/sentry,ngonzalvez/sentry,mvaled/sentry,beeftornado/sentry,fuziontech/sentry,ifduyue/sentry,beni55/sentry,JTCunning/sentry,wong2/sentry,jokey2k/sentry,argonemyth/sentry,fotinakis/sentry,1tush/sentry,NickPresta/sentry,jean/sentry,JackDanger/sentry
from django.conf import settings import base64 import os import os.path def pytest_configure(config): if not settings.configured: os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server' test_db = os.environ.get('DB', 'sqlite') if test_db == 'mysql': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sentry', 'USER': 'root', }) elif test_db == 'postgres': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres', 'NAME': 'sentry', 'OPTIONS': { 'autocommit': True, } }) elif test_db == 'sqlite': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }) # Compressors is not fast, disable it in tests. settings.COMPRESS_ENABLED = False # override a few things with our test specifics settings.INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + ( 'tests', ) settings.SENTRY_KEY = base64.b64encode(os.urandom(40)) settings.SENTRY_PUBLIC = False Improve test performance by using the md5 hasher for tests.
from django.conf import settings import base64 import os import os.path def pytest_configure(config): if not settings.configured: os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server' test_db = os.environ.get('DB', 'sqlite') if test_db == 'mysql': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sentry', 'USER': 'root', }) elif test_db == 'postgres': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres', 'NAME': 'sentry', 'OPTIONS': { 'autocommit': True, } }) elif test_db == 'sqlite': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }) # Compressors is not fast, disable it in tests. settings.COMPRESS_ENABLED = False # override a few things with our test specifics settings.INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + ( 'tests', ) settings.SENTRY_KEY = base64.b64encode(os.urandom(40)) settings.SENTRY_PUBLIC = False # This speeds up the tests considerably, pbkdf2 is by design, slow. settings.PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.MD5PasswordHasher', ]
<commit_before>from django.conf import settings import base64 import os import os.path def pytest_configure(config): if not settings.configured: os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server' test_db = os.environ.get('DB', 'sqlite') if test_db == 'mysql': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sentry', 'USER': 'root', }) elif test_db == 'postgres': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres', 'NAME': 'sentry', 'OPTIONS': { 'autocommit': True, } }) elif test_db == 'sqlite': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }) # Compressors is not fast, disable it in tests. settings.COMPRESS_ENABLED = False # override a few things with our test specifics settings.INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + ( 'tests', ) settings.SENTRY_KEY = base64.b64encode(os.urandom(40)) settings.SENTRY_PUBLIC = False <commit_msg>Improve test performance by using the md5 hasher for tests.<commit_after>
from django.conf import settings import base64 import os import os.path def pytest_configure(config): if not settings.configured: os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server' test_db = os.environ.get('DB', 'sqlite') if test_db == 'mysql': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sentry', 'USER': 'root', }) elif test_db == 'postgres': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres', 'NAME': 'sentry', 'OPTIONS': { 'autocommit': True, } }) elif test_db == 'sqlite': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }) # Compressors is not fast, disable it in tests. settings.COMPRESS_ENABLED = False # override a few things with our test specifics settings.INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + ( 'tests', ) settings.SENTRY_KEY = base64.b64encode(os.urandom(40)) settings.SENTRY_PUBLIC = False # This speeds up the tests considerably, pbkdf2 is by design, slow. settings.PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.MD5PasswordHasher', ]
from django.conf import settings import base64 import os import os.path def pytest_configure(config): if not settings.configured: os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server' test_db = os.environ.get('DB', 'sqlite') if test_db == 'mysql': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sentry', 'USER': 'root', }) elif test_db == 'postgres': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres', 'NAME': 'sentry', 'OPTIONS': { 'autocommit': True, } }) elif test_db == 'sqlite': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }) # Compressors is not fast, disable it in tests. settings.COMPRESS_ENABLED = False # override a few things with our test specifics settings.INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + ( 'tests', ) settings.SENTRY_KEY = base64.b64encode(os.urandom(40)) settings.SENTRY_PUBLIC = False Improve test performance by using the md5 hasher for tests.from django.conf import settings import base64 import os import os.path def pytest_configure(config): if not settings.configured: os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server' test_db = os.environ.get('DB', 'sqlite') if test_db == 'mysql': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sentry', 'USER': 'root', }) elif test_db == 'postgres': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres', 'NAME': 'sentry', 'OPTIONS': { 'autocommit': True, } }) elif test_db == 'sqlite': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }) # Compressors is not fast, disable it in tests. settings.COMPRESS_ENABLED = False # override a few things with our test specifics settings.INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + ( 'tests', ) settings.SENTRY_KEY = base64.b64encode(os.urandom(40)) settings.SENTRY_PUBLIC = False # This speeds up the tests considerably, pbkdf2 is by design, slow. settings.PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.MD5PasswordHasher', ]
<commit_before>from django.conf import settings import base64 import os import os.path def pytest_configure(config): if not settings.configured: os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server' test_db = os.environ.get('DB', 'sqlite') if test_db == 'mysql': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sentry', 'USER': 'root', }) elif test_db == 'postgres': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres', 'NAME': 'sentry', 'OPTIONS': { 'autocommit': True, } }) elif test_db == 'sqlite': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }) # Compressors is not fast, disable it in tests. settings.COMPRESS_ENABLED = False # override a few things with our test specifics settings.INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + ( 'tests', ) settings.SENTRY_KEY = base64.b64encode(os.urandom(40)) settings.SENTRY_PUBLIC = False <commit_msg>Improve test performance by using the md5 hasher for tests.<commit_after>from django.conf import settings import base64 import os import os.path def pytest_configure(config): if not settings.configured: os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server' test_db = os.environ.get('DB', 'sqlite') if test_db == 'mysql': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sentry', 'USER': 'root', }) elif test_db == 'postgres': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres', 'NAME': 'sentry', 'OPTIONS': { 'autocommit': True, } }) elif test_db == 'sqlite': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }) # Compressors is not fast, disable it in tests. settings.COMPRESS_ENABLED = False # override a few things with our test specifics settings.INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + ( 'tests', ) settings.SENTRY_KEY = base64.b64encode(os.urandom(40)) settings.SENTRY_PUBLIC = False # This speeds up the tests considerably, pbkdf2 is by design, slow. settings.PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.MD5PasswordHasher', ]
fa4cc4cab3e76ba0211736da4862a85d50bdcccc
gameconf.py
gameconf.py
import os from traceback import format_exc from apps.config.models import ConfigValue import functions_general """ Handle the setting/retrieving of server config directives. """ def host_os_is(osname): """ Check to see if the host OS matches the query. """ if os.name == osname: return True return False def get_configvalue(configname): """ Retrieve a configuration value. """ try: return ConfigValue.objects.get(conf_key=configname).conf_value except: functions_general.log_errmsg("Unable to get config value for %s:\n%s" % (configname, (format_exc()))) def set_configvalue(configname, newvalue): """ Sets a configuration value with the specified name. """ conf = ConfigValue.objects.get(conf_key=configname) conf.conf_value = newvalue conf.save()
import os from traceback import format_exc from apps.config.models import ConfigValue import functions_general """ Handle the setting/retrieving of server config directives. """ def host_os_is(osname): """ Check to see if the host OS matches the query. """ if os.name == osname: return True return False def get_configvalue(configname): """ Retrieve a configuration value. """ try: return ConfigValue.objects.get(conf_key__iexact=configname).conf_value except: functions_general.log_errmsg("Unable to get config value for %s:\n%s" % (configname, (format_exc()))) def set_configvalue(configname, newvalue): """ Sets a configuration value with the specified name. """ conf = ConfigValue.objects.get(conf_key=configname) conf.conf_value = newvalue conf.save()
Make config values not case-sensitive.
Make config values not case-sensitive.
Python
bsd-3-clause
mrkulk/text-world,titeuf87/evennia,mrkulk/text-world,shollen/evennia,feend78/evennia,TheTypoMaster/evennia,feend78/evennia,ypwalter/evennia,ergodicbreak/evennia,mrkulk/text-world,emergebtc/evennia,ypwalter/evennia,titeuf87/evennia,emergebtc/evennia,titeuf87/evennia,emergebtc/evennia,ypwalter/evennia,jamesbeebop/evennia,titeuf87/evennia,TheTypoMaster/evennia,ergodicbreak/evennia,TheTypoMaster/evennia,mrkulk/text-world,feend78/evennia,ergodicbreak/evennia,shollen/evennia,jamesbeebop/evennia,jamesbeebop/evennia,feend78/evennia
import os from traceback import format_exc from apps.config.models import ConfigValue import functions_general """ Handle the setting/retrieving of server config directives. """ def host_os_is(osname): """ Check to see if the host OS matches the query. """ if os.name == osname: return True return False def get_configvalue(configname): """ Retrieve a configuration value. """ try: return ConfigValue.objects.get(conf_key=configname).conf_value except: functions_general.log_errmsg("Unable to get config value for %s:\n%s" % (configname, (format_exc()))) def set_configvalue(configname, newvalue): """ Sets a configuration value with the specified name. """ conf = ConfigValue.objects.get(conf_key=configname) conf.conf_value = newvalue conf.save() Make config values not case-sensitive.
import os from traceback import format_exc from apps.config.models import ConfigValue import functions_general """ Handle the setting/retrieving of server config directives. """ def host_os_is(osname): """ Check to see if the host OS matches the query. """ if os.name == osname: return True return False def get_configvalue(configname): """ Retrieve a configuration value. """ try: return ConfigValue.objects.get(conf_key__iexact=configname).conf_value except: functions_general.log_errmsg("Unable to get config value for %s:\n%s" % (configname, (format_exc()))) def set_configvalue(configname, newvalue): """ Sets a configuration value with the specified name. """ conf = ConfigValue.objects.get(conf_key=configname) conf.conf_value = newvalue conf.save()
<commit_before>import os from traceback import format_exc from apps.config.models import ConfigValue import functions_general """ Handle the setting/retrieving of server config directives. """ def host_os_is(osname): """ Check to see if the host OS matches the query. """ if os.name == osname: return True return False def get_configvalue(configname): """ Retrieve a configuration value. """ try: return ConfigValue.objects.get(conf_key=configname).conf_value except: functions_general.log_errmsg("Unable to get config value for %s:\n%s" % (configname, (format_exc()))) def set_configvalue(configname, newvalue): """ Sets a configuration value with the specified name. """ conf = ConfigValue.objects.get(conf_key=configname) conf.conf_value = newvalue conf.save() <commit_msg>Make config values not case-sensitive.<commit_after>
import os from traceback import format_exc from apps.config.models import ConfigValue import functions_general """ Handle the setting/retrieving of server config directives. """ def host_os_is(osname): """ Check to see if the host OS matches the query. """ if os.name == osname: return True return False def get_configvalue(configname): """ Retrieve a configuration value. """ try: return ConfigValue.objects.get(conf_key__iexact=configname).conf_value except: functions_general.log_errmsg("Unable to get config value for %s:\n%s" % (configname, (format_exc()))) def set_configvalue(configname, newvalue): """ Sets a configuration value with the specified name. """ conf = ConfigValue.objects.get(conf_key=configname) conf.conf_value = newvalue conf.save()
import os from traceback import format_exc from apps.config.models import ConfigValue import functions_general """ Handle the setting/retrieving of server config directives. """ def host_os_is(osname): """ Check to see if the host OS matches the query. """ if os.name == osname: return True return False def get_configvalue(configname): """ Retrieve a configuration value. """ try: return ConfigValue.objects.get(conf_key=configname).conf_value except: functions_general.log_errmsg("Unable to get config value for %s:\n%s" % (configname, (format_exc()))) def set_configvalue(configname, newvalue): """ Sets a configuration value with the specified name. """ conf = ConfigValue.objects.get(conf_key=configname) conf.conf_value = newvalue conf.save() Make config values not case-sensitive.import os from traceback import format_exc from apps.config.models import ConfigValue import functions_general """ Handle the setting/retrieving of server config directives. """ def host_os_is(osname): """ Check to see if the host OS matches the query. """ if os.name == osname: return True return False def get_configvalue(configname): """ Retrieve a configuration value. """ try: return ConfigValue.objects.get(conf_key__iexact=configname).conf_value except: functions_general.log_errmsg("Unable to get config value for %s:\n%s" % (configname, (format_exc()))) def set_configvalue(configname, newvalue): """ Sets a configuration value with the specified name. """ conf = ConfigValue.objects.get(conf_key=configname) conf.conf_value = newvalue conf.save()
<commit_before>import os from traceback import format_exc from apps.config.models import ConfigValue import functions_general """ Handle the setting/retrieving of server config directives. """ def host_os_is(osname): """ Check to see if the host OS matches the query. """ if os.name == osname: return True return False def get_configvalue(configname): """ Retrieve a configuration value. """ try: return ConfigValue.objects.get(conf_key=configname).conf_value except: functions_general.log_errmsg("Unable to get config value for %s:\n%s" % (configname, (format_exc()))) def set_configvalue(configname, newvalue): """ Sets a configuration value with the specified name. """ conf = ConfigValue.objects.get(conf_key=configname) conf.conf_value = newvalue conf.save() <commit_msg>Make config values not case-sensitive.<commit_after>import os from traceback import format_exc from apps.config.models import ConfigValue import functions_general """ Handle the setting/retrieving of server config directives. """ def host_os_is(osname): """ Check to see if the host OS matches the query. """ if os.name == osname: return True return False def get_configvalue(configname): """ Retrieve a configuration value. """ try: return ConfigValue.objects.get(conf_key__iexact=configname).conf_value except: functions_general.log_errmsg("Unable to get config value for %s:\n%s" % (configname, (format_exc()))) def set_configvalue(configname, newvalue): """ Sets a configuration value with the specified name. """ conf = ConfigValue.objects.get(conf_key=configname) conf.conf_value = newvalue conf.save()
aaaab6f87fef26feb29ddf8188e6410e7be55376
falcom/test/test_logtree.py
falcom/test/test_logtree.py
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from hamcrest import * import unittest from .hamcrest import evaluates_to_false from ..logtree import Tree class TreeTest (unittest.TestCase): def test_tree_is_a_class (self): t = Tree() assert_that(repr(t), starts_with("<Tree")) def test_empty_tree_is_false (self): t = Tree() assert_that(t, evaluates_to_false())
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from hamcrest import * import unittest from .hamcrest import evaluates_to_false from ..logtree import Tree class GivenEmptyTree (unittest.TestCase): def setUp (self): self.tree = Tree() def test_tree_has_repr (self): assert_that(repr(self.tree), starts_with("<Tree")) def test_evaluates_to_false (self): assert_that(self.tree, evaluates_to_false())
Refactor tests to use setup
Refactor tests to use setup
Python
bsd-3-clause
mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from hamcrest import * import unittest from .hamcrest import evaluates_to_false from ..logtree import Tree class TreeTest (unittest.TestCase): def test_tree_is_a_class (self): t = Tree() assert_that(repr(t), starts_with("<Tree")) def test_empty_tree_is_false (self): t = Tree() assert_that(t, evaluates_to_false()) Refactor tests to use setup
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from hamcrest import * import unittest from .hamcrest import evaluates_to_false from ..logtree import Tree class GivenEmptyTree (unittest.TestCase): def setUp (self): self.tree = Tree() def test_tree_has_repr (self): assert_that(repr(self.tree), starts_with("<Tree")) def test_evaluates_to_false (self): assert_that(self.tree, evaluates_to_false())
<commit_before># Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from hamcrest import * import unittest from .hamcrest import evaluates_to_false from ..logtree import Tree class TreeTest (unittest.TestCase): def test_tree_is_a_class (self): t = Tree() assert_that(repr(t), starts_with("<Tree")) def test_empty_tree_is_false (self): t = Tree() assert_that(t, evaluates_to_false()) <commit_msg>Refactor tests to use setup<commit_after>
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from hamcrest import * import unittest from .hamcrest import evaluates_to_false from ..logtree import Tree class GivenEmptyTree (unittest.TestCase): def setUp (self): self.tree = Tree() def test_tree_has_repr (self): assert_that(repr(self.tree), starts_with("<Tree")) def test_evaluates_to_false (self): assert_that(self.tree, evaluates_to_false())
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from hamcrest import * import unittest from .hamcrest import evaluates_to_false from ..logtree import Tree class TreeTest (unittest.TestCase): def test_tree_is_a_class (self): t = Tree() assert_that(repr(t), starts_with("<Tree")) def test_empty_tree_is_false (self): t = Tree() assert_that(t, evaluates_to_false()) Refactor tests to use setup# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from hamcrest import * import unittest from .hamcrest import evaluates_to_false from ..logtree import Tree class GivenEmptyTree (unittest.TestCase): def setUp (self): self.tree = Tree() def test_tree_has_repr (self): assert_that(repr(self.tree), starts_with("<Tree")) def test_evaluates_to_false (self): assert_that(self.tree, evaluates_to_false())
<commit_before># Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from hamcrest import * import unittest from .hamcrest import evaluates_to_false from ..logtree import Tree class TreeTest (unittest.TestCase): def test_tree_is_a_class (self): t = Tree() assert_that(repr(t), starts_with("<Tree")) def test_empty_tree_is_false (self): t = Tree() assert_that(t, evaluates_to_false()) <commit_msg>Refactor tests to use setup<commit_after># Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from hamcrest import * import unittest from .hamcrest import evaluates_to_false from ..logtree import Tree class GivenEmptyTree (unittest.TestCase): def setUp (self): self.tree = Tree() def test_tree_has_repr (self): assert_that(repr(self.tree), starts_with("<Tree")) def test_evaluates_to_false (self): assert_that(self.tree, evaluates_to_false())
245d0b91a778d6c0015e04bf369bc59304588cb9
block_disposable_email.py
block_disposable_email.py
#!/usr/bin/env python import re import sys def chunk(l,n): return (l[i:i+n] for i in xrange(0, len(l), n)) def is_disposable_email(email): emails = [line.strip() for line in open('domain-list.txt')] """ Chunk it! Regex parser doesn't deal with hundreds of groups """ for email_group in chunk(emails, 20): regex = "(.*" + ")|(.*".join(email_group) + ")" if re.match(regex, email): return True return False if __name__ == "__main__": if len(sys.argv) < 2: sys.stderr.write("You must supply at least 1 email\n") for email in sys.argv[1:]: if is_disposable_email(email): sys.stderr.write("{email} appears to be a disposable address\n".format(email=email))
from django.conf import settings import re import sys class DisposableEmailChecker(): """ Check if an email is from a disposable email service """ def __init__(self): self.emails = [line.strip() for line in open(settings.DISPOSABLE_EMAIL_DOMAINS)] def chunk(l,n): return (l[i:i+n] for i in xrange(0, len(l), n)) def is_disposable(self, email): for email_group in self.chunk(self.emails, 20): regex = "(.*" + ")|(.*".join(email_group) + ")" if re.match(regex, email): return True return False
Convert for use with Django
Convert for use with Django
Python
bsd-3-clause
aaronbassett/DisposableEmailChecker
#!/usr/bin/env python import re import sys def chunk(l,n): return (l[i:i+n] for i in xrange(0, len(l), n)) def is_disposable_email(email): emails = [line.strip() for line in open('domain-list.txt')] """ Chunk it! Regex parser doesn't deal with hundreds of groups """ for email_group in chunk(emails, 20): regex = "(.*" + ")|(.*".join(email_group) + ")" if re.match(regex, email): return True return False if __name__ == "__main__": if len(sys.argv) < 2: sys.stderr.write("You must supply at least 1 email\n") for email in sys.argv[1:]: if is_disposable_email(email): sys.stderr.write("{email} appears to be a disposable address\n".format(email=email))Convert for use with Django
from django.conf import settings import re import sys class DisposableEmailChecker(): """ Check if an email is from a disposable email service """ def __init__(self): self.emails = [line.strip() for line in open(settings.DISPOSABLE_EMAIL_DOMAINS)] def chunk(l,n): return (l[i:i+n] for i in xrange(0, len(l), n)) def is_disposable(self, email): for email_group in self.chunk(self.emails, 20): regex = "(.*" + ")|(.*".join(email_group) + ")" if re.match(regex, email): return True return False
<commit_before>#!/usr/bin/env python import re import sys def chunk(l,n): return (l[i:i+n] for i in xrange(0, len(l), n)) def is_disposable_email(email): emails = [line.strip() for line in open('domain-list.txt')] """ Chunk it! Regex parser doesn't deal with hundreds of groups """ for email_group in chunk(emails, 20): regex = "(.*" + ")|(.*".join(email_group) + ")" if re.match(regex, email): return True return False if __name__ == "__main__": if len(sys.argv) < 2: sys.stderr.write("You must supply at least 1 email\n") for email in sys.argv[1:]: if is_disposable_email(email): sys.stderr.write("{email} appears to be a disposable address\n".format(email=email))<commit_msg>Convert for use with Django<commit_after>
from django.conf import settings import re import sys class DisposableEmailChecker(): """ Check if an email is from a disposable email service """ def __init__(self): self.emails = [line.strip() for line in open(settings.DISPOSABLE_EMAIL_DOMAINS)] def chunk(l,n): return (l[i:i+n] for i in xrange(0, len(l), n)) def is_disposable(self, email): for email_group in self.chunk(self.emails, 20): regex = "(.*" + ")|(.*".join(email_group) + ")" if re.match(regex, email): return True return False
#!/usr/bin/env python import re import sys def chunk(l,n): return (l[i:i+n] for i in xrange(0, len(l), n)) def is_disposable_email(email): emails = [line.strip() for line in open('domain-list.txt')] """ Chunk it! Regex parser doesn't deal with hundreds of groups """ for email_group in chunk(emails, 20): regex = "(.*" + ")|(.*".join(email_group) + ")" if re.match(regex, email): return True return False if __name__ == "__main__": if len(sys.argv) < 2: sys.stderr.write("You must supply at least 1 email\n") for email in sys.argv[1:]: if is_disposable_email(email): sys.stderr.write("{email} appears to be a disposable address\n".format(email=email))Convert for use with Djangofrom django.conf import settings import re import sys class DisposableEmailChecker(): """ Check if an email is from a disposable email service """ def __init__(self): self.emails = [line.strip() for line in open(settings.DISPOSABLE_EMAIL_DOMAINS)] def chunk(l,n): return (l[i:i+n] for i in xrange(0, len(l), n)) def is_disposable(self, email): for email_group in self.chunk(self.emails, 20): regex = "(.*" + ")|(.*".join(email_group) + ")" if re.match(regex, email): return True return False
<commit_before>#!/usr/bin/env python import re import sys def chunk(l,n): return (l[i:i+n] for i in xrange(0, len(l), n)) def is_disposable_email(email): emails = [line.strip() for line in open('domain-list.txt')] """ Chunk it! Regex parser doesn't deal with hundreds of groups """ for email_group in chunk(emails, 20): regex = "(.*" + ")|(.*".join(email_group) + ")" if re.match(regex, email): return True return False if __name__ == "__main__": if len(sys.argv) < 2: sys.stderr.write("You must supply at least 1 email\n") for email in sys.argv[1:]: if is_disposable_email(email): sys.stderr.write("{email} appears to be a disposable address\n".format(email=email))<commit_msg>Convert for use with Django<commit_after>from django.conf import settings import re import sys class DisposableEmailChecker(): """ Check if an email is from a disposable email service """ def __init__(self): self.emails = [line.strip() for line in open(settings.DISPOSABLE_EMAIL_DOMAINS)] def chunk(l,n): return (l[i:i+n] for i in xrange(0, len(l), n)) def is_disposable(self, email): for email_group in self.chunk(self.emails, 20): regex = "(.*" + ")|(.*".join(email_group) + ")" if re.match(regex, email): return True return False
22800562830d11cf8287656f098e163d7cedf2d3
test/test_scraping.py
test/test_scraping.py
from datetime import datetime import sys import unittest import btceapi class TestScraping(unittest.TestCase): def test_scrape_main_page(self): mainPage = btceapi.scrapeMainPage() for message in mainPage.messages: msgId, user, time, text = message assert type(time) is datetime if sys.version_info[0] == 2: # python2.x self.assertIn(type(msgId), (str, unicode)) self.assertIn(type(user), (str, unicode)) self.assertIn(type(text), (str, unicode)) else: # python3.x self.assertIs(type(msgId), str) self.assertIs(type(user), str) self.assertIs(type(text), str) if __name__ == '__main__': unittest.main()
from datetime import datetime import sys import unittest import btceapi class TestScraping(unittest.TestCase): def test_scrape_main_page(self): mainPage = btceapi.scrapeMainPage() for message in mainPage.messages: msgId, user, time, text = message self.assertIs(type(time), datetime) if sys.version_info[0] == 2: # python2.x assert type(msgId) in (str, unicode) assert type(user) in (str, unicode) assert type(text) in (str, unicode) else: # python3.x self.assertIs(type(msgId), str) self.assertIs(type(user), str) self.assertIs(type(text), str) if __name__ == '__main__': unittest.main()
Fix for assertIn method not being present in Python 2.6. Undo prior erroneous commit (assertIn is missing, not assertIs).
Fix for assertIn method not being present in Python 2.6. Undo prior erroneous commit (assertIn is missing, not assertIs).
Python
mit
alanmcintyre/btce-api,CodeReclaimers/btce-api,lromanov/tidex-api
from datetime import datetime import sys import unittest import btceapi class TestScraping(unittest.TestCase): def test_scrape_main_page(self): mainPage = btceapi.scrapeMainPage() for message in mainPage.messages: msgId, user, time, text = message assert type(time) is datetime if sys.version_info[0] == 2: # python2.x self.assertIn(type(msgId), (str, unicode)) self.assertIn(type(user), (str, unicode)) self.assertIn(type(text), (str, unicode)) else: # python3.x self.assertIs(type(msgId), str) self.assertIs(type(user), str) self.assertIs(type(text), str) if __name__ == '__main__': unittest.main() Fix for assertIn method not being present in Python 2.6. Undo prior erroneous commit (assertIn is missing, not assertIs).
from datetime import datetime import sys import unittest import btceapi class TestScraping(unittest.TestCase): def test_scrape_main_page(self): mainPage = btceapi.scrapeMainPage() for message in mainPage.messages: msgId, user, time, text = message self.assertIs(type(time), datetime) if sys.version_info[0] == 2: # python2.x assert type(msgId) in (str, unicode) assert type(user) in (str, unicode) assert type(text) in (str, unicode) else: # python3.x self.assertIs(type(msgId), str) self.assertIs(type(user), str) self.assertIs(type(text), str) if __name__ == '__main__': unittest.main()
<commit_before>from datetime import datetime import sys import unittest import btceapi class TestScraping(unittest.TestCase): def test_scrape_main_page(self): mainPage = btceapi.scrapeMainPage() for message in mainPage.messages: msgId, user, time, text = message assert type(time) is datetime if sys.version_info[0] == 2: # python2.x self.assertIn(type(msgId), (str, unicode)) self.assertIn(type(user), (str, unicode)) self.assertIn(type(text), (str, unicode)) else: # python3.x self.assertIs(type(msgId), str) self.assertIs(type(user), str) self.assertIs(type(text), str) if __name__ == '__main__': unittest.main() <commit_msg>Fix for assertIn method not being present in Python 2.6. Undo prior erroneous commit (assertIn is missing, not assertIs).<commit_after>
from datetime import datetime import sys import unittest import btceapi class TestScraping(unittest.TestCase): def test_scrape_main_page(self): mainPage = btceapi.scrapeMainPage() for message in mainPage.messages: msgId, user, time, text = message self.assertIs(type(time), datetime) if sys.version_info[0] == 2: # python2.x assert type(msgId) in (str, unicode) assert type(user) in (str, unicode) assert type(text) in (str, unicode) else: # python3.x self.assertIs(type(msgId), str) self.assertIs(type(user), str) self.assertIs(type(text), str) if __name__ == '__main__': unittest.main()
from datetime import datetime import sys import unittest import btceapi class TestScraping(unittest.TestCase): def test_scrape_main_page(self): mainPage = btceapi.scrapeMainPage() for message in mainPage.messages: msgId, user, time, text = message assert type(time) is datetime if sys.version_info[0] == 2: # python2.x self.assertIn(type(msgId), (str, unicode)) self.assertIn(type(user), (str, unicode)) self.assertIn(type(text), (str, unicode)) else: # python3.x self.assertIs(type(msgId), str) self.assertIs(type(user), str) self.assertIs(type(text), str) if __name__ == '__main__': unittest.main() Fix for assertIn method not being present in Python 2.6. Undo prior erroneous commit (assertIn is missing, not assertIs).from datetime import datetime import sys import unittest import btceapi class TestScraping(unittest.TestCase): def test_scrape_main_page(self): mainPage = btceapi.scrapeMainPage() for message in mainPage.messages: msgId, user, time, text = message self.assertIs(type(time), datetime) if sys.version_info[0] == 2: # python2.x assert type(msgId) in (str, unicode) assert type(user) in (str, unicode) assert type(text) in (str, unicode) else: # python3.x self.assertIs(type(msgId), str) self.assertIs(type(user), str) self.assertIs(type(text), str) if __name__ == '__main__': unittest.main()
<commit_before>from datetime import datetime import sys import unittest import btceapi class TestScraping(unittest.TestCase): def test_scrape_main_page(self): mainPage = btceapi.scrapeMainPage() for message in mainPage.messages: msgId, user, time, text = message assert type(time) is datetime if sys.version_info[0] == 2: # python2.x self.assertIn(type(msgId), (str, unicode)) self.assertIn(type(user), (str, unicode)) self.assertIn(type(text), (str, unicode)) else: # python3.x self.assertIs(type(msgId), str) self.assertIs(type(user), str) self.assertIs(type(text), str) if __name__ == '__main__': unittest.main() <commit_msg>Fix for assertIn method not being present in Python 2.6. Undo prior erroneous commit (assertIn is missing, not assertIs).<commit_after>from datetime import datetime import sys import unittest import btceapi class TestScraping(unittest.TestCase): def test_scrape_main_page(self): mainPage = btceapi.scrapeMainPage() for message in mainPage.messages: msgId, user, time, text = message self.assertIs(type(time), datetime) if sys.version_info[0] == 2: # python2.x assert type(msgId) in (str, unicode) assert type(user) in (str, unicode) assert type(text) in (str, unicode) else: # python3.x self.assertIs(type(msgId), str) self.assertIs(type(user), str) self.assertIs(type(text), str) if __name__ == '__main__': unittest.main()
8a39404dc2b6e3acc0324d9c11619640e44f6bd5
tests/test_threads.py
tests/test_threads.py
from guv.green import threading, time def f1(): """A simple function """ print('Hello, world!') def f2(): """A simple function that sleeps for a short period of time """ time.sleep(0.1) class TestThread: def test_thread_create(self): t = threading.Thread(target=f1) assert t def test_thread_start(self): t = threading.Thread(target=f1) t.start() assert t def test_thread_join(self): t = threading.Thread(target=f1) t.start() t.join() assert t def test_thread_active(self): initial_count = threading.active_count() t = threading.Thread(target=f2) t.start() assert threading.active_count() > initial_count t.join() assert threading.active_count() == initial_count
from guv.green import threading, time def f1(): """A simple function """ print('Hello, world!') def f2(): """A simple function that sleeps for a short period of time """ time.sleep(0.1) class TestThread: def test_thread_create(self): t = threading.Thread(target=f1) assert 'green' in repr(t) def test_thread_start(self): t = threading.Thread(target=f1) assert 'green' in repr(t) t.start() def test_thread_join(self): t = threading.Thread(target=f1) assert 'green' in repr(t) t.start() t.join() def test_thread_active(self): initial_count = threading.active_count() t = threading.Thread(target=f2) assert 'green' in repr(t) t.start() assert threading.active_count() > initial_count t.join() assert threading.active_count() == initial_count
Check to ensure that we're dealing with "green" threads
Check to ensure that we're dealing with "green" threads
Python
mit
veegee/guv,veegee/guv
from guv.green import threading, time def f1(): """A simple function """ print('Hello, world!') def f2(): """A simple function that sleeps for a short period of time """ time.sleep(0.1) class TestThread: def test_thread_create(self): t = threading.Thread(target=f1) assert t def test_thread_start(self): t = threading.Thread(target=f1) t.start() assert t def test_thread_join(self): t = threading.Thread(target=f1) t.start() t.join() assert t def test_thread_active(self): initial_count = threading.active_count() t = threading.Thread(target=f2) t.start() assert threading.active_count() > initial_count t.join() assert threading.active_count() == initial_count Check to ensure that we're dealing with "green" threads
from guv.green import threading, time def f1(): """A simple function """ print('Hello, world!') def f2(): """A simple function that sleeps for a short period of time """ time.sleep(0.1) class TestThread: def test_thread_create(self): t = threading.Thread(target=f1) assert 'green' in repr(t) def test_thread_start(self): t = threading.Thread(target=f1) assert 'green' in repr(t) t.start() def test_thread_join(self): t = threading.Thread(target=f1) assert 'green' in repr(t) t.start() t.join() def test_thread_active(self): initial_count = threading.active_count() t = threading.Thread(target=f2) assert 'green' in repr(t) t.start() assert threading.active_count() > initial_count t.join() assert threading.active_count() == initial_count
<commit_before>from guv.green import threading, time def f1(): """A simple function """ print('Hello, world!') def f2(): """A simple function that sleeps for a short period of time """ time.sleep(0.1) class TestThread: def test_thread_create(self): t = threading.Thread(target=f1) assert t def test_thread_start(self): t = threading.Thread(target=f1) t.start() assert t def test_thread_join(self): t = threading.Thread(target=f1) t.start() t.join() assert t def test_thread_active(self): initial_count = threading.active_count() t = threading.Thread(target=f2) t.start() assert threading.active_count() > initial_count t.join() assert threading.active_count() == initial_count <commit_msg>Check to ensure that we're dealing with "green" threads<commit_after>
from guv.green import threading, time def f1(): """A simple function """ print('Hello, world!') def f2(): """A simple function that sleeps for a short period of time """ time.sleep(0.1) class TestThread: def test_thread_create(self): t = threading.Thread(target=f1) assert 'green' in repr(t) def test_thread_start(self): t = threading.Thread(target=f1) assert 'green' in repr(t) t.start() def test_thread_join(self): t = threading.Thread(target=f1) assert 'green' in repr(t) t.start() t.join() def test_thread_active(self): initial_count = threading.active_count() t = threading.Thread(target=f2) assert 'green' in repr(t) t.start() assert threading.active_count() > initial_count t.join() assert threading.active_count() == initial_count
from guv.green import threading, time def f1(): """A simple function """ print('Hello, world!') def f2(): """A simple function that sleeps for a short period of time """ time.sleep(0.1) class TestThread: def test_thread_create(self): t = threading.Thread(target=f1) assert t def test_thread_start(self): t = threading.Thread(target=f1) t.start() assert t def test_thread_join(self): t = threading.Thread(target=f1) t.start() t.join() assert t def test_thread_active(self): initial_count = threading.active_count() t = threading.Thread(target=f2) t.start() assert threading.active_count() > initial_count t.join() assert threading.active_count() == initial_count Check to ensure that we're dealing with "green" threadsfrom guv.green import threading, time def f1(): """A simple function """ print('Hello, world!') def f2(): """A simple function that sleeps for a short period of time """ time.sleep(0.1) class TestThread: def test_thread_create(self): t = threading.Thread(target=f1) assert 'green' in repr(t) def test_thread_start(self): t = threading.Thread(target=f1) assert 'green' in repr(t) t.start() def test_thread_join(self): t = threading.Thread(target=f1) assert 'green' in repr(t) t.start() t.join() def test_thread_active(self): initial_count = threading.active_count() t = threading.Thread(target=f2) assert 'green' in repr(t) t.start() assert threading.active_count() > initial_count t.join() assert threading.active_count() == initial_count
<commit_before>from guv.green import threading, time def f1(): """A simple function """ print('Hello, world!') def f2(): """A simple function that sleeps for a short period of time """ time.sleep(0.1) class TestThread: def test_thread_create(self): t = threading.Thread(target=f1) assert t def test_thread_start(self): t = threading.Thread(target=f1) t.start() assert t def test_thread_join(self): t = threading.Thread(target=f1) t.start() t.join() assert t def test_thread_active(self): initial_count = threading.active_count() t = threading.Thread(target=f2) t.start() assert threading.active_count() > initial_count t.join() assert threading.active_count() == initial_count <commit_msg>Check to ensure that we're dealing with "green" threads<commit_after>from guv.green import threading, time def f1(): """A simple function """ print('Hello, world!') def f2(): """A simple function that sleeps for a short period of time """ time.sleep(0.1) class TestThread: def test_thread_create(self): t = threading.Thread(target=f1) assert 'green' in repr(t) def test_thread_start(self): t = threading.Thread(target=f1) assert 'green' in repr(t) t.start() def test_thread_join(self): t = threading.Thread(target=f1) assert 'green' in repr(t) t.start() t.join() def test_thread_active(self): initial_count = threading.active_count() t = threading.Thread(target=f2) assert 'green' in repr(t) t.start() assert threading.active_count() > initial_count t.join() assert threading.active_count() == initial_count
d565fdab9cefc080ff3127f036c19e95cba73f6e
tests/test_udacity.py
tests/test_udacity.py
import unittest from mooc_aggregator_restful_api import udacity class UdacityTestCase(unittest.TestCase): ''' Unit Tests for module udacity ''' def setUp(self): self.udacity_test_object = udacity.UdacityAPI() def test_udacity_api_response(self): self.assertEqual(self.udacity_test_object.status_code(), 200) def tearDown(self): pass if __name__ == '__main__': unittest.main()
import unittest from mooc_aggregator_restful_api import udacity class UdacityTestCase(unittest.TestCase): ''' Unit Tests for module udacity ''' def setUp(self): self.udacity_test_object = udacity.UdacityAPI() def test_udacity_api_response(self): self.assertEqual(self.udacity_test_object.status_code(), 200) def test_udacity_api_mongofy_courses(self): course = self.udacity_test_object.mongofy_courses()[0] self.assertEqual(course['title'], 'Intro to Computer Science') def tearDown(self): pass if __name__ == '__main__': unittest.main()
Add unit test for mongofy_courses of udacity module
Add unit test for mongofy_courses of udacity module
Python
mit
ueg1990/mooc_aggregator_restful_api
import unittest from mooc_aggregator_restful_api import udacity class UdacityTestCase(unittest.TestCase): ''' Unit Tests for module udacity ''' def setUp(self): self.udacity_test_object = udacity.UdacityAPI() def test_udacity_api_response(self): self.assertEqual(self.udacity_test_object.status_code(), 200) def tearDown(self): pass if __name__ == '__main__': unittest.main() Add unit test for mongofy_courses of udacity module
import unittest from mooc_aggregator_restful_api import udacity class UdacityTestCase(unittest.TestCase): ''' Unit Tests for module udacity ''' def setUp(self): self.udacity_test_object = udacity.UdacityAPI() def test_udacity_api_response(self): self.assertEqual(self.udacity_test_object.status_code(), 200) def test_udacity_api_mongofy_courses(self): course = self.udacity_test_object.mongofy_courses()[0] self.assertEqual(course['title'], 'Intro to Computer Science') def tearDown(self): pass if __name__ == '__main__': unittest.main()
<commit_before>import unittest from mooc_aggregator_restful_api import udacity class UdacityTestCase(unittest.TestCase): ''' Unit Tests for module udacity ''' def setUp(self): self.udacity_test_object = udacity.UdacityAPI() def test_udacity_api_response(self): self.assertEqual(self.udacity_test_object.status_code(), 200) def tearDown(self): pass if __name__ == '__main__': unittest.main() <commit_msg>Add unit test for mongofy_courses of udacity module<commit_after>
import unittest from mooc_aggregator_restful_api import udacity class UdacityTestCase(unittest.TestCase): ''' Unit Tests for module udacity ''' def setUp(self): self.udacity_test_object = udacity.UdacityAPI() def test_udacity_api_response(self): self.assertEqual(self.udacity_test_object.status_code(), 200) def test_udacity_api_mongofy_courses(self): course = self.udacity_test_object.mongofy_courses()[0] self.assertEqual(course['title'], 'Intro to Computer Science') def tearDown(self): pass if __name__ == '__main__': unittest.main()
import unittest from mooc_aggregator_restful_api import udacity class UdacityTestCase(unittest.TestCase): ''' Unit Tests for module udacity ''' def setUp(self): self.udacity_test_object = udacity.UdacityAPI() def test_udacity_api_response(self): self.assertEqual(self.udacity_test_object.status_code(), 200) def tearDown(self): pass if __name__ == '__main__': unittest.main() Add unit test for mongofy_courses of udacity moduleimport unittest from mooc_aggregator_restful_api import udacity class UdacityTestCase(unittest.TestCase): ''' Unit Tests for module udacity ''' def setUp(self): self.udacity_test_object = udacity.UdacityAPI() def test_udacity_api_response(self): self.assertEqual(self.udacity_test_object.status_code(), 200) def test_udacity_api_mongofy_courses(self): course = self.udacity_test_object.mongofy_courses()[0] self.assertEqual(course['title'], 'Intro to Computer Science') def tearDown(self): pass if __name__ == '__main__': unittest.main()
<commit_before>import unittest from mooc_aggregator_restful_api import udacity class UdacityTestCase(unittest.TestCase): ''' Unit Tests for module udacity ''' def setUp(self): self.udacity_test_object = udacity.UdacityAPI() def test_udacity_api_response(self): self.assertEqual(self.udacity_test_object.status_code(), 200) def tearDown(self): pass if __name__ == '__main__': unittest.main() <commit_msg>Add unit test for mongofy_courses of udacity module<commit_after>import unittest from mooc_aggregator_restful_api import udacity class UdacityTestCase(unittest.TestCase): ''' Unit Tests for module udacity ''' def setUp(self): self.udacity_test_object = udacity.UdacityAPI() def test_udacity_api_response(self): self.assertEqual(self.udacity_test_object.status_code(), 200) def test_udacity_api_mongofy_courses(self): course = self.udacity_test_object.mongofy_courses()[0] self.assertEqual(course['title'], 'Intro to Computer Science') def tearDown(self): pass if __name__ == '__main__': unittest.main()
badbe38249297372c14cde1c58501854ccda413a
uncertainty/lib/nlp/__init__.py
uncertainty/lib/nlp/__init__.py
import os VERBS_PATH = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'verbs.txt' )
from pkg_resources import resource_filename VERBS_PATH = resource_filename('uncertainty.lib.nlp', 'verbs.txt')
Use pkg_resources to resolve file paths
Use pkg_resources to resolve file paths
Python
mit
meyersbs/uncertainty
import os VERBS_PATH = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'verbs.txt' ) Use pkg_resources to resolve file paths
from pkg_resources import resource_filename VERBS_PATH = resource_filename('uncertainty.lib.nlp', 'verbs.txt')
<commit_before>import os VERBS_PATH = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'verbs.txt' ) <commit_msg>Use pkg_resources to resolve file paths<commit_after>
from pkg_resources import resource_filename VERBS_PATH = resource_filename('uncertainty.lib.nlp', 'verbs.txt')
import os VERBS_PATH = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'verbs.txt' ) Use pkg_resources to resolve file pathsfrom pkg_resources import resource_filename VERBS_PATH = resource_filename('uncertainty.lib.nlp', 'verbs.txt')
<commit_before>import os VERBS_PATH = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'verbs.txt' ) <commit_msg>Use pkg_resources to resolve file paths<commit_after>from pkg_resources import resource_filename VERBS_PATH = resource_filename('uncertainty.lib.nlp', 'verbs.txt')
0cf45ad47d8b5e6e6df329990e76c4e5702f8e6c
django_lightweight_queue/app_settings.py
django_lightweight_queue/app_settings.py
from django.conf import settings def setting(suffix, default): return getattr(settings, 'LIGHTWEIGHT_QUEUE_%s' % suffix, default) BACKEND = setting('BACKED', 'django_lightweight_queue.backends.synchronous.SynchronousBackend') MIDDLEWARE = setting('MIDDLEWARE', ( 'django_lightweight_queue.middleware.logging.LoggingMiddleware', ))
from django.conf import settings def setting(suffix, default): return getattr(settings, 'LIGHTWEIGHT_QUEUE_%s' % suffix, default) BACKEND = setting('BACKEND', 'django_lightweight_queue.backends.synchronous.SynchronousBackend') MIDDLEWARE = setting('MIDDLEWARE', ( 'django_lightweight_queue.middleware.logging.LoggingMiddleware', ))
Correct typo in getting BACKEND.
Correct typo in getting BACKEND. Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com>
Python
bsd-3-clause
prophile/django-lightweight-queue,thread/django-lightweight-queue,lamby/django-lightweight-queue,thread/django-lightweight-queue,prophile/django-lightweight-queue
from django.conf import settings def setting(suffix, default): return getattr(settings, 'LIGHTWEIGHT_QUEUE_%s' % suffix, default) BACKEND = setting('BACKED', 'django_lightweight_queue.backends.synchronous.SynchronousBackend') MIDDLEWARE = setting('MIDDLEWARE', ( 'django_lightweight_queue.middleware.logging.LoggingMiddleware', )) Correct typo in getting BACKEND. Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com>
from django.conf import settings def setting(suffix, default): return getattr(settings, 'LIGHTWEIGHT_QUEUE_%s' % suffix, default) BACKEND = setting('BACKEND', 'django_lightweight_queue.backends.synchronous.SynchronousBackend') MIDDLEWARE = setting('MIDDLEWARE', ( 'django_lightweight_queue.middleware.logging.LoggingMiddleware', ))
<commit_before>from django.conf import settings def setting(suffix, default): return getattr(settings, 'LIGHTWEIGHT_QUEUE_%s' % suffix, default) BACKEND = setting('BACKED', 'django_lightweight_queue.backends.synchronous.SynchronousBackend') MIDDLEWARE = setting('MIDDLEWARE', ( 'django_lightweight_queue.middleware.logging.LoggingMiddleware', )) <commit_msg>Correct typo in getting BACKEND. Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com><commit_after>
from django.conf import settings def setting(suffix, default): return getattr(settings, 'LIGHTWEIGHT_QUEUE_%s' % suffix, default) BACKEND = setting('BACKEND', 'django_lightweight_queue.backends.synchronous.SynchronousBackend') MIDDLEWARE = setting('MIDDLEWARE', ( 'django_lightweight_queue.middleware.logging.LoggingMiddleware', ))
from django.conf import settings def setting(suffix, default): return getattr(settings, 'LIGHTWEIGHT_QUEUE_%s' % suffix, default) BACKEND = setting('BACKED', 'django_lightweight_queue.backends.synchronous.SynchronousBackend') MIDDLEWARE = setting('MIDDLEWARE', ( 'django_lightweight_queue.middleware.logging.LoggingMiddleware', )) Correct typo in getting BACKEND. Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com>from django.conf import settings def setting(suffix, default): return getattr(settings, 'LIGHTWEIGHT_QUEUE_%s' % suffix, default) BACKEND = setting('BACKEND', 'django_lightweight_queue.backends.synchronous.SynchronousBackend') MIDDLEWARE = setting('MIDDLEWARE', ( 'django_lightweight_queue.middleware.logging.LoggingMiddleware', ))
<commit_before>from django.conf import settings def setting(suffix, default): return getattr(settings, 'LIGHTWEIGHT_QUEUE_%s' % suffix, default) BACKEND = setting('BACKED', 'django_lightweight_queue.backends.synchronous.SynchronousBackend') MIDDLEWARE = setting('MIDDLEWARE', ( 'django_lightweight_queue.middleware.logging.LoggingMiddleware', )) <commit_msg>Correct typo in getting BACKEND. Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com><commit_after>from django.conf import settings def setting(suffix, default): return getattr(settings, 'LIGHTWEIGHT_QUEUE_%s' % suffix, default) BACKEND = setting('BACKEND', 'django_lightweight_queue.backends.synchronous.SynchronousBackend') MIDDLEWARE = setting('MIDDLEWARE', ( 'django_lightweight_queue.middleware.logging.LoggingMiddleware', ))
42f9c3ae74073fd55702e3ffccd5b4b820d86c22
bpython/test/test_keys.py
bpython/test/test_keys.py
#!/usr/bin/env python import unittest import bpython.keys as keys class TestKeys(unittest.TestCase): def test_keymap_map(self): """Verify KeyMap.map being a dictionary with the correct length.""" self.assertEqual(len(keys.key_dispatch.map), 43) def test_keymap_setitem(self): """Verify keys.KeyMap correctly setting items.""" keys.key_dispatch['simon'] = 'awesome'; self.assertEqual(keys.key_dispatch['simon'], 'awesome') def test_keymap_delitem(self): """Verify keys.KeyMap correctly removing items.""" keys.key_dispatch['simon'] = 'awesome' del keys.key_dispatch['simon'] if 'simon' in keys.key_dispatch.map: raise Exception('Key still exists in dictionary') def test_keymap_getitem(self): """Verify keys.KeyMap correctly looking up items.""" self.assertEqual(keys.key_dispatch['C-['], (chr(27), '^[')) self.assertEqual(keys.key_dispatch['F11'], ('KEY_F(11)',)) self.assertEqual(keys.key_dispatch['C-a'], ('\x01', '^A')) def test_keymap_keyerror(self): """Verify keys.KeyMap raising KeyError when getting undefined key""" def raiser(): keys.key_dispatch['C-asdf'] keys.key_dispatch['C-qwerty'] self.assertRaises(KeyError, raiser); if __name__ == '__main__': unittest.main()
#!/usr/bin/env python import unittest import bpython.keys as keys class TestKeys(unittest.TestCase): def test_keymap_getitem(self): """Verify keys.KeyMap correctly looking up items.""" self.assertEqual(keys.key_dispatch['C-['], (chr(27), '^[')) self.assertEqual(keys.key_dispatch['F11'], ('KEY_F(11)',)) self.assertEqual(keys.key_dispatch['C-a'], ('\x01', '^A')) def test_keymap_keyerror(self): """Verify keys.KeyMap raising KeyError when getting undefined key""" def raiser(): keys.key_dispatch['C-asdf'] keys.key_dispatch['C-qwerty'] self.assertRaises(KeyError, raiser); if __name__ == '__main__': unittest.main()
Add __delitem__, and dict length checking to tests for keys
Add __delitem__, and dict length checking to tests for keys
Python
mit
5monkeys/bpython
#!/usr/bin/env python import unittest import bpython.keys as keys class TestKeys(unittest.TestCase): def test_keymap_map(self): """Verify KeyMap.map being a dictionary with the correct length.""" self.assertEqual(len(keys.key_dispatch.map), 43) def test_keymap_setitem(self): """Verify keys.KeyMap correctly setting items.""" keys.key_dispatch['simon'] = 'awesome'; self.assertEqual(keys.key_dispatch['simon'], 'awesome') def test_keymap_delitem(self): """Verify keys.KeyMap correctly removing items.""" keys.key_dispatch['simon'] = 'awesome' del keys.key_dispatch['simon'] if 'simon' in keys.key_dispatch.map: raise Exception('Key still exists in dictionary') def test_keymap_getitem(self): """Verify keys.KeyMap correctly looking up items.""" self.assertEqual(keys.key_dispatch['C-['], (chr(27), '^[')) self.assertEqual(keys.key_dispatch['F11'], ('KEY_F(11)',)) self.assertEqual(keys.key_dispatch['C-a'], ('\x01', '^A')) def test_keymap_keyerror(self): """Verify keys.KeyMap raising KeyError when getting undefined key""" def raiser(): keys.key_dispatch['C-asdf'] keys.key_dispatch['C-qwerty'] self.assertRaises(KeyError, raiser); if __name__ == '__main__': unittest.main() Add __delitem__, and dict length checking to tests for keys
#!/usr/bin/env python import unittest import bpython.keys as keys class TestKeys(unittest.TestCase): def test_keymap_getitem(self): """Verify keys.KeyMap correctly looking up items.""" self.assertEqual(keys.key_dispatch['C-['], (chr(27), '^[')) self.assertEqual(keys.key_dispatch['F11'], ('KEY_F(11)',)) self.assertEqual(keys.key_dispatch['C-a'], ('\x01', '^A')) def test_keymap_keyerror(self): """Verify keys.KeyMap raising KeyError when getting undefined key""" def raiser(): keys.key_dispatch['C-asdf'] keys.key_dispatch['C-qwerty'] self.assertRaises(KeyError, raiser); if __name__ == '__main__': unittest.main()
<commit_before>#!/usr/bin/env python import unittest import bpython.keys as keys class TestKeys(unittest.TestCase): def test_keymap_map(self): """Verify KeyMap.map being a dictionary with the correct length.""" self.assertEqual(len(keys.key_dispatch.map), 43) def test_keymap_setitem(self): """Verify keys.KeyMap correctly setting items.""" keys.key_dispatch['simon'] = 'awesome'; self.assertEqual(keys.key_dispatch['simon'], 'awesome') def test_keymap_delitem(self): """Verify keys.KeyMap correctly removing items.""" keys.key_dispatch['simon'] = 'awesome' del keys.key_dispatch['simon'] if 'simon' in keys.key_dispatch.map: raise Exception('Key still exists in dictionary') def test_keymap_getitem(self): """Verify keys.KeyMap correctly looking up items.""" self.assertEqual(keys.key_dispatch['C-['], (chr(27), '^[')) self.assertEqual(keys.key_dispatch['F11'], ('KEY_F(11)',)) self.assertEqual(keys.key_dispatch['C-a'], ('\x01', '^A')) def test_keymap_keyerror(self): """Verify keys.KeyMap raising KeyError when getting undefined key""" def raiser(): keys.key_dispatch['C-asdf'] keys.key_dispatch['C-qwerty'] self.assertRaises(KeyError, raiser); if __name__ == '__main__': unittest.main() <commit_msg>Add __delitem__, and dict length checking to tests for keys<commit_after>
#!/usr/bin/env python import unittest import bpython.keys as keys class TestKeys(unittest.TestCase): def test_keymap_getitem(self): """Verify keys.KeyMap correctly looking up items.""" self.assertEqual(keys.key_dispatch['C-['], (chr(27), '^[')) self.assertEqual(keys.key_dispatch['F11'], ('KEY_F(11)',)) self.assertEqual(keys.key_dispatch['C-a'], ('\x01', '^A')) def test_keymap_keyerror(self): """Verify keys.KeyMap raising KeyError when getting undefined key""" def raiser(): keys.key_dispatch['C-asdf'] keys.key_dispatch['C-qwerty'] self.assertRaises(KeyError, raiser); if __name__ == '__main__': unittest.main()
#!/usr/bin/env python import unittest import bpython.keys as keys class TestKeys(unittest.TestCase): def test_keymap_map(self): """Verify KeyMap.map being a dictionary with the correct length.""" self.assertEqual(len(keys.key_dispatch.map), 43) def test_keymap_setitem(self): """Verify keys.KeyMap correctly setting items.""" keys.key_dispatch['simon'] = 'awesome'; self.assertEqual(keys.key_dispatch['simon'], 'awesome') def test_keymap_delitem(self): """Verify keys.KeyMap correctly removing items.""" keys.key_dispatch['simon'] = 'awesome' del keys.key_dispatch['simon'] if 'simon' in keys.key_dispatch.map: raise Exception('Key still exists in dictionary') def test_keymap_getitem(self): """Verify keys.KeyMap correctly looking up items.""" self.assertEqual(keys.key_dispatch['C-['], (chr(27), '^[')) self.assertEqual(keys.key_dispatch['F11'], ('KEY_F(11)',)) self.assertEqual(keys.key_dispatch['C-a'], ('\x01', '^A')) def test_keymap_keyerror(self): """Verify keys.KeyMap raising KeyError when getting undefined key""" def raiser(): keys.key_dispatch['C-asdf'] keys.key_dispatch['C-qwerty'] self.assertRaises(KeyError, raiser); if __name__ == '__main__': unittest.main() Add __delitem__, and dict length checking to tests for keys#!/usr/bin/env python import unittest import bpython.keys as keys class TestKeys(unittest.TestCase): def test_keymap_getitem(self): """Verify keys.KeyMap correctly looking up items.""" self.assertEqual(keys.key_dispatch['C-['], (chr(27), '^[')) self.assertEqual(keys.key_dispatch['F11'], ('KEY_F(11)',)) self.assertEqual(keys.key_dispatch['C-a'], ('\x01', '^A')) def test_keymap_keyerror(self): """Verify keys.KeyMap raising KeyError when getting undefined key""" def raiser(): keys.key_dispatch['C-asdf'] keys.key_dispatch['C-qwerty'] self.assertRaises(KeyError, raiser); if __name__ == '__main__': unittest.main()
<commit_before>#!/usr/bin/env python import unittest import bpython.keys as keys class TestKeys(unittest.TestCase): def test_keymap_map(self): """Verify KeyMap.map being a dictionary with the correct length.""" self.assertEqual(len(keys.key_dispatch.map), 43) def test_keymap_setitem(self): """Verify keys.KeyMap correctly setting items.""" keys.key_dispatch['simon'] = 'awesome'; self.assertEqual(keys.key_dispatch['simon'], 'awesome') def test_keymap_delitem(self): """Verify keys.KeyMap correctly removing items.""" keys.key_dispatch['simon'] = 'awesome' del keys.key_dispatch['simon'] if 'simon' in keys.key_dispatch.map: raise Exception('Key still exists in dictionary') def test_keymap_getitem(self): """Verify keys.KeyMap correctly looking up items.""" self.assertEqual(keys.key_dispatch['C-['], (chr(27), '^[')) self.assertEqual(keys.key_dispatch['F11'], ('KEY_F(11)',)) self.assertEqual(keys.key_dispatch['C-a'], ('\x01', '^A')) def test_keymap_keyerror(self): """Verify keys.KeyMap raising KeyError when getting undefined key""" def raiser(): keys.key_dispatch['C-asdf'] keys.key_dispatch['C-qwerty'] self.assertRaises(KeyError, raiser); if __name__ == '__main__': unittest.main() <commit_msg>Add __delitem__, and dict length checking to tests for keys<commit_after>#!/usr/bin/env python import unittest import bpython.keys as keys class TestKeys(unittest.TestCase): def test_keymap_getitem(self): """Verify keys.KeyMap correctly looking up items.""" self.assertEqual(keys.key_dispatch['C-['], (chr(27), '^[')) self.assertEqual(keys.key_dispatch['F11'], ('KEY_F(11)',)) self.assertEqual(keys.key_dispatch['C-a'], ('\x01', '^A')) def test_keymap_keyerror(self): """Verify keys.KeyMap raising KeyError when getting undefined key""" def raiser(): keys.key_dispatch['C-asdf'] keys.key_dispatch['C-qwerty'] self.assertRaises(KeyError, raiser); if __name__ == '__main__': unittest.main()
91951e85caf1b928224dba1ecc33a59957187dff
tkp/tests/__init__.py
tkp/tests/__init__.py
import unittest testfiles = [ 'tkp.tests.accessors', 'tkp.tests.classification', 'tkp.tests.config', 'tkp.tests.coordinates', 'tkp.tests.database', 'tkp.tests.dataset', 'tkp.tests.FDR', 'tkp.tests.feature_extraction', 'tkp.tests.gaussian', 'tkp.tests.L15_12h_const', 'tkp.tests.sigmaclip', 'tkp.tests.source_measurements', 'tkp.tests.wcs', ] # Pyrap is required for AIPS++ image support, but # not necessary for the rest of the library. try: import pyrap except: pass else: testfiles.append('tkp.tests.aipsppimage')
import unittest testfiles = [ 'tkp.tests.accessors', 'tkp.tests.classification', 'tkp.tests.config', 'tkp.tests.coordinates', 'tkp.tests.database', 'tkp.tests.dataset', 'tkp.tests.FDR', 'tkp.tests.feature_extraction', 'tkp.tests.gaussian', 'tkp.tests.L15_12h_const', 'tkp.tests.sigmaclip', 'tkp.tests.source_measurements', 'tkp.tests.wcs', 'tkp.tests.aipsppimage' ]
Remove special-casing of aipsppimage test
Remove special-casing of aipsppimage test We have other dependencies on pyrap too... git-svn-id: 71bcaaf8fac6301ed959c5094abb905057e55e2d@2123 2b73c8c1-3922-0410-90dd-bc0a5c6f2ac6
Python
bsd-2-clause
bartscheers/tkp,mkuiack/tkp,transientskp/tkp,transientskp/tkp,mkuiack/tkp,bartscheers/tkp
import unittest testfiles = [ 'tkp.tests.accessors', 'tkp.tests.classification', 'tkp.tests.config', 'tkp.tests.coordinates', 'tkp.tests.database', 'tkp.tests.dataset', 'tkp.tests.FDR', 'tkp.tests.feature_extraction', 'tkp.tests.gaussian', 'tkp.tests.L15_12h_const', 'tkp.tests.sigmaclip', 'tkp.tests.source_measurements', 'tkp.tests.wcs', ] # Pyrap is required for AIPS++ image support, but # not necessary for the rest of the library. try: import pyrap except: pass else: testfiles.append('tkp.tests.aipsppimage') Remove special-casing of aipsppimage test We have other dependencies on pyrap too... git-svn-id: 71bcaaf8fac6301ed959c5094abb905057e55e2d@2123 2b73c8c1-3922-0410-90dd-bc0a5c6f2ac6
import unittest testfiles = [ 'tkp.tests.accessors', 'tkp.tests.classification', 'tkp.tests.config', 'tkp.tests.coordinates', 'tkp.tests.database', 'tkp.tests.dataset', 'tkp.tests.FDR', 'tkp.tests.feature_extraction', 'tkp.tests.gaussian', 'tkp.tests.L15_12h_const', 'tkp.tests.sigmaclip', 'tkp.tests.source_measurements', 'tkp.tests.wcs', 'tkp.tests.aipsppimage' ]
<commit_before>import unittest testfiles = [ 'tkp.tests.accessors', 'tkp.tests.classification', 'tkp.tests.config', 'tkp.tests.coordinates', 'tkp.tests.database', 'tkp.tests.dataset', 'tkp.tests.FDR', 'tkp.tests.feature_extraction', 'tkp.tests.gaussian', 'tkp.tests.L15_12h_const', 'tkp.tests.sigmaclip', 'tkp.tests.source_measurements', 'tkp.tests.wcs', ] # Pyrap is required for AIPS++ image support, but # not necessary for the rest of the library. try: import pyrap except: pass else: testfiles.append('tkp.tests.aipsppimage') <commit_msg>Remove special-casing of aipsppimage test We have other dependencies on pyrap too... git-svn-id: 71bcaaf8fac6301ed959c5094abb905057e55e2d@2123 2b73c8c1-3922-0410-90dd-bc0a5c6f2ac6<commit_after>
import unittest testfiles = [ 'tkp.tests.accessors', 'tkp.tests.classification', 'tkp.tests.config', 'tkp.tests.coordinates', 'tkp.tests.database', 'tkp.tests.dataset', 'tkp.tests.FDR', 'tkp.tests.feature_extraction', 'tkp.tests.gaussian', 'tkp.tests.L15_12h_const', 'tkp.tests.sigmaclip', 'tkp.tests.source_measurements', 'tkp.tests.wcs', 'tkp.tests.aipsppimage' ]
import unittest testfiles = [ 'tkp.tests.accessors', 'tkp.tests.classification', 'tkp.tests.config', 'tkp.tests.coordinates', 'tkp.tests.database', 'tkp.tests.dataset', 'tkp.tests.FDR', 'tkp.tests.feature_extraction', 'tkp.tests.gaussian', 'tkp.tests.L15_12h_const', 'tkp.tests.sigmaclip', 'tkp.tests.source_measurements', 'tkp.tests.wcs', ] # Pyrap is required for AIPS++ image support, but # not necessary for the rest of the library. try: import pyrap except: pass else: testfiles.append('tkp.tests.aipsppimage') Remove special-casing of aipsppimage test We have other dependencies on pyrap too... git-svn-id: 71bcaaf8fac6301ed959c5094abb905057e55e2d@2123 2b73c8c1-3922-0410-90dd-bc0a5c6f2ac6import unittest testfiles = [ 'tkp.tests.accessors', 'tkp.tests.classification', 'tkp.tests.config', 'tkp.tests.coordinates', 'tkp.tests.database', 'tkp.tests.dataset', 'tkp.tests.FDR', 'tkp.tests.feature_extraction', 'tkp.tests.gaussian', 'tkp.tests.L15_12h_const', 'tkp.tests.sigmaclip', 'tkp.tests.source_measurements', 'tkp.tests.wcs', 'tkp.tests.aipsppimage' ]
<commit_before>import unittest testfiles = [ 'tkp.tests.accessors', 'tkp.tests.classification', 'tkp.tests.config', 'tkp.tests.coordinates', 'tkp.tests.database', 'tkp.tests.dataset', 'tkp.tests.FDR', 'tkp.tests.feature_extraction', 'tkp.tests.gaussian', 'tkp.tests.L15_12h_const', 'tkp.tests.sigmaclip', 'tkp.tests.source_measurements', 'tkp.tests.wcs', ] # Pyrap is required for AIPS++ image support, but # not necessary for the rest of the library. try: import pyrap except: pass else: testfiles.append('tkp.tests.aipsppimage') <commit_msg>Remove special-casing of aipsppimage test We have other dependencies on pyrap too... git-svn-id: 71bcaaf8fac6301ed959c5094abb905057e55e2d@2123 2b73c8c1-3922-0410-90dd-bc0a5c6f2ac6<commit_after>import unittest testfiles = [ 'tkp.tests.accessors', 'tkp.tests.classification', 'tkp.tests.config', 'tkp.tests.coordinates', 'tkp.tests.database', 'tkp.tests.dataset', 'tkp.tests.FDR', 'tkp.tests.feature_extraction', 'tkp.tests.gaussian', 'tkp.tests.L15_12h_const', 'tkp.tests.sigmaclip', 'tkp.tests.source_measurements', 'tkp.tests.wcs', 'tkp.tests.aipsppimage' ]
60f696c07b64909ccaee8d90eff54ac6301b7a71
buildbox/app.py
buildbox/app.py
from sqlalchemy import create_engine from tornado.web import Application, url from buildbox.config import settings from buildbox.db.backend import Backend from buildbox.web.frontend.build_list import BuildListHandler from buildbox.web.frontend.build_details import BuildDetailsHandler application = Application( [ url(r"/", BuildListHandler, name='build-list'), url(r"/projects/([^/]+)/build/([^/]+)/", BuildDetailsHandler, name='build-details'), ], static_path=settings['static_path'], template_path=settings['template_path'], debug=settings['debug'], sqla_engine=create_engine( settings['database'], # pool_size=options.mysql_poolsize, # pool_recycle=3600, echo=settings['debug'], echo_pool=settings['debug'], ), ) db = Backend.instance()
from sqlalchemy import create_engine from tornado.web import Application, url from buildbox.config import settings from buildbox.db.backend import Backend from buildbox.web.frontend.build_list import BuildListHandler from buildbox.web.frontend.build_details import BuildDetailsHandler application = Application( [ url(r"/", BuildListHandler, name='build-list'), url(r"/projects/([^/]+)/build/([^/]+)/", BuildDetailsHandler, name='build-details'), ], static_path=settings['static_path'], template_path=settings['template_path'], debug=settings['debug'], sqla_engine=create_engine( settings['database'], # pool_size=options.mysql_poolsize, # pool_recycle=3600, # echo=settings['debug'], # echo_pool=settings['debug'], ), ) db = Backend.instance()
Disable debug output of sqla
Disable debug output of sqla
Python
apache-2.0
bowlofstew/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes
from sqlalchemy import create_engine from tornado.web import Application, url from buildbox.config import settings from buildbox.db.backend import Backend from buildbox.web.frontend.build_list import BuildListHandler from buildbox.web.frontend.build_details import BuildDetailsHandler application = Application( [ url(r"/", BuildListHandler, name='build-list'), url(r"/projects/([^/]+)/build/([^/]+)/", BuildDetailsHandler, name='build-details'), ], static_path=settings['static_path'], template_path=settings['template_path'], debug=settings['debug'], sqla_engine=create_engine( settings['database'], # pool_size=options.mysql_poolsize, # pool_recycle=3600, echo=settings['debug'], echo_pool=settings['debug'], ), ) db = Backend.instance() Disable debug output of sqla
from sqlalchemy import create_engine from tornado.web import Application, url from buildbox.config import settings from buildbox.db.backend import Backend from buildbox.web.frontend.build_list import BuildListHandler from buildbox.web.frontend.build_details import BuildDetailsHandler application = Application( [ url(r"/", BuildListHandler, name='build-list'), url(r"/projects/([^/]+)/build/([^/]+)/", BuildDetailsHandler, name='build-details'), ], static_path=settings['static_path'], template_path=settings['template_path'], debug=settings['debug'], sqla_engine=create_engine( settings['database'], # pool_size=options.mysql_poolsize, # pool_recycle=3600, # echo=settings['debug'], # echo_pool=settings['debug'], ), ) db = Backend.instance()
<commit_before>from sqlalchemy import create_engine from tornado.web import Application, url from buildbox.config import settings from buildbox.db.backend import Backend from buildbox.web.frontend.build_list import BuildListHandler from buildbox.web.frontend.build_details import BuildDetailsHandler application = Application( [ url(r"/", BuildListHandler, name='build-list'), url(r"/projects/([^/]+)/build/([^/]+)/", BuildDetailsHandler, name='build-details'), ], static_path=settings['static_path'], template_path=settings['template_path'], debug=settings['debug'], sqla_engine=create_engine( settings['database'], # pool_size=options.mysql_poolsize, # pool_recycle=3600, echo=settings['debug'], echo_pool=settings['debug'], ), ) db = Backend.instance() <commit_msg>Disable debug output of sqla<commit_after>
from sqlalchemy import create_engine from tornado.web import Application, url from buildbox.config import settings from buildbox.db.backend import Backend from buildbox.web.frontend.build_list import BuildListHandler from buildbox.web.frontend.build_details import BuildDetailsHandler application = Application( [ url(r"/", BuildListHandler, name='build-list'), url(r"/projects/([^/]+)/build/([^/]+)/", BuildDetailsHandler, name='build-details'), ], static_path=settings['static_path'], template_path=settings['template_path'], debug=settings['debug'], sqla_engine=create_engine( settings['database'], # pool_size=options.mysql_poolsize, # pool_recycle=3600, # echo=settings['debug'], # echo_pool=settings['debug'], ), ) db = Backend.instance()
from sqlalchemy import create_engine from tornado.web import Application, url from buildbox.config import settings from buildbox.db.backend import Backend from buildbox.web.frontend.build_list import BuildListHandler from buildbox.web.frontend.build_details import BuildDetailsHandler application = Application( [ url(r"/", BuildListHandler, name='build-list'), url(r"/projects/([^/]+)/build/([^/]+)/", BuildDetailsHandler, name='build-details'), ], static_path=settings['static_path'], template_path=settings['template_path'], debug=settings['debug'], sqla_engine=create_engine( settings['database'], # pool_size=options.mysql_poolsize, # pool_recycle=3600, echo=settings['debug'], echo_pool=settings['debug'], ), ) db = Backend.instance() Disable debug output of sqlafrom sqlalchemy import create_engine from tornado.web import Application, url from buildbox.config import settings from buildbox.db.backend import Backend from buildbox.web.frontend.build_list import BuildListHandler from buildbox.web.frontend.build_details import BuildDetailsHandler application = Application( [ url(r"/", BuildListHandler, name='build-list'), url(r"/projects/([^/]+)/build/([^/]+)/", BuildDetailsHandler, name='build-details'), ], static_path=settings['static_path'], template_path=settings['template_path'], debug=settings['debug'], sqla_engine=create_engine( settings['database'], # pool_size=options.mysql_poolsize, # pool_recycle=3600, # echo=settings['debug'], # echo_pool=settings['debug'], ), ) db = Backend.instance()
<commit_before>from sqlalchemy import create_engine from tornado.web import Application, url from buildbox.config import settings from buildbox.db.backend import Backend from buildbox.web.frontend.build_list import BuildListHandler from buildbox.web.frontend.build_details import BuildDetailsHandler application = Application( [ url(r"/", BuildListHandler, name='build-list'), url(r"/projects/([^/]+)/build/([^/]+)/", BuildDetailsHandler, name='build-details'), ], static_path=settings['static_path'], template_path=settings['template_path'], debug=settings['debug'], sqla_engine=create_engine( settings['database'], # pool_size=options.mysql_poolsize, # pool_recycle=3600, echo=settings['debug'], echo_pool=settings['debug'], ), ) db = Backend.instance() <commit_msg>Disable debug output of sqla<commit_after>from sqlalchemy import create_engine from tornado.web import Application, url from buildbox.config import settings from buildbox.db.backend import Backend from buildbox.web.frontend.build_list import BuildListHandler from buildbox.web.frontend.build_details import BuildDetailsHandler application = Application( [ url(r"/", BuildListHandler, name='build-list'), url(r"/projects/([^/]+)/build/([^/]+)/", BuildDetailsHandler, name='build-details'), ], static_path=settings['static_path'], template_path=settings['template_path'], debug=settings['debug'], sqla_engine=create_engine( settings['database'], # pool_size=options.mysql_poolsize, # pool_recycle=3600, # echo=settings['debug'], # echo_pool=settings['debug'], ), ) db = Backend.instance()
68b2536c53426d9b624527f7ef0eb5b22c68986e
helusers/models.py
helusers/models.py
import uuid import logging from django.db import models from django.contrib.auth.models import AbstractUser as DjangoAbstractUser logger = logging.getLogger(__name__) class AbstractUser(DjangoAbstractUser): uuid = models.UUIDField(primary_key=True) department_name = models.CharField(max_length=50, null=True, blank=True) def save(self, *args, **kwargs): if self.uuid is None: self.uuid = uuid.uuid1() return super(AbstractUser, self).save(*args, **kwargs) class Meta: abstract = True
import uuid import logging from django.db import models from django.contrib.auth.models import AbstractUser as DjangoAbstractUser logger = logging.getLogger(__name__) class AbstractUser(DjangoAbstractUser): uuid = models.UUIDField() department_name = models.CharField(max_length=50, null=True, blank=True) def save(self, *args, **kwargs): if self.uuid is None: self.uuid = uuid.uuid1() return super(AbstractUser, self).save(*args, **kwargs) class Meta: abstract = True
Make UUID a non-pk to work around problems in 3rd party apps
Make UUID a non-pk to work around problems in 3rd party apps
Python
bsd-2-clause
City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers
import uuid import logging from django.db import models from django.contrib.auth.models import AbstractUser as DjangoAbstractUser logger = logging.getLogger(__name__) class AbstractUser(DjangoAbstractUser): uuid = models.UUIDField(primary_key=True) department_name = models.CharField(max_length=50, null=True, blank=True) def save(self, *args, **kwargs): if self.uuid is None: self.uuid = uuid.uuid1() return super(AbstractUser, self).save(*args, **kwargs) class Meta: abstract = True Make UUID a non-pk to work around problems in 3rd party apps
import uuid import logging from django.db import models from django.contrib.auth.models import AbstractUser as DjangoAbstractUser logger = logging.getLogger(__name__) class AbstractUser(DjangoAbstractUser): uuid = models.UUIDField() department_name = models.CharField(max_length=50, null=True, blank=True) def save(self, *args, **kwargs): if self.uuid is None: self.uuid = uuid.uuid1() return super(AbstractUser, self).save(*args, **kwargs) class Meta: abstract = True
<commit_before>import uuid import logging from django.db import models from django.contrib.auth.models import AbstractUser as DjangoAbstractUser logger = logging.getLogger(__name__) class AbstractUser(DjangoAbstractUser): uuid = models.UUIDField(primary_key=True) department_name = models.CharField(max_length=50, null=True, blank=True) def save(self, *args, **kwargs): if self.uuid is None: self.uuid = uuid.uuid1() return super(AbstractUser, self).save(*args, **kwargs) class Meta: abstract = True <commit_msg>Make UUID a non-pk to work around problems in 3rd party apps<commit_after>
import uuid import logging from django.db import models from django.contrib.auth.models import AbstractUser as DjangoAbstractUser logger = logging.getLogger(__name__) class AbstractUser(DjangoAbstractUser): uuid = models.UUIDField() department_name = models.CharField(max_length=50, null=True, blank=True) def save(self, *args, **kwargs): if self.uuid is None: self.uuid = uuid.uuid1() return super(AbstractUser, self).save(*args, **kwargs) class Meta: abstract = True
import uuid import logging from django.db import models from django.contrib.auth.models import AbstractUser as DjangoAbstractUser logger = logging.getLogger(__name__) class AbstractUser(DjangoAbstractUser): uuid = models.UUIDField(primary_key=True) department_name = models.CharField(max_length=50, null=True, blank=True) def save(self, *args, **kwargs): if self.uuid is None: self.uuid = uuid.uuid1() return super(AbstractUser, self).save(*args, **kwargs) class Meta: abstract = True Make UUID a non-pk to work around problems in 3rd party appsimport uuid import logging from django.db import models from django.contrib.auth.models import AbstractUser as DjangoAbstractUser logger = logging.getLogger(__name__) class AbstractUser(DjangoAbstractUser): uuid = models.UUIDField() department_name = models.CharField(max_length=50, null=True, blank=True) def save(self, *args, **kwargs): if self.uuid is None: self.uuid = uuid.uuid1() return super(AbstractUser, self).save(*args, **kwargs) class Meta: abstract = True
<commit_before>import uuid import logging from django.db import models from django.contrib.auth.models import AbstractUser as DjangoAbstractUser logger = logging.getLogger(__name__) class AbstractUser(DjangoAbstractUser): uuid = models.UUIDField(primary_key=True) department_name = models.CharField(max_length=50, null=True, blank=True) def save(self, *args, **kwargs): if self.uuid is None: self.uuid = uuid.uuid1() return super(AbstractUser, self).save(*args, **kwargs) class Meta: abstract = True <commit_msg>Make UUID a non-pk to work around problems in 3rd party apps<commit_after>import uuid import logging from django.db import models from django.contrib.auth.models import AbstractUser as DjangoAbstractUser logger = logging.getLogger(__name__) class AbstractUser(DjangoAbstractUser): uuid = models.UUIDField() department_name = models.CharField(max_length=50, null=True, blank=True) def save(self, *args, **kwargs): if self.uuid is None: self.uuid = uuid.uuid1() return super(AbstractUser, self).save(*args, **kwargs) class Meta: abstract = True