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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
baf4f922a9f473a4351c3fd9832000244a73a40a | chainerrl/explorers/additive_gaussian.py | chainerrl/explorers/additive_gaussian.py | from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases()
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale):
self.scale = scale
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
| from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases()
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale):
self.scale = scale
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
| Remove spaces in empty lines | Remove spaces in empty lines | Python | mit | toslunar/chainerrl,toslunar/chainerrl | from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases()
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale):
self.scale = scale
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
Remove spaces in empty lines | from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases()
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale):
self.scale = scale
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
| <commit_before>from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases()
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale):
self.scale = scale
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
<commit_msg>Remove spaces in empty lines<commit_after> | from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases()
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale):
self.scale = scale
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
| from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases()
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale):
self.scale = scale
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
Remove spaces in empty linesfrom __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases()
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale):
self.scale = scale
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
| <commit_before>from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases()
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale):
self.scale = scale
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
<commit_msg>Remove spaces in empty lines<commit_after>from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases()
import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
"""
def __init__(self, scale):
self.scale = scale
def select_action(self, t, greedy_action_func, action_value=None):
a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
return a + noise
def __repr__(self):
return 'AdditiveGaussian(scale={})'.format(self.scale)
|
147c53115864cc3b3194fb9c585179d12197c998 | settings_example.py | settings_example.py | import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
# If this is set to a valid path, all CSV files extracted from emails will be
# stored in sub-folders within it.
CSV_FOLDER = os.getcwd()
# Values come from `EMAIL_SUBJECT_RE`.
CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv'
# Restrict emails by sender.
EMAIL_FROM = 'sender@example.com'
# Restrict emails by subject.
EMAIL_SUBJECT_RE = re.compile(''.join([
r'(?P<year>\d{4})',
r'(?P<month>\d{2})',
r'(?P<day>\d{2})',
r'(?P<hour>\d{2})',
r'(?P<minute>\d{2})',
r'\.csv',
]))
LOGGING_FORMAT = '''
- file: %(pathname)s
level: %(levelname)s
line: %(lineno)s
message: |
%(message)s
time: %(asctime)s
'''.strip()
# Values come from `EMAIL_SUBJECT_RE`.
TABLE_NAME_FORMAT = 'data_{year}{month}'
def get_database_client():
con = 'my_username/my_password@database.example.com:5432/my_database'
return DatabaseServer(con)
def get_email_client():
return EmailServer('mail.example.com', 'my_username', 'my_password')
| import logging
import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
# If this is set to a valid path, all CSV files extracted from emails will be
# stored in sub-folders within it.
CSV_FOLDER = os.getcwd()
# Values come from `EMAIL_SUBJECT_RE`.
CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv'
# Restrict emails by sender.
EMAIL_FROM = 'sender@example.com'
# Restrict emails by subject.
EMAIL_SUBJECT_RE = re.compile(''.join([
r'(?P<year>\d{4})',
r'(?P<month>\d{2})',
r'(?P<day>\d{2})',
r'(?P<hour>\d{2})',
r'(?P<minute>\d{2})',
r'\.csv',
]))
LOGGING_FORMAT = '''
- file: %(pathname)s
level: %(levelname)s
line: %(lineno)s
message: |
%(message)s
time: %(asctime)s
'''.strip()
LOGGING_LEVEL = logging.DEBUG
# Values come from `EMAIL_SUBJECT_RE`.
TABLE_NAME_FORMAT = 'data_{year}{month}'
def get_database_client():
con = 'my_username/my_password@database.example.com:5432/my_database'
return DatabaseServer(con)
def get_email_client():
return EmailServer('mail.example.com', 'my_username', 'my_password')
| Add logging level to settings | Add logging level to settings
| Python | mit | AustralianAntarcticDataCentre/save_emails_to_files,AustralianAntarcticDataCentre/save_emails_to_files | import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
# If this is set to a valid path, all CSV files extracted from emails will be
# stored in sub-folders within it.
CSV_FOLDER = os.getcwd()
# Values come from `EMAIL_SUBJECT_RE`.
CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv'
# Restrict emails by sender.
EMAIL_FROM = 'sender@example.com'
# Restrict emails by subject.
EMAIL_SUBJECT_RE = re.compile(''.join([
r'(?P<year>\d{4})',
r'(?P<month>\d{2})',
r'(?P<day>\d{2})',
r'(?P<hour>\d{2})',
r'(?P<minute>\d{2})',
r'\.csv',
]))
LOGGING_FORMAT = '''
- file: %(pathname)s
level: %(levelname)s
line: %(lineno)s
message: |
%(message)s
time: %(asctime)s
'''.strip()
# Values come from `EMAIL_SUBJECT_RE`.
TABLE_NAME_FORMAT = 'data_{year}{month}'
def get_database_client():
con = 'my_username/my_password@database.example.com:5432/my_database'
return DatabaseServer(con)
def get_email_client():
return EmailServer('mail.example.com', 'my_username', 'my_password')
Add logging level to settings | import logging
import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
# If this is set to a valid path, all CSV files extracted from emails will be
# stored in sub-folders within it.
CSV_FOLDER = os.getcwd()
# Values come from `EMAIL_SUBJECT_RE`.
CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv'
# Restrict emails by sender.
EMAIL_FROM = 'sender@example.com'
# Restrict emails by subject.
EMAIL_SUBJECT_RE = re.compile(''.join([
r'(?P<year>\d{4})',
r'(?P<month>\d{2})',
r'(?P<day>\d{2})',
r'(?P<hour>\d{2})',
r'(?P<minute>\d{2})',
r'\.csv',
]))
LOGGING_FORMAT = '''
- file: %(pathname)s
level: %(levelname)s
line: %(lineno)s
message: |
%(message)s
time: %(asctime)s
'''.strip()
LOGGING_LEVEL = logging.DEBUG
# Values come from `EMAIL_SUBJECT_RE`.
TABLE_NAME_FORMAT = 'data_{year}{month}'
def get_database_client():
con = 'my_username/my_password@database.example.com:5432/my_database'
return DatabaseServer(con)
def get_email_client():
return EmailServer('mail.example.com', 'my_username', 'my_password')
| <commit_before>import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
# If this is set to a valid path, all CSV files extracted from emails will be
# stored in sub-folders within it.
CSV_FOLDER = os.getcwd()
# Values come from `EMAIL_SUBJECT_RE`.
CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv'
# Restrict emails by sender.
EMAIL_FROM = 'sender@example.com'
# Restrict emails by subject.
EMAIL_SUBJECT_RE = re.compile(''.join([
r'(?P<year>\d{4})',
r'(?P<month>\d{2})',
r'(?P<day>\d{2})',
r'(?P<hour>\d{2})',
r'(?P<minute>\d{2})',
r'\.csv',
]))
LOGGING_FORMAT = '''
- file: %(pathname)s
level: %(levelname)s
line: %(lineno)s
message: |
%(message)s
time: %(asctime)s
'''.strip()
# Values come from `EMAIL_SUBJECT_RE`.
TABLE_NAME_FORMAT = 'data_{year}{month}'
def get_database_client():
con = 'my_username/my_password@database.example.com:5432/my_database'
return DatabaseServer(con)
def get_email_client():
return EmailServer('mail.example.com', 'my_username', 'my_password')
<commit_msg>Add logging level to settings<commit_after> | import logging
import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
# If this is set to a valid path, all CSV files extracted from emails will be
# stored in sub-folders within it.
CSV_FOLDER = os.getcwd()
# Values come from `EMAIL_SUBJECT_RE`.
CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv'
# Restrict emails by sender.
EMAIL_FROM = 'sender@example.com'
# Restrict emails by subject.
EMAIL_SUBJECT_RE = re.compile(''.join([
r'(?P<year>\d{4})',
r'(?P<month>\d{2})',
r'(?P<day>\d{2})',
r'(?P<hour>\d{2})',
r'(?P<minute>\d{2})',
r'\.csv',
]))
LOGGING_FORMAT = '''
- file: %(pathname)s
level: %(levelname)s
line: %(lineno)s
message: |
%(message)s
time: %(asctime)s
'''.strip()
LOGGING_LEVEL = logging.DEBUG
# Values come from `EMAIL_SUBJECT_RE`.
TABLE_NAME_FORMAT = 'data_{year}{month}'
def get_database_client():
con = 'my_username/my_password@database.example.com:5432/my_database'
return DatabaseServer(con)
def get_email_client():
return EmailServer('mail.example.com', 'my_username', 'my_password')
| import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
# If this is set to a valid path, all CSV files extracted from emails will be
# stored in sub-folders within it.
CSV_FOLDER = os.getcwd()
# Values come from `EMAIL_SUBJECT_RE`.
CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv'
# Restrict emails by sender.
EMAIL_FROM = 'sender@example.com'
# Restrict emails by subject.
EMAIL_SUBJECT_RE = re.compile(''.join([
r'(?P<year>\d{4})',
r'(?P<month>\d{2})',
r'(?P<day>\d{2})',
r'(?P<hour>\d{2})',
r'(?P<minute>\d{2})',
r'\.csv',
]))
LOGGING_FORMAT = '''
- file: %(pathname)s
level: %(levelname)s
line: %(lineno)s
message: |
%(message)s
time: %(asctime)s
'''.strip()
# Values come from `EMAIL_SUBJECT_RE`.
TABLE_NAME_FORMAT = 'data_{year}{month}'
def get_database_client():
con = 'my_username/my_password@database.example.com:5432/my_database'
return DatabaseServer(con)
def get_email_client():
return EmailServer('mail.example.com', 'my_username', 'my_password')
Add logging level to settingsimport logging
import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
# If this is set to a valid path, all CSV files extracted from emails will be
# stored in sub-folders within it.
CSV_FOLDER = os.getcwd()
# Values come from `EMAIL_SUBJECT_RE`.
CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv'
# Restrict emails by sender.
EMAIL_FROM = 'sender@example.com'
# Restrict emails by subject.
EMAIL_SUBJECT_RE = re.compile(''.join([
r'(?P<year>\d{4})',
r'(?P<month>\d{2})',
r'(?P<day>\d{2})',
r'(?P<hour>\d{2})',
r'(?P<minute>\d{2})',
r'\.csv',
]))
LOGGING_FORMAT = '''
- file: %(pathname)s
level: %(levelname)s
line: %(lineno)s
message: |
%(message)s
time: %(asctime)s
'''.strip()
LOGGING_LEVEL = logging.DEBUG
# Values come from `EMAIL_SUBJECT_RE`.
TABLE_NAME_FORMAT = 'data_{year}{month}'
def get_database_client():
con = 'my_username/my_password@database.example.com:5432/my_database'
return DatabaseServer(con)
def get_email_client():
return EmailServer('mail.example.com', 'my_username', 'my_password')
| <commit_before>import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
# If this is set to a valid path, all CSV files extracted from emails will be
# stored in sub-folders within it.
CSV_FOLDER = os.getcwd()
# Values come from `EMAIL_SUBJECT_RE`.
CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv'
# Restrict emails by sender.
EMAIL_FROM = 'sender@example.com'
# Restrict emails by subject.
EMAIL_SUBJECT_RE = re.compile(''.join([
r'(?P<year>\d{4})',
r'(?P<month>\d{2})',
r'(?P<day>\d{2})',
r'(?P<hour>\d{2})',
r'(?P<minute>\d{2})',
r'\.csv',
]))
LOGGING_FORMAT = '''
- file: %(pathname)s
level: %(levelname)s
line: %(lineno)s
message: |
%(message)s
time: %(asctime)s
'''.strip()
# Values come from `EMAIL_SUBJECT_RE`.
TABLE_NAME_FORMAT = 'data_{year}{month}'
def get_database_client():
con = 'my_username/my_password@database.example.com:5432/my_database'
return DatabaseServer(con)
def get_email_client():
return EmailServer('mail.example.com', 'my_username', 'my_password')
<commit_msg>Add logging level to settings<commit_after>import logging
import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
# If this is set to a valid path, all CSV files extracted from emails will be
# stored in sub-folders within it.
CSV_FOLDER = os.getcwd()
# Values come from `EMAIL_SUBJECT_RE`.
CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv'
# Restrict emails by sender.
EMAIL_FROM = 'sender@example.com'
# Restrict emails by subject.
EMAIL_SUBJECT_RE = re.compile(''.join([
r'(?P<year>\d{4})',
r'(?P<month>\d{2})',
r'(?P<day>\d{2})',
r'(?P<hour>\d{2})',
r'(?P<minute>\d{2})',
r'\.csv',
]))
LOGGING_FORMAT = '''
- file: %(pathname)s
level: %(levelname)s
line: %(lineno)s
message: |
%(message)s
time: %(asctime)s
'''.strip()
LOGGING_LEVEL = logging.DEBUG
# Values come from `EMAIL_SUBJECT_RE`.
TABLE_NAME_FORMAT = 'data_{year}{month}'
def get_database_client():
con = 'my_username/my_password@database.example.com:5432/my_database'
return DatabaseServer(con)
def get_email_client():
return EmailServer('mail.example.com', 'my_username', 'my_password')
|
84fbe1eebc2c19b72ab4bba8017e1cb37818afc1 | scripts/reactions.py | scripts/reactions.py | import argparse
from lenrmc.nubase import System
from lenrmc.terminal import TerminalView, StudiesTerminalView
class App(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
if 'studies' == self.kwargs.get('view'):
self.view_cls = StudiesTerminalView
else:
self.view_cls = TerminalView
def run(self):
s = System.parse(self.kwargs['system'], **self.kwargs)
for line in self.view_cls(s).lines(**self.kwargs):
print(line)
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('system', type=str)
parser.add_argument('--lb', dest='lower_bound')
parser.add_argument('--spins', dest='spins', action='store_true')
parser.add_argument('--references', dest='references', action='store_true')
parser.add_argument('--view', type=str, dest='view')
parser.set_defaults(
lower_bound = 0,
spins = False,
references = True,
view = 'default',
)
return parser.parse_args()
if '__main__' == __name__:
opts = parse_arguments()
App(**vars(opts)).run()
| import argparse
from lenrmc.nubase import System
from lenrmc.terminal import TerminalView, StudiesTerminalView
class App(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
if 'studies' == self.kwargs.get('view') or kwargs.get('studies'):
self.view_cls = StudiesTerminalView
else:
self.view_cls = TerminalView
def run(self):
s = System.parse(self.kwargs['system'], **self.kwargs)
for line in self.view_cls(s).lines(**self.kwargs):
print(line)
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('system', type=str)
parser.add_argument('--lb', dest='lower_bound')
parser.add_argument('--spins', dest='spins', action='store_true')
parser.add_argument('--references', dest='references', action='store_true')
parser.add_argument('--view', type=str, dest='view')
parser.add_argument('--studies', dest='studies', action='store_true')
parser.set_defaults(
lower_bound = 0,
spins = False,
references = True,
view = 'default',
)
return parser.parse_args()
if '__main__' == __name__:
opts = parse_arguments()
App(**vars(opts)).run()
| Add --studies as an alias for --view studies. | Add --studies as an alias for --view studies.
| Python | mit | emwalker/lenrmc | import argparse
from lenrmc.nubase import System
from lenrmc.terminal import TerminalView, StudiesTerminalView
class App(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
if 'studies' == self.kwargs.get('view'):
self.view_cls = StudiesTerminalView
else:
self.view_cls = TerminalView
def run(self):
s = System.parse(self.kwargs['system'], **self.kwargs)
for line in self.view_cls(s).lines(**self.kwargs):
print(line)
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('system', type=str)
parser.add_argument('--lb', dest='lower_bound')
parser.add_argument('--spins', dest='spins', action='store_true')
parser.add_argument('--references', dest='references', action='store_true')
parser.add_argument('--view', type=str, dest='view')
parser.set_defaults(
lower_bound = 0,
spins = False,
references = True,
view = 'default',
)
return parser.parse_args()
if '__main__' == __name__:
opts = parse_arguments()
App(**vars(opts)).run()
Add --studies as an alias for --view studies. | import argparse
from lenrmc.nubase import System
from lenrmc.terminal import TerminalView, StudiesTerminalView
class App(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
if 'studies' == self.kwargs.get('view') or kwargs.get('studies'):
self.view_cls = StudiesTerminalView
else:
self.view_cls = TerminalView
def run(self):
s = System.parse(self.kwargs['system'], **self.kwargs)
for line in self.view_cls(s).lines(**self.kwargs):
print(line)
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('system', type=str)
parser.add_argument('--lb', dest='lower_bound')
parser.add_argument('--spins', dest='spins', action='store_true')
parser.add_argument('--references', dest='references', action='store_true')
parser.add_argument('--view', type=str, dest='view')
parser.add_argument('--studies', dest='studies', action='store_true')
parser.set_defaults(
lower_bound = 0,
spins = False,
references = True,
view = 'default',
)
return parser.parse_args()
if '__main__' == __name__:
opts = parse_arguments()
App(**vars(opts)).run()
| <commit_before>import argparse
from lenrmc.nubase import System
from lenrmc.terminal import TerminalView, StudiesTerminalView
class App(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
if 'studies' == self.kwargs.get('view'):
self.view_cls = StudiesTerminalView
else:
self.view_cls = TerminalView
def run(self):
s = System.parse(self.kwargs['system'], **self.kwargs)
for line in self.view_cls(s).lines(**self.kwargs):
print(line)
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('system', type=str)
parser.add_argument('--lb', dest='lower_bound')
parser.add_argument('--spins', dest='spins', action='store_true')
parser.add_argument('--references', dest='references', action='store_true')
parser.add_argument('--view', type=str, dest='view')
parser.set_defaults(
lower_bound = 0,
spins = False,
references = True,
view = 'default',
)
return parser.parse_args()
if '__main__' == __name__:
opts = parse_arguments()
App(**vars(opts)).run()
<commit_msg>Add --studies as an alias for --view studies.<commit_after> | import argparse
from lenrmc.nubase import System
from lenrmc.terminal import TerminalView, StudiesTerminalView
class App(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
if 'studies' == self.kwargs.get('view') or kwargs.get('studies'):
self.view_cls = StudiesTerminalView
else:
self.view_cls = TerminalView
def run(self):
s = System.parse(self.kwargs['system'], **self.kwargs)
for line in self.view_cls(s).lines(**self.kwargs):
print(line)
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('system', type=str)
parser.add_argument('--lb', dest='lower_bound')
parser.add_argument('--spins', dest='spins', action='store_true')
parser.add_argument('--references', dest='references', action='store_true')
parser.add_argument('--view', type=str, dest='view')
parser.add_argument('--studies', dest='studies', action='store_true')
parser.set_defaults(
lower_bound = 0,
spins = False,
references = True,
view = 'default',
)
return parser.parse_args()
if '__main__' == __name__:
opts = parse_arguments()
App(**vars(opts)).run()
| import argparse
from lenrmc.nubase import System
from lenrmc.terminal import TerminalView, StudiesTerminalView
class App(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
if 'studies' == self.kwargs.get('view'):
self.view_cls = StudiesTerminalView
else:
self.view_cls = TerminalView
def run(self):
s = System.parse(self.kwargs['system'], **self.kwargs)
for line in self.view_cls(s).lines(**self.kwargs):
print(line)
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('system', type=str)
parser.add_argument('--lb', dest='lower_bound')
parser.add_argument('--spins', dest='spins', action='store_true')
parser.add_argument('--references', dest='references', action='store_true')
parser.add_argument('--view', type=str, dest='view')
parser.set_defaults(
lower_bound = 0,
spins = False,
references = True,
view = 'default',
)
return parser.parse_args()
if '__main__' == __name__:
opts = parse_arguments()
App(**vars(opts)).run()
Add --studies as an alias for --view studies.import argparse
from lenrmc.nubase import System
from lenrmc.terminal import TerminalView, StudiesTerminalView
class App(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
if 'studies' == self.kwargs.get('view') or kwargs.get('studies'):
self.view_cls = StudiesTerminalView
else:
self.view_cls = TerminalView
def run(self):
s = System.parse(self.kwargs['system'], **self.kwargs)
for line in self.view_cls(s).lines(**self.kwargs):
print(line)
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('system', type=str)
parser.add_argument('--lb', dest='lower_bound')
parser.add_argument('--spins', dest='spins', action='store_true')
parser.add_argument('--references', dest='references', action='store_true')
parser.add_argument('--view', type=str, dest='view')
parser.add_argument('--studies', dest='studies', action='store_true')
parser.set_defaults(
lower_bound = 0,
spins = False,
references = True,
view = 'default',
)
return parser.parse_args()
if '__main__' == __name__:
opts = parse_arguments()
App(**vars(opts)).run()
| <commit_before>import argparse
from lenrmc.nubase import System
from lenrmc.terminal import TerminalView, StudiesTerminalView
class App(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
if 'studies' == self.kwargs.get('view'):
self.view_cls = StudiesTerminalView
else:
self.view_cls = TerminalView
def run(self):
s = System.parse(self.kwargs['system'], **self.kwargs)
for line in self.view_cls(s).lines(**self.kwargs):
print(line)
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('system', type=str)
parser.add_argument('--lb', dest='lower_bound')
parser.add_argument('--spins', dest='spins', action='store_true')
parser.add_argument('--references', dest='references', action='store_true')
parser.add_argument('--view', type=str, dest='view')
parser.set_defaults(
lower_bound = 0,
spins = False,
references = True,
view = 'default',
)
return parser.parse_args()
if '__main__' == __name__:
opts = parse_arguments()
App(**vars(opts)).run()
<commit_msg>Add --studies as an alias for --view studies.<commit_after>import argparse
from lenrmc.nubase import System
from lenrmc.terminal import TerminalView, StudiesTerminalView
class App(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
if 'studies' == self.kwargs.get('view') or kwargs.get('studies'):
self.view_cls = StudiesTerminalView
else:
self.view_cls = TerminalView
def run(self):
s = System.parse(self.kwargs['system'], **self.kwargs)
for line in self.view_cls(s).lines(**self.kwargs):
print(line)
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('system', type=str)
parser.add_argument('--lb', dest='lower_bound')
parser.add_argument('--spins', dest='spins', action='store_true')
parser.add_argument('--references', dest='references', action='store_true')
parser.add_argument('--view', type=str, dest='view')
parser.add_argument('--studies', dest='studies', action='store_true')
parser.set_defaults(
lower_bound = 0,
spins = False,
references = True,
view = 'default',
)
return parser.parse_args()
if '__main__' == __name__:
opts = parse_arguments()
App(**vars(opts)).run()
|
530297a29150736208cd30c018a427f9d7e2d2eb | swift3/__init__.py | swift3/__init__.py | # Copyright (c) 2012-2014 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Static Web Middleware for OpenStack Swift
"""
import pbr.version
__all__ = ['version_info', 'version']
# get version info using pbr.version.
# pbr version info is inferred from version in setup.cfg
# and vcs information.
_version_info = pbr.version.VersionInfo('swift3')
#: Version string ``'major.minor.revision'``.
version = _version_info.version_string()
#: Version information ``(major, minor, revision)``.
version_info = version.split('.')
| # Copyright (c) 2012-2014 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pkg_resources
__all__ = ['version_info', 'version']
try:
# First, try to get our version out of PKG-INFO. If we're installed,
# this'll let us find our version without pulling in pbr. After all, if
# we're installed on a system, we're not in a Git-managed source tree, so
# pbr doesn't really buy us anything.
__version__ = pkg_resources.get_provider(
pkg_resources.Requirement.parse('swift3')).version
except pkg_resources.DistributionNotFound:
# No PKG-INFO? We're probably running from a checkout, then. Let pbr do
# its thing to figure out a version number.
import pbr.version
__version__ = pbr.version.VersionInfo('swift3').release_string()
#: Version information ``(major, minor, revision)``.
version_info = tuple(map(int, __version__.split('.')[:3]))
#: Version string ``'major.minor.revision'``.
version = '.'.join(map(str, version_info))
| Remove pbr dependency at run time | Remove pbr dependency at run time
This change is based on the following commit in the Swift tree.
0717133 Make pbr a build-time only dependency
Change-Id: I43956f531a9928ade296236b3b605e52dc2f86f3
| Python | apache-2.0 | swiftstack/swift3-stackforge,stackforge/swift3,stackforge/swift3,tumf/swift3,KoreaCloudObjectStorage/swift3,KoreaCloudObjectStorage/swift3,swiftstack/swift3-stackforge,tumf/swift3 | # Copyright (c) 2012-2014 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Static Web Middleware for OpenStack Swift
"""
import pbr.version
__all__ = ['version_info', 'version']
# get version info using pbr.version.
# pbr version info is inferred from version in setup.cfg
# and vcs information.
_version_info = pbr.version.VersionInfo('swift3')
#: Version string ``'major.minor.revision'``.
version = _version_info.version_string()
#: Version information ``(major, minor, revision)``.
version_info = version.split('.')
Remove pbr dependency at run time
This change is based on the following commit in the Swift tree.
0717133 Make pbr a build-time only dependency
Change-Id: I43956f531a9928ade296236b3b605e52dc2f86f3 | # Copyright (c) 2012-2014 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pkg_resources
__all__ = ['version_info', 'version']
try:
# First, try to get our version out of PKG-INFO. If we're installed,
# this'll let us find our version without pulling in pbr. After all, if
# we're installed on a system, we're not in a Git-managed source tree, so
# pbr doesn't really buy us anything.
__version__ = pkg_resources.get_provider(
pkg_resources.Requirement.parse('swift3')).version
except pkg_resources.DistributionNotFound:
# No PKG-INFO? We're probably running from a checkout, then. Let pbr do
# its thing to figure out a version number.
import pbr.version
__version__ = pbr.version.VersionInfo('swift3').release_string()
#: Version information ``(major, minor, revision)``.
version_info = tuple(map(int, __version__.split('.')[:3]))
#: Version string ``'major.minor.revision'``.
version = '.'.join(map(str, version_info))
| <commit_before># Copyright (c) 2012-2014 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Static Web Middleware for OpenStack Swift
"""
import pbr.version
__all__ = ['version_info', 'version']
# get version info using pbr.version.
# pbr version info is inferred from version in setup.cfg
# and vcs information.
_version_info = pbr.version.VersionInfo('swift3')
#: Version string ``'major.minor.revision'``.
version = _version_info.version_string()
#: Version information ``(major, minor, revision)``.
version_info = version.split('.')
<commit_msg>Remove pbr dependency at run time
This change is based on the following commit in the Swift tree.
0717133 Make pbr a build-time only dependency
Change-Id: I43956f531a9928ade296236b3b605e52dc2f86f3<commit_after> | # Copyright (c) 2012-2014 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pkg_resources
__all__ = ['version_info', 'version']
try:
# First, try to get our version out of PKG-INFO. If we're installed,
# this'll let us find our version without pulling in pbr. After all, if
# we're installed on a system, we're not in a Git-managed source tree, so
# pbr doesn't really buy us anything.
__version__ = pkg_resources.get_provider(
pkg_resources.Requirement.parse('swift3')).version
except pkg_resources.DistributionNotFound:
# No PKG-INFO? We're probably running from a checkout, then. Let pbr do
# its thing to figure out a version number.
import pbr.version
__version__ = pbr.version.VersionInfo('swift3').release_string()
#: Version information ``(major, minor, revision)``.
version_info = tuple(map(int, __version__.split('.')[:3]))
#: Version string ``'major.minor.revision'``.
version = '.'.join(map(str, version_info))
| # Copyright (c) 2012-2014 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Static Web Middleware for OpenStack Swift
"""
import pbr.version
__all__ = ['version_info', 'version']
# get version info using pbr.version.
# pbr version info is inferred from version in setup.cfg
# and vcs information.
_version_info = pbr.version.VersionInfo('swift3')
#: Version string ``'major.minor.revision'``.
version = _version_info.version_string()
#: Version information ``(major, minor, revision)``.
version_info = version.split('.')
Remove pbr dependency at run time
This change is based on the following commit in the Swift tree.
0717133 Make pbr a build-time only dependency
Change-Id: I43956f531a9928ade296236b3b605e52dc2f86f3# Copyright (c) 2012-2014 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pkg_resources
__all__ = ['version_info', 'version']
try:
# First, try to get our version out of PKG-INFO. If we're installed,
# this'll let us find our version without pulling in pbr. After all, if
# we're installed on a system, we're not in a Git-managed source tree, so
# pbr doesn't really buy us anything.
__version__ = pkg_resources.get_provider(
pkg_resources.Requirement.parse('swift3')).version
except pkg_resources.DistributionNotFound:
# No PKG-INFO? We're probably running from a checkout, then. Let pbr do
# its thing to figure out a version number.
import pbr.version
__version__ = pbr.version.VersionInfo('swift3').release_string()
#: Version information ``(major, minor, revision)``.
version_info = tuple(map(int, __version__.split('.')[:3]))
#: Version string ``'major.minor.revision'``.
version = '.'.join(map(str, version_info))
| <commit_before># Copyright (c) 2012-2014 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Static Web Middleware for OpenStack Swift
"""
import pbr.version
__all__ = ['version_info', 'version']
# get version info using pbr.version.
# pbr version info is inferred from version in setup.cfg
# and vcs information.
_version_info = pbr.version.VersionInfo('swift3')
#: Version string ``'major.minor.revision'``.
version = _version_info.version_string()
#: Version information ``(major, minor, revision)``.
version_info = version.split('.')
<commit_msg>Remove pbr dependency at run time
This change is based on the following commit in the Swift tree.
0717133 Make pbr a build-time only dependency
Change-Id: I43956f531a9928ade296236b3b605e52dc2f86f3<commit_after># Copyright (c) 2012-2014 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pkg_resources
__all__ = ['version_info', 'version']
try:
# First, try to get our version out of PKG-INFO. If we're installed,
# this'll let us find our version without pulling in pbr. After all, if
# we're installed on a system, we're not in a Git-managed source tree, so
# pbr doesn't really buy us anything.
__version__ = pkg_resources.get_provider(
pkg_resources.Requirement.parse('swift3')).version
except pkg_resources.DistributionNotFound:
# No PKG-INFO? We're probably running from a checkout, then. Let pbr do
# its thing to figure out a version number.
import pbr.version
__version__ = pbr.version.VersionInfo('swift3').release_string()
#: Version information ``(major, minor, revision)``.
version_info = tuple(map(int, __version__.split('.')[:3]))
#: Version string ``'major.minor.revision'``.
version = '.'.join(map(str, version_info))
|
f731cef20b07998dd5ec76e20af20cb9e60d9afb | UM/Operations/RemoveSceneNodeOperation.py | UM/Operations/RemoveSceneNodeOperation.py | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
## An operation that removes an list of SceneNode from the scene.
class RemoveSceneNodeOperation(Operation.Operation):
def __init__(self, node):
super().__init__()
self._node = node
self._parent = node.getParent()
def undo(self):
self._node.setParent(self._parent)
def redo(self):
self._node.setParent(None)
| # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
from UM.Scene.Selection import Selection
## An operation that removes an list of SceneNode from the scene.
class RemoveSceneNodeOperation(Operation.Operation):
def __init__(self, node):
super().__init__()
self._node = node
self._parent = node.getParent()
def undo(self):
self._node.setParent(self._parent)
def redo(self):
self._node.setParent(None)
if Selection.isSelected(self._node):
Selection.remove(self._node)
| Remove the object from selection if it is selected | Remove the object from selection if it is selected
This cleans up any leftovers due to the object being selected.
Fixes #42
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
## An operation that removes an list of SceneNode from the scene.
class RemoveSceneNodeOperation(Operation.Operation):
def __init__(self, node):
super().__init__()
self._node = node
self._parent = node.getParent()
def undo(self):
self._node.setParent(self._parent)
def redo(self):
self._node.setParent(None)
Remove the object from selection if it is selected
This cleans up any leftovers due to the object being selected.
Fixes #42 | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
from UM.Scene.Selection import Selection
## An operation that removes an list of SceneNode from the scene.
class RemoveSceneNodeOperation(Operation.Operation):
def __init__(self, node):
super().__init__()
self._node = node
self._parent = node.getParent()
def undo(self):
self._node.setParent(self._parent)
def redo(self):
self._node.setParent(None)
if Selection.isSelected(self._node):
Selection.remove(self._node)
| <commit_before># Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
## An operation that removes an list of SceneNode from the scene.
class RemoveSceneNodeOperation(Operation.Operation):
def __init__(self, node):
super().__init__()
self._node = node
self._parent = node.getParent()
def undo(self):
self._node.setParent(self._parent)
def redo(self):
self._node.setParent(None)
<commit_msg>Remove the object from selection if it is selected
This cleans up any leftovers due to the object being selected.
Fixes #42<commit_after> | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
from UM.Scene.Selection import Selection
## An operation that removes an list of SceneNode from the scene.
class RemoveSceneNodeOperation(Operation.Operation):
def __init__(self, node):
super().__init__()
self._node = node
self._parent = node.getParent()
def undo(self):
self._node.setParent(self._parent)
def redo(self):
self._node.setParent(None)
if Selection.isSelected(self._node):
Selection.remove(self._node)
| # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
## An operation that removes an list of SceneNode from the scene.
class RemoveSceneNodeOperation(Operation.Operation):
def __init__(self, node):
super().__init__()
self._node = node
self._parent = node.getParent()
def undo(self):
self._node.setParent(self._parent)
def redo(self):
self._node.setParent(None)
Remove the object from selection if it is selected
This cleans up any leftovers due to the object being selected.
Fixes #42# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
from UM.Scene.Selection import Selection
## An operation that removes an list of SceneNode from the scene.
class RemoveSceneNodeOperation(Operation.Operation):
def __init__(self, node):
super().__init__()
self._node = node
self._parent = node.getParent()
def undo(self):
self._node.setParent(self._parent)
def redo(self):
self._node.setParent(None)
if Selection.isSelected(self._node):
Selection.remove(self._node)
| <commit_before># Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
## An operation that removes an list of SceneNode from the scene.
class RemoveSceneNodeOperation(Operation.Operation):
def __init__(self, node):
super().__init__()
self._node = node
self._parent = node.getParent()
def undo(self):
self._node.setParent(self._parent)
def redo(self):
self._node.setParent(None)
<commit_msg>Remove the object from selection if it is selected
This cleans up any leftovers due to the object being selected.
Fixes #42<commit_after># Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
from UM.Scene.Selection import Selection
## An operation that removes an list of SceneNode from the scene.
class RemoveSceneNodeOperation(Operation.Operation):
def __init__(self, node):
super().__init__()
self._node = node
self._parent = node.getParent()
def undo(self):
self._node.setParent(self._parent)
def redo(self):
self._node.setParent(None)
if Selection.isSelected(self._node):
Selection.remove(self._node)
|
59055a9f8d6093e2fc82bb4f656200b71279da1c | tml/rules/contexts/genders.py | tml/rules/contexts/genders.py | from .gender import Gender
from _ctypes import ArgumentError
class Genders(object):
@classmethod
def match(cls, data):
""" Check is data list of genders """
if type(data) is str:
raise ArgumentError('String is not genders list', data)
try:
ret = []
for el in data:
ret.append(Gender.match(el))
return ret
except TypeError:
raise ArgumentError('Not iterable data', data)
| from .gender import Gender
from _ctypes import ArgumentError
class Genders(object):
""" List of objects having gender """
@classmethod
def match(cls, data):
""" Check is data list of genders """
if type(data) is str:
raise ArgumentError('String is not genders list', data)
try:
ret = []
for el in data:
ret.append(Gender.match(el))
return ret
except TypeError:
raise ArgumentError('Not iterable data', data)
| Add comment to gender class | Add comment to gender class
| Python | mit | translationexchange/tml-python,translationexchange/tml-python | from .gender import Gender
from _ctypes import ArgumentError
class Genders(object):
@classmethod
def match(cls, data):
""" Check is data list of genders """
if type(data) is str:
raise ArgumentError('String is not genders list', data)
try:
ret = []
for el in data:
ret.append(Gender.match(el))
return ret
except TypeError:
raise ArgumentError('Not iterable data', data)
Add comment to gender class | from .gender import Gender
from _ctypes import ArgumentError
class Genders(object):
""" List of objects having gender """
@classmethod
def match(cls, data):
""" Check is data list of genders """
if type(data) is str:
raise ArgumentError('String is not genders list', data)
try:
ret = []
for el in data:
ret.append(Gender.match(el))
return ret
except TypeError:
raise ArgumentError('Not iterable data', data)
| <commit_before>from .gender import Gender
from _ctypes import ArgumentError
class Genders(object):
@classmethod
def match(cls, data):
""" Check is data list of genders """
if type(data) is str:
raise ArgumentError('String is not genders list', data)
try:
ret = []
for el in data:
ret.append(Gender.match(el))
return ret
except TypeError:
raise ArgumentError('Not iterable data', data)
<commit_msg>Add comment to gender class<commit_after> | from .gender import Gender
from _ctypes import ArgumentError
class Genders(object):
""" List of objects having gender """
@classmethod
def match(cls, data):
""" Check is data list of genders """
if type(data) is str:
raise ArgumentError('String is not genders list', data)
try:
ret = []
for el in data:
ret.append(Gender.match(el))
return ret
except TypeError:
raise ArgumentError('Not iterable data', data)
| from .gender import Gender
from _ctypes import ArgumentError
class Genders(object):
@classmethod
def match(cls, data):
""" Check is data list of genders """
if type(data) is str:
raise ArgumentError('String is not genders list', data)
try:
ret = []
for el in data:
ret.append(Gender.match(el))
return ret
except TypeError:
raise ArgumentError('Not iterable data', data)
Add comment to gender classfrom .gender import Gender
from _ctypes import ArgumentError
class Genders(object):
""" List of objects having gender """
@classmethod
def match(cls, data):
""" Check is data list of genders """
if type(data) is str:
raise ArgumentError('String is not genders list', data)
try:
ret = []
for el in data:
ret.append(Gender.match(el))
return ret
except TypeError:
raise ArgumentError('Not iterable data', data)
| <commit_before>from .gender import Gender
from _ctypes import ArgumentError
class Genders(object):
@classmethod
def match(cls, data):
""" Check is data list of genders """
if type(data) is str:
raise ArgumentError('String is not genders list', data)
try:
ret = []
for el in data:
ret.append(Gender.match(el))
return ret
except TypeError:
raise ArgumentError('Not iterable data', data)
<commit_msg>Add comment to gender class<commit_after>from .gender import Gender
from _ctypes import ArgumentError
class Genders(object):
""" List of objects having gender """
@classmethod
def match(cls, data):
""" Check is data list of genders """
if type(data) is str:
raise ArgumentError('String is not genders list', data)
try:
ret = []
for el in data:
ret.append(Gender.match(el))
return ret
except TypeError:
raise ArgumentError('Not iterable data', data)
|
9de8bae6b310473c1e42448b3fbca64a4807678a | astrobin/tasks.py | astrobin/tasks.py | from __future__ import absolute_import
from django.core.cache import cache
from celery import shared_task
from haystack.query import SearchQuerySet
from astrobin.models import Image
@shared_task()
def update_top100_ids():
sqs = SearchQuerySet().models(Image).order_by('-likes')
top100_ids = [int(x.pk) for x in sqs][:100]
cache.set('top100_ids', top100_ids, 60*60*24)
| from __future__ import absolute_import
from hashlib import md5
from django.core.cache import cache
from celery import shared_task
from celery.utils.log import get_task_logger
from haystack.query import SearchQuerySet
from astrobin.models import Image
logger = get_task_logger(__name__)
LOCK_EXPIRE = 60 * 5 # Lock expires in 5 minutes
@shared_task()
def update_top100_ids():
lock_id = 'top100_ids_lock'
# cache.add fails if the key already exists
acquire_lock = lambda: cache.add(lock_id, 'true', LOCK_EXPIRE)
# memcache delete is very slow, but we have to use it to take
# advantage of using add() for atomic locking
release_lock = lambda: cache.delete(lock_id)
logger.debug('Building Top100 ids...')
if acquire_lock():
try:
sqs = SearchQuerySet().models(Image).order_by('-likes')
top100_ids = [int(x.pk) for x in sqs][:100]
cache.set('top100_ids', top100_ids, 60*60*24)
finally:
release_lock()
logger.debug(
'Top100 ids task is already being run by another worker')
| Make task for top100_ids atomic | Make task for top100_ids atomic
| Python | agpl-3.0 | astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin | from __future__ import absolute_import
from django.core.cache import cache
from celery import shared_task
from haystack.query import SearchQuerySet
from astrobin.models import Image
@shared_task()
def update_top100_ids():
sqs = SearchQuerySet().models(Image).order_by('-likes')
top100_ids = [int(x.pk) for x in sqs][:100]
cache.set('top100_ids', top100_ids, 60*60*24)
Make task for top100_ids atomic | from __future__ import absolute_import
from hashlib import md5
from django.core.cache import cache
from celery import shared_task
from celery.utils.log import get_task_logger
from haystack.query import SearchQuerySet
from astrobin.models import Image
logger = get_task_logger(__name__)
LOCK_EXPIRE = 60 * 5 # Lock expires in 5 minutes
@shared_task()
def update_top100_ids():
lock_id = 'top100_ids_lock'
# cache.add fails if the key already exists
acquire_lock = lambda: cache.add(lock_id, 'true', LOCK_EXPIRE)
# memcache delete is very slow, but we have to use it to take
# advantage of using add() for atomic locking
release_lock = lambda: cache.delete(lock_id)
logger.debug('Building Top100 ids...')
if acquire_lock():
try:
sqs = SearchQuerySet().models(Image).order_by('-likes')
top100_ids = [int(x.pk) for x in sqs][:100]
cache.set('top100_ids', top100_ids, 60*60*24)
finally:
release_lock()
logger.debug(
'Top100 ids task is already being run by another worker')
| <commit_before>from __future__ import absolute_import
from django.core.cache import cache
from celery import shared_task
from haystack.query import SearchQuerySet
from astrobin.models import Image
@shared_task()
def update_top100_ids():
sqs = SearchQuerySet().models(Image).order_by('-likes')
top100_ids = [int(x.pk) for x in sqs][:100]
cache.set('top100_ids', top100_ids, 60*60*24)
<commit_msg>Make task for top100_ids atomic<commit_after> | from __future__ import absolute_import
from hashlib import md5
from django.core.cache import cache
from celery import shared_task
from celery.utils.log import get_task_logger
from haystack.query import SearchQuerySet
from astrobin.models import Image
logger = get_task_logger(__name__)
LOCK_EXPIRE = 60 * 5 # Lock expires in 5 minutes
@shared_task()
def update_top100_ids():
lock_id = 'top100_ids_lock'
# cache.add fails if the key already exists
acquire_lock = lambda: cache.add(lock_id, 'true', LOCK_EXPIRE)
# memcache delete is very slow, but we have to use it to take
# advantage of using add() for atomic locking
release_lock = lambda: cache.delete(lock_id)
logger.debug('Building Top100 ids...')
if acquire_lock():
try:
sqs = SearchQuerySet().models(Image).order_by('-likes')
top100_ids = [int(x.pk) for x in sqs][:100]
cache.set('top100_ids', top100_ids, 60*60*24)
finally:
release_lock()
logger.debug(
'Top100 ids task is already being run by another worker')
| from __future__ import absolute_import
from django.core.cache import cache
from celery import shared_task
from haystack.query import SearchQuerySet
from astrobin.models import Image
@shared_task()
def update_top100_ids():
sqs = SearchQuerySet().models(Image).order_by('-likes')
top100_ids = [int(x.pk) for x in sqs][:100]
cache.set('top100_ids', top100_ids, 60*60*24)
Make task for top100_ids atomicfrom __future__ import absolute_import
from hashlib import md5
from django.core.cache import cache
from celery import shared_task
from celery.utils.log import get_task_logger
from haystack.query import SearchQuerySet
from astrobin.models import Image
logger = get_task_logger(__name__)
LOCK_EXPIRE = 60 * 5 # Lock expires in 5 minutes
@shared_task()
def update_top100_ids():
lock_id = 'top100_ids_lock'
# cache.add fails if the key already exists
acquire_lock = lambda: cache.add(lock_id, 'true', LOCK_EXPIRE)
# memcache delete is very slow, but we have to use it to take
# advantage of using add() for atomic locking
release_lock = lambda: cache.delete(lock_id)
logger.debug('Building Top100 ids...')
if acquire_lock():
try:
sqs = SearchQuerySet().models(Image).order_by('-likes')
top100_ids = [int(x.pk) for x in sqs][:100]
cache.set('top100_ids', top100_ids, 60*60*24)
finally:
release_lock()
logger.debug(
'Top100 ids task is already being run by another worker')
| <commit_before>from __future__ import absolute_import
from django.core.cache import cache
from celery import shared_task
from haystack.query import SearchQuerySet
from astrobin.models import Image
@shared_task()
def update_top100_ids():
sqs = SearchQuerySet().models(Image).order_by('-likes')
top100_ids = [int(x.pk) for x in sqs][:100]
cache.set('top100_ids', top100_ids, 60*60*24)
<commit_msg>Make task for top100_ids atomic<commit_after>from __future__ import absolute_import
from hashlib import md5
from django.core.cache import cache
from celery import shared_task
from celery.utils.log import get_task_logger
from haystack.query import SearchQuerySet
from astrobin.models import Image
logger = get_task_logger(__name__)
LOCK_EXPIRE = 60 * 5 # Lock expires in 5 minutes
@shared_task()
def update_top100_ids():
lock_id = 'top100_ids_lock'
# cache.add fails if the key already exists
acquire_lock = lambda: cache.add(lock_id, 'true', LOCK_EXPIRE)
# memcache delete is very slow, but we have to use it to take
# advantage of using add() for atomic locking
release_lock = lambda: cache.delete(lock_id)
logger.debug('Building Top100 ids...')
if acquire_lock():
try:
sqs = SearchQuerySet().models(Image).order_by('-likes')
top100_ids = [int(x.pk) for x in sqs][:100]
cache.set('top100_ids', top100_ids, 60*60*24)
finally:
release_lock()
logger.debug(
'Top100 ids task is already being run by another worker')
|
d70014d317f7abc9dffe674aca5eaf77d20a002f | djangosaml2/urls.py | djangosaml2/urls.py | # Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
| # Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# 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.
try:
from django.conf.urls import patterns, handler500, url
# Fallback for Django versions < 1.4
except ImportError:
from django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
| Fix imports for Django 1.6 and above | Fix imports for Django 1.6 and above
| Python | apache-2.0 | bernii/djangosaml2,azavea/djangosaml2 | # Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
Fix imports for Django 1.6 and above | # Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# 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.
try:
from django.conf.urls import patterns, handler500, url
# Fallback for Django versions < 1.4
except ImportError:
from django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
| <commit_before># Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
<commit_msg>Fix imports for Django 1.6 and above<commit_after> | # Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# 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.
try:
from django.conf.urls import patterns, handler500, url
# Fallback for Django versions < 1.4
except ImportError:
from django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
| # Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
Fix imports for Django 1.6 and above# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# 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.
try:
from django.conf.urls import patterns, handler500, url
# Fallback for Django versions < 1.4
except ImportError:
from django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
| <commit_before># Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
<commit_msg>Fix imports for Django 1.6 and above<commit_after># Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# 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.
try:
from django.conf.urls import patterns, handler500, url
# Fallback for Django versions < 1.4
except ImportError:
from django.conf.urls.defaults import patterns, handler500, url
urlpatterns = patterns(
'djangosaml2.views',
url(r'^login/$', 'login', name='saml2_login'),
url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
url(r'^logout/$', 'logout', name='saml2_logout'),
url(r'^ls/$', 'logout_service', name='saml2_ls'),
url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)
handler500 = handler500
|
ebadbdda9b522588d534697696d3270542d3167e | zinnia/migrations/__init__.py | zinnia/migrations/__init__.py | """Migrations for Zinnia"""
from django.contrib.auth import get_user_model
User = get_user_model()
user_name = User.__name__
user_table = User._meta.db_table
user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name)
user_model_label = '%s.%s' % (User._meta.app_label, User._meta.module_name)
| """Migrations for Zinnia"""
from django.contrib.auth import get_user_model
User = get_user_model()
user_name = User.__name__
user_table = User._meta.db_table
user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name)
user_model_label = '%s.%s' % (User._meta.app_label, User._meta.model_name)
| Use _meta.model_name instead of _meta.module_name | Use _meta.model_name instead of _meta.module_name
| Python | bsd-3-clause | ghachey/django-blog-zinnia,ZuluPro/django-blog-zinnia,Zopieux/django-blog-zinnia,petecummings/django-blog-zinnia,extertioner/django-blog-zinnia,Zopieux/django-blog-zinnia,ZuluPro/django-blog-zinnia,petecummings/django-blog-zinnia,aorzh/django-blog-zinnia,extertioner/django-blog-zinnia,petecummings/django-blog-zinnia,ghachey/django-blog-zinnia,Maplecroft/django-blog-zinnia,marctc/django-blog-zinnia,ZuluPro/django-blog-zinnia,bywbilly/django-blog-zinnia,bywbilly/django-blog-zinnia,bywbilly/django-blog-zinnia,Fantomas42/django-blog-zinnia,Maplecroft/django-blog-zinnia,marctc/django-blog-zinnia,Zopieux/django-blog-zinnia,1844144/django-blog-zinnia,dapeng0802/django-blog-zinnia,marctc/django-blog-zinnia,Maplecroft/django-blog-zinnia,Fantomas42/django-blog-zinnia,1844144/django-blog-zinnia,dapeng0802/django-blog-zinnia,Fantomas42/django-blog-zinnia,1844144/django-blog-zinnia,extertioner/django-blog-zinnia,aorzh/django-blog-zinnia,dapeng0802/django-blog-zinnia,ghachey/django-blog-zinnia,aorzh/django-blog-zinnia | """Migrations for Zinnia"""
from django.contrib.auth import get_user_model
User = get_user_model()
user_name = User.__name__
user_table = User._meta.db_table
user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name)
user_model_label = '%s.%s' % (User._meta.app_label, User._meta.module_name)
Use _meta.model_name instead of _meta.module_name | """Migrations for Zinnia"""
from django.contrib.auth import get_user_model
User = get_user_model()
user_name = User.__name__
user_table = User._meta.db_table
user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name)
user_model_label = '%s.%s' % (User._meta.app_label, User._meta.model_name)
| <commit_before>"""Migrations for Zinnia"""
from django.contrib.auth import get_user_model
User = get_user_model()
user_name = User.__name__
user_table = User._meta.db_table
user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name)
user_model_label = '%s.%s' % (User._meta.app_label, User._meta.module_name)
<commit_msg>Use _meta.model_name instead of _meta.module_name<commit_after> | """Migrations for Zinnia"""
from django.contrib.auth import get_user_model
User = get_user_model()
user_name = User.__name__
user_table = User._meta.db_table
user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name)
user_model_label = '%s.%s' % (User._meta.app_label, User._meta.model_name)
| """Migrations for Zinnia"""
from django.contrib.auth import get_user_model
User = get_user_model()
user_name = User.__name__
user_table = User._meta.db_table
user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name)
user_model_label = '%s.%s' % (User._meta.app_label, User._meta.module_name)
Use _meta.model_name instead of _meta.module_name"""Migrations for Zinnia"""
from django.contrib.auth import get_user_model
User = get_user_model()
user_name = User.__name__
user_table = User._meta.db_table
user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name)
user_model_label = '%s.%s' % (User._meta.app_label, User._meta.model_name)
| <commit_before>"""Migrations for Zinnia"""
from django.contrib.auth import get_user_model
User = get_user_model()
user_name = User.__name__
user_table = User._meta.db_table
user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name)
user_model_label = '%s.%s' % (User._meta.app_label, User._meta.module_name)
<commit_msg>Use _meta.model_name instead of _meta.module_name<commit_after>"""Migrations for Zinnia"""
from django.contrib.auth import get_user_model
User = get_user_model()
user_name = User.__name__
user_table = User._meta.db_table
user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name)
user_model_label = '%s.%s' % (User._meta.app_label, User._meta.model_name)
|
7ea630074262beed16c70649809fe8115bcc6105 | saleor/account/templatetags/i18n_address_tags.py | saleor/account/templatetags/i18n_address_tags.py | import i18naddress
from django import template
from django.utils.translation import pgettext
register = template.Library()
@register.inclusion_tag("formatted_address.html")
def format_address(address, include_phone=True, inline=False, latin=False):
address_data = address.as_data()
address_data["name"] = (
pgettext("Address data", "%(first_name)s %(last_name)s") % address_data
)
address_data["country_code"] = address_data["country"]
address_data["street_address"] = pgettext(
"Address data", "%(street_address_1)s\n" "%(street_address_2)s" % address_data
)
address_lines = i18naddress.format_address(address_data, latin).split("\n")
if include_phone and address.phone:
address_lines.append(address.phone)
return {"address_lines": address_lines, "inline": inline}
| import i18naddress
from django import template
from django.utils.translation import pgettext
register = template.Library()
@register.inclusion_tag("formatted_address.html")
def format_address(address, include_phone=True, inline=False, latin=False):
address_data = address.as_data()
address_data["name"] = (
pgettext("Address data", "%(first_name)s %(last_name)s") % address_data
)
address_data["country_code"] = address_data["country"]
address_data["street_address"] = pgettext(
"Address data", "%(street_address_1)s\n" "%(street_address_2)s" % address_data
)
address_lines = i18naddress.format_address(address_data, latin).split("\n")
if include_phone and address.phone:
address_lines.append(str(address.phone))
return {"address_lines": address_lines, "inline": inline}
| Fix phone number formatting in emails | Fix phone number formatting in emails
| Python | bsd-3-clause | mociepka/saleor,mociepka/saleor,mociepka/saleor | import i18naddress
from django import template
from django.utils.translation import pgettext
register = template.Library()
@register.inclusion_tag("formatted_address.html")
def format_address(address, include_phone=True, inline=False, latin=False):
address_data = address.as_data()
address_data["name"] = (
pgettext("Address data", "%(first_name)s %(last_name)s") % address_data
)
address_data["country_code"] = address_data["country"]
address_data["street_address"] = pgettext(
"Address data", "%(street_address_1)s\n" "%(street_address_2)s" % address_data
)
address_lines = i18naddress.format_address(address_data, latin).split("\n")
if include_phone and address.phone:
address_lines.append(address.phone)
return {"address_lines": address_lines, "inline": inline}
Fix phone number formatting in emails | import i18naddress
from django import template
from django.utils.translation import pgettext
register = template.Library()
@register.inclusion_tag("formatted_address.html")
def format_address(address, include_phone=True, inline=False, latin=False):
address_data = address.as_data()
address_data["name"] = (
pgettext("Address data", "%(first_name)s %(last_name)s") % address_data
)
address_data["country_code"] = address_data["country"]
address_data["street_address"] = pgettext(
"Address data", "%(street_address_1)s\n" "%(street_address_2)s" % address_data
)
address_lines = i18naddress.format_address(address_data, latin).split("\n")
if include_phone and address.phone:
address_lines.append(str(address.phone))
return {"address_lines": address_lines, "inline": inline}
| <commit_before>import i18naddress
from django import template
from django.utils.translation import pgettext
register = template.Library()
@register.inclusion_tag("formatted_address.html")
def format_address(address, include_phone=True, inline=False, latin=False):
address_data = address.as_data()
address_data["name"] = (
pgettext("Address data", "%(first_name)s %(last_name)s") % address_data
)
address_data["country_code"] = address_data["country"]
address_data["street_address"] = pgettext(
"Address data", "%(street_address_1)s\n" "%(street_address_2)s" % address_data
)
address_lines = i18naddress.format_address(address_data, latin).split("\n")
if include_phone and address.phone:
address_lines.append(address.phone)
return {"address_lines": address_lines, "inline": inline}
<commit_msg>Fix phone number formatting in emails<commit_after> | import i18naddress
from django import template
from django.utils.translation import pgettext
register = template.Library()
@register.inclusion_tag("formatted_address.html")
def format_address(address, include_phone=True, inline=False, latin=False):
address_data = address.as_data()
address_data["name"] = (
pgettext("Address data", "%(first_name)s %(last_name)s") % address_data
)
address_data["country_code"] = address_data["country"]
address_data["street_address"] = pgettext(
"Address data", "%(street_address_1)s\n" "%(street_address_2)s" % address_data
)
address_lines = i18naddress.format_address(address_data, latin).split("\n")
if include_phone and address.phone:
address_lines.append(str(address.phone))
return {"address_lines": address_lines, "inline": inline}
| import i18naddress
from django import template
from django.utils.translation import pgettext
register = template.Library()
@register.inclusion_tag("formatted_address.html")
def format_address(address, include_phone=True, inline=False, latin=False):
address_data = address.as_data()
address_data["name"] = (
pgettext("Address data", "%(first_name)s %(last_name)s") % address_data
)
address_data["country_code"] = address_data["country"]
address_data["street_address"] = pgettext(
"Address data", "%(street_address_1)s\n" "%(street_address_2)s" % address_data
)
address_lines = i18naddress.format_address(address_data, latin).split("\n")
if include_phone and address.phone:
address_lines.append(address.phone)
return {"address_lines": address_lines, "inline": inline}
Fix phone number formatting in emailsimport i18naddress
from django import template
from django.utils.translation import pgettext
register = template.Library()
@register.inclusion_tag("formatted_address.html")
def format_address(address, include_phone=True, inline=False, latin=False):
address_data = address.as_data()
address_data["name"] = (
pgettext("Address data", "%(first_name)s %(last_name)s") % address_data
)
address_data["country_code"] = address_data["country"]
address_data["street_address"] = pgettext(
"Address data", "%(street_address_1)s\n" "%(street_address_2)s" % address_data
)
address_lines = i18naddress.format_address(address_data, latin).split("\n")
if include_phone and address.phone:
address_lines.append(str(address.phone))
return {"address_lines": address_lines, "inline": inline}
| <commit_before>import i18naddress
from django import template
from django.utils.translation import pgettext
register = template.Library()
@register.inclusion_tag("formatted_address.html")
def format_address(address, include_phone=True, inline=False, latin=False):
address_data = address.as_data()
address_data["name"] = (
pgettext("Address data", "%(first_name)s %(last_name)s") % address_data
)
address_data["country_code"] = address_data["country"]
address_data["street_address"] = pgettext(
"Address data", "%(street_address_1)s\n" "%(street_address_2)s" % address_data
)
address_lines = i18naddress.format_address(address_data, latin).split("\n")
if include_phone and address.phone:
address_lines.append(address.phone)
return {"address_lines": address_lines, "inline": inline}
<commit_msg>Fix phone number formatting in emails<commit_after>import i18naddress
from django import template
from django.utils.translation import pgettext
register = template.Library()
@register.inclusion_tag("formatted_address.html")
def format_address(address, include_phone=True, inline=False, latin=False):
address_data = address.as_data()
address_data["name"] = (
pgettext("Address data", "%(first_name)s %(last_name)s") % address_data
)
address_data["country_code"] = address_data["country"]
address_data["street_address"] = pgettext(
"Address data", "%(street_address_1)s\n" "%(street_address_2)s" % address_data
)
address_lines = i18naddress.format_address(address_data, latin).split("\n")
if include_phone and address.phone:
address_lines.append(str(address.phone))
return {"address_lines": address_lines, "inline": inline}
|
c62b42eb528babebf96e56738031dcda97868e80 | flowfairy/app.py | flowfairy/app.py | import tensorflow as tf
import numpy as np
import itertools as it
import importlib
from flowfairy.conf import settings
from flowfairy.utils import take
from flowfairy import data
from flowfairy.feature import FeatureManager
from flowfairy.core.queue import FlowQueue
from flowfairy.core.stage import stage
def load_net():
net = importlib.import_module(settings.NET).Net()
return net
def run(*args, **options):
coord = tf.train.Coordinator()
net = load_net()
queues = []
with tf.variable_scope('network') as scope:
for data_loader in data.provider:
fts = FeatureManager(data_loader)
queue = FlowQueue(fts, coord)
queues.append(queue)
X = queue.dequeue()
func = getattr(net, data_loader.name)
func(**dict(zip(fts.fields, X)))
scope.reuse_variables()
with tf.Session() as sess:
stage.before(sess, net)
for queue in queues: queue.start(sess)
sess.run(tf.global_variables_initializer())
try:
step = 1
while not coord.should_stop() and not net.should_stop():
stage.run(sess, step)
step += 1
except KeyboardInterrupt:
pass
coord.request_stop()
queue.stop()
coord.join(stop_grace_period_secs=5)
| import tensorflow as tf
import numpy as np
import itertools as it
import importlib
from flowfairy.conf import settings
from flowfairy.utils import take
from flowfairy import data
from flowfairy.feature import FeatureManager
from flowfairy.core.queue import FlowQueue
from flowfairy.core.stage import stage
def load_net():
net = importlib.import_module(settings.NET).Net()
return net
def run(*args, **options):
coord = tf.train.Coordinator()
net = load_net()
queues = []
for data_loader in data.provider:
with tf.variable_scope(data_loader.name) as scope:
fts = FeatureManager(data_loader)
queue = FlowQueue(fts, coord)
queues.append(queue)
X = queue.dequeue()
func = getattr(net, data_loader.name)
func(**dict(zip(fts.fields, X)))
scope.reuse_variables()
with tf.Session() as sess:
stage.before(sess, net)
for queue in queues: queue.start(sess)
sess.run(tf.global_variables_initializer())
try:
step = 1
while not coord.should_stop() and not net.should_stop():
stage.run(sess, step)
step += 1
except KeyboardInterrupt:
pass
coord.request_stop()
queue.stop()
coord.join(stop_grace_period_secs=5)
| Set name_scope of entire network to the dataset it handles | Set name_scope of entire network to the dataset it handles
| Python | mit | WhatDo/FlowFairy | import tensorflow as tf
import numpy as np
import itertools as it
import importlib
from flowfairy.conf import settings
from flowfairy.utils import take
from flowfairy import data
from flowfairy.feature import FeatureManager
from flowfairy.core.queue import FlowQueue
from flowfairy.core.stage import stage
def load_net():
net = importlib.import_module(settings.NET).Net()
return net
def run(*args, **options):
coord = tf.train.Coordinator()
net = load_net()
queues = []
with tf.variable_scope('network') as scope:
for data_loader in data.provider:
fts = FeatureManager(data_loader)
queue = FlowQueue(fts, coord)
queues.append(queue)
X = queue.dequeue()
func = getattr(net, data_loader.name)
func(**dict(zip(fts.fields, X)))
scope.reuse_variables()
with tf.Session() as sess:
stage.before(sess, net)
for queue in queues: queue.start(sess)
sess.run(tf.global_variables_initializer())
try:
step = 1
while not coord.should_stop() and not net.should_stop():
stage.run(sess, step)
step += 1
except KeyboardInterrupt:
pass
coord.request_stop()
queue.stop()
coord.join(stop_grace_period_secs=5)
Set name_scope of entire network to the dataset it handles | import tensorflow as tf
import numpy as np
import itertools as it
import importlib
from flowfairy.conf import settings
from flowfairy.utils import take
from flowfairy import data
from flowfairy.feature import FeatureManager
from flowfairy.core.queue import FlowQueue
from flowfairy.core.stage import stage
def load_net():
net = importlib.import_module(settings.NET).Net()
return net
def run(*args, **options):
coord = tf.train.Coordinator()
net = load_net()
queues = []
for data_loader in data.provider:
with tf.variable_scope(data_loader.name) as scope:
fts = FeatureManager(data_loader)
queue = FlowQueue(fts, coord)
queues.append(queue)
X = queue.dequeue()
func = getattr(net, data_loader.name)
func(**dict(zip(fts.fields, X)))
scope.reuse_variables()
with tf.Session() as sess:
stage.before(sess, net)
for queue in queues: queue.start(sess)
sess.run(tf.global_variables_initializer())
try:
step = 1
while not coord.should_stop() and not net.should_stop():
stage.run(sess, step)
step += 1
except KeyboardInterrupt:
pass
coord.request_stop()
queue.stop()
coord.join(stop_grace_period_secs=5)
| <commit_before>import tensorflow as tf
import numpy as np
import itertools as it
import importlib
from flowfairy.conf import settings
from flowfairy.utils import take
from flowfairy import data
from flowfairy.feature import FeatureManager
from flowfairy.core.queue import FlowQueue
from flowfairy.core.stage import stage
def load_net():
net = importlib.import_module(settings.NET).Net()
return net
def run(*args, **options):
coord = tf.train.Coordinator()
net = load_net()
queues = []
with tf.variable_scope('network') as scope:
for data_loader in data.provider:
fts = FeatureManager(data_loader)
queue = FlowQueue(fts, coord)
queues.append(queue)
X = queue.dequeue()
func = getattr(net, data_loader.name)
func(**dict(zip(fts.fields, X)))
scope.reuse_variables()
with tf.Session() as sess:
stage.before(sess, net)
for queue in queues: queue.start(sess)
sess.run(tf.global_variables_initializer())
try:
step = 1
while not coord.should_stop() and not net.should_stop():
stage.run(sess, step)
step += 1
except KeyboardInterrupt:
pass
coord.request_stop()
queue.stop()
coord.join(stop_grace_period_secs=5)
<commit_msg>Set name_scope of entire network to the dataset it handles<commit_after> | import tensorflow as tf
import numpy as np
import itertools as it
import importlib
from flowfairy.conf import settings
from flowfairy.utils import take
from flowfairy import data
from flowfairy.feature import FeatureManager
from flowfairy.core.queue import FlowQueue
from flowfairy.core.stage import stage
def load_net():
net = importlib.import_module(settings.NET).Net()
return net
def run(*args, **options):
coord = tf.train.Coordinator()
net = load_net()
queues = []
for data_loader in data.provider:
with tf.variable_scope(data_loader.name) as scope:
fts = FeatureManager(data_loader)
queue = FlowQueue(fts, coord)
queues.append(queue)
X = queue.dequeue()
func = getattr(net, data_loader.name)
func(**dict(zip(fts.fields, X)))
scope.reuse_variables()
with tf.Session() as sess:
stage.before(sess, net)
for queue in queues: queue.start(sess)
sess.run(tf.global_variables_initializer())
try:
step = 1
while not coord.should_stop() and not net.should_stop():
stage.run(sess, step)
step += 1
except KeyboardInterrupt:
pass
coord.request_stop()
queue.stop()
coord.join(stop_grace_period_secs=5)
| import tensorflow as tf
import numpy as np
import itertools as it
import importlib
from flowfairy.conf import settings
from flowfairy.utils import take
from flowfairy import data
from flowfairy.feature import FeatureManager
from flowfairy.core.queue import FlowQueue
from flowfairy.core.stage import stage
def load_net():
net = importlib.import_module(settings.NET).Net()
return net
def run(*args, **options):
coord = tf.train.Coordinator()
net = load_net()
queues = []
with tf.variable_scope('network') as scope:
for data_loader in data.provider:
fts = FeatureManager(data_loader)
queue = FlowQueue(fts, coord)
queues.append(queue)
X = queue.dequeue()
func = getattr(net, data_loader.name)
func(**dict(zip(fts.fields, X)))
scope.reuse_variables()
with tf.Session() as sess:
stage.before(sess, net)
for queue in queues: queue.start(sess)
sess.run(tf.global_variables_initializer())
try:
step = 1
while not coord.should_stop() and not net.should_stop():
stage.run(sess, step)
step += 1
except KeyboardInterrupt:
pass
coord.request_stop()
queue.stop()
coord.join(stop_grace_period_secs=5)
Set name_scope of entire network to the dataset it handlesimport tensorflow as tf
import numpy as np
import itertools as it
import importlib
from flowfairy.conf import settings
from flowfairy.utils import take
from flowfairy import data
from flowfairy.feature import FeatureManager
from flowfairy.core.queue import FlowQueue
from flowfairy.core.stage import stage
def load_net():
net = importlib.import_module(settings.NET).Net()
return net
def run(*args, **options):
coord = tf.train.Coordinator()
net = load_net()
queues = []
for data_loader in data.provider:
with tf.variable_scope(data_loader.name) as scope:
fts = FeatureManager(data_loader)
queue = FlowQueue(fts, coord)
queues.append(queue)
X = queue.dequeue()
func = getattr(net, data_loader.name)
func(**dict(zip(fts.fields, X)))
scope.reuse_variables()
with tf.Session() as sess:
stage.before(sess, net)
for queue in queues: queue.start(sess)
sess.run(tf.global_variables_initializer())
try:
step = 1
while not coord.should_stop() and not net.should_stop():
stage.run(sess, step)
step += 1
except KeyboardInterrupt:
pass
coord.request_stop()
queue.stop()
coord.join(stop_grace_period_secs=5)
| <commit_before>import tensorflow as tf
import numpy as np
import itertools as it
import importlib
from flowfairy.conf import settings
from flowfairy.utils import take
from flowfairy import data
from flowfairy.feature import FeatureManager
from flowfairy.core.queue import FlowQueue
from flowfairy.core.stage import stage
def load_net():
net = importlib.import_module(settings.NET).Net()
return net
def run(*args, **options):
coord = tf.train.Coordinator()
net = load_net()
queues = []
with tf.variable_scope('network') as scope:
for data_loader in data.provider:
fts = FeatureManager(data_loader)
queue = FlowQueue(fts, coord)
queues.append(queue)
X = queue.dequeue()
func = getattr(net, data_loader.name)
func(**dict(zip(fts.fields, X)))
scope.reuse_variables()
with tf.Session() as sess:
stage.before(sess, net)
for queue in queues: queue.start(sess)
sess.run(tf.global_variables_initializer())
try:
step = 1
while not coord.should_stop() and not net.should_stop():
stage.run(sess, step)
step += 1
except KeyboardInterrupt:
pass
coord.request_stop()
queue.stop()
coord.join(stop_grace_period_secs=5)
<commit_msg>Set name_scope of entire network to the dataset it handles<commit_after>import tensorflow as tf
import numpy as np
import itertools as it
import importlib
from flowfairy.conf import settings
from flowfairy.utils import take
from flowfairy import data
from flowfairy.feature import FeatureManager
from flowfairy.core.queue import FlowQueue
from flowfairy.core.stage import stage
def load_net():
net = importlib.import_module(settings.NET).Net()
return net
def run(*args, **options):
coord = tf.train.Coordinator()
net = load_net()
queues = []
for data_loader in data.provider:
with tf.variable_scope(data_loader.name) as scope:
fts = FeatureManager(data_loader)
queue = FlowQueue(fts, coord)
queues.append(queue)
X = queue.dequeue()
func = getattr(net, data_loader.name)
func(**dict(zip(fts.fields, X)))
scope.reuse_variables()
with tf.Session() as sess:
stage.before(sess, net)
for queue in queues: queue.start(sess)
sess.run(tf.global_variables_initializer())
try:
step = 1
while not coord.should_stop() and not net.should_stop():
stage.run(sess, step)
step += 1
except KeyboardInterrupt:
pass
coord.request_stop()
queue.stop()
coord.join(stop_grace_period_secs=5)
|
8ea996de13e1ad3c9865866385fa0ecb49d6cbca | tests/help_test.py | tests/help_test.py | from __future__ import unicode_literals
import os
import subprocess
import sys
import unittest
import mopidy
class HelpTest(unittest.TestCase):
def test_help_has_mopidy_options(self):
mopidy_dir = os.path.dirname(mopidy.__file__)
args = [sys.executable, mopidy_dir, '--help']
python_path = sys.path[:]
python_path.insert(0, os.path.join(mopidy_dir, '..'))
process = subprocess.Popen(
args,
env={'PYTHONPATH': ':'.join(python_path)},
stdout=subprocess.PIPE)
output = process.communicate()[0]
self.assertIn('--version', output)
self.assertIn('--help', output)
self.assertIn('--quiet', output)
self.assertIn('--verbose', output)
self.assertIn('--save-debug-log', output)
self.assertIn('--config', output)
self.assertIn('--option', output)
| from __future__ import unicode_literals
import os
import subprocess
import sys
import unittest
import mopidy
class HelpTest(unittest.TestCase):
def test_help_has_mopidy_options(self):
mopidy_dir = os.path.dirname(mopidy.__file__)
args = [sys.executable, mopidy_dir, '--help']
process = subprocess.Popen(
args,
env={'PYTHONPATH': os.path.join(mopidy_dir, '..')},
stdout=subprocess.PIPE)
output = process.communicate()[0]
self.assertIn('--version', output)
self.assertIn('--help', output)
self.assertIn('--quiet', output)
self.assertIn('--verbose', output)
self.assertIn('--save-debug-log', output)
self.assertIn('--config', output)
self.assertIn('--option', output)
| Revert "tests: Don't redefine PYTHONPATH" | Revert "tests: Don't redefine PYTHONPATH"
This reverts commit 6be5cc0f1b1d34521fa8d8c91ca1cc2a96a65b69.
| Python | apache-2.0 | jodal/mopidy,adamcik/mopidy,mokieyue/mopidy,jcass77/mopidy,glogiotatidis/mopidy,diandiankan/mopidy,bencevans/mopidy,quartz55/mopidy,dbrgn/mopidy,abarisain/mopidy,swak/mopidy,rawdlite/mopidy,jcass77/mopidy,ZenithDK/mopidy,mopidy/mopidy,bacontext/mopidy,diandiankan/mopidy,jodal/mopidy,diandiankan/mopidy,ali/mopidy,swak/mopidy,liamw9534/mopidy,bacontext/mopidy,vrs01/mopidy,hkariti/mopidy,mokieyue/mopidy,glogiotatidis/mopidy,vrs01/mopidy,swak/mopidy,ali/mopidy,rawdlite/mopidy,woutervanwijk/mopidy,jmarsik/mopidy,hkariti/mopidy,quartz55/mopidy,ZenithDK/mopidy,pacificIT/mopidy,priestd09/mopidy,dbrgn/mopidy,pacificIT/mopidy,vrs01/mopidy,SuperStarPL/mopidy,glogiotatidis/mopidy,dbrgn/mopidy,jodal/mopidy,adamcik/mopidy,jmarsik/mopidy,kingosticks/mopidy,priestd09/mopidy,mopidy/mopidy,rawdlite/mopidy,jmarsik/mopidy,hkariti/mopidy,SuperStarPL/mopidy,hkariti/mopidy,mokieyue/mopidy,SuperStarPL/mopidy,tkem/mopidy,ZenithDK/mopidy,tkem/mopidy,jcass77/mopidy,ali/mopidy,pacificIT/mopidy,abarisain/mopidy,kingosticks/mopidy,bacontext/mopidy,priestd09/mopidy,glogiotatidis/mopidy,dbrgn/mopidy,jmarsik/mopidy,vrs01/mopidy,quartz55/mopidy,bacontext/mopidy,quartz55/mopidy,mopidy/mopidy,adamcik/mopidy,SuperStarPL/mopidy,tkem/mopidy,rawdlite/mopidy,diandiankan/mopidy,woutervanwijk/mopidy,ZenithDK/mopidy,mokieyue/mopidy,swak/mopidy,bencevans/mopidy,ali/mopidy,liamw9534/mopidy,tkem/mopidy,pacificIT/mopidy,bencevans/mopidy,kingosticks/mopidy,bencevans/mopidy | from __future__ import unicode_literals
import os
import subprocess
import sys
import unittest
import mopidy
class HelpTest(unittest.TestCase):
def test_help_has_mopidy_options(self):
mopidy_dir = os.path.dirname(mopidy.__file__)
args = [sys.executable, mopidy_dir, '--help']
python_path = sys.path[:]
python_path.insert(0, os.path.join(mopidy_dir, '..'))
process = subprocess.Popen(
args,
env={'PYTHONPATH': ':'.join(python_path)},
stdout=subprocess.PIPE)
output = process.communicate()[0]
self.assertIn('--version', output)
self.assertIn('--help', output)
self.assertIn('--quiet', output)
self.assertIn('--verbose', output)
self.assertIn('--save-debug-log', output)
self.assertIn('--config', output)
self.assertIn('--option', output)
Revert "tests: Don't redefine PYTHONPATH"
This reverts commit 6be5cc0f1b1d34521fa8d8c91ca1cc2a96a65b69. | from __future__ import unicode_literals
import os
import subprocess
import sys
import unittest
import mopidy
class HelpTest(unittest.TestCase):
def test_help_has_mopidy_options(self):
mopidy_dir = os.path.dirname(mopidy.__file__)
args = [sys.executable, mopidy_dir, '--help']
process = subprocess.Popen(
args,
env={'PYTHONPATH': os.path.join(mopidy_dir, '..')},
stdout=subprocess.PIPE)
output = process.communicate()[0]
self.assertIn('--version', output)
self.assertIn('--help', output)
self.assertIn('--quiet', output)
self.assertIn('--verbose', output)
self.assertIn('--save-debug-log', output)
self.assertIn('--config', output)
self.assertIn('--option', output)
| <commit_before>from __future__ import unicode_literals
import os
import subprocess
import sys
import unittest
import mopidy
class HelpTest(unittest.TestCase):
def test_help_has_mopidy_options(self):
mopidy_dir = os.path.dirname(mopidy.__file__)
args = [sys.executable, mopidy_dir, '--help']
python_path = sys.path[:]
python_path.insert(0, os.path.join(mopidy_dir, '..'))
process = subprocess.Popen(
args,
env={'PYTHONPATH': ':'.join(python_path)},
stdout=subprocess.PIPE)
output = process.communicate()[0]
self.assertIn('--version', output)
self.assertIn('--help', output)
self.assertIn('--quiet', output)
self.assertIn('--verbose', output)
self.assertIn('--save-debug-log', output)
self.assertIn('--config', output)
self.assertIn('--option', output)
<commit_msg>Revert "tests: Don't redefine PYTHONPATH"
This reverts commit 6be5cc0f1b1d34521fa8d8c91ca1cc2a96a65b69.<commit_after> | from __future__ import unicode_literals
import os
import subprocess
import sys
import unittest
import mopidy
class HelpTest(unittest.TestCase):
def test_help_has_mopidy_options(self):
mopidy_dir = os.path.dirname(mopidy.__file__)
args = [sys.executable, mopidy_dir, '--help']
process = subprocess.Popen(
args,
env={'PYTHONPATH': os.path.join(mopidy_dir, '..')},
stdout=subprocess.PIPE)
output = process.communicate()[0]
self.assertIn('--version', output)
self.assertIn('--help', output)
self.assertIn('--quiet', output)
self.assertIn('--verbose', output)
self.assertIn('--save-debug-log', output)
self.assertIn('--config', output)
self.assertIn('--option', output)
| from __future__ import unicode_literals
import os
import subprocess
import sys
import unittest
import mopidy
class HelpTest(unittest.TestCase):
def test_help_has_mopidy_options(self):
mopidy_dir = os.path.dirname(mopidy.__file__)
args = [sys.executable, mopidy_dir, '--help']
python_path = sys.path[:]
python_path.insert(0, os.path.join(mopidy_dir, '..'))
process = subprocess.Popen(
args,
env={'PYTHONPATH': ':'.join(python_path)},
stdout=subprocess.PIPE)
output = process.communicate()[0]
self.assertIn('--version', output)
self.assertIn('--help', output)
self.assertIn('--quiet', output)
self.assertIn('--verbose', output)
self.assertIn('--save-debug-log', output)
self.assertIn('--config', output)
self.assertIn('--option', output)
Revert "tests: Don't redefine PYTHONPATH"
This reverts commit 6be5cc0f1b1d34521fa8d8c91ca1cc2a96a65b69.from __future__ import unicode_literals
import os
import subprocess
import sys
import unittest
import mopidy
class HelpTest(unittest.TestCase):
def test_help_has_mopidy_options(self):
mopidy_dir = os.path.dirname(mopidy.__file__)
args = [sys.executable, mopidy_dir, '--help']
process = subprocess.Popen(
args,
env={'PYTHONPATH': os.path.join(mopidy_dir, '..')},
stdout=subprocess.PIPE)
output = process.communicate()[0]
self.assertIn('--version', output)
self.assertIn('--help', output)
self.assertIn('--quiet', output)
self.assertIn('--verbose', output)
self.assertIn('--save-debug-log', output)
self.assertIn('--config', output)
self.assertIn('--option', output)
| <commit_before>from __future__ import unicode_literals
import os
import subprocess
import sys
import unittest
import mopidy
class HelpTest(unittest.TestCase):
def test_help_has_mopidy_options(self):
mopidy_dir = os.path.dirname(mopidy.__file__)
args = [sys.executable, mopidy_dir, '--help']
python_path = sys.path[:]
python_path.insert(0, os.path.join(mopidy_dir, '..'))
process = subprocess.Popen(
args,
env={'PYTHONPATH': ':'.join(python_path)},
stdout=subprocess.PIPE)
output = process.communicate()[0]
self.assertIn('--version', output)
self.assertIn('--help', output)
self.assertIn('--quiet', output)
self.assertIn('--verbose', output)
self.assertIn('--save-debug-log', output)
self.assertIn('--config', output)
self.assertIn('--option', output)
<commit_msg>Revert "tests: Don't redefine PYTHONPATH"
This reverts commit 6be5cc0f1b1d34521fa8d8c91ca1cc2a96a65b69.<commit_after>from __future__ import unicode_literals
import os
import subprocess
import sys
import unittest
import mopidy
class HelpTest(unittest.TestCase):
def test_help_has_mopidy_options(self):
mopidy_dir = os.path.dirname(mopidy.__file__)
args = [sys.executable, mopidy_dir, '--help']
process = subprocess.Popen(
args,
env={'PYTHONPATH': os.path.join(mopidy_dir, '..')},
stdout=subprocess.PIPE)
output = process.communicate()[0]
self.assertIn('--version', output)
self.assertIn('--help', output)
self.assertIn('--quiet', output)
self.assertIn('--verbose', output)
self.assertIn('--save-debug-log', output)
self.assertIn('--config', output)
self.assertIn('--option', output)
|
f2af85f7e9de7ca7494a849856a9274a5d969378 | icekit_events/apps.py | icekit_events/apps.py | """
App configuration for ``icekit_events`` app.
"""
# Register signal handlers, but avoid interacting with the database.
# See: https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.AppConfig.ready
from django.apps import AppConfig
from django.utils.module_loading import autodiscover_modules
from any_urlfield.forms import SimpleRawIdWidget
from icekit.fields import ICEkitURLField
class AppConfig(AppConfig):
name = '_'.join(__name__.split('.')[:-1])
label = 'icekit_events'
verbose_name = "Events"
def ready(self):
# look through installed apps to see what event types are registered
autodiscover_modules('event_type_plugins')
from .models import EventBase
ICEkitURLField.register_model(
EventBase, widget=SimpleRawIdWidget(EventBase), title='Event')
| """
App configuration for ``icekit_events`` app.
"""
# Register signal handlers, but avoid interacting with the database.
# See: https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.AppConfig.ready
from django.apps import AppConfig
from django.utils.module_loading import autodiscover_modules
from any_urlfield.forms import SimpleRawIdWidget
from icekit.fields import ICEkitURLField
class AppConfig(AppConfig):
name = '_'.join(__name__.split('.')[:-1])
label = 'icekit_events'
verbose_name = "Events"
def ready(self):
# look through installed apps to see what event types are registered
autodiscover_modules('event_type_plugins')
from .models import EventBase
ICEkitURLField.register_model_once(
EventBase, widget=SimpleRawIdWidget(EventBase), title='Event')
| Fix test run failures with double-registration on ICEkitURLField | Fix test run failures with double-registration on ICEkitURLField
Use the new `ICEkitURLField.register_model_once` method available in
django-icekit to safely register base events for `ICEkitURLField`
without the risk that they will be re-registered (and therefore fail)
because of the way the unit tests reload this app.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/icekit-events,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/icekit-events,ic-labs/icekit-events | """
App configuration for ``icekit_events`` app.
"""
# Register signal handlers, but avoid interacting with the database.
# See: https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.AppConfig.ready
from django.apps import AppConfig
from django.utils.module_loading import autodiscover_modules
from any_urlfield.forms import SimpleRawIdWidget
from icekit.fields import ICEkitURLField
class AppConfig(AppConfig):
name = '_'.join(__name__.split('.')[:-1])
label = 'icekit_events'
verbose_name = "Events"
def ready(self):
# look through installed apps to see what event types are registered
autodiscover_modules('event_type_plugins')
from .models import EventBase
ICEkitURLField.register_model(
EventBase, widget=SimpleRawIdWidget(EventBase), title='Event')
Fix test run failures with double-registration on ICEkitURLField
Use the new `ICEkitURLField.register_model_once` method available in
django-icekit to safely register base events for `ICEkitURLField`
without the risk that they will be re-registered (and therefore fail)
because of the way the unit tests reload this app. | """
App configuration for ``icekit_events`` app.
"""
# Register signal handlers, but avoid interacting with the database.
# See: https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.AppConfig.ready
from django.apps import AppConfig
from django.utils.module_loading import autodiscover_modules
from any_urlfield.forms import SimpleRawIdWidget
from icekit.fields import ICEkitURLField
class AppConfig(AppConfig):
name = '_'.join(__name__.split('.')[:-1])
label = 'icekit_events'
verbose_name = "Events"
def ready(self):
# look through installed apps to see what event types are registered
autodiscover_modules('event_type_plugins')
from .models import EventBase
ICEkitURLField.register_model_once(
EventBase, widget=SimpleRawIdWidget(EventBase), title='Event')
| <commit_before>"""
App configuration for ``icekit_events`` app.
"""
# Register signal handlers, but avoid interacting with the database.
# See: https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.AppConfig.ready
from django.apps import AppConfig
from django.utils.module_loading import autodiscover_modules
from any_urlfield.forms import SimpleRawIdWidget
from icekit.fields import ICEkitURLField
class AppConfig(AppConfig):
name = '_'.join(__name__.split('.')[:-1])
label = 'icekit_events'
verbose_name = "Events"
def ready(self):
# look through installed apps to see what event types are registered
autodiscover_modules('event_type_plugins')
from .models import EventBase
ICEkitURLField.register_model(
EventBase, widget=SimpleRawIdWidget(EventBase), title='Event')
<commit_msg>Fix test run failures with double-registration on ICEkitURLField
Use the new `ICEkitURLField.register_model_once` method available in
django-icekit to safely register base events for `ICEkitURLField`
without the risk that they will be re-registered (and therefore fail)
because of the way the unit tests reload this app.<commit_after> | """
App configuration for ``icekit_events`` app.
"""
# Register signal handlers, but avoid interacting with the database.
# See: https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.AppConfig.ready
from django.apps import AppConfig
from django.utils.module_loading import autodiscover_modules
from any_urlfield.forms import SimpleRawIdWidget
from icekit.fields import ICEkitURLField
class AppConfig(AppConfig):
name = '_'.join(__name__.split('.')[:-1])
label = 'icekit_events'
verbose_name = "Events"
def ready(self):
# look through installed apps to see what event types are registered
autodiscover_modules('event_type_plugins')
from .models import EventBase
ICEkitURLField.register_model_once(
EventBase, widget=SimpleRawIdWidget(EventBase), title='Event')
| """
App configuration for ``icekit_events`` app.
"""
# Register signal handlers, but avoid interacting with the database.
# See: https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.AppConfig.ready
from django.apps import AppConfig
from django.utils.module_loading import autodiscover_modules
from any_urlfield.forms import SimpleRawIdWidget
from icekit.fields import ICEkitURLField
class AppConfig(AppConfig):
name = '_'.join(__name__.split('.')[:-1])
label = 'icekit_events'
verbose_name = "Events"
def ready(self):
# look through installed apps to see what event types are registered
autodiscover_modules('event_type_plugins')
from .models import EventBase
ICEkitURLField.register_model(
EventBase, widget=SimpleRawIdWidget(EventBase), title='Event')
Fix test run failures with double-registration on ICEkitURLField
Use the new `ICEkitURLField.register_model_once` method available in
django-icekit to safely register base events for `ICEkitURLField`
without the risk that they will be re-registered (and therefore fail)
because of the way the unit tests reload this app."""
App configuration for ``icekit_events`` app.
"""
# Register signal handlers, but avoid interacting with the database.
# See: https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.AppConfig.ready
from django.apps import AppConfig
from django.utils.module_loading import autodiscover_modules
from any_urlfield.forms import SimpleRawIdWidget
from icekit.fields import ICEkitURLField
class AppConfig(AppConfig):
name = '_'.join(__name__.split('.')[:-1])
label = 'icekit_events'
verbose_name = "Events"
def ready(self):
# look through installed apps to see what event types are registered
autodiscover_modules('event_type_plugins')
from .models import EventBase
ICEkitURLField.register_model_once(
EventBase, widget=SimpleRawIdWidget(EventBase), title='Event')
| <commit_before>"""
App configuration for ``icekit_events`` app.
"""
# Register signal handlers, but avoid interacting with the database.
# See: https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.AppConfig.ready
from django.apps import AppConfig
from django.utils.module_loading import autodiscover_modules
from any_urlfield.forms import SimpleRawIdWidget
from icekit.fields import ICEkitURLField
class AppConfig(AppConfig):
name = '_'.join(__name__.split('.')[:-1])
label = 'icekit_events'
verbose_name = "Events"
def ready(self):
# look through installed apps to see what event types are registered
autodiscover_modules('event_type_plugins')
from .models import EventBase
ICEkitURLField.register_model(
EventBase, widget=SimpleRawIdWidget(EventBase), title='Event')
<commit_msg>Fix test run failures with double-registration on ICEkitURLField
Use the new `ICEkitURLField.register_model_once` method available in
django-icekit to safely register base events for `ICEkitURLField`
without the risk that they will be re-registered (and therefore fail)
because of the way the unit tests reload this app.<commit_after>"""
App configuration for ``icekit_events`` app.
"""
# Register signal handlers, but avoid interacting with the database.
# See: https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.AppConfig.ready
from django.apps import AppConfig
from django.utils.module_loading import autodiscover_modules
from any_urlfield.forms import SimpleRawIdWidget
from icekit.fields import ICEkitURLField
class AppConfig(AppConfig):
name = '_'.join(__name__.split('.')[:-1])
label = 'icekit_events'
verbose_name = "Events"
def ready(self):
# look through installed apps to see what event types are registered
autodiscover_modules('event_type_plugins')
from .models import EventBase
ICEkitURLField.register_model_once(
EventBase, widget=SimpleRawIdWidget(EventBase), title='Event')
|
9a64f7b08704f2f343564698d83dd73bb1f0d4b2 | slackbot_settings.py | slackbot_settings.py | DEFAULT_REPLY = "Sorry, I did not understand you."
ERRORS_TO = 'general'
PLUGINS = [
'plugins.witai'
]
| DEFAULT_REPLY = "Sorry, I did not understand you."
PLUGINS = [
'plugins.witai'
]
| Remove sending error to general channel | Remove sending error to general channel
| Python | mit | sanjaybv/netbot | DEFAULT_REPLY = "Sorry, I did not understand you."
ERRORS_TO = 'general'
PLUGINS = [
'plugins.witai'
]
Remove sending error to general channel | DEFAULT_REPLY = "Sorry, I did not understand you."
PLUGINS = [
'plugins.witai'
]
| <commit_before>DEFAULT_REPLY = "Sorry, I did not understand you."
ERRORS_TO = 'general'
PLUGINS = [
'plugins.witai'
]
<commit_msg>Remove sending error to general channel<commit_after> | DEFAULT_REPLY = "Sorry, I did not understand you."
PLUGINS = [
'plugins.witai'
]
| DEFAULT_REPLY = "Sorry, I did not understand you."
ERRORS_TO = 'general'
PLUGINS = [
'plugins.witai'
]
Remove sending error to general channelDEFAULT_REPLY = "Sorry, I did not understand you."
PLUGINS = [
'plugins.witai'
]
| <commit_before>DEFAULT_REPLY = "Sorry, I did not understand you."
ERRORS_TO = 'general'
PLUGINS = [
'plugins.witai'
]
<commit_msg>Remove sending error to general channel<commit_after>DEFAULT_REPLY = "Sorry, I did not understand you."
PLUGINS = [
'plugins.witai'
]
|
827644a143a0fae0a1fa34ce2c624b199d0c1b63 | bisnode/models.py | bisnode/models.py | from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
from .bisnode import get_bisnode_company_report
class BisnodeRatingReport(models.Model):
organization_number = models.CharField(max_length=10)
rating = models.CharField(max_length=3, choices=RATING_CHOICES,
null=True, blank=True)
date_of_rating = models.DateField(blank=True, null=True)
last_updated = models.DateTimeField(auto_now=True)
def get(self):
rating_report = get_bisnode_company_report(
report_type=COMPANY_RATING_REPORT,
organization_number=self.organization_number)
company_data = rating_report.generalCompanyData[0]
self.rating_code = company_data['ratingCode']
self.date_of_rating = company_data['dateOfRating']
self.save()
| from datetime import datetime, date
from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
from .bisnode import get_bisnode_company_report
def bisnode_date_to_date(bisnode_date):
formatted_datetime = datetime.strptime(bisnode_date, "%Y%m%d")
return formatted_datetime.date()
class BisnodeRatingReport(models.Model):
organization_number = models.CharField(max_length=10)
rating = models.CharField(max_length=3, choices=RATING_CHOICES,
null=True, blank=True)
date_of_rating = models.DateField(blank=True, null=True)
last_updated = models.DateTimeField(auto_now=True)
def get(self):
rating_report = get_bisnode_company_report(
report_type=COMPANY_RATING_REPORT,
organization_number=self.organization_number)
company_data = rating_report.generalCompanyData[0]
self.rating_code = company_data['ratingCode']
self.date_of_rating = bisnode_date_to_date(
company_data['dateOfRating'])
self.save()
| Save dates from Bisnode correctly | Save dates from Bisnode correctly
| Python | mit | FundedByMe/django-bisnode | from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
from .bisnode import get_bisnode_company_report
class BisnodeRatingReport(models.Model):
organization_number = models.CharField(max_length=10)
rating = models.CharField(max_length=3, choices=RATING_CHOICES,
null=True, blank=True)
date_of_rating = models.DateField(blank=True, null=True)
last_updated = models.DateTimeField(auto_now=True)
def get(self):
rating_report = get_bisnode_company_report(
report_type=COMPANY_RATING_REPORT,
organization_number=self.organization_number)
company_data = rating_report.generalCompanyData[0]
self.rating_code = company_data['ratingCode']
self.date_of_rating = company_data['dateOfRating']
self.save()
Save dates from Bisnode correctly | from datetime import datetime, date
from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
from .bisnode import get_bisnode_company_report
def bisnode_date_to_date(bisnode_date):
formatted_datetime = datetime.strptime(bisnode_date, "%Y%m%d")
return formatted_datetime.date()
class BisnodeRatingReport(models.Model):
organization_number = models.CharField(max_length=10)
rating = models.CharField(max_length=3, choices=RATING_CHOICES,
null=True, blank=True)
date_of_rating = models.DateField(blank=True, null=True)
last_updated = models.DateTimeField(auto_now=True)
def get(self):
rating_report = get_bisnode_company_report(
report_type=COMPANY_RATING_REPORT,
organization_number=self.organization_number)
company_data = rating_report.generalCompanyData[0]
self.rating_code = company_data['ratingCode']
self.date_of_rating = bisnode_date_to_date(
company_data['dateOfRating'])
self.save()
| <commit_before>from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
from .bisnode import get_bisnode_company_report
class BisnodeRatingReport(models.Model):
organization_number = models.CharField(max_length=10)
rating = models.CharField(max_length=3, choices=RATING_CHOICES,
null=True, blank=True)
date_of_rating = models.DateField(blank=True, null=True)
last_updated = models.DateTimeField(auto_now=True)
def get(self):
rating_report = get_bisnode_company_report(
report_type=COMPANY_RATING_REPORT,
organization_number=self.organization_number)
company_data = rating_report.generalCompanyData[0]
self.rating_code = company_data['ratingCode']
self.date_of_rating = company_data['dateOfRating']
self.save()
<commit_msg>Save dates from Bisnode correctly<commit_after> | from datetime import datetime, date
from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
from .bisnode import get_bisnode_company_report
def bisnode_date_to_date(bisnode_date):
formatted_datetime = datetime.strptime(bisnode_date, "%Y%m%d")
return formatted_datetime.date()
class BisnodeRatingReport(models.Model):
organization_number = models.CharField(max_length=10)
rating = models.CharField(max_length=3, choices=RATING_CHOICES,
null=True, blank=True)
date_of_rating = models.DateField(blank=True, null=True)
last_updated = models.DateTimeField(auto_now=True)
def get(self):
rating_report = get_bisnode_company_report(
report_type=COMPANY_RATING_REPORT,
organization_number=self.organization_number)
company_data = rating_report.generalCompanyData[0]
self.rating_code = company_data['ratingCode']
self.date_of_rating = bisnode_date_to_date(
company_data['dateOfRating'])
self.save()
| from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
from .bisnode import get_bisnode_company_report
class BisnodeRatingReport(models.Model):
organization_number = models.CharField(max_length=10)
rating = models.CharField(max_length=3, choices=RATING_CHOICES,
null=True, blank=True)
date_of_rating = models.DateField(blank=True, null=True)
last_updated = models.DateTimeField(auto_now=True)
def get(self):
rating_report = get_bisnode_company_report(
report_type=COMPANY_RATING_REPORT,
organization_number=self.organization_number)
company_data = rating_report.generalCompanyData[0]
self.rating_code = company_data['ratingCode']
self.date_of_rating = company_data['dateOfRating']
self.save()
Save dates from Bisnode correctlyfrom datetime import datetime, date
from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
from .bisnode import get_bisnode_company_report
def bisnode_date_to_date(bisnode_date):
formatted_datetime = datetime.strptime(bisnode_date, "%Y%m%d")
return formatted_datetime.date()
class BisnodeRatingReport(models.Model):
organization_number = models.CharField(max_length=10)
rating = models.CharField(max_length=3, choices=RATING_CHOICES,
null=True, blank=True)
date_of_rating = models.DateField(blank=True, null=True)
last_updated = models.DateTimeField(auto_now=True)
def get(self):
rating_report = get_bisnode_company_report(
report_type=COMPANY_RATING_REPORT,
organization_number=self.organization_number)
company_data = rating_report.generalCompanyData[0]
self.rating_code = company_data['ratingCode']
self.date_of_rating = bisnode_date_to_date(
company_data['dateOfRating'])
self.save()
| <commit_before>from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
from .bisnode import get_bisnode_company_report
class BisnodeRatingReport(models.Model):
organization_number = models.CharField(max_length=10)
rating = models.CharField(max_length=3, choices=RATING_CHOICES,
null=True, blank=True)
date_of_rating = models.DateField(blank=True, null=True)
last_updated = models.DateTimeField(auto_now=True)
def get(self):
rating_report = get_bisnode_company_report(
report_type=COMPANY_RATING_REPORT,
organization_number=self.organization_number)
company_data = rating_report.generalCompanyData[0]
self.rating_code = company_data['ratingCode']
self.date_of_rating = company_data['dateOfRating']
self.save()
<commit_msg>Save dates from Bisnode correctly<commit_after>from datetime import datetime, date
from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
from .bisnode import get_bisnode_company_report
def bisnode_date_to_date(bisnode_date):
formatted_datetime = datetime.strptime(bisnode_date, "%Y%m%d")
return formatted_datetime.date()
class BisnodeRatingReport(models.Model):
organization_number = models.CharField(max_length=10)
rating = models.CharField(max_length=3, choices=RATING_CHOICES,
null=True, blank=True)
date_of_rating = models.DateField(blank=True, null=True)
last_updated = models.DateTimeField(auto_now=True)
def get(self):
rating_report = get_bisnode_company_report(
report_type=COMPANY_RATING_REPORT,
organization_number=self.organization_number)
company_data = rating_report.generalCompanyData[0]
self.rating_code = company_data['ratingCode']
self.date_of_rating = bisnode_date_to_date(
company_data['dateOfRating'])
self.save()
|
f5fd149316d1a5bfc0e271c2c0e0fc6ee74daa96 | models/augmented_user.py | models/augmented_user.py | # coding: utf-8
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Model for an Oppia editor."""
__author__ = 'Sean Lip'
from exploration import Exploration
from google.appengine.ext import ndb
class AugmentedUser(ndb.Model):
"""Stores information about a particular user."""
# The corresponding user.
user = ndb.UserProperty(required=True)
# The list of explorations that this user has editing rights for.
editable_explorations = ndb.KeyProperty(kind=Exploration, repeated=True)
@classmethod
def get(cls, user):
"""Gets (or creates) the corresponding AugmentedUser."""
augmented_user = cls.query().filter(
cls.user == user).get()
if not augmented_user:
augmented_user = cls(user=user)
augmented_user.put()
return augmented_user
| # coding: utf-8
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Model for an Oppia editor."""
__author__ = 'Sean Lip'
from exploration import Exploration
from google.appengine.ext import ndb
class AugmentedUser(ndb.Model):
"""Stores information about a particular user."""
# TODO(sll): Should this class be keyed by user.email()?
# The corresponding user.
user = ndb.UserProperty(required=True)
# The list of explorations that this user has editing rights for.
editable_explorations = ndb.KeyProperty(kind=Exploration, repeated=True)
@classmethod
def get(cls, user):
"""Gets (or creates) the corresponding AugmentedUser."""
augmented_user = cls.query().filter(
cls.user == user).get()
if not augmented_user:
augmented_user = cls(user=user)
augmented_user.put()
return augmented_user
| Add TODO to think about. | Add TODO to think about.
| Python | apache-2.0 | sanyaade-teachings/oppia,danieljjh/oppia,kaffeel/oppia,whygee/oppia,kennho/oppia,directorlive/oppia,sarahfo/oppia,toooooper/oppia,fernandopinhati/oppia,VictoriaRoux/oppia,danieljjh/oppia,Atlas-Sailed-Co/oppia,fernandopinhati/oppia,DewarM/oppia,brylie/oppia,oppia/oppia,aldeka/oppia,amgowano/oppia,AllanYangZhou/oppia,sdulal/oppia,mit0110/oppia,souravbadami/oppia,raju249/oppia,AllanYangZhou/oppia,anthkris/oppia,amgowano/oppia,sunu/oppia-test-4,rackstar17/oppia,miyucy/oppia,kevinlee12/oppia,jestapinski/oppia,asandyz/oppia,miyucy/oppia,asandyz/oppia,himanshu-dixit/oppia,whygee/oppia,brylie/oppia,amitdeutsch/oppia,felipecocco/oppia,won0089/oppia,VictoriaRoux/oppia,shaz13/oppia,danieljjh/oppia,mit0110/oppia,won0089/oppia,won0089/oppia,gale320/oppia,gale320/oppia,wangsai/oppia,openhatch/oh-missions-oppia-beta,sdulal/oppia,bjvoth/oppia,leandrotoledo/oppia,Dev4X/oppia,Dev4X/oppia,wangsai/oppia,CMDann/oppia,michaelWagner/oppia,openhatch/oh-missions-oppia-beta,sunu/oppia,kennho/oppia,Cgruppo/oppia,oulan/oppia,dippatel1994/oppia,brianrodri/oppia,kevinlee12/oppia,miyucy/oppia,MAKOSCAFEE/oppia,aldeka/oppia,zgchizi/oppia-uc,felipecocco/oppia,zgchizi/oppia-uc,kennho/oppia,aldeka/oppia,toooooper/oppia,BenHenning/oppia,MaximLich/oppia,BenHenning/oppia,raju249/oppia,DewarM/oppia,cleophasmashiri/oppia,wangsai/oppia,anggorodewanto/oppia,sunu/oh-missions-oppia-beta,whygee/oppia,sunu/oppia-test-2,DewarM/oppia,prasanna08/oppia,Dev4X/oppia,brylie/oppia,kaffeel/oppia,toooooper/oppia,VictoriaRoux/oppia,kingctan/oppia,amitdeutsch/oppia,kevinlee12/oppia,edallison/oppia,hazmatzo/oppia,jestapinski/oppia,brianrodri/oppia,brylie/oppia,mit0110/oppia,felipecocco/oppia,DewarM/oppia,sunu/oppia,Cgruppo/oppia,kaffeel/oppia,Cgruppo/oppia,bjvoth/oppia,prasanna08/oppia,CMDann/oppia,mindpin/mindpin_oppia,himanshu-dixit/oppia,prasanna08/oppia,terrameijar/oppia,kennho/oppia,oulan/oppia,himanshu-dixit/oppia,asandyz/oppia,nagyistoce/oppia,VictoriaRoux/oppia,infinyte/oppia,sarahfo/oppia,cleophasmashiri/oppia,kingctan/oppia,dippatel1994/oppia,wangsai/oppia,felipecocco/oppia,directorlive/oppia,souravbadami/oppia,infinyte/oppia,infinyte/oppia,CMDann/oppia,nagyistoce/oppia,MaximLich/oppia,hazmatzo/oppia,sbhowmik89/oppia,VictoriaRoux/oppia,directorlive/oppia,nagyistoce/oppia,virajprabhu/oppia,openhatch/oh-missions-oppia-beta,Dev4X/oppia,directorlive/oppia,DewarM/oppia,cleophasmashiri/oppia,amitdeutsch/oppia,sunu/oppia-test-4,kevinlee12/oppia,oppia/oppia,fernandopinhati/oppia,BenHenning/oppia,nagyistoce/oppia,kevinlee12/oppia,BenHenning/oppia,brianrodri/oppia,toooooper/oppia,zgchizi/oppia-uc,Cgruppo/oppia,virajprabhu/oppia,toooooper/oppia,anthkris/oppia,brianrodri/oppia,terrameijar/oppia,gale320/oppia,google-code-export/oppia,sanyaade-teachings/oppia,cleophasmashiri/oppia,sunu/oppia-test-4,sunu/oppia,openhatch/oh-missions-oppia-beta,sunu/oppia,mit0110/oppia,shaz13/oppia,leandrotoledo/oppia,michaelWagner/oppia,danieljjh/oppia,dippatel1994/oppia,oulan/oppia,hazmatzo/oppia,MAKOSCAFEE/oppia,infinyte/oppia,Dev4X/oppia,nagyistoce/oppia,google-code-export/oppia,directorlive/oppia,hazmatzo/oppia,jestapinski/oppia,leandrotoledo/oppia,sbhowmik89/oppia,prasanna08/oppia,kingctan/oppia,shaz13/oppia,sunu/oh-missions-oppia-beta,oppia/oppia,MAKOSCAFEE/oppia,mindpin/mindpin_oppia,kaffeel/oppia,sanyaade-teachings/oppia,terrameijar/oppia,anthkris/oppia,virajprabhu/oppia,infinyte/oppia,AllanYangZhou/oppia,mindpin/mindpin_oppia,oppia/oppia,CMDann/oppia,michaelWagner/oppia,miyucy/oppia,fernandopinhati/oppia,dippatel1994/oppia,sunu/oh-missions-oppia-beta,michaelWagner/oppia,michaelWagner/oppia,asandyz/oppia,mit0110/oppia,sdulal/oppia,Atlas-Sailed-Co/oppia,sarahfo/oppia,souravbadami/oppia,paulproteus/oppia-test-3,jestapinski/oppia,edallison/oppia,sdulal/oppia,Atlas-Sailed-Co/oppia,kaffeel/oppia,AllanYangZhou/oppia,amgowano/oppia,gale320/oppia,souravbadami/oppia,raju249/oppia,danieljjh/oppia,bjvoth/oppia,won0089/oppia,sbhowmik89/oppia,kingctan/oppia,amitdeutsch/oppia,edallison/oppia,anggorodewanto/oppia,rackstar17/oppia,rackstar17/oppia,zgchizi/oppia-uc,won0089/oppia,edallison/oppia,sarahfo/oppia,leandrotoledo/oppia,Atlas-Sailed-Co/oppia,google-code-export/oppia,cleophasmashiri/oppia,sunu/oppia-test,Cgruppo/oppia,sunu/oppia,sunu/oh-missions-oppia-beta,sunu/oppia-test,CMDann/oppia,kingctan/oppia,paulproteus/oppia-test-3,MaximLich/oppia,oppia/oppia,sanyaade-teachings/oppia,sunu/oppia-test-2,BenHenning/oppia,amgowano/oppia,sarahfo/oppia,oulan/oppia,anggorodewanto/oppia,aldeka/oppia,wangsai/oppia,sbhowmik89/oppia,MAKOSCAFEE/oppia,rackstar17/oppia,Atlas-Sailed-Co/oppia,hazmatzo/oppia,sunu/oppia-test-2,google-code-export/oppia,fernandopinhati/oppia,shaz13/oppia,gale320/oppia,prasanna08/oppia,asandyz/oppia,sunu/oppia-test,whygee/oppia,paulproteus/oppia-test-3,sbhowmik89/oppia,anggorodewanto/oppia,leandrotoledo/oppia,raju249/oppia,google-code-export/oppia,felipecocco/oppia,mindpin/mindpin_oppia,virajprabhu/oppia,amitdeutsch/oppia,anthkris/oppia,sanyaade-teachings/oppia,terrameijar/oppia,brylie/oppia,whygee/oppia,dippatel1994/oppia,bjvoth/oppia,sdulal/oppia,virajprabhu/oppia,oulan/oppia,kennho/oppia,himanshu-dixit/oppia,brianrodri/oppia,bjvoth/oppia,souravbadami/oppia,MaximLich/oppia | # coding: utf-8
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Model for an Oppia editor."""
__author__ = 'Sean Lip'
from exploration import Exploration
from google.appengine.ext import ndb
class AugmentedUser(ndb.Model):
"""Stores information about a particular user."""
# The corresponding user.
user = ndb.UserProperty(required=True)
# The list of explorations that this user has editing rights for.
editable_explorations = ndb.KeyProperty(kind=Exploration, repeated=True)
@classmethod
def get(cls, user):
"""Gets (or creates) the corresponding AugmentedUser."""
augmented_user = cls.query().filter(
cls.user == user).get()
if not augmented_user:
augmented_user = cls(user=user)
augmented_user.put()
return augmented_user
Add TODO to think about. | # coding: utf-8
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Model for an Oppia editor."""
__author__ = 'Sean Lip'
from exploration import Exploration
from google.appengine.ext import ndb
class AugmentedUser(ndb.Model):
"""Stores information about a particular user."""
# TODO(sll): Should this class be keyed by user.email()?
# The corresponding user.
user = ndb.UserProperty(required=True)
# The list of explorations that this user has editing rights for.
editable_explorations = ndb.KeyProperty(kind=Exploration, repeated=True)
@classmethod
def get(cls, user):
"""Gets (or creates) the corresponding AugmentedUser."""
augmented_user = cls.query().filter(
cls.user == user).get()
if not augmented_user:
augmented_user = cls(user=user)
augmented_user.put()
return augmented_user
| <commit_before># coding: utf-8
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Model for an Oppia editor."""
__author__ = 'Sean Lip'
from exploration import Exploration
from google.appengine.ext import ndb
class AugmentedUser(ndb.Model):
"""Stores information about a particular user."""
# The corresponding user.
user = ndb.UserProperty(required=True)
# The list of explorations that this user has editing rights for.
editable_explorations = ndb.KeyProperty(kind=Exploration, repeated=True)
@classmethod
def get(cls, user):
"""Gets (or creates) the corresponding AugmentedUser."""
augmented_user = cls.query().filter(
cls.user == user).get()
if not augmented_user:
augmented_user = cls(user=user)
augmented_user.put()
return augmented_user
<commit_msg>Add TODO to think about.<commit_after> | # coding: utf-8
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Model for an Oppia editor."""
__author__ = 'Sean Lip'
from exploration import Exploration
from google.appengine.ext import ndb
class AugmentedUser(ndb.Model):
"""Stores information about a particular user."""
# TODO(sll): Should this class be keyed by user.email()?
# The corresponding user.
user = ndb.UserProperty(required=True)
# The list of explorations that this user has editing rights for.
editable_explorations = ndb.KeyProperty(kind=Exploration, repeated=True)
@classmethod
def get(cls, user):
"""Gets (or creates) the corresponding AugmentedUser."""
augmented_user = cls.query().filter(
cls.user == user).get()
if not augmented_user:
augmented_user = cls(user=user)
augmented_user.put()
return augmented_user
| # coding: utf-8
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Model for an Oppia editor."""
__author__ = 'Sean Lip'
from exploration import Exploration
from google.appengine.ext import ndb
class AugmentedUser(ndb.Model):
"""Stores information about a particular user."""
# The corresponding user.
user = ndb.UserProperty(required=True)
# The list of explorations that this user has editing rights for.
editable_explorations = ndb.KeyProperty(kind=Exploration, repeated=True)
@classmethod
def get(cls, user):
"""Gets (or creates) the corresponding AugmentedUser."""
augmented_user = cls.query().filter(
cls.user == user).get()
if not augmented_user:
augmented_user = cls(user=user)
augmented_user.put()
return augmented_user
Add TODO to think about.# coding: utf-8
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Model for an Oppia editor."""
__author__ = 'Sean Lip'
from exploration import Exploration
from google.appengine.ext import ndb
class AugmentedUser(ndb.Model):
"""Stores information about a particular user."""
# TODO(sll): Should this class be keyed by user.email()?
# The corresponding user.
user = ndb.UserProperty(required=True)
# The list of explorations that this user has editing rights for.
editable_explorations = ndb.KeyProperty(kind=Exploration, repeated=True)
@classmethod
def get(cls, user):
"""Gets (or creates) the corresponding AugmentedUser."""
augmented_user = cls.query().filter(
cls.user == user).get()
if not augmented_user:
augmented_user = cls(user=user)
augmented_user.put()
return augmented_user
| <commit_before># coding: utf-8
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Model for an Oppia editor."""
__author__ = 'Sean Lip'
from exploration import Exploration
from google.appengine.ext import ndb
class AugmentedUser(ndb.Model):
"""Stores information about a particular user."""
# The corresponding user.
user = ndb.UserProperty(required=True)
# The list of explorations that this user has editing rights for.
editable_explorations = ndb.KeyProperty(kind=Exploration, repeated=True)
@classmethod
def get(cls, user):
"""Gets (or creates) the corresponding AugmentedUser."""
augmented_user = cls.query().filter(
cls.user == user).get()
if not augmented_user:
augmented_user = cls(user=user)
augmented_user.put()
return augmented_user
<commit_msg>Add TODO to think about.<commit_after># coding: utf-8
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Model for an Oppia editor."""
__author__ = 'Sean Lip'
from exploration import Exploration
from google.appengine.ext import ndb
class AugmentedUser(ndb.Model):
"""Stores information about a particular user."""
# TODO(sll): Should this class be keyed by user.email()?
# The corresponding user.
user = ndb.UserProperty(required=True)
# The list of explorations that this user has editing rights for.
editable_explorations = ndb.KeyProperty(kind=Exploration, repeated=True)
@classmethod
def get(cls, user):
"""Gets (or creates) the corresponding AugmentedUser."""
augmented_user = cls.query().filter(
cls.user == user).get()
if not augmented_user:
augmented_user = cls(user=user)
augmented_user.put()
return augmented_user
|
a6c6175c6d15cd9d7fd711431a6741afa35e78fb | smartbot/storage.py | smartbot/storage.py | import yaml
class _Storage:
def __getitem__(self, key):
pass
def __setitem__(self, key, value):
pass
def __delitem__(self, key):
pass
class _DictionaryStorage(_Storage):
def __init__(self):
self.data = {}
def __del__(self):
self.commit()
def commit(self):
pass
def get(self, key, default=None):
return self.data.get(key, default)
def setdefault(self, key, default=None):
return self.data.setdefault(key, default)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
self.commit()
def __delitem__(self, key):
del self.data[key]
class Memory(_DictionaryStorage):
pass
class YAML(_DictionaryStorage):
def __init__(self, filename="storage.yaml"):
super().__init__()
self.filename = filename
try:
with open(self.filename) as fd:
self.data = yaml.load(fd.read())
except FileNotFoundError:
pass
if not self.data:
self.data = {}
def commit(self):
with open(self.filename, "w") as fd:
fd.write(yaml.dump(self.data))
| import yaml
class _Storage:
def __getitem__(self, key):
pass
def __setitem__(self, key, value):
pass
def __delitem__(self, key):
pass
class _DictionaryStorage(_Storage):
def __init__(self):
self.data = {}
def __del__(self):
self.commit()
def commit(self):
pass
def get(self, key, default=None):
return self.data.get(key, default)
def setdefault(self, key, default=None):
if key not in self.data:
self[key] = default
return self[key]
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
self.commit()
def __delitem__(self, key):
del self.data[key]
class Memory(_DictionaryStorage):
pass
class YAML(_DictionaryStorage):
def __init__(self, filename="storage.yaml"):
super().__init__()
self.filename = filename
try:
with open(self.filename) as fd:
self.data = yaml.load(fd.read())
except FileNotFoundError:
pass
if not self.data:
self.data = {}
def commit(self):
with open(self.filename, "w") as fd:
fd.write(yaml.dump(self.data))
| Update setdefault to ensure commit is called | Update setdefault to ensure commit is called
| Python | mit | Cyanogenoid/smartbot,Muzer/smartbot,thomasleese/smartbot-old,tomleese/smartbot | import yaml
class _Storage:
def __getitem__(self, key):
pass
def __setitem__(self, key, value):
pass
def __delitem__(self, key):
pass
class _DictionaryStorage(_Storage):
def __init__(self):
self.data = {}
def __del__(self):
self.commit()
def commit(self):
pass
def get(self, key, default=None):
return self.data.get(key, default)
def setdefault(self, key, default=None):
return self.data.setdefault(key, default)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
self.commit()
def __delitem__(self, key):
del self.data[key]
class Memory(_DictionaryStorage):
pass
class YAML(_DictionaryStorage):
def __init__(self, filename="storage.yaml"):
super().__init__()
self.filename = filename
try:
with open(self.filename) as fd:
self.data = yaml.load(fd.read())
except FileNotFoundError:
pass
if not self.data:
self.data = {}
def commit(self):
with open(self.filename, "w") as fd:
fd.write(yaml.dump(self.data))
Update setdefault to ensure commit is called | import yaml
class _Storage:
def __getitem__(self, key):
pass
def __setitem__(self, key, value):
pass
def __delitem__(self, key):
pass
class _DictionaryStorage(_Storage):
def __init__(self):
self.data = {}
def __del__(self):
self.commit()
def commit(self):
pass
def get(self, key, default=None):
return self.data.get(key, default)
def setdefault(self, key, default=None):
if key not in self.data:
self[key] = default
return self[key]
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
self.commit()
def __delitem__(self, key):
del self.data[key]
class Memory(_DictionaryStorage):
pass
class YAML(_DictionaryStorage):
def __init__(self, filename="storage.yaml"):
super().__init__()
self.filename = filename
try:
with open(self.filename) as fd:
self.data = yaml.load(fd.read())
except FileNotFoundError:
pass
if not self.data:
self.data = {}
def commit(self):
with open(self.filename, "w") as fd:
fd.write(yaml.dump(self.data))
| <commit_before>import yaml
class _Storage:
def __getitem__(self, key):
pass
def __setitem__(self, key, value):
pass
def __delitem__(self, key):
pass
class _DictionaryStorage(_Storage):
def __init__(self):
self.data = {}
def __del__(self):
self.commit()
def commit(self):
pass
def get(self, key, default=None):
return self.data.get(key, default)
def setdefault(self, key, default=None):
return self.data.setdefault(key, default)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
self.commit()
def __delitem__(self, key):
del self.data[key]
class Memory(_DictionaryStorage):
pass
class YAML(_DictionaryStorage):
def __init__(self, filename="storage.yaml"):
super().__init__()
self.filename = filename
try:
with open(self.filename) as fd:
self.data = yaml.load(fd.read())
except FileNotFoundError:
pass
if not self.data:
self.data = {}
def commit(self):
with open(self.filename, "w") as fd:
fd.write(yaml.dump(self.data))
<commit_msg>Update setdefault to ensure commit is called<commit_after> | import yaml
class _Storage:
def __getitem__(self, key):
pass
def __setitem__(self, key, value):
pass
def __delitem__(self, key):
pass
class _DictionaryStorage(_Storage):
def __init__(self):
self.data = {}
def __del__(self):
self.commit()
def commit(self):
pass
def get(self, key, default=None):
return self.data.get(key, default)
def setdefault(self, key, default=None):
if key not in self.data:
self[key] = default
return self[key]
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
self.commit()
def __delitem__(self, key):
del self.data[key]
class Memory(_DictionaryStorage):
pass
class YAML(_DictionaryStorage):
def __init__(self, filename="storage.yaml"):
super().__init__()
self.filename = filename
try:
with open(self.filename) as fd:
self.data = yaml.load(fd.read())
except FileNotFoundError:
pass
if not self.data:
self.data = {}
def commit(self):
with open(self.filename, "w") as fd:
fd.write(yaml.dump(self.data))
| import yaml
class _Storage:
def __getitem__(self, key):
pass
def __setitem__(self, key, value):
pass
def __delitem__(self, key):
pass
class _DictionaryStorage(_Storage):
def __init__(self):
self.data = {}
def __del__(self):
self.commit()
def commit(self):
pass
def get(self, key, default=None):
return self.data.get(key, default)
def setdefault(self, key, default=None):
return self.data.setdefault(key, default)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
self.commit()
def __delitem__(self, key):
del self.data[key]
class Memory(_DictionaryStorage):
pass
class YAML(_DictionaryStorage):
def __init__(self, filename="storage.yaml"):
super().__init__()
self.filename = filename
try:
with open(self.filename) as fd:
self.data = yaml.load(fd.read())
except FileNotFoundError:
pass
if not self.data:
self.data = {}
def commit(self):
with open(self.filename, "w") as fd:
fd.write(yaml.dump(self.data))
Update setdefault to ensure commit is calledimport yaml
class _Storage:
def __getitem__(self, key):
pass
def __setitem__(self, key, value):
pass
def __delitem__(self, key):
pass
class _DictionaryStorage(_Storage):
def __init__(self):
self.data = {}
def __del__(self):
self.commit()
def commit(self):
pass
def get(self, key, default=None):
return self.data.get(key, default)
def setdefault(self, key, default=None):
if key not in self.data:
self[key] = default
return self[key]
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
self.commit()
def __delitem__(self, key):
del self.data[key]
class Memory(_DictionaryStorage):
pass
class YAML(_DictionaryStorage):
def __init__(self, filename="storage.yaml"):
super().__init__()
self.filename = filename
try:
with open(self.filename) as fd:
self.data = yaml.load(fd.read())
except FileNotFoundError:
pass
if not self.data:
self.data = {}
def commit(self):
with open(self.filename, "w") as fd:
fd.write(yaml.dump(self.data))
| <commit_before>import yaml
class _Storage:
def __getitem__(self, key):
pass
def __setitem__(self, key, value):
pass
def __delitem__(self, key):
pass
class _DictionaryStorage(_Storage):
def __init__(self):
self.data = {}
def __del__(self):
self.commit()
def commit(self):
pass
def get(self, key, default=None):
return self.data.get(key, default)
def setdefault(self, key, default=None):
return self.data.setdefault(key, default)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
self.commit()
def __delitem__(self, key):
del self.data[key]
class Memory(_DictionaryStorage):
pass
class YAML(_DictionaryStorage):
def __init__(self, filename="storage.yaml"):
super().__init__()
self.filename = filename
try:
with open(self.filename) as fd:
self.data = yaml.load(fd.read())
except FileNotFoundError:
pass
if not self.data:
self.data = {}
def commit(self):
with open(self.filename, "w") as fd:
fd.write(yaml.dump(self.data))
<commit_msg>Update setdefault to ensure commit is called<commit_after>import yaml
class _Storage:
def __getitem__(self, key):
pass
def __setitem__(self, key, value):
pass
def __delitem__(self, key):
pass
class _DictionaryStorage(_Storage):
def __init__(self):
self.data = {}
def __del__(self):
self.commit()
def commit(self):
pass
def get(self, key, default=None):
return self.data.get(key, default)
def setdefault(self, key, default=None):
if key not in self.data:
self[key] = default
return self[key]
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
self.commit()
def __delitem__(self, key):
del self.data[key]
class Memory(_DictionaryStorage):
pass
class YAML(_DictionaryStorage):
def __init__(self, filename="storage.yaml"):
super().__init__()
self.filename = filename
try:
with open(self.filename) as fd:
self.data = yaml.load(fd.read())
except FileNotFoundError:
pass
if not self.data:
self.data = {}
def commit(self):
with open(self.filename, "w") as fd:
fd.write(yaml.dump(self.data))
|
617ac4a745afb07299c73977477f52911f3e6e4c | flask_skeleton_api/app.py | flask_skeleton_api/app.py | from flask import Flask, g, request
import uuid
import requests
app = Flask(__name__)
app.config.from_pyfile("config.py")
@app.before_request
def before_request():
# Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller.
# Generate a new one if it has not. We will use this in log messages.
trace_id = request.headers.get('X-Trace-ID', None)
if trace_id is None:
trace_id = uuid.uuid4().hex
g.trace_id = trace_id
# We also create a session-level requests object for the app to use with the header pre-set, so other APIs will receive it.
# These lines can be removed if the app will not make requests to other LR APIs!
g.requests = requests.Session()
g.requests.headers.update({'X-Trace-ID': trace_id})
| from flask import Flask, g, request
import uuid
import requests
app = Flask(__name__)
app.config.from_pyfile("config.py")
@app.before_request
def before_request():
# Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller.
# Generate a new one if it has not. We will use this in log messages.
trace_id = request.headers.get('X-Trace-ID', None)
if trace_id is None:
trace_id = uuid.uuid4().hex
g.trace_id = trace_id
# We also create a session-level requests object for the app to use with the header pre-set, so other APIs will receive it.
# These lines can be removed if the app will not make requests to other LR APIs!
g.requests = requests.Session()
g.requests.headers.update({'X-Trace-ID': trace_id})
@app.after_request
def after_request(response):
# Add the API version (as in the interface spec, not the app) to the header. Semantic versioning applies - see the
# API manual. A major version update will need to go in the URL. All changes should be documented though, for
# reusing teams to take advantage of.
response.headers["X-API-Version"] = "1.0.0"
return response
| Add API version into response header | Add API version into response header
| Python | mit | matthew-shaw/thing-api | from flask import Flask, g, request
import uuid
import requests
app = Flask(__name__)
app.config.from_pyfile("config.py")
@app.before_request
def before_request():
# Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller.
# Generate a new one if it has not. We will use this in log messages.
trace_id = request.headers.get('X-Trace-ID', None)
if trace_id is None:
trace_id = uuid.uuid4().hex
g.trace_id = trace_id
# We also create a session-level requests object for the app to use with the header pre-set, so other APIs will receive it.
# These lines can be removed if the app will not make requests to other LR APIs!
g.requests = requests.Session()
g.requests.headers.update({'X-Trace-ID': trace_id})
Add API version into response header | from flask import Flask, g, request
import uuid
import requests
app = Flask(__name__)
app.config.from_pyfile("config.py")
@app.before_request
def before_request():
# Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller.
# Generate a new one if it has not. We will use this in log messages.
trace_id = request.headers.get('X-Trace-ID', None)
if trace_id is None:
trace_id = uuid.uuid4().hex
g.trace_id = trace_id
# We also create a session-level requests object for the app to use with the header pre-set, so other APIs will receive it.
# These lines can be removed if the app will not make requests to other LR APIs!
g.requests = requests.Session()
g.requests.headers.update({'X-Trace-ID': trace_id})
@app.after_request
def after_request(response):
# Add the API version (as in the interface spec, not the app) to the header. Semantic versioning applies - see the
# API manual. A major version update will need to go in the URL. All changes should be documented though, for
# reusing teams to take advantage of.
response.headers["X-API-Version"] = "1.0.0"
return response
| <commit_before>from flask import Flask, g, request
import uuid
import requests
app = Flask(__name__)
app.config.from_pyfile("config.py")
@app.before_request
def before_request():
# Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller.
# Generate a new one if it has not. We will use this in log messages.
trace_id = request.headers.get('X-Trace-ID', None)
if trace_id is None:
trace_id = uuid.uuid4().hex
g.trace_id = trace_id
# We also create a session-level requests object for the app to use with the header pre-set, so other APIs will receive it.
# These lines can be removed if the app will not make requests to other LR APIs!
g.requests = requests.Session()
g.requests.headers.update({'X-Trace-ID': trace_id})
<commit_msg>Add API version into response header<commit_after> | from flask import Flask, g, request
import uuid
import requests
app = Flask(__name__)
app.config.from_pyfile("config.py")
@app.before_request
def before_request():
# Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller.
# Generate a new one if it has not. We will use this in log messages.
trace_id = request.headers.get('X-Trace-ID', None)
if trace_id is None:
trace_id = uuid.uuid4().hex
g.trace_id = trace_id
# We also create a session-level requests object for the app to use with the header pre-set, so other APIs will receive it.
# These lines can be removed if the app will not make requests to other LR APIs!
g.requests = requests.Session()
g.requests.headers.update({'X-Trace-ID': trace_id})
@app.after_request
def after_request(response):
# Add the API version (as in the interface spec, not the app) to the header. Semantic versioning applies - see the
# API manual. A major version update will need to go in the URL. All changes should be documented though, for
# reusing teams to take advantage of.
response.headers["X-API-Version"] = "1.0.0"
return response
| from flask import Flask, g, request
import uuid
import requests
app = Flask(__name__)
app.config.from_pyfile("config.py")
@app.before_request
def before_request():
# Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller.
# Generate a new one if it has not. We will use this in log messages.
trace_id = request.headers.get('X-Trace-ID', None)
if trace_id is None:
trace_id = uuid.uuid4().hex
g.trace_id = trace_id
# We also create a session-level requests object for the app to use with the header pre-set, so other APIs will receive it.
# These lines can be removed if the app will not make requests to other LR APIs!
g.requests = requests.Session()
g.requests.headers.update({'X-Trace-ID': trace_id})
Add API version into response headerfrom flask import Flask, g, request
import uuid
import requests
app = Flask(__name__)
app.config.from_pyfile("config.py")
@app.before_request
def before_request():
# Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller.
# Generate a new one if it has not. We will use this in log messages.
trace_id = request.headers.get('X-Trace-ID', None)
if trace_id is None:
trace_id = uuid.uuid4().hex
g.trace_id = trace_id
# We also create a session-level requests object for the app to use with the header pre-set, so other APIs will receive it.
# These lines can be removed if the app will not make requests to other LR APIs!
g.requests = requests.Session()
g.requests.headers.update({'X-Trace-ID': trace_id})
@app.after_request
def after_request(response):
# Add the API version (as in the interface spec, not the app) to the header. Semantic versioning applies - see the
# API manual. A major version update will need to go in the URL. All changes should be documented though, for
# reusing teams to take advantage of.
response.headers["X-API-Version"] = "1.0.0"
return response
| <commit_before>from flask import Flask, g, request
import uuid
import requests
app = Flask(__name__)
app.config.from_pyfile("config.py")
@app.before_request
def before_request():
# Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller.
# Generate a new one if it has not. We will use this in log messages.
trace_id = request.headers.get('X-Trace-ID', None)
if trace_id is None:
trace_id = uuid.uuid4().hex
g.trace_id = trace_id
# We also create a session-level requests object for the app to use with the header pre-set, so other APIs will receive it.
# These lines can be removed if the app will not make requests to other LR APIs!
g.requests = requests.Session()
g.requests.headers.update({'X-Trace-ID': trace_id})
<commit_msg>Add API version into response header<commit_after>from flask import Flask, g, request
import uuid
import requests
app = Flask(__name__)
app.config.from_pyfile("config.py")
@app.before_request
def before_request():
# Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller.
# Generate a new one if it has not. We will use this in log messages.
trace_id = request.headers.get('X-Trace-ID', None)
if trace_id is None:
trace_id = uuid.uuid4().hex
g.trace_id = trace_id
# We also create a session-level requests object for the app to use with the header pre-set, so other APIs will receive it.
# These lines can be removed if the app will not make requests to other LR APIs!
g.requests = requests.Session()
g.requests.headers.update({'X-Trace-ID': trace_id})
@app.after_request
def after_request(response):
# Add the API version (as in the interface spec, not the app) to the header. Semantic versioning applies - see the
# API manual. A major version update will need to go in the URL. All changes should be documented though, for
# reusing teams to take advantage of.
response.headers["X-API-Version"] = "1.0.0"
return response
|
bcf4c5e632ae3ee678ac10e93887b14c63d4eb4a | examples/plain_actor.py | examples/plain_actor.py | #!/usr/bin/env python3
import pykka
class PlainActor(pykka.ThreadingActor):
def __init__(self):
super().__init__()
self.stored_messages = []
def on_receive(self, message):
if message.get('command') == 'get_messages':
return self.stored_messages
else:
self.stored_messages.append(message)
if __name__ == '__main__':
actor = PlainActor.start()
actor.tell({'no': 'Norway', 'se': 'Sweden'})
actor.tell({'a': 3, 'b': 4, 'c': 5})
print(actor.ask({'command': 'get_messages'}))
actor.stop()
| #!/usr/bin/env python3
import pykka
GetMessages = object()
class PlainActor(pykka.ThreadingActor):
def __init__(self):
super().__init__()
self.stored_messages = []
def on_receive(self, message):
if message is GetMessages:
return self.stored_messages
else:
self.stored_messages.append(message)
if __name__ == '__main__':
actor = PlainActor.start()
actor.tell({'no': 'Norway', 'se': 'Sweden'})
actor.tell({'a': 3, 'b': 4, 'c': 5})
print(actor.ask(GetMessages))
actor.stop()
| Use custom message instead of dict | examples: Use custom message instead of dict
| Python | apache-2.0 | jodal/pykka | #!/usr/bin/env python3
import pykka
class PlainActor(pykka.ThreadingActor):
def __init__(self):
super().__init__()
self.stored_messages = []
def on_receive(self, message):
if message.get('command') == 'get_messages':
return self.stored_messages
else:
self.stored_messages.append(message)
if __name__ == '__main__':
actor = PlainActor.start()
actor.tell({'no': 'Norway', 'se': 'Sweden'})
actor.tell({'a': 3, 'b': 4, 'c': 5})
print(actor.ask({'command': 'get_messages'}))
actor.stop()
examples: Use custom message instead of dict | #!/usr/bin/env python3
import pykka
GetMessages = object()
class PlainActor(pykka.ThreadingActor):
def __init__(self):
super().__init__()
self.stored_messages = []
def on_receive(self, message):
if message is GetMessages:
return self.stored_messages
else:
self.stored_messages.append(message)
if __name__ == '__main__':
actor = PlainActor.start()
actor.tell({'no': 'Norway', 'se': 'Sweden'})
actor.tell({'a': 3, 'b': 4, 'c': 5})
print(actor.ask(GetMessages))
actor.stop()
| <commit_before>#!/usr/bin/env python3
import pykka
class PlainActor(pykka.ThreadingActor):
def __init__(self):
super().__init__()
self.stored_messages = []
def on_receive(self, message):
if message.get('command') == 'get_messages':
return self.stored_messages
else:
self.stored_messages.append(message)
if __name__ == '__main__':
actor = PlainActor.start()
actor.tell({'no': 'Norway', 'se': 'Sweden'})
actor.tell({'a': 3, 'b': 4, 'c': 5})
print(actor.ask({'command': 'get_messages'}))
actor.stop()
<commit_msg>examples: Use custom message instead of dict<commit_after> | #!/usr/bin/env python3
import pykka
GetMessages = object()
class PlainActor(pykka.ThreadingActor):
def __init__(self):
super().__init__()
self.stored_messages = []
def on_receive(self, message):
if message is GetMessages:
return self.stored_messages
else:
self.stored_messages.append(message)
if __name__ == '__main__':
actor = PlainActor.start()
actor.tell({'no': 'Norway', 'se': 'Sweden'})
actor.tell({'a': 3, 'b': 4, 'c': 5})
print(actor.ask(GetMessages))
actor.stop()
| #!/usr/bin/env python3
import pykka
class PlainActor(pykka.ThreadingActor):
def __init__(self):
super().__init__()
self.stored_messages = []
def on_receive(self, message):
if message.get('command') == 'get_messages':
return self.stored_messages
else:
self.stored_messages.append(message)
if __name__ == '__main__':
actor = PlainActor.start()
actor.tell({'no': 'Norway', 'se': 'Sweden'})
actor.tell({'a': 3, 'b': 4, 'c': 5})
print(actor.ask({'command': 'get_messages'}))
actor.stop()
examples: Use custom message instead of dict#!/usr/bin/env python3
import pykka
GetMessages = object()
class PlainActor(pykka.ThreadingActor):
def __init__(self):
super().__init__()
self.stored_messages = []
def on_receive(self, message):
if message is GetMessages:
return self.stored_messages
else:
self.stored_messages.append(message)
if __name__ == '__main__':
actor = PlainActor.start()
actor.tell({'no': 'Norway', 'se': 'Sweden'})
actor.tell({'a': 3, 'b': 4, 'c': 5})
print(actor.ask(GetMessages))
actor.stop()
| <commit_before>#!/usr/bin/env python3
import pykka
class PlainActor(pykka.ThreadingActor):
def __init__(self):
super().__init__()
self.stored_messages = []
def on_receive(self, message):
if message.get('command') == 'get_messages':
return self.stored_messages
else:
self.stored_messages.append(message)
if __name__ == '__main__':
actor = PlainActor.start()
actor.tell({'no': 'Norway', 'se': 'Sweden'})
actor.tell({'a': 3, 'b': 4, 'c': 5})
print(actor.ask({'command': 'get_messages'}))
actor.stop()
<commit_msg>examples: Use custom message instead of dict<commit_after>#!/usr/bin/env python3
import pykka
GetMessages = object()
class PlainActor(pykka.ThreadingActor):
def __init__(self):
super().__init__()
self.stored_messages = []
def on_receive(self, message):
if message is GetMessages:
return self.stored_messages
else:
self.stored_messages.append(message)
if __name__ == '__main__':
actor = PlainActor.start()
actor.tell({'no': 'Norway', 'se': 'Sweden'})
actor.tell({'a': 3, 'b': 4, 'c': 5})
print(actor.ask(GetMessages))
actor.stop()
|
3dda5003b3ce345a08369b15fc3447d2a4c7d1ad | examples/plotting_2d.py | examples/plotting_2d.py | from bluesky.examples import *
from bluesky.standard_config import RE
from matplotlib import pyplot as plt
from xray_vision.backend.mpl.cross_section_2d import CrossSection
import numpy as np
import filestore.api as fsapi
import time as ttime
from filestore.handlers import NpyHandler
fsapi.register_handler('npy', NpyHandler)
def stepscan(motor, det):
for i in np.linspace(-5, 5, 75):
yield Msg('create')
yield Msg('set', motor, i)
yield Msg('trigger', det)
yield Msg('read', motor)
yield Msg('read', det)
yield Msg('save')
ic = LiveImage('det_2d')
table_callback = LiveTable(fields=[motor._name, det_2d._name])
RE(stepscan(motor, det_2d), subs={'event': ic, 'all': table_callback}, beamline_id='c08i')
| from bluesky.examples import *
from bluesky.tests.utils import setup_test_run_engine
from matplotlib import pyplot as plt
from xray_vision.backend.mpl.cross_section_2d import CrossSection
import numpy as np
import filestore.api as fsapi
import time as ttime
from filestore.handlers import NpyHandler
fsapi.register_handler('npy', NpyHandler)
def stepscan(motor, det):
for i in np.linspace(-5, 5, 75):
yield Msg('create')
yield Msg('set', motor, i)
yield Msg('trigger', det)
yield Msg('read', motor)
yield Msg('read', det)
yield Msg('save')
ic = LiveImage('det_2d')
table_callback = LiveTable(fields=[motor._name, det_2d._name])
RE = setup_test_run_engine()
RE(stepscan(motor, det_2d), subs={'event': ic, 'all': table_callback}, beamline_id='c08i')
| Set up RunEngine with required metadata. | FIX: Set up RunEngine with required metadata.
| Python | bsd-3-clause | ericdill/bluesky,sameera2004/bluesky,sameera2004/bluesky,klauer/bluesky,klauer/bluesky,dchabot/bluesky,ericdill/bluesky,dchabot/bluesky | from bluesky.examples import *
from bluesky.standard_config import RE
from matplotlib import pyplot as plt
from xray_vision.backend.mpl.cross_section_2d import CrossSection
import numpy as np
import filestore.api as fsapi
import time as ttime
from filestore.handlers import NpyHandler
fsapi.register_handler('npy', NpyHandler)
def stepscan(motor, det):
for i in np.linspace(-5, 5, 75):
yield Msg('create')
yield Msg('set', motor, i)
yield Msg('trigger', det)
yield Msg('read', motor)
yield Msg('read', det)
yield Msg('save')
ic = LiveImage('det_2d')
table_callback = LiveTable(fields=[motor._name, det_2d._name])
RE(stepscan(motor, det_2d), subs={'event': ic, 'all': table_callback}, beamline_id='c08i')
FIX: Set up RunEngine with required metadata. | from bluesky.examples import *
from bluesky.tests.utils import setup_test_run_engine
from matplotlib import pyplot as plt
from xray_vision.backend.mpl.cross_section_2d import CrossSection
import numpy as np
import filestore.api as fsapi
import time as ttime
from filestore.handlers import NpyHandler
fsapi.register_handler('npy', NpyHandler)
def stepscan(motor, det):
for i in np.linspace(-5, 5, 75):
yield Msg('create')
yield Msg('set', motor, i)
yield Msg('trigger', det)
yield Msg('read', motor)
yield Msg('read', det)
yield Msg('save')
ic = LiveImage('det_2d')
table_callback = LiveTable(fields=[motor._name, det_2d._name])
RE = setup_test_run_engine()
RE(stepscan(motor, det_2d), subs={'event': ic, 'all': table_callback}, beamline_id='c08i')
| <commit_before>from bluesky.examples import *
from bluesky.standard_config import RE
from matplotlib import pyplot as plt
from xray_vision.backend.mpl.cross_section_2d import CrossSection
import numpy as np
import filestore.api as fsapi
import time as ttime
from filestore.handlers import NpyHandler
fsapi.register_handler('npy', NpyHandler)
def stepscan(motor, det):
for i in np.linspace(-5, 5, 75):
yield Msg('create')
yield Msg('set', motor, i)
yield Msg('trigger', det)
yield Msg('read', motor)
yield Msg('read', det)
yield Msg('save')
ic = LiveImage('det_2d')
table_callback = LiveTable(fields=[motor._name, det_2d._name])
RE(stepscan(motor, det_2d), subs={'event': ic, 'all': table_callback}, beamline_id='c08i')
<commit_msg>FIX: Set up RunEngine with required metadata.<commit_after> | from bluesky.examples import *
from bluesky.tests.utils import setup_test_run_engine
from matplotlib import pyplot as plt
from xray_vision.backend.mpl.cross_section_2d import CrossSection
import numpy as np
import filestore.api as fsapi
import time as ttime
from filestore.handlers import NpyHandler
fsapi.register_handler('npy', NpyHandler)
def stepscan(motor, det):
for i in np.linspace(-5, 5, 75):
yield Msg('create')
yield Msg('set', motor, i)
yield Msg('trigger', det)
yield Msg('read', motor)
yield Msg('read', det)
yield Msg('save')
ic = LiveImage('det_2d')
table_callback = LiveTable(fields=[motor._name, det_2d._name])
RE = setup_test_run_engine()
RE(stepscan(motor, det_2d), subs={'event': ic, 'all': table_callback}, beamline_id='c08i')
| from bluesky.examples import *
from bluesky.standard_config import RE
from matplotlib import pyplot as plt
from xray_vision.backend.mpl.cross_section_2d import CrossSection
import numpy as np
import filestore.api as fsapi
import time as ttime
from filestore.handlers import NpyHandler
fsapi.register_handler('npy', NpyHandler)
def stepscan(motor, det):
for i in np.linspace(-5, 5, 75):
yield Msg('create')
yield Msg('set', motor, i)
yield Msg('trigger', det)
yield Msg('read', motor)
yield Msg('read', det)
yield Msg('save')
ic = LiveImage('det_2d')
table_callback = LiveTable(fields=[motor._name, det_2d._name])
RE(stepscan(motor, det_2d), subs={'event': ic, 'all': table_callback}, beamline_id='c08i')
FIX: Set up RunEngine with required metadata.from bluesky.examples import *
from bluesky.tests.utils import setup_test_run_engine
from matplotlib import pyplot as plt
from xray_vision.backend.mpl.cross_section_2d import CrossSection
import numpy as np
import filestore.api as fsapi
import time as ttime
from filestore.handlers import NpyHandler
fsapi.register_handler('npy', NpyHandler)
def stepscan(motor, det):
for i in np.linspace(-5, 5, 75):
yield Msg('create')
yield Msg('set', motor, i)
yield Msg('trigger', det)
yield Msg('read', motor)
yield Msg('read', det)
yield Msg('save')
ic = LiveImage('det_2d')
table_callback = LiveTable(fields=[motor._name, det_2d._name])
RE = setup_test_run_engine()
RE(stepscan(motor, det_2d), subs={'event': ic, 'all': table_callback}, beamline_id='c08i')
| <commit_before>from bluesky.examples import *
from bluesky.standard_config import RE
from matplotlib import pyplot as plt
from xray_vision.backend.mpl.cross_section_2d import CrossSection
import numpy as np
import filestore.api as fsapi
import time as ttime
from filestore.handlers import NpyHandler
fsapi.register_handler('npy', NpyHandler)
def stepscan(motor, det):
for i in np.linspace(-5, 5, 75):
yield Msg('create')
yield Msg('set', motor, i)
yield Msg('trigger', det)
yield Msg('read', motor)
yield Msg('read', det)
yield Msg('save')
ic = LiveImage('det_2d')
table_callback = LiveTable(fields=[motor._name, det_2d._name])
RE(stepscan(motor, det_2d), subs={'event': ic, 'all': table_callback}, beamline_id='c08i')
<commit_msg>FIX: Set up RunEngine with required metadata.<commit_after>from bluesky.examples import *
from bluesky.tests.utils import setup_test_run_engine
from matplotlib import pyplot as plt
from xray_vision.backend.mpl.cross_section_2d import CrossSection
import numpy as np
import filestore.api as fsapi
import time as ttime
from filestore.handlers import NpyHandler
fsapi.register_handler('npy', NpyHandler)
def stepscan(motor, det):
for i in np.linspace(-5, 5, 75):
yield Msg('create')
yield Msg('set', motor, i)
yield Msg('trigger', det)
yield Msg('read', motor)
yield Msg('read', det)
yield Msg('save')
ic = LiveImage('det_2d')
table_callback = LiveTable(fields=[motor._name, det_2d._name])
RE = setup_test_run_engine()
RE(stepscan(motor, det_2d), subs={'event': ic, 'all': table_callback}, beamline_id='c08i')
|
c02dc4c0717d15f4f042c992b4b404056e0e0a14 | braubuddy/tests/thermometer/test_dummy.py | braubuddy/tests/thermometer/test_dummy.py | """
Braubuddy Dummy thermometer unit tests
"""
import unittest
from mock import patch, call, MagicMock
from braubuddy.thermometer import dummy
from braubuddy.thermometer import DeviceError
from braubuddy.thermometer import ReadError
class TestDummy(unittest.TestCase):
def test_within_bounds(self):
"""Dummy thermometer returns values within bounds."""
lower_bound = 20
upper_bound = 30
allowed_range = range(lower_bound, upper_bound)
test_dummy = dummy.DummyThermometer(
lower_bound = lower_bound,
upper_bound = upper_bound)
for i in range(0,1000):
self.assertIn(test_dummy.get_temperature(), allowed_range)
| """
Braubuddy Dummy thermometer unit tests
"""
import unittest
from mock import patch, call, MagicMock
from braubuddy.thermometer import dummy
class TestDummy(unittest.TestCase):
def test_within_bounds(self):
"""Dummy thermometer returns values within bounds."""
lower_bound = 20
upper_bound = 30
allowed_range = range(lower_bound, upper_bound)
test_dummy = dummy.DummyThermometer(
lower_bound = lower_bound,
upper_bound = upper_bound)
for i in range(0,1000):
self.assertIn(test_dummy.get_temperature(), allowed_range)
| Remove unnecessary imports form dummy tests. | Remove unnecessary imports form dummy tests.
| Python | bsd-3-clause | amorphic/braubuddy,amorphic/braubuddy,amorphic/braubuddy | """
Braubuddy Dummy thermometer unit tests
"""
import unittest
from mock import patch, call, MagicMock
from braubuddy.thermometer import dummy
from braubuddy.thermometer import DeviceError
from braubuddy.thermometer import ReadError
class TestDummy(unittest.TestCase):
def test_within_bounds(self):
"""Dummy thermometer returns values within bounds."""
lower_bound = 20
upper_bound = 30
allowed_range = range(lower_bound, upper_bound)
test_dummy = dummy.DummyThermometer(
lower_bound = lower_bound,
upper_bound = upper_bound)
for i in range(0,1000):
self.assertIn(test_dummy.get_temperature(), allowed_range)
Remove unnecessary imports form dummy tests. | """
Braubuddy Dummy thermometer unit tests
"""
import unittest
from mock import patch, call, MagicMock
from braubuddy.thermometer import dummy
class TestDummy(unittest.TestCase):
def test_within_bounds(self):
"""Dummy thermometer returns values within bounds."""
lower_bound = 20
upper_bound = 30
allowed_range = range(lower_bound, upper_bound)
test_dummy = dummy.DummyThermometer(
lower_bound = lower_bound,
upper_bound = upper_bound)
for i in range(0,1000):
self.assertIn(test_dummy.get_temperature(), allowed_range)
| <commit_before>"""
Braubuddy Dummy thermometer unit tests
"""
import unittest
from mock import patch, call, MagicMock
from braubuddy.thermometer import dummy
from braubuddy.thermometer import DeviceError
from braubuddy.thermometer import ReadError
class TestDummy(unittest.TestCase):
def test_within_bounds(self):
"""Dummy thermometer returns values within bounds."""
lower_bound = 20
upper_bound = 30
allowed_range = range(lower_bound, upper_bound)
test_dummy = dummy.DummyThermometer(
lower_bound = lower_bound,
upper_bound = upper_bound)
for i in range(0,1000):
self.assertIn(test_dummy.get_temperature(), allowed_range)
<commit_msg>Remove unnecessary imports form dummy tests.<commit_after> | """
Braubuddy Dummy thermometer unit tests
"""
import unittest
from mock import patch, call, MagicMock
from braubuddy.thermometer import dummy
class TestDummy(unittest.TestCase):
def test_within_bounds(self):
"""Dummy thermometer returns values within bounds."""
lower_bound = 20
upper_bound = 30
allowed_range = range(lower_bound, upper_bound)
test_dummy = dummy.DummyThermometer(
lower_bound = lower_bound,
upper_bound = upper_bound)
for i in range(0,1000):
self.assertIn(test_dummy.get_temperature(), allowed_range)
| """
Braubuddy Dummy thermometer unit tests
"""
import unittest
from mock import patch, call, MagicMock
from braubuddy.thermometer import dummy
from braubuddy.thermometer import DeviceError
from braubuddy.thermometer import ReadError
class TestDummy(unittest.TestCase):
def test_within_bounds(self):
"""Dummy thermometer returns values within bounds."""
lower_bound = 20
upper_bound = 30
allowed_range = range(lower_bound, upper_bound)
test_dummy = dummy.DummyThermometer(
lower_bound = lower_bound,
upper_bound = upper_bound)
for i in range(0,1000):
self.assertIn(test_dummy.get_temperature(), allowed_range)
Remove unnecessary imports form dummy tests."""
Braubuddy Dummy thermometer unit tests
"""
import unittest
from mock import patch, call, MagicMock
from braubuddy.thermometer import dummy
class TestDummy(unittest.TestCase):
def test_within_bounds(self):
"""Dummy thermometer returns values within bounds."""
lower_bound = 20
upper_bound = 30
allowed_range = range(lower_bound, upper_bound)
test_dummy = dummy.DummyThermometer(
lower_bound = lower_bound,
upper_bound = upper_bound)
for i in range(0,1000):
self.assertIn(test_dummy.get_temperature(), allowed_range)
| <commit_before>"""
Braubuddy Dummy thermometer unit tests
"""
import unittest
from mock import patch, call, MagicMock
from braubuddy.thermometer import dummy
from braubuddy.thermometer import DeviceError
from braubuddy.thermometer import ReadError
class TestDummy(unittest.TestCase):
def test_within_bounds(self):
"""Dummy thermometer returns values within bounds."""
lower_bound = 20
upper_bound = 30
allowed_range = range(lower_bound, upper_bound)
test_dummy = dummy.DummyThermometer(
lower_bound = lower_bound,
upper_bound = upper_bound)
for i in range(0,1000):
self.assertIn(test_dummy.get_temperature(), allowed_range)
<commit_msg>Remove unnecessary imports form dummy tests.<commit_after>"""
Braubuddy Dummy thermometer unit tests
"""
import unittest
from mock import patch, call, MagicMock
from braubuddy.thermometer import dummy
class TestDummy(unittest.TestCase):
def test_within_bounds(self):
"""Dummy thermometer returns values within bounds."""
lower_bound = 20
upper_bound = 30
allowed_range = range(lower_bound, upper_bound)
test_dummy = dummy.DummyThermometer(
lower_bound = lower_bound,
upper_bound = upper_bound)
for i in range(0,1000):
self.assertIn(test_dummy.get_temperature(), allowed_range)
|
e543a6e12f34dfdde4f55630fcd1514d7622e0ee | countBob.py | countBob.py | """ Q7- Assume s is a string of lower case characters. Write a program that
prints the number of times the string 'bob' occurs in s. For example, if s =
'azcbobobegghakl', then your program should print Number of times bob occurs
is: 2
"""
def countBob( string ):
count = 0
start = 0
while string.find( "bob" ) != -1:
start = string.find( "bob" ) # Finds the first character where the substring "bob" first appears.
# Strings are immutable. Hence, we store the new string by slicing the existing string from position start + 1 to the last position(length of string - 1)
string = string[ start + 1 : ]
count += 1
return count
print( "Remember all the characters in the string should be in LOWERCASE" )
string = input( "Enter the string: ")
print( "Number of times bob occurs is: " + str( countBob( string ) ) )
# Uncomment the following line if you are using Console/Terminal
# input("Press any key to exit..." )
| """
Q7- Assume s is a string of lower case characters. Write a program that
prints the number of times the string 'bob' occurs in s. For example, if s =
'azcbobobegghakl', then your program should print Number of times bob occurs
is: 2
"""
def countBob( string ):
count = 0
start = 0
while string.find( "bob" ) != -1:
start = string.find( "bob" ) # Finds the first character where the substring "bob" first appears.
# Strings are immutable. Hence, we store the new string by slicing the existing string from position start + 1 to the last position(length of string - 1)
string = string[ start + 1 : ]
count += 1
return count
print( "Remember all the characters in the string should be in LOWERCASE" )
string = input( "Enter the string: ")
print( "Number of times bob occurs is: " + str( countBob( string ) ) )
| Add the answer of seventh question of Assignment 3 | Add the answer of seventh question of Assignment 3
| Python | mit | SuyashD95/python-assignments | """ Q7- Assume s is a string of lower case characters. Write a program that
prints the number of times the string 'bob' occurs in s. For example, if s =
'azcbobobegghakl', then your program should print Number of times bob occurs
is: 2
"""
def countBob( string ):
count = 0
start = 0
while string.find( "bob" ) != -1:
start = string.find( "bob" ) # Finds the first character where the substring "bob" first appears.
# Strings are immutable. Hence, we store the new string by slicing the existing string from position start + 1 to the last position(length of string - 1)
string = string[ start + 1 : ]
count += 1
return count
print( "Remember all the characters in the string should be in LOWERCASE" )
string = input( "Enter the string: ")
print( "Number of times bob occurs is: " + str( countBob( string ) ) )
# Uncomment the following line if you are using Console/Terminal
# input("Press any key to exit..." )
Add the answer of seventh question of Assignment 3 | """
Q7- Assume s is a string of lower case characters. Write a program that
prints the number of times the string 'bob' occurs in s. For example, if s =
'azcbobobegghakl', then your program should print Number of times bob occurs
is: 2
"""
def countBob( string ):
count = 0
start = 0
while string.find( "bob" ) != -1:
start = string.find( "bob" ) # Finds the first character where the substring "bob" first appears.
# Strings are immutable. Hence, we store the new string by slicing the existing string from position start + 1 to the last position(length of string - 1)
string = string[ start + 1 : ]
count += 1
return count
print( "Remember all the characters in the string should be in LOWERCASE" )
string = input( "Enter the string: ")
print( "Number of times bob occurs is: " + str( countBob( string ) ) )
| <commit_before>""" Q7- Assume s is a string of lower case characters. Write a program that
prints the number of times the string 'bob' occurs in s. For example, if s =
'azcbobobegghakl', then your program should print Number of times bob occurs
is: 2
"""
def countBob( string ):
count = 0
start = 0
while string.find( "bob" ) != -1:
start = string.find( "bob" ) # Finds the first character where the substring "bob" first appears.
# Strings are immutable. Hence, we store the new string by slicing the existing string from position start + 1 to the last position(length of string - 1)
string = string[ start + 1 : ]
count += 1
return count
print( "Remember all the characters in the string should be in LOWERCASE" )
string = input( "Enter the string: ")
print( "Number of times bob occurs is: " + str( countBob( string ) ) )
# Uncomment the following line if you are using Console/Terminal
# input("Press any key to exit..." )
<commit_msg>Add the answer of seventh question of Assignment 3<commit_after> | """
Q7- Assume s is a string of lower case characters. Write a program that
prints the number of times the string 'bob' occurs in s. For example, if s =
'azcbobobegghakl', then your program should print Number of times bob occurs
is: 2
"""
def countBob( string ):
count = 0
start = 0
while string.find( "bob" ) != -1:
start = string.find( "bob" ) # Finds the first character where the substring "bob" first appears.
# Strings are immutable. Hence, we store the new string by slicing the existing string from position start + 1 to the last position(length of string - 1)
string = string[ start + 1 : ]
count += 1
return count
print( "Remember all the characters in the string should be in LOWERCASE" )
string = input( "Enter the string: ")
print( "Number of times bob occurs is: " + str( countBob( string ) ) )
| """ Q7- Assume s is a string of lower case characters. Write a program that
prints the number of times the string 'bob' occurs in s. For example, if s =
'azcbobobegghakl', then your program should print Number of times bob occurs
is: 2
"""
def countBob( string ):
count = 0
start = 0
while string.find( "bob" ) != -1:
start = string.find( "bob" ) # Finds the first character where the substring "bob" first appears.
# Strings are immutable. Hence, we store the new string by slicing the existing string from position start + 1 to the last position(length of string - 1)
string = string[ start + 1 : ]
count += 1
return count
print( "Remember all the characters in the string should be in LOWERCASE" )
string = input( "Enter the string: ")
print( "Number of times bob occurs is: " + str( countBob( string ) ) )
# Uncomment the following line if you are using Console/Terminal
# input("Press any key to exit..." )
Add the answer of seventh question of Assignment 3"""
Q7- Assume s is a string of lower case characters. Write a program that
prints the number of times the string 'bob' occurs in s. For example, if s =
'azcbobobegghakl', then your program should print Number of times bob occurs
is: 2
"""
def countBob( string ):
count = 0
start = 0
while string.find( "bob" ) != -1:
start = string.find( "bob" ) # Finds the first character where the substring "bob" first appears.
# Strings are immutable. Hence, we store the new string by slicing the existing string from position start + 1 to the last position(length of string - 1)
string = string[ start + 1 : ]
count += 1
return count
print( "Remember all the characters in the string should be in LOWERCASE" )
string = input( "Enter the string: ")
print( "Number of times bob occurs is: " + str( countBob( string ) ) )
| <commit_before>""" Q7- Assume s is a string of lower case characters. Write a program that
prints the number of times the string 'bob' occurs in s. For example, if s =
'azcbobobegghakl', then your program should print Number of times bob occurs
is: 2
"""
def countBob( string ):
count = 0
start = 0
while string.find( "bob" ) != -1:
start = string.find( "bob" ) # Finds the first character where the substring "bob" first appears.
# Strings are immutable. Hence, we store the new string by slicing the existing string from position start + 1 to the last position(length of string - 1)
string = string[ start + 1 : ]
count += 1
return count
print( "Remember all the characters in the string should be in LOWERCASE" )
string = input( "Enter the string: ")
print( "Number of times bob occurs is: " + str( countBob( string ) ) )
# Uncomment the following line if you are using Console/Terminal
# input("Press any key to exit..." )
<commit_msg>Add the answer of seventh question of Assignment 3<commit_after>"""
Q7- Assume s is a string of lower case characters. Write a program that
prints the number of times the string 'bob' occurs in s. For example, if s =
'azcbobobegghakl', then your program should print Number of times bob occurs
is: 2
"""
def countBob( string ):
count = 0
start = 0
while string.find( "bob" ) != -1:
start = string.find( "bob" ) # Finds the first character where the substring "bob" first appears.
# Strings are immutable. Hence, we store the new string by slicing the existing string from position start + 1 to the last position(length of string - 1)
string = string[ start + 1 : ]
count += 1
return count
print( "Remember all the characters in the string should be in LOWERCASE" )
string = input( "Enter the string: ")
print( "Number of times bob occurs is: " + str( countBob( string ) ) )
|
602d0f487f8926f41577adb442830796d6612998 | nurseconnect/services.py | nurseconnect/services.py | import logging
import requests
from django.conf import settings
logger = logging.getLogger("nurseconnect.services")
def get_clinic_code(clinic_code):
if settings.FAKE_CLINIC_CODE_VALIDATION and settings.DEBUG:
return [0, 1, "fake_clinic_name"]
url = settings.CLINIC_CODE_API
try:
response = requests.get(url)
except requests.RequestException as e:
logger.error("Error: {}".format(e))
return None
if response.status_code == 200:
try:
data = response.json()
logger.info("Obtained clinic code data from API")
except ValueError as e:
logger.error("JSON Error: {}".format(e))
return None
if data and ("rows" in data):
for clinic in data["rows"]:
if clinic_code == clinic[0]:
return clinic
else:
logger.error("Error: Status code {}".format(response.status_code))
return None
| import logging
import requests
from django.conf import settings
logger = logging.getLogger("nurseconnect.services")
def get_clinic_code(clinic_code):
if settings.FAKE_CLINIC_CODE_VALIDATION and settings.DEBUG:
return [0, 1, "fake_clinic_name"]
try:
response = requests.get(
settings.CLINIC_CODE_API,
params={"criteria": "value:{}".format(clinic_code)})
except requests.RequestException as e:
logger.error("Error: {}".format(e))
return None
if response.status_code == 200:
try:
data = response.json()
logger.info("Obtained clinic code data from API")
except ValueError as e:
logger.error("JSON Error: {}".format(e))
return None
if data and ("rows" in data):
if len(data["rows"]) >= 1:
return data["rows"][0]
else:
return None
else:
logger.error(
"Returned data in unexpected format: {}".format(
data if data is not None else "None"))
return None
else:
logger.error("Error: Status code {}".format(response.status_code))
return None
| Update how get_clinic_code fetches/extracts info from external service | Update how get_clinic_code fetches/extracts info from external service
We were sending the external API a message to ask for a list of clinic codes and then checking whether the code was in that list of clinic codes.
Instead we send a message which includes the clinic code, to check against that specific clinic.
| Python | bsd-2-clause | praekelt/nurseconnect,praekelt/nurseconnect,praekelt/nurseconnect | import logging
import requests
from django.conf import settings
logger = logging.getLogger("nurseconnect.services")
def get_clinic_code(clinic_code):
if settings.FAKE_CLINIC_CODE_VALIDATION and settings.DEBUG:
return [0, 1, "fake_clinic_name"]
url = settings.CLINIC_CODE_API
try:
response = requests.get(url)
except requests.RequestException as e:
logger.error("Error: {}".format(e))
return None
if response.status_code == 200:
try:
data = response.json()
logger.info("Obtained clinic code data from API")
except ValueError as e:
logger.error("JSON Error: {}".format(e))
return None
if data and ("rows" in data):
for clinic in data["rows"]:
if clinic_code == clinic[0]:
return clinic
else:
logger.error("Error: Status code {}".format(response.status_code))
return None
Update how get_clinic_code fetches/extracts info from external service
We were sending the external API a message to ask for a list of clinic codes and then checking whether the code was in that list of clinic codes.
Instead we send a message which includes the clinic code, to check against that specific clinic. | import logging
import requests
from django.conf import settings
logger = logging.getLogger("nurseconnect.services")
def get_clinic_code(clinic_code):
if settings.FAKE_CLINIC_CODE_VALIDATION and settings.DEBUG:
return [0, 1, "fake_clinic_name"]
try:
response = requests.get(
settings.CLINIC_CODE_API,
params={"criteria": "value:{}".format(clinic_code)})
except requests.RequestException as e:
logger.error("Error: {}".format(e))
return None
if response.status_code == 200:
try:
data = response.json()
logger.info("Obtained clinic code data from API")
except ValueError as e:
logger.error("JSON Error: {}".format(e))
return None
if data and ("rows" in data):
if len(data["rows"]) >= 1:
return data["rows"][0]
else:
return None
else:
logger.error(
"Returned data in unexpected format: {}".format(
data if data is not None else "None"))
return None
else:
logger.error("Error: Status code {}".format(response.status_code))
return None
| <commit_before>import logging
import requests
from django.conf import settings
logger = logging.getLogger("nurseconnect.services")
def get_clinic_code(clinic_code):
if settings.FAKE_CLINIC_CODE_VALIDATION and settings.DEBUG:
return [0, 1, "fake_clinic_name"]
url = settings.CLINIC_CODE_API
try:
response = requests.get(url)
except requests.RequestException as e:
logger.error("Error: {}".format(e))
return None
if response.status_code == 200:
try:
data = response.json()
logger.info("Obtained clinic code data from API")
except ValueError as e:
logger.error("JSON Error: {}".format(e))
return None
if data and ("rows" in data):
for clinic in data["rows"]:
if clinic_code == clinic[0]:
return clinic
else:
logger.error("Error: Status code {}".format(response.status_code))
return None
<commit_msg>Update how get_clinic_code fetches/extracts info from external service
We were sending the external API a message to ask for a list of clinic codes and then checking whether the code was in that list of clinic codes.
Instead we send a message which includes the clinic code, to check against that specific clinic.<commit_after> | import logging
import requests
from django.conf import settings
logger = logging.getLogger("nurseconnect.services")
def get_clinic_code(clinic_code):
if settings.FAKE_CLINIC_CODE_VALIDATION and settings.DEBUG:
return [0, 1, "fake_clinic_name"]
try:
response = requests.get(
settings.CLINIC_CODE_API,
params={"criteria": "value:{}".format(clinic_code)})
except requests.RequestException as e:
logger.error("Error: {}".format(e))
return None
if response.status_code == 200:
try:
data = response.json()
logger.info("Obtained clinic code data from API")
except ValueError as e:
logger.error("JSON Error: {}".format(e))
return None
if data and ("rows" in data):
if len(data["rows"]) >= 1:
return data["rows"][0]
else:
return None
else:
logger.error(
"Returned data in unexpected format: {}".format(
data if data is not None else "None"))
return None
else:
logger.error("Error: Status code {}".format(response.status_code))
return None
| import logging
import requests
from django.conf import settings
logger = logging.getLogger("nurseconnect.services")
def get_clinic_code(clinic_code):
if settings.FAKE_CLINIC_CODE_VALIDATION and settings.DEBUG:
return [0, 1, "fake_clinic_name"]
url = settings.CLINIC_CODE_API
try:
response = requests.get(url)
except requests.RequestException as e:
logger.error("Error: {}".format(e))
return None
if response.status_code == 200:
try:
data = response.json()
logger.info("Obtained clinic code data from API")
except ValueError as e:
logger.error("JSON Error: {}".format(e))
return None
if data and ("rows" in data):
for clinic in data["rows"]:
if clinic_code == clinic[0]:
return clinic
else:
logger.error("Error: Status code {}".format(response.status_code))
return None
Update how get_clinic_code fetches/extracts info from external service
We were sending the external API a message to ask for a list of clinic codes and then checking whether the code was in that list of clinic codes.
Instead we send a message which includes the clinic code, to check against that specific clinic.import logging
import requests
from django.conf import settings
logger = logging.getLogger("nurseconnect.services")
def get_clinic_code(clinic_code):
if settings.FAKE_CLINIC_CODE_VALIDATION and settings.DEBUG:
return [0, 1, "fake_clinic_name"]
try:
response = requests.get(
settings.CLINIC_CODE_API,
params={"criteria": "value:{}".format(clinic_code)})
except requests.RequestException as e:
logger.error("Error: {}".format(e))
return None
if response.status_code == 200:
try:
data = response.json()
logger.info("Obtained clinic code data from API")
except ValueError as e:
logger.error("JSON Error: {}".format(e))
return None
if data and ("rows" in data):
if len(data["rows"]) >= 1:
return data["rows"][0]
else:
return None
else:
logger.error(
"Returned data in unexpected format: {}".format(
data if data is not None else "None"))
return None
else:
logger.error("Error: Status code {}".format(response.status_code))
return None
| <commit_before>import logging
import requests
from django.conf import settings
logger = logging.getLogger("nurseconnect.services")
def get_clinic_code(clinic_code):
if settings.FAKE_CLINIC_CODE_VALIDATION and settings.DEBUG:
return [0, 1, "fake_clinic_name"]
url = settings.CLINIC_CODE_API
try:
response = requests.get(url)
except requests.RequestException as e:
logger.error("Error: {}".format(e))
return None
if response.status_code == 200:
try:
data = response.json()
logger.info("Obtained clinic code data from API")
except ValueError as e:
logger.error("JSON Error: {}".format(e))
return None
if data and ("rows" in data):
for clinic in data["rows"]:
if clinic_code == clinic[0]:
return clinic
else:
logger.error("Error: Status code {}".format(response.status_code))
return None
<commit_msg>Update how get_clinic_code fetches/extracts info from external service
We were sending the external API a message to ask for a list of clinic codes and then checking whether the code was in that list of clinic codes.
Instead we send a message which includes the clinic code, to check against that specific clinic.<commit_after>import logging
import requests
from django.conf import settings
logger = logging.getLogger("nurseconnect.services")
def get_clinic_code(clinic_code):
if settings.FAKE_CLINIC_CODE_VALIDATION and settings.DEBUG:
return [0, 1, "fake_clinic_name"]
try:
response = requests.get(
settings.CLINIC_CODE_API,
params={"criteria": "value:{}".format(clinic_code)})
except requests.RequestException as e:
logger.error("Error: {}".format(e))
return None
if response.status_code == 200:
try:
data = response.json()
logger.info("Obtained clinic code data from API")
except ValueError as e:
logger.error("JSON Error: {}".format(e))
return None
if data and ("rows" in data):
if len(data["rows"]) >= 1:
return data["rows"][0]
else:
return None
else:
logger.error(
"Returned data in unexpected format: {}".format(
data if data is not None else "None"))
return None
else:
logger.error("Error: Status code {}".format(response.status_code))
return None
|
09418ae8fa652a5f8d2d3b3058e4acc774cbcbe9 | genes/nginx/main.py | genes/nginx/main.py | from genes.apt import commands as apt
from genes.brew import commands as brew
from genes.debian.traits import is_debian
from genes.mac.traits import is_osx
from genes.ubuntu.traits import is_ubuntu
def main():
if is_ubuntu() or is_debian():
apt.update()
apt.install('nginx')
elif is_osx():
brew.update()
brew.install('nginx')
else:
pass
| from typing import Callable, Optional
from genes.apt import commands as apt
from genes.brew import commands as brew
from genes.debian.traits import is_debian
from genes.mac.traits import is_osx
from genes.ubuntu.traits import is_ubuntu
def main(config: Optional[Callable[[], None]]=None):
# Install nginx
if is_ubuntu() or is_debian():
apt.update()
apt.install('nginx')
elif is_osx():
brew.update()
brew.install('nginx')
else:
pass
# Then configure it
if config is not None:
config()
| Add config option for nginx | Add config option for nginx | Python | mit | hatchery/genepool,hatchery/Genepool2 | from genes.apt import commands as apt
from genes.brew import commands as brew
from genes.debian.traits import is_debian
from genes.mac.traits import is_osx
from genes.ubuntu.traits import is_ubuntu
def main():
if is_ubuntu() or is_debian():
apt.update()
apt.install('nginx')
elif is_osx():
brew.update()
brew.install('nginx')
else:
pass
Add config option for nginx | from typing import Callable, Optional
from genes.apt import commands as apt
from genes.brew import commands as brew
from genes.debian.traits import is_debian
from genes.mac.traits import is_osx
from genes.ubuntu.traits import is_ubuntu
def main(config: Optional[Callable[[], None]]=None):
# Install nginx
if is_ubuntu() or is_debian():
apt.update()
apt.install('nginx')
elif is_osx():
brew.update()
brew.install('nginx')
else:
pass
# Then configure it
if config is not None:
config()
| <commit_before>from genes.apt import commands as apt
from genes.brew import commands as brew
from genes.debian.traits import is_debian
from genes.mac.traits import is_osx
from genes.ubuntu.traits import is_ubuntu
def main():
if is_ubuntu() or is_debian():
apt.update()
apt.install('nginx')
elif is_osx():
brew.update()
brew.install('nginx')
else:
pass
<commit_msg>Add config option for nginx<commit_after> | from typing import Callable, Optional
from genes.apt import commands as apt
from genes.brew import commands as brew
from genes.debian.traits import is_debian
from genes.mac.traits import is_osx
from genes.ubuntu.traits import is_ubuntu
def main(config: Optional[Callable[[], None]]=None):
# Install nginx
if is_ubuntu() or is_debian():
apt.update()
apt.install('nginx')
elif is_osx():
brew.update()
brew.install('nginx')
else:
pass
# Then configure it
if config is not None:
config()
| from genes.apt import commands as apt
from genes.brew import commands as brew
from genes.debian.traits import is_debian
from genes.mac.traits import is_osx
from genes.ubuntu.traits import is_ubuntu
def main():
if is_ubuntu() or is_debian():
apt.update()
apt.install('nginx')
elif is_osx():
brew.update()
brew.install('nginx')
else:
pass
Add config option for nginxfrom typing import Callable, Optional
from genes.apt import commands as apt
from genes.brew import commands as brew
from genes.debian.traits import is_debian
from genes.mac.traits import is_osx
from genes.ubuntu.traits import is_ubuntu
def main(config: Optional[Callable[[], None]]=None):
# Install nginx
if is_ubuntu() or is_debian():
apt.update()
apt.install('nginx')
elif is_osx():
brew.update()
brew.install('nginx')
else:
pass
# Then configure it
if config is not None:
config()
| <commit_before>from genes.apt import commands as apt
from genes.brew import commands as brew
from genes.debian.traits import is_debian
from genes.mac.traits import is_osx
from genes.ubuntu.traits import is_ubuntu
def main():
if is_ubuntu() or is_debian():
apt.update()
apt.install('nginx')
elif is_osx():
brew.update()
brew.install('nginx')
else:
pass
<commit_msg>Add config option for nginx<commit_after>from typing import Callable, Optional
from genes.apt import commands as apt
from genes.brew import commands as brew
from genes.debian.traits import is_debian
from genes.mac.traits import is_osx
from genes.ubuntu.traits import is_ubuntu
def main(config: Optional[Callable[[], None]]=None):
# Install nginx
if is_ubuntu() or is_debian():
apt.update()
apt.install('nginx')
elif is_osx():
brew.update()
brew.install('nginx')
else:
pass
# Then configure it
if config is not None:
config()
|
aed4d20d4e101891d2dd1149a6c111f06036ec73 | libnacl/utils.py | libnacl/utils.py | # -*- coding: utf-8 -*-
# Import nacl libs
import libnacl
import libnacl.encode
# Import python libs
import datetime
import binascii
class BaseKey(object):
'''
Include methods for key management convenience
'''
def hex_sk(self):
if hasattr(self, 'sk'):
return libnacl.encode.hex_encode(self.sk)
else:
return ''
def hex_pk(self):
if hasattr(self, 'pk'):
return libnacl.encode.hex_encode(self.pk)
def hex_vk(self):
if hasattr(self, 'vk'):
return libnacl.encode.hex_encode(self.vk)
def hex_seed(self):
if hasattr(self, 'seed'):
return libnacl.encode.hex_encode(self.seed)
def salsa_key():
'''
Generates a salsa2020 key
'''
return libnacl.randombytes(libnacl.crypto_secretbox_KEYBYTES)
def time_nonce():
'''
Generates a safe nonce
The nonce generated here is done by grabbing the 20 digit microsecond
timestamp and appending 4 random chars
'''
nonce = '{0:%Y%m%d%H%M%S%f}{1}'.format(
datetime.datetime.now(),
binascii.hexlify(libnacl.randombytes(2)).decode(encoding='UTF-8'))
return nonce.encode(encoding='UTF-8')
| # -*- coding: utf-8 -*-
# Import nacl libs
import libnacl
import libnacl.encode
# Import python libs
import time
import binascii
class BaseKey(object):
'''
Include methods for key management convenience
'''
def hex_sk(self):
if hasattr(self, 'sk'):
return libnacl.encode.hex_encode(self.sk)
else:
return ''
def hex_pk(self):
if hasattr(self, 'pk'):
return libnacl.encode.hex_encode(self.pk)
def hex_vk(self):
if hasattr(self, 'vk'):
return libnacl.encode.hex_encode(self.vk)
def hex_seed(self):
if hasattr(self, 'seed'):
return libnacl.encode.hex_encode(self.seed)
def salsa_key():
'''
Generates a salsa2020 key
'''
return libnacl.randombytes(libnacl.crypto_secretbox_KEYBYTES)
def time_nonce():
'''
Generates a safe nonce
The nonce generated here is done by grabbing the 20 digit microsecond
timestamp and appending 4 random chars
'''
nonce = '{0}{1}'.format(
str(int(time.time() * 1000000)),
binascii.hexlify(libnacl.randombytes(24)).decode(encoding='UTF-8'))
return nonce.encode(encoding='UTF-8')[:libnacl.crypto_box_NONCEBYTES]
| Make the nonce more secure and faster to generate | Make the nonce more secure and faster to generate
| Python | apache-2.0 | cachedout/libnacl,saltstack/libnacl,mindw/libnacl,johnttan/libnacl,RaetProtocol/libnacl,coinkite/libnacl | # -*- coding: utf-8 -*-
# Import nacl libs
import libnacl
import libnacl.encode
# Import python libs
import datetime
import binascii
class BaseKey(object):
'''
Include methods for key management convenience
'''
def hex_sk(self):
if hasattr(self, 'sk'):
return libnacl.encode.hex_encode(self.sk)
else:
return ''
def hex_pk(self):
if hasattr(self, 'pk'):
return libnacl.encode.hex_encode(self.pk)
def hex_vk(self):
if hasattr(self, 'vk'):
return libnacl.encode.hex_encode(self.vk)
def hex_seed(self):
if hasattr(self, 'seed'):
return libnacl.encode.hex_encode(self.seed)
def salsa_key():
'''
Generates a salsa2020 key
'''
return libnacl.randombytes(libnacl.crypto_secretbox_KEYBYTES)
def time_nonce():
'''
Generates a safe nonce
The nonce generated here is done by grabbing the 20 digit microsecond
timestamp and appending 4 random chars
'''
nonce = '{0:%Y%m%d%H%M%S%f}{1}'.format(
datetime.datetime.now(),
binascii.hexlify(libnacl.randombytes(2)).decode(encoding='UTF-8'))
return nonce.encode(encoding='UTF-8')
Make the nonce more secure and faster to generate | # -*- coding: utf-8 -*-
# Import nacl libs
import libnacl
import libnacl.encode
# Import python libs
import time
import binascii
class BaseKey(object):
'''
Include methods for key management convenience
'''
def hex_sk(self):
if hasattr(self, 'sk'):
return libnacl.encode.hex_encode(self.sk)
else:
return ''
def hex_pk(self):
if hasattr(self, 'pk'):
return libnacl.encode.hex_encode(self.pk)
def hex_vk(self):
if hasattr(self, 'vk'):
return libnacl.encode.hex_encode(self.vk)
def hex_seed(self):
if hasattr(self, 'seed'):
return libnacl.encode.hex_encode(self.seed)
def salsa_key():
'''
Generates a salsa2020 key
'''
return libnacl.randombytes(libnacl.crypto_secretbox_KEYBYTES)
def time_nonce():
'''
Generates a safe nonce
The nonce generated here is done by grabbing the 20 digit microsecond
timestamp and appending 4 random chars
'''
nonce = '{0}{1}'.format(
str(int(time.time() * 1000000)),
binascii.hexlify(libnacl.randombytes(24)).decode(encoding='UTF-8'))
return nonce.encode(encoding='UTF-8')[:libnacl.crypto_box_NONCEBYTES]
| <commit_before># -*- coding: utf-8 -*-
# Import nacl libs
import libnacl
import libnacl.encode
# Import python libs
import datetime
import binascii
class BaseKey(object):
'''
Include methods for key management convenience
'''
def hex_sk(self):
if hasattr(self, 'sk'):
return libnacl.encode.hex_encode(self.sk)
else:
return ''
def hex_pk(self):
if hasattr(self, 'pk'):
return libnacl.encode.hex_encode(self.pk)
def hex_vk(self):
if hasattr(self, 'vk'):
return libnacl.encode.hex_encode(self.vk)
def hex_seed(self):
if hasattr(self, 'seed'):
return libnacl.encode.hex_encode(self.seed)
def salsa_key():
'''
Generates a salsa2020 key
'''
return libnacl.randombytes(libnacl.crypto_secretbox_KEYBYTES)
def time_nonce():
'''
Generates a safe nonce
The nonce generated here is done by grabbing the 20 digit microsecond
timestamp and appending 4 random chars
'''
nonce = '{0:%Y%m%d%H%M%S%f}{1}'.format(
datetime.datetime.now(),
binascii.hexlify(libnacl.randombytes(2)).decode(encoding='UTF-8'))
return nonce.encode(encoding='UTF-8')
<commit_msg>Make the nonce more secure and faster to generate<commit_after> | # -*- coding: utf-8 -*-
# Import nacl libs
import libnacl
import libnacl.encode
# Import python libs
import time
import binascii
class BaseKey(object):
'''
Include methods for key management convenience
'''
def hex_sk(self):
if hasattr(self, 'sk'):
return libnacl.encode.hex_encode(self.sk)
else:
return ''
def hex_pk(self):
if hasattr(self, 'pk'):
return libnacl.encode.hex_encode(self.pk)
def hex_vk(self):
if hasattr(self, 'vk'):
return libnacl.encode.hex_encode(self.vk)
def hex_seed(self):
if hasattr(self, 'seed'):
return libnacl.encode.hex_encode(self.seed)
def salsa_key():
'''
Generates a salsa2020 key
'''
return libnacl.randombytes(libnacl.crypto_secretbox_KEYBYTES)
def time_nonce():
'''
Generates a safe nonce
The nonce generated here is done by grabbing the 20 digit microsecond
timestamp and appending 4 random chars
'''
nonce = '{0}{1}'.format(
str(int(time.time() * 1000000)),
binascii.hexlify(libnacl.randombytes(24)).decode(encoding='UTF-8'))
return nonce.encode(encoding='UTF-8')[:libnacl.crypto_box_NONCEBYTES]
| # -*- coding: utf-8 -*-
# Import nacl libs
import libnacl
import libnacl.encode
# Import python libs
import datetime
import binascii
class BaseKey(object):
'''
Include methods for key management convenience
'''
def hex_sk(self):
if hasattr(self, 'sk'):
return libnacl.encode.hex_encode(self.sk)
else:
return ''
def hex_pk(self):
if hasattr(self, 'pk'):
return libnacl.encode.hex_encode(self.pk)
def hex_vk(self):
if hasattr(self, 'vk'):
return libnacl.encode.hex_encode(self.vk)
def hex_seed(self):
if hasattr(self, 'seed'):
return libnacl.encode.hex_encode(self.seed)
def salsa_key():
'''
Generates a salsa2020 key
'''
return libnacl.randombytes(libnacl.crypto_secretbox_KEYBYTES)
def time_nonce():
'''
Generates a safe nonce
The nonce generated here is done by grabbing the 20 digit microsecond
timestamp and appending 4 random chars
'''
nonce = '{0:%Y%m%d%H%M%S%f}{1}'.format(
datetime.datetime.now(),
binascii.hexlify(libnacl.randombytes(2)).decode(encoding='UTF-8'))
return nonce.encode(encoding='UTF-8')
Make the nonce more secure and faster to generate# -*- coding: utf-8 -*-
# Import nacl libs
import libnacl
import libnacl.encode
# Import python libs
import time
import binascii
class BaseKey(object):
'''
Include methods for key management convenience
'''
def hex_sk(self):
if hasattr(self, 'sk'):
return libnacl.encode.hex_encode(self.sk)
else:
return ''
def hex_pk(self):
if hasattr(self, 'pk'):
return libnacl.encode.hex_encode(self.pk)
def hex_vk(self):
if hasattr(self, 'vk'):
return libnacl.encode.hex_encode(self.vk)
def hex_seed(self):
if hasattr(self, 'seed'):
return libnacl.encode.hex_encode(self.seed)
def salsa_key():
'''
Generates a salsa2020 key
'''
return libnacl.randombytes(libnacl.crypto_secretbox_KEYBYTES)
def time_nonce():
'''
Generates a safe nonce
The nonce generated here is done by grabbing the 20 digit microsecond
timestamp and appending 4 random chars
'''
nonce = '{0}{1}'.format(
str(int(time.time() * 1000000)),
binascii.hexlify(libnacl.randombytes(24)).decode(encoding='UTF-8'))
return nonce.encode(encoding='UTF-8')[:libnacl.crypto_box_NONCEBYTES]
| <commit_before># -*- coding: utf-8 -*-
# Import nacl libs
import libnacl
import libnacl.encode
# Import python libs
import datetime
import binascii
class BaseKey(object):
'''
Include methods for key management convenience
'''
def hex_sk(self):
if hasattr(self, 'sk'):
return libnacl.encode.hex_encode(self.sk)
else:
return ''
def hex_pk(self):
if hasattr(self, 'pk'):
return libnacl.encode.hex_encode(self.pk)
def hex_vk(self):
if hasattr(self, 'vk'):
return libnacl.encode.hex_encode(self.vk)
def hex_seed(self):
if hasattr(self, 'seed'):
return libnacl.encode.hex_encode(self.seed)
def salsa_key():
'''
Generates a salsa2020 key
'''
return libnacl.randombytes(libnacl.crypto_secretbox_KEYBYTES)
def time_nonce():
'''
Generates a safe nonce
The nonce generated here is done by grabbing the 20 digit microsecond
timestamp and appending 4 random chars
'''
nonce = '{0:%Y%m%d%H%M%S%f}{1}'.format(
datetime.datetime.now(),
binascii.hexlify(libnacl.randombytes(2)).decode(encoding='UTF-8'))
return nonce.encode(encoding='UTF-8')
<commit_msg>Make the nonce more secure and faster to generate<commit_after># -*- coding: utf-8 -*-
# Import nacl libs
import libnacl
import libnacl.encode
# Import python libs
import time
import binascii
class BaseKey(object):
'''
Include methods for key management convenience
'''
def hex_sk(self):
if hasattr(self, 'sk'):
return libnacl.encode.hex_encode(self.sk)
else:
return ''
def hex_pk(self):
if hasattr(self, 'pk'):
return libnacl.encode.hex_encode(self.pk)
def hex_vk(self):
if hasattr(self, 'vk'):
return libnacl.encode.hex_encode(self.vk)
def hex_seed(self):
if hasattr(self, 'seed'):
return libnacl.encode.hex_encode(self.seed)
def salsa_key():
'''
Generates a salsa2020 key
'''
return libnacl.randombytes(libnacl.crypto_secretbox_KEYBYTES)
def time_nonce():
'''
Generates a safe nonce
The nonce generated here is done by grabbing the 20 digit microsecond
timestamp and appending 4 random chars
'''
nonce = '{0}{1}'.format(
str(int(time.time() * 1000000)),
binascii.hexlify(libnacl.randombytes(24)).decode(encoding='UTF-8'))
return nonce.encode(encoding='UTF-8')[:libnacl.crypto_box_NONCEBYTES]
|
73e50feae8fb6c06ace5f268e11c8df985e5eace | login/routers.py | login/routers.py | # List of apps that will use the users database
USERS_DATABASE_APPS = ['auth','login','sessions']
class UserRouter(object):
"""
A router to control all database operations on models in the
login application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read login models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
print model._meta.app_label
print "BRISA"
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the login app is involved.
"""
if obj1._meta.app_label in USERS_DATABASE_APPS or \
obj2._meta.app_label in USERS_DATABASE_APPS:
return True
return None
def allow_syncdb(self, db, model):
"""
Make sure the login app only appears in the 'users'
database.
"""
if db == 'users':
return model._meta.app_label in USERS_DATABASE_APPS
elif model._meta.app_label in USERS_DATABASE_APPS:
return False
return None
| # List of apps that will use the users database
USERS_DATABASE_APPS = ['auth', 'login', 'sessions', 'contenttypes', 'sites']
class UserRouter(object):
"""
A router to control all database operations on models in the
login application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read login models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the login app is involved.
"""
if obj1._meta.app_label in USERS_DATABASE_APPS or \
obj2._meta.app_label in USERS_DATABASE_APPS:
return True
print model._meta.app_label
print "BRISA1"
return None
def allow_syncdb(self, db, model):
"""
Make sure the login app only appears in the 'users'
database.
"""
if db == 'users':
return model._meta.app_label in USERS_DATABASE_APPS
elif model._meta.app_label in USERS_DATABASE_APPS:
return False
print model._meta.app_label
print "BRISA"
return None
| Add apps on list that will be used on the test databases | [login] Add apps on list that will be used on the test databases
Added apps sites and contenttypes to the list.
These apps were causing troubles on the test databases.
Signed off by: Heitor Reis <marcheing@gmail.com>
Signed off by: Filipe Vaz <vazfilipe92@gmail.com>
| Python | agpl-3.0 | SuperNovaPOLIUSP/supernova,SuperNovaPOLIUSP/supernova,SuperNovaPOLIUSP/supernova,SuperNovaPOLIUSP/supernova | # List of apps that will use the users database
USERS_DATABASE_APPS = ['auth','login','sessions']
class UserRouter(object):
"""
A router to control all database operations on models in the
login application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read login models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
print model._meta.app_label
print "BRISA"
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the login app is involved.
"""
if obj1._meta.app_label in USERS_DATABASE_APPS or \
obj2._meta.app_label in USERS_DATABASE_APPS:
return True
return None
def allow_syncdb(self, db, model):
"""
Make sure the login app only appears in the 'users'
database.
"""
if db == 'users':
return model._meta.app_label in USERS_DATABASE_APPS
elif model._meta.app_label in USERS_DATABASE_APPS:
return False
return None
[login] Add apps on list that will be used on the test databases
Added apps sites and contenttypes to the list.
These apps were causing troubles on the test databases.
Signed off by: Heitor Reis <marcheing@gmail.com>
Signed off by: Filipe Vaz <vazfilipe92@gmail.com> | # List of apps that will use the users database
USERS_DATABASE_APPS = ['auth', 'login', 'sessions', 'contenttypes', 'sites']
class UserRouter(object):
"""
A router to control all database operations on models in the
login application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read login models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the login app is involved.
"""
if obj1._meta.app_label in USERS_DATABASE_APPS or \
obj2._meta.app_label in USERS_DATABASE_APPS:
return True
print model._meta.app_label
print "BRISA1"
return None
def allow_syncdb(self, db, model):
"""
Make sure the login app only appears in the 'users'
database.
"""
if db == 'users':
return model._meta.app_label in USERS_DATABASE_APPS
elif model._meta.app_label in USERS_DATABASE_APPS:
return False
print model._meta.app_label
print "BRISA"
return None
| <commit_before># List of apps that will use the users database
USERS_DATABASE_APPS = ['auth','login','sessions']
class UserRouter(object):
"""
A router to control all database operations on models in the
login application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read login models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
print model._meta.app_label
print "BRISA"
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the login app is involved.
"""
if obj1._meta.app_label in USERS_DATABASE_APPS or \
obj2._meta.app_label in USERS_DATABASE_APPS:
return True
return None
def allow_syncdb(self, db, model):
"""
Make sure the login app only appears in the 'users'
database.
"""
if db == 'users':
return model._meta.app_label in USERS_DATABASE_APPS
elif model._meta.app_label in USERS_DATABASE_APPS:
return False
return None
<commit_msg>[login] Add apps on list that will be used on the test databases
Added apps sites and contenttypes to the list.
These apps were causing troubles on the test databases.
Signed off by: Heitor Reis <marcheing@gmail.com>
Signed off by: Filipe Vaz <vazfilipe92@gmail.com><commit_after> | # List of apps that will use the users database
USERS_DATABASE_APPS = ['auth', 'login', 'sessions', 'contenttypes', 'sites']
class UserRouter(object):
"""
A router to control all database operations on models in the
login application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read login models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the login app is involved.
"""
if obj1._meta.app_label in USERS_DATABASE_APPS or \
obj2._meta.app_label in USERS_DATABASE_APPS:
return True
print model._meta.app_label
print "BRISA1"
return None
def allow_syncdb(self, db, model):
"""
Make sure the login app only appears in the 'users'
database.
"""
if db == 'users':
return model._meta.app_label in USERS_DATABASE_APPS
elif model._meta.app_label in USERS_DATABASE_APPS:
return False
print model._meta.app_label
print "BRISA"
return None
| # List of apps that will use the users database
USERS_DATABASE_APPS = ['auth','login','sessions']
class UserRouter(object):
"""
A router to control all database operations on models in the
login application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read login models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
print model._meta.app_label
print "BRISA"
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the login app is involved.
"""
if obj1._meta.app_label in USERS_DATABASE_APPS or \
obj2._meta.app_label in USERS_DATABASE_APPS:
return True
return None
def allow_syncdb(self, db, model):
"""
Make sure the login app only appears in the 'users'
database.
"""
if db == 'users':
return model._meta.app_label in USERS_DATABASE_APPS
elif model._meta.app_label in USERS_DATABASE_APPS:
return False
return None
[login] Add apps on list that will be used on the test databases
Added apps sites and contenttypes to the list.
These apps were causing troubles on the test databases.
Signed off by: Heitor Reis <marcheing@gmail.com>
Signed off by: Filipe Vaz <vazfilipe92@gmail.com># List of apps that will use the users database
USERS_DATABASE_APPS = ['auth', 'login', 'sessions', 'contenttypes', 'sites']
class UserRouter(object):
"""
A router to control all database operations on models in the
login application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read login models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the login app is involved.
"""
if obj1._meta.app_label in USERS_DATABASE_APPS or \
obj2._meta.app_label in USERS_DATABASE_APPS:
return True
print model._meta.app_label
print "BRISA1"
return None
def allow_syncdb(self, db, model):
"""
Make sure the login app only appears in the 'users'
database.
"""
if db == 'users':
return model._meta.app_label in USERS_DATABASE_APPS
elif model._meta.app_label in USERS_DATABASE_APPS:
return False
print model._meta.app_label
print "BRISA"
return None
| <commit_before># List of apps that will use the users database
USERS_DATABASE_APPS = ['auth','login','sessions']
class UserRouter(object):
"""
A router to control all database operations on models in the
login application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read login models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
print model._meta.app_label
print "BRISA"
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the login app is involved.
"""
if obj1._meta.app_label in USERS_DATABASE_APPS or \
obj2._meta.app_label in USERS_DATABASE_APPS:
return True
return None
def allow_syncdb(self, db, model):
"""
Make sure the login app only appears in the 'users'
database.
"""
if db == 'users':
return model._meta.app_label in USERS_DATABASE_APPS
elif model._meta.app_label in USERS_DATABASE_APPS:
return False
return None
<commit_msg>[login] Add apps on list that will be used on the test databases
Added apps sites and contenttypes to the list.
These apps were causing troubles on the test databases.
Signed off by: Heitor Reis <marcheing@gmail.com>
Signed off by: Filipe Vaz <vazfilipe92@gmail.com><commit_after># List of apps that will use the users database
USERS_DATABASE_APPS = ['auth', 'login', 'sessions', 'contenttypes', 'sites']
class UserRouter(object):
"""
A router to control all database operations on models in the
login application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read login models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to users.
"""
if model._meta.app_label in USERS_DATABASE_APPS:
return 'users'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the login app is involved.
"""
if obj1._meta.app_label in USERS_DATABASE_APPS or \
obj2._meta.app_label in USERS_DATABASE_APPS:
return True
print model._meta.app_label
print "BRISA1"
return None
def allow_syncdb(self, db, model):
"""
Make sure the login app only appears in the 'users'
database.
"""
if db == 'users':
return model._meta.app_label in USERS_DATABASE_APPS
elif model._meta.app_label in USERS_DATABASE_APPS:
return False
print model._meta.app_label
print "BRISA"
return None
|
6f5e4ff4f8e4002566a9ac18bcb22778be9409bd | electro/api.py | electro/api.py | # -*- coding: utf-8 -*-
from electro.errors import ResourceDuplicatedDefinedError
class API(object):
def __init__(self, app=None, decorators=None,
catch_all_404s=None):
self.app = app
self.endpoints = set()
self.decorators = decorators or []
self.catch_all_404s = catch_all_404s
def add_resource(self, resource, url, **kw):
endpoint = kw.pop('endpoint', None) or resource.__name__.lower()
self.endpoints.add(endpoint)
if endpoint in self.app.view_functions:
previous_view_class = self.app.view_functions[endpoint].__dict__['view_class']
if previous_view_class != resource:
raise ResourceDuplicatedDefinedError(endpoint)
resource.endpoint = endpoint
resource_func = resource.as_view(endpoint)
for decorator in self.decorators:
resource_func = decorator(resource_func)
self.app.add_url_rule(url, view_func=resource_func, **kw)
| # -*- coding: utf-8 -*-
from electro.errors import ResourceDuplicatedDefinedError
class API(object):
def __init__(self, app=None, decorators=None,
catch_all_404s=None):
self.app = app
self.endpoints = set()
self.decorators = decorators or []
self.catch_all_404s = catch_all_404s
def add_resource(self, resource, url, **kw):
endpoint = kw.pop('endpoint', None) or resource.__name__.lower()
self.endpoints.add(endpoint)
if endpoint in self.app.view_functions:
previous_view_class = self.app.view_functions[endpoint].__dict__['view_class']
if previous_view_class != resource:
raise ResourceDuplicatedDefinedError(endpoint)
resource.endpoint = endpoint
resource_func = resource.as_view(endpoint)
for decorator in self.decorators:
resource_func = decorator(resource_func)
self.app.add_url_rule(url, view_func=resource_func, endpoint=endpoint, **kw)
| Add endpoint for flask app. | Add endpoint for flask app.
| Python | mit | soasme/electro | # -*- coding: utf-8 -*-
from electro.errors import ResourceDuplicatedDefinedError
class API(object):
def __init__(self, app=None, decorators=None,
catch_all_404s=None):
self.app = app
self.endpoints = set()
self.decorators = decorators or []
self.catch_all_404s = catch_all_404s
def add_resource(self, resource, url, **kw):
endpoint = kw.pop('endpoint', None) or resource.__name__.lower()
self.endpoints.add(endpoint)
if endpoint in self.app.view_functions:
previous_view_class = self.app.view_functions[endpoint].__dict__['view_class']
if previous_view_class != resource:
raise ResourceDuplicatedDefinedError(endpoint)
resource.endpoint = endpoint
resource_func = resource.as_view(endpoint)
for decorator in self.decorators:
resource_func = decorator(resource_func)
self.app.add_url_rule(url, view_func=resource_func, **kw)
Add endpoint for flask app. | # -*- coding: utf-8 -*-
from electro.errors import ResourceDuplicatedDefinedError
class API(object):
def __init__(self, app=None, decorators=None,
catch_all_404s=None):
self.app = app
self.endpoints = set()
self.decorators = decorators or []
self.catch_all_404s = catch_all_404s
def add_resource(self, resource, url, **kw):
endpoint = kw.pop('endpoint', None) or resource.__name__.lower()
self.endpoints.add(endpoint)
if endpoint in self.app.view_functions:
previous_view_class = self.app.view_functions[endpoint].__dict__['view_class']
if previous_view_class != resource:
raise ResourceDuplicatedDefinedError(endpoint)
resource.endpoint = endpoint
resource_func = resource.as_view(endpoint)
for decorator in self.decorators:
resource_func = decorator(resource_func)
self.app.add_url_rule(url, view_func=resource_func, endpoint=endpoint, **kw)
| <commit_before># -*- coding: utf-8 -*-
from electro.errors import ResourceDuplicatedDefinedError
class API(object):
def __init__(self, app=None, decorators=None,
catch_all_404s=None):
self.app = app
self.endpoints = set()
self.decorators = decorators or []
self.catch_all_404s = catch_all_404s
def add_resource(self, resource, url, **kw):
endpoint = kw.pop('endpoint', None) or resource.__name__.lower()
self.endpoints.add(endpoint)
if endpoint in self.app.view_functions:
previous_view_class = self.app.view_functions[endpoint].__dict__['view_class']
if previous_view_class != resource:
raise ResourceDuplicatedDefinedError(endpoint)
resource.endpoint = endpoint
resource_func = resource.as_view(endpoint)
for decorator in self.decorators:
resource_func = decorator(resource_func)
self.app.add_url_rule(url, view_func=resource_func, **kw)
<commit_msg>Add endpoint for flask app.<commit_after> | # -*- coding: utf-8 -*-
from electro.errors import ResourceDuplicatedDefinedError
class API(object):
def __init__(self, app=None, decorators=None,
catch_all_404s=None):
self.app = app
self.endpoints = set()
self.decorators = decorators or []
self.catch_all_404s = catch_all_404s
def add_resource(self, resource, url, **kw):
endpoint = kw.pop('endpoint', None) or resource.__name__.lower()
self.endpoints.add(endpoint)
if endpoint in self.app.view_functions:
previous_view_class = self.app.view_functions[endpoint].__dict__['view_class']
if previous_view_class != resource:
raise ResourceDuplicatedDefinedError(endpoint)
resource.endpoint = endpoint
resource_func = resource.as_view(endpoint)
for decorator in self.decorators:
resource_func = decorator(resource_func)
self.app.add_url_rule(url, view_func=resource_func, endpoint=endpoint, **kw)
| # -*- coding: utf-8 -*-
from electro.errors import ResourceDuplicatedDefinedError
class API(object):
def __init__(self, app=None, decorators=None,
catch_all_404s=None):
self.app = app
self.endpoints = set()
self.decorators = decorators or []
self.catch_all_404s = catch_all_404s
def add_resource(self, resource, url, **kw):
endpoint = kw.pop('endpoint', None) or resource.__name__.lower()
self.endpoints.add(endpoint)
if endpoint in self.app.view_functions:
previous_view_class = self.app.view_functions[endpoint].__dict__['view_class']
if previous_view_class != resource:
raise ResourceDuplicatedDefinedError(endpoint)
resource.endpoint = endpoint
resource_func = resource.as_view(endpoint)
for decorator in self.decorators:
resource_func = decorator(resource_func)
self.app.add_url_rule(url, view_func=resource_func, **kw)
Add endpoint for flask app.# -*- coding: utf-8 -*-
from electro.errors import ResourceDuplicatedDefinedError
class API(object):
def __init__(self, app=None, decorators=None,
catch_all_404s=None):
self.app = app
self.endpoints = set()
self.decorators = decorators or []
self.catch_all_404s = catch_all_404s
def add_resource(self, resource, url, **kw):
endpoint = kw.pop('endpoint', None) or resource.__name__.lower()
self.endpoints.add(endpoint)
if endpoint in self.app.view_functions:
previous_view_class = self.app.view_functions[endpoint].__dict__['view_class']
if previous_view_class != resource:
raise ResourceDuplicatedDefinedError(endpoint)
resource.endpoint = endpoint
resource_func = resource.as_view(endpoint)
for decorator in self.decorators:
resource_func = decorator(resource_func)
self.app.add_url_rule(url, view_func=resource_func, endpoint=endpoint, **kw)
| <commit_before># -*- coding: utf-8 -*-
from electro.errors import ResourceDuplicatedDefinedError
class API(object):
def __init__(self, app=None, decorators=None,
catch_all_404s=None):
self.app = app
self.endpoints = set()
self.decorators = decorators or []
self.catch_all_404s = catch_all_404s
def add_resource(self, resource, url, **kw):
endpoint = kw.pop('endpoint', None) or resource.__name__.lower()
self.endpoints.add(endpoint)
if endpoint in self.app.view_functions:
previous_view_class = self.app.view_functions[endpoint].__dict__['view_class']
if previous_view_class != resource:
raise ResourceDuplicatedDefinedError(endpoint)
resource.endpoint = endpoint
resource_func = resource.as_view(endpoint)
for decorator in self.decorators:
resource_func = decorator(resource_func)
self.app.add_url_rule(url, view_func=resource_func, **kw)
<commit_msg>Add endpoint for flask app.<commit_after># -*- coding: utf-8 -*-
from electro.errors import ResourceDuplicatedDefinedError
class API(object):
def __init__(self, app=None, decorators=None,
catch_all_404s=None):
self.app = app
self.endpoints = set()
self.decorators = decorators or []
self.catch_all_404s = catch_all_404s
def add_resource(self, resource, url, **kw):
endpoint = kw.pop('endpoint', None) or resource.__name__.lower()
self.endpoints.add(endpoint)
if endpoint in self.app.view_functions:
previous_view_class = self.app.view_functions[endpoint].__dict__['view_class']
if previous_view_class != resource:
raise ResourceDuplicatedDefinedError(endpoint)
resource.endpoint = endpoint
resource_func = resource.as_view(endpoint)
for decorator in self.decorators:
resource_func = decorator(resource_func)
self.app.add_url_rule(url, view_func=resource_func, endpoint=endpoint, **kw)
|
92b2c210133d1be628330db37b1ac69278bf99b5 | config.py | config.py | import os
import jinja2
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
SECRET_KEY = 'this is not secret'
STATIC_URL_PATH = '/supplier/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'asset_path': ASSET_PATH,
'header_class': 'with-proposition'
}
# Logging
DM_LOG_LEVEL = 'DEBUG'
DM_APP_NAME = 'buyer-frontend'
DM_LOG_PATH = '/var/log/digitalmarketplace/application.log'
DM_DOWNSTREAM_REQUEST_ID_HEADER = 'X-Amz-Cf-Id'
@staticmethod
def init_app(app):
repo_root = os.path.abspath(os.path.dirname(__file__))
template_folders = [
os.path.join(repo_root,
'bower_components/govuk_template/views/layouts'),
os.path.join(repo_root, 'app/templates')
]
jinja_loader = jinja2.FileSystemLoader(template_folders)
app.jinja_loader = jinja_loader
class Test(Config):
DEBUG = True
class Development(Config):
DEBUG = True,
class Live(Config):
DEBUG = False
config = {
'development': Development,
'preview': Development,
'staging': Live,
'production': Live,
'test': Test,
}
| import os
import jinja2
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
SECRET_KEY = 'this is not secret'
STATIC_URL_PATH = '/suppliers/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'asset_path': ASSET_PATH,
'header_class': 'with-proposition'
}
# Logging
DM_LOG_LEVEL = 'DEBUG'
DM_APP_NAME = 'buyer-frontend'
DM_LOG_PATH = '/var/log/digitalmarketplace/application.log'
DM_DOWNSTREAM_REQUEST_ID_HEADER = 'X-Amz-Cf-Id'
@staticmethod
def init_app(app):
repo_root = os.path.abspath(os.path.dirname(__file__))
template_folders = [
os.path.join(repo_root,
'bower_components/govuk_template/views/layouts'),
os.path.join(repo_root, 'app/templates')
]
jinja_loader = jinja2.FileSystemLoader(template_folders)
app.jinja_loader = jinja_loader
class Test(Config):
DEBUG = True
class Development(Config):
DEBUG = True,
class Live(Config):
DEBUG = False
config = {
'development': Development,
'preview': Development,
'staging': Live,
'production': Live,
'test': Test,
}
| Fix static path to match the /suppliers URL prefix | Fix static path to match the /suppliers URL prefix
| Python | mit | alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend | import os
import jinja2
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
SECRET_KEY = 'this is not secret'
STATIC_URL_PATH = '/supplier/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'asset_path': ASSET_PATH,
'header_class': 'with-proposition'
}
# Logging
DM_LOG_LEVEL = 'DEBUG'
DM_APP_NAME = 'buyer-frontend'
DM_LOG_PATH = '/var/log/digitalmarketplace/application.log'
DM_DOWNSTREAM_REQUEST_ID_HEADER = 'X-Amz-Cf-Id'
@staticmethod
def init_app(app):
repo_root = os.path.abspath(os.path.dirname(__file__))
template_folders = [
os.path.join(repo_root,
'bower_components/govuk_template/views/layouts'),
os.path.join(repo_root, 'app/templates')
]
jinja_loader = jinja2.FileSystemLoader(template_folders)
app.jinja_loader = jinja_loader
class Test(Config):
DEBUG = True
class Development(Config):
DEBUG = True,
class Live(Config):
DEBUG = False
config = {
'development': Development,
'preview': Development,
'staging': Live,
'production': Live,
'test': Test,
}
Fix static path to match the /suppliers URL prefix | import os
import jinja2
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
SECRET_KEY = 'this is not secret'
STATIC_URL_PATH = '/suppliers/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'asset_path': ASSET_PATH,
'header_class': 'with-proposition'
}
# Logging
DM_LOG_LEVEL = 'DEBUG'
DM_APP_NAME = 'buyer-frontend'
DM_LOG_PATH = '/var/log/digitalmarketplace/application.log'
DM_DOWNSTREAM_REQUEST_ID_HEADER = 'X-Amz-Cf-Id'
@staticmethod
def init_app(app):
repo_root = os.path.abspath(os.path.dirname(__file__))
template_folders = [
os.path.join(repo_root,
'bower_components/govuk_template/views/layouts'),
os.path.join(repo_root, 'app/templates')
]
jinja_loader = jinja2.FileSystemLoader(template_folders)
app.jinja_loader = jinja_loader
class Test(Config):
DEBUG = True
class Development(Config):
DEBUG = True,
class Live(Config):
DEBUG = False
config = {
'development': Development,
'preview': Development,
'staging': Live,
'production': Live,
'test': Test,
}
| <commit_before>import os
import jinja2
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
SECRET_KEY = 'this is not secret'
STATIC_URL_PATH = '/supplier/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'asset_path': ASSET_PATH,
'header_class': 'with-proposition'
}
# Logging
DM_LOG_LEVEL = 'DEBUG'
DM_APP_NAME = 'buyer-frontend'
DM_LOG_PATH = '/var/log/digitalmarketplace/application.log'
DM_DOWNSTREAM_REQUEST_ID_HEADER = 'X-Amz-Cf-Id'
@staticmethod
def init_app(app):
repo_root = os.path.abspath(os.path.dirname(__file__))
template_folders = [
os.path.join(repo_root,
'bower_components/govuk_template/views/layouts'),
os.path.join(repo_root, 'app/templates')
]
jinja_loader = jinja2.FileSystemLoader(template_folders)
app.jinja_loader = jinja_loader
class Test(Config):
DEBUG = True
class Development(Config):
DEBUG = True,
class Live(Config):
DEBUG = False
config = {
'development': Development,
'preview': Development,
'staging': Live,
'production': Live,
'test': Test,
}
<commit_msg>Fix static path to match the /suppliers URL prefix<commit_after> | import os
import jinja2
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
SECRET_KEY = 'this is not secret'
STATIC_URL_PATH = '/suppliers/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'asset_path': ASSET_PATH,
'header_class': 'with-proposition'
}
# Logging
DM_LOG_LEVEL = 'DEBUG'
DM_APP_NAME = 'buyer-frontend'
DM_LOG_PATH = '/var/log/digitalmarketplace/application.log'
DM_DOWNSTREAM_REQUEST_ID_HEADER = 'X-Amz-Cf-Id'
@staticmethod
def init_app(app):
repo_root = os.path.abspath(os.path.dirname(__file__))
template_folders = [
os.path.join(repo_root,
'bower_components/govuk_template/views/layouts'),
os.path.join(repo_root, 'app/templates')
]
jinja_loader = jinja2.FileSystemLoader(template_folders)
app.jinja_loader = jinja_loader
class Test(Config):
DEBUG = True
class Development(Config):
DEBUG = True,
class Live(Config):
DEBUG = False
config = {
'development': Development,
'preview': Development,
'staging': Live,
'production': Live,
'test': Test,
}
| import os
import jinja2
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
SECRET_KEY = 'this is not secret'
STATIC_URL_PATH = '/supplier/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'asset_path': ASSET_PATH,
'header_class': 'with-proposition'
}
# Logging
DM_LOG_LEVEL = 'DEBUG'
DM_APP_NAME = 'buyer-frontend'
DM_LOG_PATH = '/var/log/digitalmarketplace/application.log'
DM_DOWNSTREAM_REQUEST_ID_HEADER = 'X-Amz-Cf-Id'
@staticmethod
def init_app(app):
repo_root = os.path.abspath(os.path.dirname(__file__))
template_folders = [
os.path.join(repo_root,
'bower_components/govuk_template/views/layouts'),
os.path.join(repo_root, 'app/templates')
]
jinja_loader = jinja2.FileSystemLoader(template_folders)
app.jinja_loader = jinja_loader
class Test(Config):
DEBUG = True
class Development(Config):
DEBUG = True,
class Live(Config):
DEBUG = False
config = {
'development': Development,
'preview': Development,
'staging': Live,
'production': Live,
'test': Test,
}
Fix static path to match the /suppliers URL prefiximport os
import jinja2
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
SECRET_KEY = 'this is not secret'
STATIC_URL_PATH = '/suppliers/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'asset_path': ASSET_PATH,
'header_class': 'with-proposition'
}
# Logging
DM_LOG_LEVEL = 'DEBUG'
DM_APP_NAME = 'buyer-frontend'
DM_LOG_PATH = '/var/log/digitalmarketplace/application.log'
DM_DOWNSTREAM_REQUEST_ID_HEADER = 'X-Amz-Cf-Id'
@staticmethod
def init_app(app):
repo_root = os.path.abspath(os.path.dirname(__file__))
template_folders = [
os.path.join(repo_root,
'bower_components/govuk_template/views/layouts'),
os.path.join(repo_root, 'app/templates')
]
jinja_loader = jinja2.FileSystemLoader(template_folders)
app.jinja_loader = jinja_loader
class Test(Config):
DEBUG = True
class Development(Config):
DEBUG = True,
class Live(Config):
DEBUG = False
config = {
'development': Development,
'preview': Development,
'staging': Live,
'production': Live,
'test': Test,
}
| <commit_before>import os
import jinja2
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
SECRET_KEY = 'this is not secret'
STATIC_URL_PATH = '/supplier/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'asset_path': ASSET_PATH,
'header_class': 'with-proposition'
}
# Logging
DM_LOG_LEVEL = 'DEBUG'
DM_APP_NAME = 'buyer-frontend'
DM_LOG_PATH = '/var/log/digitalmarketplace/application.log'
DM_DOWNSTREAM_REQUEST_ID_HEADER = 'X-Amz-Cf-Id'
@staticmethod
def init_app(app):
repo_root = os.path.abspath(os.path.dirname(__file__))
template_folders = [
os.path.join(repo_root,
'bower_components/govuk_template/views/layouts'),
os.path.join(repo_root, 'app/templates')
]
jinja_loader = jinja2.FileSystemLoader(template_folders)
app.jinja_loader = jinja_loader
class Test(Config):
DEBUG = True
class Development(Config):
DEBUG = True,
class Live(Config):
DEBUG = False
config = {
'development': Development,
'preview': Development,
'staging': Live,
'production': Live,
'test': Test,
}
<commit_msg>Fix static path to match the /suppliers URL prefix<commit_after>import os
import jinja2
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
SECRET_KEY = 'this is not secret'
STATIC_URL_PATH = '/suppliers/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'asset_path': ASSET_PATH,
'header_class': 'with-proposition'
}
# Logging
DM_LOG_LEVEL = 'DEBUG'
DM_APP_NAME = 'buyer-frontend'
DM_LOG_PATH = '/var/log/digitalmarketplace/application.log'
DM_DOWNSTREAM_REQUEST_ID_HEADER = 'X-Amz-Cf-Id'
@staticmethod
def init_app(app):
repo_root = os.path.abspath(os.path.dirname(__file__))
template_folders = [
os.path.join(repo_root,
'bower_components/govuk_template/views/layouts'),
os.path.join(repo_root, 'app/templates')
]
jinja_loader = jinja2.FileSystemLoader(template_folders)
app.jinja_loader = jinja_loader
class Test(Config):
DEBUG = True
class Development(Config):
DEBUG = True,
class Live(Config):
DEBUG = False
config = {
'development': Development,
'preview': Development,
'staging': Live,
'production': Live,
'test': Test,
}
|
d0ae974d737ff173cd8af159f869be7d69db08cd | tests/functional/test_l10n.py | tests/functional/test_l10n.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(base_url, selenium):
page = HomePage(base_url, selenium).open()
initial = page.footer.language
available = page.footer.languages
available.remove(initial) # avoid selecting the same language
new = random.choice(available) # pick a random lanugage
page.footer.select_language(new)
assert new in selenium.current_url, 'Language is not in URL'
assert new == page.footer.language, 'Language has not been selected'
| # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(base_url, selenium):
page = HomePage(base_url, selenium).open()
initial = page.footer.language
# avoid selecting the same language or locales that have homepage redirects
excluded = [initial, 'ja', 'zh-TW', 'zh-CN']
available = [l for l in page.footer.languages if l not in excluded]
new = random.choice(available)
page.footer.select_language(new)
assert new in selenium.current_url, 'Language is not in URL'
assert new == page.footer.language, 'Language has not been selected'
| Exclude redirected locales from homepage language selector functional tests | Exclude redirected locales from homepage language selector functional tests
| Python | mpl-2.0 | MichaelKohler/bedrock,glogiotatidis/bedrock,gerv/bedrock,pascalchevrel/bedrock,sylvestre/bedrock,gerv/bedrock,mkmelin/bedrock,sgarrity/bedrock,alexgibson/bedrock,gauthierm/bedrock,TheJJ100100/bedrock,CSCI-462-01-2017/bedrock,glogiotatidis/bedrock,gerv/bedrock,mkmelin/bedrock,mkmelin/bedrock,mermi/bedrock,analytics-pros/mozilla-bedrock,jpetto/bedrock,davehunt/bedrock,alexgibson/bedrock,Sancus/bedrock,alexgibson/bedrock,craigcook/bedrock,schalkneethling/bedrock,sgarrity/bedrock,mkmelin/bedrock,l-hedgehog/bedrock,CSCI-462-01-2017/bedrock,flodolo/bedrock,TheJJ100100/bedrock,davehunt/bedrock,davehunt/bedrock,davehunt/bedrock,schalkneethling/bedrock,jpetto/bedrock,craigcook/bedrock,craigcook/bedrock,jpetto/bedrock,analytics-pros/mozilla-bedrock,sgarrity/bedrock,flodolo/bedrock,TheJJ100100/bedrock,mozilla/bedrock,l-hedgehog/bedrock,mozilla/bedrock,jpetto/bedrock,MichaelKohler/bedrock,kyoshino/bedrock,pascalchevrel/bedrock,gauthierm/bedrock,mermi/bedrock,jgmize/bedrock,sgarrity/bedrock,Sancus/bedrock,alexgibson/bedrock,analytics-pros/mozilla-bedrock,pascalchevrel/bedrock,kyoshino/bedrock,hoosteeno/bedrock,mermi/bedrock,hoosteeno/bedrock,ericawright/bedrock,sylvestre/bedrock,jgmize/bedrock,pascalchevrel/bedrock,l-hedgehog/bedrock,TheoChevalier/bedrock,hoosteeno/bedrock,schalkneethling/bedrock,glogiotatidis/bedrock,mozilla/bedrock,CSCI-462-01-2017/bedrock,CSCI-462-01-2017/bedrock,kyoshino/bedrock,glogiotatidis/bedrock,gauthierm/bedrock,gauthierm/bedrock,craigcook/bedrock,hoosteeno/bedrock,schalkneethling/bedrock,flodolo/bedrock,mermi/bedrock,jgmize/bedrock,analytics-pros/mozilla-bedrock,MichaelKohler/bedrock,sylvestre/bedrock,TheJJ100100/bedrock,l-hedgehog/bedrock,TheoChevalier/bedrock,TheoChevalier/bedrock,ericawright/bedrock,ericawright/bedrock,MichaelKohler/bedrock,gerv/bedrock,mozilla/bedrock,sylvestre/bedrock,Sancus/bedrock,flodolo/bedrock,TheoChevalier/bedrock,jgmize/bedrock,Sancus/bedrock,ericawright/bedrock,kyoshino/bedrock | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(base_url, selenium):
page = HomePage(base_url, selenium).open()
initial = page.footer.language
available = page.footer.languages
available.remove(initial) # avoid selecting the same language
new = random.choice(available) # pick a random lanugage
page.footer.select_language(new)
assert new in selenium.current_url, 'Language is not in URL'
assert new == page.footer.language, 'Language has not been selected'
Exclude redirected locales from homepage language selector functional tests | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(base_url, selenium):
page = HomePage(base_url, selenium).open()
initial = page.footer.language
# avoid selecting the same language or locales that have homepage redirects
excluded = [initial, 'ja', 'zh-TW', 'zh-CN']
available = [l for l in page.footer.languages if l not in excluded]
new = random.choice(available)
page.footer.select_language(new)
assert new in selenium.current_url, 'Language is not in URL'
assert new == page.footer.language, 'Language has not been selected'
| <commit_before># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(base_url, selenium):
page = HomePage(base_url, selenium).open()
initial = page.footer.language
available = page.footer.languages
available.remove(initial) # avoid selecting the same language
new = random.choice(available) # pick a random lanugage
page.footer.select_language(new)
assert new in selenium.current_url, 'Language is not in URL'
assert new == page.footer.language, 'Language has not been selected'
<commit_msg>Exclude redirected locales from homepage language selector functional tests<commit_after> | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(base_url, selenium):
page = HomePage(base_url, selenium).open()
initial = page.footer.language
# avoid selecting the same language or locales that have homepage redirects
excluded = [initial, 'ja', 'zh-TW', 'zh-CN']
available = [l for l in page.footer.languages if l not in excluded]
new = random.choice(available)
page.footer.select_language(new)
assert new in selenium.current_url, 'Language is not in URL'
assert new == page.footer.language, 'Language has not been selected'
| # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(base_url, selenium):
page = HomePage(base_url, selenium).open()
initial = page.footer.language
available = page.footer.languages
available.remove(initial) # avoid selecting the same language
new = random.choice(available) # pick a random lanugage
page.footer.select_language(new)
assert new in selenium.current_url, 'Language is not in URL'
assert new == page.footer.language, 'Language has not been selected'
Exclude redirected locales from homepage language selector functional tests# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(base_url, selenium):
page = HomePage(base_url, selenium).open()
initial = page.footer.language
# avoid selecting the same language or locales that have homepage redirects
excluded = [initial, 'ja', 'zh-TW', 'zh-CN']
available = [l for l in page.footer.languages if l not in excluded]
new = random.choice(available)
page.footer.select_language(new)
assert new in selenium.current_url, 'Language is not in URL'
assert new == page.footer.language, 'Language has not been selected'
| <commit_before># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(base_url, selenium):
page = HomePage(base_url, selenium).open()
initial = page.footer.language
available = page.footer.languages
available.remove(initial) # avoid selecting the same language
new = random.choice(available) # pick a random lanugage
page.footer.select_language(new)
assert new in selenium.current_url, 'Language is not in URL'
assert new == page.footer.language, 'Language has not been selected'
<commit_msg>Exclude redirected locales from homepage language selector functional tests<commit_after># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(base_url, selenium):
page = HomePage(base_url, selenium).open()
initial = page.footer.language
# avoid selecting the same language or locales that have homepage redirects
excluded = [initial, 'ja', 'zh-TW', 'zh-CN']
available = [l for l in page.footer.languages if l not in excluded]
new = random.choice(available)
page.footer.select_language(new)
assert new in selenium.current_url, 'Language is not in URL'
assert new == page.footer.language, 'Language has not been selected'
|
6daa585138413b38e04cae940d973bb9e13aa387 | registration/__init__.py | registration/__init__.py | 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
| VERSION = (1, 0, 0, 'final', 0)
def get_version():
"Returns a PEP 386-compliant version number from VERSION."
assert len(VERSION) == 5
assert VERSION[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|c}N - for alpha, beta and rc releases
parts = 2 if VERSION[2] == 0 else 3
main = '.'.join(str(x) for x in VERSION[:parts])
sub = ''
if VERSION[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[VERSION[3]] + str(VERSION[4])
return str(main + sub)
| Fix version number reporting so we can be installed before Django. | Fix version number reporting so we can be installed before Django.
| Python | bsd-3-clause | stillmatic/django-registration,matejkloska/django-registration,yorkedork/django-registration,wda-hb/test,alawnchen/django-registration,PSU-OIT-ARC/django-registration,memnonila/django-registration,kazitanvirahsan/django-registration,allo-/django-registration,PetrDlouhy/django-registration,Geffersonvivan/django-registration,furious-luke/django-registration,arpitremarkable/django-registration,matejkloska/django-registration,memnonila/django-registration,erinspace/django-registration,nikolas/django-registration,pando85/django-registration,PetrDlouhy/django-registration,yorkedork/django-registration,alawnchen/django-registration,imgmix/django-registration,stillmatic/django-registration,ei-grad/django-registration,Geffersonvivan/django-registration,maitho/django-registration,rulz/django-registration,tanjunyen/django-registration,timgraham/django-registration,kinsights/django-registration,PSU-OIT-ARC/django-registration,wy123123/django-registration,erinspace/django-registration,arpitremarkable/django-registration,sergafts/django-registration,kazitanvirahsan/django-registration,maitho/django-registration,torchingloom/django-registration,mick-t/django-registration,sergafts/django-registration,furious-luke/django-registration,pando85/django-registration,wy123123/django-registration,timgraham/django-registration,percipient/django-registration,percipient/django-registration,imgmix/django-registration,nikolas/django-registration,mick-t/django-registration,ei-grad/django-registration,kinsights/django-registration,tanjunyen/django-registration,wda-hb/test,rulz/django-registration,torchingloom/django-registration,allo-/django-registration | 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
Fix version number reporting so we can be installed before Django. | VERSION = (1, 0, 0, 'final', 0)
def get_version():
"Returns a PEP 386-compliant version number from VERSION."
assert len(VERSION) == 5
assert VERSION[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|c}N - for alpha, beta and rc releases
parts = 2 if VERSION[2] == 0 else 3
main = '.'.join(str(x) for x in VERSION[:parts])
sub = ''
if VERSION[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[VERSION[3]] + str(VERSION[4])
return str(main + sub)
| <commit_before>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_msg>Fix version number reporting so we can be installed before Django.<commit_after> | VERSION = (1, 0, 0, 'final', 0)
def get_version():
"Returns a PEP 386-compliant version number from VERSION."
assert len(VERSION) == 5
assert VERSION[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|c}N - for alpha, beta and rc releases
parts = 2 if VERSION[2] == 0 else 3
main = '.'.join(str(x) for x in VERSION[:parts])
sub = ''
if VERSION[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[VERSION[3]] + str(VERSION[4])
return str(main + sub)
| 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
Fix version number reporting so we can be installed before Django.VERSION = (1, 0, 0, 'final', 0)
def get_version():
"Returns a PEP 386-compliant version number from VERSION."
assert len(VERSION) == 5
assert VERSION[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|c}N - for alpha, beta and rc releases
parts = 2 if VERSION[2] == 0 else 3
main = '.'.join(str(x) for x in VERSION[:parts])
sub = ''
if VERSION[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[VERSION[3]] + str(VERSION[4])
return str(main + sub)
| <commit_before>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_msg>Fix version number reporting so we can be installed before Django.<commit_after>VERSION = (1, 0, 0, 'final', 0)
def get_version():
"Returns a PEP 386-compliant version number from VERSION."
assert len(VERSION) == 5
assert VERSION[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|c}N - for alpha, beta and rc releases
parts = 2 if VERSION[2] == 0 else 3
main = '.'.join(str(x) for x in VERSION[:parts])
sub = ''
if VERSION[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[VERSION[3]] + str(VERSION[4])
return str(main + sub)
|
b73691f2c9f10f44ecd87fe9a6a18bb14a570e6d | modules/admin.py | modules/admin.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Blueprint, render_template
import subprocess
import tempfile
import os
admin_controller = Blueprint('admin_controller', 'admin_controller',
template_folder='templates')
@admin_controller.route('/admin/exportlanguages')
def exportlanguages():
tempfilename = tempfile.TemporaryFile()
subprocess.Popen(['mongoexport', '-d', 'pastedirectory', '-c', 'languages', '-o', tempfilename])
with open (tempfilename, "r") as myfile:
return myfile.read()
| #!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Blueprint, render_template
import subprocess
import tempfile
import os
admin_controller = Blueprint('admin_controller', 'admin_controller',
template_folder='templates')
@admin_controller.route('/admin/exportlanguages')
def exportlanguages():
tempfilename = tempfile.TemporaryFile()
subprocess.Popen(['mongoexport', '-d', 'pastedirectory', '-c', 'languages_unstable', '-o', tempfilename])
with open (tempfilename, "r") as myfile:
return myfile.read()
| Use a secondary language database for development | Use a secondary language database for development
| Python | bsd-3-clause | xlexi/pastedirectory,xlexi/pastedirectory,xlexi/pastedirectory,xlexi/pastedirectory | #!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Blueprint, render_template
import subprocess
import tempfile
import os
admin_controller = Blueprint('admin_controller', 'admin_controller',
template_folder='templates')
@admin_controller.route('/admin/exportlanguages')
def exportlanguages():
tempfilename = tempfile.TemporaryFile()
subprocess.Popen(['mongoexport', '-d', 'pastedirectory', '-c', 'languages', '-o', tempfilename])
with open (tempfilename, "r") as myfile:
return myfile.read()
Use a secondary language database for development | #!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Blueprint, render_template
import subprocess
import tempfile
import os
admin_controller = Blueprint('admin_controller', 'admin_controller',
template_folder='templates')
@admin_controller.route('/admin/exportlanguages')
def exportlanguages():
tempfilename = tempfile.TemporaryFile()
subprocess.Popen(['mongoexport', '-d', 'pastedirectory', '-c', 'languages_unstable', '-o', tempfilename])
with open (tempfilename, "r") as myfile:
return myfile.read()
| <commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Blueprint, render_template
import subprocess
import tempfile
import os
admin_controller = Blueprint('admin_controller', 'admin_controller',
template_folder='templates')
@admin_controller.route('/admin/exportlanguages')
def exportlanguages():
tempfilename = tempfile.TemporaryFile()
subprocess.Popen(['mongoexport', '-d', 'pastedirectory', '-c', 'languages', '-o', tempfilename])
with open (tempfilename, "r") as myfile:
return myfile.read()
<commit_msg>Use a secondary language database for development<commit_after> | #!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Blueprint, render_template
import subprocess
import tempfile
import os
admin_controller = Blueprint('admin_controller', 'admin_controller',
template_folder='templates')
@admin_controller.route('/admin/exportlanguages')
def exportlanguages():
tempfilename = tempfile.TemporaryFile()
subprocess.Popen(['mongoexport', '-d', 'pastedirectory', '-c', 'languages_unstable', '-o', tempfilename])
with open (tempfilename, "r") as myfile:
return myfile.read()
| #!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Blueprint, render_template
import subprocess
import tempfile
import os
admin_controller = Blueprint('admin_controller', 'admin_controller',
template_folder='templates')
@admin_controller.route('/admin/exportlanguages')
def exportlanguages():
tempfilename = tempfile.TemporaryFile()
subprocess.Popen(['mongoexport', '-d', 'pastedirectory', '-c', 'languages', '-o', tempfilename])
with open (tempfilename, "r") as myfile:
return myfile.read()
Use a secondary language database for development#!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Blueprint, render_template
import subprocess
import tempfile
import os
admin_controller = Blueprint('admin_controller', 'admin_controller',
template_folder='templates')
@admin_controller.route('/admin/exportlanguages')
def exportlanguages():
tempfilename = tempfile.TemporaryFile()
subprocess.Popen(['mongoexport', '-d', 'pastedirectory', '-c', 'languages_unstable', '-o', tempfilename])
with open (tempfilename, "r") as myfile:
return myfile.read()
| <commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Blueprint, render_template
import subprocess
import tempfile
import os
admin_controller = Blueprint('admin_controller', 'admin_controller',
template_folder='templates')
@admin_controller.route('/admin/exportlanguages')
def exportlanguages():
tempfilename = tempfile.TemporaryFile()
subprocess.Popen(['mongoexport', '-d', 'pastedirectory', '-c', 'languages', '-o', tempfilename])
with open (tempfilename, "r") as myfile:
return myfile.read()
<commit_msg>Use a secondary language database for development<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Blueprint, render_template
import subprocess
import tempfile
import os
admin_controller = Blueprint('admin_controller', 'admin_controller',
template_folder='templates')
@admin_controller.route('/admin/exportlanguages')
def exportlanguages():
tempfilename = tempfile.TemporaryFile()
subprocess.Popen(['mongoexport', '-d', 'pastedirectory', '-c', 'languages_unstable', '-o', tempfilename])
with open (tempfilename, "r") as myfile:
return myfile.read()
|
a2444bd563b2e8e5b774e2f229583532f4d454ed | myhdl/_compat.py | myhdl/_compat.py | import sys
import types
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
| from __future__ import print_function
from __future__ import division
import sys
import types
from ast import PyCF_ONLY_AST
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
def ast_parse(s):
return compile(s, '<string>', 'exec', \
print_function.compiler_flag|division.compiler_flag|PyCF_ONLY_AST)
| Create a compatible ast.parse with PY3 | Create a compatible ast.parse with PY3
Created a function compatible with both PY2 and PY3 equivalent to
ast.parse.
| Python | lgpl-2.1 | jmgc/myhdl-numeric,jmgc/myhdl-numeric,jmgc/myhdl-numeric | import sys
import types
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
Create a compatible ast.parse with PY3
Created a function compatible with both PY2 and PY3 equivalent to
ast.parse. | from __future__ import print_function
from __future__ import division
import sys
import types
from ast import PyCF_ONLY_AST
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
def ast_parse(s):
return compile(s, '<string>', 'exec', \
print_function.compiler_flag|division.compiler_flag|PyCF_ONLY_AST)
| <commit_before>import sys
import types
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
<commit_msg>Create a compatible ast.parse with PY3
Created a function compatible with both PY2 and PY3 equivalent to
ast.parse.<commit_after> | from __future__ import print_function
from __future__ import division
import sys
import types
from ast import PyCF_ONLY_AST
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
def ast_parse(s):
return compile(s, '<string>', 'exec', \
print_function.compiler_flag|division.compiler_flag|PyCF_ONLY_AST)
| import sys
import types
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
Create a compatible ast.parse with PY3
Created a function compatible with both PY2 and PY3 equivalent to
ast.parse.from __future__ import print_function
from __future__ import division
import sys
import types
from ast import PyCF_ONLY_AST
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
def ast_parse(s):
return compile(s, '<string>', 'exec', \
print_function.compiler_flag|division.compiler_flag|PyCF_ONLY_AST)
| <commit_before>import sys
import types
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
<commit_msg>Create a compatible ast.parse with PY3
Created a function compatible with both PY2 and PY3 equivalent to
ast.parse.<commit_after>from __future__ import print_function
from __future__ import division
import sys
import types
from ast import PyCF_ONLY_AST
PY2 = sys.version_info[0] == 2
PYPY = hasattr(sys, 'pypy_translation_info')
_identity = lambda x: x
if not PY2:
string_types = (str,)
integer_types = (int,)
long = int
class_types = (type,)
from io import StringIO
import builtins
def to_bytes(s):
return s.encode()
def to_str(b):
return b.decode()
else:
string_types = (str, unicode)
integer_types = (int, long)
long = long
class_types = (type, types.ClassType)
from cStringIO import StringIO
import __builtin__ as builtins
to_bytes = _identity
to_str = _identity
def ast_parse(s):
return compile(s, '<string>', 'exec', \
print_function.compiler_flag|division.compiler_flag|PyCF_ONLY_AST)
|
c5e2b375cc722f717c2b159451b8ca1e45060e83 | models.py | models.py | from django.db import models
from django.conf import settings
import urllib, urllib2
C2DM_URL = 'https://android.apis.google.com/c2dm/send'
class C2DMProfile(models.Model):
deviceId = models.CharField(max_length = 64)
registrationId = models.CharField(max_length = 140)
collapseKey = models.CharField(max_length = 50)
def send_message(self, **kwargs):
values = {
'registration_id': self.registrationId,
'collapse_key': self.collapseKey,
}
for key,value in kwargs.items():
values['data.%s' % key] = value
headers = {
'Authorization': 'GoogleLogin auth=%s' % settings.AUTH_TOKEN,
}
try:
params = urllib.urlencode(values)
request = urllib2.Request(C2DM_URL, params, headers)
# Make the request
response = urllib2.urlopen(request)
except Exception, error:
print error
def __unicode__(self):
return '%s' % self.deviceId
| from django.db import models
from django.conf import settings
import urllib, urllib2
C2DM_URL = 'https://android.apis.google.com/c2dm/send'
class C2DMProfile(models.Model):
'''
Profile of a c2dm-enabled Android device
device_id - Unique ID for the device. Simply used as a default method to specify a device.
registration_id - Result of calling registration intent on the device. Subject to change.
collapse_key - Required arbitrary collapse_key string.
last_messaged - When did we last send a push to the device
failed_push - Have we had a failure when pushing to this device? Flag it here.
'''
device_id = models.CharField(max_length = 64)
registration_id = models.CharField(max_length = 140)
collapse_key = models.CharField(max_length = 50)
last_messaged = models.DateTimeField(blank = True, default = datetime.datetime.now)
failed_push = models.BooleanField(default = False)
def send_message(self, **kwargs):
'''
Sends a message to the device.
data.keyX fields are populated via kwargs.
'''
values = {
'registration_id': self.registration_id,
'collapse_key': self.collapse_key,
}
for key,value in kwargs.items():
values['data.%s' % key] = value
headers = {
'Authorization': 'GoogleLogin auth=%s' % settings.AUTH_TOKEN,
}
try:
params = urllib.urlencode(values)
request = urllib2.Request(C2DM_URL, params, headers)
# Make the request
response = urllib2.urlopen(request)
except Exception, error:
print error
def __unicode__(self):
return '%s' % self.deviceId
def send_multiple_messages(self, device_list, **kwargs):
'''
Same as send_message but sends to a list of devices.
data.keyX fields are populated via kwargs.
'''
for device in device_list:
device.send_message(kwargs)
| Add documentation and utility functions | Add documentation and utility functions
| Python | bsd-3-clause | scottferg/django-c2dm | from django.db import models
from django.conf import settings
import urllib, urllib2
C2DM_URL = 'https://android.apis.google.com/c2dm/send'
class C2DMProfile(models.Model):
deviceId = models.CharField(max_length = 64)
registrationId = models.CharField(max_length = 140)
collapseKey = models.CharField(max_length = 50)
def send_message(self, **kwargs):
values = {
'registration_id': self.registrationId,
'collapse_key': self.collapseKey,
}
for key,value in kwargs.items():
values['data.%s' % key] = value
headers = {
'Authorization': 'GoogleLogin auth=%s' % settings.AUTH_TOKEN,
}
try:
params = urllib.urlencode(values)
request = urllib2.Request(C2DM_URL, params, headers)
# Make the request
response = urllib2.urlopen(request)
except Exception, error:
print error
def __unicode__(self):
return '%s' % self.deviceId
Add documentation and utility functions | from django.db import models
from django.conf import settings
import urllib, urllib2
C2DM_URL = 'https://android.apis.google.com/c2dm/send'
class C2DMProfile(models.Model):
'''
Profile of a c2dm-enabled Android device
device_id - Unique ID for the device. Simply used as a default method to specify a device.
registration_id - Result of calling registration intent on the device. Subject to change.
collapse_key - Required arbitrary collapse_key string.
last_messaged - When did we last send a push to the device
failed_push - Have we had a failure when pushing to this device? Flag it here.
'''
device_id = models.CharField(max_length = 64)
registration_id = models.CharField(max_length = 140)
collapse_key = models.CharField(max_length = 50)
last_messaged = models.DateTimeField(blank = True, default = datetime.datetime.now)
failed_push = models.BooleanField(default = False)
def send_message(self, **kwargs):
'''
Sends a message to the device.
data.keyX fields are populated via kwargs.
'''
values = {
'registration_id': self.registration_id,
'collapse_key': self.collapse_key,
}
for key,value in kwargs.items():
values['data.%s' % key] = value
headers = {
'Authorization': 'GoogleLogin auth=%s' % settings.AUTH_TOKEN,
}
try:
params = urllib.urlencode(values)
request = urllib2.Request(C2DM_URL, params, headers)
# Make the request
response = urllib2.urlopen(request)
except Exception, error:
print error
def __unicode__(self):
return '%s' % self.deviceId
def send_multiple_messages(self, device_list, **kwargs):
'''
Same as send_message but sends to a list of devices.
data.keyX fields are populated via kwargs.
'''
for device in device_list:
device.send_message(kwargs)
| <commit_before>from django.db import models
from django.conf import settings
import urllib, urllib2
C2DM_URL = 'https://android.apis.google.com/c2dm/send'
class C2DMProfile(models.Model):
deviceId = models.CharField(max_length = 64)
registrationId = models.CharField(max_length = 140)
collapseKey = models.CharField(max_length = 50)
def send_message(self, **kwargs):
values = {
'registration_id': self.registrationId,
'collapse_key': self.collapseKey,
}
for key,value in kwargs.items():
values['data.%s' % key] = value
headers = {
'Authorization': 'GoogleLogin auth=%s' % settings.AUTH_TOKEN,
}
try:
params = urllib.urlencode(values)
request = urllib2.Request(C2DM_URL, params, headers)
# Make the request
response = urllib2.urlopen(request)
except Exception, error:
print error
def __unicode__(self):
return '%s' % self.deviceId
<commit_msg>Add documentation and utility functions<commit_after> | from django.db import models
from django.conf import settings
import urllib, urllib2
C2DM_URL = 'https://android.apis.google.com/c2dm/send'
class C2DMProfile(models.Model):
'''
Profile of a c2dm-enabled Android device
device_id - Unique ID for the device. Simply used as a default method to specify a device.
registration_id - Result of calling registration intent on the device. Subject to change.
collapse_key - Required arbitrary collapse_key string.
last_messaged - When did we last send a push to the device
failed_push - Have we had a failure when pushing to this device? Flag it here.
'''
device_id = models.CharField(max_length = 64)
registration_id = models.CharField(max_length = 140)
collapse_key = models.CharField(max_length = 50)
last_messaged = models.DateTimeField(blank = True, default = datetime.datetime.now)
failed_push = models.BooleanField(default = False)
def send_message(self, **kwargs):
'''
Sends a message to the device.
data.keyX fields are populated via kwargs.
'''
values = {
'registration_id': self.registration_id,
'collapse_key': self.collapse_key,
}
for key,value in kwargs.items():
values['data.%s' % key] = value
headers = {
'Authorization': 'GoogleLogin auth=%s' % settings.AUTH_TOKEN,
}
try:
params = urllib.urlencode(values)
request = urllib2.Request(C2DM_URL, params, headers)
# Make the request
response = urllib2.urlopen(request)
except Exception, error:
print error
def __unicode__(self):
return '%s' % self.deviceId
def send_multiple_messages(self, device_list, **kwargs):
'''
Same as send_message but sends to a list of devices.
data.keyX fields are populated via kwargs.
'''
for device in device_list:
device.send_message(kwargs)
| from django.db import models
from django.conf import settings
import urllib, urllib2
C2DM_URL = 'https://android.apis.google.com/c2dm/send'
class C2DMProfile(models.Model):
deviceId = models.CharField(max_length = 64)
registrationId = models.CharField(max_length = 140)
collapseKey = models.CharField(max_length = 50)
def send_message(self, **kwargs):
values = {
'registration_id': self.registrationId,
'collapse_key': self.collapseKey,
}
for key,value in kwargs.items():
values['data.%s' % key] = value
headers = {
'Authorization': 'GoogleLogin auth=%s' % settings.AUTH_TOKEN,
}
try:
params = urllib.urlencode(values)
request = urllib2.Request(C2DM_URL, params, headers)
# Make the request
response = urllib2.urlopen(request)
except Exception, error:
print error
def __unicode__(self):
return '%s' % self.deviceId
Add documentation and utility functionsfrom django.db import models
from django.conf import settings
import urllib, urllib2
C2DM_URL = 'https://android.apis.google.com/c2dm/send'
class C2DMProfile(models.Model):
'''
Profile of a c2dm-enabled Android device
device_id - Unique ID for the device. Simply used as a default method to specify a device.
registration_id - Result of calling registration intent on the device. Subject to change.
collapse_key - Required arbitrary collapse_key string.
last_messaged - When did we last send a push to the device
failed_push - Have we had a failure when pushing to this device? Flag it here.
'''
device_id = models.CharField(max_length = 64)
registration_id = models.CharField(max_length = 140)
collapse_key = models.CharField(max_length = 50)
last_messaged = models.DateTimeField(blank = True, default = datetime.datetime.now)
failed_push = models.BooleanField(default = False)
def send_message(self, **kwargs):
'''
Sends a message to the device.
data.keyX fields are populated via kwargs.
'''
values = {
'registration_id': self.registration_id,
'collapse_key': self.collapse_key,
}
for key,value in kwargs.items():
values['data.%s' % key] = value
headers = {
'Authorization': 'GoogleLogin auth=%s' % settings.AUTH_TOKEN,
}
try:
params = urllib.urlencode(values)
request = urllib2.Request(C2DM_URL, params, headers)
# Make the request
response = urllib2.urlopen(request)
except Exception, error:
print error
def __unicode__(self):
return '%s' % self.deviceId
def send_multiple_messages(self, device_list, **kwargs):
'''
Same as send_message but sends to a list of devices.
data.keyX fields are populated via kwargs.
'''
for device in device_list:
device.send_message(kwargs)
| <commit_before>from django.db import models
from django.conf import settings
import urllib, urllib2
C2DM_URL = 'https://android.apis.google.com/c2dm/send'
class C2DMProfile(models.Model):
deviceId = models.CharField(max_length = 64)
registrationId = models.CharField(max_length = 140)
collapseKey = models.CharField(max_length = 50)
def send_message(self, **kwargs):
values = {
'registration_id': self.registrationId,
'collapse_key': self.collapseKey,
}
for key,value in kwargs.items():
values['data.%s' % key] = value
headers = {
'Authorization': 'GoogleLogin auth=%s' % settings.AUTH_TOKEN,
}
try:
params = urllib.urlencode(values)
request = urllib2.Request(C2DM_URL, params, headers)
# Make the request
response = urllib2.urlopen(request)
except Exception, error:
print error
def __unicode__(self):
return '%s' % self.deviceId
<commit_msg>Add documentation and utility functions<commit_after>from django.db import models
from django.conf import settings
import urllib, urllib2
C2DM_URL = 'https://android.apis.google.com/c2dm/send'
class C2DMProfile(models.Model):
'''
Profile of a c2dm-enabled Android device
device_id - Unique ID for the device. Simply used as a default method to specify a device.
registration_id - Result of calling registration intent on the device. Subject to change.
collapse_key - Required arbitrary collapse_key string.
last_messaged - When did we last send a push to the device
failed_push - Have we had a failure when pushing to this device? Flag it here.
'''
device_id = models.CharField(max_length = 64)
registration_id = models.CharField(max_length = 140)
collapse_key = models.CharField(max_length = 50)
last_messaged = models.DateTimeField(blank = True, default = datetime.datetime.now)
failed_push = models.BooleanField(default = False)
def send_message(self, **kwargs):
'''
Sends a message to the device.
data.keyX fields are populated via kwargs.
'''
values = {
'registration_id': self.registration_id,
'collapse_key': self.collapse_key,
}
for key,value in kwargs.items():
values['data.%s' % key] = value
headers = {
'Authorization': 'GoogleLogin auth=%s' % settings.AUTH_TOKEN,
}
try:
params = urllib.urlencode(values)
request = urllib2.Request(C2DM_URL, params, headers)
# Make the request
response = urllib2.urlopen(request)
except Exception, error:
print error
def __unicode__(self):
return '%s' % self.deviceId
def send_multiple_messages(self, device_list, **kwargs):
'''
Same as send_message but sends to a list of devices.
data.keyX fields are populated via kwargs.
'''
for device in device_list:
device.send_message(kwargs)
|
d042f4ced40d8d03bd65edf798a29058f26e98c6 | test/test_wsstat.py | test/test_wsstat.py | import hashlib
from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection
class Tests(object):
def setup(self):
self.client = WebsocketTestingClient('wss://testserver/', total_connections=1, max_connecting_sockets=1)
def teardown(self):
pass
class TestConnectedWebsocketConnection:
def setup(self):
self.token = hashlib.sha256(b'derp').hexdigest()
self.socket = ConnectedWebsocketConnection(None, self.token)
def test_message_increment(self):
assert self.socket.message_count == 0
self.socket.increment_message_counter()
assert self.socket.message_count == 1
self.socket.increment_message_counter()
assert self.socket.message_count == 2
def test_socket_as_string(self):
assert str(self.socket) == "<Websocket {}>".format(self.socket.id)
| import hashlib
from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection
class Tests(object):
def setup(self):
self.client = WebsocketTestingClient('wss://testserver/', total_connections=3, max_connecting_sockets=3)
def test_coroutines(self):
print(self.client)
assert len(self.client.tasks._children) == (1 + self.client.total_connections)
class TestConnectedWebsocketConnection:
def setup(self):
self.token = hashlib.sha256(b'derp').hexdigest()
self.socket = ConnectedWebsocketConnection(None, self.token)
def test_message_increment(self):
assert self.socket.message_count == 0
self.socket.increment_message_counter()
assert self.socket.message_count == 1
self.socket.increment_message_counter()
assert self.socket.message_count == 2
def test_socket_as_string(self):
assert str(self.socket) == "<Websocket {}>".format(self.socket.id)
| Add a test for running tasks | Add a test for running tasks
| Python | mit | Fitblip/wsstat | import hashlib
from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection
class Tests(object):
def setup(self):
self.client = WebsocketTestingClient('wss://testserver/', total_connections=1, max_connecting_sockets=1)
def teardown(self):
pass
class TestConnectedWebsocketConnection:
def setup(self):
self.token = hashlib.sha256(b'derp').hexdigest()
self.socket = ConnectedWebsocketConnection(None, self.token)
def test_message_increment(self):
assert self.socket.message_count == 0
self.socket.increment_message_counter()
assert self.socket.message_count == 1
self.socket.increment_message_counter()
assert self.socket.message_count == 2
def test_socket_as_string(self):
assert str(self.socket) == "<Websocket {}>".format(self.socket.id)
Add a test for running tasks | import hashlib
from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection
class Tests(object):
def setup(self):
self.client = WebsocketTestingClient('wss://testserver/', total_connections=3, max_connecting_sockets=3)
def test_coroutines(self):
print(self.client)
assert len(self.client.tasks._children) == (1 + self.client.total_connections)
class TestConnectedWebsocketConnection:
def setup(self):
self.token = hashlib.sha256(b'derp').hexdigest()
self.socket = ConnectedWebsocketConnection(None, self.token)
def test_message_increment(self):
assert self.socket.message_count == 0
self.socket.increment_message_counter()
assert self.socket.message_count == 1
self.socket.increment_message_counter()
assert self.socket.message_count == 2
def test_socket_as_string(self):
assert str(self.socket) == "<Websocket {}>".format(self.socket.id)
| <commit_before>import hashlib
from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection
class Tests(object):
def setup(self):
self.client = WebsocketTestingClient('wss://testserver/', total_connections=1, max_connecting_sockets=1)
def teardown(self):
pass
class TestConnectedWebsocketConnection:
def setup(self):
self.token = hashlib.sha256(b'derp').hexdigest()
self.socket = ConnectedWebsocketConnection(None, self.token)
def test_message_increment(self):
assert self.socket.message_count == 0
self.socket.increment_message_counter()
assert self.socket.message_count == 1
self.socket.increment_message_counter()
assert self.socket.message_count == 2
def test_socket_as_string(self):
assert str(self.socket) == "<Websocket {}>".format(self.socket.id)
<commit_msg>Add a test for running tasks<commit_after> | import hashlib
from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection
class Tests(object):
def setup(self):
self.client = WebsocketTestingClient('wss://testserver/', total_connections=3, max_connecting_sockets=3)
def test_coroutines(self):
print(self.client)
assert len(self.client.tasks._children) == (1 + self.client.total_connections)
class TestConnectedWebsocketConnection:
def setup(self):
self.token = hashlib.sha256(b'derp').hexdigest()
self.socket = ConnectedWebsocketConnection(None, self.token)
def test_message_increment(self):
assert self.socket.message_count == 0
self.socket.increment_message_counter()
assert self.socket.message_count == 1
self.socket.increment_message_counter()
assert self.socket.message_count == 2
def test_socket_as_string(self):
assert str(self.socket) == "<Websocket {}>".format(self.socket.id)
| import hashlib
from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection
class Tests(object):
def setup(self):
self.client = WebsocketTestingClient('wss://testserver/', total_connections=1, max_connecting_sockets=1)
def teardown(self):
pass
class TestConnectedWebsocketConnection:
def setup(self):
self.token = hashlib.sha256(b'derp').hexdigest()
self.socket = ConnectedWebsocketConnection(None, self.token)
def test_message_increment(self):
assert self.socket.message_count == 0
self.socket.increment_message_counter()
assert self.socket.message_count == 1
self.socket.increment_message_counter()
assert self.socket.message_count == 2
def test_socket_as_string(self):
assert str(self.socket) == "<Websocket {}>".format(self.socket.id)
Add a test for running tasksimport hashlib
from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection
class Tests(object):
def setup(self):
self.client = WebsocketTestingClient('wss://testserver/', total_connections=3, max_connecting_sockets=3)
def test_coroutines(self):
print(self.client)
assert len(self.client.tasks._children) == (1 + self.client.total_connections)
class TestConnectedWebsocketConnection:
def setup(self):
self.token = hashlib.sha256(b'derp').hexdigest()
self.socket = ConnectedWebsocketConnection(None, self.token)
def test_message_increment(self):
assert self.socket.message_count == 0
self.socket.increment_message_counter()
assert self.socket.message_count == 1
self.socket.increment_message_counter()
assert self.socket.message_count == 2
def test_socket_as_string(self):
assert str(self.socket) == "<Websocket {}>".format(self.socket.id)
| <commit_before>import hashlib
from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection
class Tests(object):
def setup(self):
self.client = WebsocketTestingClient('wss://testserver/', total_connections=1, max_connecting_sockets=1)
def teardown(self):
pass
class TestConnectedWebsocketConnection:
def setup(self):
self.token = hashlib.sha256(b'derp').hexdigest()
self.socket = ConnectedWebsocketConnection(None, self.token)
def test_message_increment(self):
assert self.socket.message_count == 0
self.socket.increment_message_counter()
assert self.socket.message_count == 1
self.socket.increment_message_counter()
assert self.socket.message_count == 2
def test_socket_as_string(self):
assert str(self.socket) == "<Websocket {}>".format(self.socket.id)
<commit_msg>Add a test for running tasks<commit_after>import hashlib
from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection
class Tests(object):
def setup(self):
self.client = WebsocketTestingClient('wss://testserver/', total_connections=3, max_connecting_sockets=3)
def test_coroutines(self):
print(self.client)
assert len(self.client.tasks._children) == (1 + self.client.total_connections)
class TestConnectedWebsocketConnection:
def setup(self):
self.token = hashlib.sha256(b'derp').hexdigest()
self.socket = ConnectedWebsocketConnection(None, self.token)
def test_message_increment(self):
assert self.socket.message_count == 0
self.socket.increment_message_counter()
assert self.socket.message_count == 1
self.socket.increment_message_counter()
assert self.socket.message_count == 2
def test_socket_as_string(self):
assert str(self.socket) == "<Websocket {}>".format(self.socket.id)
|
c9f2ecea38711db75235aca2879f9a0b14762c9f | tests/test_spell.py | tests/test_spell.py | # -*- coding: utf-8 -*-
import datetime
import os
import sys
import unittest
from pythainlp.spell import NorvigSpellChecker, correct, spell
class TestSpellPackage(unittest.TestCase):
def test_spell(self):
self.assertEqual(spell(None), [""])
self.assertEqual(spell(""), [""])
result = spell("เน้ร")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
result = spell("เกสมร์")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
def test_word_correct(self):
self.assertEqual(correct(None), "")
self.assertEqual(correct(""), "")
result = correct("ทดสอง")
self.assertIsInstance(result, str)
self.assertNotEqual(result, "")
def test_norvig_spell_checker(self):
checker = NorvigSpellChecker(dict_filter=None)
self.assertTrue(len(checker.dictionary()) > 0)
self.assertGreaterEqual(checker.prob("มี"), 0)
| # -*- coding: utf-8 -*-
import datetime
import os
import sys
import unittest
from pythainlp.spell import NorvigSpellChecker, correct, spell
class TestSpellPackage(unittest.TestCase):
def test_spell(self):
self.assertEqual(spell(None), [""])
self.assertEqual(spell(""), [""])
result = spell("เน้ร")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
result = spell("เกสมร์")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
def test_word_correct(self):
self.assertEqual(correct(None), "")
self.assertEqual(correct(""), "")
self.assertEqual(correct("1"), "1")
self.assertEqual(correct("56"), "56")
self.assertEqual(correct("1.01"), "1.01")
result = correct("ทดสอง")
self.assertIsInstance(result, str)
self.assertNotEqual(result, "")
def test_norvig_spell_checker(self):
checker = NorvigSpellChecker(dict_filter=None)
self.assertTrue(len(checker.dictionary()) > 0)
self.assertGreaterEqual(checker.prob("มี"), 0)
| Add unittest for correct function in spell module | Add unittest for correct function in spell module
| Python | apache-2.0 | PyThaiNLP/pythainlp | # -*- coding: utf-8 -*-
import datetime
import os
import sys
import unittest
from pythainlp.spell import NorvigSpellChecker, correct, spell
class TestSpellPackage(unittest.TestCase):
def test_spell(self):
self.assertEqual(spell(None), [""])
self.assertEqual(spell(""), [""])
result = spell("เน้ร")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
result = spell("เกสมร์")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
def test_word_correct(self):
self.assertEqual(correct(None), "")
self.assertEqual(correct(""), "")
result = correct("ทดสอง")
self.assertIsInstance(result, str)
self.assertNotEqual(result, "")
def test_norvig_spell_checker(self):
checker = NorvigSpellChecker(dict_filter=None)
self.assertTrue(len(checker.dictionary()) > 0)
self.assertGreaterEqual(checker.prob("มี"), 0)
Add unittest for correct function in spell module | # -*- coding: utf-8 -*-
import datetime
import os
import sys
import unittest
from pythainlp.spell import NorvigSpellChecker, correct, spell
class TestSpellPackage(unittest.TestCase):
def test_spell(self):
self.assertEqual(spell(None), [""])
self.assertEqual(spell(""), [""])
result = spell("เน้ร")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
result = spell("เกสมร์")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
def test_word_correct(self):
self.assertEqual(correct(None), "")
self.assertEqual(correct(""), "")
self.assertEqual(correct("1"), "1")
self.assertEqual(correct("56"), "56")
self.assertEqual(correct("1.01"), "1.01")
result = correct("ทดสอง")
self.assertIsInstance(result, str)
self.assertNotEqual(result, "")
def test_norvig_spell_checker(self):
checker = NorvigSpellChecker(dict_filter=None)
self.assertTrue(len(checker.dictionary()) > 0)
self.assertGreaterEqual(checker.prob("มี"), 0)
| <commit_before># -*- coding: utf-8 -*-
import datetime
import os
import sys
import unittest
from pythainlp.spell import NorvigSpellChecker, correct, spell
class TestSpellPackage(unittest.TestCase):
def test_spell(self):
self.assertEqual(spell(None), [""])
self.assertEqual(spell(""), [""])
result = spell("เน้ร")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
result = spell("เกสมร์")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
def test_word_correct(self):
self.assertEqual(correct(None), "")
self.assertEqual(correct(""), "")
result = correct("ทดสอง")
self.assertIsInstance(result, str)
self.assertNotEqual(result, "")
def test_norvig_spell_checker(self):
checker = NorvigSpellChecker(dict_filter=None)
self.assertTrue(len(checker.dictionary()) > 0)
self.assertGreaterEqual(checker.prob("มี"), 0)
<commit_msg>Add unittest for correct function in spell module<commit_after> | # -*- coding: utf-8 -*-
import datetime
import os
import sys
import unittest
from pythainlp.spell import NorvigSpellChecker, correct, spell
class TestSpellPackage(unittest.TestCase):
def test_spell(self):
self.assertEqual(spell(None), [""])
self.assertEqual(spell(""), [""])
result = spell("เน้ร")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
result = spell("เกสมร์")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
def test_word_correct(self):
self.assertEqual(correct(None), "")
self.assertEqual(correct(""), "")
self.assertEqual(correct("1"), "1")
self.assertEqual(correct("56"), "56")
self.assertEqual(correct("1.01"), "1.01")
result = correct("ทดสอง")
self.assertIsInstance(result, str)
self.assertNotEqual(result, "")
def test_norvig_spell_checker(self):
checker = NorvigSpellChecker(dict_filter=None)
self.assertTrue(len(checker.dictionary()) > 0)
self.assertGreaterEqual(checker.prob("มี"), 0)
| # -*- coding: utf-8 -*-
import datetime
import os
import sys
import unittest
from pythainlp.spell import NorvigSpellChecker, correct, spell
class TestSpellPackage(unittest.TestCase):
def test_spell(self):
self.assertEqual(spell(None), [""])
self.assertEqual(spell(""), [""])
result = spell("เน้ร")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
result = spell("เกสมร์")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
def test_word_correct(self):
self.assertEqual(correct(None), "")
self.assertEqual(correct(""), "")
result = correct("ทดสอง")
self.assertIsInstance(result, str)
self.assertNotEqual(result, "")
def test_norvig_spell_checker(self):
checker = NorvigSpellChecker(dict_filter=None)
self.assertTrue(len(checker.dictionary()) > 0)
self.assertGreaterEqual(checker.prob("มี"), 0)
Add unittest for correct function in spell module# -*- coding: utf-8 -*-
import datetime
import os
import sys
import unittest
from pythainlp.spell import NorvigSpellChecker, correct, spell
class TestSpellPackage(unittest.TestCase):
def test_spell(self):
self.assertEqual(spell(None), [""])
self.assertEqual(spell(""), [""])
result = spell("เน้ร")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
result = spell("เกสมร์")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
def test_word_correct(self):
self.assertEqual(correct(None), "")
self.assertEqual(correct(""), "")
self.assertEqual(correct("1"), "1")
self.assertEqual(correct("56"), "56")
self.assertEqual(correct("1.01"), "1.01")
result = correct("ทดสอง")
self.assertIsInstance(result, str)
self.assertNotEqual(result, "")
def test_norvig_spell_checker(self):
checker = NorvigSpellChecker(dict_filter=None)
self.assertTrue(len(checker.dictionary()) > 0)
self.assertGreaterEqual(checker.prob("มี"), 0)
| <commit_before># -*- coding: utf-8 -*-
import datetime
import os
import sys
import unittest
from pythainlp.spell import NorvigSpellChecker, correct, spell
class TestSpellPackage(unittest.TestCase):
def test_spell(self):
self.assertEqual(spell(None), [""])
self.assertEqual(spell(""), [""])
result = spell("เน้ร")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
result = spell("เกสมร์")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
def test_word_correct(self):
self.assertEqual(correct(None), "")
self.assertEqual(correct(""), "")
result = correct("ทดสอง")
self.assertIsInstance(result, str)
self.assertNotEqual(result, "")
def test_norvig_spell_checker(self):
checker = NorvigSpellChecker(dict_filter=None)
self.assertTrue(len(checker.dictionary()) > 0)
self.assertGreaterEqual(checker.prob("มี"), 0)
<commit_msg>Add unittest for correct function in spell module<commit_after># -*- coding: utf-8 -*-
import datetime
import os
import sys
import unittest
from pythainlp.spell import NorvigSpellChecker, correct, spell
class TestSpellPackage(unittest.TestCase):
def test_spell(self):
self.assertEqual(spell(None), [""])
self.assertEqual(spell(""), [""])
result = spell("เน้ร")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
result = spell("เกสมร์")
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
def test_word_correct(self):
self.assertEqual(correct(None), "")
self.assertEqual(correct(""), "")
self.assertEqual(correct("1"), "1")
self.assertEqual(correct("56"), "56")
self.assertEqual(correct("1.01"), "1.01")
result = correct("ทดสอง")
self.assertIsInstance(result, str)
self.assertNotEqual(result, "")
def test_norvig_spell_checker(self):
checker = NorvigSpellChecker(dict_filter=None)
self.assertTrue(len(checker.dictionary()) > 0)
self.assertGreaterEqual(checker.prob("มี"), 0)
|
5984c55a555ef88068f33a28c45a449416ee2896 | src/models/invalidated_token.py | src/models/invalidated_token.py | from src.main import db
from sqlalchemy.sql import func
class InvalidatedToken(db.Model):
token = db.Column(db.String(120), primary_key=True)
invalidated_date = db.Column(db.DateTime(timezone = True), server_default = func.now())
def __init__(self, token):
self.token = token
def __repr__(self):
return '<InvalidatedToken %s, %s>' % self.token, str(self.invalidated_date)
def jsonify(self):
"""Return JSON representation of the object"""
return {
'token' : self.token,
'invalidated_date': str(self.invalidated_date)
}
| from src.main import db
from sqlalchemy.sql import func
class InvalidatedToken(db.Model):
token = db.Column(db.String(120), primary_key=True)
invalidated_date = db.Column(db.DateTime(timezone = True), server_default = func.now())
def __init__(self, token):
self.token = token
def __repr__(self):
return '<InvalidatedToken %s, %s>' % (self.token, str(self.invalidated_date))
def jsonify(self):
"""Return JSON representation of the object"""
return {
'token' : self.token,
'invalidated_date': str(self.invalidated_date)
}
| Fix for representation of InvalidatedToken model. | Fix for representation of InvalidatedToken model.
| Python | apache-2.0 | tomaszguzialek/flask-api,tomaszguzialek/flask-api,tomaszguzialek/flask-api | from src.main import db
from sqlalchemy.sql import func
class InvalidatedToken(db.Model):
token = db.Column(db.String(120), primary_key=True)
invalidated_date = db.Column(db.DateTime(timezone = True), server_default = func.now())
def __init__(self, token):
self.token = token
def __repr__(self):
return '<InvalidatedToken %s, %s>' % self.token, str(self.invalidated_date)
def jsonify(self):
"""Return JSON representation of the object"""
return {
'token' : self.token,
'invalidated_date': str(self.invalidated_date)
}
Fix for representation of InvalidatedToken model. | from src.main import db
from sqlalchemy.sql import func
class InvalidatedToken(db.Model):
token = db.Column(db.String(120), primary_key=True)
invalidated_date = db.Column(db.DateTime(timezone = True), server_default = func.now())
def __init__(self, token):
self.token = token
def __repr__(self):
return '<InvalidatedToken %s, %s>' % (self.token, str(self.invalidated_date))
def jsonify(self):
"""Return JSON representation of the object"""
return {
'token' : self.token,
'invalidated_date': str(self.invalidated_date)
}
| <commit_before>from src.main import db
from sqlalchemy.sql import func
class InvalidatedToken(db.Model):
token = db.Column(db.String(120), primary_key=True)
invalidated_date = db.Column(db.DateTime(timezone = True), server_default = func.now())
def __init__(self, token):
self.token = token
def __repr__(self):
return '<InvalidatedToken %s, %s>' % self.token, str(self.invalidated_date)
def jsonify(self):
"""Return JSON representation of the object"""
return {
'token' : self.token,
'invalidated_date': str(self.invalidated_date)
}
<commit_msg>Fix for representation of InvalidatedToken model.<commit_after> | from src.main import db
from sqlalchemy.sql import func
class InvalidatedToken(db.Model):
token = db.Column(db.String(120), primary_key=True)
invalidated_date = db.Column(db.DateTime(timezone = True), server_default = func.now())
def __init__(self, token):
self.token = token
def __repr__(self):
return '<InvalidatedToken %s, %s>' % (self.token, str(self.invalidated_date))
def jsonify(self):
"""Return JSON representation of the object"""
return {
'token' : self.token,
'invalidated_date': str(self.invalidated_date)
}
| from src.main import db
from sqlalchemy.sql import func
class InvalidatedToken(db.Model):
token = db.Column(db.String(120), primary_key=True)
invalidated_date = db.Column(db.DateTime(timezone = True), server_default = func.now())
def __init__(self, token):
self.token = token
def __repr__(self):
return '<InvalidatedToken %s, %s>' % self.token, str(self.invalidated_date)
def jsonify(self):
"""Return JSON representation of the object"""
return {
'token' : self.token,
'invalidated_date': str(self.invalidated_date)
}
Fix for representation of InvalidatedToken model.from src.main import db
from sqlalchemy.sql import func
class InvalidatedToken(db.Model):
token = db.Column(db.String(120), primary_key=True)
invalidated_date = db.Column(db.DateTime(timezone = True), server_default = func.now())
def __init__(self, token):
self.token = token
def __repr__(self):
return '<InvalidatedToken %s, %s>' % (self.token, str(self.invalidated_date))
def jsonify(self):
"""Return JSON representation of the object"""
return {
'token' : self.token,
'invalidated_date': str(self.invalidated_date)
}
| <commit_before>from src.main import db
from sqlalchemy.sql import func
class InvalidatedToken(db.Model):
token = db.Column(db.String(120), primary_key=True)
invalidated_date = db.Column(db.DateTime(timezone = True), server_default = func.now())
def __init__(self, token):
self.token = token
def __repr__(self):
return '<InvalidatedToken %s, %s>' % self.token, str(self.invalidated_date)
def jsonify(self):
"""Return JSON representation of the object"""
return {
'token' : self.token,
'invalidated_date': str(self.invalidated_date)
}
<commit_msg>Fix for representation of InvalidatedToken model.<commit_after>from src.main import db
from sqlalchemy.sql import func
class InvalidatedToken(db.Model):
token = db.Column(db.String(120), primary_key=True)
invalidated_date = db.Column(db.DateTime(timezone = True), server_default = func.now())
def __init__(self, token):
self.token = token
def __repr__(self):
return '<InvalidatedToken %s, %s>' % (self.token, str(self.invalidated_date))
def jsonify(self):
"""Return JSON representation of the object"""
return {
'token' : self.token,
'invalidated_date': str(self.invalidated_date)
}
|
b12ff9bbdea517a9ac70f9ea2f06c50e110da003 | pyramid/__init__.py | pyramid/__init__.py | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.6.1-dev0"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except NameError:
__PYRAMID_SETUP__ = False
if __PYRAMID_SETUP__:
import sys
import os
sys.stderr.write('Partial import of pyramid during the build process.' + os.linesep)
else:
# check that the build completed properly. This prints an informative
# message in the case that any of the C code was not properly compiled.
from . import __check_build
__all__ = [
'arima',
'compat',
'datasets',
'utils'
]
def setup_module(module):
import numpy as np
import random
_random_seed = int(np.random.uniform() * (2 ** 31 - 1))
np.random.seed(_random_seed)
random.seed(_random_seed)
| # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.6.2"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except NameError:
__PYRAMID_SETUP__ = False
if __PYRAMID_SETUP__:
import sys
import os
sys.stderr.write('Partial import of pyramid during the build process.' + os.linesep)
else:
# check that the build completed properly. This prints an informative
# message in the case that any of the C code was not properly compiled.
from . import __check_build
__all__ = [
'arima',
'compat',
'datasets',
'utils'
]
def setup_module(module):
import numpy as np
import random
_random_seed = int(np.random.uniform() * (2 ** 31 - 1))
np.random.seed(_random_seed)
random.seed(_random_seed)
| Increment minor version for :fire: HOTFIX release | Increment minor version for :fire: HOTFIX release
| Python | mit | alkaline-ml/pmdarima,tgsmith61591/pyramid,tgsmith61591/pyramid,tgsmith61591/pyramid,alkaline-ml/pmdarima,alkaline-ml/pmdarima | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.6.1-dev0"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except NameError:
__PYRAMID_SETUP__ = False
if __PYRAMID_SETUP__:
import sys
import os
sys.stderr.write('Partial import of pyramid during the build process.' + os.linesep)
else:
# check that the build completed properly. This prints an informative
# message in the case that any of the C code was not properly compiled.
from . import __check_build
__all__ = [
'arima',
'compat',
'datasets',
'utils'
]
def setup_module(module):
import numpy as np
import random
_random_seed = int(np.random.uniform() * (2 ** 31 - 1))
np.random.seed(_random_seed)
random.seed(_random_seed)
Increment minor version for :fire: HOTFIX release | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.6.2"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except NameError:
__PYRAMID_SETUP__ = False
if __PYRAMID_SETUP__:
import sys
import os
sys.stderr.write('Partial import of pyramid during the build process.' + os.linesep)
else:
# check that the build completed properly. This prints an informative
# message in the case that any of the C code was not properly compiled.
from . import __check_build
__all__ = [
'arima',
'compat',
'datasets',
'utils'
]
def setup_module(module):
import numpy as np
import random
_random_seed = int(np.random.uniform() * (2 ** 31 - 1))
np.random.seed(_random_seed)
random.seed(_random_seed)
| <commit_before># -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.6.1-dev0"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except NameError:
__PYRAMID_SETUP__ = False
if __PYRAMID_SETUP__:
import sys
import os
sys.stderr.write('Partial import of pyramid during the build process.' + os.linesep)
else:
# check that the build completed properly. This prints an informative
# message in the case that any of the C code was not properly compiled.
from . import __check_build
__all__ = [
'arima',
'compat',
'datasets',
'utils'
]
def setup_module(module):
import numpy as np
import random
_random_seed = int(np.random.uniform() * (2 ** 31 - 1))
np.random.seed(_random_seed)
random.seed(_random_seed)
<commit_msg>Increment minor version for :fire: HOTFIX release<commit_after> | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.6.2"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except NameError:
__PYRAMID_SETUP__ = False
if __PYRAMID_SETUP__:
import sys
import os
sys.stderr.write('Partial import of pyramid during the build process.' + os.linesep)
else:
# check that the build completed properly. This prints an informative
# message in the case that any of the C code was not properly compiled.
from . import __check_build
__all__ = [
'arima',
'compat',
'datasets',
'utils'
]
def setup_module(module):
import numpy as np
import random
_random_seed = int(np.random.uniform() * (2 ** 31 - 1))
np.random.seed(_random_seed)
random.seed(_random_seed)
| # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.6.1-dev0"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except NameError:
__PYRAMID_SETUP__ = False
if __PYRAMID_SETUP__:
import sys
import os
sys.stderr.write('Partial import of pyramid during the build process.' + os.linesep)
else:
# check that the build completed properly. This prints an informative
# message in the case that any of the C code was not properly compiled.
from . import __check_build
__all__ = [
'arima',
'compat',
'datasets',
'utils'
]
def setup_module(module):
import numpy as np
import random
_random_seed = int(np.random.uniform() * (2 ** 31 - 1))
np.random.seed(_random_seed)
random.seed(_random_seed)
Increment minor version for :fire: HOTFIX release# -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.6.2"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except NameError:
__PYRAMID_SETUP__ = False
if __PYRAMID_SETUP__:
import sys
import os
sys.stderr.write('Partial import of pyramid during the build process.' + os.linesep)
else:
# check that the build completed properly. This prints an informative
# message in the case that any of the C code was not properly compiled.
from . import __check_build
__all__ = [
'arima',
'compat',
'datasets',
'utils'
]
def setup_module(module):
import numpy as np
import random
_random_seed = int(np.random.uniform() * (2 ** 31 - 1))
np.random.seed(_random_seed)
random.seed(_random_seed)
| <commit_before># -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.6.1-dev0"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except NameError:
__PYRAMID_SETUP__ = False
if __PYRAMID_SETUP__:
import sys
import os
sys.stderr.write('Partial import of pyramid during the build process.' + os.linesep)
else:
# check that the build completed properly. This prints an informative
# message in the case that any of the C code was not properly compiled.
from . import __check_build
__all__ = [
'arima',
'compat',
'datasets',
'utils'
]
def setup_module(module):
import numpy as np
import random
_random_seed = int(np.random.uniform() * (2 ** 31 - 1))
np.random.seed(_random_seed)
random.seed(_random_seed)
<commit_msg>Increment minor version for :fire: HOTFIX release<commit_after># -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.6.2"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except NameError:
__PYRAMID_SETUP__ = False
if __PYRAMID_SETUP__:
import sys
import os
sys.stderr.write('Partial import of pyramid during the build process.' + os.linesep)
else:
# check that the build completed properly. This prints an informative
# message in the case that any of the C code was not properly compiled.
from . import __check_build
__all__ = [
'arima',
'compat',
'datasets',
'utils'
]
def setup_module(module):
import numpy as np
import random
_random_seed = int(np.random.uniform() * (2 ** 31 - 1))
np.random.seed(_random_seed)
random.seed(_random_seed)
|
bc313462e7d1d1e45cfa0b15baf668b96569f52f | python/wordcount.py | python/wordcount.py | import sys, re
counts = {}
for line in sys.stdin:
for word in re.findall(r'[A-Za-z\']+', line.lower()):
counts[word] = counts.get(word, 0) + 1
for word, count in sorted(counts.items()):
print(word, count)
| import sys, re
counts = {}
for line in sys.stdin:
for word in re.findall(r'[a-z\']+', line.lower()):
counts[word] = counts.get(word, 0) + 1
for word, count in sorted(counts.items()):
print(word, count)
| Use a more efficient regex | Use a more efficient regex
| Python | mit | rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot | import sys, re
counts = {}
for line in sys.stdin:
for word in re.findall(r'[A-Za-z\']+', line.lower()):
counts[word] = counts.get(word, 0) + 1
for word, count in sorted(counts.items()):
print(word, count)
Use a more efficient regex | import sys, re
counts = {}
for line in sys.stdin:
for word in re.findall(r'[a-z\']+', line.lower()):
counts[word] = counts.get(word, 0) + 1
for word, count in sorted(counts.items()):
print(word, count)
| <commit_before>import sys, re
counts = {}
for line in sys.stdin:
for word in re.findall(r'[A-Za-z\']+', line.lower()):
counts[word] = counts.get(word, 0) + 1
for word, count in sorted(counts.items()):
print(word, count)
<commit_msg>Use a more efficient regex<commit_after> | import sys, re
counts = {}
for line in sys.stdin:
for word in re.findall(r'[a-z\']+', line.lower()):
counts[word] = counts.get(word, 0) + 1
for word, count in sorted(counts.items()):
print(word, count)
| import sys, re
counts = {}
for line in sys.stdin:
for word in re.findall(r'[A-Za-z\']+', line.lower()):
counts[word] = counts.get(word, 0) + 1
for word, count in sorted(counts.items()):
print(word, count)
Use a more efficient regeximport sys, re
counts = {}
for line in sys.stdin:
for word in re.findall(r'[a-z\']+', line.lower()):
counts[word] = counts.get(word, 0) + 1
for word, count in sorted(counts.items()):
print(word, count)
| <commit_before>import sys, re
counts = {}
for line in sys.stdin:
for word in re.findall(r'[A-Za-z\']+', line.lower()):
counts[word] = counts.get(word, 0) + 1
for word, count in sorted(counts.items()):
print(word, count)
<commit_msg>Use a more efficient regex<commit_after>import sys, re
counts = {}
for line in sys.stdin:
for word in re.findall(r'[a-z\']+', line.lower()):
counts[word] = counts.get(word, 0) + 1
for word, count in sorted(counts.items()):
print(word, count)
|
f5d9fbf618f44e8572344e04e9a09c7cae3302bb | neurodsp/plts/__init__.py | neurodsp/plts/__init__.py | """Plotting functions."""
from .time_series import plot_time_series, plot_bursts
from .filt import plot_filter_properties, plot_frequency_response, plot_impulse_response
from .rhythm import plot_swm_pattern, plot_lagged_coherence
from .spectral import plot_power_spectra, plot_scv, plot_scv_rs_lines, plot_scv_rs_matrix, plot_spectral_hist
| """Plotting functions."""
from .time_series import plot_time_series, plot_bursts, plot_instantaneous_measure
from .filt import plot_filter_properties, plot_frequency_response, plot_impulse_response
from .rhythm import plot_swm_pattern, plot_lagged_coherence
from .spectral import plot_power_spectra, plot_scv, plot_scv_rs_lines, plot_scv_rs_matrix, plot_spectral_hist
| Make plot_instantaneous_measure accessible from root of plots | Make plot_instantaneous_measure accessible from root of plots
| Python | apache-2.0 | voytekresearch/neurodsp | """Plotting functions."""
from .time_series import plot_time_series, plot_bursts
from .filt import plot_filter_properties, plot_frequency_response, plot_impulse_response
from .rhythm import plot_swm_pattern, plot_lagged_coherence
from .spectral import plot_power_spectra, plot_scv, plot_scv_rs_lines, plot_scv_rs_matrix, plot_spectral_hist
Make plot_instantaneous_measure accessible from root of plots | """Plotting functions."""
from .time_series import plot_time_series, plot_bursts, plot_instantaneous_measure
from .filt import plot_filter_properties, plot_frequency_response, plot_impulse_response
from .rhythm import plot_swm_pattern, plot_lagged_coherence
from .spectral import plot_power_spectra, plot_scv, plot_scv_rs_lines, plot_scv_rs_matrix, plot_spectral_hist
| <commit_before>"""Plotting functions."""
from .time_series import plot_time_series, plot_bursts
from .filt import plot_filter_properties, plot_frequency_response, plot_impulse_response
from .rhythm import plot_swm_pattern, plot_lagged_coherence
from .spectral import plot_power_spectra, plot_scv, plot_scv_rs_lines, plot_scv_rs_matrix, plot_spectral_hist
<commit_msg>Make plot_instantaneous_measure accessible from root of plots<commit_after> | """Plotting functions."""
from .time_series import plot_time_series, plot_bursts, plot_instantaneous_measure
from .filt import plot_filter_properties, plot_frequency_response, plot_impulse_response
from .rhythm import plot_swm_pattern, plot_lagged_coherence
from .spectral import plot_power_spectra, plot_scv, plot_scv_rs_lines, plot_scv_rs_matrix, plot_spectral_hist
| """Plotting functions."""
from .time_series import plot_time_series, plot_bursts
from .filt import plot_filter_properties, plot_frequency_response, plot_impulse_response
from .rhythm import plot_swm_pattern, plot_lagged_coherence
from .spectral import plot_power_spectra, plot_scv, plot_scv_rs_lines, plot_scv_rs_matrix, plot_spectral_hist
Make plot_instantaneous_measure accessible from root of plots"""Plotting functions."""
from .time_series import plot_time_series, plot_bursts, plot_instantaneous_measure
from .filt import plot_filter_properties, plot_frequency_response, plot_impulse_response
from .rhythm import plot_swm_pattern, plot_lagged_coherence
from .spectral import plot_power_spectra, plot_scv, plot_scv_rs_lines, plot_scv_rs_matrix, plot_spectral_hist
| <commit_before>"""Plotting functions."""
from .time_series import plot_time_series, plot_bursts
from .filt import plot_filter_properties, plot_frequency_response, plot_impulse_response
from .rhythm import plot_swm_pattern, plot_lagged_coherence
from .spectral import plot_power_spectra, plot_scv, plot_scv_rs_lines, plot_scv_rs_matrix, plot_spectral_hist
<commit_msg>Make plot_instantaneous_measure accessible from root of plots<commit_after>"""Plotting functions."""
from .time_series import plot_time_series, plot_bursts, plot_instantaneous_measure
from .filt import plot_filter_properties, plot_frequency_response, plot_impulse_response
from .rhythm import plot_swm_pattern, plot_lagged_coherence
from .spectral import plot_power_spectra, plot_scv, plot_scv_rs_lines, plot_scv_rs_matrix, plot_spectral_hist
|
a06c4da0cc683162b8ecf8569f6d8878b8d45872 | examples/esp8266/lux_sensor_demo.py | examples/esp8266/lux_sensor_demo.py | # Simple demo of reading the tsl2591 lux sensor from the
# ESP8266 running micropython.
from antevents import *
from tsl2591 import Tsl2591
tsl = Tsl2591('lux-1')
tsl.sample()
sched = Scheduler()
class Output:
def on_next(self, x):
print(x)
def on_completed():
pass
def on_error(self, e):
pass
sched.schedule_sensor(tsl, 2.0, Output()
sched.run_forever()
| # Simple demo of reading the tsl2591 lux sensor from the
# ESP8266 running micropython.
from antevents import *
from tsl2591 import Tsl2591
tsl = Tsl2591('lux-1')
tsl.sample()
sched = Scheduler()
class Output:
def on_next(self, x):
print(x)
def on_completed():
pass
def on_error(self, e):
pass
sched.schedule_sensor(tsl, 2.0, Output())
sched.run_forever()
| Fix missing paren (copy and paste error) | Fix missing paren (copy and paste error) | Python | apache-2.0 | mpi-sws-rse/antevents-python,mpi-sws-rse/antevents-python,mpi-sws-rse/thingflow-python,mpi-sws-rse/thingflow-python | # Simple demo of reading the tsl2591 lux sensor from the
# ESP8266 running micropython.
from antevents import *
from tsl2591 import Tsl2591
tsl = Tsl2591('lux-1')
tsl.sample()
sched = Scheduler()
class Output:
def on_next(self, x):
print(x)
def on_completed():
pass
def on_error(self, e):
pass
sched.schedule_sensor(tsl, 2.0, Output()
sched.run_forever()
Fix missing paren (copy and paste error) | # Simple demo of reading the tsl2591 lux sensor from the
# ESP8266 running micropython.
from antevents import *
from tsl2591 import Tsl2591
tsl = Tsl2591('lux-1')
tsl.sample()
sched = Scheduler()
class Output:
def on_next(self, x):
print(x)
def on_completed():
pass
def on_error(self, e):
pass
sched.schedule_sensor(tsl, 2.0, Output())
sched.run_forever()
| <commit_before># Simple demo of reading the tsl2591 lux sensor from the
# ESP8266 running micropython.
from antevents import *
from tsl2591 import Tsl2591
tsl = Tsl2591('lux-1')
tsl.sample()
sched = Scheduler()
class Output:
def on_next(self, x):
print(x)
def on_completed():
pass
def on_error(self, e):
pass
sched.schedule_sensor(tsl, 2.0, Output()
sched.run_forever()
<commit_msg>Fix missing paren (copy and paste error)<commit_after> | # Simple demo of reading the tsl2591 lux sensor from the
# ESP8266 running micropython.
from antevents import *
from tsl2591 import Tsl2591
tsl = Tsl2591('lux-1')
tsl.sample()
sched = Scheduler()
class Output:
def on_next(self, x):
print(x)
def on_completed():
pass
def on_error(self, e):
pass
sched.schedule_sensor(tsl, 2.0, Output())
sched.run_forever()
| # Simple demo of reading the tsl2591 lux sensor from the
# ESP8266 running micropython.
from antevents import *
from tsl2591 import Tsl2591
tsl = Tsl2591('lux-1')
tsl.sample()
sched = Scheduler()
class Output:
def on_next(self, x):
print(x)
def on_completed():
pass
def on_error(self, e):
pass
sched.schedule_sensor(tsl, 2.0, Output()
sched.run_forever()
Fix missing paren (copy and paste error)# Simple demo of reading the tsl2591 lux sensor from the
# ESP8266 running micropython.
from antevents import *
from tsl2591 import Tsl2591
tsl = Tsl2591('lux-1')
tsl.sample()
sched = Scheduler()
class Output:
def on_next(self, x):
print(x)
def on_completed():
pass
def on_error(self, e):
pass
sched.schedule_sensor(tsl, 2.0, Output())
sched.run_forever()
| <commit_before># Simple demo of reading the tsl2591 lux sensor from the
# ESP8266 running micropython.
from antevents import *
from tsl2591 import Tsl2591
tsl = Tsl2591('lux-1')
tsl.sample()
sched = Scheduler()
class Output:
def on_next(self, x):
print(x)
def on_completed():
pass
def on_error(self, e):
pass
sched.schedule_sensor(tsl, 2.0, Output()
sched.run_forever()
<commit_msg>Fix missing paren (copy and paste error)<commit_after># Simple demo of reading the tsl2591 lux sensor from the
# ESP8266 running micropython.
from antevents import *
from tsl2591 import Tsl2591
tsl = Tsl2591('lux-1')
tsl.sample()
sched = Scheduler()
class Output:
def on_next(self, x):
print(x)
def on_completed():
pass
def on_error(self, e):
pass
sched.schedule_sensor(tsl, 2.0, Output())
sched.run_forever()
|
372cb5cfb74e207c169bec473eeed48497748d51 | nipype/utils/setup.py | nipype/utils/setup.py | from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('utils', parent_package, top_path)
config.add_data_dir('tests')
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('utils', parent_package, top_path)
config.add_data_dir('tests')
try:
# If the user has IPython installed, this will install the
# nipype profile under their '~/.ipython' directory so they
# can launch ipython with 'ipython -p nipype' and the traits
# completer will be enabled by default.
from IPython.genutils import get_ipython_dir
pth = get_ipython_dir()
config.data_files = [(pth, ['ipy_profile_nipype.py'])]
except ImportError:
# Don't do anything if they haven't installed IPython
pass
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| Add install for nipype ipython profile. | Add install for nipype ipython profile.
git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@1352 ead46cd0-7350-4e37-8683-fc4c6f79bf00
| Python | bsd-3-clause | wanderine/nipype,JohnGriffiths/nipype,iglpdc/nipype,blakedewey/nipype,Leoniela/nipype,FredLoney/nipype,arokem/nipype,Leoniela/nipype,mick-d/nipype,glatard/nipype,dmordom/nipype,pearsonlab/nipype,pearsonlab/nipype,rameshvs/nipype,pearsonlab/nipype,sgiavasis/nipype,grlee77/nipype,arokem/nipype,wanderine/nipype,iglpdc/nipype,carlohamalainen/nipype,dmordom/nipype,glatard/nipype,blakedewey/nipype,carolFrohlich/nipype,pearsonlab/nipype,FCP-INDI/nipype,dgellis90/nipype,carolFrohlich/nipype,grlee77/nipype,gerddie/nipype,sgiavasis/nipype,sgiavasis/nipype,glatard/nipype,iglpdc/nipype,rameshvs/nipype,JohnGriffiths/nipype,FCP-INDI/nipype,dgellis90/nipype,dgellis90/nipype,fprados/nipype,mick-d/nipype_source,wanderine/nipype,carolFrohlich/nipype,wanderine/nipype,mick-d/nipype_source,arokem/nipype,FredLoney/nipype,blakedewey/nipype,dgellis90/nipype,christianbrodbeck/nipype,FredLoney/nipype,glatard/nipype,satra/NiPypeold,gerddie/nipype,rameshvs/nipype,carlohamalainen/nipype,gerddie/nipype,dmordom/nipype,gerddie/nipype,mick-d/nipype,arokem/nipype,grlee77/nipype,blakedewey/nipype,iglpdc/nipype,JohnGriffiths/nipype,satra/NiPypeold,mick-d/nipype,mick-d/nipype,FCP-INDI/nipype,carolFrohlich/nipype,fprados/nipype,carlohamalainen/nipype,rameshvs/nipype,grlee77/nipype,FCP-INDI/nipype,Leoniela/nipype,fprados/nipype,sgiavasis/nipype,christianbrodbeck/nipype,JohnGriffiths/nipype,mick-d/nipype_source | from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('utils', parent_package, top_path)
config.add_data_dir('tests')
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
Add install for nipype ipython profile.
git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@1352 ead46cd0-7350-4e37-8683-fc4c6f79bf00 | from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('utils', parent_package, top_path)
config.add_data_dir('tests')
try:
# If the user has IPython installed, this will install the
# nipype profile under their '~/.ipython' directory so they
# can launch ipython with 'ipython -p nipype' and the traits
# completer will be enabled by default.
from IPython.genutils import get_ipython_dir
pth = get_ipython_dir()
config.data_files = [(pth, ['ipy_profile_nipype.py'])]
except ImportError:
# Don't do anything if they haven't installed IPython
pass
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| <commit_before>from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('utils', parent_package, top_path)
config.add_data_dir('tests')
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
<commit_msg>Add install for nipype ipython profile.
git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@1352 ead46cd0-7350-4e37-8683-fc4c6f79bf00<commit_after> | from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('utils', parent_package, top_path)
config.add_data_dir('tests')
try:
# If the user has IPython installed, this will install the
# nipype profile under their '~/.ipython' directory so they
# can launch ipython with 'ipython -p nipype' and the traits
# completer will be enabled by default.
from IPython.genutils import get_ipython_dir
pth = get_ipython_dir()
config.data_files = [(pth, ['ipy_profile_nipype.py'])]
except ImportError:
# Don't do anything if they haven't installed IPython
pass
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('utils', parent_package, top_path)
config.add_data_dir('tests')
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
Add install for nipype ipython profile.
git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@1352 ead46cd0-7350-4e37-8683-fc4c6f79bf00from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('utils', parent_package, top_path)
config.add_data_dir('tests')
try:
# If the user has IPython installed, this will install the
# nipype profile under their '~/.ipython' directory so they
# can launch ipython with 'ipython -p nipype' and the traits
# completer will be enabled by default.
from IPython.genutils import get_ipython_dir
pth = get_ipython_dir()
config.data_files = [(pth, ['ipy_profile_nipype.py'])]
except ImportError:
# Don't do anything if they haven't installed IPython
pass
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| <commit_before>from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('utils', parent_package, top_path)
config.add_data_dir('tests')
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
<commit_msg>Add install for nipype ipython profile.
git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@1352 ead46cd0-7350-4e37-8683-fc4c6f79bf00<commit_after>from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('utils', parent_package, top_path)
config.add_data_dir('tests')
try:
# If the user has IPython installed, this will install the
# nipype profile under their '~/.ipython' directory so they
# can launch ipython with 'ipython -p nipype' and the traits
# completer will be enabled by default.
from IPython.genutils import get_ipython_dir
pth = get_ipython_dir()
config.data_files = [(pth, ['ipy_profile_nipype.py'])]
except ImportError:
# Don't do anything if they haven't installed IPython
pass
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
|
259b212c68233ed56f9bc3123d85ea28f885af78 | dijkstraNew.py | dijkstraNew.py | class DijkstraNew:
def __init__(self,edges,start):
self.edges = edges
self.take_shorter_edges() # Bei doppelten Kanten kürzere nehmen
self.start = start
self.edges_in_dijkstra = [] # Kanten, über die Dijkstra geht
self.visible_edges = [] # Sichtbare Kanten
self.visible_nodes = [start] # Besuchte Knoten
| class DijkstraNew:
def __init__(self,edges,start):
self.edges = edges
self.take_shorter_edges() # Bei doppelten Kanten kürzere nehmen
self.start = start
self.edges_in_dijkstra = [] # Kanten, über die Dijkstra geht
self.visible_edges = [] # Sichtbare Kanten
self.visible_nodes = [start] # Besuchte Knoten
# Falls doppelte Kanten zwischen Knoten, dann nur kürzesten lassen
def take_shorter_edges(self):
delete_edges = self.index_of_longer_edges()
if(delete_edges != [] and delete_edges != None):
delete_edges.sort()
delete_edges.reverse()
self.delete_long_edges(delete_edges)
# Indizes der langen Kanten bekommen
def index_of_longer_edges(self):
delete_edges = []
for i in range(len(self.edges)):
for j in range(len(self.edges)):
if i != j and self.edges[i][0] == self.edges[j][0] and \
self.edges[i][2] == self.edges[j][2]:
if self.edges[i][1] > self.edges[j][1] \
and i not in delete_edges:
delete_edges.append(i)
elif self.edges[i][1] < self.edges[j][1] \
and j not in delete_edges:
delete_edges.append(j)
return delete_edges
# Lange Kanten löschen
def delete_long_edges(self,delete_edges):
for edge in delete_edges:
self.edges.pop(edge)
| Delete long edges if there are multiple edges between the same two nodes | Delete long edges if there are multiple edges between the same two nodes
| Python | apache-2.0 | NWuensche/DijkstraInPython | class DijkstraNew:
def __init__(self,edges,start):
self.edges = edges
self.take_shorter_edges() # Bei doppelten Kanten kürzere nehmen
self.start = start
self.edges_in_dijkstra = [] # Kanten, über die Dijkstra geht
self.visible_edges = [] # Sichtbare Kanten
self.visible_nodes = [start] # Besuchte Knoten
Delete long edges if there are multiple edges between the same two nodes | class DijkstraNew:
def __init__(self,edges,start):
self.edges = edges
self.take_shorter_edges() # Bei doppelten Kanten kürzere nehmen
self.start = start
self.edges_in_dijkstra = [] # Kanten, über die Dijkstra geht
self.visible_edges = [] # Sichtbare Kanten
self.visible_nodes = [start] # Besuchte Knoten
# Falls doppelte Kanten zwischen Knoten, dann nur kürzesten lassen
def take_shorter_edges(self):
delete_edges = self.index_of_longer_edges()
if(delete_edges != [] and delete_edges != None):
delete_edges.sort()
delete_edges.reverse()
self.delete_long_edges(delete_edges)
# Indizes der langen Kanten bekommen
def index_of_longer_edges(self):
delete_edges = []
for i in range(len(self.edges)):
for j in range(len(self.edges)):
if i != j and self.edges[i][0] == self.edges[j][0] and \
self.edges[i][2] == self.edges[j][2]:
if self.edges[i][1] > self.edges[j][1] \
and i not in delete_edges:
delete_edges.append(i)
elif self.edges[i][1] < self.edges[j][1] \
and j not in delete_edges:
delete_edges.append(j)
return delete_edges
# Lange Kanten löschen
def delete_long_edges(self,delete_edges):
for edge in delete_edges:
self.edges.pop(edge)
| <commit_before>class DijkstraNew:
def __init__(self,edges,start):
self.edges = edges
self.take_shorter_edges() # Bei doppelten Kanten kürzere nehmen
self.start = start
self.edges_in_dijkstra = [] # Kanten, über die Dijkstra geht
self.visible_edges = [] # Sichtbare Kanten
self.visible_nodes = [start] # Besuchte Knoten
<commit_msg>Delete long edges if there are multiple edges between the same two nodes<commit_after> | class DijkstraNew:
def __init__(self,edges,start):
self.edges = edges
self.take_shorter_edges() # Bei doppelten Kanten kürzere nehmen
self.start = start
self.edges_in_dijkstra = [] # Kanten, über die Dijkstra geht
self.visible_edges = [] # Sichtbare Kanten
self.visible_nodes = [start] # Besuchte Knoten
# Falls doppelte Kanten zwischen Knoten, dann nur kürzesten lassen
def take_shorter_edges(self):
delete_edges = self.index_of_longer_edges()
if(delete_edges != [] and delete_edges != None):
delete_edges.sort()
delete_edges.reverse()
self.delete_long_edges(delete_edges)
# Indizes der langen Kanten bekommen
def index_of_longer_edges(self):
delete_edges = []
for i in range(len(self.edges)):
for j in range(len(self.edges)):
if i != j and self.edges[i][0] == self.edges[j][0] and \
self.edges[i][2] == self.edges[j][2]:
if self.edges[i][1] > self.edges[j][1] \
and i not in delete_edges:
delete_edges.append(i)
elif self.edges[i][1] < self.edges[j][1] \
and j not in delete_edges:
delete_edges.append(j)
return delete_edges
# Lange Kanten löschen
def delete_long_edges(self,delete_edges):
for edge in delete_edges:
self.edges.pop(edge)
| class DijkstraNew:
def __init__(self,edges,start):
self.edges = edges
self.take_shorter_edges() # Bei doppelten Kanten kürzere nehmen
self.start = start
self.edges_in_dijkstra = [] # Kanten, über die Dijkstra geht
self.visible_edges = [] # Sichtbare Kanten
self.visible_nodes = [start] # Besuchte Knoten
Delete long edges if there are multiple edges between the same two nodesclass DijkstraNew:
def __init__(self,edges,start):
self.edges = edges
self.take_shorter_edges() # Bei doppelten Kanten kürzere nehmen
self.start = start
self.edges_in_dijkstra = [] # Kanten, über die Dijkstra geht
self.visible_edges = [] # Sichtbare Kanten
self.visible_nodes = [start] # Besuchte Knoten
# Falls doppelte Kanten zwischen Knoten, dann nur kürzesten lassen
def take_shorter_edges(self):
delete_edges = self.index_of_longer_edges()
if(delete_edges != [] and delete_edges != None):
delete_edges.sort()
delete_edges.reverse()
self.delete_long_edges(delete_edges)
# Indizes der langen Kanten bekommen
def index_of_longer_edges(self):
delete_edges = []
for i in range(len(self.edges)):
for j in range(len(self.edges)):
if i != j and self.edges[i][0] == self.edges[j][0] and \
self.edges[i][2] == self.edges[j][2]:
if self.edges[i][1] > self.edges[j][1] \
and i not in delete_edges:
delete_edges.append(i)
elif self.edges[i][1] < self.edges[j][1] \
and j not in delete_edges:
delete_edges.append(j)
return delete_edges
# Lange Kanten löschen
def delete_long_edges(self,delete_edges):
for edge in delete_edges:
self.edges.pop(edge)
| <commit_before>class DijkstraNew:
def __init__(self,edges,start):
self.edges = edges
self.take_shorter_edges() # Bei doppelten Kanten kürzere nehmen
self.start = start
self.edges_in_dijkstra = [] # Kanten, über die Dijkstra geht
self.visible_edges = [] # Sichtbare Kanten
self.visible_nodes = [start] # Besuchte Knoten
<commit_msg>Delete long edges if there are multiple edges between the same two nodes<commit_after>class DijkstraNew:
def __init__(self,edges,start):
self.edges = edges
self.take_shorter_edges() # Bei doppelten Kanten kürzere nehmen
self.start = start
self.edges_in_dijkstra = [] # Kanten, über die Dijkstra geht
self.visible_edges = [] # Sichtbare Kanten
self.visible_nodes = [start] # Besuchte Knoten
# Falls doppelte Kanten zwischen Knoten, dann nur kürzesten lassen
def take_shorter_edges(self):
delete_edges = self.index_of_longer_edges()
if(delete_edges != [] and delete_edges != None):
delete_edges.sort()
delete_edges.reverse()
self.delete_long_edges(delete_edges)
# Indizes der langen Kanten bekommen
def index_of_longer_edges(self):
delete_edges = []
for i in range(len(self.edges)):
for j in range(len(self.edges)):
if i != j and self.edges[i][0] == self.edges[j][0] and \
self.edges[i][2] == self.edges[j][2]:
if self.edges[i][1] > self.edges[j][1] \
and i not in delete_edges:
delete_edges.append(i)
elif self.edges[i][1] < self.edges[j][1] \
and j not in delete_edges:
delete_edges.append(j)
return delete_edges
# Lange Kanten löschen
def delete_long_edges(self,delete_edges):
for edge in delete_edges:
self.edges.pop(edge)
|
b5871e451955e993ea368cb832714612a6dd48d1 | fog-aws-testing/scripts/test_all.py | fog-aws-testing/scripts/test_all.py | #!/usr/bin/python
from threading import Thread
import subprocess
from functions import *
def runTest(branch,os):
subprocess.call(test_script + " " + branch + " " + os, shell=True)
for branch in branches:
threads = []
for os in OSs:
instance = get_instance("Name","fogtesting-" + os)
snapshot = get_snapshot("Name",os + '-clean')
restore_snapshot_to_instance(snapshot,instance)
threads.append(Thread(target=runTest,args=(branch,os)))
time.sleep(20)
# Start all the tests for this branch.
for x in threads:
x.start()
# Wait for all of them to get done before proceeding.
for x in threads:
x.join()
| #!/usr/bin/python
from threading import Thread
import subprocess
from functions import *
def runTest(branch,os):
subprocess.call(test_script + " " + branch + " " + os, shell=True)
from functions import *
threads = []
for os in OSs:
instance = get_instance("Name","fogtesting-" + os)
snapshot = get_snapshot("Name",os + '-clean')
if os == "debian9":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"xvda")))
elif os == "centos7":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"/dev/sda1")))
# Start all the threads.
for x in threads:
x.start()
# Wait for all threads to exit.
for x in threads:
x.join()
for branch in branches:
threads = []
for os in OSs:
instance = get_instance("Name","fogtesting-" + os)
snapshot = get_snapshot("Name",os + '-clean')
if os == "debian9":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"xvda")))
elif os == "centos7":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"/dev/sda1")))
# Start snapshot restore threads.
for x in threads:
x.start()
# Wait for all threads to be done.
for x in threads:
x.join()
# Reset threads.
threads = []
for os in OSs:
threads.append(Thread(target=runTest,args=(branch,os)))
# Start all the tests for this branch.
for x in threads:
x.start()
# Wait for all of them to get done before proceeding.
for x in threads:
x.join()
| Use threading when restoring snapshots during testing | Use threading when restoring snapshots during testing
| Python | mit | FOGProject/fog-community-scripts,FOGProject/fog-community-scripts,FOGProject/fog-community-scripts | #!/usr/bin/python
from threading import Thread
import subprocess
from functions import *
def runTest(branch,os):
subprocess.call(test_script + " " + branch + " " + os, shell=True)
for branch in branches:
threads = []
for os in OSs:
instance = get_instance("Name","fogtesting-" + os)
snapshot = get_snapshot("Name",os + '-clean')
restore_snapshot_to_instance(snapshot,instance)
threads.append(Thread(target=runTest,args=(branch,os)))
time.sleep(20)
# Start all the tests for this branch.
for x in threads:
x.start()
# Wait for all of them to get done before proceeding.
for x in threads:
x.join()
Use threading when restoring snapshots during testing | #!/usr/bin/python
from threading import Thread
import subprocess
from functions import *
def runTest(branch,os):
subprocess.call(test_script + " " + branch + " " + os, shell=True)
from functions import *
threads = []
for os in OSs:
instance = get_instance("Name","fogtesting-" + os)
snapshot = get_snapshot("Name",os + '-clean')
if os == "debian9":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"xvda")))
elif os == "centos7":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"/dev/sda1")))
# Start all the threads.
for x in threads:
x.start()
# Wait for all threads to exit.
for x in threads:
x.join()
for branch in branches:
threads = []
for os in OSs:
instance = get_instance("Name","fogtesting-" + os)
snapshot = get_snapshot("Name",os + '-clean')
if os == "debian9":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"xvda")))
elif os == "centos7":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"/dev/sda1")))
# Start snapshot restore threads.
for x in threads:
x.start()
# Wait for all threads to be done.
for x in threads:
x.join()
# Reset threads.
threads = []
for os in OSs:
threads.append(Thread(target=runTest,args=(branch,os)))
# Start all the tests for this branch.
for x in threads:
x.start()
# Wait for all of them to get done before proceeding.
for x in threads:
x.join()
| <commit_before>#!/usr/bin/python
from threading import Thread
import subprocess
from functions import *
def runTest(branch,os):
subprocess.call(test_script + " " + branch + " " + os, shell=True)
for branch in branches:
threads = []
for os in OSs:
instance = get_instance("Name","fogtesting-" + os)
snapshot = get_snapshot("Name",os + '-clean')
restore_snapshot_to_instance(snapshot,instance)
threads.append(Thread(target=runTest,args=(branch,os)))
time.sleep(20)
# Start all the tests for this branch.
for x in threads:
x.start()
# Wait for all of them to get done before proceeding.
for x in threads:
x.join()
<commit_msg>Use threading when restoring snapshots during testing<commit_after> | #!/usr/bin/python
from threading import Thread
import subprocess
from functions import *
def runTest(branch,os):
subprocess.call(test_script + " " + branch + " " + os, shell=True)
from functions import *
threads = []
for os in OSs:
instance = get_instance("Name","fogtesting-" + os)
snapshot = get_snapshot("Name",os + '-clean')
if os == "debian9":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"xvda")))
elif os == "centos7":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"/dev/sda1")))
# Start all the threads.
for x in threads:
x.start()
# Wait for all threads to exit.
for x in threads:
x.join()
for branch in branches:
threads = []
for os in OSs:
instance = get_instance("Name","fogtesting-" + os)
snapshot = get_snapshot("Name",os + '-clean')
if os == "debian9":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"xvda")))
elif os == "centos7":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"/dev/sda1")))
# Start snapshot restore threads.
for x in threads:
x.start()
# Wait for all threads to be done.
for x in threads:
x.join()
# Reset threads.
threads = []
for os in OSs:
threads.append(Thread(target=runTest,args=(branch,os)))
# Start all the tests for this branch.
for x in threads:
x.start()
# Wait for all of them to get done before proceeding.
for x in threads:
x.join()
| #!/usr/bin/python
from threading import Thread
import subprocess
from functions import *
def runTest(branch,os):
subprocess.call(test_script + " " + branch + " " + os, shell=True)
for branch in branches:
threads = []
for os in OSs:
instance = get_instance("Name","fogtesting-" + os)
snapshot = get_snapshot("Name",os + '-clean')
restore_snapshot_to_instance(snapshot,instance)
threads.append(Thread(target=runTest,args=(branch,os)))
time.sleep(20)
# Start all the tests for this branch.
for x in threads:
x.start()
# Wait for all of them to get done before proceeding.
for x in threads:
x.join()
Use threading when restoring snapshots during testing#!/usr/bin/python
from threading import Thread
import subprocess
from functions import *
def runTest(branch,os):
subprocess.call(test_script + " " + branch + " " + os, shell=True)
from functions import *
threads = []
for os in OSs:
instance = get_instance("Name","fogtesting-" + os)
snapshot = get_snapshot("Name",os + '-clean')
if os == "debian9":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"xvda")))
elif os == "centos7":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"/dev/sda1")))
# Start all the threads.
for x in threads:
x.start()
# Wait for all threads to exit.
for x in threads:
x.join()
for branch in branches:
threads = []
for os in OSs:
instance = get_instance("Name","fogtesting-" + os)
snapshot = get_snapshot("Name",os + '-clean')
if os == "debian9":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"xvda")))
elif os == "centos7":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"/dev/sda1")))
# Start snapshot restore threads.
for x in threads:
x.start()
# Wait for all threads to be done.
for x in threads:
x.join()
# Reset threads.
threads = []
for os in OSs:
threads.append(Thread(target=runTest,args=(branch,os)))
# Start all the tests for this branch.
for x in threads:
x.start()
# Wait for all of them to get done before proceeding.
for x in threads:
x.join()
| <commit_before>#!/usr/bin/python
from threading import Thread
import subprocess
from functions import *
def runTest(branch,os):
subprocess.call(test_script + " " + branch + " " + os, shell=True)
for branch in branches:
threads = []
for os in OSs:
instance = get_instance("Name","fogtesting-" + os)
snapshot = get_snapshot("Name",os + '-clean')
restore_snapshot_to_instance(snapshot,instance)
threads.append(Thread(target=runTest,args=(branch,os)))
time.sleep(20)
# Start all the tests for this branch.
for x in threads:
x.start()
# Wait for all of them to get done before proceeding.
for x in threads:
x.join()
<commit_msg>Use threading when restoring snapshots during testing<commit_after>#!/usr/bin/python
from threading import Thread
import subprocess
from functions import *
def runTest(branch,os):
subprocess.call(test_script + " " + branch + " " + os, shell=True)
from functions import *
threads = []
for os in OSs:
instance = get_instance("Name","fogtesting-" + os)
snapshot = get_snapshot("Name",os + '-clean')
if os == "debian9":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"xvda")))
elif os == "centos7":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"/dev/sda1")))
# Start all the threads.
for x in threads:
x.start()
# Wait for all threads to exit.
for x in threads:
x.join()
for branch in branches:
threads = []
for os in OSs:
instance = get_instance("Name","fogtesting-" + os)
snapshot = get_snapshot("Name",os + '-clean')
if os == "debian9":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"xvda")))
elif os == "centos7":
threads.append(Thread(target=restore_snapshot_to_instance,args=(snapshot,instance,"/dev/sda1")))
# Start snapshot restore threads.
for x in threads:
x.start()
# Wait for all threads to be done.
for x in threads:
x.join()
# Reset threads.
threads = []
for os in OSs:
threads.append(Thread(target=runTest,args=(branch,os)))
# Start all the tests for this branch.
for x in threads:
x.start()
# Wait for all of them to get done before proceeding.
for x in threads:
x.join()
|
30a81d64c513d23aae6dc6cc51fa047d6479150f | halo/_utils.py | halo/_utils.py | """Utilities for Halo library.
"""
import platform
import six
import codecs
from colorama import init, Fore
from termcolor import colored
init(autoreset=True)
def is_supported():
"""Check whether operating system supports main symbols or not.
Returns
-------
boolean
Whether operating system supports main symbols or not
"""
os_arch = platform.system() + str(platform.architecture()[0])
if os_arch != 'Windows32bit':
return True
return False
def colored_frame(frame, color):
"""Color the frame with given color and returns.
Parameters
----------
frame : str
Frame to be colored
color : str
Color to be applied
Returns
-------
str
Colored frame
"""
return colored(frame, color, attrs=['bold'])
def is_text_type(text):
"""Check if given parameter is a string or not
Parameters
----------
text : *
Parameter to be checked for text type
Returns
-------
bool
Whether parameter is a string or not
"""
if isinstance(text, six.text_type) or isinstance(text, six.string_types):
return True
return False
def decode_utf_8_text(text):
"""Decode the text from utf-8 format
Parameters
----------
text : str
String to be decoded
Returns
-------
str
Decoded string
"""
try:
return codecs.decode(text, 'utf-8')
except:
return text
| """Utilities for Halo library.
"""
import platform
import six
import codecs
from colorama import init, Fore
from termcolor import colored
init(autoreset=True)
def is_supported():
"""Check whether operating system supports main symbols or not.
Returns
-------
boolean
Whether operating system supports main symbols or not
"""
os_arch = platform.system()
if os_arch != 'Windows':
return True
return False
def colored_frame(frame, color):
"""Color the frame with given color and returns.
Parameters
----------
frame : str
Frame to be colored
color : str
Color to be applied
Returns
-------
str
Colored frame
"""
return colored(frame, color, attrs=['bold'])
def is_text_type(text):
"""Check if given parameter is a string or not
Parameters
----------
text : *
Parameter to be checked for text type
Returns
-------
bool
Whether parameter is a string or not
"""
if isinstance(text, six.text_type) or isinstance(text, six.string_types):
return True
return False
def decode_utf_8_text(text):
"""Decode the text from utf-8 format
Parameters
----------
text : str
String to be decoded
Returns
-------
str
Decoded string
"""
try:
return codecs.decode(text, 'utf-8')
except:
return text
| Remove support for windows till fully tested | Halo: Remove support for windows till fully tested
| Python | mit | ManrajGrover/halo,manrajgrover/halo | """Utilities for Halo library.
"""
import platform
import six
import codecs
from colorama import init, Fore
from termcolor import colored
init(autoreset=True)
def is_supported():
"""Check whether operating system supports main symbols or not.
Returns
-------
boolean
Whether operating system supports main symbols or not
"""
os_arch = platform.system() + str(platform.architecture()[0])
if os_arch != 'Windows32bit':
return True
return False
def colored_frame(frame, color):
"""Color the frame with given color and returns.
Parameters
----------
frame : str
Frame to be colored
color : str
Color to be applied
Returns
-------
str
Colored frame
"""
return colored(frame, color, attrs=['bold'])
def is_text_type(text):
"""Check if given parameter is a string or not
Parameters
----------
text : *
Parameter to be checked for text type
Returns
-------
bool
Whether parameter is a string or not
"""
if isinstance(text, six.text_type) or isinstance(text, six.string_types):
return True
return False
def decode_utf_8_text(text):
"""Decode the text from utf-8 format
Parameters
----------
text : str
String to be decoded
Returns
-------
str
Decoded string
"""
try:
return codecs.decode(text, 'utf-8')
except:
return text
Halo: Remove support for windows till fully tested | """Utilities for Halo library.
"""
import platform
import six
import codecs
from colorama import init, Fore
from termcolor import colored
init(autoreset=True)
def is_supported():
"""Check whether operating system supports main symbols or not.
Returns
-------
boolean
Whether operating system supports main symbols or not
"""
os_arch = platform.system()
if os_arch != 'Windows':
return True
return False
def colored_frame(frame, color):
"""Color the frame with given color and returns.
Parameters
----------
frame : str
Frame to be colored
color : str
Color to be applied
Returns
-------
str
Colored frame
"""
return colored(frame, color, attrs=['bold'])
def is_text_type(text):
"""Check if given parameter is a string or not
Parameters
----------
text : *
Parameter to be checked for text type
Returns
-------
bool
Whether parameter is a string or not
"""
if isinstance(text, six.text_type) or isinstance(text, six.string_types):
return True
return False
def decode_utf_8_text(text):
"""Decode the text from utf-8 format
Parameters
----------
text : str
String to be decoded
Returns
-------
str
Decoded string
"""
try:
return codecs.decode(text, 'utf-8')
except:
return text
| <commit_before>"""Utilities for Halo library.
"""
import platform
import six
import codecs
from colorama import init, Fore
from termcolor import colored
init(autoreset=True)
def is_supported():
"""Check whether operating system supports main symbols or not.
Returns
-------
boolean
Whether operating system supports main symbols or not
"""
os_arch = platform.system() + str(platform.architecture()[0])
if os_arch != 'Windows32bit':
return True
return False
def colored_frame(frame, color):
"""Color the frame with given color and returns.
Parameters
----------
frame : str
Frame to be colored
color : str
Color to be applied
Returns
-------
str
Colored frame
"""
return colored(frame, color, attrs=['bold'])
def is_text_type(text):
"""Check if given parameter is a string or not
Parameters
----------
text : *
Parameter to be checked for text type
Returns
-------
bool
Whether parameter is a string or not
"""
if isinstance(text, six.text_type) or isinstance(text, six.string_types):
return True
return False
def decode_utf_8_text(text):
"""Decode the text from utf-8 format
Parameters
----------
text : str
String to be decoded
Returns
-------
str
Decoded string
"""
try:
return codecs.decode(text, 'utf-8')
except:
return text
<commit_msg>Halo: Remove support for windows till fully tested<commit_after> | """Utilities for Halo library.
"""
import platform
import six
import codecs
from colorama import init, Fore
from termcolor import colored
init(autoreset=True)
def is_supported():
"""Check whether operating system supports main symbols or not.
Returns
-------
boolean
Whether operating system supports main symbols or not
"""
os_arch = platform.system()
if os_arch != 'Windows':
return True
return False
def colored_frame(frame, color):
"""Color the frame with given color and returns.
Parameters
----------
frame : str
Frame to be colored
color : str
Color to be applied
Returns
-------
str
Colored frame
"""
return colored(frame, color, attrs=['bold'])
def is_text_type(text):
"""Check if given parameter is a string or not
Parameters
----------
text : *
Parameter to be checked for text type
Returns
-------
bool
Whether parameter is a string or not
"""
if isinstance(text, six.text_type) or isinstance(text, six.string_types):
return True
return False
def decode_utf_8_text(text):
"""Decode the text from utf-8 format
Parameters
----------
text : str
String to be decoded
Returns
-------
str
Decoded string
"""
try:
return codecs.decode(text, 'utf-8')
except:
return text
| """Utilities for Halo library.
"""
import platform
import six
import codecs
from colorama import init, Fore
from termcolor import colored
init(autoreset=True)
def is_supported():
"""Check whether operating system supports main symbols or not.
Returns
-------
boolean
Whether operating system supports main symbols or not
"""
os_arch = platform.system() + str(platform.architecture()[0])
if os_arch != 'Windows32bit':
return True
return False
def colored_frame(frame, color):
"""Color the frame with given color and returns.
Parameters
----------
frame : str
Frame to be colored
color : str
Color to be applied
Returns
-------
str
Colored frame
"""
return colored(frame, color, attrs=['bold'])
def is_text_type(text):
"""Check if given parameter is a string or not
Parameters
----------
text : *
Parameter to be checked for text type
Returns
-------
bool
Whether parameter is a string or not
"""
if isinstance(text, six.text_type) or isinstance(text, six.string_types):
return True
return False
def decode_utf_8_text(text):
"""Decode the text from utf-8 format
Parameters
----------
text : str
String to be decoded
Returns
-------
str
Decoded string
"""
try:
return codecs.decode(text, 'utf-8')
except:
return text
Halo: Remove support for windows till fully tested"""Utilities for Halo library.
"""
import platform
import six
import codecs
from colorama import init, Fore
from termcolor import colored
init(autoreset=True)
def is_supported():
"""Check whether operating system supports main symbols or not.
Returns
-------
boolean
Whether operating system supports main symbols or not
"""
os_arch = platform.system()
if os_arch != 'Windows':
return True
return False
def colored_frame(frame, color):
"""Color the frame with given color and returns.
Parameters
----------
frame : str
Frame to be colored
color : str
Color to be applied
Returns
-------
str
Colored frame
"""
return colored(frame, color, attrs=['bold'])
def is_text_type(text):
"""Check if given parameter is a string or not
Parameters
----------
text : *
Parameter to be checked for text type
Returns
-------
bool
Whether parameter is a string or not
"""
if isinstance(text, six.text_type) or isinstance(text, six.string_types):
return True
return False
def decode_utf_8_text(text):
"""Decode the text from utf-8 format
Parameters
----------
text : str
String to be decoded
Returns
-------
str
Decoded string
"""
try:
return codecs.decode(text, 'utf-8')
except:
return text
| <commit_before>"""Utilities for Halo library.
"""
import platform
import six
import codecs
from colorama import init, Fore
from termcolor import colored
init(autoreset=True)
def is_supported():
"""Check whether operating system supports main symbols or not.
Returns
-------
boolean
Whether operating system supports main symbols or not
"""
os_arch = platform.system() + str(platform.architecture()[0])
if os_arch != 'Windows32bit':
return True
return False
def colored_frame(frame, color):
"""Color the frame with given color and returns.
Parameters
----------
frame : str
Frame to be colored
color : str
Color to be applied
Returns
-------
str
Colored frame
"""
return colored(frame, color, attrs=['bold'])
def is_text_type(text):
"""Check if given parameter is a string or not
Parameters
----------
text : *
Parameter to be checked for text type
Returns
-------
bool
Whether parameter is a string or not
"""
if isinstance(text, six.text_type) or isinstance(text, six.string_types):
return True
return False
def decode_utf_8_text(text):
"""Decode the text from utf-8 format
Parameters
----------
text : str
String to be decoded
Returns
-------
str
Decoded string
"""
try:
return codecs.decode(text, 'utf-8')
except:
return text
<commit_msg>Halo: Remove support for windows till fully tested<commit_after>"""Utilities for Halo library.
"""
import platform
import six
import codecs
from colorama import init, Fore
from termcolor import colored
init(autoreset=True)
def is_supported():
"""Check whether operating system supports main symbols or not.
Returns
-------
boolean
Whether operating system supports main symbols or not
"""
os_arch = platform.system()
if os_arch != 'Windows':
return True
return False
def colored_frame(frame, color):
"""Color the frame with given color and returns.
Parameters
----------
frame : str
Frame to be colored
color : str
Color to be applied
Returns
-------
str
Colored frame
"""
return colored(frame, color, attrs=['bold'])
def is_text_type(text):
"""Check if given parameter is a string or not
Parameters
----------
text : *
Parameter to be checked for text type
Returns
-------
bool
Whether parameter is a string or not
"""
if isinstance(text, six.text_type) or isinstance(text, six.string_types):
return True
return False
def decode_utf_8_text(text):
"""Decode the text from utf-8 format
Parameters
----------
text : str
String to be decoded
Returns
-------
str
Decoded string
"""
try:
return codecs.decode(text, 'utf-8')
except:
return text
|
0bd93ad8fa88287452326ee635bbbb5d2c685a06 | permissions/tests/base.py | permissions/tests/base.py | from django.test import TestCase as BaseTestCase
from django.test import RequestFactory
from permissions import PermissionsRegistry as BasePermissionsRegistry
class PermissionsRegistry(BasePermissionsRegistry):
def _get_user_model(self):
return User
def _get_model_instance(self, model, **kwargs):
return model(**kwargs)
class Model:
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class User(Model):
def __init__(self, **kwargs):
kwargs.setdefault('permissions', [])
super(User, self).__init__(**kwargs)
def is_anonymous(self):
return False
class AnonymousUser(User):
def is_anonymous(self):
return True
class TestCase(BaseTestCase):
def setUp(self):
self.registry = PermissionsRegistry()
self.request_factory = RequestFactory()
| from django.test import TestCase as BaseTestCase
from django.test import RequestFactory
from permissions import PermissionsRegistry as BasePermissionsRegistry
class PermissionsRegistry(BasePermissionsRegistry):
def _get_user_model(self):
return User
def _get_model_instance(self, model, **kwargs):
return model(**kwargs)
class Model(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class User(Model):
def __init__(self, **kwargs):
kwargs.setdefault('permissions', [])
super(User, self).__init__(**kwargs)
def is_anonymous(self):
return False
class AnonymousUser(User):
def is_anonymous(self):
return True
class TestCase(BaseTestCase):
def setUp(self):
self.registry = PermissionsRegistry()
self.request_factory = RequestFactory()
| Make mock Model class extend object for Python 2 compat | Make mock Model class extend object for Python 2 compat
| Python | mit | PSU-OIT-ARC/django-perms,wylee/django-perms | from django.test import TestCase as BaseTestCase
from django.test import RequestFactory
from permissions import PermissionsRegistry as BasePermissionsRegistry
class PermissionsRegistry(BasePermissionsRegistry):
def _get_user_model(self):
return User
def _get_model_instance(self, model, **kwargs):
return model(**kwargs)
class Model:
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class User(Model):
def __init__(self, **kwargs):
kwargs.setdefault('permissions', [])
super(User, self).__init__(**kwargs)
def is_anonymous(self):
return False
class AnonymousUser(User):
def is_anonymous(self):
return True
class TestCase(BaseTestCase):
def setUp(self):
self.registry = PermissionsRegistry()
self.request_factory = RequestFactory()
Make mock Model class extend object for Python 2 compat | from django.test import TestCase as BaseTestCase
from django.test import RequestFactory
from permissions import PermissionsRegistry as BasePermissionsRegistry
class PermissionsRegistry(BasePermissionsRegistry):
def _get_user_model(self):
return User
def _get_model_instance(self, model, **kwargs):
return model(**kwargs)
class Model(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class User(Model):
def __init__(self, **kwargs):
kwargs.setdefault('permissions', [])
super(User, self).__init__(**kwargs)
def is_anonymous(self):
return False
class AnonymousUser(User):
def is_anonymous(self):
return True
class TestCase(BaseTestCase):
def setUp(self):
self.registry = PermissionsRegistry()
self.request_factory = RequestFactory()
| <commit_before>from django.test import TestCase as BaseTestCase
from django.test import RequestFactory
from permissions import PermissionsRegistry as BasePermissionsRegistry
class PermissionsRegistry(BasePermissionsRegistry):
def _get_user_model(self):
return User
def _get_model_instance(self, model, **kwargs):
return model(**kwargs)
class Model:
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class User(Model):
def __init__(self, **kwargs):
kwargs.setdefault('permissions', [])
super(User, self).__init__(**kwargs)
def is_anonymous(self):
return False
class AnonymousUser(User):
def is_anonymous(self):
return True
class TestCase(BaseTestCase):
def setUp(self):
self.registry = PermissionsRegistry()
self.request_factory = RequestFactory()
<commit_msg>Make mock Model class extend object for Python 2 compat<commit_after> | from django.test import TestCase as BaseTestCase
from django.test import RequestFactory
from permissions import PermissionsRegistry as BasePermissionsRegistry
class PermissionsRegistry(BasePermissionsRegistry):
def _get_user_model(self):
return User
def _get_model_instance(self, model, **kwargs):
return model(**kwargs)
class Model(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class User(Model):
def __init__(self, **kwargs):
kwargs.setdefault('permissions', [])
super(User, self).__init__(**kwargs)
def is_anonymous(self):
return False
class AnonymousUser(User):
def is_anonymous(self):
return True
class TestCase(BaseTestCase):
def setUp(self):
self.registry = PermissionsRegistry()
self.request_factory = RequestFactory()
| from django.test import TestCase as BaseTestCase
from django.test import RequestFactory
from permissions import PermissionsRegistry as BasePermissionsRegistry
class PermissionsRegistry(BasePermissionsRegistry):
def _get_user_model(self):
return User
def _get_model_instance(self, model, **kwargs):
return model(**kwargs)
class Model:
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class User(Model):
def __init__(self, **kwargs):
kwargs.setdefault('permissions', [])
super(User, self).__init__(**kwargs)
def is_anonymous(self):
return False
class AnonymousUser(User):
def is_anonymous(self):
return True
class TestCase(BaseTestCase):
def setUp(self):
self.registry = PermissionsRegistry()
self.request_factory = RequestFactory()
Make mock Model class extend object for Python 2 compatfrom django.test import TestCase as BaseTestCase
from django.test import RequestFactory
from permissions import PermissionsRegistry as BasePermissionsRegistry
class PermissionsRegistry(BasePermissionsRegistry):
def _get_user_model(self):
return User
def _get_model_instance(self, model, **kwargs):
return model(**kwargs)
class Model(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class User(Model):
def __init__(self, **kwargs):
kwargs.setdefault('permissions', [])
super(User, self).__init__(**kwargs)
def is_anonymous(self):
return False
class AnonymousUser(User):
def is_anonymous(self):
return True
class TestCase(BaseTestCase):
def setUp(self):
self.registry = PermissionsRegistry()
self.request_factory = RequestFactory()
| <commit_before>from django.test import TestCase as BaseTestCase
from django.test import RequestFactory
from permissions import PermissionsRegistry as BasePermissionsRegistry
class PermissionsRegistry(BasePermissionsRegistry):
def _get_user_model(self):
return User
def _get_model_instance(self, model, **kwargs):
return model(**kwargs)
class Model:
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class User(Model):
def __init__(self, **kwargs):
kwargs.setdefault('permissions', [])
super(User, self).__init__(**kwargs)
def is_anonymous(self):
return False
class AnonymousUser(User):
def is_anonymous(self):
return True
class TestCase(BaseTestCase):
def setUp(self):
self.registry = PermissionsRegistry()
self.request_factory = RequestFactory()
<commit_msg>Make mock Model class extend object for Python 2 compat<commit_after>from django.test import TestCase as BaseTestCase
from django.test import RequestFactory
from permissions import PermissionsRegistry as BasePermissionsRegistry
class PermissionsRegistry(BasePermissionsRegistry):
def _get_user_model(self):
return User
def _get_model_instance(self, model, **kwargs):
return model(**kwargs)
class Model(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class User(Model):
def __init__(self, **kwargs):
kwargs.setdefault('permissions', [])
super(User, self).__init__(**kwargs)
def is_anonymous(self):
return False
class AnonymousUser(User):
def is_anonymous(self):
return True
class TestCase(BaseTestCase):
def setUp(self):
self.registry = PermissionsRegistry()
self.request_factory = RequestFactory()
|
a2f13a262e22187adaf9586aac951005f43c81b3 | searchlight/opts.py | searchlight/opts.py | import itertools
import searchlight.common.wsgi
def list_opts():
return [
('DEFAULT',
itertools.chain(searchlight.common.wsgi.bind_opts,
searchlight.common.wsgi.socket_opts,
searchlight.common.wsgi.eventlet_opts)),
('profiler',
itertools.chain(searchlight.common.wsgi.profiler_opts)),
]
| import itertools
import searchlight.common.wsgi
import searchlight.common.property_utils
import searchlight.common.config
def list_opts():
return [
('DEFAULT',
itertools.chain(searchlight.common.wsgi.bind_opts,
searchlight.common.wsgi.socket_opts,
searchlight.common.wsgi.eventlet_opts,
searchlight.common.property_utils.property_opts,
searchlight.common.config.common_opts)),
('paste_deploy',
searchlight.common.config.paste_deploy_opts),
('profiler',
searchlight.common.wsgi.profiler_opts),
]
| Add some common config options | Add some common config options
| Python | apache-2.0 | openstack/searchlight,openstack/searchlight,lakshmisampath/searchlight,openstack/searchlight | import itertools
import searchlight.common.wsgi
def list_opts():
return [
('DEFAULT',
itertools.chain(searchlight.common.wsgi.bind_opts,
searchlight.common.wsgi.socket_opts,
searchlight.common.wsgi.eventlet_opts)),
('profiler',
itertools.chain(searchlight.common.wsgi.profiler_opts)),
]
Add some common config options | import itertools
import searchlight.common.wsgi
import searchlight.common.property_utils
import searchlight.common.config
def list_opts():
return [
('DEFAULT',
itertools.chain(searchlight.common.wsgi.bind_opts,
searchlight.common.wsgi.socket_opts,
searchlight.common.wsgi.eventlet_opts,
searchlight.common.property_utils.property_opts,
searchlight.common.config.common_opts)),
('paste_deploy',
searchlight.common.config.paste_deploy_opts),
('profiler',
searchlight.common.wsgi.profiler_opts),
]
| <commit_before>import itertools
import searchlight.common.wsgi
def list_opts():
return [
('DEFAULT',
itertools.chain(searchlight.common.wsgi.bind_opts,
searchlight.common.wsgi.socket_opts,
searchlight.common.wsgi.eventlet_opts)),
('profiler',
itertools.chain(searchlight.common.wsgi.profiler_opts)),
]
<commit_msg>Add some common config options<commit_after> | import itertools
import searchlight.common.wsgi
import searchlight.common.property_utils
import searchlight.common.config
def list_opts():
return [
('DEFAULT',
itertools.chain(searchlight.common.wsgi.bind_opts,
searchlight.common.wsgi.socket_opts,
searchlight.common.wsgi.eventlet_opts,
searchlight.common.property_utils.property_opts,
searchlight.common.config.common_opts)),
('paste_deploy',
searchlight.common.config.paste_deploy_opts),
('profiler',
searchlight.common.wsgi.profiler_opts),
]
| import itertools
import searchlight.common.wsgi
def list_opts():
return [
('DEFAULT',
itertools.chain(searchlight.common.wsgi.bind_opts,
searchlight.common.wsgi.socket_opts,
searchlight.common.wsgi.eventlet_opts)),
('profiler',
itertools.chain(searchlight.common.wsgi.profiler_opts)),
]
Add some common config optionsimport itertools
import searchlight.common.wsgi
import searchlight.common.property_utils
import searchlight.common.config
def list_opts():
return [
('DEFAULT',
itertools.chain(searchlight.common.wsgi.bind_opts,
searchlight.common.wsgi.socket_opts,
searchlight.common.wsgi.eventlet_opts,
searchlight.common.property_utils.property_opts,
searchlight.common.config.common_opts)),
('paste_deploy',
searchlight.common.config.paste_deploy_opts),
('profiler',
searchlight.common.wsgi.profiler_opts),
]
| <commit_before>import itertools
import searchlight.common.wsgi
def list_opts():
return [
('DEFAULT',
itertools.chain(searchlight.common.wsgi.bind_opts,
searchlight.common.wsgi.socket_opts,
searchlight.common.wsgi.eventlet_opts)),
('profiler',
itertools.chain(searchlight.common.wsgi.profiler_opts)),
]
<commit_msg>Add some common config options<commit_after>import itertools
import searchlight.common.wsgi
import searchlight.common.property_utils
import searchlight.common.config
def list_opts():
return [
('DEFAULT',
itertools.chain(searchlight.common.wsgi.bind_opts,
searchlight.common.wsgi.socket_opts,
searchlight.common.wsgi.eventlet_opts,
searchlight.common.property_utils.property_opts,
searchlight.common.config.common_opts)),
('paste_deploy',
searchlight.common.config.paste_deploy_opts),
('profiler',
searchlight.common.wsgi.profiler_opts),
]
|
2c11dd51db3a7663aa31913fa68656f60a80fcf6 | select2/__init__.py | select2/__init__.py | __version_info__ = (1, 0, 6)
__version__ = '.'.join(map(str, __version_info__))
| __version_info__ = (1, 1, 0)
__version__ = '.'.join(map(str, __version_info__))
| Increment version number to 1.1.0 | Increment version number to 1.1.0
| Python | bsd-2-clause | hkmshb/django-select2-forms,sandow-digital/django-select2-forms,sandow-digital/django-select2-forms,SpectralAngel/django-select2-forms,hkmshb/django-select2-forms,SpectralAngel/django-select2-forms,sandow-digital/django-select2-forms,hkmshb/django-select2-forms,JP-Ellis/django-select2-forms,SpectralAngel/django-select2-forms | __version_info__ = (1, 0, 6)
__version__ = '.'.join(map(str, __version_info__))
Increment version number to 1.1.0 | __version_info__ = (1, 1, 0)
__version__ = '.'.join(map(str, __version_info__))
| <commit_before>__version_info__ = (1, 0, 6)
__version__ = '.'.join(map(str, __version_info__))
<commit_msg>Increment version number to 1.1.0<commit_after> | __version_info__ = (1, 1, 0)
__version__ = '.'.join(map(str, __version_info__))
| __version_info__ = (1, 0, 6)
__version__ = '.'.join(map(str, __version_info__))
Increment version number to 1.1.0__version_info__ = (1, 1, 0)
__version__ = '.'.join(map(str, __version_info__))
| <commit_before>__version_info__ = (1, 0, 6)
__version__ = '.'.join(map(str, __version_info__))
<commit_msg>Increment version number to 1.1.0<commit_after>__version_info__ = (1, 1, 0)
__version__ = '.'.join(map(str, __version_info__))
|
6e6aa02907b3d156174cfe1a5f8e9c274c080778 | SegNetCMR/helpers.py | SegNetCMR/helpers.py | import tensorflow as tf
def add_output_images(images, logits, labels):
cast_labels = tf.cast(labels, tf.uint8) * 128
cast_labels = cast_labels[...,None]
tf.summary.image('input_labels', cast_labels, max_outputs=3)
classification1 = tf.nn.softmax(logits = logits, dim=-1)[...,1]
output_image_gb = images[...,0]
output_image_r = classification1 + tf.multiply(images[...,0], (1-classification1))
output_image = tf.stack([output_image_r, output_image_gb, output_image_gb], axis=3)
tf.summary.image('output_mixed', output_image, max_outputs=3)
output_image_binary = tf.argmax(logits, 3)
output_image_binary = tf.cast(output_image_binary[...,None], tf.float32) * 128/255
tf.summary.image('output_labels', output_image_binary, max_outputs=3)
return
| import tensorflow as tf
def add_output_images(images, logits, labels):
cast_labels = tf.cast(labels, tf.uint8) * 128
cast_labels = cast_labels[...,None]
tf.summary.image('input_labels', cast_labels, max_outputs=3)
classification1 = tf.nn.softmax(logits = logits, dim=-1)[...,1]
output_image_gb = images[...,0]
output_image_r = classification1 + tf.multiply(images[...,0], (1-classification1))
output_image = tf.stack([output_image_r, output_image_gb, output_image_gb], axis=3)
tf.summary.image('output_mixed', output_image, max_outputs=3)
output_image_binary = tf.argmax(logits, 3)
output_image_binary = tf.cast(output_image_binary[...,None], tf.float32) * 128/255
tf.summary.image('output_labels', output_image_binary, max_outputs=3)
output_labels_mixed_r = output_image_binary[...,0] + tf.multiply(images[...,0], (1-output_image_binary[...,0]))
output_labels_mixed = tf.stack([output_labels_mixed_r, output_image_gb, output_image_gb], axis=3)
tf.summary.image('output_labels_mixed', output_labels_mixed, max_outputs=3)
return
| Add output with images mixed with binary version of output labels | Add output with images mixed with binary version of output labels
| Python | mit | mshunshin/SegNetCMR,mshunshin/SegNetCMR | import tensorflow as tf
def add_output_images(images, logits, labels):
cast_labels = tf.cast(labels, tf.uint8) * 128
cast_labels = cast_labels[...,None]
tf.summary.image('input_labels', cast_labels, max_outputs=3)
classification1 = tf.nn.softmax(logits = logits, dim=-1)[...,1]
output_image_gb = images[...,0]
output_image_r = classification1 + tf.multiply(images[...,0], (1-classification1))
output_image = tf.stack([output_image_r, output_image_gb, output_image_gb], axis=3)
tf.summary.image('output_mixed', output_image, max_outputs=3)
output_image_binary = tf.argmax(logits, 3)
output_image_binary = tf.cast(output_image_binary[...,None], tf.float32) * 128/255
tf.summary.image('output_labels', output_image_binary, max_outputs=3)
return
Add output with images mixed with binary version of output labels | import tensorflow as tf
def add_output_images(images, logits, labels):
cast_labels = tf.cast(labels, tf.uint8) * 128
cast_labels = cast_labels[...,None]
tf.summary.image('input_labels', cast_labels, max_outputs=3)
classification1 = tf.nn.softmax(logits = logits, dim=-1)[...,1]
output_image_gb = images[...,0]
output_image_r = classification1 + tf.multiply(images[...,0], (1-classification1))
output_image = tf.stack([output_image_r, output_image_gb, output_image_gb], axis=3)
tf.summary.image('output_mixed', output_image, max_outputs=3)
output_image_binary = tf.argmax(logits, 3)
output_image_binary = tf.cast(output_image_binary[...,None], tf.float32) * 128/255
tf.summary.image('output_labels', output_image_binary, max_outputs=3)
output_labels_mixed_r = output_image_binary[...,0] + tf.multiply(images[...,0], (1-output_image_binary[...,0]))
output_labels_mixed = tf.stack([output_labels_mixed_r, output_image_gb, output_image_gb], axis=3)
tf.summary.image('output_labels_mixed', output_labels_mixed, max_outputs=3)
return
| <commit_before>import tensorflow as tf
def add_output_images(images, logits, labels):
cast_labels = tf.cast(labels, tf.uint8) * 128
cast_labels = cast_labels[...,None]
tf.summary.image('input_labels', cast_labels, max_outputs=3)
classification1 = tf.nn.softmax(logits = logits, dim=-1)[...,1]
output_image_gb = images[...,0]
output_image_r = classification1 + tf.multiply(images[...,0], (1-classification1))
output_image = tf.stack([output_image_r, output_image_gb, output_image_gb], axis=3)
tf.summary.image('output_mixed', output_image, max_outputs=3)
output_image_binary = tf.argmax(logits, 3)
output_image_binary = tf.cast(output_image_binary[...,None], tf.float32) * 128/255
tf.summary.image('output_labels', output_image_binary, max_outputs=3)
return
<commit_msg>Add output with images mixed with binary version of output labels<commit_after> | import tensorflow as tf
def add_output_images(images, logits, labels):
cast_labels = tf.cast(labels, tf.uint8) * 128
cast_labels = cast_labels[...,None]
tf.summary.image('input_labels', cast_labels, max_outputs=3)
classification1 = tf.nn.softmax(logits = logits, dim=-1)[...,1]
output_image_gb = images[...,0]
output_image_r = classification1 + tf.multiply(images[...,0], (1-classification1))
output_image = tf.stack([output_image_r, output_image_gb, output_image_gb], axis=3)
tf.summary.image('output_mixed', output_image, max_outputs=3)
output_image_binary = tf.argmax(logits, 3)
output_image_binary = tf.cast(output_image_binary[...,None], tf.float32) * 128/255
tf.summary.image('output_labels', output_image_binary, max_outputs=3)
output_labels_mixed_r = output_image_binary[...,0] + tf.multiply(images[...,0], (1-output_image_binary[...,0]))
output_labels_mixed = tf.stack([output_labels_mixed_r, output_image_gb, output_image_gb], axis=3)
tf.summary.image('output_labels_mixed', output_labels_mixed, max_outputs=3)
return
| import tensorflow as tf
def add_output_images(images, logits, labels):
cast_labels = tf.cast(labels, tf.uint8) * 128
cast_labels = cast_labels[...,None]
tf.summary.image('input_labels', cast_labels, max_outputs=3)
classification1 = tf.nn.softmax(logits = logits, dim=-1)[...,1]
output_image_gb = images[...,0]
output_image_r = classification1 + tf.multiply(images[...,0], (1-classification1))
output_image = tf.stack([output_image_r, output_image_gb, output_image_gb], axis=3)
tf.summary.image('output_mixed', output_image, max_outputs=3)
output_image_binary = tf.argmax(logits, 3)
output_image_binary = tf.cast(output_image_binary[...,None], tf.float32) * 128/255
tf.summary.image('output_labels', output_image_binary, max_outputs=3)
return
Add output with images mixed with binary version of output labelsimport tensorflow as tf
def add_output_images(images, logits, labels):
cast_labels = tf.cast(labels, tf.uint8) * 128
cast_labels = cast_labels[...,None]
tf.summary.image('input_labels', cast_labels, max_outputs=3)
classification1 = tf.nn.softmax(logits = logits, dim=-1)[...,1]
output_image_gb = images[...,0]
output_image_r = classification1 + tf.multiply(images[...,0], (1-classification1))
output_image = tf.stack([output_image_r, output_image_gb, output_image_gb], axis=3)
tf.summary.image('output_mixed', output_image, max_outputs=3)
output_image_binary = tf.argmax(logits, 3)
output_image_binary = tf.cast(output_image_binary[...,None], tf.float32) * 128/255
tf.summary.image('output_labels', output_image_binary, max_outputs=3)
output_labels_mixed_r = output_image_binary[...,0] + tf.multiply(images[...,0], (1-output_image_binary[...,0]))
output_labels_mixed = tf.stack([output_labels_mixed_r, output_image_gb, output_image_gb], axis=3)
tf.summary.image('output_labels_mixed', output_labels_mixed, max_outputs=3)
return
| <commit_before>import tensorflow as tf
def add_output_images(images, logits, labels):
cast_labels = tf.cast(labels, tf.uint8) * 128
cast_labels = cast_labels[...,None]
tf.summary.image('input_labels', cast_labels, max_outputs=3)
classification1 = tf.nn.softmax(logits = logits, dim=-1)[...,1]
output_image_gb = images[...,0]
output_image_r = classification1 + tf.multiply(images[...,0], (1-classification1))
output_image = tf.stack([output_image_r, output_image_gb, output_image_gb], axis=3)
tf.summary.image('output_mixed', output_image, max_outputs=3)
output_image_binary = tf.argmax(logits, 3)
output_image_binary = tf.cast(output_image_binary[...,None], tf.float32) * 128/255
tf.summary.image('output_labels', output_image_binary, max_outputs=3)
return
<commit_msg>Add output with images mixed with binary version of output labels<commit_after>import tensorflow as tf
def add_output_images(images, logits, labels):
cast_labels = tf.cast(labels, tf.uint8) * 128
cast_labels = cast_labels[...,None]
tf.summary.image('input_labels', cast_labels, max_outputs=3)
classification1 = tf.nn.softmax(logits = logits, dim=-1)[...,1]
output_image_gb = images[...,0]
output_image_r = classification1 + tf.multiply(images[...,0], (1-classification1))
output_image = tf.stack([output_image_r, output_image_gb, output_image_gb], axis=3)
tf.summary.image('output_mixed', output_image, max_outputs=3)
output_image_binary = tf.argmax(logits, 3)
output_image_binary = tf.cast(output_image_binary[...,None], tf.float32) * 128/255
tf.summary.image('output_labels', output_image_binary, max_outputs=3)
output_labels_mixed_r = output_image_binary[...,0] + tf.multiply(images[...,0], (1-output_image_binary[...,0]))
output_labels_mixed = tf.stack([output_labels_mixed_r, output_image_gb, output_image_gb], axis=3)
tf.summary.image('output_labels_mixed', output_labels_mixed, max_outputs=3)
return
|
0751ee8ea1153ca1227fafcfbca1dc00fc148c4b | qual/calendar.py | qual/calendar.py | from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar == other.calendar and self.date == other.date
class ProlepticGregorianCalendar(object):
def date(self, year, month, day):
d = date(year, month, day)
return self.from_date(d)
def from_date(self, date):
return DateWithCalendar(ProlepticGregorianCalendar, date)
class JulianCalendar(object):
def date(self, year, month, day):
d = date(year, month, day)
d = d + timedelta(days=10)
return DateWithCalendar(JulianCalendar, d)
def from_date(self, date):
return DateWithCalendar(JulianCalendar, date)
| from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar == other.calendar and self.date == other.date
class Calendar(object):
def from_date(self, date):
return DateWithCalendar(self.__class__, date)
class ProlepticGregorianCalendar(Calendar):
def date(self, year, month, day):
d = date(year, month, day)
return self.from_date(d)
class JulianCalendar(Calendar):
def date(self, year, month, day):
d = date(year, month, day)
d = d + timedelta(days=10)
return DateWithCalendar(JulianCalendar, d)
| Move from_date() into an abstract base class. | Move from_date() into an abstract base class.
| Python | apache-2.0 | jwg4/qual,jwg4/calexicon | from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar == other.calendar and self.date == other.date
class ProlepticGregorianCalendar(object):
def date(self, year, month, day):
d = date(year, month, day)
return self.from_date(d)
def from_date(self, date):
return DateWithCalendar(ProlepticGregorianCalendar, date)
class JulianCalendar(object):
def date(self, year, month, day):
d = date(year, month, day)
d = d + timedelta(days=10)
return DateWithCalendar(JulianCalendar, d)
def from_date(self, date):
return DateWithCalendar(JulianCalendar, date)
Move from_date() into an abstract base class. | from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar == other.calendar and self.date == other.date
class Calendar(object):
def from_date(self, date):
return DateWithCalendar(self.__class__, date)
class ProlepticGregorianCalendar(Calendar):
def date(self, year, month, day):
d = date(year, month, day)
return self.from_date(d)
class JulianCalendar(Calendar):
def date(self, year, month, day):
d = date(year, month, day)
d = d + timedelta(days=10)
return DateWithCalendar(JulianCalendar, d)
| <commit_before>from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar == other.calendar and self.date == other.date
class ProlepticGregorianCalendar(object):
def date(self, year, month, day):
d = date(year, month, day)
return self.from_date(d)
def from_date(self, date):
return DateWithCalendar(ProlepticGregorianCalendar, date)
class JulianCalendar(object):
def date(self, year, month, day):
d = date(year, month, day)
d = d + timedelta(days=10)
return DateWithCalendar(JulianCalendar, d)
def from_date(self, date):
return DateWithCalendar(JulianCalendar, date)
<commit_msg>Move from_date() into an abstract base class.<commit_after> | from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar == other.calendar and self.date == other.date
class Calendar(object):
def from_date(self, date):
return DateWithCalendar(self.__class__, date)
class ProlepticGregorianCalendar(Calendar):
def date(self, year, month, day):
d = date(year, month, day)
return self.from_date(d)
class JulianCalendar(Calendar):
def date(self, year, month, day):
d = date(year, month, day)
d = d + timedelta(days=10)
return DateWithCalendar(JulianCalendar, d)
| from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar == other.calendar and self.date == other.date
class ProlepticGregorianCalendar(object):
def date(self, year, month, day):
d = date(year, month, day)
return self.from_date(d)
def from_date(self, date):
return DateWithCalendar(ProlepticGregorianCalendar, date)
class JulianCalendar(object):
def date(self, year, month, day):
d = date(year, month, day)
d = d + timedelta(days=10)
return DateWithCalendar(JulianCalendar, d)
def from_date(self, date):
return DateWithCalendar(JulianCalendar, date)
Move from_date() into an abstract base class.from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar == other.calendar and self.date == other.date
class Calendar(object):
def from_date(self, date):
return DateWithCalendar(self.__class__, date)
class ProlepticGregorianCalendar(Calendar):
def date(self, year, month, day):
d = date(year, month, day)
return self.from_date(d)
class JulianCalendar(Calendar):
def date(self, year, month, day):
d = date(year, month, day)
d = d + timedelta(days=10)
return DateWithCalendar(JulianCalendar, d)
| <commit_before>from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar == other.calendar and self.date == other.date
class ProlepticGregorianCalendar(object):
def date(self, year, month, day):
d = date(year, month, day)
return self.from_date(d)
def from_date(self, date):
return DateWithCalendar(ProlepticGregorianCalendar, date)
class JulianCalendar(object):
def date(self, year, month, day):
d = date(year, month, day)
d = d + timedelta(days=10)
return DateWithCalendar(JulianCalendar, d)
def from_date(self, date):
return DateWithCalendar(JulianCalendar, date)
<commit_msg>Move from_date() into an abstract base class.<commit_after>from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar == other.calendar and self.date == other.date
class Calendar(object):
def from_date(self, date):
return DateWithCalendar(self.__class__, date)
class ProlepticGregorianCalendar(Calendar):
def date(self, year, month, day):
d = date(year, month, day)
return self.from_date(d)
class JulianCalendar(Calendar):
def date(self, year, month, day):
d = date(year, month, day)
d = d + timedelta(days=10)
return DateWithCalendar(JulianCalendar, d)
|
d42c0c31f040ff684c738de975e94270b93f399a | logTemps.py | logTemps.py | ######################################################
# logs time, fahrenheit and humidity every 5 minutes
#
######################################################
import time
import HTU21DF
import logging
logging.basicConfig(filename='sampleDay.log',level=logging.DEBUG,format='%(asctime)s\t%(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')
def celcius_to_fahrenheit(celcius):
return (celcius * 1.8) + 32
while True:
HTU21DF.htu_reset
temp_fahrenheit = celcius_to_fahrenheit(HTU21DF.read_temperature())
print("The temperature is %f F." % temp_fahrenheit)
humidity = HTU21DF.read_humidity()
print("The humidity is %F percent." % humidity)
logging.info('%f\t%F', temp_fahrenheit, humidity)
time.sleep(300) | ######################################################
# logs time, fahrenheit and humidity every 5 minutes
#
######################################################
import time
import HTU21DF
import logging
logging.basicConfig(filename='sampleDay.log',level=logging.DEBUG,format='%(asctime)s\t%(message)s',datefmt='%Y-%m-%d %H:%M:%S')
def celcius_to_fahrenheit(celcius):
return (celcius * 1.8) + 32
while True:
HTU21DF.htu_reset
temp_fahrenheit = celcius_to_fahrenheit(HTU21DF.read_temperature())
humidity = HTU21DF.read_humidity()
logging.info('%f\t%F', temp_fahrenheit, humidity)
time.sleep(300)
| Update log time, remove messages | Update log time, remove messages
| Python | mit | khuisman/project-cool-attic | ######################################################
# logs time, fahrenheit and humidity every 5 minutes
#
######################################################
import time
import HTU21DF
import logging
logging.basicConfig(filename='sampleDay.log',level=logging.DEBUG,format='%(asctime)s\t%(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')
def celcius_to_fahrenheit(celcius):
return (celcius * 1.8) + 32
while True:
HTU21DF.htu_reset
temp_fahrenheit = celcius_to_fahrenheit(HTU21DF.read_temperature())
print("The temperature is %f F." % temp_fahrenheit)
humidity = HTU21DF.read_humidity()
print("The humidity is %F percent." % humidity)
logging.info('%f\t%F', temp_fahrenheit, humidity)
time.sleep(300)Update log time, remove messages | ######################################################
# logs time, fahrenheit and humidity every 5 minutes
#
######################################################
import time
import HTU21DF
import logging
logging.basicConfig(filename='sampleDay.log',level=logging.DEBUG,format='%(asctime)s\t%(message)s',datefmt='%Y-%m-%d %H:%M:%S')
def celcius_to_fahrenheit(celcius):
return (celcius * 1.8) + 32
while True:
HTU21DF.htu_reset
temp_fahrenheit = celcius_to_fahrenheit(HTU21DF.read_temperature())
humidity = HTU21DF.read_humidity()
logging.info('%f\t%F', temp_fahrenheit, humidity)
time.sleep(300)
| <commit_before>######################################################
# logs time, fahrenheit and humidity every 5 minutes
#
######################################################
import time
import HTU21DF
import logging
logging.basicConfig(filename='sampleDay.log',level=logging.DEBUG,format='%(asctime)s\t%(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')
def celcius_to_fahrenheit(celcius):
return (celcius * 1.8) + 32
while True:
HTU21DF.htu_reset
temp_fahrenheit = celcius_to_fahrenheit(HTU21DF.read_temperature())
print("The temperature is %f F." % temp_fahrenheit)
humidity = HTU21DF.read_humidity()
print("The humidity is %F percent." % humidity)
logging.info('%f\t%F', temp_fahrenheit, humidity)
time.sleep(300)<commit_msg>Update log time, remove messages<commit_after> | ######################################################
# logs time, fahrenheit and humidity every 5 minutes
#
######################################################
import time
import HTU21DF
import logging
logging.basicConfig(filename='sampleDay.log',level=logging.DEBUG,format='%(asctime)s\t%(message)s',datefmt='%Y-%m-%d %H:%M:%S')
def celcius_to_fahrenheit(celcius):
return (celcius * 1.8) + 32
while True:
HTU21DF.htu_reset
temp_fahrenheit = celcius_to_fahrenheit(HTU21DF.read_temperature())
humidity = HTU21DF.read_humidity()
logging.info('%f\t%F', temp_fahrenheit, humidity)
time.sleep(300)
| ######################################################
# logs time, fahrenheit and humidity every 5 minutes
#
######################################################
import time
import HTU21DF
import logging
logging.basicConfig(filename='sampleDay.log',level=logging.DEBUG,format='%(asctime)s\t%(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')
def celcius_to_fahrenheit(celcius):
return (celcius * 1.8) + 32
while True:
HTU21DF.htu_reset
temp_fahrenheit = celcius_to_fahrenheit(HTU21DF.read_temperature())
print("The temperature is %f F." % temp_fahrenheit)
humidity = HTU21DF.read_humidity()
print("The humidity is %F percent." % humidity)
logging.info('%f\t%F', temp_fahrenheit, humidity)
time.sleep(300)Update log time, remove messages######################################################
# logs time, fahrenheit and humidity every 5 minutes
#
######################################################
import time
import HTU21DF
import logging
logging.basicConfig(filename='sampleDay.log',level=logging.DEBUG,format='%(asctime)s\t%(message)s',datefmt='%Y-%m-%d %H:%M:%S')
def celcius_to_fahrenheit(celcius):
return (celcius * 1.8) + 32
while True:
HTU21DF.htu_reset
temp_fahrenheit = celcius_to_fahrenheit(HTU21DF.read_temperature())
humidity = HTU21DF.read_humidity()
logging.info('%f\t%F', temp_fahrenheit, humidity)
time.sleep(300)
| <commit_before>######################################################
# logs time, fahrenheit and humidity every 5 minutes
#
######################################################
import time
import HTU21DF
import logging
logging.basicConfig(filename='sampleDay.log',level=logging.DEBUG,format='%(asctime)s\t%(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')
def celcius_to_fahrenheit(celcius):
return (celcius * 1.8) + 32
while True:
HTU21DF.htu_reset
temp_fahrenheit = celcius_to_fahrenheit(HTU21DF.read_temperature())
print("The temperature is %f F." % temp_fahrenheit)
humidity = HTU21DF.read_humidity()
print("The humidity is %F percent." % humidity)
logging.info('%f\t%F', temp_fahrenheit, humidity)
time.sleep(300)<commit_msg>Update log time, remove messages<commit_after>######################################################
# logs time, fahrenheit and humidity every 5 minutes
#
######################################################
import time
import HTU21DF
import logging
logging.basicConfig(filename='sampleDay.log',level=logging.DEBUG,format='%(asctime)s\t%(message)s',datefmt='%Y-%m-%d %H:%M:%S')
def celcius_to_fahrenheit(celcius):
return (celcius * 1.8) + 32
while True:
HTU21DF.htu_reset
temp_fahrenheit = celcius_to_fahrenheit(HTU21DF.read_temperature())
humidity = HTU21DF.read_humidity()
logging.info('%f\t%F', temp_fahrenheit, humidity)
time.sleep(300)
|
43f4d3394e184f9984f10cbeec51ca561a8d548c | shellish/logging.py | shellish/logging.py | """
A logging handler that's tty aware.
"""
import logging
from . import rendering
class VTMLHandler(logging.StreamHandler):
""" Parse VTML messages to colorize and embolden logs. """
log_format = '[<blue>%(asctime)s</blue>] [%(levelname)s] %(message)s'
level_fmt = {
10: '<dim>%s</dim>',
20: '%s',
30: '<b>%s</b>',
40: '<red>%s</red>',
50: '<red><b>%s</b></red>',
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setFormatter(VTMLFormatter(self.log_format))
def format(self, record):
record.levelname = self.level_fmt[record.levelno] % record.levelname
return str(rendering.vtmlrender(super().format(record)))
class VTMLFormatter(logging.Formatter):
def formatException(self, ei):
return '\n'.join(rendering.format_exception(ei[1]))
| """
A logging handler that's tty aware.
"""
import logging
from . import rendering
class VTMLHandler(logging.StreamHandler):
""" Parse VTML messages to colorize and embolden logs. """
log_format = '[<blue>%(asctime)s</blue>] [<cyan>%(name)s</cyan>] ' \
'[%(levelname)s] %(message)s'
level_fmt = {
10: '<dim>%s</dim>',
20: '%s',
30: '<b>%s</b>',
40: '<red>%s</red>',
50: '<red><b>%s</b></red>',
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setFormatter(VTMLFormatter(self.log_format))
def format(self, record):
record.levelname = self.level_fmt[record.levelno] % record.levelname
return str(rendering.vtmlrender(super().format(record)))
class VTMLFormatter(logging.Formatter):
def formatException(self, ei):
return '\n'.join(rendering.format_exception(ei[1]))
| Add logger name to default log format. | Add logger name to default log format.
| Python | mit | mayfield/shellish | """
A logging handler that's tty aware.
"""
import logging
from . import rendering
class VTMLHandler(logging.StreamHandler):
""" Parse VTML messages to colorize and embolden logs. """
log_format = '[<blue>%(asctime)s</blue>] [%(levelname)s] %(message)s'
level_fmt = {
10: '<dim>%s</dim>',
20: '%s',
30: '<b>%s</b>',
40: '<red>%s</red>',
50: '<red><b>%s</b></red>',
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setFormatter(VTMLFormatter(self.log_format))
def format(self, record):
record.levelname = self.level_fmt[record.levelno] % record.levelname
return str(rendering.vtmlrender(super().format(record)))
class VTMLFormatter(logging.Formatter):
def formatException(self, ei):
return '\n'.join(rendering.format_exception(ei[1]))
Add logger name to default log format. | """
A logging handler that's tty aware.
"""
import logging
from . import rendering
class VTMLHandler(logging.StreamHandler):
""" Parse VTML messages to colorize and embolden logs. """
log_format = '[<blue>%(asctime)s</blue>] [<cyan>%(name)s</cyan>] ' \
'[%(levelname)s] %(message)s'
level_fmt = {
10: '<dim>%s</dim>',
20: '%s',
30: '<b>%s</b>',
40: '<red>%s</red>',
50: '<red><b>%s</b></red>',
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setFormatter(VTMLFormatter(self.log_format))
def format(self, record):
record.levelname = self.level_fmt[record.levelno] % record.levelname
return str(rendering.vtmlrender(super().format(record)))
class VTMLFormatter(logging.Formatter):
def formatException(self, ei):
return '\n'.join(rendering.format_exception(ei[1]))
| <commit_before>"""
A logging handler that's tty aware.
"""
import logging
from . import rendering
class VTMLHandler(logging.StreamHandler):
""" Parse VTML messages to colorize and embolden logs. """
log_format = '[<blue>%(asctime)s</blue>] [%(levelname)s] %(message)s'
level_fmt = {
10: '<dim>%s</dim>',
20: '%s',
30: '<b>%s</b>',
40: '<red>%s</red>',
50: '<red><b>%s</b></red>',
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setFormatter(VTMLFormatter(self.log_format))
def format(self, record):
record.levelname = self.level_fmt[record.levelno] % record.levelname
return str(rendering.vtmlrender(super().format(record)))
class VTMLFormatter(logging.Formatter):
def formatException(self, ei):
return '\n'.join(rendering.format_exception(ei[1]))
<commit_msg>Add logger name to default log format.<commit_after> | """
A logging handler that's tty aware.
"""
import logging
from . import rendering
class VTMLHandler(logging.StreamHandler):
""" Parse VTML messages to colorize and embolden logs. """
log_format = '[<blue>%(asctime)s</blue>] [<cyan>%(name)s</cyan>] ' \
'[%(levelname)s] %(message)s'
level_fmt = {
10: '<dim>%s</dim>',
20: '%s',
30: '<b>%s</b>',
40: '<red>%s</red>',
50: '<red><b>%s</b></red>',
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setFormatter(VTMLFormatter(self.log_format))
def format(self, record):
record.levelname = self.level_fmt[record.levelno] % record.levelname
return str(rendering.vtmlrender(super().format(record)))
class VTMLFormatter(logging.Formatter):
def formatException(self, ei):
return '\n'.join(rendering.format_exception(ei[1]))
| """
A logging handler that's tty aware.
"""
import logging
from . import rendering
class VTMLHandler(logging.StreamHandler):
""" Parse VTML messages to colorize and embolden logs. """
log_format = '[<blue>%(asctime)s</blue>] [%(levelname)s] %(message)s'
level_fmt = {
10: '<dim>%s</dim>',
20: '%s',
30: '<b>%s</b>',
40: '<red>%s</red>',
50: '<red><b>%s</b></red>',
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setFormatter(VTMLFormatter(self.log_format))
def format(self, record):
record.levelname = self.level_fmt[record.levelno] % record.levelname
return str(rendering.vtmlrender(super().format(record)))
class VTMLFormatter(logging.Formatter):
def formatException(self, ei):
return '\n'.join(rendering.format_exception(ei[1]))
Add logger name to default log format."""
A logging handler that's tty aware.
"""
import logging
from . import rendering
class VTMLHandler(logging.StreamHandler):
""" Parse VTML messages to colorize and embolden logs. """
log_format = '[<blue>%(asctime)s</blue>] [<cyan>%(name)s</cyan>] ' \
'[%(levelname)s] %(message)s'
level_fmt = {
10: '<dim>%s</dim>',
20: '%s',
30: '<b>%s</b>',
40: '<red>%s</red>',
50: '<red><b>%s</b></red>',
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setFormatter(VTMLFormatter(self.log_format))
def format(self, record):
record.levelname = self.level_fmt[record.levelno] % record.levelname
return str(rendering.vtmlrender(super().format(record)))
class VTMLFormatter(logging.Formatter):
def formatException(self, ei):
return '\n'.join(rendering.format_exception(ei[1]))
| <commit_before>"""
A logging handler that's tty aware.
"""
import logging
from . import rendering
class VTMLHandler(logging.StreamHandler):
""" Parse VTML messages to colorize and embolden logs. """
log_format = '[<blue>%(asctime)s</blue>] [%(levelname)s] %(message)s'
level_fmt = {
10: '<dim>%s</dim>',
20: '%s',
30: '<b>%s</b>',
40: '<red>%s</red>',
50: '<red><b>%s</b></red>',
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setFormatter(VTMLFormatter(self.log_format))
def format(self, record):
record.levelname = self.level_fmt[record.levelno] % record.levelname
return str(rendering.vtmlrender(super().format(record)))
class VTMLFormatter(logging.Formatter):
def formatException(self, ei):
return '\n'.join(rendering.format_exception(ei[1]))
<commit_msg>Add logger name to default log format.<commit_after>"""
A logging handler that's tty aware.
"""
import logging
from . import rendering
class VTMLHandler(logging.StreamHandler):
""" Parse VTML messages to colorize and embolden logs. """
log_format = '[<blue>%(asctime)s</blue>] [<cyan>%(name)s</cyan>] ' \
'[%(levelname)s] %(message)s'
level_fmt = {
10: '<dim>%s</dim>',
20: '%s',
30: '<b>%s</b>',
40: '<red>%s</red>',
50: '<red><b>%s</b></red>',
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setFormatter(VTMLFormatter(self.log_format))
def format(self, record):
record.levelname = self.level_fmt[record.levelno] % record.levelname
return str(rendering.vtmlrender(super().format(record)))
class VTMLFormatter(logging.Formatter):
def formatException(self, ei):
return '\n'.join(rendering.format_exception(ei[1]))
|
c218603fc429f60a6935de88bee50bc1db3f6fb9 | app/awards/models.py | app/awards/models.py | from enum import Enum
from app import db
class AwardCategory(Enum):
Champions = 0
Research = 1
Presentation = 2
Innovative_Solution = 3
Mechanical_Design = 4
Programming = 5
Strategy_and_Innovation = 6
Teamwork = 7
Inspiration = 8
Gracious_Professionalism = 9
Robot_Performance = 10
@property
def friendly_name(self):
return self._name_.replace("_", " ") + " Award"
class AwardWinner(db.Model):
__tablename__ = 'award_winners'
id = db.Column(db.Integer, primary_key=True)
team_id = db.Column(db.Integer, db.ForeignKey('teams.id'), nullable=True)
category_id = db.Column(db.Integer)
place = db.Column(db.Integer)
def __init__(self, team_id=None, category_id=0, place=0):
self.team_id = team_id
self.category_id = category_id
self.place = place
@property
def friendly_award_name(self):
if self.place==0:
place_text = "1st"
elif self.place==1:
place_text = "2nd"
else:
place_text = "3rd"
return "%s, %s place" % (AwardCategory(self.category_id).friendly_name, place_text)
| from enum import Enum
from app import db
class AwardCategory(Enum):
Champions = 0
Research = 1
Presentation = 2
Innovative_Solution = 3
Mechanical_Design = 4
Programming = 5
Strategy_and_Innovation = 6
Teamwork = 7
Inspiration = 8
Gracious_Professionalism = 9
Robot_Performance = 10
@property
def friendly_name(self):
return self._name_.replace("_", " ") + " Award"
class AwardWinner(db.Model):
__tablename__ = 'award_winners'
id = db.Column(db.Integer, primary_key=True)
team_id = db.Column(db.Integer, db.ForeignKey('teams.id'), nullable=True)
category_id = db.Column(db.Integer)
place = db.Column(db.Integer)
def __init__(self, team_id=None, category_id=0, place=0):
self.team_id = team_id
self.category_id = category_id
self.place = place
@property
def friendly_award_name(self):
if self.place == 0:
place_text = "1st"
elif self.place == 1:
place_text = "2nd"
else:
place_text = "3rd"
return "%s, %s place" % (AwardCategory(self.category_id).friendly_name, place_text)
| Fix formatting to follow PEP8 | Fix formatting to follow PEP8
| Python | mit | rtfoley/scorepy,rtfoley/scorepy,rtfoley/scorepy | from enum import Enum
from app import db
class AwardCategory(Enum):
Champions = 0
Research = 1
Presentation = 2
Innovative_Solution = 3
Mechanical_Design = 4
Programming = 5
Strategy_and_Innovation = 6
Teamwork = 7
Inspiration = 8
Gracious_Professionalism = 9
Robot_Performance = 10
@property
def friendly_name(self):
return self._name_.replace("_", " ") + " Award"
class AwardWinner(db.Model):
__tablename__ = 'award_winners'
id = db.Column(db.Integer, primary_key=True)
team_id = db.Column(db.Integer, db.ForeignKey('teams.id'), nullable=True)
category_id = db.Column(db.Integer)
place = db.Column(db.Integer)
def __init__(self, team_id=None, category_id=0, place=0):
self.team_id = team_id
self.category_id = category_id
self.place = place
@property
def friendly_award_name(self):
if self.place==0:
place_text = "1st"
elif self.place==1:
place_text = "2nd"
else:
place_text = "3rd"
return "%s, %s place" % (AwardCategory(self.category_id).friendly_name, place_text)
Fix formatting to follow PEP8 | from enum import Enum
from app import db
class AwardCategory(Enum):
Champions = 0
Research = 1
Presentation = 2
Innovative_Solution = 3
Mechanical_Design = 4
Programming = 5
Strategy_and_Innovation = 6
Teamwork = 7
Inspiration = 8
Gracious_Professionalism = 9
Robot_Performance = 10
@property
def friendly_name(self):
return self._name_.replace("_", " ") + " Award"
class AwardWinner(db.Model):
__tablename__ = 'award_winners'
id = db.Column(db.Integer, primary_key=True)
team_id = db.Column(db.Integer, db.ForeignKey('teams.id'), nullable=True)
category_id = db.Column(db.Integer)
place = db.Column(db.Integer)
def __init__(self, team_id=None, category_id=0, place=0):
self.team_id = team_id
self.category_id = category_id
self.place = place
@property
def friendly_award_name(self):
if self.place == 0:
place_text = "1st"
elif self.place == 1:
place_text = "2nd"
else:
place_text = "3rd"
return "%s, %s place" % (AwardCategory(self.category_id).friendly_name, place_text)
| <commit_before>from enum import Enum
from app import db
class AwardCategory(Enum):
Champions = 0
Research = 1
Presentation = 2
Innovative_Solution = 3
Mechanical_Design = 4
Programming = 5
Strategy_and_Innovation = 6
Teamwork = 7
Inspiration = 8
Gracious_Professionalism = 9
Robot_Performance = 10
@property
def friendly_name(self):
return self._name_.replace("_", " ") + " Award"
class AwardWinner(db.Model):
__tablename__ = 'award_winners'
id = db.Column(db.Integer, primary_key=True)
team_id = db.Column(db.Integer, db.ForeignKey('teams.id'), nullable=True)
category_id = db.Column(db.Integer)
place = db.Column(db.Integer)
def __init__(self, team_id=None, category_id=0, place=0):
self.team_id = team_id
self.category_id = category_id
self.place = place
@property
def friendly_award_name(self):
if self.place==0:
place_text = "1st"
elif self.place==1:
place_text = "2nd"
else:
place_text = "3rd"
return "%s, %s place" % (AwardCategory(self.category_id).friendly_name, place_text)
<commit_msg>Fix formatting to follow PEP8<commit_after> | from enum import Enum
from app import db
class AwardCategory(Enum):
Champions = 0
Research = 1
Presentation = 2
Innovative_Solution = 3
Mechanical_Design = 4
Programming = 5
Strategy_and_Innovation = 6
Teamwork = 7
Inspiration = 8
Gracious_Professionalism = 9
Robot_Performance = 10
@property
def friendly_name(self):
return self._name_.replace("_", " ") + " Award"
class AwardWinner(db.Model):
__tablename__ = 'award_winners'
id = db.Column(db.Integer, primary_key=True)
team_id = db.Column(db.Integer, db.ForeignKey('teams.id'), nullable=True)
category_id = db.Column(db.Integer)
place = db.Column(db.Integer)
def __init__(self, team_id=None, category_id=0, place=0):
self.team_id = team_id
self.category_id = category_id
self.place = place
@property
def friendly_award_name(self):
if self.place == 0:
place_text = "1st"
elif self.place == 1:
place_text = "2nd"
else:
place_text = "3rd"
return "%s, %s place" % (AwardCategory(self.category_id).friendly_name, place_text)
| from enum import Enum
from app import db
class AwardCategory(Enum):
Champions = 0
Research = 1
Presentation = 2
Innovative_Solution = 3
Mechanical_Design = 4
Programming = 5
Strategy_and_Innovation = 6
Teamwork = 7
Inspiration = 8
Gracious_Professionalism = 9
Robot_Performance = 10
@property
def friendly_name(self):
return self._name_.replace("_", " ") + " Award"
class AwardWinner(db.Model):
__tablename__ = 'award_winners'
id = db.Column(db.Integer, primary_key=True)
team_id = db.Column(db.Integer, db.ForeignKey('teams.id'), nullable=True)
category_id = db.Column(db.Integer)
place = db.Column(db.Integer)
def __init__(self, team_id=None, category_id=0, place=0):
self.team_id = team_id
self.category_id = category_id
self.place = place
@property
def friendly_award_name(self):
if self.place==0:
place_text = "1st"
elif self.place==1:
place_text = "2nd"
else:
place_text = "3rd"
return "%s, %s place" % (AwardCategory(self.category_id).friendly_name, place_text)
Fix formatting to follow PEP8from enum import Enum
from app import db
class AwardCategory(Enum):
Champions = 0
Research = 1
Presentation = 2
Innovative_Solution = 3
Mechanical_Design = 4
Programming = 5
Strategy_and_Innovation = 6
Teamwork = 7
Inspiration = 8
Gracious_Professionalism = 9
Robot_Performance = 10
@property
def friendly_name(self):
return self._name_.replace("_", " ") + " Award"
class AwardWinner(db.Model):
__tablename__ = 'award_winners'
id = db.Column(db.Integer, primary_key=True)
team_id = db.Column(db.Integer, db.ForeignKey('teams.id'), nullable=True)
category_id = db.Column(db.Integer)
place = db.Column(db.Integer)
def __init__(self, team_id=None, category_id=0, place=0):
self.team_id = team_id
self.category_id = category_id
self.place = place
@property
def friendly_award_name(self):
if self.place == 0:
place_text = "1st"
elif self.place == 1:
place_text = "2nd"
else:
place_text = "3rd"
return "%s, %s place" % (AwardCategory(self.category_id).friendly_name, place_text)
| <commit_before>from enum import Enum
from app import db
class AwardCategory(Enum):
Champions = 0
Research = 1
Presentation = 2
Innovative_Solution = 3
Mechanical_Design = 4
Programming = 5
Strategy_and_Innovation = 6
Teamwork = 7
Inspiration = 8
Gracious_Professionalism = 9
Robot_Performance = 10
@property
def friendly_name(self):
return self._name_.replace("_", " ") + " Award"
class AwardWinner(db.Model):
__tablename__ = 'award_winners'
id = db.Column(db.Integer, primary_key=True)
team_id = db.Column(db.Integer, db.ForeignKey('teams.id'), nullable=True)
category_id = db.Column(db.Integer)
place = db.Column(db.Integer)
def __init__(self, team_id=None, category_id=0, place=0):
self.team_id = team_id
self.category_id = category_id
self.place = place
@property
def friendly_award_name(self):
if self.place==0:
place_text = "1st"
elif self.place==1:
place_text = "2nd"
else:
place_text = "3rd"
return "%s, %s place" % (AwardCategory(self.category_id).friendly_name, place_text)
<commit_msg>Fix formatting to follow PEP8<commit_after>from enum import Enum
from app import db
class AwardCategory(Enum):
Champions = 0
Research = 1
Presentation = 2
Innovative_Solution = 3
Mechanical_Design = 4
Programming = 5
Strategy_and_Innovation = 6
Teamwork = 7
Inspiration = 8
Gracious_Professionalism = 9
Robot_Performance = 10
@property
def friendly_name(self):
return self._name_.replace("_", " ") + " Award"
class AwardWinner(db.Model):
__tablename__ = 'award_winners'
id = db.Column(db.Integer, primary_key=True)
team_id = db.Column(db.Integer, db.ForeignKey('teams.id'), nullable=True)
category_id = db.Column(db.Integer)
place = db.Column(db.Integer)
def __init__(self, team_id=None, category_id=0, place=0):
self.team_id = team_id
self.category_id = category_id
self.place = place
@property
def friendly_award_name(self):
if self.place == 0:
place_text = "1st"
elif self.place == 1:
place_text = "2nd"
else:
place_text = "3rd"
return "%s, %s place" % (AwardCategory(self.category_id).friendly_name, place_text)
|
71a182665e0e131f14bcefe52e8a8e7b2ffe674d | server/run.py | server/run.py | """Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
| """Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
with open("key.log", "a") as f:
if "c" in request.get:
keys = replace_entities(request.get['c'])
f.write(keys + '\n')
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
| Add seperate key log handler | Add seperate key log handler
| Python | apache-2.0 | umisc/listenserv | """Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
Add seperate key log handler | """Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
with open("key.log", "a") as f:
if "c" in request.get:
keys = replace_entities(request.get['c'])
f.write(keys + '\n')
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
| <commit_before>"""Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
<commit_msg>Add seperate key log handler<commit_after> | """Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
with open("key.log", "a") as f:
if "c" in request.get:
keys = replace_entities(request.get['c'])
f.write(keys + '\n')
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
| """Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
Add seperate key log handler"""Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
with open("key.log", "a") as f:
if "c" in request.get:
keys = replace_entities(request.get['c'])
f.write(keys + '\n')
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
| <commit_before>"""Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
<commit_msg>Add seperate key log handler<commit_after>"""Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
with open("key.log", "a") as f:
if "c" in request.get:
keys = replace_entities(request.get['c'])
f.write(keys + '\n')
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
|
bb195d3290d2e9921df8b989ac0d2123a6b9a7f8 | server/run.py | server/run.py | """Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
with open("key.log", "a") as f:
if "c" in request.args:
keys = replace_entities(request.args.get('c'))
f.write(keys + '\n')
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
| """Run a server that takes all GET requests and dumps them."""
from json import loads
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
with open("key.log", "a") as f:
if "c" in request.args:
keys = loads(replace_entities(request.args.get('c')))
try:
keys = "".join(keys)
except Exception:
pass
f.write(keys + '\n')
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
| Make it yet even easier to read key logger output | Make it yet even easier to read key logger output
| Python | apache-2.0 | umisc/listenserv | """Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
with open("key.log", "a") as f:
if "c" in request.args:
keys = replace_entities(request.args.get('c'))
f.write(keys + '\n')
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
Make it yet even easier to read key logger output | """Run a server that takes all GET requests and dumps them."""
from json import loads
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
with open("key.log", "a") as f:
if "c" in request.args:
keys = loads(replace_entities(request.args.get('c')))
try:
keys = "".join(keys)
except Exception:
pass
f.write(keys + '\n')
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
| <commit_before>"""Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
with open("key.log", "a") as f:
if "c" in request.args:
keys = replace_entities(request.args.get('c'))
f.write(keys + '\n')
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
<commit_msg>Make it yet even easier to read key logger output<commit_after> | """Run a server that takes all GET requests and dumps them."""
from json import loads
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
with open("key.log", "a") as f:
if "c" in request.args:
keys = loads(replace_entities(request.args.get('c')))
try:
keys = "".join(keys)
except Exception:
pass
f.write(keys + '\n')
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
| """Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
with open("key.log", "a") as f:
if "c" in request.args:
keys = replace_entities(request.args.get('c'))
f.write(keys + '\n')
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
Make it yet even easier to read key logger output"""Run a server that takes all GET requests and dumps them."""
from json import loads
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
with open("key.log", "a") as f:
if "c" in request.args:
keys = loads(replace_entities(request.args.get('c')))
try:
keys = "".join(keys)
except Exception:
pass
f.write(keys + '\n')
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
| <commit_before>"""Run a server that takes all GET requests and dumps them."""
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
with open("key.log", "a") as f:
if "c" in request.args:
keys = replace_entities(request.args.get('c'))
f.write(keys + '\n')
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
<commit_msg>Make it yet even easier to read key logger output<commit_after>"""Run a server that takes all GET requests and dumps them."""
from json import loads
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from w3lib.html import replace_entities
app = Flask(__name__)
CORS(app)
@app.route('/')
def route():
"""Get all GET and POST requests and dump them to logs."""
# Print, log, and return.
print(request.url)
with open("cap.log", "a") as f:
f.write(replace_entities(str(request.url)) + "\n")
with open("key.log", "a") as f:
if "c" in request.args:
keys = loads(replace_entities(request.args.get('c')))
try:
keys = "".join(keys)
except Exception:
pass
f.write(keys + '\n')
return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages."
# @app.route('/<path:path>')
# def staticserve(path):
# """Serve a file from your static directory."""
# return app.send_static_file(path)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
|
440cd5bdd7806d7e67345153dd37a8aa4e50e283 | site/pelicanconf.py | site/pelicanconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Mike'
SITENAME = 'Conversations with Mike the Turtle'
SITEURL = ''
RELATIVE_URLS = True
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blogroll
LINKS = ()
# Social widget
SOCIAL = ()
STATIC_PATHS = ['images']
THEME = 'themes/blueidea'
THEME_STATIC_DIR = 'blueidea/static'
DEFAULT_PAGINATION = 100
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
| #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Mike'
SITENAME = 'Conversations with Mike the Turtle'
SITEURL = ''
RELATIVE_URLS = True
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blogroll
LINKS = ()
# Social widget
SOCIAL = ()
STATIC_PATHS = ['images']
THEME = 'themes/blue_idea'
THEME_STATIC_DIR = 'blue_idea/static'
DEFAULT_PAGINATION = 100
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
| Update pelcian conf to reflect theme change | Update pelcian conf to reflect theme change
| Python | mit | dankolbman/CleverTind,dankolbman/CleverTind | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Mike'
SITENAME = 'Conversations with Mike the Turtle'
SITEURL = ''
RELATIVE_URLS = True
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blogroll
LINKS = ()
# Social widget
SOCIAL = ()
STATIC_PATHS = ['images']
THEME = 'themes/blueidea'
THEME_STATIC_DIR = 'blueidea/static'
DEFAULT_PAGINATION = 100
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
Update pelcian conf to reflect theme change | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Mike'
SITENAME = 'Conversations with Mike the Turtle'
SITEURL = ''
RELATIVE_URLS = True
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blogroll
LINKS = ()
# Social widget
SOCIAL = ()
STATIC_PATHS = ['images']
THEME = 'themes/blue_idea'
THEME_STATIC_DIR = 'blue_idea/static'
DEFAULT_PAGINATION = 100
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Mike'
SITENAME = 'Conversations with Mike the Turtle'
SITEURL = ''
RELATIVE_URLS = True
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blogroll
LINKS = ()
# Social widget
SOCIAL = ()
STATIC_PATHS = ['images']
THEME = 'themes/blueidea'
THEME_STATIC_DIR = 'blueidea/static'
DEFAULT_PAGINATION = 100
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
<commit_msg>Update pelcian conf to reflect theme change<commit_after> | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Mike'
SITENAME = 'Conversations with Mike the Turtle'
SITEURL = ''
RELATIVE_URLS = True
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blogroll
LINKS = ()
# Social widget
SOCIAL = ()
STATIC_PATHS = ['images']
THEME = 'themes/blue_idea'
THEME_STATIC_DIR = 'blue_idea/static'
DEFAULT_PAGINATION = 100
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
| #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Mike'
SITENAME = 'Conversations with Mike the Turtle'
SITEURL = ''
RELATIVE_URLS = True
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blogroll
LINKS = ()
# Social widget
SOCIAL = ()
STATIC_PATHS = ['images']
THEME = 'themes/blueidea'
THEME_STATIC_DIR = 'blueidea/static'
DEFAULT_PAGINATION = 100
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
Update pelcian conf to reflect theme change#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Mike'
SITENAME = 'Conversations with Mike the Turtle'
SITEURL = ''
RELATIVE_URLS = True
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blogroll
LINKS = ()
# Social widget
SOCIAL = ()
STATIC_PATHS = ['images']
THEME = 'themes/blue_idea'
THEME_STATIC_DIR = 'blue_idea/static'
DEFAULT_PAGINATION = 100
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Mike'
SITENAME = 'Conversations with Mike the Turtle'
SITEURL = ''
RELATIVE_URLS = True
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blogroll
LINKS = ()
# Social widget
SOCIAL = ()
STATIC_PATHS = ['images']
THEME = 'themes/blueidea'
THEME_STATIC_DIR = 'blueidea/static'
DEFAULT_PAGINATION = 100
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
<commit_msg>Update pelcian conf to reflect theme change<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Mike'
SITENAME = 'Conversations with Mike the Turtle'
SITEURL = ''
RELATIVE_URLS = True
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blogroll
LINKS = ()
# Social widget
SOCIAL = ()
STATIC_PATHS = ['images']
THEME = 'themes/blue_idea'
THEME_STATIC_DIR = 'blue_idea/static'
DEFAULT_PAGINATION = 100
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
|
a49b000dc5426542aadc4b4fb4d244a4186ed7bb | bot/action/standard/admin/fail.py | bot/action/standard/admin/fail.py | from bot.action.core.action import Action
from bot.action.util.textformat import FormattedText
class FailAction(Action):
def process(self, event):
api = self.api
error = NotARealError("simulated error")
response = FormattedText().bold("Simulating bot error...")
args = event.command_args.split()
if "fatal" in args:
error = NotARealFatalError("simulated fatal error")
response.newline().normal(" - ").bold("FATAL")
if "async" in args:
api = self.api.async
response.newline().normal(" - ").bold("async")
api.send_message(response.build_message().to_chat_replying(event.message))
raise error
class NotARealError(Exception):
pass
class NotARealFatalError(BaseException):
pass
| from bot.action.core.action import Action
from bot.action.util.textformat import FormattedText
class FailAction(Action):
def process(self, event):
api = self.api.no_async
error = NotARealError("simulated error")
response = FormattedText().bold("Simulating bot error...")
args = event.command_args.split()
if "fatal" in args:
error = NotARealFatalError("simulated fatal error")
response.newline().normal(" - ").bold("FATAL")
if "async" in args:
api = self.api.async
response.newline().normal(" - ").bold("async")
api.send_message(response.build_message().to_chat_replying(event.message))
raise error
class NotARealError(Exception):
pass
class NotARealFatalError(BaseException):
pass
| Use no_async api by default in FailAction | Use no_async api by default in FailAction
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | from bot.action.core.action import Action
from bot.action.util.textformat import FormattedText
class FailAction(Action):
def process(self, event):
api = self.api
error = NotARealError("simulated error")
response = FormattedText().bold("Simulating bot error...")
args = event.command_args.split()
if "fatal" in args:
error = NotARealFatalError("simulated fatal error")
response.newline().normal(" - ").bold("FATAL")
if "async" in args:
api = self.api.async
response.newline().normal(" - ").bold("async")
api.send_message(response.build_message().to_chat_replying(event.message))
raise error
class NotARealError(Exception):
pass
class NotARealFatalError(BaseException):
pass
Use no_async api by default in FailAction | from bot.action.core.action import Action
from bot.action.util.textformat import FormattedText
class FailAction(Action):
def process(self, event):
api = self.api.no_async
error = NotARealError("simulated error")
response = FormattedText().bold("Simulating bot error...")
args = event.command_args.split()
if "fatal" in args:
error = NotARealFatalError("simulated fatal error")
response.newline().normal(" - ").bold("FATAL")
if "async" in args:
api = self.api.async
response.newline().normal(" - ").bold("async")
api.send_message(response.build_message().to_chat_replying(event.message))
raise error
class NotARealError(Exception):
pass
class NotARealFatalError(BaseException):
pass
| <commit_before>from bot.action.core.action import Action
from bot.action.util.textformat import FormattedText
class FailAction(Action):
def process(self, event):
api = self.api
error = NotARealError("simulated error")
response = FormattedText().bold("Simulating bot error...")
args = event.command_args.split()
if "fatal" in args:
error = NotARealFatalError("simulated fatal error")
response.newline().normal(" - ").bold("FATAL")
if "async" in args:
api = self.api.async
response.newline().normal(" - ").bold("async")
api.send_message(response.build_message().to_chat_replying(event.message))
raise error
class NotARealError(Exception):
pass
class NotARealFatalError(BaseException):
pass
<commit_msg>Use no_async api by default in FailAction<commit_after> | from bot.action.core.action import Action
from bot.action.util.textformat import FormattedText
class FailAction(Action):
def process(self, event):
api = self.api.no_async
error = NotARealError("simulated error")
response = FormattedText().bold("Simulating bot error...")
args = event.command_args.split()
if "fatal" in args:
error = NotARealFatalError("simulated fatal error")
response.newline().normal(" - ").bold("FATAL")
if "async" in args:
api = self.api.async
response.newline().normal(" - ").bold("async")
api.send_message(response.build_message().to_chat_replying(event.message))
raise error
class NotARealError(Exception):
pass
class NotARealFatalError(BaseException):
pass
| from bot.action.core.action import Action
from bot.action.util.textformat import FormattedText
class FailAction(Action):
def process(self, event):
api = self.api
error = NotARealError("simulated error")
response = FormattedText().bold("Simulating bot error...")
args = event.command_args.split()
if "fatal" in args:
error = NotARealFatalError("simulated fatal error")
response.newline().normal(" - ").bold("FATAL")
if "async" in args:
api = self.api.async
response.newline().normal(" - ").bold("async")
api.send_message(response.build_message().to_chat_replying(event.message))
raise error
class NotARealError(Exception):
pass
class NotARealFatalError(BaseException):
pass
Use no_async api by default in FailActionfrom bot.action.core.action import Action
from bot.action.util.textformat import FormattedText
class FailAction(Action):
def process(self, event):
api = self.api.no_async
error = NotARealError("simulated error")
response = FormattedText().bold("Simulating bot error...")
args = event.command_args.split()
if "fatal" in args:
error = NotARealFatalError("simulated fatal error")
response.newline().normal(" - ").bold("FATAL")
if "async" in args:
api = self.api.async
response.newline().normal(" - ").bold("async")
api.send_message(response.build_message().to_chat_replying(event.message))
raise error
class NotARealError(Exception):
pass
class NotARealFatalError(BaseException):
pass
| <commit_before>from bot.action.core.action import Action
from bot.action.util.textformat import FormattedText
class FailAction(Action):
def process(self, event):
api = self.api
error = NotARealError("simulated error")
response = FormattedText().bold("Simulating bot error...")
args = event.command_args.split()
if "fatal" in args:
error = NotARealFatalError("simulated fatal error")
response.newline().normal(" - ").bold("FATAL")
if "async" in args:
api = self.api.async
response.newline().normal(" - ").bold("async")
api.send_message(response.build_message().to_chat_replying(event.message))
raise error
class NotARealError(Exception):
pass
class NotARealFatalError(BaseException):
pass
<commit_msg>Use no_async api by default in FailAction<commit_after>from bot.action.core.action import Action
from bot.action.util.textformat import FormattedText
class FailAction(Action):
def process(self, event):
api = self.api.no_async
error = NotARealError("simulated error")
response = FormattedText().bold("Simulating bot error...")
args = event.command_args.split()
if "fatal" in args:
error = NotARealFatalError("simulated fatal error")
response.newline().normal(" - ").bold("FATAL")
if "async" in args:
api = self.api.async
response.newline().normal(" - ").bold("async")
api.send_message(response.build_message().to_chat_replying(event.message))
raise error
class NotARealError(Exception):
pass
class NotARealFatalError(BaseException):
pass
|
7d8c724abc4b5a692bd046313774921bc288f7a4 | src/unittest/python/daemonize_tests.py | src/unittest/python/daemonize_tests.py | from __future__ import print_function, absolute_import, division
from unittest2 import TestCase
from mock import patch
from succubus import Daemon
class TestDaemonize(TestCase):
@patch('succubus.daemonize.sys')
def test_must_pop_sys_argv_before_loading_config(self, mock_sys):
"""The sys.argv.pop() must happen before load_configuration()
This way, load_configuration() has a chance to parse the command
line arguments, which may contain something like a --config=xyz
parameter that affects config loading.
"""
class MyDaemon(Daemon):
def load_configuration(self):
if self.param1 != 'start':
raise Exception("param1 not yet set")
mock_sys.argv = ['foo', 'start', '--config=xyz']
a = MyDaemon(pid_file='foo.pid')
| from __future__ import print_function, absolute_import, division
from unittest2 import TestCase
from mock import patch
from succubus import Daemon
class TestDaemonize(TestCase):
@patch('succubus.daemonize.sys')
def test_must_pop_sys_argv_before_loading_config(self, mock_sys):
"""The sys.argv.pop() must happen before load_configuration()
This way, load_configuration() has a chance to parse the command
line arguments, which may contain something like a --config=xyz
parameter that affects config loading.
"""
class MyDaemon(Daemon):
def load_configuration(self):
if self.param1 != 'start':
raise Exception("param1 not yet set")
mock_sys.argv = ['foo', 'start', '--config=xyz']
a = MyDaemon(pid_file='foo.pid')
@patch("succubus.daemonize.os.setgid")
def test_set_gid_translates_group_name(self, mock_setgid):
daemon = Daemon(pid_file="foo")
daemon.group = "root"
daemon.set_gid()
mock_setgid.assert_called_with(0)
@patch("succubus.daemonize.os.setuid")
def test_set_uid_translates_user_name(self, mock_setuid):
daemon = Daemon(pid_file="foo")
daemon.user = "root"
daemon.set_uid()
mock_setuid.assert_called_with(0)
| Test that set_(g|u)id actually changes the id | Test that set_(g|u)id actually changes the id
| Python | apache-2.0 | ImmobilienScout24/succubus | from __future__ import print_function, absolute_import, division
from unittest2 import TestCase
from mock import patch
from succubus import Daemon
class TestDaemonize(TestCase):
@patch('succubus.daemonize.sys')
def test_must_pop_sys_argv_before_loading_config(self, mock_sys):
"""The sys.argv.pop() must happen before load_configuration()
This way, load_configuration() has a chance to parse the command
line arguments, which may contain something like a --config=xyz
parameter that affects config loading.
"""
class MyDaemon(Daemon):
def load_configuration(self):
if self.param1 != 'start':
raise Exception("param1 not yet set")
mock_sys.argv = ['foo', 'start', '--config=xyz']
a = MyDaemon(pid_file='foo.pid')
Test that set_(g|u)id actually changes the id | from __future__ import print_function, absolute_import, division
from unittest2 import TestCase
from mock import patch
from succubus import Daemon
class TestDaemonize(TestCase):
@patch('succubus.daemonize.sys')
def test_must_pop_sys_argv_before_loading_config(self, mock_sys):
"""The sys.argv.pop() must happen before load_configuration()
This way, load_configuration() has a chance to parse the command
line arguments, which may contain something like a --config=xyz
parameter that affects config loading.
"""
class MyDaemon(Daemon):
def load_configuration(self):
if self.param1 != 'start':
raise Exception("param1 not yet set")
mock_sys.argv = ['foo', 'start', '--config=xyz']
a = MyDaemon(pid_file='foo.pid')
@patch("succubus.daemonize.os.setgid")
def test_set_gid_translates_group_name(self, mock_setgid):
daemon = Daemon(pid_file="foo")
daemon.group = "root"
daemon.set_gid()
mock_setgid.assert_called_with(0)
@patch("succubus.daemonize.os.setuid")
def test_set_uid_translates_user_name(self, mock_setuid):
daemon = Daemon(pid_file="foo")
daemon.user = "root"
daemon.set_uid()
mock_setuid.assert_called_with(0)
| <commit_before>from __future__ import print_function, absolute_import, division
from unittest2 import TestCase
from mock import patch
from succubus import Daemon
class TestDaemonize(TestCase):
@patch('succubus.daemonize.sys')
def test_must_pop_sys_argv_before_loading_config(self, mock_sys):
"""The sys.argv.pop() must happen before load_configuration()
This way, load_configuration() has a chance to parse the command
line arguments, which may contain something like a --config=xyz
parameter that affects config loading.
"""
class MyDaemon(Daemon):
def load_configuration(self):
if self.param1 != 'start':
raise Exception("param1 not yet set")
mock_sys.argv = ['foo', 'start', '--config=xyz']
a = MyDaemon(pid_file='foo.pid')
<commit_msg>Test that set_(g|u)id actually changes the id<commit_after> | from __future__ import print_function, absolute_import, division
from unittest2 import TestCase
from mock import patch
from succubus import Daemon
class TestDaemonize(TestCase):
@patch('succubus.daemonize.sys')
def test_must_pop_sys_argv_before_loading_config(self, mock_sys):
"""The sys.argv.pop() must happen before load_configuration()
This way, load_configuration() has a chance to parse the command
line arguments, which may contain something like a --config=xyz
parameter that affects config loading.
"""
class MyDaemon(Daemon):
def load_configuration(self):
if self.param1 != 'start':
raise Exception("param1 not yet set")
mock_sys.argv = ['foo', 'start', '--config=xyz']
a = MyDaemon(pid_file='foo.pid')
@patch("succubus.daemonize.os.setgid")
def test_set_gid_translates_group_name(self, mock_setgid):
daemon = Daemon(pid_file="foo")
daemon.group = "root"
daemon.set_gid()
mock_setgid.assert_called_with(0)
@patch("succubus.daemonize.os.setuid")
def test_set_uid_translates_user_name(self, mock_setuid):
daemon = Daemon(pid_file="foo")
daemon.user = "root"
daemon.set_uid()
mock_setuid.assert_called_with(0)
| from __future__ import print_function, absolute_import, division
from unittest2 import TestCase
from mock import patch
from succubus import Daemon
class TestDaemonize(TestCase):
@patch('succubus.daemonize.sys')
def test_must_pop_sys_argv_before_loading_config(self, mock_sys):
"""The sys.argv.pop() must happen before load_configuration()
This way, load_configuration() has a chance to parse the command
line arguments, which may contain something like a --config=xyz
parameter that affects config loading.
"""
class MyDaemon(Daemon):
def load_configuration(self):
if self.param1 != 'start':
raise Exception("param1 not yet set")
mock_sys.argv = ['foo', 'start', '--config=xyz']
a = MyDaemon(pid_file='foo.pid')
Test that set_(g|u)id actually changes the idfrom __future__ import print_function, absolute_import, division
from unittest2 import TestCase
from mock import patch
from succubus import Daemon
class TestDaemonize(TestCase):
@patch('succubus.daemonize.sys')
def test_must_pop_sys_argv_before_loading_config(self, mock_sys):
"""The sys.argv.pop() must happen before load_configuration()
This way, load_configuration() has a chance to parse the command
line arguments, which may contain something like a --config=xyz
parameter that affects config loading.
"""
class MyDaemon(Daemon):
def load_configuration(self):
if self.param1 != 'start':
raise Exception("param1 not yet set")
mock_sys.argv = ['foo', 'start', '--config=xyz']
a = MyDaemon(pid_file='foo.pid')
@patch("succubus.daemonize.os.setgid")
def test_set_gid_translates_group_name(self, mock_setgid):
daemon = Daemon(pid_file="foo")
daemon.group = "root"
daemon.set_gid()
mock_setgid.assert_called_with(0)
@patch("succubus.daemonize.os.setuid")
def test_set_uid_translates_user_name(self, mock_setuid):
daemon = Daemon(pid_file="foo")
daemon.user = "root"
daemon.set_uid()
mock_setuid.assert_called_with(0)
| <commit_before>from __future__ import print_function, absolute_import, division
from unittest2 import TestCase
from mock import patch
from succubus import Daemon
class TestDaemonize(TestCase):
@patch('succubus.daemonize.sys')
def test_must_pop_sys_argv_before_loading_config(self, mock_sys):
"""The sys.argv.pop() must happen before load_configuration()
This way, load_configuration() has a chance to parse the command
line arguments, which may contain something like a --config=xyz
parameter that affects config loading.
"""
class MyDaemon(Daemon):
def load_configuration(self):
if self.param1 != 'start':
raise Exception("param1 not yet set")
mock_sys.argv = ['foo', 'start', '--config=xyz']
a = MyDaemon(pid_file='foo.pid')
<commit_msg>Test that set_(g|u)id actually changes the id<commit_after>from __future__ import print_function, absolute_import, division
from unittest2 import TestCase
from mock import patch
from succubus import Daemon
class TestDaemonize(TestCase):
@patch('succubus.daemonize.sys')
def test_must_pop_sys_argv_before_loading_config(self, mock_sys):
"""The sys.argv.pop() must happen before load_configuration()
This way, load_configuration() has a chance to parse the command
line arguments, which may contain something like a --config=xyz
parameter that affects config loading.
"""
class MyDaemon(Daemon):
def load_configuration(self):
if self.param1 != 'start':
raise Exception("param1 not yet set")
mock_sys.argv = ['foo', 'start', '--config=xyz']
a = MyDaemon(pid_file='foo.pid')
@patch("succubus.daemonize.os.setgid")
def test_set_gid_translates_group_name(self, mock_setgid):
daemon = Daemon(pid_file="foo")
daemon.group = "root"
daemon.set_gid()
mock_setgid.assert_called_with(0)
@patch("succubus.daemonize.os.setuid")
def test_set_uid_translates_user_name(self, mock_setuid):
daemon = Daemon(pid_file="foo")
daemon.user = "root"
daemon.set_uid()
mock_setuid.assert_called_with(0)
|
a894e53d48737f5b9ddc3cc2f5ffe4de98b558dd | forum/forms.py | forum/forms.py | from django.forms import ModelForm,Textarea,TextInput
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ('subject','body')
widgets = {
'subject': TextInput(attrs={'autofocus':'autofocus'}),
'body': Textarea(
attrs={
'data-provide':'markdown',
'data-hidden-buttons':'cmdHeading',
'data-iconlibrary':'octicons',
}),
}
| from django.forms import ModelForm,Textarea,TextInput
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ('subject','body')
widgets = {
'subject': TextInput(attrs={'autofocus':'autofocus'}),
'body': Textarea(
attrs={
'data-provide':'markdown',
'data-hidden-buttons':'cmdHeading',
'data-iconlibrary':'octicons',
'data-resize': 'vertical',
}),
}
| Allow Markdown editor to be resized | Allow Markdown editor to be resized
| Python | mit | Kromey/fbxnano,Kromey/fbxnano,Kromey/fbxnano,Kromey/akwriters,Kromey/akwriters,Kromey/akwriters,Kromey/fbxnano,Kromey/akwriters | from django.forms import ModelForm,Textarea,TextInput
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ('subject','body')
widgets = {
'subject': TextInput(attrs={'autofocus':'autofocus'}),
'body': Textarea(
attrs={
'data-provide':'markdown',
'data-hidden-buttons':'cmdHeading',
'data-iconlibrary':'octicons',
}),
}
Allow Markdown editor to be resized | from django.forms import ModelForm,Textarea,TextInput
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ('subject','body')
widgets = {
'subject': TextInput(attrs={'autofocus':'autofocus'}),
'body': Textarea(
attrs={
'data-provide':'markdown',
'data-hidden-buttons':'cmdHeading',
'data-iconlibrary':'octicons',
'data-resize': 'vertical',
}),
}
| <commit_before>from django.forms import ModelForm,Textarea,TextInput
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ('subject','body')
widgets = {
'subject': TextInput(attrs={'autofocus':'autofocus'}),
'body': Textarea(
attrs={
'data-provide':'markdown',
'data-hidden-buttons':'cmdHeading',
'data-iconlibrary':'octicons',
}),
}
<commit_msg>Allow Markdown editor to be resized<commit_after> | from django.forms import ModelForm,Textarea,TextInput
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ('subject','body')
widgets = {
'subject': TextInput(attrs={'autofocus':'autofocus'}),
'body': Textarea(
attrs={
'data-provide':'markdown',
'data-hidden-buttons':'cmdHeading',
'data-iconlibrary':'octicons',
'data-resize': 'vertical',
}),
}
| from django.forms import ModelForm,Textarea,TextInput
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ('subject','body')
widgets = {
'subject': TextInput(attrs={'autofocus':'autofocus'}),
'body': Textarea(
attrs={
'data-provide':'markdown',
'data-hidden-buttons':'cmdHeading',
'data-iconlibrary':'octicons',
}),
}
Allow Markdown editor to be resizedfrom django.forms import ModelForm,Textarea,TextInput
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ('subject','body')
widgets = {
'subject': TextInput(attrs={'autofocus':'autofocus'}),
'body': Textarea(
attrs={
'data-provide':'markdown',
'data-hidden-buttons':'cmdHeading',
'data-iconlibrary':'octicons',
'data-resize': 'vertical',
}),
}
| <commit_before>from django.forms import ModelForm,Textarea,TextInput
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ('subject','body')
widgets = {
'subject': TextInput(attrs={'autofocus':'autofocus'}),
'body': Textarea(
attrs={
'data-provide':'markdown',
'data-hidden-buttons':'cmdHeading',
'data-iconlibrary':'octicons',
}),
}
<commit_msg>Allow Markdown editor to be resized<commit_after>from django.forms import ModelForm,Textarea,TextInput
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ('subject','body')
widgets = {
'subject': TextInput(attrs={'autofocus':'autofocus'}),
'body': Textarea(
attrs={
'data-provide':'markdown',
'data-hidden-buttons':'cmdHeading',
'data-iconlibrary':'octicons',
'data-resize': 'vertical',
}),
}
|
53a442ac37bf58bca16dee2ad0787bdf2df98555 | nltk/test/gluesemantics_malt_fixt.py | nltk/test/gluesemantics_malt_fixt.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
def setup_module(module):
from nose import SkipTest
from nltk.parse.malt import MaltParser
try:
depparser = MaltParser()
except LookupError:
raise SkipTest("MaltParser is not available")
| # -*- coding: utf-8 -*-
from __future__ import absolute_import
def setup_module(module):
from nose import SkipTest
from nltk.parse.malt import MaltParser
try:
depparser = MaltParser('maltparser-1.7.2')
except LookupError:
raise SkipTest("MaltParser is not available")
| Add the malt parser directory name in the unittest | Add the malt parser directory name in the unittest
Fixes https://nltk.ci.cloudbees.com/job/nltk/TOXENV=py34-jenkins,jdk=jdk8latestOnlineInstall/lastCompletedBuild/testReport/%3Cnose/suite/ContextSuite_context_gluesemantics_malt_fixt__setup/ | Python | apache-2.0 | nltk/nltk,nltk/nltk,nltk/nltk | # -*- coding: utf-8 -*-
from __future__ import absolute_import
def setup_module(module):
from nose import SkipTest
from nltk.parse.malt import MaltParser
try:
depparser = MaltParser()
except LookupError:
raise SkipTest("MaltParser is not available")
Add the malt parser directory name in the unittest
Fixes https://nltk.ci.cloudbees.com/job/nltk/TOXENV=py34-jenkins,jdk=jdk8latestOnlineInstall/lastCompletedBuild/testReport/%3Cnose/suite/ContextSuite_context_gluesemantics_malt_fixt__setup/ | # -*- coding: utf-8 -*-
from __future__ import absolute_import
def setup_module(module):
from nose import SkipTest
from nltk.parse.malt import MaltParser
try:
depparser = MaltParser('maltparser-1.7.2')
except LookupError:
raise SkipTest("MaltParser is not available")
| <commit_before># -*- coding: utf-8 -*-
from __future__ import absolute_import
def setup_module(module):
from nose import SkipTest
from nltk.parse.malt import MaltParser
try:
depparser = MaltParser()
except LookupError:
raise SkipTest("MaltParser is not available")
<commit_msg>Add the malt parser directory name in the unittest
Fixes https://nltk.ci.cloudbees.com/job/nltk/TOXENV=py34-jenkins,jdk=jdk8latestOnlineInstall/lastCompletedBuild/testReport/%3Cnose/suite/ContextSuite_context_gluesemantics_malt_fixt__setup/<commit_after> | # -*- coding: utf-8 -*-
from __future__ import absolute_import
def setup_module(module):
from nose import SkipTest
from nltk.parse.malt import MaltParser
try:
depparser = MaltParser('maltparser-1.7.2')
except LookupError:
raise SkipTest("MaltParser is not available")
| # -*- coding: utf-8 -*-
from __future__ import absolute_import
def setup_module(module):
from nose import SkipTest
from nltk.parse.malt import MaltParser
try:
depparser = MaltParser()
except LookupError:
raise SkipTest("MaltParser is not available")
Add the malt parser directory name in the unittest
Fixes https://nltk.ci.cloudbees.com/job/nltk/TOXENV=py34-jenkins,jdk=jdk8latestOnlineInstall/lastCompletedBuild/testReport/%3Cnose/suite/ContextSuite_context_gluesemantics_malt_fixt__setup/# -*- coding: utf-8 -*-
from __future__ import absolute_import
def setup_module(module):
from nose import SkipTest
from nltk.parse.malt import MaltParser
try:
depparser = MaltParser('maltparser-1.7.2')
except LookupError:
raise SkipTest("MaltParser is not available")
| <commit_before># -*- coding: utf-8 -*-
from __future__ import absolute_import
def setup_module(module):
from nose import SkipTest
from nltk.parse.malt import MaltParser
try:
depparser = MaltParser()
except LookupError:
raise SkipTest("MaltParser is not available")
<commit_msg>Add the malt parser directory name in the unittest
Fixes https://nltk.ci.cloudbees.com/job/nltk/TOXENV=py34-jenkins,jdk=jdk8latestOnlineInstall/lastCompletedBuild/testReport/%3Cnose/suite/ContextSuite_context_gluesemantics_malt_fixt__setup/<commit_after># -*- coding: utf-8 -*-
from __future__ import absolute_import
def setup_module(module):
from nose import SkipTest
from nltk.parse.malt import MaltParser
try:
depparser = MaltParser('maltparser-1.7.2')
except LookupError:
raise SkipTest("MaltParser is not available")
|
a1300dc059bd4eeb44654b75132c3e542caa29cc | staticgen_demo/blog/staticgen_views.py | staticgen_demo/blog/staticgen_views.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
from .models import Post
class BlogPostListView(StaticgenView):
is_paginated = True
i18n = True
def items(self):
return ('blog:posts_list', )
class BlogPostDetailView(StaticgenView):
i18n = True
def items(self):
return Post.objects.all()
staticgen_pool.register(BlogPostListView)
staticgen_pool.register(BlogPostDetailView)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
from .models import Post
class BlogPostListView(StaticgenView):
is_paginated = True
i18n = True
def items(self):
return ('blog:posts_list', )
def _get_paginator(self, url):
response = self.client.get(url)
print response.status_code
print response.__dict__
if not response.status_code == 200:
pass
else:
try:
return response.context['paginator'], response.context['is_paginated']
except KeyError:
pass
return None, False
class BlogPostDetailView(StaticgenView):
i18n = True
def items(self):
return Post.objects.all()
staticgen_pool.register(BlogPostListView)
staticgen_pool.register(BlogPostDetailView)
| Add print statements to debug BlogPostListView | Add print statements to debug BlogPostListView
| Python | bsd-3-clause | mishbahr/staticgen-demo,mishbahr/staticgen-demo,mishbahr/staticgen-demo | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
from .models import Post
class BlogPostListView(StaticgenView):
is_paginated = True
i18n = True
def items(self):
return ('blog:posts_list', )
class BlogPostDetailView(StaticgenView):
i18n = True
def items(self):
return Post.objects.all()
staticgen_pool.register(BlogPostListView)
staticgen_pool.register(BlogPostDetailView)
Add print statements to debug BlogPostListView | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
from .models import Post
class BlogPostListView(StaticgenView):
is_paginated = True
i18n = True
def items(self):
return ('blog:posts_list', )
def _get_paginator(self, url):
response = self.client.get(url)
print response.status_code
print response.__dict__
if not response.status_code == 200:
pass
else:
try:
return response.context['paginator'], response.context['is_paginated']
except KeyError:
pass
return None, False
class BlogPostDetailView(StaticgenView):
i18n = True
def items(self):
return Post.objects.all()
staticgen_pool.register(BlogPostListView)
staticgen_pool.register(BlogPostDetailView)
| <commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
from .models import Post
class BlogPostListView(StaticgenView):
is_paginated = True
i18n = True
def items(self):
return ('blog:posts_list', )
class BlogPostDetailView(StaticgenView):
i18n = True
def items(self):
return Post.objects.all()
staticgen_pool.register(BlogPostListView)
staticgen_pool.register(BlogPostDetailView)
<commit_msg>Add print statements to debug BlogPostListView<commit_after> | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
from .models import Post
class BlogPostListView(StaticgenView):
is_paginated = True
i18n = True
def items(self):
return ('blog:posts_list', )
def _get_paginator(self, url):
response = self.client.get(url)
print response.status_code
print response.__dict__
if not response.status_code == 200:
pass
else:
try:
return response.context['paginator'], response.context['is_paginated']
except KeyError:
pass
return None, False
class BlogPostDetailView(StaticgenView):
i18n = True
def items(self):
return Post.objects.all()
staticgen_pool.register(BlogPostListView)
staticgen_pool.register(BlogPostDetailView)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
from .models import Post
class BlogPostListView(StaticgenView):
is_paginated = True
i18n = True
def items(self):
return ('blog:posts_list', )
class BlogPostDetailView(StaticgenView):
i18n = True
def items(self):
return Post.objects.all()
staticgen_pool.register(BlogPostListView)
staticgen_pool.register(BlogPostDetailView)
Add print statements to debug BlogPostListView# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
from .models import Post
class BlogPostListView(StaticgenView):
is_paginated = True
i18n = True
def items(self):
return ('blog:posts_list', )
def _get_paginator(self, url):
response = self.client.get(url)
print response.status_code
print response.__dict__
if not response.status_code == 200:
pass
else:
try:
return response.context['paginator'], response.context['is_paginated']
except KeyError:
pass
return None, False
class BlogPostDetailView(StaticgenView):
i18n = True
def items(self):
return Post.objects.all()
staticgen_pool.register(BlogPostListView)
staticgen_pool.register(BlogPostDetailView)
| <commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
from .models import Post
class BlogPostListView(StaticgenView):
is_paginated = True
i18n = True
def items(self):
return ('blog:posts_list', )
class BlogPostDetailView(StaticgenView):
i18n = True
def items(self):
return Post.objects.all()
staticgen_pool.register(BlogPostListView)
staticgen_pool.register(BlogPostDetailView)
<commit_msg>Add print statements to debug BlogPostListView<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
from .models import Post
class BlogPostListView(StaticgenView):
is_paginated = True
i18n = True
def items(self):
return ('blog:posts_list', )
def _get_paginator(self, url):
response = self.client.get(url)
print response.status_code
print response.__dict__
if not response.status_code == 200:
pass
else:
try:
return response.context['paginator'], response.context['is_paginated']
except KeyError:
pass
return None, False
class BlogPostDetailView(StaticgenView):
i18n = True
def items(self):
return Post.objects.all()
staticgen_pool.register(BlogPostListView)
staticgen_pool.register(BlogPostDetailView)
|
79f60cdb3853a60fd2cf6e69a141ed7b756f86cb | giphy_magic.py | giphy_magic.py | from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag):
params = {
'api_key': API_KEY,
'tag': tag
}
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
return Image(url=data['image_url'])
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
| from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag):
params = {
'api_key': API_KEY,
'tag': tag
}
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
return Image(url=data['image_url'])
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
| Call out public beta key | Call out public beta key
| Python | mit | AustinRochford/giphy-ipython-magic,AustinRochford/giphy-ipython-magic | from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag):
params = {
'api_key': API_KEY,
'tag': tag
}
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
return Image(url=data['image_url'])
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
Call out public beta key | from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag):
params = {
'api_key': API_KEY,
'tag': tag
}
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
return Image(url=data['image_url'])
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
| <commit_before>from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag):
params = {
'api_key': API_KEY,
'tag': tag
}
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
return Image(url=data['image_url'])
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
<commit_msg>Call out public beta key<commit_after> | from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag):
params = {
'api_key': API_KEY,
'tag': tag
}
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
return Image(url=data['image_url'])
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
| from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag):
params = {
'api_key': API_KEY,
'tag': tag
}
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
return Image(url=data['image_url'])
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
Call out public beta keyfrom IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag):
params = {
'api_key': API_KEY,
'tag': tag
}
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
return Image(url=data['image_url'])
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
| <commit_before>from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag):
params = {
'api_key': API_KEY,
'tag': tag
}
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
return Image(url=data['image_url'])
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
<commit_msg>Call out public beta key<commit_after>from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag):
params = {
'api_key': API_KEY,
'tag': tag
}
r = requests.get(API_ENDPOINT, params=params)
json = r.json()
data = json['data']
return Image(url=data['image_url'])
def load_ipython_extension(ipython):
ipython.register_magic_function(giphy, 'line')
|
aaaf8ef7433418f7a195c79674db56e03fc58f10 | apps/bplan/models.py | apps/bplan/models.py | from django.db import models
from adhocracy4.models.base import TimeStampedModel
from adhocracy4.modules import models as module_models
from apps.extprojects.models import ExternalProject
class Bplan(ExternalProject):
office_worker_email = models.EmailField()
class AnonymousItem(TimeStampedModel):
module = models.ForeignKey(module_models.Module, on_delete=models.CASCADE)
@property
def project(self):
return self.module.project
class Meta:
abstract = True
class Statement(AnonymousItem):
name = models.CharField(max_length=255)
email = models.EmailField(blank=True)
statement = models.TextField(max_length=17500)
street_number = models.CharField(max_length=255)
postal_code_city = models.CharField(max_length=255)
| from django.contrib.auth.models import AnonymousUser
from django.db import models
from adhocracy4.models.base import TimeStampedModel
from adhocracy4.modules import models as module_models
from apps.extprojects.models import ExternalProject
class Bplan(ExternalProject):
office_worker_email = models.EmailField()
class AnonymousItem(TimeStampedModel):
module = models.ForeignKey(module_models.Module, on_delete=models.CASCADE)
@property
def project(self):
return self.module.project
@property
def creator(self):
return AnonymousUser()
@creator.setter
def creator(self, value):
pass
class Meta:
abstract = True
class Statement(AnonymousItem):
name = models.CharField(max_length=255)
email = models.EmailField(blank=True)
statement = models.TextField(max_length=17500)
street_number = models.CharField(max_length=255)
postal_code_city = models.CharField(max_length=255)
| Add mockup creator property to AnonymousItems | Add mockup creator property to AnonymousItems
| Python | agpl-3.0 | liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin | from django.db import models
from adhocracy4.models.base import TimeStampedModel
from adhocracy4.modules import models as module_models
from apps.extprojects.models import ExternalProject
class Bplan(ExternalProject):
office_worker_email = models.EmailField()
class AnonymousItem(TimeStampedModel):
module = models.ForeignKey(module_models.Module, on_delete=models.CASCADE)
@property
def project(self):
return self.module.project
class Meta:
abstract = True
class Statement(AnonymousItem):
name = models.CharField(max_length=255)
email = models.EmailField(blank=True)
statement = models.TextField(max_length=17500)
street_number = models.CharField(max_length=255)
postal_code_city = models.CharField(max_length=255)
Add mockup creator property to AnonymousItems | from django.contrib.auth.models import AnonymousUser
from django.db import models
from adhocracy4.models.base import TimeStampedModel
from adhocracy4.modules import models as module_models
from apps.extprojects.models import ExternalProject
class Bplan(ExternalProject):
office_worker_email = models.EmailField()
class AnonymousItem(TimeStampedModel):
module = models.ForeignKey(module_models.Module, on_delete=models.CASCADE)
@property
def project(self):
return self.module.project
@property
def creator(self):
return AnonymousUser()
@creator.setter
def creator(self, value):
pass
class Meta:
abstract = True
class Statement(AnonymousItem):
name = models.CharField(max_length=255)
email = models.EmailField(blank=True)
statement = models.TextField(max_length=17500)
street_number = models.CharField(max_length=255)
postal_code_city = models.CharField(max_length=255)
| <commit_before>from django.db import models
from adhocracy4.models.base import TimeStampedModel
from adhocracy4.modules import models as module_models
from apps.extprojects.models import ExternalProject
class Bplan(ExternalProject):
office_worker_email = models.EmailField()
class AnonymousItem(TimeStampedModel):
module = models.ForeignKey(module_models.Module, on_delete=models.CASCADE)
@property
def project(self):
return self.module.project
class Meta:
abstract = True
class Statement(AnonymousItem):
name = models.CharField(max_length=255)
email = models.EmailField(blank=True)
statement = models.TextField(max_length=17500)
street_number = models.CharField(max_length=255)
postal_code_city = models.CharField(max_length=255)
<commit_msg>Add mockup creator property to AnonymousItems<commit_after> | from django.contrib.auth.models import AnonymousUser
from django.db import models
from adhocracy4.models.base import TimeStampedModel
from adhocracy4.modules import models as module_models
from apps.extprojects.models import ExternalProject
class Bplan(ExternalProject):
office_worker_email = models.EmailField()
class AnonymousItem(TimeStampedModel):
module = models.ForeignKey(module_models.Module, on_delete=models.CASCADE)
@property
def project(self):
return self.module.project
@property
def creator(self):
return AnonymousUser()
@creator.setter
def creator(self, value):
pass
class Meta:
abstract = True
class Statement(AnonymousItem):
name = models.CharField(max_length=255)
email = models.EmailField(blank=True)
statement = models.TextField(max_length=17500)
street_number = models.CharField(max_length=255)
postal_code_city = models.CharField(max_length=255)
| from django.db import models
from adhocracy4.models.base import TimeStampedModel
from adhocracy4.modules import models as module_models
from apps.extprojects.models import ExternalProject
class Bplan(ExternalProject):
office_worker_email = models.EmailField()
class AnonymousItem(TimeStampedModel):
module = models.ForeignKey(module_models.Module, on_delete=models.CASCADE)
@property
def project(self):
return self.module.project
class Meta:
abstract = True
class Statement(AnonymousItem):
name = models.CharField(max_length=255)
email = models.EmailField(blank=True)
statement = models.TextField(max_length=17500)
street_number = models.CharField(max_length=255)
postal_code_city = models.CharField(max_length=255)
Add mockup creator property to AnonymousItemsfrom django.contrib.auth.models import AnonymousUser
from django.db import models
from adhocracy4.models.base import TimeStampedModel
from adhocracy4.modules import models as module_models
from apps.extprojects.models import ExternalProject
class Bplan(ExternalProject):
office_worker_email = models.EmailField()
class AnonymousItem(TimeStampedModel):
module = models.ForeignKey(module_models.Module, on_delete=models.CASCADE)
@property
def project(self):
return self.module.project
@property
def creator(self):
return AnonymousUser()
@creator.setter
def creator(self, value):
pass
class Meta:
abstract = True
class Statement(AnonymousItem):
name = models.CharField(max_length=255)
email = models.EmailField(blank=True)
statement = models.TextField(max_length=17500)
street_number = models.CharField(max_length=255)
postal_code_city = models.CharField(max_length=255)
| <commit_before>from django.db import models
from adhocracy4.models.base import TimeStampedModel
from adhocracy4.modules import models as module_models
from apps.extprojects.models import ExternalProject
class Bplan(ExternalProject):
office_worker_email = models.EmailField()
class AnonymousItem(TimeStampedModel):
module = models.ForeignKey(module_models.Module, on_delete=models.CASCADE)
@property
def project(self):
return self.module.project
class Meta:
abstract = True
class Statement(AnonymousItem):
name = models.CharField(max_length=255)
email = models.EmailField(blank=True)
statement = models.TextField(max_length=17500)
street_number = models.CharField(max_length=255)
postal_code_city = models.CharField(max_length=255)
<commit_msg>Add mockup creator property to AnonymousItems<commit_after>from django.contrib.auth.models import AnonymousUser
from django.db import models
from adhocracy4.models.base import TimeStampedModel
from adhocracy4.modules import models as module_models
from apps.extprojects.models import ExternalProject
class Bplan(ExternalProject):
office_worker_email = models.EmailField()
class AnonymousItem(TimeStampedModel):
module = models.ForeignKey(module_models.Module, on_delete=models.CASCADE)
@property
def project(self):
return self.module.project
@property
def creator(self):
return AnonymousUser()
@creator.setter
def creator(self, value):
pass
class Meta:
abstract = True
class Statement(AnonymousItem):
name = models.CharField(max_length=255)
email = models.EmailField(blank=True)
statement = models.TextField(max_length=17500)
street_number = models.CharField(max_length=255)
postal_code_city = models.CharField(max_length=255)
|
d25167937a6e0f923d9c03cd94c227e96fdf12ba | pyalysis/analysers/raw.py | pyalysis/analysers/raw.py | # coding: utf-8
"""
pyalysis.analysers.raw
~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2014 by Daniel Neuhäuser and Contributors
:license: BSD, see LICENSE.rst for details
"""
import codecs
from pyalysis.utils import detect_encoding
from pyalysis.warnings import LineTooLong
class LineAnalyser(object):
"""
Line-level analyser of Python source code.
"""
def __init__(self, module):
self.module = module
self.encoding = detect_encoding(module)
self.warnings = []
def emit(self, warning_cls, message, lineno):
self.warnings.append(warning_cls(message, self.module.name, lineno))
def analyse(self):
reader = codecs.lookup(self.encoding).streamreader(self.module)
for i, line in enumerate(reader, 1):
self.analyse_line(i, line)
return self.warnings
def analyse_line(self, lineno, line):
if len(line.rstrip()) > 79:
self.emit(
LineTooLong,
u'Line is longer than 79 characters. '
u'You should keep it below that',
lineno
)
| # coding: utf-8
"""
pyalysis.analysers.raw
~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2014 by Daniel Neuhäuser and Contributors
:license: BSD, see LICENSE.rst for details
"""
import codecs
from blinker import Signal
from pyalysis.utils import detect_encoding
from pyalysis.warnings import LineTooLong
class LineAnalyser(object):
"""
Line-level analyser of Python source code.
"""
on_analyse = Signal()
on_line = Signal()
def __init__(self, module):
self.module = module
self.encoding = detect_encoding(module)
self.warnings = []
def emit(self, warning_cls, message, lineno):
self.warnings.append(warning_cls(message, self.module.name, lineno))
def analyse(self):
self.on_analyse.send(self)
reader = codecs.lookup(self.encoding).streamreader(self.module)
for i, line in enumerate(reader, 1):
self.on_line.send(self, lineno=i, line=line)
return self.warnings
@LineAnalyser.on_line.connect
def check_line_length(analyser, lineno, line):
if len(line.rstrip()) > 79:
analyser.emit(
LineTooLong,
u'Line is longer than 79 characters. '
u'You should keep it below that',
lineno
)
| Switch to signal based dispatch in LineAnalyser | Switch to signal based dispatch in LineAnalyser
| Python | bsd-3-clause | DasIch/pyalysis,DasIch/pyalysis | # coding: utf-8
"""
pyalysis.analysers.raw
~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2014 by Daniel Neuhäuser and Contributors
:license: BSD, see LICENSE.rst for details
"""
import codecs
from pyalysis.utils import detect_encoding
from pyalysis.warnings import LineTooLong
class LineAnalyser(object):
"""
Line-level analyser of Python source code.
"""
def __init__(self, module):
self.module = module
self.encoding = detect_encoding(module)
self.warnings = []
def emit(self, warning_cls, message, lineno):
self.warnings.append(warning_cls(message, self.module.name, lineno))
def analyse(self):
reader = codecs.lookup(self.encoding).streamreader(self.module)
for i, line in enumerate(reader, 1):
self.analyse_line(i, line)
return self.warnings
def analyse_line(self, lineno, line):
if len(line.rstrip()) > 79:
self.emit(
LineTooLong,
u'Line is longer than 79 characters. '
u'You should keep it below that',
lineno
)
Switch to signal based dispatch in LineAnalyser | # coding: utf-8
"""
pyalysis.analysers.raw
~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2014 by Daniel Neuhäuser and Contributors
:license: BSD, see LICENSE.rst for details
"""
import codecs
from blinker import Signal
from pyalysis.utils import detect_encoding
from pyalysis.warnings import LineTooLong
class LineAnalyser(object):
"""
Line-level analyser of Python source code.
"""
on_analyse = Signal()
on_line = Signal()
def __init__(self, module):
self.module = module
self.encoding = detect_encoding(module)
self.warnings = []
def emit(self, warning_cls, message, lineno):
self.warnings.append(warning_cls(message, self.module.name, lineno))
def analyse(self):
self.on_analyse.send(self)
reader = codecs.lookup(self.encoding).streamreader(self.module)
for i, line in enumerate(reader, 1):
self.on_line.send(self, lineno=i, line=line)
return self.warnings
@LineAnalyser.on_line.connect
def check_line_length(analyser, lineno, line):
if len(line.rstrip()) > 79:
analyser.emit(
LineTooLong,
u'Line is longer than 79 characters. '
u'You should keep it below that',
lineno
)
| <commit_before># coding: utf-8
"""
pyalysis.analysers.raw
~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2014 by Daniel Neuhäuser and Contributors
:license: BSD, see LICENSE.rst for details
"""
import codecs
from pyalysis.utils import detect_encoding
from pyalysis.warnings import LineTooLong
class LineAnalyser(object):
"""
Line-level analyser of Python source code.
"""
def __init__(self, module):
self.module = module
self.encoding = detect_encoding(module)
self.warnings = []
def emit(self, warning_cls, message, lineno):
self.warnings.append(warning_cls(message, self.module.name, lineno))
def analyse(self):
reader = codecs.lookup(self.encoding).streamreader(self.module)
for i, line in enumerate(reader, 1):
self.analyse_line(i, line)
return self.warnings
def analyse_line(self, lineno, line):
if len(line.rstrip()) > 79:
self.emit(
LineTooLong,
u'Line is longer than 79 characters. '
u'You should keep it below that',
lineno
)
<commit_msg>Switch to signal based dispatch in LineAnalyser<commit_after> | # coding: utf-8
"""
pyalysis.analysers.raw
~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2014 by Daniel Neuhäuser and Contributors
:license: BSD, see LICENSE.rst for details
"""
import codecs
from blinker import Signal
from pyalysis.utils import detect_encoding
from pyalysis.warnings import LineTooLong
class LineAnalyser(object):
"""
Line-level analyser of Python source code.
"""
on_analyse = Signal()
on_line = Signal()
def __init__(self, module):
self.module = module
self.encoding = detect_encoding(module)
self.warnings = []
def emit(self, warning_cls, message, lineno):
self.warnings.append(warning_cls(message, self.module.name, lineno))
def analyse(self):
self.on_analyse.send(self)
reader = codecs.lookup(self.encoding).streamreader(self.module)
for i, line in enumerate(reader, 1):
self.on_line.send(self, lineno=i, line=line)
return self.warnings
@LineAnalyser.on_line.connect
def check_line_length(analyser, lineno, line):
if len(line.rstrip()) > 79:
analyser.emit(
LineTooLong,
u'Line is longer than 79 characters. '
u'You should keep it below that',
lineno
)
| # coding: utf-8
"""
pyalysis.analysers.raw
~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2014 by Daniel Neuhäuser and Contributors
:license: BSD, see LICENSE.rst for details
"""
import codecs
from pyalysis.utils import detect_encoding
from pyalysis.warnings import LineTooLong
class LineAnalyser(object):
"""
Line-level analyser of Python source code.
"""
def __init__(self, module):
self.module = module
self.encoding = detect_encoding(module)
self.warnings = []
def emit(self, warning_cls, message, lineno):
self.warnings.append(warning_cls(message, self.module.name, lineno))
def analyse(self):
reader = codecs.lookup(self.encoding).streamreader(self.module)
for i, line in enumerate(reader, 1):
self.analyse_line(i, line)
return self.warnings
def analyse_line(self, lineno, line):
if len(line.rstrip()) > 79:
self.emit(
LineTooLong,
u'Line is longer than 79 characters. '
u'You should keep it below that',
lineno
)
Switch to signal based dispatch in LineAnalyser# coding: utf-8
"""
pyalysis.analysers.raw
~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2014 by Daniel Neuhäuser and Contributors
:license: BSD, see LICENSE.rst for details
"""
import codecs
from blinker import Signal
from pyalysis.utils import detect_encoding
from pyalysis.warnings import LineTooLong
class LineAnalyser(object):
"""
Line-level analyser of Python source code.
"""
on_analyse = Signal()
on_line = Signal()
def __init__(self, module):
self.module = module
self.encoding = detect_encoding(module)
self.warnings = []
def emit(self, warning_cls, message, lineno):
self.warnings.append(warning_cls(message, self.module.name, lineno))
def analyse(self):
self.on_analyse.send(self)
reader = codecs.lookup(self.encoding).streamreader(self.module)
for i, line in enumerate(reader, 1):
self.on_line.send(self, lineno=i, line=line)
return self.warnings
@LineAnalyser.on_line.connect
def check_line_length(analyser, lineno, line):
if len(line.rstrip()) > 79:
analyser.emit(
LineTooLong,
u'Line is longer than 79 characters. '
u'You should keep it below that',
lineno
)
| <commit_before># coding: utf-8
"""
pyalysis.analysers.raw
~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2014 by Daniel Neuhäuser and Contributors
:license: BSD, see LICENSE.rst for details
"""
import codecs
from pyalysis.utils import detect_encoding
from pyalysis.warnings import LineTooLong
class LineAnalyser(object):
"""
Line-level analyser of Python source code.
"""
def __init__(self, module):
self.module = module
self.encoding = detect_encoding(module)
self.warnings = []
def emit(self, warning_cls, message, lineno):
self.warnings.append(warning_cls(message, self.module.name, lineno))
def analyse(self):
reader = codecs.lookup(self.encoding).streamreader(self.module)
for i, line in enumerate(reader, 1):
self.analyse_line(i, line)
return self.warnings
def analyse_line(self, lineno, line):
if len(line.rstrip()) > 79:
self.emit(
LineTooLong,
u'Line is longer than 79 characters. '
u'You should keep it below that',
lineno
)
<commit_msg>Switch to signal based dispatch in LineAnalyser<commit_after># coding: utf-8
"""
pyalysis.analysers.raw
~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2014 by Daniel Neuhäuser and Contributors
:license: BSD, see LICENSE.rst for details
"""
import codecs
from blinker import Signal
from pyalysis.utils import detect_encoding
from pyalysis.warnings import LineTooLong
class LineAnalyser(object):
"""
Line-level analyser of Python source code.
"""
on_analyse = Signal()
on_line = Signal()
def __init__(self, module):
self.module = module
self.encoding = detect_encoding(module)
self.warnings = []
def emit(self, warning_cls, message, lineno):
self.warnings.append(warning_cls(message, self.module.name, lineno))
def analyse(self):
self.on_analyse.send(self)
reader = codecs.lookup(self.encoding).streamreader(self.module)
for i, line in enumerate(reader, 1):
self.on_line.send(self, lineno=i, line=line)
return self.warnings
@LineAnalyser.on_line.connect
def check_line_length(analyser, lineno, line):
if len(line.rstrip()) > 79:
analyser.emit(
LineTooLong,
u'Line is longer than 79 characters. '
u'You should keep it below that',
lineno
)
|
91162995c6425307cb586e663d4bf0241f68d588 | alg_fibonacci.py | alg_fibonacci.py | """Fibonacci series:
0, 1, 1, 2, 3, 5, 8,...
- Fib(0) = 0
- Fib(1) = 1
- Fib(n) = Fib(n - 1) + Fib(n - 2)
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def fibonacci_recur(n):
"""Get nth number of Fibonacci series by recursion."""
if n <= 1:
return n
else:
return fibonacci_recur(n - 1) + fibonacci_recur(n - 2)
def main():
import time
n = 13
start_time = time.time()
print('{}th number of Fibonacci series by recursion: {}'
.format(n, fibonacci_recur(n)))
print('Time: {}'.format(time.time() - start_time))
if __name__ == '__main__':
main()
| """Fibonacci series:
0, 1, 1, 2, 3, 5, 8,...
- Fib(0) = 0
- Fib(1) = 1
- Fib(n) = Fib(n - 1) + Fib(n - 2)
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def fibonacci_recur(n):
"""Get nth number of Fibonacci series by recursion."""
if n <= 1:
return n
else:
return fibonacci_recur(n - 1) + fibonacci_recur(n - 2)
def fibonacci_dp(n):
"""Get nth number of Fibonacci series by dynamic programming.
DP performs much faster than recursion.
"""
a, b = 0, 1
for _ in xrange(n):
a, b = a+b, a
return a
def main():
import time
n = 35
start_time = time.time()
print('{}th number of Fibonacci series by recursion: {}'
.format(n, fibonacci_recur(n)))
print('Time: {}'.format(time.time() - start_time))
start_time = time.time()
print('{}th number of Fibonacci series by recursion: {}'
.format(n, fibonacci_dp(n)))
print('Time: {}'.format(time.time() - start_time))
if __name__ == '__main__':
main()
| Complete fiboncci_dp() by dynamic programming | Complete fiboncci_dp() by dynamic programming
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | """Fibonacci series:
0, 1, 1, 2, 3, 5, 8,...
- Fib(0) = 0
- Fib(1) = 1
- Fib(n) = Fib(n - 1) + Fib(n - 2)
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def fibonacci_recur(n):
"""Get nth number of Fibonacci series by recursion."""
if n <= 1:
return n
else:
return fibonacci_recur(n - 1) + fibonacci_recur(n - 2)
def main():
import time
n = 13
start_time = time.time()
print('{}th number of Fibonacci series by recursion: {}'
.format(n, fibonacci_recur(n)))
print('Time: {}'.format(time.time() - start_time))
if __name__ == '__main__':
main()
Complete fiboncci_dp() by dynamic programming | """Fibonacci series:
0, 1, 1, 2, 3, 5, 8,...
- Fib(0) = 0
- Fib(1) = 1
- Fib(n) = Fib(n - 1) + Fib(n - 2)
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def fibonacci_recur(n):
"""Get nth number of Fibonacci series by recursion."""
if n <= 1:
return n
else:
return fibonacci_recur(n - 1) + fibonacci_recur(n - 2)
def fibonacci_dp(n):
"""Get nth number of Fibonacci series by dynamic programming.
DP performs much faster than recursion.
"""
a, b = 0, 1
for _ in xrange(n):
a, b = a+b, a
return a
def main():
import time
n = 35
start_time = time.time()
print('{}th number of Fibonacci series by recursion: {}'
.format(n, fibonacci_recur(n)))
print('Time: {}'.format(time.time() - start_time))
start_time = time.time()
print('{}th number of Fibonacci series by recursion: {}'
.format(n, fibonacci_dp(n)))
print('Time: {}'.format(time.time() - start_time))
if __name__ == '__main__':
main()
| <commit_before>"""Fibonacci series:
0, 1, 1, 2, 3, 5, 8,...
- Fib(0) = 0
- Fib(1) = 1
- Fib(n) = Fib(n - 1) + Fib(n - 2)
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def fibonacci_recur(n):
"""Get nth number of Fibonacci series by recursion."""
if n <= 1:
return n
else:
return fibonacci_recur(n - 1) + fibonacci_recur(n - 2)
def main():
import time
n = 13
start_time = time.time()
print('{}th number of Fibonacci series by recursion: {}'
.format(n, fibonacci_recur(n)))
print('Time: {}'.format(time.time() - start_time))
if __name__ == '__main__':
main()
<commit_msg>Complete fiboncci_dp() by dynamic programming<commit_after> | """Fibonacci series:
0, 1, 1, 2, 3, 5, 8,...
- Fib(0) = 0
- Fib(1) = 1
- Fib(n) = Fib(n - 1) + Fib(n - 2)
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def fibonacci_recur(n):
"""Get nth number of Fibonacci series by recursion."""
if n <= 1:
return n
else:
return fibonacci_recur(n - 1) + fibonacci_recur(n - 2)
def fibonacci_dp(n):
"""Get nth number of Fibonacci series by dynamic programming.
DP performs much faster than recursion.
"""
a, b = 0, 1
for _ in xrange(n):
a, b = a+b, a
return a
def main():
import time
n = 35
start_time = time.time()
print('{}th number of Fibonacci series by recursion: {}'
.format(n, fibonacci_recur(n)))
print('Time: {}'.format(time.time() - start_time))
start_time = time.time()
print('{}th number of Fibonacci series by recursion: {}'
.format(n, fibonacci_dp(n)))
print('Time: {}'.format(time.time() - start_time))
if __name__ == '__main__':
main()
| """Fibonacci series:
0, 1, 1, 2, 3, 5, 8,...
- Fib(0) = 0
- Fib(1) = 1
- Fib(n) = Fib(n - 1) + Fib(n - 2)
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def fibonacci_recur(n):
"""Get nth number of Fibonacci series by recursion."""
if n <= 1:
return n
else:
return fibonacci_recur(n - 1) + fibonacci_recur(n - 2)
def main():
import time
n = 13
start_time = time.time()
print('{}th number of Fibonacci series by recursion: {}'
.format(n, fibonacci_recur(n)))
print('Time: {}'.format(time.time() - start_time))
if __name__ == '__main__':
main()
Complete fiboncci_dp() by dynamic programming"""Fibonacci series:
0, 1, 1, 2, 3, 5, 8,...
- Fib(0) = 0
- Fib(1) = 1
- Fib(n) = Fib(n - 1) + Fib(n - 2)
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def fibonacci_recur(n):
"""Get nth number of Fibonacci series by recursion."""
if n <= 1:
return n
else:
return fibonacci_recur(n - 1) + fibonacci_recur(n - 2)
def fibonacci_dp(n):
"""Get nth number of Fibonacci series by dynamic programming.
DP performs much faster than recursion.
"""
a, b = 0, 1
for _ in xrange(n):
a, b = a+b, a
return a
def main():
import time
n = 35
start_time = time.time()
print('{}th number of Fibonacci series by recursion: {}'
.format(n, fibonacci_recur(n)))
print('Time: {}'.format(time.time() - start_time))
start_time = time.time()
print('{}th number of Fibonacci series by recursion: {}'
.format(n, fibonacci_dp(n)))
print('Time: {}'.format(time.time() - start_time))
if __name__ == '__main__':
main()
| <commit_before>"""Fibonacci series:
0, 1, 1, 2, 3, 5, 8,...
- Fib(0) = 0
- Fib(1) = 1
- Fib(n) = Fib(n - 1) + Fib(n - 2)
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def fibonacci_recur(n):
"""Get nth number of Fibonacci series by recursion."""
if n <= 1:
return n
else:
return fibonacci_recur(n - 1) + fibonacci_recur(n - 2)
def main():
import time
n = 13
start_time = time.time()
print('{}th number of Fibonacci series by recursion: {}'
.format(n, fibonacci_recur(n)))
print('Time: {}'.format(time.time() - start_time))
if __name__ == '__main__':
main()
<commit_msg>Complete fiboncci_dp() by dynamic programming<commit_after>"""Fibonacci series:
0, 1, 1, 2, 3, 5, 8,...
- Fib(0) = 0
- Fib(1) = 1
- Fib(n) = Fib(n - 1) + Fib(n - 2)
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def fibonacci_recur(n):
"""Get nth number of Fibonacci series by recursion."""
if n <= 1:
return n
else:
return fibonacci_recur(n - 1) + fibonacci_recur(n - 2)
def fibonacci_dp(n):
"""Get nth number of Fibonacci series by dynamic programming.
DP performs much faster than recursion.
"""
a, b = 0, 1
for _ in xrange(n):
a, b = a+b, a
return a
def main():
import time
n = 35
start_time = time.time()
print('{}th number of Fibonacci series by recursion: {}'
.format(n, fibonacci_recur(n)))
print('Time: {}'.format(time.time() - start_time))
start_time = time.time()
print('{}th number of Fibonacci series by recursion: {}'
.format(n, fibonacci_dp(n)))
print('Time: {}'.format(time.time() - start_time))
if __name__ == '__main__':
main()
|
28a35d1434cb8dfdc9da130bd86518df4e8c6d4a | uniqueids/admin.py | uniqueids/admin.py | from django.contrib import admin
from .models import Record
from .tasks import send_personnel_code
class RecordAdmin(admin.ModelAdmin):
list_display = [
"id", "identity", "write_to", "created_at", "updated_at"]
list_filter = ["write_to", "created_at"]
search_fields = ["identity", "write_to"]
actions = ["resend_personnel_code"]
def resend_personnel_code(self, request, queryset):
created = 0
for record in queryset.filter(write_to="personnel_code").iterator():
send_personnel_code.apply_async(kwargs={
"identity": str(record.identity),
"personnel_code": record.id})
created += 1
if created == 1:
created_text = "%s Record was" % created
else:
created_text = "%s Records were" % created
self.message_user(request, "%s resent." % created_text)
resend_personnel_code.short_description = "Send code by SMS (personnel "\
"code only)"
admin.site.register(Record, RecordAdmin)
| from django.contrib import admin
from .models import Record
from .tasks import send_personnel_code
class RecordAdmin(admin.ModelAdmin):
list_display = [
"id", "identity", "write_to", "created_at", "updated_at"]
list_filter = ["write_to", "created_at"]
search_fields = ["identity", "write_to"]
actions = ["resend_personnel_code"]
def resend_personnel_code(self, request, queryset):
created = 0
for record in queryset.filter(write_to="personnel_code").iterator():
send_personnel_code.apply_async(kwargs={
"identity": str(record.identity),
"personnel_code": record.id})
created += 1
if created == 1:
created_text = "%s Record was" % created
else:
created_text = "%s Records were" % created
self.message_user(request, "%s resent." % created_text)
resend_personnel_code.short_description = (
"Send code by SMS (personnel code only)")
admin.site.register(Record, RecordAdmin)
| Improve formatting of resend action description | Improve formatting of resend action description
| Python | bsd-3-clause | praekelt/hellomama-registration,praekelt/hellomama-registration | from django.contrib import admin
from .models import Record
from .tasks import send_personnel_code
class RecordAdmin(admin.ModelAdmin):
list_display = [
"id", "identity", "write_to", "created_at", "updated_at"]
list_filter = ["write_to", "created_at"]
search_fields = ["identity", "write_to"]
actions = ["resend_personnel_code"]
def resend_personnel_code(self, request, queryset):
created = 0
for record in queryset.filter(write_to="personnel_code").iterator():
send_personnel_code.apply_async(kwargs={
"identity": str(record.identity),
"personnel_code": record.id})
created += 1
if created == 1:
created_text = "%s Record was" % created
else:
created_text = "%s Records were" % created
self.message_user(request, "%s resent." % created_text)
resend_personnel_code.short_description = "Send code by SMS (personnel "\
"code only)"
admin.site.register(Record, RecordAdmin)
Improve formatting of resend action description | from django.contrib import admin
from .models import Record
from .tasks import send_personnel_code
class RecordAdmin(admin.ModelAdmin):
list_display = [
"id", "identity", "write_to", "created_at", "updated_at"]
list_filter = ["write_to", "created_at"]
search_fields = ["identity", "write_to"]
actions = ["resend_personnel_code"]
def resend_personnel_code(self, request, queryset):
created = 0
for record in queryset.filter(write_to="personnel_code").iterator():
send_personnel_code.apply_async(kwargs={
"identity": str(record.identity),
"personnel_code": record.id})
created += 1
if created == 1:
created_text = "%s Record was" % created
else:
created_text = "%s Records were" % created
self.message_user(request, "%s resent." % created_text)
resend_personnel_code.short_description = (
"Send code by SMS (personnel code only)")
admin.site.register(Record, RecordAdmin)
| <commit_before>from django.contrib import admin
from .models import Record
from .tasks import send_personnel_code
class RecordAdmin(admin.ModelAdmin):
list_display = [
"id", "identity", "write_to", "created_at", "updated_at"]
list_filter = ["write_to", "created_at"]
search_fields = ["identity", "write_to"]
actions = ["resend_personnel_code"]
def resend_personnel_code(self, request, queryset):
created = 0
for record in queryset.filter(write_to="personnel_code").iterator():
send_personnel_code.apply_async(kwargs={
"identity": str(record.identity),
"personnel_code": record.id})
created += 1
if created == 1:
created_text = "%s Record was" % created
else:
created_text = "%s Records were" % created
self.message_user(request, "%s resent." % created_text)
resend_personnel_code.short_description = "Send code by SMS (personnel "\
"code only)"
admin.site.register(Record, RecordAdmin)
<commit_msg>Improve formatting of resend action description<commit_after> | from django.contrib import admin
from .models import Record
from .tasks import send_personnel_code
class RecordAdmin(admin.ModelAdmin):
list_display = [
"id", "identity", "write_to", "created_at", "updated_at"]
list_filter = ["write_to", "created_at"]
search_fields = ["identity", "write_to"]
actions = ["resend_personnel_code"]
def resend_personnel_code(self, request, queryset):
created = 0
for record in queryset.filter(write_to="personnel_code").iterator():
send_personnel_code.apply_async(kwargs={
"identity": str(record.identity),
"personnel_code": record.id})
created += 1
if created == 1:
created_text = "%s Record was" % created
else:
created_text = "%s Records were" % created
self.message_user(request, "%s resent." % created_text)
resend_personnel_code.short_description = (
"Send code by SMS (personnel code only)")
admin.site.register(Record, RecordAdmin)
| from django.contrib import admin
from .models import Record
from .tasks import send_personnel_code
class RecordAdmin(admin.ModelAdmin):
list_display = [
"id", "identity", "write_to", "created_at", "updated_at"]
list_filter = ["write_to", "created_at"]
search_fields = ["identity", "write_to"]
actions = ["resend_personnel_code"]
def resend_personnel_code(self, request, queryset):
created = 0
for record in queryset.filter(write_to="personnel_code").iterator():
send_personnel_code.apply_async(kwargs={
"identity": str(record.identity),
"personnel_code": record.id})
created += 1
if created == 1:
created_text = "%s Record was" % created
else:
created_text = "%s Records were" % created
self.message_user(request, "%s resent." % created_text)
resend_personnel_code.short_description = "Send code by SMS (personnel "\
"code only)"
admin.site.register(Record, RecordAdmin)
Improve formatting of resend action descriptionfrom django.contrib import admin
from .models import Record
from .tasks import send_personnel_code
class RecordAdmin(admin.ModelAdmin):
list_display = [
"id", "identity", "write_to", "created_at", "updated_at"]
list_filter = ["write_to", "created_at"]
search_fields = ["identity", "write_to"]
actions = ["resend_personnel_code"]
def resend_personnel_code(self, request, queryset):
created = 0
for record in queryset.filter(write_to="personnel_code").iterator():
send_personnel_code.apply_async(kwargs={
"identity": str(record.identity),
"personnel_code": record.id})
created += 1
if created == 1:
created_text = "%s Record was" % created
else:
created_text = "%s Records were" % created
self.message_user(request, "%s resent." % created_text)
resend_personnel_code.short_description = (
"Send code by SMS (personnel code only)")
admin.site.register(Record, RecordAdmin)
| <commit_before>from django.contrib import admin
from .models import Record
from .tasks import send_personnel_code
class RecordAdmin(admin.ModelAdmin):
list_display = [
"id", "identity", "write_to", "created_at", "updated_at"]
list_filter = ["write_to", "created_at"]
search_fields = ["identity", "write_to"]
actions = ["resend_personnel_code"]
def resend_personnel_code(self, request, queryset):
created = 0
for record in queryset.filter(write_to="personnel_code").iterator():
send_personnel_code.apply_async(kwargs={
"identity": str(record.identity),
"personnel_code": record.id})
created += 1
if created == 1:
created_text = "%s Record was" % created
else:
created_text = "%s Records were" % created
self.message_user(request, "%s resent." % created_text)
resend_personnel_code.short_description = "Send code by SMS (personnel "\
"code only)"
admin.site.register(Record, RecordAdmin)
<commit_msg>Improve formatting of resend action description<commit_after>from django.contrib import admin
from .models import Record
from .tasks import send_personnel_code
class RecordAdmin(admin.ModelAdmin):
list_display = [
"id", "identity", "write_to", "created_at", "updated_at"]
list_filter = ["write_to", "created_at"]
search_fields = ["identity", "write_to"]
actions = ["resend_personnel_code"]
def resend_personnel_code(self, request, queryset):
created = 0
for record in queryset.filter(write_to="personnel_code").iterator():
send_personnel_code.apply_async(kwargs={
"identity": str(record.identity),
"personnel_code": record.id})
created += 1
if created == 1:
created_text = "%s Record was" % created
else:
created_text = "%s Records were" % created
self.message_user(request, "%s resent." % created_text)
resend_personnel_code.short_description = (
"Send code by SMS (personnel code only)")
admin.site.register(Record, RecordAdmin)
|
d55dfc5152f6ebeabe761b627a26a9f00cc4e37c | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/libs/templatetags/url_tags.py | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/libs/templatetags/url_tags.py | # encoding: utf-8
from django import template
from django.http import QueryDict
from classytags.core import Tag, Options
from classytags.arguments import MultiKeywordArgument, MultiValueArgument
from libs.utils import canonical_url
register = template.Library()
@register.filter('canonical')
def _get_canonical_url(url):
return canonical_url(url, protocol="http:")
class QueryParameters(Tag):
name = 'query'
options = Options(
MultiKeywordArgument('kwa'),
)
def render_tag(self, context, kwa):
q = QueryDict('').copy()
q.update(kwa)
return q.urlencode()
register.tag(QueryParameters)
class GetParameters(Tag):
"""
{% raw %}{% get_parameters [except_field, ] %}{% endraw %}
"""
name = 'get_parameters'
options = Options(
MultiValueArgument('except_fields', required=False),
)
def render_tag(self, context, except_fields):
try:
# If there's an exception (500), default context_processors may not
# be called.
request = context['request']
except KeyError:
return context
getvars = request.GET.copy()
for field in except_fields:
if field in getvars:
del getvars[field]
return getvars.urlencode()
register.tag(GetParameters)
| # encoding: utf-8
from django import template
from django.http import QueryDict
from classytags.core import Tag, Options
from classytags.arguments import MultiKeywordArgument, MultiValueArgument
register = template.Library()
class QueryParameters(Tag):
name = 'query'
options = Options(
MultiKeywordArgument('kwa'),
)
def render_tag(self, context, kwa):
q = QueryDict('').copy()
q.update(kwa)
return q.urlencode()
register.tag(QueryParameters)
class GetParameters(Tag):
"""
{% raw %}{% get_parameters [except_field, ] %}{% endraw %}
"""
name = 'get_parameters'
options = Options(
MultiValueArgument('except_fields', required=False),
)
def render_tag(self, context, except_fields):
try:
# If there's an exception (500), default context_processors may not
# be called.
request = context['request']
except KeyError:
return context
getvars = request.GET.copy()
for field in except_fields:
if field in getvars:
del getvars[field]
return getvars.urlencode()
register.tag(GetParameters)
| Remove an old filter reference | Remove an old filter reference
| Python | mit | dulaccc/cookiecutter-django-herokuapp,dulaccc/cookiecutter-django-herokuapp,dulaccc/cookiecutter-django-herokuapp,dulaccc/cookiecutter-django-herokuapp | # encoding: utf-8
from django import template
from django.http import QueryDict
from classytags.core import Tag, Options
from classytags.arguments import MultiKeywordArgument, MultiValueArgument
from libs.utils import canonical_url
register = template.Library()
@register.filter('canonical')
def _get_canonical_url(url):
return canonical_url(url, protocol="http:")
class QueryParameters(Tag):
name = 'query'
options = Options(
MultiKeywordArgument('kwa'),
)
def render_tag(self, context, kwa):
q = QueryDict('').copy()
q.update(kwa)
return q.urlencode()
register.tag(QueryParameters)
class GetParameters(Tag):
"""
{% raw %}{% get_parameters [except_field, ] %}{% endraw %}
"""
name = 'get_parameters'
options = Options(
MultiValueArgument('except_fields', required=False),
)
def render_tag(self, context, except_fields):
try:
# If there's an exception (500), default context_processors may not
# be called.
request = context['request']
except KeyError:
return context
getvars = request.GET.copy()
for field in except_fields:
if field in getvars:
del getvars[field]
return getvars.urlencode()
register.tag(GetParameters)
Remove an old filter reference | # encoding: utf-8
from django import template
from django.http import QueryDict
from classytags.core import Tag, Options
from classytags.arguments import MultiKeywordArgument, MultiValueArgument
register = template.Library()
class QueryParameters(Tag):
name = 'query'
options = Options(
MultiKeywordArgument('kwa'),
)
def render_tag(self, context, kwa):
q = QueryDict('').copy()
q.update(kwa)
return q.urlencode()
register.tag(QueryParameters)
class GetParameters(Tag):
"""
{% raw %}{% get_parameters [except_field, ] %}{% endraw %}
"""
name = 'get_parameters'
options = Options(
MultiValueArgument('except_fields', required=False),
)
def render_tag(self, context, except_fields):
try:
# If there's an exception (500), default context_processors may not
# be called.
request = context['request']
except KeyError:
return context
getvars = request.GET.copy()
for field in except_fields:
if field in getvars:
del getvars[field]
return getvars.urlencode()
register.tag(GetParameters)
| <commit_before># encoding: utf-8
from django import template
from django.http import QueryDict
from classytags.core import Tag, Options
from classytags.arguments import MultiKeywordArgument, MultiValueArgument
from libs.utils import canonical_url
register = template.Library()
@register.filter('canonical')
def _get_canonical_url(url):
return canonical_url(url, protocol="http:")
class QueryParameters(Tag):
name = 'query'
options = Options(
MultiKeywordArgument('kwa'),
)
def render_tag(self, context, kwa):
q = QueryDict('').copy()
q.update(kwa)
return q.urlencode()
register.tag(QueryParameters)
class GetParameters(Tag):
"""
{% raw %}{% get_parameters [except_field, ] %}{% endraw %}
"""
name = 'get_parameters'
options = Options(
MultiValueArgument('except_fields', required=False),
)
def render_tag(self, context, except_fields):
try:
# If there's an exception (500), default context_processors may not
# be called.
request = context['request']
except KeyError:
return context
getvars = request.GET.copy()
for field in except_fields:
if field in getvars:
del getvars[field]
return getvars.urlencode()
register.tag(GetParameters)
<commit_msg>Remove an old filter reference<commit_after> | # encoding: utf-8
from django import template
from django.http import QueryDict
from classytags.core import Tag, Options
from classytags.arguments import MultiKeywordArgument, MultiValueArgument
register = template.Library()
class QueryParameters(Tag):
name = 'query'
options = Options(
MultiKeywordArgument('kwa'),
)
def render_tag(self, context, kwa):
q = QueryDict('').copy()
q.update(kwa)
return q.urlencode()
register.tag(QueryParameters)
class GetParameters(Tag):
"""
{% raw %}{% get_parameters [except_field, ] %}{% endraw %}
"""
name = 'get_parameters'
options = Options(
MultiValueArgument('except_fields', required=False),
)
def render_tag(self, context, except_fields):
try:
# If there's an exception (500), default context_processors may not
# be called.
request = context['request']
except KeyError:
return context
getvars = request.GET.copy()
for field in except_fields:
if field in getvars:
del getvars[field]
return getvars.urlencode()
register.tag(GetParameters)
| # encoding: utf-8
from django import template
from django.http import QueryDict
from classytags.core import Tag, Options
from classytags.arguments import MultiKeywordArgument, MultiValueArgument
from libs.utils import canonical_url
register = template.Library()
@register.filter('canonical')
def _get_canonical_url(url):
return canonical_url(url, protocol="http:")
class QueryParameters(Tag):
name = 'query'
options = Options(
MultiKeywordArgument('kwa'),
)
def render_tag(self, context, kwa):
q = QueryDict('').copy()
q.update(kwa)
return q.urlencode()
register.tag(QueryParameters)
class GetParameters(Tag):
"""
{% raw %}{% get_parameters [except_field, ] %}{% endraw %}
"""
name = 'get_parameters'
options = Options(
MultiValueArgument('except_fields', required=False),
)
def render_tag(self, context, except_fields):
try:
# If there's an exception (500), default context_processors may not
# be called.
request = context['request']
except KeyError:
return context
getvars = request.GET.copy()
for field in except_fields:
if field in getvars:
del getvars[field]
return getvars.urlencode()
register.tag(GetParameters)
Remove an old filter reference# encoding: utf-8
from django import template
from django.http import QueryDict
from classytags.core import Tag, Options
from classytags.arguments import MultiKeywordArgument, MultiValueArgument
register = template.Library()
class QueryParameters(Tag):
name = 'query'
options = Options(
MultiKeywordArgument('kwa'),
)
def render_tag(self, context, kwa):
q = QueryDict('').copy()
q.update(kwa)
return q.urlencode()
register.tag(QueryParameters)
class GetParameters(Tag):
"""
{% raw %}{% get_parameters [except_field, ] %}{% endraw %}
"""
name = 'get_parameters'
options = Options(
MultiValueArgument('except_fields', required=False),
)
def render_tag(self, context, except_fields):
try:
# If there's an exception (500), default context_processors may not
# be called.
request = context['request']
except KeyError:
return context
getvars = request.GET.copy()
for field in except_fields:
if field in getvars:
del getvars[field]
return getvars.urlencode()
register.tag(GetParameters)
| <commit_before># encoding: utf-8
from django import template
from django.http import QueryDict
from classytags.core import Tag, Options
from classytags.arguments import MultiKeywordArgument, MultiValueArgument
from libs.utils import canonical_url
register = template.Library()
@register.filter('canonical')
def _get_canonical_url(url):
return canonical_url(url, protocol="http:")
class QueryParameters(Tag):
name = 'query'
options = Options(
MultiKeywordArgument('kwa'),
)
def render_tag(self, context, kwa):
q = QueryDict('').copy()
q.update(kwa)
return q.urlencode()
register.tag(QueryParameters)
class GetParameters(Tag):
"""
{% raw %}{% get_parameters [except_field, ] %}{% endraw %}
"""
name = 'get_parameters'
options = Options(
MultiValueArgument('except_fields', required=False),
)
def render_tag(self, context, except_fields):
try:
# If there's an exception (500), default context_processors may not
# be called.
request = context['request']
except KeyError:
return context
getvars = request.GET.copy()
for field in except_fields:
if field in getvars:
del getvars[field]
return getvars.urlencode()
register.tag(GetParameters)
<commit_msg>Remove an old filter reference<commit_after># encoding: utf-8
from django import template
from django.http import QueryDict
from classytags.core import Tag, Options
from classytags.arguments import MultiKeywordArgument, MultiValueArgument
register = template.Library()
class QueryParameters(Tag):
name = 'query'
options = Options(
MultiKeywordArgument('kwa'),
)
def render_tag(self, context, kwa):
q = QueryDict('').copy()
q.update(kwa)
return q.urlencode()
register.tag(QueryParameters)
class GetParameters(Tag):
"""
{% raw %}{% get_parameters [except_field, ] %}{% endraw %}
"""
name = 'get_parameters'
options = Options(
MultiValueArgument('except_fields', required=False),
)
def render_tag(self, context, except_fields):
try:
# If there's an exception (500), default context_processors may not
# be called.
request = context['request']
except KeyError:
return context
getvars = request.GET.copy()
for field in except_fields:
if field in getvars:
del getvars[field]
return getvars.urlencode()
register.tag(GetParameters)
|
128a9a98879fdd52f1f3fb04355fc3094f3769ba | scipy/signal/setup.py | scipy/signal/setup.py | #!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('signal', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',
'firfilter.c','medianfilter.c'],
depends = ['sigtools.h']
)
config.add_extension('spline',
sources = ['splinemodule.c','S_bspline_util.c','D_bspline_util.c',
'C_bspline_util.c','Z_bspline_util.c','bspline_util.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| #!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('signal', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',
'firfilter.c','medianfilter.c'],
depends = ['sigtools.h', 'newsig.c']
)
config.add_extension('spline',
sources = ['splinemodule.c','S_bspline_util.c','D_bspline_util.c',
'C_bspline_util.c','Z_bspline_util.c','bspline_util.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| Add newsig.c as a dependency to sigtools module. | Add newsig.c as a dependency to sigtools module.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@5176 d6536bca-fef9-0310-8506-e4c0a848fbcf
| Python | bsd-3-clause | lesserwhirls/scipy-cwt,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,scipy/scipy-svn,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn | #!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('signal', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',
'firfilter.c','medianfilter.c'],
depends = ['sigtools.h']
)
config.add_extension('spline',
sources = ['splinemodule.c','S_bspline_util.c','D_bspline_util.c',
'C_bspline_util.c','Z_bspline_util.c','bspline_util.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
Add newsig.c as a dependency to sigtools module.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@5176 d6536bca-fef9-0310-8506-e4c0a848fbcf | #!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('signal', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',
'firfilter.c','medianfilter.c'],
depends = ['sigtools.h', 'newsig.c']
)
config.add_extension('spline',
sources = ['splinemodule.c','S_bspline_util.c','D_bspline_util.c',
'C_bspline_util.c','Z_bspline_util.c','bspline_util.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| <commit_before>#!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('signal', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',
'firfilter.c','medianfilter.c'],
depends = ['sigtools.h']
)
config.add_extension('spline',
sources = ['splinemodule.c','S_bspline_util.c','D_bspline_util.c',
'C_bspline_util.c','Z_bspline_util.c','bspline_util.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
<commit_msg>Add newsig.c as a dependency to sigtools module.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@5176 d6536bca-fef9-0310-8506-e4c0a848fbcf<commit_after> | #!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('signal', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',
'firfilter.c','medianfilter.c'],
depends = ['sigtools.h', 'newsig.c']
)
config.add_extension('spline',
sources = ['splinemodule.c','S_bspline_util.c','D_bspline_util.c',
'C_bspline_util.c','Z_bspline_util.c','bspline_util.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| #!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('signal', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',
'firfilter.c','medianfilter.c'],
depends = ['sigtools.h']
)
config.add_extension('spline',
sources = ['splinemodule.c','S_bspline_util.c','D_bspline_util.c',
'C_bspline_util.c','Z_bspline_util.c','bspline_util.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
Add newsig.c as a dependency to sigtools module.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@5176 d6536bca-fef9-0310-8506-e4c0a848fbcf#!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('signal', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',
'firfilter.c','medianfilter.c'],
depends = ['sigtools.h', 'newsig.c']
)
config.add_extension('spline',
sources = ['splinemodule.c','S_bspline_util.c','D_bspline_util.c',
'C_bspline_util.c','Z_bspline_util.c','bspline_util.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| <commit_before>#!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('signal', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',
'firfilter.c','medianfilter.c'],
depends = ['sigtools.h']
)
config.add_extension('spline',
sources = ['splinemodule.c','S_bspline_util.c','D_bspline_util.c',
'C_bspline_util.c','Z_bspline_util.c','bspline_util.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
<commit_msg>Add newsig.c as a dependency to sigtools module.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@5176 d6536bca-fef9-0310-8506-e4c0a848fbcf<commit_after>#!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('signal', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('sigtools',
sources=['sigtoolsmodule.c',
'firfilter.c','medianfilter.c'],
depends = ['sigtools.h', 'newsig.c']
)
config.add_extension('spline',
sources = ['splinemodule.c','S_bspline_util.c','D_bspline_util.c',
'C_bspline_util.c','Z_bspline_util.c','bspline_util.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
|
9aad4c5f22b8dd84711df2c85147f4cb37c23802 | tools/initialcompdata/abundomegacen.py | tools/initialcompdata/abundomegacen.py | from abundsolar import elsolarlogepsilon
zfactor = 10 ** -1.92
# Smith et al. (2000) ROA 219 in Omega Centauri
# [Fe/H] is about ~-1.7
#logxtofe = log epsilon(X) - log epsilon(Fe)
targetlogxtofe = {'rb': 1.34 - 6.25,
'y': 1.15 - 6.25,
'zr': 2.01 - 6.25,
'ba': 1.88 - 6.25,
'la': 0.75 - 6.25,
'ce': 0.42 - 6.25,
'pb': 0.40 + elsolarlogepsilon['pb'] - elsolarlogepsilon['fe'] #D'Orazi+2011 Leiden 60066
} | from abundsolar import elsolarlogepsilon
zfactor = 10 ** -1.92
# Smith et al. (2000) ROA 219 in Omega Centauri
# [Fe/H] is about ~-1.7
#logxtofe = log epsilon(X) - log epsilon(Fe)
targetlogxtofe = {'rb': 1.34 - 6.25,
'y': 1.15 - 6.25,
'zr': 2.01 - 6.25,
'ba': 1.88 - 6.25,
'la': 0.75 - 6.25,
'ce': 0.42 - 6.25,
'pb': 0.40 + elsolarlogepsilon['pb'] - elsolarlogepsilon['fe'] #D'Orazi+2011 Leiden 60066
}
| Fix missing newline at EOF | Fix missing newline at EOF
| Python | mit | lukeshingles/evelchemevol | from abundsolar import elsolarlogepsilon
zfactor = 10 ** -1.92
# Smith et al. (2000) ROA 219 in Omega Centauri
# [Fe/H] is about ~-1.7
#logxtofe = log epsilon(X) - log epsilon(Fe)
targetlogxtofe = {'rb': 1.34 - 6.25,
'y': 1.15 - 6.25,
'zr': 2.01 - 6.25,
'ba': 1.88 - 6.25,
'la': 0.75 - 6.25,
'ce': 0.42 - 6.25,
'pb': 0.40 + elsolarlogepsilon['pb'] - elsolarlogepsilon['fe'] #D'Orazi+2011 Leiden 60066
}Fix missing newline at EOF | from abundsolar import elsolarlogepsilon
zfactor = 10 ** -1.92
# Smith et al. (2000) ROA 219 in Omega Centauri
# [Fe/H] is about ~-1.7
#logxtofe = log epsilon(X) - log epsilon(Fe)
targetlogxtofe = {'rb': 1.34 - 6.25,
'y': 1.15 - 6.25,
'zr': 2.01 - 6.25,
'ba': 1.88 - 6.25,
'la': 0.75 - 6.25,
'ce': 0.42 - 6.25,
'pb': 0.40 + elsolarlogepsilon['pb'] - elsolarlogepsilon['fe'] #D'Orazi+2011 Leiden 60066
}
| <commit_before>from abundsolar import elsolarlogepsilon
zfactor = 10 ** -1.92
# Smith et al. (2000) ROA 219 in Omega Centauri
# [Fe/H] is about ~-1.7
#logxtofe = log epsilon(X) - log epsilon(Fe)
targetlogxtofe = {'rb': 1.34 - 6.25,
'y': 1.15 - 6.25,
'zr': 2.01 - 6.25,
'ba': 1.88 - 6.25,
'la': 0.75 - 6.25,
'ce': 0.42 - 6.25,
'pb': 0.40 + elsolarlogepsilon['pb'] - elsolarlogepsilon['fe'] #D'Orazi+2011 Leiden 60066
}<commit_msg>Fix missing newline at EOF<commit_after> | from abundsolar import elsolarlogepsilon
zfactor = 10 ** -1.92
# Smith et al. (2000) ROA 219 in Omega Centauri
# [Fe/H] is about ~-1.7
#logxtofe = log epsilon(X) - log epsilon(Fe)
targetlogxtofe = {'rb': 1.34 - 6.25,
'y': 1.15 - 6.25,
'zr': 2.01 - 6.25,
'ba': 1.88 - 6.25,
'la': 0.75 - 6.25,
'ce': 0.42 - 6.25,
'pb': 0.40 + elsolarlogepsilon['pb'] - elsolarlogepsilon['fe'] #D'Orazi+2011 Leiden 60066
}
| from abundsolar import elsolarlogepsilon
zfactor = 10 ** -1.92
# Smith et al. (2000) ROA 219 in Omega Centauri
# [Fe/H] is about ~-1.7
#logxtofe = log epsilon(X) - log epsilon(Fe)
targetlogxtofe = {'rb': 1.34 - 6.25,
'y': 1.15 - 6.25,
'zr': 2.01 - 6.25,
'ba': 1.88 - 6.25,
'la': 0.75 - 6.25,
'ce': 0.42 - 6.25,
'pb': 0.40 + elsolarlogepsilon['pb'] - elsolarlogepsilon['fe'] #D'Orazi+2011 Leiden 60066
}Fix missing newline at EOFfrom abundsolar import elsolarlogepsilon
zfactor = 10 ** -1.92
# Smith et al. (2000) ROA 219 in Omega Centauri
# [Fe/H] is about ~-1.7
#logxtofe = log epsilon(X) - log epsilon(Fe)
targetlogxtofe = {'rb': 1.34 - 6.25,
'y': 1.15 - 6.25,
'zr': 2.01 - 6.25,
'ba': 1.88 - 6.25,
'la': 0.75 - 6.25,
'ce': 0.42 - 6.25,
'pb': 0.40 + elsolarlogepsilon['pb'] - elsolarlogepsilon['fe'] #D'Orazi+2011 Leiden 60066
}
| <commit_before>from abundsolar import elsolarlogepsilon
zfactor = 10 ** -1.92
# Smith et al. (2000) ROA 219 in Omega Centauri
# [Fe/H] is about ~-1.7
#logxtofe = log epsilon(X) - log epsilon(Fe)
targetlogxtofe = {'rb': 1.34 - 6.25,
'y': 1.15 - 6.25,
'zr': 2.01 - 6.25,
'ba': 1.88 - 6.25,
'la': 0.75 - 6.25,
'ce': 0.42 - 6.25,
'pb': 0.40 + elsolarlogepsilon['pb'] - elsolarlogepsilon['fe'] #D'Orazi+2011 Leiden 60066
}<commit_msg>Fix missing newline at EOF<commit_after>from abundsolar import elsolarlogepsilon
zfactor = 10 ** -1.92
# Smith et al. (2000) ROA 219 in Omega Centauri
# [Fe/H] is about ~-1.7
#logxtofe = log epsilon(X) - log epsilon(Fe)
targetlogxtofe = {'rb': 1.34 - 6.25,
'y': 1.15 - 6.25,
'zr': 2.01 - 6.25,
'ba': 1.88 - 6.25,
'la': 0.75 - 6.25,
'ce': 0.42 - 6.25,
'pb': 0.40 + elsolarlogepsilon['pb'] - elsolarlogepsilon['fe'] #D'Orazi+2011 Leiden 60066
}
|
3c69ace12b7aadd094ce3325cf935c66b9e27e0b | example_config.py | example_config.py | """
File to easily switch between configurations between production and
development, etc.
"""
import os
# You must set each of these in your heroku environment with the heroku
# config:set command. See README.md for more information.
HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID',
'GITHUB_SECRET', 'DATABASE_URL',
'SQLALCHEMY_DATABASE_URI', 'REPO_OWNER',
'REPO_NAME', 'REPO_OWNER_ACCESS_TOKEN',
'REDISCLOUD_URL')
class Config(object):
DEBUG = False
CSRF_ENABLED = True
GITHUB_CLIENT_ID = 'replace-me'
GITHUB_SECRET = 'replace-me'
HEROKU = False
SECRET_KEY = 'not-a-good-value'
# Details of the repo where all articles are stored. The GITHUB_CLIENT_ID
# and GITHUB_SECRET should allow full-access to this database.
REPO_OWNER = None
REPO_NAME = None
REPO_OWNER_ACCESS_TOKEN = None
REDISCLOUD_URL = None
# This should automatically be set by heroku if you've added a database to
# your app.
try:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
except KeyError:
print 'Failed finding DATABASE_URL environment variable'
SQLALCHEMY_DATABASE_URI = ''
class DevelopmentConfig(Config):
DEBUG = True
| """
File to easily switch between configurations between production and
development, etc.
"""
import os
# You must set each of these in your heroku environment with the heroku
# config:set command. See README.md for more information.
HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID',
'GITHUB_SECRET', 'DATABASE_URL',
'SQLALCHEMY_DATABASE_URI', 'REPO_OWNER',
'REPO_NAME', 'REPO_OWNER_ACCESS_TOKEN',
'REDISCLOUD_URL', 'SECONDARY_REPO_OWNER',
'SECONDARY_REPO_NAME')
class Config(object):
DEBUG = False
CSRF_ENABLED = True
GITHUB_CLIENT_ID = 'replace-me'
GITHUB_SECRET = 'replace-me'
HEROKU = False
SECRET_KEY = 'not-a-good-value'
# Details of the repo where all articles are stored. The GITHUB_CLIENT_ID
# and GITHUB_SECRET should allow full-access to this database.
REPO_OWNER = None
REPO_NAME = None
REPO_OWNER_ACCESS_TOKEN = None
# Secondary (optional) repo for articles that are not editable
SECONDARY_REPO_OWNER = None
SECONDARY_REPO_NAME = None
REDISCLOUD_URL = None
# This should automatically be set by heroku if you've added a database to
# your app.
try:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
except KeyError:
print 'Failed finding DATABASE_URL environment variable'
SQLALCHEMY_DATABASE_URI = ''
class DevelopmentConfig(Config):
DEBUG = True
| Add placeholders for new secondary repo details | Add placeholders for new secondary repo details
| Python | agpl-3.0 | pluralsight/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms,paulocheque/guides-cms | """
File to easily switch between configurations between production and
development, etc.
"""
import os
# You must set each of these in your heroku environment with the heroku
# config:set command. See README.md for more information.
HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID',
'GITHUB_SECRET', 'DATABASE_URL',
'SQLALCHEMY_DATABASE_URI', 'REPO_OWNER',
'REPO_NAME', 'REPO_OWNER_ACCESS_TOKEN',
'REDISCLOUD_URL')
class Config(object):
DEBUG = False
CSRF_ENABLED = True
GITHUB_CLIENT_ID = 'replace-me'
GITHUB_SECRET = 'replace-me'
HEROKU = False
SECRET_KEY = 'not-a-good-value'
# Details of the repo where all articles are stored. The GITHUB_CLIENT_ID
# and GITHUB_SECRET should allow full-access to this database.
REPO_OWNER = None
REPO_NAME = None
REPO_OWNER_ACCESS_TOKEN = None
REDISCLOUD_URL = None
# This should automatically be set by heroku if you've added a database to
# your app.
try:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
except KeyError:
print 'Failed finding DATABASE_URL environment variable'
SQLALCHEMY_DATABASE_URI = ''
class DevelopmentConfig(Config):
DEBUG = True
Add placeholders for new secondary repo details | """
File to easily switch between configurations between production and
development, etc.
"""
import os
# You must set each of these in your heroku environment with the heroku
# config:set command. See README.md for more information.
HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID',
'GITHUB_SECRET', 'DATABASE_URL',
'SQLALCHEMY_DATABASE_URI', 'REPO_OWNER',
'REPO_NAME', 'REPO_OWNER_ACCESS_TOKEN',
'REDISCLOUD_URL', 'SECONDARY_REPO_OWNER',
'SECONDARY_REPO_NAME')
class Config(object):
DEBUG = False
CSRF_ENABLED = True
GITHUB_CLIENT_ID = 'replace-me'
GITHUB_SECRET = 'replace-me'
HEROKU = False
SECRET_KEY = 'not-a-good-value'
# Details of the repo where all articles are stored. The GITHUB_CLIENT_ID
# and GITHUB_SECRET should allow full-access to this database.
REPO_OWNER = None
REPO_NAME = None
REPO_OWNER_ACCESS_TOKEN = None
# Secondary (optional) repo for articles that are not editable
SECONDARY_REPO_OWNER = None
SECONDARY_REPO_NAME = None
REDISCLOUD_URL = None
# This should automatically be set by heroku if you've added a database to
# your app.
try:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
except KeyError:
print 'Failed finding DATABASE_URL environment variable'
SQLALCHEMY_DATABASE_URI = ''
class DevelopmentConfig(Config):
DEBUG = True
| <commit_before>"""
File to easily switch between configurations between production and
development, etc.
"""
import os
# You must set each of these in your heroku environment with the heroku
# config:set command. See README.md for more information.
HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID',
'GITHUB_SECRET', 'DATABASE_URL',
'SQLALCHEMY_DATABASE_URI', 'REPO_OWNER',
'REPO_NAME', 'REPO_OWNER_ACCESS_TOKEN',
'REDISCLOUD_URL')
class Config(object):
DEBUG = False
CSRF_ENABLED = True
GITHUB_CLIENT_ID = 'replace-me'
GITHUB_SECRET = 'replace-me'
HEROKU = False
SECRET_KEY = 'not-a-good-value'
# Details of the repo where all articles are stored. The GITHUB_CLIENT_ID
# and GITHUB_SECRET should allow full-access to this database.
REPO_OWNER = None
REPO_NAME = None
REPO_OWNER_ACCESS_TOKEN = None
REDISCLOUD_URL = None
# This should automatically be set by heroku if you've added a database to
# your app.
try:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
except KeyError:
print 'Failed finding DATABASE_URL environment variable'
SQLALCHEMY_DATABASE_URI = ''
class DevelopmentConfig(Config):
DEBUG = True
<commit_msg>Add placeholders for new secondary repo details<commit_after> | """
File to easily switch between configurations between production and
development, etc.
"""
import os
# You must set each of these in your heroku environment with the heroku
# config:set command. See README.md for more information.
HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID',
'GITHUB_SECRET', 'DATABASE_URL',
'SQLALCHEMY_DATABASE_URI', 'REPO_OWNER',
'REPO_NAME', 'REPO_OWNER_ACCESS_TOKEN',
'REDISCLOUD_URL', 'SECONDARY_REPO_OWNER',
'SECONDARY_REPO_NAME')
class Config(object):
DEBUG = False
CSRF_ENABLED = True
GITHUB_CLIENT_ID = 'replace-me'
GITHUB_SECRET = 'replace-me'
HEROKU = False
SECRET_KEY = 'not-a-good-value'
# Details of the repo where all articles are stored. The GITHUB_CLIENT_ID
# and GITHUB_SECRET should allow full-access to this database.
REPO_OWNER = None
REPO_NAME = None
REPO_OWNER_ACCESS_TOKEN = None
# Secondary (optional) repo for articles that are not editable
SECONDARY_REPO_OWNER = None
SECONDARY_REPO_NAME = None
REDISCLOUD_URL = None
# This should automatically be set by heroku if you've added a database to
# your app.
try:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
except KeyError:
print 'Failed finding DATABASE_URL environment variable'
SQLALCHEMY_DATABASE_URI = ''
class DevelopmentConfig(Config):
DEBUG = True
| """
File to easily switch between configurations between production and
development, etc.
"""
import os
# You must set each of these in your heroku environment with the heroku
# config:set command. See README.md for more information.
HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID',
'GITHUB_SECRET', 'DATABASE_URL',
'SQLALCHEMY_DATABASE_URI', 'REPO_OWNER',
'REPO_NAME', 'REPO_OWNER_ACCESS_TOKEN',
'REDISCLOUD_URL')
class Config(object):
DEBUG = False
CSRF_ENABLED = True
GITHUB_CLIENT_ID = 'replace-me'
GITHUB_SECRET = 'replace-me'
HEROKU = False
SECRET_KEY = 'not-a-good-value'
# Details of the repo where all articles are stored. The GITHUB_CLIENT_ID
# and GITHUB_SECRET should allow full-access to this database.
REPO_OWNER = None
REPO_NAME = None
REPO_OWNER_ACCESS_TOKEN = None
REDISCLOUD_URL = None
# This should automatically be set by heroku if you've added a database to
# your app.
try:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
except KeyError:
print 'Failed finding DATABASE_URL environment variable'
SQLALCHEMY_DATABASE_URI = ''
class DevelopmentConfig(Config):
DEBUG = True
Add placeholders for new secondary repo details"""
File to easily switch between configurations between production and
development, etc.
"""
import os
# You must set each of these in your heroku environment with the heroku
# config:set command. See README.md for more information.
HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID',
'GITHUB_SECRET', 'DATABASE_URL',
'SQLALCHEMY_DATABASE_URI', 'REPO_OWNER',
'REPO_NAME', 'REPO_OWNER_ACCESS_TOKEN',
'REDISCLOUD_URL', 'SECONDARY_REPO_OWNER',
'SECONDARY_REPO_NAME')
class Config(object):
DEBUG = False
CSRF_ENABLED = True
GITHUB_CLIENT_ID = 'replace-me'
GITHUB_SECRET = 'replace-me'
HEROKU = False
SECRET_KEY = 'not-a-good-value'
# Details of the repo where all articles are stored. The GITHUB_CLIENT_ID
# and GITHUB_SECRET should allow full-access to this database.
REPO_OWNER = None
REPO_NAME = None
REPO_OWNER_ACCESS_TOKEN = None
# Secondary (optional) repo for articles that are not editable
SECONDARY_REPO_OWNER = None
SECONDARY_REPO_NAME = None
REDISCLOUD_URL = None
# This should automatically be set by heroku if you've added a database to
# your app.
try:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
except KeyError:
print 'Failed finding DATABASE_URL environment variable'
SQLALCHEMY_DATABASE_URI = ''
class DevelopmentConfig(Config):
DEBUG = True
| <commit_before>"""
File to easily switch between configurations between production and
development, etc.
"""
import os
# You must set each of these in your heroku environment with the heroku
# config:set command. See README.md for more information.
HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID',
'GITHUB_SECRET', 'DATABASE_URL',
'SQLALCHEMY_DATABASE_URI', 'REPO_OWNER',
'REPO_NAME', 'REPO_OWNER_ACCESS_TOKEN',
'REDISCLOUD_URL')
class Config(object):
DEBUG = False
CSRF_ENABLED = True
GITHUB_CLIENT_ID = 'replace-me'
GITHUB_SECRET = 'replace-me'
HEROKU = False
SECRET_KEY = 'not-a-good-value'
# Details of the repo where all articles are stored. The GITHUB_CLIENT_ID
# and GITHUB_SECRET should allow full-access to this database.
REPO_OWNER = None
REPO_NAME = None
REPO_OWNER_ACCESS_TOKEN = None
REDISCLOUD_URL = None
# This should automatically be set by heroku if you've added a database to
# your app.
try:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
except KeyError:
print 'Failed finding DATABASE_URL environment variable'
SQLALCHEMY_DATABASE_URI = ''
class DevelopmentConfig(Config):
DEBUG = True
<commit_msg>Add placeholders for new secondary repo details<commit_after>"""
File to easily switch between configurations between production and
development, etc.
"""
import os
# You must set each of these in your heroku environment with the heroku
# config:set command. See README.md for more information.
HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID',
'GITHUB_SECRET', 'DATABASE_URL',
'SQLALCHEMY_DATABASE_URI', 'REPO_OWNER',
'REPO_NAME', 'REPO_OWNER_ACCESS_TOKEN',
'REDISCLOUD_URL', 'SECONDARY_REPO_OWNER',
'SECONDARY_REPO_NAME')
class Config(object):
DEBUG = False
CSRF_ENABLED = True
GITHUB_CLIENT_ID = 'replace-me'
GITHUB_SECRET = 'replace-me'
HEROKU = False
SECRET_KEY = 'not-a-good-value'
# Details of the repo where all articles are stored. The GITHUB_CLIENT_ID
# and GITHUB_SECRET should allow full-access to this database.
REPO_OWNER = None
REPO_NAME = None
REPO_OWNER_ACCESS_TOKEN = None
# Secondary (optional) repo for articles that are not editable
SECONDARY_REPO_OWNER = None
SECONDARY_REPO_NAME = None
REDISCLOUD_URL = None
# This should automatically be set by heroku if you've added a database to
# your app.
try:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
except KeyError:
print 'Failed finding DATABASE_URL environment variable'
SQLALCHEMY_DATABASE_URI = ''
class DevelopmentConfig(Config):
DEBUG = True
|
64b4abde42b653e66444876dee0700afa64e6c6b | releasetasks/test/__init__.py | releasetasks/test/__init__.py | import os
import yaml
def read_file(path):
with open(path) as f:
return f.read()
PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa")
PVT_KEY = read_file(PVT_KEY_FILE)
PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub"))
OTHER_PUB_KEY = read_file(os.path.join(os.path.dirname(__file__),
"other_rsa.pub"))
DUMMY_PUBLIC_KEY = os.path.join(os.path.dirname(__file__), "public.key")
def create_test_args(non_standard_arguments, permitted_defaults=None):
with open(os.path.join(os.path.dirname(__file__), 'test_graph_parameters.yml')) as f:
default_arguments = yaml.safe_load(f)
default_arguments.update(non_standard_arguments)
if permitted_defaults is not None:
default_arguments = {
key: val
for key, val in default_arguments.items()
if key in non_standard_arguments or key in permitted_defaults
}
return default_arguments
| import os
import yaml
def read_file(path):
with open(path) as f:
return f.read()
PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa")
PVT_KEY = read_file(PVT_KEY_FILE)
PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub"))
OTHER_PUB_KEY = read_file(os.path.join(os.path.dirname(__file__),
"other_rsa.pub"))
DUMMY_PUBLIC_KEY = os.path.join(os.path.dirname(__file__), "public.key")
def create_test_args(non_standard_arguments):
with open(os.path.join(os.path.dirname(__file__), 'test_graph_parameters.yml')) as f:
default_arguments = yaml.safe_load(f)
default_arguments.update(non_standard_arguments)
return default_arguments
| Remove redundant keyword argument from create_test_args | Remove redundant keyword argument from create_test_args
| Python | mpl-2.0 | mozilla/releasetasks,bhearsum/releasetasks,rail/releasetasks | import os
import yaml
def read_file(path):
with open(path) as f:
return f.read()
PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa")
PVT_KEY = read_file(PVT_KEY_FILE)
PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub"))
OTHER_PUB_KEY = read_file(os.path.join(os.path.dirname(__file__),
"other_rsa.pub"))
DUMMY_PUBLIC_KEY = os.path.join(os.path.dirname(__file__), "public.key")
def create_test_args(non_standard_arguments, permitted_defaults=None):
with open(os.path.join(os.path.dirname(__file__), 'test_graph_parameters.yml')) as f:
default_arguments = yaml.safe_load(f)
default_arguments.update(non_standard_arguments)
if permitted_defaults is not None:
default_arguments = {
key: val
for key, val in default_arguments.items()
if key in non_standard_arguments or key in permitted_defaults
}
return default_arguments
Remove redundant keyword argument from create_test_args | import os
import yaml
def read_file(path):
with open(path) as f:
return f.read()
PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa")
PVT_KEY = read_file(PVT_KEY_FILE)
PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub"))
OTHER_PUB_KEY = read_file(os.path.join(os.path.dirname(__file__),
"other_rsa.pub"))
DUMMY_PUBLIC_KEY = os.path.join(os.path.dirname(__file__), "public.key")
def create_test_args(non_standard_arguments):
with open(os.path.join(os.path.dirname(__file__), 'test_graph_parameters.yml')) as f:
default_arguments = yaml.safe_load(f)
default_arguments.update(non_standard_arguments)
return default_arguments
| <commit_before>import os
import yaml
def read_file(path):
with open(path) as f:
return f.read()
PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa")
PVT_KEY = read_file(PVT_KEY_FILE)
PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub"))
OTHER_PUB_KEY = read_file(os.path.join(os.path.dirname(__file__),
"other_rsa.pub"))
DUMMY_PUBLIC_KEY = os.path.join(os.path.dirname(__file__), "public.key")
def create_test_args(non_standard_arguments, permitted_defaults=None):
with open(os.path.join(os.path.dirname(__file__), 'test_graph_parameters.yml')) as f:
default_arguments = yaml.safe_load(f)
default_arguments.update(non_standard_arguments)
if permitted_defaults is not None:
default_arguments = {
key: val
for key, val in default_arguments.items()
if key in non_standard_arguments or key in permitted_defaults
}
return default_arguments
<commit_msg>Remove redundant keyword argument from create_test_args<commit_after> | import os
import yaml
def read_file(path):
with open(path) as f:
return f.read()
PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa")
PVT_KEY = read_file(PVT_KEY_FILE)
PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub"))
OTHER_PUB_KEY = read_file(os.path.join(os.path.dirname(__file__),
"other_rsa.pub"))
DUMMY_PUBLIC_KEY = os.path.join(os.path.dirname(__file__), "public.key")
def create_test_args(non_standard_arguments):
with open(os.path.join(os.path.dirname(__file__), 'test_graph_parameters.yml')) as f:
default_arguments = yaml.safe_load(f)
default_arguments.update(non_standard_arguments)
return default_arguments
| import os
import yaml
def read_file(path):
with open(path) as f:
return f.read()
PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa")
PVT_KEY = read_file(PVT_KEY_FILE)
PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub"))
OTHER_PUB_KEY = read_file(os.path.join(os.path.dirname(__file__),
"other_rsa.pub"))
DUMMY_PUBLIC_KEY = os.path.join(os.path.dirname(__file__), "public.key")
def create_test_args(non_standard_arguments, permitted_defaults=None):
with open(os.path.join(os.path.dirname(__file__), 'test_graph_parameters.yml')) as f:
default_arguments = yaml.safe_load(f)
default_arguments.update(non_standard_arguments)
if permitted_defaults is not None:
default_arguments = {
key: val
for key, val in default_arguments.items()
if key in non_standard_arguments or key in permitted_defaults
}
return default_arguments
Remove redundant keyword argument from create_test_argsimport os
import yaml
def read_file(path):
with open(path) as f:
return f.read()
PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa")
PVT_KEY = read_file(PVT_KEY_FILE)
PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub"))
OTHER_PUB_KEY = read_file(os.path.join(os.path.dirname(__file__),
"other_rsa.pub"))
DUMMY_PUBLIC_KEY = os.path.join(os.path.dirname(__file__), "public.key")
def create_test_args(non_standard_arguments):
with open(os.path.join(os.path.dirname(__file__), 'test_graph_parameters.yml')) as f:
default_arguments = yaml.safe_load(f)
default_arguments.update(non_standard_arguments)
return default_arguments
| <commit_before>import os
import yaml
def read_file(path):
with open(path) as f:
return f.read()
PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa")
PVT_KEY = read_file(PVT_KEY_FILE)
PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub"))
OTHER_PUB_KEY = read_file(os.path.join(os.path.dirname(__file__),
"other_rsa.pub"))
DUMMY_PUBLIC_KEY = os.path.join(os.path.dirname(__file__), "public.key")
def create_test_args(non_standard_arguments, permitted_defaults=None):
with open(os.path.join(os.path.dirname(__file__), 'test_graph_parameters.yml')) as f:
default_arguments = yaml.safe_load(f)
default_arguments.update(non_standard_arguments)
if permitted_defaults is not None:
default_arguments = {
key: val
for key, val in default_arguments.items()
if key in non_standard_arguments or key in permitted_defaults
}
return default_arguments
<commit_msg>Remove redundant keyword argument from create_test_args<commit_after>import os
import yaml
def read_file(path):
with open(path) as f:
return f.read()
PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa")
PVT_KEY = read_file(PVT_KEY_FILE)
PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub"))
OTHER_PUB_KEY = read_file(os.path.join(os.path.dirname(__file__),
"other_rsa.pub"))
DUMMY_PUBLIC_KEY = os.path.join(os.path.dirname(__file__), "public.key")
def create_test_args(non_standard_arguments):
with open(os.path.join(os.path.dirname(__file__), 'test_graph_parameters.yml')) as f:
default_arguments = yaml.safe_load(f)
default_arguments.update(non_standard_arguments)
return default_arguments
|
effbffd67d52561ca1ba09201782aafc6cfc52f7 | blog/posts/models.py | blog/posts/models.py | from django.db import models
# Create your models here.
| from django.db import models
class Author(models.Model):
name = models.CharField(max_length=20)
email = models.EmailField(max_length=254)
def __unicode__(self):
return self.name
class Post(models.Model):
body = models.TextField()
title = models.CharField(max_length=50)
author = models.ForeignKey(Author)
publication_date = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.title
| Set up the DB schema for posts. | Set up the DB schema for posts.
| Python | mit | Lukasa/minimalog | from django.db import models
# Create your models here.
Set up the DB schema for posts. | from django.db import models
class Author(models.Model):
name = models.CharField(max_length=20)
email = models.EmailField(max_length=254)
def __unicode__(self):
return self.name
class Post(models.Model):
body = models.TextField()
title = models.CharField(max_length=50)
author = models.ForeignKey(Author)
publication_date = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.title
| <commit_before>from django.db import models
# Create your models here.
<commit_msg>Set up the DB schema for posts.<commit_after> | from django.db import models
class Author(models.Model):
name = models.CharField(max_length=20)
email = models.EmailField(max_length=254)
def __unicode__(self):
return self.name
class Post(models.Model):
body = models.TextField()
title = models.CharField(max_length=50)
author = models.ForeignKey(Author)
publication_date = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.title
| from django.db import models
# Create your models here.
Set up the DB schema for posts.from django.db import models
class Author(models.Model):
name = models.CharField(max_length=20)
email = models.EmailField(max_length=254)
def __unicode__(self):
return self.name
class Post(models.Model):
body = models.TextField()
title = models.CharField(max_length=50)
author = models.ForeignKey(Author)
publication_date = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.title
| <commit_before>from django.db import models
# Create your models here.
<commit_msg>Set up the DB schema for posts.<commit_after>from django.db import models
class Author(models.Model):
name = models.CharField(max_length=20)
email = models.EmailField(max_length=254)
def __unicode__(self):
return self.name
class Post(models.Model):
body = models.TextField()
title = models.CharField(max_length=50)
author = models.ForeignKey(Author)
publication_date = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.title
|
e5c4d03a8c0ef66299d30fb0ecca6dfc54c15506 | cerberus/__init__.py | cerberus/__init__.py | __all__ = ['client', 'user_auth', 'aws_auth', 'util']
CLIENT_VERSION = '1.2.0'
class CerberusClientException(Exception):
"""Wrap third-party exceptions expected by the Cerberus client."""
pass
| __all__ = ['client', 'user_auth', 'aws_auth', 'util']
CLIENT_VERSION = '1.3.0'
class CerberusClientException(Exception):
"""Wrap third-party exceptions expected by the Cerberus client."""
pass
| Update client version to 1.3.0 | Update client version to 1.3.0
| Python | apache-2.0 | Nike-Inc/cerberus-python-client | __all__ = ['client', 'user_auth', 'aws_auth', 'util']
CLIENT_VERSION = '1.2.0'
class CerberusClientException(Exception):
"""Wrap third-party exceptions expected by the Cerberus client."""
pass
Update client version to 1.3.0 | __all__ = ['client', 'user_auth', 'aws_auth', 'util']
CLIENT_VERSION = '1.3.0'
class CerberusClientException(Exception):
"""Wrap third-party exceptions expected by the Cerberus client."""
pass
| <commit_before>__all__ = ['client', 'user_auth', 'aws_auth', 'util']
CLIENT_VERSION = '1.2.0'
class CerberusClientException(Exception):
"""Wrap third-party exceptions expected by the Cerberus client."""
pass
<commit_msg>Update client version to 1.3.0<commit_after> | __all__ = ['client', 'user_auth', 'aws_auth', 'util']
CLIENT_VERSION = '1.3.0'
class CerberusClientException(Exception):
"""Wrap third-party exceptions expected by the Cerberus client."""
pass
| __all__ = ['client', 'user_auth', 'aws_auth', 'util']
CLIENT_VERSION = '1.2.0'
class CerberusClientException(Exception):
"""Wrap third-party exceptions expected by the Cerberus client."""
pass
Update client version to 1.3.0__all__ = ['client', 'user_auth', 'aws_auth', 'util']
CLIENT_VERSION = '1.3.0'
class CerberusClientException(Exception):
"""Wrap third-party exceptions expected by the Cerberus client."""
pass
| <commit_before>__all__ = ['client', 'user_auth', 'aws_auth', 'util']
CLIENT_VERSION = '1.2.0'
class CerberusClientException(Exception):
"""Wrap third-party exceptions expected by the Cerberus client."""
pass
<commit_msg>Update client version to 1.3.0<commit_after>__all__ = ['client', 'user_auth', 'aws_auth', 'util']
CLIENT_VERSION = '1.3.0'
class CerberusClientException(Exception):
"""Wrap third-party exceptions expected by the Cerberus client."""
pass
|
8cfe4d9ef565502b247b7ac3b438b49f257c7012 | enable/layout/ab_constrainable.py | enable/layout/ab_constrainable.py | #------------------------------------------------------------------------------
# Copyright (c) 2012, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
from abc import ABCMeta
class ABConstrainable(object):
""" An abstract base class for objects that can be laid out using
layout helpers.
Minimally, instances need to have `top`, `bottom`, `left`, `right`,
`width`, `height`, `v_center` and `h_center` attributes which are
`LinearSymbolic` instances.
"""
__metaclass__ = ABCMeta
| #------------------------------------------------------------------------------
# Copyright (c) 2012, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
from abc import ABCMeta
class ABConstrainable(object):
""" An abstract base class for objects that can be laid out using
layout helpers.
Minimally, instances need to have `top`, `bottom`, `left`, `right`,
`layout_width`, `layout_height`, `v_center` and `h_center` attributes
which are `LinearSymbolic` instances.
"""
__metaclass__ = ABCMeta
| Fix a small docstring bug. | Fix a small docstring bug.
| Python | bsd-3-clause | tommy-u/enable,tommy-u/enable,tommy-u/enable,tommy-u/enable | #------------------------------------------------------------------------------
# Copyright (c) 2012, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
from abc import ABCMeta
class ABConstrainable(object):
""" An abstract base class for objects that can be laid out using
layout helpers.
Minimally, instances need to have `top`, `bottom`, `left`, `right`,
`width`, `height`, `v_center` and `h_center` attributes which are
`LinearSymbolic` instances.
"""
__metaclass__ = ABCMeta
Fix a small docstring bug. | #------------------------------------------------------------------------------
# Copyright (c) 2012, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
from abc import ABCMeta
class ABConstrainable(object):
""" An abstract base class for objects that can be laid out using
layout helpers.
Minimally, instances need to have `top`, `bottom`, `left`, `right`,
`layout_width`, `layout_height`, `v_center` and `h_center` attributes
which are `LinearSymbolic` instances.
"""
__metaclass__ = ABCMeta
| <commit_before>#------------------------------------------------------------------------------
# Copyright (c) 2012, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
from abc import ABCMeta
class ABConstrainable(object):
""" An abstract base class for objects that can be laid out using
layout helpers.
Minimally, instances need to have `top`, `bottom`, `left`, `right`,
`width`, `height`, `v_center` and `h_center` attributes which are
`LinearSymbolic` instances.
"""
__metaclass__ = ABCMeta
<commit_msg>Fix a small docstring bug.<commit_after> | #------------------------------------------------------------------------------
# Copyright (c) 2012, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
from abc import ABCMeta
class ABConstrainable(object):
""" An abstract base class for objects that can be laid out using
layout helpers.
Minimally, instances need to have `top`, `bottom`, `left`, `right`,
`layout_width`, `layout_height`, `v_center` and `h_center` attributes
which are `LinearSymbolic` instances.
"""
__metaclass__ = ABCMeta
| #------------------------------------------------------------------------------
# Copyright (c) 2012, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
from abc import ABCMeta
class ABConstrainable(object):
""" An abstract base class for objects that can be laid out using
layout helpers.
Minimally, instances need to have `top`, `bottom`, `left`, `right`,
`width`, `height`, `v_center` and `h_center` attributes which are
`LinearSymbolic` instances.
"""
__metaclass__ = ABCMeta
Fix a small docstring bug.#------------------------------------------------------------------------------
# Copyright (c) 2012, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
from abc import ABCMeta
class ABConstrainable(object):
""" An abstract base class for objects that can be laid out using
layout helpers.
Minimally, instances need to have `top`, `bottom`, `left`, `right`,
`layout_width`, `layout_height`, `v_center` and `h_center` attributes
which are `LinearSymbolic` instances.
"""
__metaclass__ = ABCMeta
| <commit_before>#------------------------------------------------------------------------------
# Copyright (c) 2012, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
from abc import ABCMeta
class ABConstrainable(object):
""" An abstract base class for objects that can be laid out using
layout helpers.
Minimally, instances need to have `top`, `bottom`, `left`, `right`,
`width`, `height`, `v_center` and `h_center` attributes which are
`LinearSymbolic` instances.
"""
__metaclass__ = ABCMeta
<commit_msg>Fix a small docstring bug.<commit_after>#------------------------------------------------------------------------------
# Copyright (c) 2012, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
from abc import ABCMeta
class ABConstrainable(object):
""" An abstract base class for objects that can be laid out using
layout helpers.
Minimally, instances need to have `top`, `bottom`, `left`, `right`,
`layout_width`, `layout_height`, `v_center` and `h_center` attributes
which are `LinearSymbolic` instances.
"""
__metaclass__ = ABCMeta
|
62abb800b1b40cfbce120c0f3fb5169e32daaa60 | accounts/management/__init__.py | accounts/management/__init__.py | from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name="Giftcards")
liabilities.add_child(name="User accounts")
#post_syncdb.connect(ensure_core_accounts_exists, sender=models)
| from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name=names.UNIT_NAME_PLURAL)
liabilities.add_child(name="User accounts")
#post_syncdb.connect(ensure_core_accounts_exists, sender=models)
| Change code-account name triggered during creation | Change code-account name triggered during creation
| Python | bsd-3-clause | Jannes123/django-oscar-accounts,amsys/django-account-balances,michaelkuty/django-oscar-accounts,michaelkuty/django-oscar-accounts,Mariana-Tek/django-oscar-accounts,machtfit/django-oscar-accounts,carver/django-account-balances,machtfit/django-oscar-accounts,amsys/django-account-balances,Mariana-Tek/django-oscar-accounts,Jannes123/django-oscar-accounts,django-oscar/django-oscar-accounts,django-oscar/django-oscar-accounts | from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name="Giftcards")
liabilities.add_child(name="User accounts")
#post_syncdb.connect(ensure_core_accounts_exists, sender=models)
Change code-account name triggered during creation | from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name=names.UNIT_NAME_PLURAL)
liabilities.add_child(name="User accounts")
#post_syncdb.connect(ensure_core_accounts_exists, sender=models)
| <commit_before>from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name="Giftcards")
liabilities.add_child(name="User accounts")
#post_syncdb.connect(ensure_core_accounts_exists, sender=models)
<commit_msg>Change code-account name triggered during creation<commit_after> | from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name=names.UNIT_NAME_PLURAL)
liabilities.add_child(name="User accounts")
#post_syncdb.connect(ensure_core_accounts_exists, sender=models)
| from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name="Giftcards")
liabilities.add_child(name="User accounts")
#post_syncdb.connect(ensure_core_accounts_exists, sender=models)
Change code-account name triggered during creationfrom accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name=names.UNIT_NAME_PLURAL)
liabilities.add_child(name="User accounts")
#post_syncdb.connect(ensure_core_accounts_exists, sender=models)
| <commit_before>from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name="Giftcards")
liabilities.add_child(name="User accounts")
#post_syncdb.connect(ensure_core_accounts_exists, sender=models)
<commit_msg>Change code-account name triggered during creation<commit_after>from accounts import models, names
def ensure_core_accounts_exists(sender, **kwargs):
# We only create core accounts the first time syncdb is run
if models.Account.objects.all().count() > 0:
return
# Create asset accounts
assets = models.AccountType.add_root(name='Assets')
assets.accounts.create(name=names.REDEMPTIONS)
assets.accounts.create(name=names.LAPSED)
# Create liability accounts
liabilities = models.AccountType.add_root(name='Liabilities')
liabilities.accounts.create(name=names.MERCHANT_SOURCE,
credit_limit=None)
liabilities.add_child(name=names.UNIT_NAME_PLURAL)
liabilities.add_child(name="User accounts")
#post_syncdb.connect(ensure_core_accounts_exists, sender=models)
|
332bbd84477498a045cfdd7b56b21127fa366a2b | socli/sentry.py | socli/sentry.py | # Initialize Sentry
import sentry_sdk
sentry_sdk.init(
"https://95c4106659044cbda2ea0fe499f4be7e@o323465.ingest.sentry.io/5445901",
traces_sample_rate=0.5
)
from socli.socli import main
main()
| # Initialize Sentry
import sentry_sdk
sentry_sdk.init(
"https://95c4106659044cbda2ea0fe499f4be7e@o323465.ingest.sentry.io/5445901",
traces_sample_rate=1.0
)
from socli.socli import main
main()
| Set sample rate to 1.0 | Set sample rate to 1.0
| Python | bsd-3-clause | gautamkrishnar/socli | # Initialize Sentry
import sentry_sdk
sentry_sdk.init(
"https://95c4106659044cbda2ea0fe499f4be7e@o323465.ingest.sentry.io/5445901",
traces_sample_rate=0.5
)
from socli.socli import main
main()
Set sample rate to 1.0 | # Initialize Sentry
import sentry_sdk
sentry_sdk.init(
"https://95c4106659044cbda2ea0fe499f4be7e@o323465.ingest.sentry.io/5445901",
traces_sample_rate=1.0
)
from socli.socli import main
main()
| <commit_before># Initialize Sentry
import sentry_sdk
sentry_sdk.init(
"https://95c4106659044cbda2ea0fe499f4be7e@o323465.ingest.sentry.io/5445901",
traces_sample_rate=0.5
)
from socli.socli import main
main()
<commit_msg>Set sample rate to 1.0<commit_after> | # Initialize Sentry
import sentry_sdk
sentry_sdk.init(
"https://95c4106659044cbda2ea0fe499f4be7e@o323465.ingest.sentry.io/5445901",
traces_sample_rate=1.0
)
from socli.socli import main
main()
| # Initialize Sentry
import sentry_sdk
sentry_sdk.init(
"https://95c4106659044cbda2ea0fe499f4be7e@o323465.ingest.sentry.io/5445901",
traces_sample_rate=0.5
)
from socli.socli import main
main()
Set sample rate to 1.0# Initialize Sentry
import sentry_sdk
sentry_sdk.init(
"https://95c4106659044cbda2ea0fe499f4be7e@o323465.ingest.sentry.io/5445901",
traces_sample_rate=1.0
)
from socli.socli import main
main()
| <commit_before># Initialize Sentry
import sentry_sdk
sentry_sdk.init(
"https://95c4106659044cbda2ea0fe499f4be7e@o323465.ingest.sentry.io/5445901",
traces_sample_rate=0.5
)
from socli.socli import main
main()
<commit_msg>Set sample rate to 1.0<commit_after># Initialize Sentry
import sentry_sdk
sentry_sdk.init(
"https://95c4106659044cbda2ea0fe499f4be7e@o323465.ingest.sentry.io/5445901",
traces_sample_rate=1.0
)
from socli.socli import main
main()
|
e6d4ca44f3f71468c40842c53e3963b425ac2527 | mss/factory.py | mss/factory.py | """
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import platform
from typing import TYPE_CHECKING
from .exception import ScreenShotError
if TYPE_CHECKING:
from typing import Any # noqa
from .base import MSSMixin # noqa
def mss(**kwargs):
# type: (Any) -> MSSMixin
""" Factory returning a proper MSS class instance.
It detects the plateform we are running on
and choose the most adapted mss_class to take
screenshots.
It then proxies its arguments to the class for
instantiation.
"""
os_ = platform.system().lower()
if os_ == "darwin":
from . import darwin
return darwin.MSS(**kwargs)
if os_ == "linux":
from . import linux
return linux.MSS(**kwargs)
if os_ == "windows":
from . import windows
return windows.MSS(**kwargs)
raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
| """
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import platform
from typing import TYPE_CHECKING
from .exception import ScreenShotError
if TYPE_CHECKING:
from typing import Any # noqa
from .base import MSSMixin # noqa
def mss(**kwargs):
# type: (Any) -> MSSMixin
""" Factory returning a proper MSS class instance.
It detects the plateform we are running on
and choose the most adapted mss_class to take
screenshots.
It then proxies its arguments to the class for
instantiation.
"""
# pylint: disable=import-outside-toplevel
os_ = platform.system().lower()
if os_ == "darwin":
from . import darwin
return darwin.MSS(**kwargs)
if os_ == "linux":
from . import linux
return linux.MSS(**kwargs)
if os_ == "windows":
from . import windows
return windows.MSS(**kwargs)
raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
| Fix pylint: Import outside toplevel (%s) (import-outside-toplevel) | MSS: Fix pylint: Import outside toplevel (%s) (import-outside-toplevel)
| Python | mit | BoboTiG/python-mss | """
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import platform
from typing import TYPE_CHECKING
from .exception import ScreenShotError
if TYPE_CHECKING:
from typing import Any # noqa
from .base import MSSMixin # noqa
def mss(**kwargs):
# type: (Any) -> MSSMixin
""" Factory returning a proper MSS class instance.
It detects the plateform we are running on
and choose the most adapted mss_class to take
screenshots.
It then proxies its arguments to the class for
instantiation.
"""
os_ = platform.system().lower()
if os_ == "darwin":
from . import darwin
return darwin.MSS(**kwargs)
if os_ == "linux":
from . import linux
return linux.MSS(**kwargs)
if os_ == "windows":
from . import windows
return windows.MSS(**kwargs)
raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
MSS: Fix pylint: Import outside toplevel (%s) (import-outside-toplevel) | """
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import platform
from typing import TYPE_CHECKING
from .exception import ScreenShotError
if TYPE_CHECKING:
from typing import Any # noqa
from .base import MSSMixin # noqa
def mss(**kwargs):
# type: (Any) -> MSSMixin
""" Factory returning a proper MSS class instance.
It detects the plateform we are running on
and choose the most adapted mss_class to take
screenshots.
It then proxies its arguments to the class for
instantiation.
"""
# pylint: disable=import-outside-toplevel
os_ = platform.system().lower()
if os_ == "darwin":
from . import darwin
return darwin.MSS(**kwargs)
if os_ == "linux":
from . import linux
return linux.MSS(**kwargs)
if os_ == "windows":
from . import windows
return windows.MSS(**kwargs)
raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
| <commit_before>"""
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import platform
from typing import TYPE_CHECKING
from .exception import ScreenShotError
if TYPE_CHECKING:
from typing import Any # noqa
from .base import MSSMixin # noqa
def mss(**kwargs):
# type: (Any) -> MSSMixin
""" Factory returning a proper MSS class instance.
It detects the plateform we are running on
and choose the most adapted mss_class to take
screenshots.
It then proxies its arguments to the class for
instantiation.
"""
os_ = platform.system().lower()
if os_ == "darwin":
from . import darwin
return darwin.MSS(**kwargs)
if os_ == "linux":
from . import linux
return linux.MSS(**kwargs)
if os_ == "windows":
from . import windows
return windows.MSS(**kwargs)
raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
<commit_msg>MSS: Fix pylint: Import outside toplevel (%s) (import-outside-toplevel)<commit_after> | """
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import platform
from typing import TYPE_CHECKING
from .exception import ScreenShotError
if TYPE_CHECKING:
from typing import Any # noqa
from .base import MSSMixin # noqa
def mss(**kwargs):
# type: (Any) -> MSSMixin
""" Factory returning a proper MSS class instance.
It detects the plateform we are running on
and choose the most adapted mss_class to take
screenshots.
It then proxies its arguments to the class for
instantiation.
"""
# pylint: disable=import-outside-toplevel
os_ = platform.system().lower()
if os_ == "darwin":
from . import darwin
return darwin.MSS(**kwargs)
if os_ == "linux":
from . import linux
return linux.MSS(**kwargs)
if os_ == "windows":
from . import windows
return windows.MSS(**kwargs)
raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
| """
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import platform
from typing import TYPE_CHECKING
from .exception import ScreenShotError
if TYPE_CHECKING:
from typing import Any # noqa
from .base import MSSMixin # noqa
def mss(**kwargs):
# type: (Any) -> MSSMixin
""" Factory returning a proper MSS class instance.
It detects the plateform we are running on
and choose the most adapted mss_class to take
screenshots.
It then proxies its arguments to the class for
instantiation.
"""
os_ = platform.system().lower()
if os_ == "darwin":
from . import darwin
return darwin.MSS(**kwargs)
if os_ == "linux":
from . import linux
return linux.MSS(**kwargs)
if os_ == "windows":
from . import windows
return windows.MSS(**kwargs)
raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
MSS: Fix pylint: Import outside toplevel (%s) (import-outside-toplevel)"""
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import platform
from typing import TYPE_CHECKING
from .exception import ScreenShotError
if TYPE_CHECKING:
from typing import Any # noqa
from .base import MSSMixin # noqa
def mss(**kwargs):
# type: (Any) -> MSSMixin
""" Factory returning a proper MSS class instance.
It detects the plateform we are running on
and choose the most adapted mss_class to take
screenshots.
It then proxies its arguments to the class for
instantiation.
"""
# pylint: disable=import-outside-toplevel
os_ = platform.system().lower()
if os_ == "darwin":
from . import darwin
return darwin.MSS(**kwargs)
if os_ == "linux":
from . import linux
return linux.MSS(**kwargs)
if os_ == "windows":
from . import windows
return windows.MSS(**kwargs)
raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
| <commit_before>"""
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import platform
from typing import TYPE_CHECKING
from .exception import ScreenShotError
if TYPE_CHECKING:
from typing import Any # noqa
from .base import MSSMixin # noqa
def mss(**kwargs):
# type: (Any) -> MSSMixin
""" Factory returning a proper MSS class instance.
It detects the plateform we are running on
and choose the most adapted mss_class to take
screenshots.
It then proxies its arguments to the class for
instantiation.
"""
os_ = platform.system().lower()
if os_ == "darwin":
from . import darwin
return darwin.MSS(**kwargs)
if os_ == "linux":
from . import linux
return linux.MSS(**kwargs)
if os_ == "windows":
from . import windows
return windows.MSS(**kwargs)
raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
<commit_msg>MSS: Fix pylint: Import outside toplevel (%s) (import-outside-toplevel)<commit_after>"""
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import platform
from typing import TYPE_CHECKING
from .exception import ScreenShotError
if TYPE_CHECKING:
from typing import Any # noqa
from .base import MSSMixin # noqa
def mss(**kwargs):
# type: (Any) -> MSSMixin
""" Factory returning a proper MSS class instance.
It detects the plateform we are running on
and choose the most adapted mss_class to take
screenshots.
It then proxies its arguments to the class for
instantiation.
"""
# pylint: disable=import-outside-toplevel
os_ = platform.system().lower()
if os_ == "darwin":
from . import darwin
return darwin.MSS(**kwargs)
if os_ == "linux":
from . import linux
return linux.MSS(**kwargs)
if os_ == "windows":
from . import windows
return windows.MSS(**kwargs)
raise ScreenShotError("System {!r} not (yet?) implemented.".format(os_))
|
65b2dd9e0293265d528059a3a240d555661d1460 | main/models.py | main/models.py | from django.db import models
from django.contric.auth.models import User
from django.template.defaultfilters import slugify
#class MyModel(models.Model):
# title = models.CharField(max_length=255)
# slug = models.SlugField()
# author = models.ForeignKey(User)
# content = models.TextField()
# created_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ['-created_at']
#
# def __unicode__(self):
# return self.title
#
# def get_absolute_url(self):
# return '/my-object/%s-%d' % (self.slug, self.id)
#
# def save(self, *args, **kwargs):
# self.slug = slugify("%s-%d" % (self.title, self.id))
| from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
#class Document(models.Model):
# title = models.CharField(max_length=255)
# slug = models.SlugField()
# author = models.ForeignKey(User)
# content = models.TextField()
# created_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ['-created_at']
#
# def __unicode__(self):
# return self.title
#
# def get_absolute_url(self):
# return '/my-object/%s-%d' % (self.slug, self.id)
#
# def save(self, *args, **kwargs):
# self.slug = slugify("%s-%d" % (self.title, self.id))
| Rename the generic model to Document | Rename the generic model to Document
| Python | bsd-3-clause | strycore/djung,strycore/djung,strycore/djung,strycore/djung | from django.db import models
from django.contric.auth.models import User
from django.template.defaultfilters import slugify
#class MyModel(models.Model):
# title = models.CharField(max_length=255)
# slug = models.SlugField()
# author = models.ForeignKey(User)
# content = models.TextField()
# created_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ['-created_at']
#
# def __unicode__(self):
# return self.title
#
# def get_absolute_url(self):
# return '/my-object/%s-%d' % (self.slug, self.id)
#
# def save(self, *args, **kwargs):
# self.slug = slugify("%s-%d" % (self.title, self.id))
Rename the generic model to Document | from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
#class Document(models.Model):
# title = models.CharField(max_length=255)
# slug = models.SlugField()
# author = models.ForeignKey(User)
# content = models.TextField()
# created_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ['-created_at']
#
# def __unicode__(self):
# return self.title
#
# def get_absolute_url(self):
# return '/my-object/%s-%d' % (self.slug, self.id)
#
# def save(self, *args, **kwargs):
# self.slug = slugify("%s-%d" % (self.title, self.id))
| <commit_before>from django.db import models
from django.contric.auth.models import User
from django.template.defaultfilters import slugify
#class MyModel(models.Model):
# title = models.CharField(max_length=255)
# slug = models.SlugField()
# author = models.ForeignKey(User)
# content = models.TextField()
# created_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ['-created_at']
#
# def __unicode__(self):
# return self.title
#
# def get_absolute_url(self):
# return '/my-object/%s-%d' % (self.slug, self.id)
#
# def save(self, *args, **kwargs):
# self.slug = slugify("%s-%d" % (self.title, self.id))
<commit_msg>Rename the generic model to Document<commit_after> | from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
#class Document(models.Model):
# title = models.CharField(max_length=255)
# slug = models.SlugField()
# author = models.ForeignKey(User)
# content = models.TextField()
# created_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ['-created_at']
#
# def __unicode__(self):
# return self.title
#
# def get_absolute_url(self):
# return '/my-object/%s-%d' % (self.slug, self.id)
#
# def save(self, *args, **kwargs):
# self.slug = slugify("%s-%d" % (self.title, self.id))
| from django.db import models
from django.contric.auth.models import User
from django.template.defaultfilters import slugify
#class MyModel(models.Model):
# title = models.CharField(max_length=255)
# slug = models.SlugField()
# author = models.ForeignKey(User)
# content = models.TextField()
# created_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ['-created_at']
#
# def __unicode__(self):
# return self.title
#
# def get_absolute_url(self):
# return '/my-object/%s-%d' % (self.slug, self.id)
#
# def save(self, *args, **kwargs):
# self.slug = slugify("%s-%d" % (self.title, self.id))
Rename the generic model to Documentfrom django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
#class Document(models.Model):
# title = models.CharField(max_length=255)
# slug = models.SlugField()
# author = models.ForeignKey(User)
# content = models.TextField()
# created_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ['-created_at']
#
# def __unicode__(self):
# return self.title
#
# def get_absolute_url(self):
# return '/my-object/%s-%d' % (self.slug, self.id)
#
# def save(self, *args, **kwargs):
# self.slug = slugify("%s-%d" % (self.title, self.id))
| <commit_before>from django.db import models
from django.contric.auth.models import User
from django.template.defaultfilters import slugify
#class MyModel(models.Model):
# title = models.CharField(max_length=255)
# slug = models.SlugField()
# author = models.ForeignKey(User)
# content = models.TextField()
# created_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ['-created_at']
#
# def __unicode__(self):
# return self.title
#
# def get_absolute_url(self):
# return '/my-object/%s-%d' % (self.slug, self.id)
#
# def save(self, *args, **kwargs):
# self.slug = slugify("%s-%d" % (self.title, self.id))
<commit_msg>Rename the generic model to Document<commit_after>from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
#class Document(models.Model):
# title = models.CharField(max_length=255)
# slug = models.SlugField()
# author = models.ForeignKey(User)
# content = models.TextField()
# created_at = models.DateTimeField(auto_now=True)
#
# class Meta:
# ordering = ['-created_at']
#
# def __unicode__(self):
# return self.title
#
# def get_absolute_url(self):
# return '/my-object/%s-%d' % (self.slug, self.id)
#
# def save(self, *args, **kwargs):
# self.slug = slugify("%s-%d" % (self.title, self.id))
|
760a543cf13552ce951fee12c6e9a9d5d335a168 | formation/output_specification.py | formation/output_specification.py | # -*- coding: utf-8 -*-
import json
from . import ATTRIBUTE_SPECIFICATION_PATH, REF_SPECIFICATION_PATH
class OutputSpecification(object):
def __init__(
self, attribute_specification_path=ATTRIBUTE_SPECIFICATION_PATH,
ref_specification_path=REF_SPECIFICATION_PATH
):
self.attribute_specification_path = attribute_specification_path
self.ref_specification_path = ref_specification_path
@property
def attribute_specification(self):
with open(self.attribute_specification_path) as f:
data = json.load(f)
return data
@property
def ref_specification(self):
with open(self.ref_specification_path) as f:
data = json.load(f)
return data
def get_refs(self, resource_type):
return self.ref_specification[resource_type]
def get_attributes(self, resource_type):
return self.attribute_specification[resource_type]
| # -*- coding: utf-8 -*-
import json
from . import ATTRIBUTE_SPECIFICATION_PATH, REF_SPECIFICATION_PATH
class OutputSpecification(object):
def __init__(
self, attribute_specification_path=ATTRIBUTE_SPECIFICATION_PATH,
ref_specification_path=REF_SPECIFICATION_PATH
):
self.attribute_specification_path = attribute_specification_path
self.ref_specification_path = ref_specification_path
@property
def attribute_specification(self):
with open(self.attribute_specification_path) as f:
data = json.load(f)
return data
@property
def ref_specification(self):
with open(self.ref_specification_path) as f:
data = json.load(f)
return data
def get_refs(self, resource_type):
return self.ref_specification.get(resource_type, [])
def get_attributes(self, resource_type):
return self.attribute_specification.get(resource_type, [])
| Handle resources with no outputs | Handle resources with no outputs
| Python | apache-2.0 | jamesroutley/formation | # -*- coding: utf-8 -*-
import json
from . import ATTRIBUTE_SPECIFICATION_PATH, REF_SPECIFICATION_PATH
class OutputSpecification(object):
def __init__(
self, attribute_specification_path=ATTRIBUTE_SPECIFICATION_PATH,
ref_specification_path=REF_SPECIFICATION_PATH
):
self.attribute_specification_path = attribute_specification_path
self.ref_specification_path = ref_specification_path
@property
def attribute_specification(self):
with open(self.attribute_specification_path) as f:
data = json.load(f)
return data
@property
def ref_specification(self):
with open(self.ref_specification_path) as f:
data = json.load(f)
return data
def get_refs(self, resource_type):
return self.ref_specification[resource_type]
def get_attributes(self, resource_type):
return self.attribute_specification[resource_type]
Handle resources with no outputs | # -*- coding: utf-8 -*-
import json
from . import ATTRIBUTE_SPECIFICATION_PATH, REF_SPECIFICATION_PATH
class OutputSpecification(object):
def __init__(
self, attribute_specification_path=ATTRIBUTE_SPECIFICATION_PATH,
ref_specification_path=REF_SPECIFICATION_PATH
):
self.attribute_specification_path = attribute_specification_path
self.ref_specification_path = ref_specification_path
@property
def attribute_specification(self):
with open(self.attribute_specification_path) as f:
data = json.load(f)
return data
@property
def ref_specification(self):
with open(self.ref_specification_path) as f:
data = json.load(f)
return data
def get_refs(self, resource_type):
return self.ref_specification.get(resource_type, [])
def get_attributes(self, resource_type):
return self.attribute_specification.get(resource_type, [])
| <commit_before># -*- coding: utf-8 -*-
import json
from . import ATTRIBUTE_SPECIFICATION_PATH, REF_SPECIFICATION_PATH
class OutputSpecification(object):
def __init__(
self, attribute_specification_path=ATTRIBUTE_SPECIFICATION_PATH,
ref_specification_path=REF_SPECIFICATION_PATH
):
self.attribute_specification_path = attribute_specification_path
self.ref_specification_path = ref_specification_path
@property
def attribute_specification(self):
with open(self.attribute_specification_path) as f:
data = json.load(f)
return data
@property
def ref_specification(self):
with open(self.ref_specification_path) as f:
data = json.load(f)
return data
def get_refs(self, resource_type):
return self.ref_specification[resource_type]
def get_attributes(self, resource_type):
return self.attribute_specification[resource_type]
<commit_msg>Handle resources with no outputs<commit_after> | # -*- coding: utf-8 -*-
import json
from . import ATTRIBUTE_SPECIFICATION_PATH, REF_SPECIFICATION_PATH
class OutputSpecification(object):
def __init__(
self, attribute_specification_path=ATTRIBUTE_SPECIFICATION_PATH,
ref_specification_path=REF_SPECIFICATION_PATH
):
self.attribute_specification_path = attribute_specification_path
self.ref_specification_path = ref_specification_path
@property
def attribute_specification(self):
with open(self.attribute_specification_path) as f:
data = json.load(f)
return data
@property
def ref_specification(self):
with open(self.ref_specification_path) as f:
data = json.load(f)
return data
def get_refs(self, resource_type):
return self.ref_specification.get(resource_type, [])
def get_attributes(self, resource_type):
return self.attribute_specification.get(resource_type, [])
| # -*- coding: utf-8 -*-
import json
from . import ATTRIBUTE_SPECIFICATION_PATH, REF_SPECIFICATION_PATH
class OutputSpecification(object):
def __init__(
self, attribute_specification_path=ATTRIBUTE_SPECIFICATION_PATH,
ref_specification_path=REF_SPECIFICATION_PATH
):
self.attribute_specification_path = attribute_specification_path
self.ref_specification_path = ref_specification_path
@property
def attribute_specification(self):
with open(self.attribute_specification_path) as f:
data = json.load(f)
return data
@property
def ref_specification(self):
with open(self.ref_specification_path) as f:
data = json.load(f)
return data
def get_refs(self, resource_type):
return self.ref_specification[resource_type]
def get_attributes(self, resource_type):
return self.attribute_specification[resource_type]
Handle resources with no outputs# -*- coding: utf-8 -*-
import json
from . import ATTRIBUTE_SPECIFICATION_PATH, REF_SPECIFICATION_PATH
class OutputSpecification(object):
def __init__(
self, attribute_specification_path=ATTRIBUTE_SPECIFICATION_PATH,
ref_specification_path=REF_SPECIFICATION_PATH
):
self.attribute_specification_path = attribute_specification_path
self.ref_specification_path = ref_specification_path
@property
def attribute_specification(self):
with open(self.attribute_specification_path) as f:
data = json.load(f)
return data
@property
def ref_specification(self):
with open(self.ref_specification_path) as f:
data = json.load(f)
return data
def get_refs(self, resource_type):
return self.ref_specification.get(resource_type, [])
def get_attributes(self, resource_type):
return self.attribute_specification.get(resource_type, [])
| <commit_before># -*- coding: utf-8 -*-
import json
from . import ATTRIBUTE_SPECIFICATION_PATH, REF_SPECIFICATION_PATH
class OutputSpecification(object):
def __init__(
self, attribute_specification_path=ATTRIBUTE_SPECIFICATION_PATH,
ref_specification_path=REF_SPECIFICATION_PATH
):
self.attribute_specification_path = attribute_specification_path
self.ref_specification_path = ref_specification_path
@property
def attribute_specification(self):
with open(self.attribute_specification_path) as f:
data = json.load(f)
return data
@property
def ref_specification(self):
with open(self.ref_specification_path) as f:
data = json.load(f)
return data
def get_refs(self, resource_type):
return self.ref_specification[resource_type]
def get_attributes(self, resource_type):
return self.attribute_specification[resource_type]
<commit_msg>Handle resources with no outputs<commit_after># -*- coding: utf-8 -*-
import json
from . import ATTRIBUTE_SPECIFICATION_PATH, REF_SPECIFICATION_PATH
class OutputSpecification(object):
def __init__(
self, attribute_specification_path=ATTRIBUTE_SPECIFICATION_PATH,
ref_specification_path=REF_SPECIFICATION_PATH
):
self.attribute_specification_path = attribute_specification_path
self.ref_specification_path = ref_specification_path
@property
def attribute_specification(self):
with open(self.attribute_specification_path) as f:
data = json.load(f)
return data
@property
def ref_specification(self):
with open(self.ref_specification_path) as f:
data = json.load(f)
return data
def get_refs(self, resource_type):
return self.ref_specification.get(resource_type, [])
def get_attributes(self, resource_type):
return self.attribute_specification.get(resource_type, [])
|
7a7afea2539048d172b1d5abfc4a4d9dff0827e7 | runtests.py | runtests.py | #!/usr/bin/env python
import sys
from os.path import dirname, abspath
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASE_ENGINE = 'sqlite3',
SITE_ID = 1,
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
),
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
),
ROOT_URLCONF = 'relationships.relationships_tests.urls',
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'relationships',
'relationships.relationships_tests',
],
)
from django.test.simple import run_tests
def runtests(*test_args):
if not test_args:
test_args = ['relationships_tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
| #!/usr/bin/env python
import sys
from os.path import dirname, abspath
from django.conf import settings
if len(sys.argv) > 1 and 'postgres' in sys.argv:
sys.argv.remove('postgres')
db_engine = 'postgresql_psycopg2'
db_name = 'test_main'
else:
db_engine = 'sqlite3'
db_name = ''
if not settings.configured:
settings.configure(
DATABASE_ENGINE = db_engine,
DATABASE_NAME = db_name,
SITE_ID = 1,
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
),
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
),
ROOT_URLCONF = 'relationships.relationships_tests.urls',
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'relationships',
'relationships.relationships_tests',
],
)
from django.test.simple import run_tests
def runtests(*test_args):
if not test_args:
test_args = ['relationships_tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
| Allow running tests with postgres | Allow running tests with postgres
| Python | mit | coleifer/django-relationships,maroux/django-relationships,coleifer/django-relationships,maroux/django-relationships | #!/usr/bin/env python
import sys
from os.path import dirname, abspath
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASE_ENGINE = 'sqlite3',
SITE_ID = 1,
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
),
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
),
ROOT_URLCONF = 'relationships.relationships_tests.urls',
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'relationships',
'relationships.relationships_tests',
],
)
from django.test.simple import run_tests
def runtests(*test_args):
if not test_args:
test_args = ['relationships_tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
Allow running tests with postgres | #!/usr/bin/env python
import sys
from os.path import dirname, abspath
from django.conf import settings
if len(sys.argv) > 1 and 'postgres' in sys.argv:
sys.argv.remove('postgres')
db_engine = 'postgresql_psycopg2'
db_name = 'test_main'
else:
db_engine = 'sqlite3'
db_name = ''
if not settings.configured:
settings.configure(
DATABASE_ENGINE = db_engine,
DATABASE_NAME = db_name,
SITE_ID = 1,
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
),
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
),
ROOT_URLCONF = 'relationships.relationships_tests.urls',
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'relationships',
'relationships.relationships_tests',
],
)
from django.test.simple import run_tests
def runtests(*test_args):
if not test_args:
test_args = ['relationships_tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
| <commit_before>#!/usr/bin/env python
import sys
from os.path import dirname, abspath
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASE_ENGINE = 'sqlite3',
SITE_ID = 1,
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
),
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
),
ROOT_URLCONF = 'relationships.relationships_tests.urls',
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'relationships',
'relationships.relationships_tests',
],
)
from django.test.simple import run_tests
def runtests(*test_args):
if not test_args:
test_args = ['relationships_tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
<commit_msg>Allow running tests with postgres<commit_after> | #!/usr/bin/env python
import sys
from os.path import dirname, abspath
from django.conf import settings
if len(sys.argv) > 1 and 'postgres' in sys.argv:
sys.argv.remove('postgres')
db_engine = 'postgresql_psycopg2'
db_name = 'test_main'
else:
db_engine = 'sqlite3'
db_name = ''
if not settings.configured:
settings.configure(
DATABASE_ENGINE = db_engine,
DATABASE_NAME = db_name,
SITE_ID = 1,
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
),
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
),
ROOT_URLCONF = 'relationships.relationships_tests.urls',
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'relationships',
'relationships.relationships_tests',
],
)
from django.test.simple import run_tests
def runtests(*test_args):
if not test_args:
test_args = ['relationships_tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
| #!/usr/bin/env python
import sys
from os.path import dirname, abspath
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASE_ENGINE = 'sqlite3',
SITE_ID = 1,
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
),
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
),
ROOT_URLCONF = 'relationships.relationships_tests.urls',
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'relationships',
'relationships.relationships_tests',
],
)
from django.test.simple import run_tests
def runtests(*test_args):
if not test_args:
test_args = ['relationships_tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
Allow running tests with postgres#!/usr/bin/env python
import sys
from os.path import dirname, abspath
from django.conf import settings
if len(sys.argv) > 1 and 'postgres' in sys.argv:
sys.argv.remove('postgres')
db_engine = 'postgresql_psycopg2'
db_name = 'test_main'
else:
db_engine = 'sqlite3'
db_name = ''
if not settings.configured:
settings.configure(
DATABASE_ENGINE = db_engine,
DATABASE_NAME = db_name,
SITE_ID = 1,
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
),
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
),
ROOT_URLCONF = 'relationships.relationships_tests.urls',
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'relationships',
'relationships.relationships_tests',
],
)
from django.test.simple import run_tests
def runtests(*test_args):
if not test_args:
test_args = ['relationships_tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
| <commit_before>#!/usr/bin/env python
import sys
from os.path import dirname, abspath
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASE_ENGINE = 'sqlite3',
SITE_ID = 1,
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
),
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
),
ROOT_URLCONF = 'relationships.relationships_tests.urls',
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'relationships',
'relationships.relationships_tests',
],
)
from django.test.simple import run_tests
def runtests(*test_args):
if not test_args:
test_args = ['relationships_tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
<commit_msg>Allow running tests with postgres<commit_after>#!/usr/bin/env python
import sys
from os.path import dirname, abspath
from django.conf import settings
if len(sys.argv) > 1 and 'postgres' in sys.argv:
sys.argv.remove('postgres')
db_engine = 'postgresql_psycopg2'
db_name = 'test_main'
else:
db_engine = 'sqlite3'
db_name = ''
if not settings.configured:
settings.configure(
DATABASE_ENGINE = db_engine,
DATABASE_NAME = db_name,
SITE_ID = 1,
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
),
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
),
ROOT_URLCONF = 'relationships.relationships_tests.urls',
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'relationships',
'relationships.relationships_tests',
],
)
from django.test.simple import run_tests
def runtests(*test_args):
if not test_args:
test_args = ['relationships_tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
039d326907d88e24a48100b7f3cb0b8e0eb843d0 | rocket_snake/__init__.py | rocket_snake/__init__.py | # -*- coding: utf-8 -*-
__author__ = 'Hugo Berg'
__email__ = 'hb11002@icloud.com'
__version__ = '0.1.0'
from rocket_snake.constants import *
| # -*- coding: utf-8 -*-
__author__ = 'Hugo Berg'
__email__ = 'hb11002@icloud.com'
__version__ = '0.1.0'
from rocket_snake.client import RLS_Client
from rocket_snake.constants import *
| Add the RLS client import to init file | Add the RLS client import to init file
Signed-off-by: drummersbrother <d12fd520b57756512907f841763cabff8eb36464@icloud.com>
| Python | apache-2.0 | Drummersbrother/rocket-snake | # -*- coding: utf-8 -*-
__author__ = 'Hugo Berg'
__email__ = 'hb11002@icloud.com'
__version__ = '0.1.0'
from rocket_snake.constants import *
Add the RLS client import to init file
Signed-off-by: drummersbrother <d12fd520b57756512907f841763cabff8eb36464@icloud.com> | # -*- coding: utf-8 -*-
__author__ = 'Hugo Berg'
__email__ = 'hb11002@icloud.com'
__version__ = '0.1.0'
from rocket_snake.client import RLS_Client
from rocket_snake.constants import *
| <commit_before># -*- coding: utf-8 -*-
__author__ = 'Hugo Berg'
__email__ = 'hb11002@icloud.com'
__version__ = '0.1.0'
from rocket_snake.constants import *
<commit_msg>Add the RLS client import to init file
Signed-off-by: drummersbrother <d12fd520b57756512907f841763cabff8eb36464@icloud.com><commit_after> | # -*- coding: utf-8 -*-
__author__ = 'Hugo Berg'
__email__ = 'hb11002@icloud.com'
__version__ = '0.1.0'
from rocket_snake.client import RLS_Client
from rocket_snake.constants import *
| # -*- coding: utf-8 -*-
__author__ = 'Hugo Berg'
__email__ = 'hb11002@icloud.com'
__version__ = '0.1.0'
from rocket_snake.constants import *
Add the RLS client import to init file
Signed-off-by: drummersbrother <d12fd520b57756512907f841763cabff8eb36464@icloud.com># -*- coding: utf-8 -*-
__author__ = 'Hugo Berg'
__email__ = 'hb11002@icloud.com'
__version__ = '0.1.0'
from rocket_snake.client import RLS_Client
from rocket_snake.constants import *
| <commit_before># -*- coding: utf-8 -*-
__author__ = 'Hugo Berg'
__email__ = 'hb11002@icloud.com'
__version__ = '0.1.0'
from rocket_snake.constants import *
<commit_msg>Add the RLS client import to init file
Signed-off-by: drummersbrother <d12fd520b57756512907f841763cabff8eb36464@icloud.com><commit_after># -*- coding: utf-8 -*-
__author__ = 'Hugo Berg'
__email__ = 'hb11002@icloud.com'
__version__ = '0.1.0'
from rocket_snake.client import RLS_Client
from rocket_snake.constants import *
|
4065f8edc61ae9078238219dad674ae114c78003 | moocng/wsgi.py | moocng/wsgi.py | """
WSGI config for moocng project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "moocng.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
| """
WSGI config for moocng project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "moocng.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
#from django.core.wsgi import get_wsgi_application
#application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
def application(environ, start_response):
virtualenv = environ.get('VIRTUALENV', '/var/www')
activate_this = os.path.join(virtualenv, 'bin', 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
from django.core.wsgi import get_wsgi_application
django_app = get_wsgi_application()
return django_app(environ, start_response)
| Allow to configure the virtualenv path from the Apache configuration | Allow to configure the virtualenv path from the Apache configuration
| Python | apache-2.0 | OpenMOOC/moocng,GeographicaGS/moocng,GeographicaGS/moocng,GeographicaGS/moocng,OpenMOOC/moocng,GeographicaGS/moocng | """
WSGI config for moocng project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "moocng.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
Allow to configure the virtualenv path from the Apache configuration | """
WSGI config for moocng project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "moocng.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
#from django.core.wsgi import get_wsgi_application
#application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
def application(environ, start_response):
virtualenv = environ.get('VIRTUALENV', '/var/www')
activate_this = os.path.join(virtualenv, 'bin', 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
from django.core.wsgi import get_wsgi_application
django_app = get_wsgi_application()
return django_app(environ, start_response)
| <commit_before>"""
WSGI config for moocng project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "moocng.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
<commit_msg>Allow to configure the virtualenv path from the Apache configuration<commit_after> | """
WSGI config for moocng project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "moocng.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
#from django.core.wsgi import get_wsgi_application
#application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
def application(environ, start_response):
virtualenv = environ.get('VIRTUALENV', '/var/www')
activate_this = os.path.join(virtualenv, 'bin', 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
from django.core.wsgi import get_wsgi_application
django_app = get_wsgi_application()
return django_app(environ, start_response)
| """
WSGI config for moocng project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "moocng.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
Allow to configure the virtualenv path from the Apache configuration"""
WSGI config for moocng project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "moocng.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
#from django.core.wsgi import get_wsgi_application
#application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
def application(environ, start_response):
virtualenv = environ.get('VIRTUALENV', '/var/www')
activate_this = os.path.join(virtualenv, 'bin', 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
from django.core.wsgi import get_wsgi_application
django_app = get_wsgi_application()
return django_app(environ, start_response)
| <commit_before>"""
WSGI config for moocng project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "moocng.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
<commit_msg>Allow to configure the virtualenv path from the Apache configuration<commit_after>"""
WSGI config for moocng project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "moocng.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
#from django.core.wsgi import get_wsgi_application
#application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
def application(environ, start_response):
virtualenv = environ.get('VIRTUALENV', '/var/www')
activate_this = os.path.join(virtualenv, 'bin', 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
from django.core.wsgi import get_wsgi_application
django_app = get_wsgi_application()
return django_app(environ, start_response)
|
bd1a244aa3d9126a12365611372e6449e47e5693 | pelicanconf.py | pelicanconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml'
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
# Social widget
#SOCIAL = (('Twitter', 'https://twitter.com/Mappy'),
# )
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images','resources']
TWITTER_URL = 'https://twitter.com/Mappy'
GITHUB_URL = 'https://github.com/Mappy'
FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
| #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml'
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Appli Android', 'https://play.google.com/store/apps/details?id=com.mappy.app'),
('Appli iOS', 'https://itunes.apple.com/fr/app/mappy-itineraire-et-recherche/id313834655?mt=8'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
# Social widget
#SOCIAL = (('Twitter', 'https://twitter.com/Mappy'),
# )
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images','resources']
TWITTER_URL = 'https://twitter.com/Mappy'
GITHUB_URL = 'https://github.com/Mappy'
FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
| Add links to Android/iOS apps | Add links to Android/iOS apps
| Python | mit | paulgreg/mappy.github.io-source,paulgreg/mappy.github.io-source,Mappy/mappy.github.io-source,Mappy/mappy.github.io-source,paulgreg/mappy.github.io-source,Mappy/mappy.github.io-source,paulgreg/mappy.github.io-source,Mappy/mappy.github.io-source | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml'
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
# Social widget
#SOCIAL = (('Twitter', 'https://twitter.com/Mappy'),
# )
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images','resources']
TWITTER_URL = 'https://twitter.com/Mappy'
GITHUB_URL = 'https://github.com/Mappy'
FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
Add links to Android/iOS apps | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml'
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Appli Android', 'https://play.google.com/store/apps/details?id=com.mappy.app'),
('Appli iOS', 'https://itunes.apple.com/fr/app/mappy-itineraire-et-recherche/id313834655?mt=8'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
# Social widget
#SOCIAL = (('Twitter', 'https://twitter.com/Mappy'),
# )
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images','resources']
TWITTER_URL = 'https://twitter.com/Mappy'
GITHUB_URL = 'https://github.com/Mappy'
FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml'
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
# Social widget
#SOCIAL = (('Twitter', 'https://twitter.com/Mappy'),
# )
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images','resources']
TWITTER_URL = 'https://twitter.com/Mappy'
GITHUB_URL = 'https://github.com/Mappy'
FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
<commit_msg>Add links to Android/iOS apps<commit_after> | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml'
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Appli Android', 'https://play.google.com/store/apps/details?id=com.mappy.app'),
('Appli iOS', 'https://itunes.apple.com/fr/app/mappy-itineraire-et-recherche/id313834655?mt=8'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
# Social widget
#SOCIAL = (('Twitter', 'https://twitter.com/Mappy'),
# )
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images','resources']
TWITTER_URL = 'https://twitter.com/Mappy'
GITHUB_URL = 'https://github.com/Mappy'
FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
| #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml'
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
# Social widget
#SOCIAL = (('Twitter', 'https://twitter.com/Mappy'),
# )
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images','resources']
TWITTER_URL = 'https://twitter.com/Mappy'
GITHUB_URL = 'https://github.com/Mappy'
FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
Add links to Android/iOS apps#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml'
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Appli Android', 'https://play.google.com/store/apps/details?id=com.mappy.app'),
('Appli iOS', 'https://itunes.apple.com/fr/app/mappy-itineraire-et-recherche/id313834655?mt=8'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
# Social widget
#SOCIAL = (('Twitter', 'https://twitter.com/Mappy'),
# )
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images','resources']
TWITTER_URL = 'https://twitter.com/Mappy'
GITHUB_URL = 'https://github.com/Mappy'
FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml'
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
# Social widget
#SOCIAL = (('Twitter', 'https://twitter.com/Mappy'),
# )
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images','resources']
TWITTER_URL = 'https://twitter.com/Mappy'
GITHUB_URL = 'https://github.com/Mappy'
FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
<commit_msg>Add links to Android/iOS apps<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Mappy'
SITENAME = u'Mappy Labs'
SITEURL = ''
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
THEME = 'theme/mappy'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = 'feeds/rss.xml'
CATEGORY_FEED_ATOM = 'feeds/%s/rss.xml'
TRANSLATION_FEED_ATOM = None
# Blogroll
LINKS = (('Mappy', 'https://www.mappy.com/'),
('Appli Android', 'https://play.google.com/store/apps/details?id=com.mappy.app'),
('Appli iOS', 'https://itunes.apple.com/fr/app/mappy-itineraire-et-recherche/id313834655?mt=8'),
('Blog Mappy', 'http://corporate.mappy.com'),
('API Mappy', 'http://corporate.mappy.com/faq/integrez-mappy/'),
)
# Social widget
#SOCIAL = (('Twitter', 'https://twitter.com/Mappy'),
# )
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images','resources']
TWITTER_URL = 'https://twitter.com/Mappy'
GITHUB_URL = 'https://github.com/Mappy'
FACEBOOK_URL = 'https://www.facebook.com/MappyOnline'
|
835cae8c7bb8a9120008657e5641d6fbbdc5782b | tba_config.py | tba_config.py | import os
DEBUG = os.environ['SERVER_SOFTWARE'].startswith('Dev')
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['kickoff'] = False
# Add your FB app info here
CONFIG['FACEBOOK_APP_ID'] = "YOUR_APP_ID"
CONFIG['FACEBOOK_APP_SECRET'] = "YOUR_SECRET"
| import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['kickoff'] = False
# Add your FB app info here
CONFIG['FACEBOOK_APP_ID'] = "YOUR_APP_ID"
CONFIG['FACEBOOK_APP_SECRET'] = "YOUR_SECRET"
| Work around for SERVER_SOFTWARE not being set | Work around for SERVER_SOFTWARE not being set
| Python | mit | phil-lopreiato/the-blue-alliance,1fish2/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,nwalters512/the-blue-alliance,jaredhasenklein/the-blue-alliance,synth3tk/the-blue-alliance,1fish2/the-blue-alliance,synth3tk/the-blue-alliance,bdaroz/the-blue-alliance,synth3tk/the-blue-alliance,josephbisch/the-blue-alliance,bvisness/the-blue-alliance,josephbisch/the-blue-alliance,jaredhasenklein/the-blue-alliance,the-blue-alliance/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,bvisness/the-blue-alliance,tsteward/the-blue-alliance,the-blue-alliance/the-blue-alliance,bvisness/the-blue-alliance,synth3tk/the-blue-alliance,phil-lopreiato/the-blue-alliance,fangeugene/the-blue-alliance,bvisness/the-blue-alliance,synth3tk/the-blue-alliance,nwalters512/the-blue-alliance,bvisness/the-blue-alliance,the-blue-alliance/the-blue-alliance,bdaroz/the-blue-alliance,tsteward/the-blue-alliance,josephbisch/the-blue-alliance,tsteward/the-blue-alliance,the-blue-alliance/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,phil-lopreiato/the-blue-alliance,1fish2/the-blue-alliance,phil-lopreiato/the-blue-alliance,josephbisch/the-blue-alliance,bvisness/the-blue-alliance,the-blue-alliance/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,phil-lopreiato/the-blue-alliance,fangeugene/the-blue-alliance,1fish2/the-blue-alliance,bdaroz/the-blue-alliance,phil-lopreiato/the-blue-alliance,josephbisch/the-blue-alliance,1fish2/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,jaredhasenklein/the-blue-alliance,nwalters512/the-blue-alliance,josephbisch/the-blue-alliance,the-blue-alliance/the-blue-alliance,bdaroz/the-blue-alliance,nwalters512/the-blue-alliance,1fish2/the-blue-alliance,bdaroz/the-blue-alliance,fangeugene/the-blue-alliance,verycumbersome/the-blue-alliance,tsteward/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance,jaredhasenklein/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,fangeugene/the-blue-alliance | import os
DEBUG = os.environ['SERVER_SOFTWARE'].startswith('Dev')
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['kickoff'] = False
# Add your FB app info here
CONFIG['FACEBOOK_APP_ID'] = "YOUR_APP_ID"
CONFIG['FACEBOOK_APP_SECRET'] = "YOUR_SECRET"
Work around for SERVER_SOFTWARE not being set | import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['kickoff'] = False
# Add your FB app info here
CONFIG['FACEBOOK_APP_ID'] = "YOUR_APP_ID"
CONFIG['FACEBOOK_APP_SECRET'] = "YOUR_SECRET"
| <commit_before>import os
DEBUG = os.environ['SERVER_SOFTWARE'].startswith('Dev')
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['kickoff'] = False
# Add your FB app info here
CONFIG['FACEBOOK_APP_ID'] = "YOUR_APP_ID"
CONFIG['FACEBOOK_APP_SECRET'] = "YOUR_SECRET"
<commit_msg>Work around for SERVER_SOFTWARE not being set<commit_after> | import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['kickoff'] = False
# Add your FB app info here
CONFIG['FACEBOOK_APP_ID'] = "YOUR_APP_ID"
CONFIG['FACEBOOK_APP_SECRET'] = "YOUR_SECRET"
| import os
DEBUG = os.environ['SERVER_SOFTWARE'].startswith('Dev')
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['kickoff'] = False
# Add your FB app info here
CONFIG['FACEBOOK_APP_ID'] = "YOUR_APP_ID"
CONFIG['FACEBOOK_APP_SECRET'] = "YOUR_SECRET"
Work around for SERVER_SOFTWARE not being setimport os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['kickoff'] = False
# Add your FB app info here
CONFIG['FACEBOOK_APP_ID'] = "YOUR_APP_ID"
CONFIG['FACEBOOK_APP_SECRET'] = "YOUR_SECRET"
| <commit_before>import os
DEBUG = os.environ['SERVER_SOFTWARE'].startswith('Dev')
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['kickoff'] = False
# Add your FB app info here
CONFIG['FACEBOOK_APP_ID'] = "YOUR_APP_ID"
CONFIG['FACEBOOK_APP_SECRET'] = "YOUR_SECRET"
<commit_msg>Work around for SERVER_SOFTWARE not being set<commit_after>import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['kickoff'] = False
# Add your FB app info here
CONFIG['FACEBOOK_APP_ID'] = "YOUR_APP_ID"
CONFIG['FACEBOOK_APP_SECRET'] = "YOUR_SECRET"
|
321b627c3c7d241d6e6cc4e319911cfbcd1533fb | src/temp_functions.py | src/temp_functions.py | def k_to_c(temp):
return temp - 273.15
| def k_to_c(temp):
return temp - 273.15
def f_to_k(temp):
return ((temp - 32) * (5 / 9)) + 273.15
| Write a function to covert far to kelvin | Write a function to covert far to kelvin
| Python | mit | xykang/2015-05-12-BUSM-git,xykang/2015-05-12-BUSM-git | def k_to_c(temp):
return temp - 273.15
Write a function to covert far to kelvin | def k_to_c(temp):
return temp - 273.15
def f_to_k(temp):
return ((temp - 32) * (5 / 9)) + 273.15
| <commit_before>def k_to_c(temp):
return temp - 273.15
<commit_msg>Write a function to covert far to kelvin<commit_after> | def k_to_c(temp):
return temp - 273.15
def f_to_k(temp):
return ((temp - 32) * (5 / 9)) + 273.15
| def k_to_c(temp):
return temp - 273.15
Write a function to covert far to kelvindef k_to_c(temp):
return temp - 273.15
def f_to_k(temp):
return ((temp - 32) * (5 / 9)) + 273.15
| <commit_before>def k_to_c(temp):
return temp - 273.15
<commit_msg>Write a function to covert far to kelvin<commit_after>def k_to_c(temp):
return temp - 273.15
def f_to_k(temp):
return ((temp - 32) * (5 / 9)) + 273.15
|
d676a1b1e7e3efbbfc72f1d7e522865b623783df | utils/etc.py | utils/etc.py | def reverse_insort(seq, val):
lo = 0
hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]:
hi = mid
else:
lo = mid + 1
seq.insert(lo, val)
| def reverse_insort(seq, val, lo=0, hi=None):
if hi is None:
hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]:
hi = mid
else:
lo = mid + 1
seq.insert(lo, val)
| Add optional hi and lo params to reverse_insort | Add optional hi and lo params to reverse_insort
| Python | mit | BeatButton/beattie,BeatButton/beattie-bot | def reverse_insort(seq, val):
lo = 0
hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]:
hi = mid
else:
lo = mid + 1
seq.insert(lo, val)
Add optional hi and lo params to reverse_insort | def reverse_insort(seq, val, lo=0, hi=None):
if hi is None:
hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]:
hi = mid
else:
lo = mid + 1
seq.insert(lo, val)
| <commit_before>def reverse_insort(seq, val):
lo = 0
hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]:
hi = mid
else:
lo = mid + 1
seq.insert(lo, val)
<commit_msg>Add optional hi and lo params to reverse_insort<commit_after> | def reverse_insort(seq, val, lo=0, hi=None):
if hi is None:
hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]:
hi = mid
else:
lo = mid + 1
seq.insert(lo, val)
| def reverse_insort(seq, val):
lo = 0
hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]:
hi = mid
else:
lo = mid + 1
seq.insert(lo, val)
Add optional hi and lo params to reverse_insortdef reverse_insort(seq, val, lo=0, hi=None):
if hi is None:
hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]:
hi = mid
else:
lo = mid + 1
seq.insert(lo, val)
| <commit_before>def reverse_insort(seq, val):
lo = 0
hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]:
hi = mid
else:
lo = mid + 1
seq.insert(lo, val)
<commit_msg>Add optional hi and lo params to reverse_insort<commit_after>def reverse_insort(seq, val, lo=0, hi=None):
if hi is None:
hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]:
hi = mid
else:
lo = mid + 1
seq.insert(lo, val)
|
b13efa6234c2748515a9c3f5a8fbb3ad43093083 | test/test_device.py | test/test_device.py | from pml.exceptions import PvException
import pml.device
import pytest
import mock
@pytest.fixture
def create_device(readback, setpoint):
_rb = readback
_sp = setpoint
device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock())
return device
def test_set_device_value():
rb_pv = 'SR01A-PC-SQUAD-01:I'
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device1 = create_device(rb_pv, sp_pv)
device1.put_value(40)
device1._cs.put.assert_called_with(sp_pv, 40)
device2 = create_device(rb_pv, None)
with pytest.raises(PvException):
device2.put_value(40)
def test_get_device_value():
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device = create_device(None, sp_pv)
with pytest.raises(PvException):
device.get_value('non_existent')
with pytest.raises(PvException):
create_device(None, None)
| from pml.exceptions import PvException
import pml.device
import pytest
import mock
@pytest.fixture
def create_device(readback, setpoint):
_rb = readback
_sp = setpoint
device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock())
return device
def test_set_device_value():
rb_pv = 'SR01A-PC-SQUAD-01:I'
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device1 = create_device(rb_pv, sp_pv)
device1.put_value(40)
device1._cs.put.assert_called_with(sp_pv, 40)
device2 = create_device(rb_pv, None)
with pytest.raises(PvException):
device2.put_value(40)
def test_get_device_value():
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device = create_device(None, sp_pv)
with pytest.raises(PvException):
device.get_value('non_existent')
with pytest.raises(AssertionError):
create_device(None, None)
| Raise assertion error when creating a device with no pv | Raise assertion error when creating a device with no pv
| Python | apache-2.0 | willrogers/pml,willrogers/pml | from pml.exceptions import PvException
import pml.device
import pytest
import mock
@pytest.fixture
def create_device(readback, setpoint):
_rb = readback
_sp = setpoint
device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock())
return device
def test_set_device_value():
rb_pv = 'SR01A-PC-SQUAD-01:I'
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device1 = create_device(rb_pv, sp_pv)
device1.put_value(40)
device1._cs.put.assert_called_with(sp_pv, 40)
device2 = create_device(rb_pv, None)
with pytest.raises(PvException):
device2.put_value(40)
def test_get_device_value():
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device = create_device(None, sp_pv)
with pytest.raises(PvException):
device.get_value('non_existent')
with pytest.raises(PvException):
create_device(None, None)
Raise assertion error when creating a device with no pv | from pml.exceptions import PvException
import pml.device
import pytest
import mock
@pytest.fixture
def create_device(readback, setpoint):
_rb = readback
_sp = setpoint
device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock())
return device
def test_set_device_value():
rb_pv = 'SR01A-PC-SQUAD-01:I'
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device1 = create_device(rb_pv, sp_pv)
device1.put_value(40)
device1._cs.put.assert_called_with(sp_pv, 40)
device2 = create_device(rb_pv, None)
with pytest.raises(PvException):
device2.put_value(40)
def test_get_device_value():
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device = create_device(None, sp_pv)
with pytest.raises(PvException):
device.get_value('non_existent')
with pytest.raises(AssertionError):
create_device(None, None)
| <commit_before>from pml.exceptions import PvException
import pml.device
import pytest
import mock
@pytest.fixture
def create_device(readback, setpoint):
_rb = readback
_sp = setpoint
device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock())
return device
def test_set_device_value():
rb_pv = 'SR01A-PC-SQUAD-01:I'
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device1 = create_device(rb_pv, sp_pv)
device1.put_value(40)
device1._cs.put.assert_called_with(sp_pv, 40)
device2 = create_device(rb_pv, None)
with pytest.raises(PvException):
device2.put_value(40)
def test_get_device_value():
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device = create_device(None, sp_pv)
with pytest.raises(PvException):
device.get_value('non_existent')
with pytest.raises(PvException):
create_device(None, None)
<commit_msg>Raise assertion error when creating a device with no pv<commit_after> | from pml.exceptions import PvException
import pml.device
import pytest
import mock
@pytest.fixture
def create_device(readback, setpoint):
_rb = readback
_sp = setpoint
device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock())
return device
def test_set_device_value():
rb_pv = 'SR01A-PC-SQUAD-01:I'
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device1 = create_device(rb_pv, sp_pv)
device1.put_value(40)
device1._cs.put.assert_called_with(sp_pv, 40)
device2 = create_device(rb_pv, None)
with pytest.raises(PvException):
device2.put_value(40)
def test_get_device_value():
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device = create_device(None, sp_pv)
with pytest.raises(PvException):
device.get_value('non_existent')
with pytest.raises(AssertionError):
create_device(None, None)
| from pml.exceptions import PvException
import pml.device
import pytest
import mock
@pytest.fixture
def create_device(readback, setpoint):
_rb = readback
_sp = setpoint
device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock())
return device
def test_set_device_value():
rb_pv = 'SR01A-PC-SQUAD-01:I'
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device1 = create_device(rb_pv, sp_pv)
device1.put_value(40)
device1._cs.put.assert_called_with(sp_pv, 40)
device2 = create_device(rb_pv, None)
with pytest.raises(PvException):
device2.put_value(40)
def test_get_device_value():
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device = create_device(None, sp_pv)
with pytest.raises(PvException):
device.get_value('non_existent')
with pytest.raises(PvException):
create_device(None, None)
Raise assertion error when creating a device with no pvfrom pml.exceptions import PvException
import pml.device
import pytest
import mock
@pytest.fixture
def create_device(readback, setpoint):
_rb = readback
_sp = setpoint
device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock())
return device
def test_set_device_value():
rb_pv = 'SR01A-PC-SQUAD-01:I'
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device1 = create_device(rb_pv, sp_pv)
device1.put_value(40)
device1._cs.put.assert_called_with(sp_pv, 40)
device2 = create_device(rb_pv, None)
with pytest.raises(PvException):
device2.put_value(40)
def test_get_device_value():
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device = create_device(None, sp_pv)
with pytest.raises(PvException):
device.get_value('non_existent')
with pytest.raises(AssertionError):
create_device(None, None)
| <commit_before>from pml.exceptions import PvException
import pml.device
import pytest
import mock
@pytest.fixture
def create_device(readback, setpoint):
_rb = readback
_sp = setpoint
device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock())
return device
def test_set_device_value():
rb_pv = 'SR01A-PC-SQUAD-01:I'
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device1 = create_device(rb_pv, sp_pv)
device1.put_value(40)
device1._cs.put.assert_called_with(sp_pv, 40)
device2 = create_device(rb_pv, None)
with pytest.raises(PvException):
device2.put_value(40)
def test_get_device_value():
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device = create_device(None, sp_pv)
with pytest.raises(PvException):
device.get_value('non_existent')
with pytest.raises(PvException):
create_device(None, None)
<commit_msg>Raise assertion error when creating a device with no pv<commit_after>from pml.exceptions import PvException
import pml.device
import pytest
import mock
@pytest.fixture
def create_device(readback, setpoint):
_rb = readback
_sp = setpoint
device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock())
return device
def test_set_device_value():
rb_pv = 'SR01A-PC-SQUAD-01:I'
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device1 = create_device(rb_pv, sp_pv)
device1.put_value(40)
device1._cs.put.assert_called_with(sp_pv, 40)
device2 = create_device(rb_pv, None)
with pytest.raises(PvException):
device2.put_value(40)
def test_get_device_value():
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
device = create_device(None, sp_pv)
with pytest.raises(PvException):
device.get_value('non_existent')
with pytest.raises(AssertionError):
create_device(None, None)
|
4607c2fdb39301cc60d49280dd1253e3d62845be | st2api/setup.py | st2api/setup.py | # -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') 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.
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='st2api',
version='0.4.0',
description='',
author='StackStorm',
author_email='info@stackstorm.com',
install_requires=[
"pecan",
],
test_suite='st2api',
zip_safe=False,
include_package_data=True,
packages=find_packages(exclude=['ez_setup'])
)
| # -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') 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.
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='st2api',
version='0.4.0',
description='',
author='StackStorm',
author_email='info@stackstorm.com',
install_requires=[
"pecan",
],
package_data={
'st2api': ['templates/*.html']
},
test_suite='st2api',
zip_safe=False,
include_package_data=True,
packages=find_packages(exclude=['ez_setup'])
)
| Fix a packaging bug and make sure we also include templates directory. | Fix a packaging bug and make sure we also include templates directory.
| Python | apache-2.0 | pixelrebel/st2,jtopjian/st2,nzlosh/st2,Itxaka/st2,Plexxi/st2,grengojbo/st2,lakshmi-kannan/st2,armab/st2,Plexxi/st2,peak6/st2,pixelrebel/st2,emedvedev/st2,emedvedev/st2,Plexxi/st2,Itxaka/st2,tonybaloney/st2,lakshmi-kannan/st2,pixelrebel/st2,jtopjian/st2,jtopjian/st2,dennybaa/st2,punalpatel/st2,dennybaa/st2,alfasin/st2,alfasin/st2,StackStorm/st2,Itxaka/st2,peak6/st2,grengojbo/st2,nzlosh/st2,emedvedev/st2,nzlosh/st2,alfasin/st2,StackStorm/st2,lakshmi-kannan/st2,pinterb/st2,Plexxi/st2,punalpatel/st2,dennybaa/st2,armab/st2,nzlosh/st2,StackStorm/st2,grengojbo/st2,armab/st2,StackStorm/st2,tonybaloney/st2,tonybaloney/st2,pinterb/st2,peak6/st2,punalpatel/st2,pinterb/st2 | # -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') 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.
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='st2api',
version='0.4.0',
description='',
author='StackStorm',
author_email='info@stackstorm.com',
install_requires=[
"pecan",
],
test_suite='st2api',
zip_safe=False,
include_package_data=True,
packages=find_packages(exclude=['ez_setup'])
)
Fix a packaging bug and make sure we also include templates directory. | # -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') 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.
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='st2api',
version='0.4.0',
description='',
author='StackStorm',
author_email='info@stackstorm.com',
install_requires=[
"pecan",
],
package_data={
'st2api': ['templates/*.html']
},
test_suite='st2api',
zip_safe=False,
include_package_data=True,
packages=find_packages(exclude=['ez_setup'])
)
| <commit_before># -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') 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.
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='st2api',
version='0.4.0',
description='',
author='StackStorm',
author_email='info@stackstorm.com',
install_requires=[
"pecan",
],
test_suite='st2api',
zip_safe=False,
include_package_data=True,
packages=find_packages(exclude=['ez_setup'])
)
<commit_msg>Fix a packaging bug and make sure we also include templates directory.<commit_after> | # -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') 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.
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='st2api',
version='0.4.0',
description='',
author='StackStorm',
author_email='info@stackstorm.com',
install_requires=[
"pecan",
],
package_data={
'st2api': ['templates/*.html']
},
test_suite='st2api',
zip_safe=False,
include_package_data=True,
packages=find_packages(exclude=['ez_setup'])
)
| # -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') 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.
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='st2api',
version='0.4.0',
description='',
author='StackStorm',
author_email='info@stackstorm.com',
install_requires=[
"pecan",
],
test_suite='st2api',
zip_safe=False,
include_package_data=True,
packages=find_packages(exclude=['ez_setup'])
)
Fix a packaging bug and make sure we also include templates directory.# -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') 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.
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='st2api',
version='0.4.0',
description='',
author='StackStorm',
author_email='info@stackstorm.com',
install_requires=[
"pecan",
],
package_data={
'st2api': ['templates/*.html']
},
test_suite='st2api',
zip_safe=False,
include_package_data=True,
packages=find_packages(exclude=['ez_setup'])
)
| <commit_before># -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') 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.
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='st2api',
version='0.4.0',
description='',
author='StackStorm',
author_email='info@stackstorm.com',
install_requires=[
"pecan",
],
test_suite='st2api',
zip_safe=False,
include_package_data=True,
packages=find_packages(exclude=['ez_setup'])
)
<commit_msg>Fix a packaging bug and make sure we also include templates directory.<commit_after># -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') 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.
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='st2api',
version='0.4.0',
description='',
author='StackStorm',
author_email='info@stackstorm.com',
install_requires=[
"pecan",
],
package_data={
'st2api': ['templates/*.html']
},
test_suite='st2api',
zip_safe=False,
include_package_data=True,
packages=find_packages(exclude=['ez_setup'])
)
|
b77622311c69cd74c9c3c3b7c66747c79ea41bec | troposphere/qldb.py | troposphere/qldb.py | # Copyright (c) 2012-2019, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 16.1.0
from troposphere import Tags
from . import AWSObject, AWSProperty
from .validators import boolean
class Ledger(AWSObject):
resource_type = "AWS::QLDB::Ledger"
props = {
"DeletionProtection": (boolean, False),
"Name": (str, False),
"PermissionsMode": (str, True),
"Tags": (Tags, False),
}
class KinesisConfiguration(AWSProperty):
props = {
"AggregationEnabled": (boolean, False),
"StreamArn": (str, False),
}
class Stream(AWSObject):
resource_type = "AWS::QLDB::Stream"
props = {
"ExclusiveEndTime": (str, False),
"InclusiveStartTime": (str, True),
"KinesisConfiguration": (KinesisConfiguration, True),
"LedgerName": (str, True),
"RoleArn": (str, True),
"StreamName": (str, True),
"Tags": (Tags, False),
}
| # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 39.7.0
from troposphere import Tags
from . import AWSObject, AWSProperty
from .validators import boolean
class Ledger(AWSObject):
resource_type = "AWS::QLDB::Ledger"
props = {
"DeletionProtection": (boolean, False),
"KmsKey": (str, False),
"Name": (str, False),
"PermissionsMode": (str, True),
"Tags": (Tags, False),
}
class KinesisConfiguration(AWSProperty):
props = {
"AggregationEnabled": (boolean, False),
"StreamArn": (str, False),
}
class Stream(AWSObject):
resource_type = "AWS::QLDB::Stream"
props = {
"ExclusiveEndTime": (str, False),
"InclusiveStartTime": (str, True),
"KinesisConfiguration": (KinesisConfiguration, True),
"LedgerName": (str, True),
"RoleArn": (str, True),
"StreamName": (str, True),
"Tags": (Tags, False),
}
| Update QLDB per 2021-07-22 changes | Update QLDB per 2021-07-22 changes
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere | # Copyright (c) 2012-2019, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 16.1.0
from troposphere import Tags
from . import AWSObject, AWSProperty
from .validators import boolean
class Ledger(AWSObject):
resource_type = "AWS::QLDB::Ledger"
props = {
"DeletionProtection": (boolean, False),
"Name": (str, False),
"PermissionsMode": (str, True),
"Tags": (Tags, False),
}
class KinesisConfiguration(AWSProperty):
props = {
"AggregationEnabled": (boolean, False),
"StreamArn": (str, False),
}
class Stream(AWSObject):
resource_type = "AWS::QLDB::Stream"
props = {
"ExclusiveEndTime": (str, False),
"InclusiveStartTime": (str, True),
"KinesisConfiguration": (KinesisConfiguration, True),
"LedgerName": (str, True),
"RoleArn": (str, True),
"StreamName": (str, True),
"Tags": (Tags, False),
}
Update QLDB per 2021-07-22 changes | # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 39.7.0
from troposphere import Tags
from . import AWSObject, AWSProperty
from .validators import boolean
class Ledger(AWSObject):
resource_type = "AWS::QLDB::Ledger"
props = {
"DeletionProtection": (boolean, False),
"KmsKey": (str, False),
"Name": (str, False),
"PermissionsMode": (str, True),
"Tags": (Tags, False),
}
class KinesisConfiguration(AWSProperty):
props = {
"AggregationEnabled": (boolean, False),
"StreamArn": (str, False),
}
class Stream(AWSObject):
resource_type = "AWS::QLDB::Stream"
props = {
"ExclusiveEndTime": (str, False),
"InclusiveStartTime": (str, True),
"KinesisConfiguration": (KinesisConfiguration, True),
"LedgerName": (str, True),
"RoleArn": (str, True),
"StreamName": (str, True),
"Tags": (Tags, False),
}
| <commit_before># Copyright (c) 2012-2019, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 16.1.0
from troposphere import Tags
from . import AWSObject, AWSProperty
from .validators import boolean
class Ledger(AWSObject):
resource_type = "AWS::QLDB::Ledger"
props = {
"DeletionProtection": (boolean, False),
"Name": (str, False),
"PermissionsMode": (str, True),
"Tags": (Tags, False),
}
class KinesisConfiguration(AWSProperty):
props = {
"AggregationEnabled": (boolean, False),
"StreamArn": (str, False),
}
class Stream(AWSObject):
resource_type = "AWS::QLDB::Stream"
props = {
"ExclusiveEndTime": (str, False),
"InclusiveStartTime": (str, True),
"KinesisConfiguration": (KinesisConfiguration, True),
"LedgerName": (str, True),
"RoleArn": (str, True),
"StreamName": (str, True),
"Tags": (Tags, False),
}
<commit_msg>Update QLDB per 2021-07-22 changes<commit_after> | # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 39.7.0
from troposphere import Tags
from . import AWSObject, AWSProperty
from .validators import boolean
class Ledger(AWSObject):
resource_type = "AWS::QLDB::Ledger"
props = {
"DeletionProtection": (boolean, False),
"KmsKey": (str, False),
"Name": (str, False),
"PermissionsMode": (str, True),
"Tags": (Tags, False),
}
class KinesisConfiguration(AWSProperty):
props = {
"AggregationEnabled": (boolean, False),
"StreamArn": (str, False),
}
class Stream(AWSObject):
resource_type = "AWS::QLDB::Stream"
props = {
"ExclusiveEndTime": (str, False),
"InclusiveStartTime": (str, True),
"KinesisConfiguration": (KinesisConfiguration, True),
"LedgerName": (str, True),
"RoleArn": (str, True),
"StreamName": (str, True),
"Tags": (Tags, False),
}
| # Copyright (c) 2012-2019, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 16.1.0
from troposphere import Tags
from . import AWSObject, AWSProperty
from .validators import boolean
class Ledger(AWSObject):
resource_type = "AWS::QLDB::Ledger"
props = {
"DeletionProtection": (boolean, False),
"Name": (str, False),
"PermissionsMode": (str, True),
"Tags": (Tags, False),
}
class KinesisConfiguration(AWSProperty):
props = {
"AggregationEnabled": (boolean, False),
"StreamArn": (str, False),
}
class Stream(AWSObject):
resource_type = "AWS::QLDB::Stream"
props = {
"ExclusiveEndTime": (str, False),
"InclusiveStartTime": (str, True),
"KinesisConfiguration": (KinesisConfiguration, True),
"LedgerName": (str, True),
"RoleArn": (str, True),
"StreamName": (str, True),
"Tags": (Tags, False),
}
Update QLDB per 2021-07-22 changes# Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 39.7.0
from troposphere import Tags
from . import AWSObject, AWSProperty
from .validators import boolean
class Ledger(AWSObject):
resource_type = "AWS::QLDB::Ledger"
props = {
"DeletionProtection": (boolean, False),
"KmsKey": (str, False),
"Name": (str, False),
"PermissionsMode": (str, True),
"Tags": (Tags, False),
}
class KinesisConfiguration(AWSProperty):
props = {
"AggregationEnabled": (boolean, False),
"StreamArn": (str, False),
}
class Stream(AWSObject):
resource_type = "AWS::QLDB::Stream"
props = {
"ExclusiveEndTime": (str, False),
"InclusiveStartTime": (str, True),
"KinesisConfiguration": (KinesisConfiguration, True),
"LedgerName": (str, True),
"RoleArn": (str, True),
"StreamName": (str, True),
"Tags": (Tags, False),
}
| <commit_before># Copyright (c) 2012-2019, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 16.1.0
from troposphere import Tags
from . import AWSObject, AWSProperty
from .validators import boolean
class Ledger(AWSObject):
resource_type = "AWS::QLDB::Ledger"
props = {
"DeletionProtection": (boolean, False),
"Name": (str, False),
"PermissionsMode": (str, True),
"Tags": (Tags, False),
}
class KinesisConfiguration(AWSProperty):
props = {
"AggregationEnabled": (boolean, False),
"StreamArn": (str, False),
}
class Stream(AWSObject):
resource_type = "AWS::QLDB::Stream"
props = {
"ExclusiveEndTime": (str, False),
"InclusiveStartTime": (str, True),
"KinesisConfiguration": (KinesisConfiguration, True),
"LedgerName": (str, True),
"RoleArn": (str, True),
"StreamName": (str, True),
"Tags": (Tags, False),
}
<commit_msg>Update QLDB per 2021-07-22 changes<commit_after># Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 39.7.0
from troposphere import Tags
from . import AWSObject, AWSProperty
from .validators import boolean
class Ledger(AWSObject):
resource_type = "AWS::QLDB::Ledger"
props = {
"DeletionProtection": (boolean, False),
"KmsKey": (str, False),
"Name": (str, False),
"PermissionsMode": (str, True),
"Tags": (Tags, False),
}
class KinesisConfiguration(AWSProperty):
props = {
"AggregationEnabled": (boolean, False),
"StreamArn": (str, False),
}
class Stream(AWSObject):
resource_type = "AWS::QLDB::Stream"
props = {
"ExclusiveEndTime": (str, False),
"InclusiveStartTime": (str, True),
"KinesisConfiguration": (KinesisConfiguration, True),
"LedgerName": (str, True),
"RoleArn": (str, True),
"StreamName": (str, True),
"Tags": (Tags, False),
}
|
315e6da0dc3d7424a14c65ac243af1faef36b710 | test/parse_dive.py | test/parse_dive.py | #! /bin/python
import argparse
from xml.dom import minidom
parser = argparse.ArgumentParser(description='Parse a dive in xml formt.')
parser.add_argument('-f', '--file', required=True,
dest='path', help='path to xml file')
args = parser.parse_args()
path = args.path
doc = minidom.parse(path)
nodes = doc.getElementsByTagName('Dive.Sample')
for node in nodes:
depth = (float(node.childNodes[2].childNodes[0].nodeValue) / 10 )+ 1
time = float(node.childNodes[8].childNodes[0].nodeValue) / 60
print ("%.2f %.2f" % (time , depth)) | #! /bin/python
import argparse
from xml.dom import minidom
parser = argparse.ArgumentParser(description='Parse a dive in xml formt.')
parser.add_argument('-f', '--file', required=True,
dest='path', help='path to xml file')
args = parser.parse_args()
path = args.path
doc = minidom.parse(path)
nodes = doc.getElementsByTagName('Dive.Sample')
for node in nodes:
if node.hasChildNodes() and len(node.childNodes) > 8:
for subNode in node.childNodes:
if (subNode.nodeName == "Depth" and subNode.hasChildNodes()):
depth = (float(subNode.childNodes[0].nodeValue) / 10) + 1
if (subNode.nodeName == "Time" and subNode.hasChildNodes()):
time = float(subNode.childNodes[0].nodeValue) / 60
print ("%.2f %.2f" % (time , depth))
| Add a correct parsing of the file | Add a correct parsing of the file
| Python | isc | AquaBSD/libbuhlmann,AquaBSD/libbuhlmann,AquaBSD/libbuhlmann | #! /bin/python
import argparse
from xml.dom import minidom
parser = argparse.ArgumentParser(description='Parse a dive in xml formt.')
parser.add_argument('-f', '--file', required=True,
dest='path', help='path to xml file')
args = parser.parse_args()
path = args.path
doc = minidom.parse(path)
nodes = doc.getElementsByTagName('Dive.Sample')
for node in nodes:
depth = (float(node.childNodes[2].childNodes[0].nodeValue) / 10 )+ 1
time = float(node.childNodes[8].childNodes[0].nodeValue) / 60
print ("%.2f %.2f" % (time , depth))Add a correct parsing of the file | #! /bin/python
import argparse
from xml.dom import minidom
parser = argparse.ArgumentParser(description='Parse a dive in xml formt.')
parser.add_argument('-f', '--file', required=True,
dest='path', help='path to xml file')
args = parser.parse_args()
path = args.path
doc = minidom.parse(path)
nodes = doc.getElementsByTagName('Dive.Sample')
for node in nodes:
if node.hasChildNodes() and len(node.childNodes) > 8:
for subNode in node.childNodes:
if (subNode.nodeName == "Depth" and subNode.hasChildNodes()):
depth = (float(subNode.childNodes[0].nodeValue) / 10) + 1
if (subNode.nodeName == "Time" and subNode.hasChildNodes()):
time = float(subNode.childNodes[0].nodeValue) / 60
print ("%.2f %.2f" % (time , depth))
| <commit_before>#! /bin/python
import argparse
from xml.dom import minidom
parser = argparse.ArgumentParser(description='Parse a dive in xml formt.')
parser.add_argument('-f', '--file', required=True,
dest='path', help='path to xml file')
args = parser.parse_args()
path = args.path
doc = minidom.parse(path)
nodes = doc.getElementsByTagName('Dive.Sample')
for node in nodes:
depth = (float(node.childNodes[2].childNodes[0].nodeValue) / 10 )+ 1
time = float(node.childNodes[8].childNodes[0].nodeValue) / 60
print ("%.2f %.2f" % (time , depth))<commit_msg>Add a correct parsing of the file<commit_after> | #! /bin/python
import argparse
from xml.dom import minidom
parser = argparse.ArgumentParser(description='Parse a dive in xml formt.')
parser.add_argument('-f', '--file', required=True,
dest='path', help='path to xml file')
args = parser.parse_args()
path = args.path
doc = minidom.parse(path)
nodes = doc.getElementsByTagName('Dive.Sample')
for node in nodes:
if node.hasChildNodes() and len(node.childNodes) > 8:
for subNode in node.childNodes:
if (subNode.nodeName == "Depth" and subNode.hasChildNodes()):
depth = (float(subNode.childNodes[0].nodeValue) / 10) + 1
if (subNode.nodeName == "Time" and subNode.hasChildNodes()):
time = float(subNode.childNodes[0].nodeValue) / 60
print ("%.2f %.2f" % (time , depth))
| #! /bin/python
import argparse
from xml.dom import minidom
parser = argparse.ArgumentParser(description='Parse a dive in xml formt.')
parser.add_argument('-f', '--file', required=True,
dest='path', help='path to xml file')
args = parser.parse_args()
path = args.path
doc = minidom.parse(path)
nodes = doc.getElementsByTagName('Dive.Sample')
for node in nodes:
depth = (float(node.childNodes[2].childNodes[0].nodeValue) / 10 )+ 1
time = float(node.childNodes[8].childNodes[0].nodeValue) / 60
print ("%.2f %.2f" % (time , depth))Add a correct parsing of the file#! /bin/python
import argparse
from xml.dom import minidom
parser = argparse.ArgumentParser(description='Parse a dive in xml formt.')
parser.add_argument('-f', '--file', required=True,
dest='path', help='path to xml file')
args = parser.parse_args()
path = args.path
doc = minidom.parse(path)
nodes = doc.getElementsByTagName('Dive.Sample')
for node in nodes:
if node.hasChildNodes() and len(node.childNodes) > 8:
for subNode in node.childNodes:
if (subNode.nodeName == "Depth" and subNode.hasChildNodes()):
depth = (float(subNode.childNodes[0].nodeValue) / 10) + 1
if (subNode.nodeName == "Time" and subNode.hasChildNodes()):
time = float(subNode.childNodes[0].nodeValue) / 60
print ("%.2f %.2f" % (time , depth))
| <commit_before>#! /bin/python
import argparse
from xml.dom import minidom
parser = argparse.ArgumentParser(description='Parse a dive in xml formt.')
parser.add_argument('-f', '--file', required=True,
dest='path', help='path to xml file')
args = parser.parse_args()
path = args.path
doc = minidom.parse(path)
nodes = doc.getElementsByTagName('Dive.Sample')
for node in nodes:
depth = (float(node.childNodes[2].childNodes[0].nodeValue) / 10 )+ 1
time = float(node.childNodes[8].childNodes[0].nodeValue) / 60
print ("%.2f %.2f" % (time , depth))<commit_msg>Add a correct parsing of the file<commit_after>#! /bin/python
import argparse
from xml.dom import minidom
parser = argparse.ArgumentParser(description='Parse a dive in xml formt.')
parser.add_argument('-f', '--file', required=True,
dest='path', help='path to xml file')
args = parser.parse_args()
path = args.path
doc = minidom.parse(path)
nodes = doc.getElementsByTagName('Dive.Sample')
for node in nodes:
if node.hasChildNodes() and len(node.childNodes) > 8:
for subNode in node.childNodes:
if (subNode.nodeName == "Depth" and subNode.hasChildNodes()):
depth = (float(subNode.childNodes[0].nodeValue) / 10) + 1
if (subNode.nodeName == "Time" and subNode.hasChildNodes()):
time = float(subNode.childNodes[0].nodeValue) / 60
print ("%.2f %.2f" % (time , depth))
|
1b085180ff6d9cb4e395551682c5a628545cb70c | twython/advisory.py | twython/advisory.py | # -*- coding: utf-8 -*-
"""
twython.advisory
~~~~~~~~~~~~~~~~
This module contains Warning classes for Twython to specifically
alert the user about.
This mainly is because Python 2.7 > mutes DeprecationWarning and when
we deprecate a method or variable in Twython, we want to use to see
the Warning but don't want ALL DeprecationWarnings to appear,
only TwythonDeprecationWarnings.
"""
class TwythonDeprecationWarning(DeprecationWarning):
"""Custom DeprecationWarning to be raised when methods/variables
are being deprecated in Twython. Python 2.7 > ignores DeprecationWarning
so we want to specifcally bubble up ONLY Twython Deprecation Warnings
"""
pass
| # -*- coding: utf-8 -*-
"""
twython.advisory
~~~~~~~~~~~~~~~~
This module contains Warning classes for Twython to specifically
alert the user about.
This mainly is because Python 2.7 > mutes DeprecationWarning and when
we deprecate a method or variable in Twython, we want to use to see
the Warning but don't want ALL DeprecationWarnings to appear,
only TwythonDeprecationWarnings.
"""
class TwythonDeprecationWarning(DeprecationWarning):
"""Custom DeprecationWarning to be raised when methods/variables
are being deprecated in Twython. Python 2.7 > ignores DeprecationWarning
so we want to specifically bubble up ONLY Twython Deprecation Warnings
"""
pass
| Fix simple typo: specifcally -> specifically | Fix simple typo: specifcally -> specifically
Closes #526
| Python | mit | ryanmcgrath/twython | # -*- coding: utf-8 -*-
"""
twython.advisory
~~~~~~~~~~~~~~~~
This module contains Warning classes for Twython to specifically
alert the user about.
This mainly is because Python 2.7 > mutes DeprecationWarning and when
we deprecate a method or variable in Twython, we want to use to see
the Warning but don't want ALL DeprecationWarnings to appear,
only TwythonDeprecationWarnings.
"""
class TwythonDeprecationWarning(DeprecationWarning):
"""Custom DeprecationWarning to be raised when methods/variables
are being deprecated in Twython. Python 2.7 > ignores DeprecationWarning
so we want to specifcally bubble up ONLY Twython Deprecation Warnings
"""
pass
Fix simple typo: specifcally -> specifically
Closes #526 | # -*- coding: utf-8 -*-
"""
twython.advisory
~~~~~~~~~~~~~~~~
This module contains Warning classes for Twython to specifically
alert the user about.
This mainly is because Python 2.7 > mutes DeprecationWarning and when
we deprecate a method or variable in Twython, we want to use to see
the Warning but don't want ALL DeprecationWarnings to appear,
only TwythonDeprecationWarnings.
"""
class TwythonDeprecationWarning(DeprecationWarning):
"""Custom DeprecationWarning to be raised when methods/variables
are being deprecated in Twython. Python 2.7 > ignores DeprecationWarning
so we want to specifically bubble up ONLY Twython Deprecation Warnings
"""
pass
| <commit_before># -*- coding: utf-8 -*-
"""
twython.advisory
~~~~~~~~~~~~~~~~
This module contains Warning classes for Twython to specifically
alert the user about.
This mainly is because Python 2.7 > mutes DeprecationWarning and when
we deprecate a method or variable in Twython, we want to use to see
the Warning but don't want ALL DeprecationWarnings to appear,
only TwythonDeprecationWarnings.
"""
class TwythonDeprecationWarning(DeprecationWarning):
"""Custom DeprecationWarning to be raised when methods/variables
are being deprecated in Twython. Python 2.7 > ignores DeprecationWarning
so we want to specifcally bubble up ONLY Twython Deprecation Warnings
"""
pass
<commit_msg>Fix simple typo: specifcally -> specifically
Closes #526<commit_after> | # -*- coding: utf-8 -*-
"""
twython.advisory
~~~~~~~~~~~~~~~~
This module contains Warning classes for Twython to specifically
alert the user about.
This mainly is because Python 2.7 > mutes DeprecationWarning and when
we deprecate a method or variable in Twython, we want to use to see
the Warning but don't want ALL DeprecationWarnings to appear,
only TwythonDeprecationWarnings.
"""
class TwythonDeprecationWarning(DeprecationWarning):
"""Custom DeprecationWarning to be raised when methods/variables
are being deprecated in Twython. Python 2.7 > ignores DeprecationWarning
so we want to specifically bubble up ONLY Twython Deprecation Warnings
"""
pass
| # -*- coding: utf-8 -*-
"""
twython.advisory
~~~~~~~~~~~~~~~~
This module contains Warning classes for Twython to specifically
alert the user about.
This mainly is because Python 2.7 > mutes DeprecationWarning and when
we deprecate a method or variable in Twython, we want to use to see
the Warning but don't want ALL DeprecationWarnings to appear,
only TwythonDeprecationWarnings.
"""
class TwythonDeprecationWarning(DeprecationWarning):
"""Custom DeprecationWarning to be raised when methods/variables
are being deprecated in Twython. Python 2.7 > ignores DeprecationWarning
so we want to specifcally bubble up ONLY Twython Deprecation Warnings
"""
pass
Fix simple typo: specifcally -> specifically
Closes #526# -*- coding: utf-8 -*-
"""
twython.advisory
~~~~~~~~~~~~~~~~
This module contains Warning classes for Twython to specifically
alert the user about.
This mainly is because Python 2.7 > mutes DeprecationWarning and when
we deprecate a method or variable in Twython, we want to use to see
the Warning but don't want ALL DeprecationWarnings to appear,
only TwythonDeprecationWarnings.
"""
class TwythonDeprecationWarning(DeprecationWarning):
"""Custom DeprecationWarning to be raised when methods/variables
are being deprecated in Twython. Python 2.7 > ignores DeprecationWarning
so we want to specifically bubble up ONLY Twython Deprecation Warnings
"""
pass
| <commit_before># -*- coding: utf-8 -*-
"""
twython.advisory
~~~~~~~~~~~~~~~~
This module contains Warning classes for Twython to specifically
alert the user about.
This mainly is because Python 2.7 > mutes DeprecationWarning and when
we deprecate a method or variable in Twython, we want to use to see
the Warning but don't want ALL DeprecationWarnings to appear,
only TwythonDeprecationWarnings.
"""
class TwythonDeprecationWarning(DeprecationWarning):
"""Custom DeprecationWarning to be raised when methods/variables
are being deprecated in Twython. Python 2.7 > ignores DeprecationWarning
so we want to specifcally bubble up ONLY Twython Deprecation Warnings
"""
pass
<commit_msg>Fix simple typo: specifcally -> specifically
Closes #526<commit_after># -*- coding: utf-8 -*-
"""
twython.advisory
~~~~~~~~~~~~~~~~
This module contains Warning classes for Twython to specifically
alert the user about.
This mainly is because Python 2.7 > mutes DeprecationWarning and when
we deprecate a method or variable in Twython, we want to use to see
the Warning but don't want ALL DeprecationWarnings to appear,
only TwythonDeprecationWarnings.
"""
class TwythonDeprecationWarning(DeprecationWarning):
"""Custom DeprecationWarning to be raised when methods/variables
are being deprecated in Twython. Python 2.7 > ignores DeprecationWarning
so we want to specifically bubble up ONLY Twython Deprecation Warnings
"""
pass
|
5a4a71aaed65bb2ea676a0ec1fa75a8a801f1013 | django_enumfield/contrib/drf.py | django_enumfield/contrib/drf.py | from django.utils import six
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class EnumField(serializers.ChoiceField):
default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')}
def __init__(self, enum, **kwargs):
self.enum = enum
choices = (
(self.get_choice_value(enum_value), enum_value.label)
for _, enum_value in enum.choices()
)
super(EnumField, self).__init__(choices, **kwargs)
def get_choice_value(self, enum_value):
return enum_value.value
def to_internal_value(self, data):
if isinstance(data, six.string_types) and data.isdigit():
data = int(data)
try:
value = self.enum.get(data).value
except AttributeError: # .get() returned None
if not self.required:
raise serializers.SkipField()
self.fail("invalid_choice", input=data)
return value
def to_representation(self, value):
enum_value = self.enum.get(value)
if enum_value is not None:
return self.get_choice_value(enum_value)
class NamedEnumField(EnumField):
def get_choice_value(self, enum_value):
return enum_value.name
| from django.utils import six
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class EnumField(serializers.ChoiceField):
default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')}
def __init__(self, enum, **kwargs):
self.enum = enum
choices = (
(self.get_choice_value(enum_value), enum_value.label)
for _, enum_value in enum.choices()
)
super(EnumField, self).__init__(choices, **kwargs)
def get_choice_value(self, enum_value):
return enum_value.value
def to_internal_value(self, data):
if isinstance(data, six.string_types) and data.isdigit():
data = int(data)
try:
value = self.enum.get(data).value
except AttributeError: # .get() returned None
if not self.required:
raise serializers.SkipField()
self.fail("invalid_choice", input=data)
return value
def to_representation(self, value):
enum_value = self.enum.get(value)
if enum_value is not None:
return self.get_choice_value(enum_value)
class NamedEnumField(EnumField):
def get_choice_value(self, enum_value):
return enum_value.name
class Meta:
swagger_schema_fields = {"type": "string"}
| Document the type of NamedEnumField properly | Document the type of NamedEnumField properly
| Python | mit | 5monkeys/django-enumfield | from django.utils import six
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class EnumField(serializers.ChoiceField):
default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')}
def __init__(self, enum, **kwargs):
self.enum = enum
choices = (
(self.get_choice_value(enum_value), enum_value.label)
for _, enum_value in enum.choices()
)
super(EnumField, self).__init__(choices, **kwargs)
def get_choice_value(self, enum_value):
return enum_value.value
def to_internal_value(self, data):
if isinstance(data, six.string_types) and data.isdigit():
data = int(data)
try:
value = self.enum.get(data).value
except AttributeError: # .get() returned None
if not self.required:
raise serializers.SkipField()
self.fail("invalid_choice", input=data)
return value
def to_representation(self, value):
enum_value = self.enum.get(value)
if enum_value is not None:
return self.get_choice_value(enum_value)
class NamedEnumField(EnumField):
def get_choice_value(self, enum_value):
return enum_value.name
Document the type of NamedEnumField properly | from django.utils import six
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class EnumField(serializers.ChoiceField):
default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')}
def __init__(self, enum, **kwargs):
self.enum = enum
choices = (
(self.get_choice_value(enum_value), enum_value.label)
for _, enum_value in enum.choices()
)
super(EnumField, self).__init__(choices, **kwargs)
def get_choice_value(self, enum_value):
return enum_value.value
def to_internal_value(self, data):
if isinstance(data, six.string_types) and data.isdigit():
data = int(data)
try:
value = self.enum.get(data).value
except AttributeError: # .get() returned None
if not self.required:
raise serializers.SkipField()
self.fail("invalid_choice", input=data)
return value
def to_representation(self, value):
enum_value = self.enum.get(value)
if enum_value is not None:
return self.get_choice_value(enum_value)
class NamedEnumField(EnumField):
def get_choice_value(self, enum_value):
return enum_value.name
class Meta:
swagger_schema_fields = {"type": "string"}
| <commit_before>from django.utils import six
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class EnumField(serializers.ChoiceField):
default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')}
def __init__(self, enum, **kwargs):
self.enum = enum
choices = (
(self.get_choice_value(enum_value), enum_value.label)
for _, enum_value in enum.choices()
)
super(EnumField, self).__init__(choices, **kwargs)
def get_choice_value(self, enum_value):
return enum_value.value
def to_internal_value(self, data):
if isinstance(data, six.string_types) and data.isdigit():
data = int(data)
try:
value = self.enum.get(data).value
except AttributeError: # .get() returned None
if not self.required:
raise serializers.SkipField()
self.fail("invalid_choice", input=data)
return value
def to_representation(self, value):
enum_value = self.enum.get(value)
if enum_value is not None:
return self.get_choice_value(enum_value)
class NamedEnumField(EnumField):
def get_choice_value(self, enum_value):
return enum_value.name
<commit_msg>Document the type of NamedEnumField properly<commit_after> | from django.utils import six
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class EnumField(serializers.ChoiceField):
default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')}
def __init__(self, enum, **kwargs):
self.enum = enum
choices = (
(self.get_choice_value(enum_value), enum_value.label)
for _, enum_value in enum.choices()
)
super(EnumField, self).__init__(choices, **kwargs)
def get_choice_value(self, enum_value):
return enum_value.value
def to_internal_value(self, data):
if isinstance(data, six.string_types) and data.isdigit():
data = int(data)
try:
value = self.enum.get(data).value
except AttributeError: # .get() returned None
if not self.required:
raise serializers.SkipField()
self.fail("invalid_choice", input=data)
return value
def to_representation(self, value):
enum_value = self.enum.get(value)
if enum_value is not None:
return self.get_choice_value(enum_value)
class NamedEnumField(EnumField):
def get_choice_value(self, enum_value):
return enum_value.name
class Meta:
swagger_schema_fields = {"type": "string"}
| from django.utils import six
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class EnumField(serializers.ChoiceField):
default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')}
def __init__(self, enum, **kwargs):
self.enum = enum
choices = (
(self.get_choice_value(enum_value), enum_value.label)
for _, enum_value in enum.choices()
)
super(EnumField, self).__init__(choices, **kwargs)
def get_choice_value(self, enum_value):
return enum_value.value
def to_internal_value(self, data):
if isinstance(data, six.string_types) and data.isdigit():
data = int(data)
try:
value = self.enum.get(data).value
except AttributeError: # .get() returned None
if not self.required:
raise serializers.SkipField()
self.fail("invalid_choice", input=data)
return value
def to_representation(self, value):
enum_value = self.enum.get(value)
if enum_value is not None:
return self.get_choice_value(enum_value)
class NamedEnumField(EnumField):
def get_choice_value(self, enum_value):
return enum_value.name
Document the type of NamedEnumField properlyfrom django.utils import six
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class EnumField(serializers.ChoiceField):
default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')}
def __init__(self, enum, **kwargs):
self.enum = enum
choices = (
(self.get_choice_value(enum_value), enum_value.label)
for _, enum_value in enum.choices()
)
super(EnumField, self).__init__(choices, **kwargs)
def get_choice_value(self, enum_value):
return enum_value.value
def to_internal_value(self, data):
if isinstance(data, six.string_types) and data.isdigit():
data = int(data)
try:
value = self.enum.get(data).value
except AttributeError: # .get() returned None
if not self.required:
raise serializers.SkipField()
self.fail("invalid_choice", input=data)
return value
def to_representation(self, value):
enum_value = self.enum.get(value)
if enum_value is not None:
return self.get_choice_value(enum_value)
class NamedEnumField(EnumField):
def get_choice_value(self, enum_value):
return enum_value.name
class Meta:
swagger_schema_fields = {"type": "string"}
| <commit_before>from django.utils import six
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class EnumField(serializers.ChoiceField):
default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')}
def __init__(self, enum, **kwargs):
self.enum = enum
choices = (
(self.get_choice_value(enum_value), enum_value.label)
for _, enum_value in enum.choices()
)
super(EnumField, self).__init__(choices, **kwargs)
def get_choice_value(self, enum_value):
return enum_value.value
def to_internal_value(self, data):
if isinstance(data, six.string_types) and data.isdigit():
data = int(data)
try:
value = self.enum.get(data).value
except AttributeError: # .get() returned None
if not self.required:
raise serializers.SkipField()
self.fail("invalid_choice", input=data)
return value
def to_representation(self, value):
enum_value = self.enum.get(value)
if enum_value is not None:
return self.get_choice_value(enum_value)
class NamedEnumField(EnumField):
def get_choice_value(self, enum_value):
return enum_value.name
<commit_msg>Document the type of NamedEnumField properly<commit_after>from django.utils import six
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class EnumField(serializers.ChoiceField):
default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')}
def __init__(self, enum, **kwargs):
self.enum = enum
choices = (
(self.get_choice_value(enum_value), enum_value.label)
for _, enum_value in enum.choices()
)
super(EnumField, self).__init__(choices, **kwargs)
def get_choice_value(self, enum_value):
return enum_value.value
def to_internal_value(self, data):
if isinstance(data, six.string_types) and data.isdigit():
data = int(data)
try:
value = self.enum.get(data).value
except AttributeError: # .get() returned None
if not self.required:
raise serializers.SkipField()
self.fail("invalid_choice", input=data)
return value
def to_representation(self, value):
enum_value = self.enum.get(value)
if enum_value is not None:
return self.get_choice_value(enum_value)
class NamedEnumField(EnumField):
def get_choice_value(self, enum_value):
return enum_value.name
class Meta:
swagger_schema_fields = {"type": "string"}
|
bbfa404e4679f4229e44fd7e641e62fdd2e7bdd5 | djangorestframework/__init__.py | djangorestframework/__init__.py | __version__ = '0.3.2-dev'
VERSION = __version__ # synonym
| __version__ = '0.3.3-dev'
VERSION = __version__ # synonym
| Fix silly error. This makes more sense. | Fix silly error. This makes more sense. | Python | bsd-2-clause | kylefox/django-rest-framework,sbellem/django-rest-framework,jerryhebert/django-rest-framework,atombrella/django-rest-framework,rafaelcaricio/django-rest-framework,brandoncazander/django-rest-framework,hnakamur/django-rest-framework,YBJAY00000/django-rest-framework,maryokhin/django-rest-framework,ezheidtmann/django-rest-framework,zeldalink0515/django-rest-framework,jtiai/django-rest-framework,werthen/django-rest-framework,sbellem/django-rest-framework,d0ugal/django-rest-framework,AlexandreProenca/django-rest-framework,simudream/django-rest-framework,lubomir/django-rest-framework,thedrow/django-rest-framework-1,cheif/django-rest-framework,sehmaschine/django-rest-framework,ossanna16/django-rest-framework,agconti/django-rest-framework,johnraz/django-rest-framework,dmwyatt/django-rest-framework,pombredanne/django-rest-framework,jerryhebert/django-rest-framework,douwevandermeij/django-rest-framework,elim/django-rest-framework,tigeraniya/django-rest-framework,yiyocx/django-rest-framework,wwj718/django-rest-framework,ashishfinoit/django-rest-framework,antonyc/django-rest-framework,rafaelcaricio/django-rest-framework,johnraz/django-rest-framework,raphaelmerx/django-rest-framework,wangpanjun/django-rest-framework,ambivalentno/django-rest-framework,uruz/django-rest-framework,callorico/django-rest-framework,kennydude/django-rest-framework,potpath/django-rest-framework,wzbozon/django-rest-framework,hunter007/django-rest-framework,fishky/django-rest-framework,ashishfinoit/django-rest-framework,ambivalentno/django-rest-framework,kylefox/django-rest-framework,nryoung/django-rest-framework,krinart/django-rest-framework,hnarayanan/django-rest-framework,ambivalentno/django-rest-framework,uploadcare/django-rest-framework,rhblind/django-rest-framework,damycra/django-rest-framework,wedaly/django-rest-framework,werthen/django-rest-framework,gregmuellegger/django-rest-framework,sheppard/django-rest-framework,rubendura/django-rest-framework,uploadcare/django-rest-framework,ticosax/django-rest-framework,jtiai/django-rest-framework,mgaitan/django-rest-framework,lubomir/django-rest-framework,sehmaschine/django-rest-framework,simudream/django-rest-framework,callorico/django-rest-framework,alacritythief/django-rest-framework,yiyocx/django-rest-framework,alacritythief/django-rest-framework,MJafarMashhadi/django-rest-framework,atombrella/django-rest-framework,xiaotangyuan/django-rest-framework,agconti/django-rest-framework,AlexandreProenca/django-rest-framework,wedaly/django-rest-framework,VishvajitP/django-rest-framework,fishky/django-rest-framework,werthen/django-rest-framework,dmwyatt/django-rest-framework,jpadilla/django-rest-framework,ticosax/django-rest-framework,nhorelik/django-rest-framework,jpadilla/django-rest-framework,brandoncazander/django-rest-framework,ebsaral/django-rest-framework,abdulhaq-e/django-rest-framework,akalipetis/django-rest-framework,adambain-vokal/django-rest-framework,paolopaolopaolo/django-rest-framework,wwj718/django-rest-framework,ajaali/django-rest-framework,simudream/django-rest-framework,potpath/django-rest-framework,adambain-vokal/django-rest-framework,canassa/django-rest-framework,pombredanne/django-rest-framework,gregmuellegger/django-rest-framework,edx/django-rest-framework,damycra/django-rest-framework,James1345/django-rest-framework,uruz/django-rest-framework,justanr/django-rest-framework,justanr/django-rest-framework,potpath/django-rest-framework,uploadcare/django-rest-framework,qsorix/django-rest-framework,jpulec/django-rest-framework,cyberj/django-rest-framework,uruz/django-rest-framework,gregmuellegger/django-rest-framework,xiaotangyuan/django-rest-framework,thedrow/django-rest-framework-1,ebsaral/django-rest-framework,davesque/django-rest-framework,fishky/django-rest-framework,rafaelang/django-rest-framework,wangpanjun/django-rest-framework,andriy-s/django-rest-framework,cheif/django-rest-framework,jpulec/django-rest-framework,sheppard/django-rest-framework,jness/django-rest-framework,arpheno/django-rest-framework,ebsaral/django-rest-framework,rhblind/django-rest-framework,kezabelle/django-rest-framework,paolopaolopaolo/django-rest-framework,tigeraniya/django-rest-framework,raphaelmerx/django-rest-framework,kgeorgy/django-rest-framework,MJafarMashhadi/django-rest-framework,wangpanjun/django-rest-framework,VishvajitP/django-rest-framework,xiaotangyuan/django-rest-framework,aericson/django-rest-framework,aericson/django-rest-framework,ezheidtmann/django-rest-framework,vstoykov/django-rest-framework,elim/django-rest-framework,kennydude/django-rest-framework,kgeorgy/django-rest-framework,ajaali/django-rest-framework,iheitlager/django-rest-framework,tigeraniya/django-rest-framework,akalipetis/django-rest-framework,linovia/django-rest-framework,ashishfinoit/django-rest-framework,douwevandermeij/django-rest-framework,wwj718/django-rest-framework,linovia/django-rest-framework,arpheno/django-rest-framework,abdulhaq-e/django-rest-framework,MJafarMashhadi/django-rest-framework,jpadilla/django-rest-framework,cyberj/django-rest-framework,delinhabit/django-rest-framework,tcroiset/django-rest-framework,davesque/django-rest-framework,damycra/django-rest-framework,James1345/django-rest-framework,waytai/django-rest-framework,agconti/django-rest-framework,bluedazzle/django-rest-framework,leeahoward/django-rest-framework,tomchristie/django-rest-framework,antonyc/django-rest-framework,rubendura/django-rest-framework,edx/django-rest-framework,hunter007/django-rest-framework,lubomir/django-rest-framework,sehmaschine/django-rest-framework,kezabelle/django-rest-framework,James1345/django-rest-framework,douwevandermeij/django-rest-framework,bluedazzle/django-rest-framework,hnarayanan/django-rest-framework,canassa/django-rest-framework,d0ugal/django-rest-framework,alacritythief/django-rest-framework,sheppard/django-rest-framework,krinart/django-rest-framework,qsorix/django-rest-framework,mgaitan/django-rest-framework,pombredanne/django-rest-framework,ossanna16/django-rest-framework,waytai/django-rest-framework,jpulec/django-rest-framework,raphaelmerx/django-rest-framework,cyberj/django-rest-framework,nryoung/django-rest-framework,abdulhaq-e/django-rest-framework,thedrow/django-rest-framework-1,kylefox/django-rest-framework,ossanna16/django-rest-framework,arpheno/django-rest-framework,wzbozon/django-rest-framework,nryoung/django-rest-framework,tcroiset/django-rest-framework,linovia/django-rest-framework,hnakamur/django-rest-framework,sbellem/django-rest-framework,dmwyatt/django-rest-framework,zeldalink0515/django-rest-framework,iheitlager/django-rest-framework,vstoykov/django-rest-framework,kgeorgy/django-rest-framework,hnakamur/django-rest-framework,rhblind/django-rest-framework,antonyc/django-rest-framework,jerryhebert/django-rest-framework,tomchristie/django-rest-framework,bluedazzle/django-rest-framework,tomchristie/django-rest-framework,jness/django-rest-framework,hunter007/django-rest-framework,elim/django-rest-framework,brandoncazander/django-rest-framework,paolopaolopaolo/django-rest-framework,rafaelang/django-rest-framework,adambain-vokal/django-rest-framework,tcroiset/django-rest-framework,maryokhin/django-rest-framework,vstoykov/django-rest-framework,nhorelik/django-rest-framework,VishvajitP/django-rest-framework,johnraz/django-rest-framework,rafaelcaricio/django-rest-framework,andriy-s/django-rest-framework,buptlsl/django-rest-framework,buptlsl/django-rest-framework,rubendura/django-rest-framework,ezheidtmann/django-rest-framework,waytai/django-rest-framework,jness/django-rest-framework,YBJAY00000/django-rest-framework,rafaelang/django-rest-framework,leeahoward/django-rest-framework,HireAnEsquire/django-rest-framework,maryokhin/django-rest-framework,AlexandreProenca/django-rest-framework,zeldalink0515/django-rest-framework,mgaitan/django-rest-framework,iheitlager/django-rest-framework,andriy-s/django-rest-framework,HireAnEsquire/django-rest-framework,kezabelle/django-rest-framework,yiyocx/django-rest-framework,cheif/django-rest-framework,ajaali/django-rest-framework,nhorelik/django-rest-framework,justanr/django-rest-framework,edx/django-rest-framework,krinart/django-rest-framework,HireAnEsquire/django-rest-framework,hnarayanan/django-rest-framework,ticosax/django-rest-framework,canassa/django-rest-framework,leeahoward/django-rest-framework,buptlsl/django-rest-framework,delinhabit/django-rest-framework,YBJAY00000/django-rest-framework,wedaly/django-rest-framework,delinhabit/django-rest-framework,aericson/django-rest-framework,qsorix/django-rest-framework,d0ugal/django-rest-framework,wzbozon/django-rest-framework,jtiai/django-rest-framework,akalipetis/django-rest-framework,callorico/django-rest-framework,kennydude/django-rest-framework,davesque/django-rest-framework,atombrella/django-rest-framework | __version__ = '0.3.2-dev'
VERSION = __version__ # synonym
Fix silly error. This makes more sense. | __version__ = '0.3.3-dev'
VERSION = __version__ # synonym
| <commit_before>__version__ = '0.3.2-dev'
VERSION = __version__ # synonym
<commit_msg>Fix silly error. This makes more sense.<commit_after> | __version__ = '0.3.3-dev'
VERSION = __version__ # synonym
| __version__ = '0.3.2-dev'
VERSION = __version__ # synonym
Fix silly error. This makes more sense.__version__ = '0.3.3-dev'
VERSION = __version__ # synonym
| <commit_before>__version__ = '0.3.2-dev'
VERSION = __version__ # synonym
<commit_msg>Fix silly error. This makes more sense.<commit_after>__version__ = '0.3.3-dev'
VERSION = __version__ # synonym
|
fbea1cdd96ef259e8affc87ee72d8bbaef40c00d | salt/config.py | salt/config.py | '''
All salt configuration loading and defaults should be in this module
'''
# Import python modules
import os
import sys
import socket
# Import third party libs
import yaml
def minion_config(path):
'''
Reads in the minion configuration file and sets up special options
'''
opts = {'master': 'mcp',
'master_port': '7777',
'pki_dir': '/etc/salt/pki',
'hostname': socket.getfqdn(),
}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The minon configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
opts['master_uri'] = 'tcp://' + opts['master'] + ':' + opts['master_port']
return opts
def master_config(path):
'''
Reads in the master configuration file and sets up default options
'''
opts = {}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The master configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
return opts
| '''
All salt configuration loading and defaults should be in this module
'''
# Import python modules
import os
import sys
import socket
# Import third party libs
import yaml
def minion_config(path):
'''
Reads in the minion configuration file and sets up special options
'''
opts = {'master': 'mcp',
'master_port': '7777',
'pki_dir': '/etc/salt/pki',
'hostname': socket.getfqdn(),
}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The minon configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
opts['master_uri'] = 'tcp://' + opts['master'] + ':' + opts['master_port']
return opts
def master_config(path):
'''
Reads in the master configuration file and sets up default options
'''
opts = {'interface': '0.0.0.0',
'publish_port': 7777,
'worker_threads': 5,
'worker_port': 7778,
'ret_port': 7776,
'local_threads': 5,
'local_port': 7775,
'local_worker_port': 7774,
'cachedir': '/var/cache/salt'}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The master configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
return opts
| Add the default options for the salt master | Add the default options for the salt master
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | '''
All salt configuration loading and defaults should be in this module
'''
# Import python modules
import os
import sys
import socket
# Import third party libs
import yaml
def minion_config(path):
'''
Reads in the minion configuration file and sets up special options
'''
opts = {'master': 'mcp',
'master_port': '7777',
'pki_dir': '/etc/salt/pki',
'hostname': socket.getfqdn(),
}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The minon configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
opts['master_uri'] = 'tcp://' + opts['master'] + ':' + opts['master_port']
return opts
def master_config(path):
'''
Reads in the master configuration file and sets up default options
'''
opts = {}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The master configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
return opts
Add the default options for the salt master | '''
All salt configuration loading and defaults should be in this module
'''
# Import python modules
import os
import sys
import socket
# Import third party libs
import yaml
def minion_config(path):
'''
Reads in the minion configuration file and sets up special options
'''
opts = {'master': 'mcp',
'master_port': '7777',
'pki_dir': '/etc/salt/pki',
'hostname': socket.getfqdn(),
}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The minon configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
opts['master_uri'] = 'tcp://' + opts['master'] + ':' + opts['master_port']
return opts
def master_config(path):
'''
Reads in the master configuration file and sets up default options
'''
opts = {'interface': '0.0.0.0',
'publish_port': 7777,
'worker_threads': 5,
'worker_port': 7778,
'ret_port': 7776,
'local_threads': 5,
'local_port': 7775,
'local_worker_port': 7774,
'cachedir': '/var/cache/salt'}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The master configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
return opts
| <commit_before>'''
All salt configuration loading and defaults should be in this module
'''
# Import python modules
import os
import sys
import socket
# Import third party libs
import yaml
def minion_config(path):
'''
Reads in the minion configuration file and sets up special options
'''
opts = {'master': 'mcp',
'master_port': '7777',
'pki_dir': '/etc/salt/pki',
'hostname': socket.getfqdn(),
}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The minon configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
opts['master_uri'] = 'tcp://' + opts['master'] + ':' + opts['master_port']
return opts
def master_config(path):
'''
Reads in the master configuration file and sets up default options
'''
opts = {}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The master configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
return opts
<commit_msg>Add the default options for the salt master<commit_after> | '''
All salt configuration loading and defaults should be in this module
'''
# Import python modules
import os
import sys
import socket
# Import third party libs
import yaml
def minion_config(path):
'''
Reads in the minion configuration file and sets up special options
'''
opts = {'master': 'mcp',
'master_port': '7777',
'pki_dir': '/etc/salt/pki',
'hostname': socket.getfqdn(),
}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The minon configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
opts['master_uri'] = 'tcp://' + opts['master'] + ':' + opts['master_port']
return opts
def master_config(path):
'''
Reads in the master configuration file and sets up default options
'''
opts = {'interface': '0.0.0.0',
'publish_port': 7777,
'worker_threads': 5,
'worker_port': 7778,
'ret_port': 7776,
'local_threads': 5,
'local_port': 7775,
'local_worker_port': 7774,
'cachedir': '/var/cache/salt'}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The master configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
return opts
| '''
All salt configuration loading and defaults should be in this module
'''
# Import python modules
import os
import sys
import socket
# Import third party libs
import yaml
def minion_config(path):
'''
Reads in the minion configuration file and sets up special options
'''
opts = {'master': 'mcp',
'master_port': '7777',
'pki_dir': '/etc/salt/pki',
'hostname': socket.getfqdn(),
}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The minon configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
opts['master_uri'] = 'tcp://' + opts['master'] + ':' + opts['master_port']
return opts
def master_config(path):
'''
Reads in the master configuration file and sets up default options
'''
opts = {}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The master configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
return opts
Add the default options for the salt master'''
All salt configuration loading and defaults should be in this module
'''
# Import python modules
import os
import sys
import socket
# Import third party libs
import yaml
def minion_config(path):
'''
Reads in the minion configuration file and sets up special options
'''
opts = {'master': 'mcp',
'master_port': '7777',
'pki_dir': '/etc/salt/pki',
'hostname': socket.getfqdn(),
}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The minon configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
opts['master_uri'] = 'tcp://' + opts['master'] + ':' + opts['master_port']
return opts
def master_config(path):
'''
Reads in the master configuration file and sets up default options
'''
opts = {'interface': '0.0.0.0',
'publish_port': 7777,
'worker_threads': 5,
'worker_port': 7778,
'ret_port': 7776,
'local_threads': 5,
'local_port': 7775,
'local_worker_port': 7774,
'cachedir': '/var/cache/salt'}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The master configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
return opts
| <commit_before>'''
All salt configuration loading and defaults should be in this module
'''
# Import python modules
import os
import sys
import socket
# Import third party libs
import yaml
def minion_config(path):
'''
Reads in the minion configuration file and sets up special options
'''
opts = {'master': 'mcp',
'master_port': '7777',
'pki_dir': '/etc/salt/pki',
'hostname': socket.getfqdn(),
}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The minon configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
opts['master_uri'] = 'tcp://' + opts['master'] + ':' + opts['master_port']
return opts
def master_config(path):
'''
Reads in the master configuration file and sets up default options
'''
opts = {}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The master configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
return opts
<commit_msg>Add the default options for the salt master<commit_after>'''
All salt configuration loading and defaults should be in this module
'''
# Import python modules
import os
import sys
import socket
# Import third party libs
import yaml
def minion_config(path):
'''
Reads in the minion configuration file and sets up special options
'''
opts = {'master': 'mcp',
'master_port': '7777',
'pki_dir': '/etc/salt/pki',
'hostname': socket.getfqdn(),
}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The minon configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
opts['master_uri'] = 'tcp://' + opts['master'] + ':' + opts['master_port']
return opts
def master_config(path):
'''
Reads in the master configuration file and sets up default options
'''
opts = {'interface': '0.0.0.0',
'publish_port': 7777,
'worker_threads': 5,
'worker_port': 7778,
'ret_port': 7776,
'local_threads': 5,
'local_port': 7775,
'local_worker_port': 7774,
'cachedir': '/var/cache/salt'}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The master configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
return opts
|
baf08cb5aedd7a75dad8f79601ce31244544a3dd | elections/uk_general_election_2015/views/parties.py | elections/uk_general_election_2015/views/parties.py | from candidates.views import PartyDetailView
class UKPartyDetailView(PartyDetailView):
def get_context_data(self, **kwargs):
context = super(UKPartyDetailView, self).get_context_data(**kwargs)
party_ec_id = context['party'].identifiers.get(scheme='electoral-commission')
context['ec_url'] = None
if party_ec_id:
ec_tmpl = 'http://search.electoralcommission.org.uk/English/Registrations/{0}'
context['ec_url'] = ec_tmpl.format(party_ec_id)
context['register'] = context['party'].extra.register
return context
| from candidates.views import PartyDetailView
from popolo.models import Identifier
class UKPartyDetailView(PartyDetailView):
def get_context_data(self, **kwargs):
context = super(UKPartyDetailView, self).get_context_data(**kwargs)
context['ec_url'] = ''
context['register'] = ''
try:
party_ec_id = context['party'].identifiers.get(scheme='electoral-commission')
if party_ec_id:
ec_tmpl = 'http://search.electoralcommission.org.uk/English/Registrations/{0}'
context['ec_url'] = ec_tmpl.format(party_ec_id)
context['register'] = context['party'].extra.register
except Identifier.DoesNotExist:
pass
return context
| Fix the 'Independent' party pages for UK elections | Fix the 'Independent' party pages for UK elections
There's no Electoral Commission identifier for the 'Independent'
pseudo-party, so the party page for independents was failing.
| Python | agpl-3.0 | mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,datamade/yournextmp-popit,neavouli/yournextrepresentative,neavouli/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextmp-popit,neavouli/yournextrepresentative,datamade/yournextmp-popit,datamade/yournextmp-popit,mysociety/yournextmp-popit,datamade/yournextmp-popit | from candidates.views import PartyDetailView
class UKPartyDetailView(PartyDetailView):
def get_context_data(self, **kwargs):
context = super(UKPartyDetailView, self).get_context_data(**kwargs)
party_ec_id = context['party'].identifiers.get(scheme='electoral-commission')
context['ec_url'] = None
if party_ec_id:
ec_tmpl = 'http://search.electoralcommission.org.uk/English/Registrations/{0}'
context['ec_url'] = ec_tmpl.format(party_ec_id)
context['register'] = context['party'].extra.register
return context
Fix the 'Independent' party pages for UK elections
There's no Electoral Commission identifier for the 'Independent'
pseudo-party, so the party page for independents was failing. | from candidates.views import PartyDetailView
from popolo.models import Identifier
class UKPartyDetailView(PartyDetailView):
def get_context_data(self, **kwargs):
context = super(UKPartyDetailView, self).get_context_data(**kwargs)
context['ec_url'] = ''
context['register'] = ''
try:
party_ec_id = context['party'].identifiers.get(scheme='electoral-commission')
if party_ec_id:
ec_tmpl = 'http://search.electoralcommission.org.uk/English/Registrations/{0}'
context['ec_url'] = ec_tmpl.format(party_ec_id)
context['register'] = context['party'].extra.register
except Identifier.DoesNotExist:
pass
return context
| <commit_before>from candidates.views import PartyDetailView
class UKPartyDetailView(PartyDetailView):
def get_context_data(self, **kwargs):
context = super(UKPartyDetailView, self).get_context_data(**kwargs)
party_ec_id = context['party'].identifiers.get(scheme='electoral-commission')
context['ec_url'] = None
if party_ec_id:
ec_tmpl = 'http://search.electoralcommission.org.uk/English/Registrations/{0}'
context['ec_url'] = ec_tmpl.format(party_ec_id)
context['register'] = context['party'].extra.register
return context
<commit_msg>Fix the 'Independent' party pages for UK elections
There's no Electoral Commission identifier for the 'Independent'
pseudo-party, so the party page for independents was failing.<commit_after> | from candidates.views import PartyDetailView
from popolo.models import Identifier
class UKPartyDetailView(PartyDetailView):
def get_context_data(self, **kwargs):
context = super(UKPartyDetailView, self).get_context_data(**kwargs)
context['ec_url'] = ''
context['register'] = ''
try:
party_ec_id = context['party'].identifiers.get(scheme='electoral-commission')
if party_ec_id:
ec_tmpl = 'http://search.electoralcommission.org.uk/English/Registrations/{0}'
context['ec_url'] = ec_tmpl.format(party_ec_id)
context['register'] = context['party'].extra.register
except Identifier.DoesNotExist:
pass
return context
| from candidates.views import PartyDetailView
class UKPartyDetailView(PartyDetailView):
def get_context_data(self, **kwargs):
context = super(UKPartyDetailView, self).get_context_data(**kwargs)
party_ec_id = context['party'].identifiers.get(scheme='electoral-commission')
context['ec_url'] = None
if party_ec_id:
ec_tmpl = 'http://search.electoralcommission.org.uk/English/Registrations/{0}'
context['ec_url'] = ec_tmpl.format(party_ec_id)
context['register'] = context['party'].extra.register
return context
Fix the 'Independent' party pages for UK elections
There's no Electoral Commission identifier for the 'Independent'
pseudo-party, so the party page for independents was failing.from candidates.views import PartyDetailView
from popolo.models import Identifier
class UKPartyDetailView(PartyDetailView):
def get_context_data(self, **kwargs):
context = super(UKPartyDetailView, self).get_context_data(**kwargs)
context['ec_url'] = ''
context['register'] = ''
try:
party_ec_id = context['party'].identifiers.get(scheme='electoral-commission')
if party_ec_id:
ec_tmpl = 'http://search.electoralcommission.org.uk/English/Registrations/{0}'
context['ec_url'] = ec_tmpl.format(party_ec_id)
context['register'] = context['party'].extra.register
except Identifier.DoesNotExist:
pass
return context
| <commit_before>from candidates.views import PartyDetailView
class UKPartyDetailView(PartyDetailView):
def get_context_data(self, **kwargs):
context = super(UKPartyDetailView, self).get_context_data(**kwargs)
party_ec_id = context['party'].identifiers.get(scheme='electoral-commission')
context['ec_url'] = None
if party_ec_id:
ec_tmpl = 'http://search.electoralcommission.org.uk/English/Registrations/{0}'
context['ec_url'] = ec_tmpl.format(party_ec_id)
context['register'] = context['party'].extra.register
return context
<commit_msg>Fix the 'Independent' party pages for UK elections
There's no Electoral Commission identifier for the 'Independent'
pseudo-party, so the party page for independents was failing.<commit_after>from candidates.views import PartyDetailView
from popolo.models import Identifier
class UKPartyDetailView(PartyDetailView):
def get_context_data(self, **kwargs):
context = super(UKPartyDetailView, self).get_context_data(**kwargs)
context['ec_url'] = ''
context['register'] = ''
try:
party_ec_id = context['party'].identifiers.get(scheme='electoral-commission')
if party_ec_id:
ec_tmpl = 'http://search.electoralcommission.org.uk/English/Registrations/{0}'
context['ec_url'] = ec_tmpl.format(party_ec_id)
context['register'] = context['party'].extra.register
except Identifier.DoesNotExist:
pass
return context
|
e0f296e776e2aaed2536eeebfb4900a23973aaf5 | tests/test_json.py | tests/test_json.py | from __future__ import absolute_import
import fnmatch
import os
import unittest
from . import validate_json_format
class TestSettings(unittest.TestCase):
def _get_json_files(self, file_pattern, folder='.'):
for root, dirnames, filenames in os.walk(folder):
for filename in fnmatch.filter(filenames, file_pattern):
yield os.path.join(root, filename)
for dirname in [d for d in dirnames
if d not in ('.git', '.tox')]:
for f in self._get_json_files(
file_pattern, os.path.join(root, dirname)):
yield f
def test_json_settings(self):
"""Test each JSON file."""
file_patterns = (
'*.sublime-settings',
'*.sublime-commands',
'*.sublime-menu',
)
for file_pattern in file_patterns:
for f in self._get_json_files(file_pattern):
print(f)
self.assertFalse(
validate_json_format.CheckJsonFormat(
False, True).check_format(f),
"%s does not comform to expected format!" % f)
| from __future__ import absolute_import
import fnmatch
import os
import unittest
from . import validate_json_format
class TestSettings(unittest.TestCase):
def _get_json_files(self, file_pattern, folder='.'):
for root, dirnames, filenames in os.walk(folder):
for filename in fnmatch.filter(filenames, file_pattern):
yield os.path.join(root, filename)
for dirname in [d for d in dirnames
if d not in ('.git', '.tox')]:
for f in self._get_json_files(
file_pattern, os.path.join(root, dirname)):
yield f
def test_json_settings(self):
"""Test each JSON file."""
file_patterns = (
'*.sublime-settings',
'*.sublime-commands',
'*.sublime-menu',
'*.json'
)
for file_pattern in file_patterns:
for f in self._get_json_files(file_pattern):
print(f)
self.assertFalse(
validate_json_format.CheckJsonFormat(
False, True).check_format(f),
"%s does not comform to expected format!" % f)
| Add '*.json' file extensions to test pattern list. | Add '*.json' file extensions to test pattern list.
| Python | mit | jonlabelle/SublimeJsPrettier,jonlabelle/SublimeJsPrettier | from __future__ import absolute_import
import fnmatch
import os
import unittest
from . import validate_json_format
class TestSettings(unittest.TestCase):
def _get_json_files(self, file_pattern, folder='.'):
for root, dirnames, filenames in os.walk(folder):
for filename in fnmatch.filter(filenames, file_pattern):
yield os.path.join(root, filename)
for dirname in [d for d in dirnames
if d not in ('.git', '.tox')]:
for f in self._get_json_files(
file_pattern, os.path.join(root, dirname)):
yield f
def test_json_settings(self):
"""Test each JSON file."""
file_patterns = (
'*.sublime-settings',
'*.sublime-commands',
'*.sublime-menu',
)
for file_pattern in file_patterns:
for f in self._get_json_files(file_pattern):
print(f)
self.assertFalse(
validate_json_format.CheckJsonFormat(
False, True).check_format(f),
"%s does not comform to expected format!" % f)
Add '*.json' file extensions to test pattern list. | from __future__ import absolute_import
import fnmatch
import os
import unittest
from . import validate_json_format
class TestSettings(unittest.TestCase):
def _get_json_files(self, file_pattern, folder='.'):
for root, dirnames, filenames in os.walk(folder):
for filename in fnmatch.filter(filenames, file_pattern):
yield os.path.join(root, filename)
for dirname in [d for d in dirnames
if d not in ('.git', '.tox')]:
for f in self._get_json_files(
file_pattern, os.path.join(root, dirname)):
yield f
def test_json_settings(self):
"""Test each JSON file."""
file_patterns = (
'*.sublime-settings',
'*.sublime-commands',
'*.sublime-menu',
'*.json'
)
for file_pattern in file_patterns:
for f in self._get_json_files(file_pattern):
print(f)
self.assertFalse(
validate_json_format.CheckJsonFormat(
False, True).check_format(f),
"%s does not comform to expected format!" % f)
| <commit_before>from __future__ import absolute_import
import fnmatch
import os
import unittest
from . import validate_json_format
class TestSettings(unittest.TestCase):
def _get_json_files(self, file_pattern, folder='.'):
for root, dirnames, filenames in os.walk(folder):
for filename in fnmatch.filter(filenames, file_pattern):
yield os.path.join(root, filename)
for dirname in [d for d in dirnames
if d not in ('.git', '.tox')]:
for f in self._get_json_files(
file_pattern, os.path.join(root, dirname)):
yield f
def test_json_settings(self):
"""Test each JSON file."""
file_patterns = (
'*.sublime-settings',
'*.sublime-commands',
'*.sublime-menu',
)
for file_pattern in file_patterns:
for f in self._get_json_files(file_pattern):
print(f)
self.assertFalse(
validate_json_format.CheckJsonFormat(
False, True).check_format(f),
"%s does not comform to expected format!" % f)
<commit_msg>Add '*.json' file extensions to test pattern list.<commit_after> | from __future__ import absolute_import
import fnmatch
import os
import unittest
from . import validate_json_format
class TestSettings(unittest.TestCase):
def _get_json_files(self, file_pattern, folder='.'):
for root, dirnames, filenames in os.walk(folder):
for filename in fnmatch.filter(filenames, file_pattern):
yield os.path.join(root, filename)
for dirname in [d for d in dirnames
if d not in ('.git', '.tox')]:
for f in self._get_json_files(
file_pattern, os.path.join(root, dirname)):
yield f
def test_json_settings(self):
"""Test each JSON file."""
file_patterns = (
'*.sublime-settings',
'*.sublime-commands',
'*.sublime-menu',
'*.json'
)
for file_pattern in file_patterns:
for f in self._get_json_files(file_pattern):
print(f)
self.assertFalse(
validate_json_format.CheckJsonFormat(
False, True).check_format(f),
"%s does not comform to expected format!" % f)
| from __future__ import absolute_import
import fnmatch
import os
import unittest
from . import validate_json_format
class TestSettings(unittest.TestCase):
def _get_json_files(self, file_pattern, folder='.'):
for root, dirnames, filenames in os.walk(folder):
for filename in fnmatch.filter(filenames, file_pattern):
yield os.path.join(root, filename)
for dirname in [d for d in dirnames
if d not in ('.git', '.tox')]:
for f in self._get_json_files(
file_pattern, os.path.join(root, dirname)):
yield f
def test_json_settings(self):
"""Test each JSON file."""
file_patterns = (
'*.sublime-settings',
'*.sublime-commands',
'*.sublime-menu',
)
for file_pattern in file_patterns:
for f in self._get_json_files(file_pattern):
print(f)
self.assertFalse(
validate_json_format.CheckJsonFormat(
False, True).check_format(f),
"%s does not comform to expected format!" % f)
Add '*.json' file extensions to test pattern list.from __future__ import absolute_import
import fnmatch
import os
import unittest
from . import validate_json_format
class TestSettings(unittest.TestCase):
def _get_json_files(self, file_pattern, folder='.'):
for root, dirnames, filenames in os.walk(folder):
for filename in fnmatch.filter(filenames, file_pattern):
yield os.path.join(root, filename)
for dirname in [d for d in dirnames
if d not in ('.git', '.tox')]:
for f in self._get_json_files(
file_pattern, os.path.join(root, dirname)):
yield f
def test_json_settings(self):
"""Test each JSON file."""
file_patterns = (
'*.sublime-settings',
'*.sublime-commands',
'*.sublime-menu',
'*.json'
)
for file_pattern in file_patterns:
for f in self._get_json_files(file_pattern):
print(f)
self.assertFalse(
validate_json_format.CheckJsonFormat(
False, True).check_format(f),
"%s does not comform to expected format!" % f)
| <commit_before>from __future__ import absolute_import
import fnmatch
import os
import unittest
from . import validate_json_format
class TestSettings(unittest.TestCase):
def _get_json_files(self, file_pattern, folder='.'):
for root, dirnames, filenames in os.walk(folder):
for filename in fnmatch.filter(filenames, file_pattern):
yield os.path.join(root, filename)
for dirname in [d for d in dirnames
if d not in ('.git', '.tox')]:
for f in self._get_json_files(
file_pattern, os.path.join(root, dirname)):
yield f
def test_json_settings(self):
"""Test each JSON file."""
file_patterns = (
'*.sublime-settings',
'*.sublime-commands',
'*.sublime-menu',
)
for file_pattern in file_patterns:
for f in self._get_json_files(file_pattern):
print(f)
self.assertFalse(
validate_json_format.CheckJsonFormat(
False, True).check_format(f),
"%s does not comform to expected format!" % f)
<commit_msg>Add '*.json' file extensions to test pattern list.<commit_after>from __future__ import absolute_import
import fnmatch
import os
import unittest
from . import validate_json_format
class TestSettings(unittest.TestCase):
def _get_json_files(self, file_pattern, folder='.'):
for root, dirnames, filenames in os.walk(folder):
for filename in fnmatch.filter(filenames, file_pattern):
yield os.path.join(root, filename)
for dirname in [d for d in dirnames
if d not in ('.git', '.tox')]:
for f in self._get_json_files(
file_pattern, os.path.join(root, dirname)):
yield f
def test_json_settings(self):
"""Test each JSON file."""
file_patterns = (
'*.sublime-settings',
'*.sublime-commands',
'*.sublime-menu',
'*.json'
)
for file_pattern in file_patterns:
for f in self._get_json_files(file_pattern):
print(f)
self.assertFalse(
validate_json_format.CheckJsonFormat(
False, True).check_format(f),
"%s does not comform to expected format!" % f)
|
1e2edd3ff285e71feffac932592e08a483e002be | git_pre_commit_hook/builtin_plugins/flake8_check.py | git_pre_commit_hook/builtin_plugins/flake8_check.py | """Check files with flake8."""
import flake8.main
import re
DEFAULTS = {
'ignore': '',
'complexity': '10',
}
PYTHON_SHEBANG_REGEX = re.compile(r'''^#!.*python''')
def check(file_staged_for_commit, options):
if file_staged_for_commit.path.endswith('.py') or \
PYTHON_SHEBANG_REGEX.search(file_staged_for_commit.contents):
status = flake8.main.check_code(
file_staged_for_commit.contents,
ignore=(
c for c in options.flake8_ignore.split(',') if c
),
complexity=int(options.flake8_complexity),
)
return status == 0
else:
return True
| """Check files with flake8."""
import flake8.main
import re
DEFAULTS = {
'ignore': 'E226',
'complexity': '10',
}
PYTHON_SHEBANG_REGEX = re.compile(r'''^#!.*python''')
def check(file_staged_for_commit, options):
if file_staged_for_commit.path.endswith('.py') or \
PYTHON_SHEBANG_REGEX.search(file_staged_for_commit.contents):
status = flake8.main.check_code(
file_staged_for_commit.contents,
ignore=(
c for c in options.flake8_ignore.split(',') if c
),
complexity=int(options.flake8_complexity),
)
return status == 0
else:
return True
| Add E226 to default ignores for pep8 | Add E226 to default ignores for pep8
E226 - missing whitespace around arithmetic operator
2*3 + 5*6 must pass
| Python | mit | evvers/git-pre-commit-hook | """Check files with flake8."""
import flake8.main
import re
DEFAULTS = {
'ignore': '',
'complexity': '10',
}
PYTHON_SHEBANG_REGEX = re.compile(r'''^#!.*python''')
def check(file_staged_for_commit, options):
if file_staged_for_commit.path.endswith('.py') or \
PYTHON_SHEBANG_REGEX.search(file_staged_for_commit.contents):
status = flake8.main.check_code(
file_staged_for_commit.contents,
ignore=(
c for c in options.flake8_ignore.split(',') if c
),
complexity=int(options.flake8_complexity),
)
return status == 0
else:
return True
Add E226 to default ignores for pep8
E226 - missing whitespace around arithmetic operator
2*3 + 5*6 must pass | """Check files with flake8."""
import flake8.main
import re
DEFAULTS = {
'ignore': 'E226',
'complexity': '10',
}
PYTHON_SHEBANG_REGEX = re.compile(r'''^#!.*python''')
def check(file_staged_for_commit, options):
if file_staged_for_commit.path.endswith('.py') or \
PYTHON_SHEBANG_REGEX.search(file_staged_for_commit.contents):
status = flake8.main.check_code(
file_staged_for_commit.contents,
ignore=(
c for c in options.flake8_ignore.split(',') if c
),
complexity=int(options.flake8_complexity),
)
return status == 0
else:
return True
| <commit_before>"""Check files with flake8."""
import flake8.main
import re
DEFAULTS = {
'ignore': '',
'complexity': '10',
}
PYTHON_SHEBANG_REGEX = re.compile(r'''^#!.*python''')
def check(file_staged_for_commit, options):
if file_staged_for_commit.path.endswith('.py') or \
PYTHON_SHEBANG_REGEX.search(file_staged_for_commit.contents):
status = flake8.main.check_code(
file_staged_for_commit.contents,
ignore=(
c for c in options.flake8_ignore.split(',') if c
),
complexity=int(options.flake8_complexity),
)
return status == 0
else:
return True
<commit_msg>Add E226 to default ignores for pep8
E226 - missing whitespace around arithmetic operator
2*3 + 5*6 must pass<commit_after> | """Check files with flake8."""
import flake8.main
import re
DEFAULTS = {
'ignore': 'E226',
'complexity': '10',
}
PYTHON_SHEBANG_REGEX = re.compile(r'''^#!.*python''')
def check(file_staged_for_commit, options):
if file_staged_for_commit.path.endswith('.py') or \
PYTHON_SHEBANG_REGEX.search(file_staged_for_commit.contents):
status = flake8.main.check_code(
file_staged_for_commit.contents,
ignore=(
c for c in options.flake8_ignore.split(',') if c
),
complexity=int(options.flake8_complexity),
)
return status == 0
else:
return True
| """Check files with flake8."""
import flake8.main
import re
DEFAULTS = {
'ignore': '',
'complexity': '10',
}
PYTHON_SHEBANG_REGEX = re.compile(r'''^#!.*python''')
def check(file_staged_for_commit, options):
if file_staged_for_commit.path.endswith('.py') or \
PYTHON_SHEBANG_REGEX.search(file_staged_for_commit.contents):
status = flake8.main.check_code(
file_staged_for_commit.contents,
ignore=(
c for c in options.flake8_ignore.split(',') if c
),
complexity=int(options.flake8_complexity),
)
return status == 0
else:
return True
Add E226 to default ignores for pep8
E226 - missing whitespace around arithmetic operator
2*3 + 5*6 must pass"""Check files with flake8."""
import flake8.main
import re
DEFAULTS = {
'ignore': 'E226',
'complexity': '10',
}
PYTHON_SHEBANG_REGEX = re.compile(r'''^#!.*python''')
def check(file_staged_for_commit, options):
if file_staged_for_commit.path.endswith('.py') or \
PYTHON_SHEBANG_REGEX.search(file_staged_for_commit.contents):
status = flake8.main.check_code(
file_staged_for_commit.contents,
ignore=(
c for c in options.flake8_ignore.split(',') if c
),
complexity=int(options.flake8_complexity),
)
return status == 0
else:
return True
| <commit_before>"""Check files with flake8."""
import flake8.main
import re
DEFAULTS = {
'ignore': '',
'complexity': '10',
}
PYTHON_SHEBANG_REGEX = re.compile(r'''^#!.*python''')
def check(file_staged_for_commit, options):
if file_staged_for_commit.path.endswith('.py') or \
PYTHON_SHEBANG_REGEX.search(file_staged_for_commit.contents):
status = flake8.main.check_code(
file_staged_for_commit.contents,
ignore=(
c for c in options.flake8_ignore.split(',') if c
),
complexity=int(options.flake8_complexity),
)
return status == 0
else:
return True
<commit_msg>Add E226 to default ignores for pep8
E226 - missing whitespace around arithmetic operator
2*3 + 5*6 must pass<commit_after>"""Check files with flake8."""
import flake8.main
import re
DEFAULTS = {
'ignore': 'E226',
'complexity': '10',
}
PYTHON_SHEBANG_REGEX = re.compile(r'''^#!.*python''')
def check(file_staged_for_commit, options):
if file_staged_for_commit.path.endswith('.py') or \
PYTHON_SHEBANG_REGEX.search(file_staged_for_commit.contents):
status = flake8.main.check_code(
file_staged_for_commit.contents,
ignore=(
c for c in options.flake8_ignore.split(',') if c
),
complexity=int(options.flake8_complexity),
)
return status == 0
else:
return True
|
ff0bae24be1dfc800dd76940f95cc4580cdc7421 | rest-api/metrics_api.py | rest-api/metrics_api.py | """The API definition for the metrics API.
This defines the APIs and the handlers for the APIs.
"""
import api_util
import metrics
from protorpc import protojson
from flask import request
from flask.ext.restful import Resource
class MetricsApi(Resource):
@api_util.auth_required
def post(self):
resource = request.get_data()
metrics_request = protojson.decode_message(metrics.MetricsRequest, resource)
metrics_response = metrics.SERVICE.get_metrics(metrics_request)
return protojson.encode_message(metrics_response)
| """The API definition for the metrics API.
This defines the APIs and the handlers for the APIs.
"""
import api_util
import metrics
import json
from protorpc import protojson
from flask import request
from flask.ext.restful import Resource
class MetricsApi(Resource):
@api_util.auth_required
def post(self):
resource = request.get_data()
metrics_request = protojson.decode_message(metrics.MetricsRequest, resource)
metrics_response = metrics.SERVICE.get_metrics(metrics_request)
return json.loads(protojson.encode_message(metrics_response))
| Return a JSON payload, rather than stringified JSON | Return a JSON payload, rather than stringified JSON
| Python | bsd-3-clause | all-of-us/raw-data-repository,all-of-us/raw-data-repository,all-of-us/raw-data-repository | """The API definition for the metrics API.
This defines the APIs and the handlers for the APIs.
"""
import api_util
import metrics
from protorpc import protojson
from flask import request
from flask.ext.restful import Resource
class MetricsApi(Resource):
@api_util.auth_required
def post(self):
resource = request.get_data()
metrics_request = protojson.decode_message(metrics.MetricsRequest, resource)
metrics_response = metrics.SERVICE.get_metrics(metrics_request)
return protojson.encode_message(metrics_response)
Return a JSON payload, rather than stringified JSON | """The API definition for the metrics API.
This defines the APIs and the handlers for the APIs.
"""
import api_util
import metrics
import json
from protorpc import protojson
from flask import request
from flask.ext.restful import Resource
class MetricsApi(Resource):
@api_util.auth_required
def post(self):
resource = request.get_data()
metrics_request = protojson.decode_message(metrics.MetricsRequest, resource)
metrics_response = metrics.SERVICE.get_metrics(metrics_request)
return json.loads(protojson.encode_message(metrics_response))
| <commit_before>"""The API definition for the metrics API.
This defines the APIs and the handlers for the APIs.
"""
import api_util
import metrics
from protorpc import protojson
from flask import request
from flask.ext.restful import Resource
class MetricsApi(Resource):
@api_util.auth_required
def post(self):
resource = request.get_data()
metrics_request = protojson.decode_message(metrics.MetricsRequest, resource)
metrics_response = metrics.SERVICE.get_metrics(metrics_request)
return protojson.encode_message(metrics_response)
<commit_msg>Return a JSON payload, rather than stringified JSON<commit_after> | """The API definition for the metrics API.
This defines the APIs and the handlers for the APIs.
"""
import api_util
import metrics
import json
from protorpc import protojson
from flask import request
from flask.ext.restful import Resource
class MetricsApi(Resource):
@api_util.auth_required
def post(self):
resource = request.get_data()
metrics_request = protojson.decode_message(metrics.MetricsRequest, resource)
metrics_response = metrics.SERVICE.get_metrics(metrics_request)
return json.loads(protojson.encode_message(metrics_response))
| """The API definition for the metrics API.
This defines the APIs and the handlers for the APIs.
"""
import api_util
import metrics
from protorpc import protojson
from flask import request
from flask.ext.restful import Resource
class MetricsApi(Resource):
@api_util.auth_required
def post(self):
resource = request.get_data()
metrics_request = protojson.decode_message(metrics.MetricsRequest, resource)
metrics_response = metrics.SERVICE.get_metrics(metrics_request)
return protojson.encode_message(metrics_response)
Return a JSON payload, rather than stringified JSON"""The API definition for the metrics API.
This defines the APIs and the handlers for the APIs.
"""
import api_util
import metrics
import json
from protorpc import protojson
from flask import request
from flask.ext.restful import Resource
class MetricsApi(Resource):
@api_util.auth_required
def post(self):
resource = request.get_data()
metrics_request = protojson.decode_message(metrics.MetricsRequest, resource)
metrics_response = metrics.SERVICE.get_metrics(metrics_request)
return json.loads(protojson.encode_message(metrics_response))
| <commit_before>"""The API definition for the metrics API.
This defines the APIs and the handlers for the APIs.
"""
import api_util
import metrics
from protorpc import protojson
from flask import request
from flask.ext.restful import Resource
class MetricsApi(Resource):
@api_util.auth_required
def post(self):
resource = request.get_data()
metrics_request = protojson.decode_message(metrics.MetricsRequest, resource)
metrics_response = metrics.SERVICE.get_metrics(metrics_request)
return protojson.encode_message(metrics_response)
<commit_msg>Return a JSON payload, rather than stringified JSON<commit_after>"""The API definition for the metrics API.
This defines the APIs and the handlers for the APIs.
"""
import api_util
import metrics
import json
from protorpc import protojson
from flask import request
from flask.ext.restful import Resource
class MetricsApi(Resource):
@api_util.auth_required
def post(self):
resource = request.get_data()
metrics_request = protojson.decode_message(metrics.MetricsRequest, resource)
metrics_response = metrics.SERVICE.get_metrics(metrics_request)
return json.loads(protojson.encode_message(metrics_response))
|
066d776041b2cae4e0435935d7f9a05173e34563 | script/echo.py | script/echo.py | #!/usr/bin/env python3
# -*- coding: ascii -*-
import sys
import instabot
NICKNAME = 'Echo'
def post_cb(self, msg, meta):
if msg['text'].startswith('!echo '):
return msg['text'][6:]
def main():
parser = instabot.argparse(sys.argv[1:])
url, nickname = None, NICKNAME
for arg in parser:
if arg == '--help':
sys.stderr.write('USAGE: %s [--help] [--nick name] url\n' %
sys.argv[0])
sys.exit(0)
elif arg == '--nick':
nickname = parser.send('arg')
elif arg.startswith('-'):
parser.send('unknown')
elif url is not None:
parser.send('toomany')
else:
url = arg
if url is None: raise SystemExit('ERROR: Too few arguments')
bot = instabot.HookBot(url, nickname, post_cb=post_cb)
bot.run()
if __name__ == '__main__': main()
| #!/usr/bin/env python3
# -*- coding: ascii -*-
import sys
import instabot
NICKNAME = 'Echo'
def post_cb(self, msg, meta):
if msg['text'].startswith('!echo '):
return msg['text'][6:]
def main():
parser = instabot.argparse(sys.argv[1:])
url, nickname = None, NICKNAME
for arg in parser:
if arg == '--help':
sys.stderr.write('USAGE: %s [--help] [--nick name] url\n' %
sys.argv[0])
sys.exit(0)
elif arg == '--nick':
nickname = parser.send('arg')
elif arg.startswith('-'):
parser.send('unknown')
elif url is not None:
parser.send('toomany')
else:
url = arg
if url is None: raise SystemExit('ERROR: Too few arguments')
bot = instabot.HookBot(url, nickname, post_cb=post_cb)
try:
bot.run()
except KeyboardInterrupt:
sys.stderr.write('\n')
finally:
bot.close()
if __name__ == '__main__': main()
| Make example bot react to SIGINT better | [Instabot] Make example bot react to SIGINT better
| Python | mit | CylonicRaider/Instant,CylonicRaider/Instant,CylonicRaider/Instant,CylonicRaider/Instant,CylonicRaider/Instant | #!/usr/bin/env python3
# -*- coding: ascii -*-
import sys
import instabot
NICKNAME = 'Echo'
def post_cb(self, msg, meta):
if msg['text'].startswith('!echo '):
return msg['text'][6:]
def main():
parser = instabot.argparse(sys.argv[1:])
url, nickname = None, NICKNAME
for arg in parser:
if arg == '--help':
sys.stderr.write('USAGE: %s [--help] [--nick name] url\n' %
sys.argv[0])
sys.exit(0)
elif arg == '--nick':
nickname = parser.send('arg')
elif arg.startswith('-'):
parser.send('unknown')
elif url is not None:
parser.send('toomany')
else:
url = arg
if url is None: raise SystemExit('ERROR: Too few arguments')
bot = instabot.HookBot(url, nickname, post_cb=post_cb)
bot.run()
if __name__ == '__main__': main()
[Instabot] Make example bot react to SIGINT better | #!/usr/bin/env python3
# -*- coding: ascii -*-
import sys
import instabot
NICKNAME = 'Echo'
def post_cb(self, msg, meta):
if msg['text'].startswith('!echo '):
return msg['text'][6:]
def main():
parser = instabot.argparse(sys.argv[1:])
url, nickname = None, NICKNAME
for arg in parser:
if arg == '--help':
sys.stderr.write('USAGE: %s [--help] [--nick name] url\n' %
sys.argv[0])
sys.exit(0)
elif arg == '--nick':
nickname = parser.send('arg')
elif arg.startswith('-'):
parser.send('unknown')
elif url is not None:
parser.send('toomany')
else:
url = arg
if url is None: raise SystemExit('ERROR: Too few arguments')
bot = instabot.HookBot(url, nickname, post_cb=post_cb)
try:
bot.run()
except KeyboardInterrupt:
sys.stderr.write('\n')
finally:
bot.close()
if __name__ == '__main__': main()
| <commit_before>#!/usr/bin/env python3
# -*- coding: ascii -*-
import sys
import instabot
NICKNAME = 'Echo'
def post_cb(self, msg, meta):
if msg['text'].startswith('!echo '):
return msg['text'][6:]
def main():
parser = instabot.argparse(sys.argv[1:])
url, nickname = None, NICKNAME
for arg in parser:
if arg == '--help':
sys.stderr.write('USAGE: %s [--help] [--nick name] url\n' %
sys.argv[0])
sys.exit(0)
elif arg == '--nick':
nickname = parser.send('arg')
elif arg.startswith('-'):
parser.send('unknown')
elif url is not None:
parser.send('toomany')
else:
url = arg
if url is None: raise SystemExit('ERROR: Too few arguments')
bot = instabot.HookBot(url, nickname, post_cb=post_cb)
bot.run()
if __name__ == '__main__': main()
<commit_msg>[Instabot] Make example bot react to SIGINT better<commit_after> | #!/usr/bin/env python3
# -*- coding: ascii -*-
import sys
import instabot
NICKNAME = 'Echo'
def post_cb(self, msg, meta):
if msg['text'].startswith('!echo '):
return msg['text'][6:]
def main():
parser = instabot.argparse(sys.argv[1:])
url, nickname = None, NICKNAME
for arg in parser:
if arg == '--help':
sys.stderr.write('USAGE: %s [--help] [--nick name] url\n' %
sys.argv[0])
sys.exit(0)
elif arg == '--nick':
nickname = parser.send('arg')
elif arg.startswith('-'):
parser.send('unknown')
elif url is not None:
parser.send('toomany')
else:
url = arg
if url is None: raise SystemExit('ERROR: Too few arguments')
bot = instabot.HookBot(url, nickname, post_cb=post_cb)
try:
bot.run()
except KeyboardInterrupt:
sys.stderr.write('\n')
finally:
bot.close()
if __name__ == '__main__': main()
| #!/usr/bin/env python3
# -*- coding: ascii -*-
import sys
import instabot
NICKNAME = 'Echo'
def post_cb(self, msg, meta):
if msg['text'].startswith('!echo '):
return msg['text'][6:]
def main():
parser = instabot.argparse(sys.argv[1:])
url, nickname = None, NICKNAME
for arg in parser:
if arg == '--help':
sys.stderr.write('USAGE: %s [--help] [--nick name] url\n' %
sys.argv[0])
sys.exit(0)
elif arg == '--nick':
nickname = parser.send('arg')
elif arg.startswith('-'):
parser.send('unknown')
elif url is not None:
parser.send('toomany')
else:
url = arg
if url is None: raise SystemExit('ERROR: Too few arguments')
bot = instabot.HookBot(url, nickname, post_cb=post_cb)
bot.run()
if __name__ == '__main__': main()
[Instabot] Make example bot react to SIGINT better#!/usr/bin/env python3
# -*- coding: ascii -*-
import sys
import instabot
NICKNAME = 'Echo'
def post_cb(self, msg, meta):
if msg['text'].startswith('!echo '):
return msg['text'][6:]
def main():
parser = instabot.argparse(sys.argv[1:])
url, nickname = None, NICKNAME
for arg in parser:
if arg == '--help':
sys.stderr.write('USAGE: %s [--help] [--nick name] url\n' %
sys.argv[0])
sys.exit(0)
elif arg == '--nick':
nickname = parser.send('arg')
elif arg.startswith('-'):
parser.send('unknown')
elif url is not None:
parser.send('toomany')
else:
url = arg
if url is None: raise SystemExit('ERROR: Too few arguments')
bot = instabot.HookBot(url, nickname, post_cb=post_cb)
try:
bot.run()
except KeyboardInterrupt:
sys.stderr.write('\n')
finally:
bot.close()
if __name__ == '__main__': main()
| <commit_before>#!/usr/bin/env python3
# -*- coding: ascii -*-
import sys
import instabot
NICKNAME = 'Echo'
def post_cb(self, msg, meta):
if msg['text'].startswith('!echo '):
return msg['text'][6:]
def main():
parser = instabot.argparse(sys.argv[1:])
url, nickname = None, NICKNAME
for arg in parser:
if arg == '--help':
sys.stderr.write('USAGE: %s [--help] [--nick name] url\n' %
sys.argv[0])
sys.exit(0)
elif arg == '--nick':
nickname = parser.send('arg')
elif arg.startswith('-'):
parser.send('unknown')
elif url is not None:
parser.send('toomany')
else:
url = arg
if url is None: raise SystemExit('ERROR: Too few arguments')
bot = instabot.HookBot(url, nickname, post_cb=post_cb)
bot.run()
if __name__ == '__main__': main()
<commit_msg>[Instabot] Make example bot react to SIGINT better<commit_after>#!/usr/bin/env python3
# -*- coding: ascii -*-
import sys
import instabot
NICKNAME = 'Echo'
def post_cb(self, msg, meta):
if msg['text'].startswith('!echo '):
return msg['text'][6:]
def main():
parser = instabot.argparse(sys.argv[1:])
url, nickname = None, NICKNAME
for arg in parser:
if arg == '--help':
sys.stderr.write('USAGE: %s [--help] [--nick name] url\n' %
sys.argv[0])
sys.exit(0)
elif arg == '--nick':
nickname = parser.send('arg')
elif arg.startswith('-'):
parser.send('unknown')
elif url is not None:
parser.send('toomany')
else:
url = arg
if url is None: raise SystemExit('ERROR: Too few arguments')
bot = instabot.HookBot(url, nickname, post_cb=post_cb)
try:
bot.run()
except KeyboardInterrupt:
sys.stderr.write('\n')
finally:
bot.close()
if __name__ == '__main__': main()
|
dbba9e403538fb3bfd29763b8741e07dad3db1b1 | src/main/python/cfn_sphere/resolver/file.py | src/main/python/cfn_sphere/resolver/file.py |
class FileResolver(object):
def read(self, path):
with open(path, 'r') as file:
return file.read()
|
class FileResolver(object):
def read(self, path):
try:
with open(path, 'r') as f:
return f.read()
except IOError as e:
raise CfnSphereException("Cannot read file " + path, e)
| Throw CfnSphereException on IOErrors. Fix landmark issue. | Throw CfnSphereException on IOErrors. Fix landmark issue.
| Python | apache-2.0 | cfn-sphere/cfn-sphere,cfn-sphere/cfn-sphere,ImmobilienScout24/cfn-sphere,cfn-sphere/cfn-sphere,marco-hoyer/cfn-sphere |
class FileResolver(object):
def read(self, path):
with open(path, 'r') as file:
return file.read()
Throw CfnSphereException on IOErrors. Fix landmark issue. |
class FileResolver(object):
def read(self, path):
try:
with open(path, 'r') as f:
return f.read()
except IOError as e:
raise CfnSphereException("Cannot read file " + path, e)
| <commit_before>
class FileResolver(object):
def read(self, path):
with open(path, 'r') as file:
return file.read()
<commit_msg>Throw CfnSphereException on IOErrors. Fix landmark issue.<commit_after> |
class FileResolver(object):
def read(self, path):
try:
with open(path, 'r') as f:
return f.read()
except IOError as e:
raise CfnSphereException("Cannot read file " + path, e)
|
class FileResolver(object):
def read(self, path):
with open(path, 'r') as file:
return file.read()
Throw CfnSphereException on IOErrors. Fix landmark issue.
class FileResolver(object):
def read(self, path):
try:
with open(path, 'r') as f:
return f.read()
except IOError as e:
raise CfnSphereException("Cannot read file " + path, e)
| <commit_before>
class FileResolver(object):
def read(self, path):
with open(path, 'r') as file:
return file.read()
<commit_msg>Throw CfnSphereException on IOErrors. Fix landmark issue.<commit_after>
class FileResolver(object):
def read(self, path):
try:
with open(path, 'r') as f:
return f.read()
except IOError as e:
raise CfnSphereException("Cannot read file " + path, e)
|
9c3d24083be5969ca84c1625dbc0d368acdc51f8 | tg/tests/test_util.py | tg/tests/test_util.py | import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
# These tests aren't reliable if the package in question has
# entry points.
def test_get_package_name():
eq_(get_package_name(), 'tg')
def test_get_project_name():
eq_(get_project_name(), 'TurboGears2')
def test_get_project_meta():
eq_(get_project_meta('requires.txt'), os.path.join('TurboGears2.egg-info', 'requires.txt'))
def test_get_model():
eq_(get_model(), None) | import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
def test_get_partial_dict():
eq_(get_partial_dict('prefix', {'prefix.xyz':1, 'prefix.zyx':2, 'xy':3}),
{'xyz':1,'zyx':2})
# These tests aren't reliable if the package in question has
# entry points.
def test_get_package_name():
eq_(get_package_name(), 'tg')
def test_get_project_name():
eq_(get_project_name(), 'TurboGears2')
def test_get_project_meta():
eq_(get_project_meta('requires.txt'), os.path.join('TurboGears2.egg-info', 'requires.txt'))
def test_get_model():
eq_(get_model(), None)
| Add a test_get_partial_dict unit test, which currently fails | Add a test_get_partial_dict unit test, which currently fails
| Python | mit | lucius-feng/tg2,lucius-feng/tg2 | import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
# These tests aren't reliable if the package in question has
# entry points.
def test_get_package_name():
eq_(get_package_name(), 'tg')
def test_get_project_name():
eq_(get_project_name(), 'TurboGears2')
def test_get_project_meta():
eq_(get_project_meta('requires.txt'), os.path.join('TurboGears2.egg-info', 'requires.txt'))
def test_get_model():
eq_(get_model(), None)Add a test_get_partial_dict unit test, which currently fails | import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
def test_get_partial_dict():
eq_(get_partial_dict('prefix', {'prefix.xyz':1, 'prefix.zyx':2, 'xy':3}),
{'xyz':1,'zyx':2})
# These tests aren't reliable if the package in question has
# entry points.
def test_get_package_name():
eq_(get_package_name(), 'tg')
def test_get_project_name():
eq_(get_project_name(), 'TurboGears2')
def test_get_project_meta():
eq_(get_project_meta('requires.txt'), os.path.join('TurboGears2.egg-info', 'requires.txt'))
def test_get_model():
eq_(get_model(), None)
| <commit_before>import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
# These tests aren't reliable if the package in question has
# entry points.
def test_get_package_name():
eq_(get_package_name(), 'tg')
def test_get_project_name():
eq_(get_project_name(), 'TurboGears2')
def test_get_project_meta():
eq_(get_project_meta('requires.txt'), os.path.join('TurboGears2.egg-info', 'requires.txt'))
def test_get_model():
eq_(get_model(), None)<commit_msg>Add a test_get_partial_dict unit test, which currently fails<commit_after> | import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
def test_get_partial_dict():
eq_(get_partial_dict('prefix', {'prefix.xyz':1, 'prefix.zyx':2, 'xy':3}),
{'xyz':1,'zyx':2})
# These tests aren't reliable if the package in question has
# entry points.
def test_get_package_name():
eq_(get_package_name(), 'tg')
def test_get_project_name():
eq_(get_project_name(), 'TurboGears2')
def test_get_project_meta():
eq_(get_project_meta('requires.txt'), os.path.join('TurboGears2.egg-info', 'requires.txt'))
def test_get_model():
eq_(get_model(), None)
| import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
# These tests aren't reliable if the package in question has
# entry points.
def test_get_package_name():
eq_(get_package_name(), 'tg')
def test_get_project_name():
eq_(get_project_name(), 'TurboGears2')
def test_get_project_meta():
eq_(get_project_meta('requires.txt'), os.path.join('TurboGears2.egg-info', 'requires.txt'))
def test_get_model():
eq_(get_model(), None)Add a test_get_partial_dict unit test, which currently failsimport tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
def test_get_partial_dict():
eq_(get_partial_dict('prefix', {'prefix.xyz':1, 'prefix.zyx':2, 'xy':3}),
{'xyz':1,'zyx':2})
# These tests aren't reliable if the package in question has
# entry points.
def test_get_package_name():
eq_(get_package_name(), 'tg')
def test_get_project_name():
eq_(get_project_name(), 'TurboGears2')
def test_get_project_meta():
eq_(get_project_meta('requires.txt'), os.path.join('TurboGears2.egg-info', 'requires.txt'))
def test_get_model():
eq_(get_model(), None)
| <commit_before>import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
# These tests aren't reliable if the package in question has
# entry points.
def test_get_package_name():
eq_(get_package_name(), 'tg')
def test_get_project_name():
eq_(get_project_name(), 'TurboGears2')
def test_get_project_meta():
eq_(get_project_meta('requires.txt'), os.path.join('TurboGears2.egg-info', 'requires.txt'))
def test_get_model():
eq_(get_model(), None)<commit_msg>Add a test_get_partial_dict unit test, which currently fails<commit_after>import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
def test_get_partial_dict():
eq_(get_partial_dict('prefix', {'prefix.xyz':1, 'prefix.zyx':2, 'xy':3}),
{'xyz':1,'zyx':2})
# These tests aren't reliable if the package in question has
# entry points.
def test_get_package_name():
eq_(get_package_name(), 'tg')
def test_get_project_name():
eq_(get_project_name(), 'TurboGears2')
def test_get_project_meta():
eq_(get_project_meta('requires.txt'), os.path.join('TurboGears2.egg-info', 'requires.txt'))
def test_get_model():
eq_(get_model(), None)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.