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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c827ba1ec1846847e44416c6ec5a74418558657c | soundmeter/settings.py | soundmeter/settings.py | # Default settings
import ConfigParser
import os
import pyaudio
PROG = 'soundmeter'
USER_DIR = os.path.join(os.path.expanduser('~'), '.' + PROG)
USER_LOGFILE = os.path.join(USER_DIR, 'log')
USER_CONFIG = os.path.join(USER_DIR, 'config')
USER_SCRIPT = os.path.join(USER_DIR, 'trigger.sh')
config = ConfigParser.ConfigParser()
config.read(os.environ.get('SOUNDMETER_TEST_CONFIG') or USER_CONFIG)
items = {}
if config.has_section(PROG):
items = dict(config.items(PROG))
for name in items:
try:
if name in ['frames_per_buffer', 'format', 'channels', 'rate']:
items[name] = int(items[name])
if name in ['audio_segment_length']:
items[name] = float(items[name])
except:
items[name] = None
FRAMES_PER_BUFFER = items.get('frames_per_buffer') or 2048
FORMAT = items.get('format') or pyaudio.paInt16
CHANNELS = items.get('channels') or 2
RATE = items.get('rate') or 44100
AUDIO_SEGMENT_LENGTH = items.get('audio_segment_length') or 0.5
| # Default settings
import ConfigParser
import os
import pyaudio
PROG = 'soundmeter'
USER_DIR = os.path.join(os.path.expanduser('~'), '.' + PROG)
USER_LOGFILE = os.path.join(USER_DIR, 'log')
USER_CONFIG = os.path.join(USER_DIR, 'config')
USER_SCRIPT = os.path.join(USER_DIR, 'trigger.sh')
config = ConfigParser.ConfigParser()
config.read(os.environ.get('SOUNDMETER_TEST_CONFIG') or USER_CONFIG)
items = {}
if config.has_section(PROG):
items = dict(config.items(PROG))
for name in items:
try:
if name in ['frames_per_buffer', 'format', 'channels', 'rate']:
items[name] = int(items[name])
elif name in ['audio_segment_length']:
items[name] = float(items[name])
else:
raise Exception('Unknown name "%s" in config' % name)
except ValueError:
raise Exception('Invalid value to "%s" in config' % name)
FRAMES_PER_BUFFER = items.get('frames_per_buffer') or 2048
FORMAT = items.get('format') or pyaudio.paInt16
CHANNELS = items.get('channels') or 2
RATE = items.get('rate') or 44100
AUDIO_SEGMENT_LENGTH = items.get('audio_segment_length') or 0.5
| Modify exception handling to local config names | Modify exception handling to local config names
| Python | bsd-2-clause | shichao-an/soundmeter | # Default settings
import ConfigParser
import os
import pyaudio
PROG = 'soundmeter'
USER_DIR = os.path.join(os.path.expanduser('~'), '.' + PROG)
USER_LOGFILE = os.path.join(USER_DIR, 'log')
USER_CONFIG = os.path.join(USER_DIR, 'config')
USER_SCRIPT = os.path.join(USER_DIR, 'trigger.sh')
config = ConfigParser.ConfigParser()
config.read(os.environ.get('SOUNDMETER_TEST_CONFIG') or USER_CONFIG)
items = {}
if config.has_section(PROG):
items = dict(config.items(PROG))
for name in items:
try:
if name in ['frames_per_buffer', 'format', 'channels', 'rate']:
items[name] = int(items[name])
if name in ['audio_segment_length']:
items[name] = float(items[name])
except:
items[name] = None
FRAMES_PER_BUFFER = items.get('frames_per_buffer') or 2048
FORMAT = items.get('format') or pyaudio.paInt16
CHANNELS = items.get('channels') or 2
RATE = items.get('rate') or 44100
AUDIO_SEGMENT_LENGTH = items.get('audio_segment_length') or 0.5
Modify exception handling to local config names | # Default settings
import ConfigParser
import os
import pyaudio
PROG = 'soundmeter'
USER_DIR = os.path.join(os.path.expanduser('~'), '.' + PROG)
USER_LOGFILE = os.path.join(USER_DIR, 'log')
USER_CONFIG = os.path.join(USER_DIR, 'config')
USER_SCRIPT = os.path.join(USER_DIR, 'trigger.sh')
config = ConfigParser.ConfigParser()
config.read(os.environ.get('SOUNDMETER_TEST_CONFIG') or USER_CONFIG)
items = {}
if config.has_section(PROG):
items = dict(config.items(PROG))
for name in items:
try:
if name in ['frames_per_buffer', 'format', 'channels', 'rate']:
items[name] = int(items[name])
elif name in ['audio_segment_length']:
items[name] = float(items[name])
else:
raise Exception('Unknown name "%s" in config' % name)
except ValueError:
raise Exception('Invalid value to "%s" in config' % name)
FRAMES_PER_BUFFER = items.get('frames_per_buffer') or 2048
FORMAT = items.get('format') or pyaudio.paInt16
CHANNELS = items.get('channels') or 2
RATE = items.get('rate') or 44100
AUDIO_SEGMENT_LENGTH = items.get('audio_segment_length') or 0.5
| <commit_before># Default settings
import ConfigParser
import os
import pyaudio
PROG = 'soundmeter'
USER_DIR = os.path.join(os.path.expanduser('~'), '.' + PROG)
USER_LOGFILE = os.path.join(USER_DIR, 'log')
USER_CONFIG = os.path.join(USER_DIR, 'config')
USER_SCRIPT = os.path.join(USER_DIR, 'trigger.sh')
config = ConfigParser.ConfigParser()
config.read(os.environ.get('SOUNDMETER_TEST_CONFIG') or USER_CONFIG)
items = {}
if config.has_section(PROG):
items = dict(config.items(PROG))
for name in items:
try:
if name in ['frames_per_buffer', 'format', 'channels', 'rate']:
items[name] = int(items[name])
if name in ['audio_segment_length']:
items[name] = float(items[name])
except:
items[name] = None
FRAMES_PER_BUFFER = items.get('frames_per_buffer') or 2048
FORMAT = items.get('format') or pyaudio.paInt16
CHANNELS = items.get('channels') or 2
RATE = items.get('rate') or 44100
AUDIO_SEGMENT_LENGTH = items.get('audio_segment_length') or 0.5
<commit_msg>Modify exception handling to local config names<commit_after> | # Default settings
import ConfigParser
import os
import pyaudio
PROG = 'soundmeter'
USER_DIR = os.path.join(os.path.expanduser('~'), '.' + PROG)
USER_LOGFILE = os.path.join(USER_DIR, 'log')
USER_CONFIG = os.path.join(USER_DIR, 'config')
USER_SCRIPT = os.path.join(USER_DIR, 'trigger.sh')
config = ConfigParser.ConfigParser()
config.read(os.environ.get('SOUNDMETER_TEST_CONFIG') or USER_CONFIG)
items = {}
if config.has_section(PROG):
items = dict(config.items(PROG))
for name in items:
try:
if name in ['frames_per_buffer', 'format', 'channels', 'rate']:
items[name] = int(items[name])
elif name in ['audio_segment_length']:
items[name] = float(items[name])
else:
raise Exception('Unknown name "%s" in config' % name)
except ValueError:
raise Exception('Invalid value to "%s" in config' % name)
FRAMES_PER_BUFFER = items.get('frames_per_buffer') or 2048
FORMAT = items.get('format') or pyaudio.paInt16
CHANNELS = items.get('channels') or 2
RATE = items.get('rate') or 44100
AUDIO_SEGMENT_LENGTH = items.get('audio_segment_length') or 0.5
| # Default settings
import ConfigParser
import os
import pyaudio
PROG = 'soundmeter'
USER_DIR = os.path.join(os.path.expanduser('~'), '.' + PROG)
USER_LOGFILE = os.path.join(USER_DIR, 'log')
USER_CONFIG = os.path.join(USER_DIR, 'config')
USER_SCRIPT = os.path.join(USER_DIR, 'trigger.sh')
config = ConfigParser.ConfigParser()
config.read(os.environ.get('SOUNDMETER_TEST_CONFIG') or USER_CONFIG)
items = {}
if config.has_section(PROG):
items = dict(config.items(PROG))
for name in items:
try:
if name in ['frames_per_buffer', 'format', 'channels', 'rate']:
items[name] = int(items[name])
if name in ['audio_segment_length']:
items[name] = float(items[name])
except:
items[name] = None
FRAMES_PER_BUFFER = items.get('frames_per_buffer') or 2048
FORMAT = items.get('format') or pyaudio.paInt16
CHANNELS = items.get('channels') or 2
RATE = items.get('rate') or 44100
AUDIO_SEGMENT_LENGTH = items.get('audio_segment_length') or 0.5
Modify exception handling to local config names# Default settings
import ConfigParser
import os
import pyaudio
PROG = 'soundmeter'
USER_DIR = os.path.join(os.path.expanduser('~'), '.' + PROG)
USER_LOGFILE = os.path.join(USER_DIR, 'log')
USER_CONFIG = os.path.join(USER_DIR, 'config')
USER_SCRIPT = os.path.join(USER_DIR, 'trigger.sh')
config = ConfigParser.ConfigParser()
config.read(os.environ.get('SOUNDMETER_TEST_CONFIG') or USER_CONFIG)
items = {}
if config.has_section(PROG):
items = dict(config.items(PROG))
for name in items:
try:
if name in ['frames_per_buffer', 'format', 'channels', 'rate']:
items[name] = int(items[name])
elif name in ['audio_segment_length']:
items[name] = float(items[name])
else:
raise Exception('Unknown name "%s" in config' % name)
except ValueError:
raise Exception('Invalid value to "%s" in config' % name)
FRAMES_PER_BUFFER = items.get('frames_per_buffer') or 2048
FORMAT = items.get('format') or pyaudio.paInt16
CHANNELS = items.get('channels') or 2
RATE = items.get('rate') or 44100
AUDIO_SEGMENT_LENGTH = items.get('audio_segment_length') or 0.5
| <commit_before># Default settings
import ConfigParser
import os
import pyaudio
PROG = 'soundmeter'
USER_DIR = os.path.join(os.path.expanduser('~'), '.' + PROG)
USER_LOGFILE = os.path.join(USER_DIR, 'log')
USER_CONFIG = os.path.join(USER_DIR, 'config')
USER_SCRIPT = os.path.join(USER_DIR, 'trigger.sh')
config = ConfigParser.ConfigParser()
config.read(os.environ.get('SOUNDMETER_TEST_CONFIG') or USER_CONFIG)
items = {}
if config.has_section(PROG):
items = dict(config.items(PROG))
for name in items:
try:
if name in ['frames_per_buffer', 'format', 'channels', 'rate']:
items[name] = int(items[name])
if name in ['audio_segment_length']:
items[name] = float(items[name])
except:
items[name] = None
FRAMES_PER_BUFFER = items.get('frames_per_buffer') or 2048
FORMAT = items.get('format') or pyaudio.paInt16
CHANNELS = items.get('channels') or 2
RATE = items.get('rate') or 44100
AUDIO_SEGMENT_LENGTH = items.get('audio_segment_length') or 0.5
<commit_msg>Modify exception handling to local config names<commit_after># Default settings
import ConfigParser
import os
import pyaudio
PROG = 'soundmeter'
USER_DIR = os.path.join(os.path.expanduser('~'), '.' + PROG)
USER_LOGFILE = os.path.join(USER_DIR, 'log')
USER_CONFIG = os.path.join(USER_DIR, 'config')
USER_SCRIPT = os.path.join(USER_DIR, 'trigger.sh')
config = ConfigParser.ConfigParser()
config.read(os.environ.get('SOUNDMETER_TEST_CONFIG') or USER_CONFIG)
items = {}
if config.has_section(PROG):
items = dict(config.items(PROG))
for name in items:
try:
if name in ['frames_per_buffer', 'format', 'channels', 'rate']:
items[name] = int(items[name])
elif name in ['audio_segment_length']:
items[name] = float(items[name])
else:
raise Exception('Unknown name "%s" in config' % name)
except ValueError:
raise Exception('Invalid value to "%s" in config' % name)
FRAMES_PER_BUFFER = items.get('frames_per_buffer') or 2048
FORMAT = items.get('format') or pyaudio.paInt16
CHANNELS = items.get('channels') or 2
RATE = items.get('rate') or 44100
AUDIO_SEGMENT_LENGTH = items.get('audio_segment_length') or 0.5
|
e9aef2b63b1a6036703aa73bc0a6c30bb9425eb6 | io_helpers.py | io_helpers.py | import subprocess
def speak(say_wa):
echo_string = "'{0}'".format(say_wa.replace("'", "'\''"))
echo = subprocess.Popen(['echo', echo_string], stdout=subprocess.PIPE)
espeak = subprocess.Popen(["espeak", "-v", "english", "--stdout"],
stdin=echo.stdout, stdout=subprocess.PIPE)
echo.stdout.close()
subprocess.Popen(['aplay'], stdin=espeak.stdout)
espeak.stdout.close()
| import subprocess
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
class Button(object):
def __init__(self, button_gpio, callback):
self._button_gpio = button_gpio
self._callback = callback
GPIO.setup(self._button_gpio, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def is_pressed(self):
return not GPIO.input(self._button_gpio)
def listen(self):
if self.is_pressed():
self._callback()
class LED(object):
def __init__(self, led_gpio):
self._led_gpio = led_gpio
GPIO.setup(self._led_gpio, GPIO.OUT)
self.off() # start with it off
def on(self):
GPIO.output(self._led_gpio, True)
def off(self):
GPIO.output(self._led_gpio, False)
def speak(say_wa):
echo_string = "'{0}'".format(say_wa.replace("'", "'\''"))
echo = subprocess.Popen(['echo', echo_string], stdout=subprocess.PIPE)
espeak = subprocess.Popen(["espeak", "-v", "english", "--stdout"],
stdin=echo.stdout, stdout=subprocess.PIPE)
echo.stdout.close()
subprocess.Popen(['aplay'], stdin=espeak.stdout)
espeak.stdout.close()
| Add LED and Button classes | Add LED and Button classes
| Python | mit | jessstringham/raspberrypi | import subprocess
def speak(say_wa):
echo_string = "'{0}'".format(say_wa.replace("'", "'\''"))
echo = subprocess.Popen(['echo', echo_string], stdout=subprocess.PIPE)
espeak = subprocess.Popen(["espeak", "-v", "english", "--stdout"],
stdin=echo.stdout, stdout=subprocess.PIPE)
echo.stdout.close()
subprocess.Popen(['aplay'], stdin=espeak.stdout)
espeak.stdout.close()
Add LED and Button classes | import subprocess
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
class Button(object):
def __init__(self, button_gpio, callback):
self._button_gpio = button_gpio
self._callback = callback
GPIO.setup(self._button_gpio, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def is_pressed(self):
return not GPIO.input(self._button_gpio)
def listen(self):
if self.is_pressed():
self._callback()
class LED(object):
def __init__(self, led_gpio):
self._led_gpio = led_gpio
GPIO.setup(self._led_gpio, GPIO.OUT)
self.off() # start with it off
def on(self):
GPIO.output(self._led_gpio, True)
def off(self):
GPIO.output(self._led_gpio, False)
def speak(say_wa):
echo_string = "'{0}'".format(say_wa.replace("'", "'\''"))
echo = subprocess.Popen(['echo', echo_string], stdout=subprocess.PIPE)
espeak = subprocess.Popen(["espeak", "-v", "english", "--stdout"],
stdin=echo.stdout, stdout=subprocess.PIPE)
echo.stdout.close()
subprocess.Popen(['aplay'], stdin=espeak.stdout)
espeak.stdout.close()
| <commit_before>import subprocess
def speak(say_wa):
echo_string = "'{0}'".format(say_wa.replace("'", "'\''"))
echo = subprocess.Popen(['echo', echo_string], stdout=subprocess.PIPE)
espeak = subprocess.Popen(["espeak", "-v", "english", "--stdout"],
stdin=echo.stdout, stdout=subprocess.PIPE)
echo.stdout.close()
subprocess.Popen(['aplay'], stdin=espeak.stdout)
espeak.stdout.close()
<commit_msg>Add LED and Button classes<commit_after> | import subprocess
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
class Button(object):
def __init__(self, button_gpio, callback):
self._button_gpio = button_gpio
self._callback = callback
GPIO.setup(self._button_gpio, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def is_pressed(self):
return not GPIO.input(self._button_gpio)
def listen(self):
if self.is_pressed():
self._callback()
class LED(object):
def __init__(self, led_gpio):
self._led_gpio = led_gpio
GPIO.setup(self._led_gpio, GPIO.OUT)
self.off() # start with it off
def on(self):
GPIO.output(self._led_gpio, True)
def off(self):
GPIO.output(self._led_gpio, False)
def speak(say_wa):
echo_string = "'{0}'".format(say_wa.replace("'", "'\''"))
echo = subprocess.Popen(['echo', echo_string], stdout=subprocess.PIPE)
espeak = subprocess.Popen(["espeak", "-v", "english", "--stdout"],
stdin=echo.stdout, stdout=subprocess.PIPE)
echo.stdout.close()
subprocess.Popen(['aplay'], stdin=espeak.stdout)
espeak.stdout.close()
| import subprocess
def speak(say_wa):
echo_string = "'{0}'".format(say_wa.replace("'", "'\''"))
echo = subprocess.Popen(['echo', echo_string], stdout=subprocess.PIPE)
espeak = subprocess.Popen(["espeak", "-v", "english", "--stdout"],
stdin=echo.stdout, stdout=subprocess.PIPE)
echo.stdout.close()
subprocess.Popen(['aplay'], stdin=espeak.stdout)
espeak.stdout.close()
Add LED and Button classesimport subprocess
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
class Button(object):
def __init__(self, button_gpio, callback):
self._button_gpio = button_gpio
self._callback = callback
GPIO.setup(self._button_gpio, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def is_pressed(self):
return not GPIO.input(self._button_gpio)
def listen(self):
if self.is_pressed():
self._callback()
class LED(object):
def __init__(self, led_gpio):
self._led_gpio = led_gpio
GPIO.setup(self._led_gpio, GPIO.OUT)
self.off() # start with it off
def on(self):
GPIO.output(self._led_gpio, True)
def off(self):
GPIO.output(self._led_gpio, False)
def speak(say_wa):
echo_string = "'{0}'".format(say_wa.replace("'", "'\''"))
echo = subprocess.Popen(['echo', echo_string], stdout=subprocess.PIPE)
espeak = subprocess.Popen(["espeak", "-v", "english", "--stdout"],
stdin=echo.stdout, stdout=subprocess.PIPE)
echo.stdout.close()
subprocess.Popen(['aplay'], stdin=espeak.stdout)
espeak.stdout.close()
| <commit_before>import subprocess
def speak(say_wa):
echo_string = "'{0}'".format(say_wa.replace("'", "'\''"))
echo = subprocess.Popen(['echo', echo_string], stdout=subprocess.PIPE)
espeak = subprocess.Popen(["espeak", "-v", "english", "--stdout"],
stdin=echo.stdout, stdout=subprocess.PIPE)
echo.stdout.close()
subprocess.Popen(['aplay'], stdin=espeak.stdout)
espeak.stdout.close()
<commit_msg>Add LED and Button classes<commit_after>import subprocess
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
class Button(object):
def __init__(self, button_gpio, callback):
self._button_gpio = button_gpio
self._callback = callback
GPIO.setup(self._button_gpio, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def is_pressed(self):
return not GPIO.input(self._button_gpio)
def listen(self):
if self.is_pressed():
self._callback()
class LED(object):
def __init__(self, led_gpio):
self._led_gpio = led_gpio
GPIO.setup(self._led_gpio, GPIO.OUT)
self.off() # start with it off
def on(self):
GPIO.output(self._led_gpio, True)
def off(self):
GPIO.output(self._led_gpio, False)
def speak(say_wa):
echo_string = "'{0}'".format(say_wa.replace("'", "'\''"))
echo = subprocess.Popen(['echo', echo_string], stdout=subprocess.PIPE)
espeak = subprocess.Popen(["espeak", "-v", "english", "--stdout"],
stdin=echo.stdout, stdout=subprocess.PIPE)
echo.stdout.close()
subprocess.Popen(['aplay'], stdin=espeak.stdout)
espeak.stdout.close()
|
0337d51dc2c65c376f30046a0869c6fabf012cd0 | webfinger/__init__.py | webfinger/__init__.py | """A simple Python client implementation of WebFinger (RFC 7033).
WebFinger is a discovery protocol that allows you to find information about
people or things in a standardized way.
"""
__version__ = "3.0.0.dev0"
# Backwards compatibility stubs
from webfinger.client.requests import WebFingerClient
from webfinger.objects import WebFingerResponse
from webfinger.exceptions import *
_client = WebFingerClient()
def finger(resource, rel=None):
"""Invoke finger without creating a WebFingerClient instance.
args:
resource - resource to look up
rel - relation to request from the server
"""
return _client.finger(resource, rel=rel)
| """A simple Python client implementation of WebFinger (RFC 7033).
WebFinger is a discovery protocol that allows you to find information about
people or things in a standardized way.
This package provides a few tools for using WebFinger, including:
- requests-based webfinger client (webfinger.client.requests.WebFingerClient)
- aiohttp-based webfinger client(webfinger.client.aiohttp.WebFingerClient)
- a class to build WebFinger JRD's (webfinger.objects.WebFingerBuilder)
In this module, the following are exposed:
- BaseWebFingerClient (from webfinger.client)
- WebFingerClient (from webfinger.client.requests for backwards
compatibility)
- The WebFingerResponse and WebFingerBuilder objects (from
webfinger.objects)
- Exceptions (from webfinger.exceptions)
- A simple helper for basic finger requests (the finger function)
"""
__version__ = "3.0.0.dev1"
from webfinger.client import BaseWebFingerClient
from webfinger.client.requests import WebFingerClient
from webfinger.objects import WebFingerResponse, WebFingerBuilder
from webfinger.exceptions import *
_client = WebFingerClient()
def finger(resource, rel=None):
"""Invoke finger without creating a WebFingerClient instance.
args:
resource - resource to look up
rel - relation to request from the server
"""
return _client.finger(resource, rel=rel)
| Improve docs and import WebFingerBuilder | Improve docs and import WebFingerBuilder
| Python | bsd-3-clause | Elizafox/python-webfinger | """A simple Python client implementation of WebFinger (RFC 7033).
WebFinger is a discovery protocol that allows you to find information about
people or things in a standardized way.
"""
__version__ = "3.0.0.dev0"
# Backwards compatibility stubs
from webfinger.client.requests import WebFingerClient
from webfinger.objects import WebFingerResponse
from webfinger.exceptions import *
_client = WebFingerClient()
def finger(resource, rel=None):
"""Invoke finger without creating a WebFingerClient instance.
args:
resource - resource to look up
rel - relation to request from the server
"""
return _client.finger(resource, rel=rel)
Improve docs and import WebFingerBuilder | """A simple Python client implementation of WebFinger (RFC 7033).
WebFinger is a discovery protocol that allows you to find information about
people or things in a standardized way.
This package provides a few tools for using WebFinger, including:
- requests-based webfinger client (webfinger.client.requests.WebFingerClient)
- aiohttp-based webfinger client(webfinger.client.aiohttp.WebFingerClient)
- a class to build WebFinger JRD's (webfinger.objects.WebFingerBuilder)
In this module, the following are exposed:
- BaseWebFingerClient (from webfinger.client)
- WebFingerClient (from webfinger.client.requests for backwards
compatibility)
- The WebFingerResponse and WebFingerBuilder objects (from
webfinger.objects)
- Exceptions (from webfinger.exceptions)
- A simple helper for basic finger requests (the finger function)
"""
__version__ = "3.0.0.dev1"
from webfinger.client import BaseWebFingerClient
from webfinger.client.requests import WebFingerClient
from webfinger.objects import WebFingerResponse, WebFingerBuilder
from webfinger.exceptions import *
_client = WebFingerClient()
def finger(resource, rel=None):
"""Invoke finger without creating a WebFingerClient instance.
args:
resource - resource to look up
rel - relation to request from the server
"""
return _client.finger(resource, rel=rel)
| <commit_before>"""A simple Python client implementation of WebFinger (RFC 7033).
WebFinger is a discovery protocol that allows you to find information about
people or things in a standardized way.
"""
__version__ = "3.0.0.dev0"
# Backwards compatibility stubs
from webfinger.client.requests import WebFingerClient
from webfinger.objects import WebFingerResponse
from webfinger.exceptions import *
_client = WebFingerClient()
def finger(resource, rel=None):
"""Invoke finger without creating a WebFingerClient instance.
args:
resource - resource to look up
rel - relation to request from the server
"""
return _client.finger(resource, rel=rel)
<commit_msg>Improve docs and import WebFingerBuilder<commit_after> | """A simple Python client implementation of WebFinger (RFC 7033).
WebFinger is a discovery protocol that allows you to find information about
people or things in a standardized way.
This package provides a few tools for using WebFinger, including:
- requests-based webfinger client (webfinger.client.requests.WebFingerClient)
- aiohttp-based webfinger client(webfinger.client.aiohttp.WebFingerClient)
- a class to build WebFinger JRD's (webfinger.objects.WebFingerBuilder)
In this module, the following are exposed:
- BaseWebFingerClient (from webfinger.client)
- WebFingerClient (from webfinger.client.requests for backwards
compatibility)
- The WebFingerResponse and WebFingerBuilder objects (from
webfinger.objects)
- Exceptions (from webfinger.exceptions)
- A simple helper for basic finger requests (the finger function)
"""
__version__ = "3.0.0.dev1"
from webfinger.client import BaseWebFingerClient
from webfinger.client.requests import WebFingerClient
from webfinger.objects import WebFingerResponse, WebFingerBuilder
from webfinger.exceptions import *
_client = WebFingerClient()
def finger(resource, rel=None):
"""Invoke finger without creating a WebFingerClient instance.
args:
resource - resource to look up
rel - relation to request from the server
"""
return _client.finger(resource, rel=rel)
| """A simple Python client implementation of WebFinger (RFC 7033).
WebFinger is a discovery protocol that allows you to find information about
people or things in a standardized way.
"""
__version__ = "3.0.0.dev0"
# Backwards compatibility stubs
from webfinger.client.requests import WebFingerClient
from webfinger.objects import WebFingerResponse
from webfinger.exceptions import *
_client = WebFingerClient()
def finger(resource, rel=None):
"""Invoke finger without creating a WebFingerClient instance.
args:
resource - resource to look up
rel - relation to request from the server
"""
return _client.finger(resource, rel=rel)
Improve docs and import WebFingerBuilder"""A simple Python client implementation of WebFinger (RFC 7033).
WebFinger is a discovery protocol that allows you to find information about
people or things in a standardized way.
This package provides a few tools for using WebFinger, including:
- requests-based webfinger client (webfinger.client.requests.WebFingerClient)
- aiohttp-based webfinger client(webfinger.client.aiohttp.WebFingerClient)
- a class to build WebFinger JRD's (webfinger.objects.WebFingerBuilder)
In this module, the following are exposed:
- BaseWebFingerClient (from webfinger.client)
- WebFingerClient (from webfinger.client.requests for backwards
compatibility)
- The WebFingerResponse and WebFingerBuilder objects (from
webfinger.objects)
- Exceptions (from webfinger.exceptions)
- A simple helper for basic finger requests (the finger function)
"""
__version__ = "3.0.0.dev1"
from webfinger.client import BaseWebFingerClient
from webfinger.client.requests import WebFingerClient
from webfinger.objects import WebFingerResponse, WebFingerBuilder
from webfinger.exceptions import *
_client = WebFingerClient()
def finger(resource, rel=None):
"""Invoke finger without creating a WebFingerClient instance.
args:
resource - resource to look up
rel - relation to request from the server
"""
return _client.finger(resource, rel=rel)
| <commit_before>"""A simple Python client implementation of WebFinger (RFC 7033).
WebFinger is a discovery protocol that allows you to find information about
people or things in a standardized way.
"""
__version__ = "3.0.0.dev0"
# Backwards compatibility stubs
from webfinger.client.requests import WebFingerClient
from webfinger.objects import WebFingerResponse
from webfinger.exceptions import *
_client = WebFingerClient()
def finger(resource, rel=None):
"""Invoke finger without creating a WebFingerClient instance.
args:
resource - resource to look up
rel - relation to request from the server
"""
return _client.finger(resource, rel=rel)
<commit_msg>Improve docs and import WebFingerBuilder<commit_after>"""A simple Python client implementation of WebFinger (RFC 7033).
WebFinger is a discovery protocol that allows you to find information about
people or things in a standardized way.
This package provides a few tools for using WebFinger, including:
- requests-based webfinger client (webfinger.client.requests.WebFingerClient)
- aiohttp-based webfinger client(webfinger.client.aiohttp.WebFingerClient)
- a class to build WebFinger JRD's (webfinger.objects.WebFingerBuilder)
In this module, the following are exposed:
- BaseWebFingerClient (from webfinger.client)
- WebFingerClient (from webfinger.client.requests for backwards
compatibility)
- The WebFingerResponse and WebFingerBuilder objects (from
webfinger.objects)
- Exceptions (from webfinger.exceptions)
- A simple helper for basic finger requests (the finger function)
"""
__version__ = "3.0.0.dev1"
from webfinger.client import BaseWebFingerClient
from webfinger.client.requests import WebFingerClient
from webfinger.objects import WebFingerResponse, WebFingerBuilder
from webfinger.exceptions import *
_client = WebFingerClient()
def finger(resource, rel=None):
"""Invoke finger without creating a WebFingerClient instance.
args:
resource - resource to look up
rel - relation to request from the server
"""
return _client.finger(resource, rel=rel)
|
0656b4c1be9820f3cd096359cd8817153f2e0b81 | freelancefinder/remotes/tests/test_tasks.py | freelancefinder/remotes/tests/test_tasks.py | """Tests related to the remotes.tasks functions."""
from django_celery_beat.models import IntervalSchedule, PeriodicTask
from jobs.models import Post
from ..models import Source
from ..tasks import setup_periodic_tasks, harvest_sources
def test_make_tasks():
"""Ensure that setup makes some tasks/schedules."""
setup_periodic_tasks(None)
intervals = IntervalSchedule.objects.all().count()
tasks = PeriodicTask.objects.all().count()
assert intervals > 0
assert tasks > 0
def test_harvest_sources(fossjobs_rss_feed, mocker):
"""Verify that harvest sources calls harvest."""
mocker.patch('feedparser.parse', side_effect=lambda x: fossjobs_rss_feed)
Source.objects.all().delete()
Source.objects.create(code='fossjobs', name='FossJobs', url='http://test.example.com/')
pre_posts = Post.objects.all().count()
harvest_sources()
post_posts = Post.objects.all().count()
assert pre_posts != post_posts
assert post_posts > 0
| """Tests related to the remotes.tasks functions."""
from django_celery_beat.models import IntervalSchedule, PeriodicTask
from jobs.models import Post
from ..models import Source
from ..tasks import setup_periodic_tasks, harvest_sources
def test_make_tasks():
"""Ensure that setup makes some tasks/schedules."""
setup_periodic_tasks(None)
intervals = IntervalSchedule.objects.all().count()
tasks = PeriodicTask.objects.all().count()
assert intervals > 0
assert tasks > 0
def test_harvest_sources(fossjobs_rss_feed, mocker):
"""Verify that harvest sources calls harvest."""
mocker.patch('feedparser.parse', side_effect=lambda x: fossjobs_rss_feed)
Source.objects.all().delete()
Source.objects.create(code='fossjobs', name='FossJobs', url='http://test.example.com/')
pre_posts = Post.objects.all().count()
harvest_sources()
post_posts = Post.objects.all().count()
assert pre_posts != post_posts
assert post_posts > 0
def test_broken_harvest(mocker):
"""Verify that broken harvest doesn't throw."""
mocker.patch('feedparser.parse', side_effect=lambda x: 'broken')
Source.objects.all().delete()
Source.objects.create(code='fossjobs', name='FossJobs', url='http://test.example.com/')
harvest_sources()
# If that raises, then we've got an issue.
assert True
| Test broken harvest doesn't break everything. | Test broken harvest doesn't break everything.
| Python | bsd-3-clause | ScorpionResponse/freelancefinder,ScorpionResponse/freelancefinder,ScorpionResponse/freelancefinder | """Tests related to the remotes.tasks functions."""
from django_celery_beat.models import IntervalSchedule, PeriodicTask
from jobs.models import Post
from ..models import Source
from ..tasks import setup_periodic_tasks, harvest_sources
def test_make_tasks():
"""Ensure that setup makes some tasks/schedules."""
setup_periodic_tasks(None)
intervals = IntervalSchedule.objects.all().count()
tasks = PeriodicTask.objects.all().count()
assert intervals > 0
assert tasks > 0
def test_harvest_sources(fossjobs_rss_feed, mocker):
"""Verify that harvest sources calls harvest."""
mocker.patch('feedparser.parse', side_effect=lambda x: fossjobs_rss_feed)
Source.objects.all().delete()
Source.objects.create(code='fossjobs', name='FossJobs', url='http://test.example.com/')
pre_posts = Post.objects.all().count()
harvest_sources()
post_posts = Post.objects.all().count()
assert pre_posts != post_posts
assert post_posts > 0
Test broken harvest doesn't break everything. | """Tests related to the remotes.tasks functions."""
from django_celery_beat.models import IntervalSchedule, PeriodicTask
from jobs.models import Post
from ..models import Source
from ..tasks import setup_periodic_tasks, harvest_sources
def test_make_tasks():
"""Ensure that setup makes some tasks/schedules."""
setup_periodic_tasks(None)
intervals = IntervalSchedule.objects.all().count()
tasks = PeriodicTask.objects.all().count()
assert intervals > 0
assert tasks > 0
def test_harvest_sources(fossjobs_rss_feed, mocker):
"""Verify that harvest sources calls harvest."""
mocker.patch('feedparser.parse', side_effect=lambda x: fossjobs_rss_feed)
Source.objects.all().delete()
Source.objects.create(code='fossjobs', name='FossJobs', url='http://test.example.com/')
pre_posts = Post.objects.all().count()
harvest_sources()
post_posts = Post.objects.all().count()
assert pre_posts != post_posts
assert post_posts > 0
def test_broken_harvest(mocker):
"""Verify that broken harvest doesn't throw."""
mocker.patch('feedparser.parse', side_effect=lambda x: 'broken')
Source.objects.all().delete()
Source.objects.create(code='fossjobs', name='FossJobs', url='http://test.example.com/')
harvest_sources()
# If that raises, then we've got an issue.
assert True
| <commit_before>"""Tests related to the remotes.tasks functions."""
from django_celery_beat.models import IntervalSchedule, PeriodicTask
from jobs.models import Post
from ..models import Source
from ..tasks import setup_periodic_tasks, harvest_sources
def test_make_tasks():
"""Ensure that setup makes some tasks/schedules."""
setup_periodic_tasks(None)
intervals = IntervalSchedule.objects.all().count()
tasks = PeriodicTask.objects.all().count()
assert intervals > 0
assert tasks > 0
def test_harvest_sources(fossjobs_rss_feed, mocker):
"""Verify that harvest sources calls harvest."""
mocker.patch('feedparser.parse', side_effect=lambda x: fossjobs_rss_feed)
Source.objects.all().delete()
Source.objects.create(code='fossjobs', name='FossJobs', url='http://test.example.com/')
pre_posts = Post.objects.all().count()
harvest_sources()
post_posts = Post.objects.all().count()
assert pre_posts != post_posts
assert post_posts > 0
<commit_msg>Test broken harvest doesn't break everything.<commit_after> | """Tests related to the remotes.tasks functions."""
from django_celery_beat.models import IntervalSchedule, PeriodicTask
from jobs.models import Post
from ..models import Source
from ..tasks import setup_periodic_tasks, harvest_sources
def test_make_tasks():
"""Ensure that setup makes some tasks/schedules."""
setup_periodic_tasks(None)
intervals = IntervalSchedule.objects.all().count()
tasks = PeriodicTask.objects.all().count()
assert intervals > 0
assert tasks > 0
def test_harvest_sources(fossjobs_rss_feed, mocker):
"""Verify that harvest sources calls harvest."""
mocker.patch('feedparser.parse', side_effect=lambda x: fossjobs_rss_feed)
Source.objects.all().delete()
Source.objects.create(code='fossjobs', name='FossJobs', url='http://test.example.com/')
pre_posts = Post.objects.all().count()
harvest_sources()
post_posts = Post.objects.all().count()
assert pre_posts != post_posts
assert post_posts > 0
def test_broken_harvest(mocker):
"""Verify that broken harvest doesn't throw."""
mocker.patch('feedparser.parse', side_effect=lambda x: 'broken')
Source.objects.all().delete()
Source.objects.create(code='fossjobs', name='FossJobs', url='http://test.example.com/')
harvest_sources()
# If that raises, then we've got an issue.
assert True
| """Tests related to the remotes.tasks functions."""
from django_celery_beat.models import IntervalSchedule, PeriodicTask
from jobs.models import Post
from ..models import Source
from ..tasks import setup_periodic_tasks, harvest_sources
def test_make_tasks():
"""Ensure that setup makes some tasks/schedules."""
setup_periodic_tasks(None)
intervals = IntervalSchedule.objects.all().count()
tasks = PeriodicTask.objects.all().count()
assert intervals > 0
assert tasks > 0
def test_harvest_sources(fossjobs_rss_feed, mocker):
"""Verify that harvest sources calls harvest."""
mocker.patch('feedparser.parse', side_effect=lambda x: fossjobs_rss_feed)
Source.objects.all().delete()
Source.objects.create(code='fossjobs', name='FossJobs', url='http://test.example.com/')
pre_posts = Post.objects.all().count()
harvest_sources()
post_posts = Post.objects.all().count()
assert pre_posts != post_posts
assert post_posts > 0
Test broken harvest doesn't break everything."""Tests related to the remotes.tasks functions."""
from django_celery_beat.models import IntervalSchedule, PeriodicTask
from jobs.models import Post
from ..models import Source
from ..tasks import setup_periodic_tasks, harvest_sources
def test_make_tasks():
"""Ensure that setup makes some tasks/schedules."""
setup_periodic_tasks(None)
intervals = IntervalSchedule.objects.all().count()
tasks = PeriodicTask.objects.all().count()
assert intervals > 0
assert tasks > 0
def test_harvest_sources(fossjobs_rss_feed, mocker):
"""Verify that harvest sources calls harvest."""
mocker.patch('feedparser.parse', side_effect=lambda x: fossjobs_rss_feed)
Source.objects.all().delete()
Source.objects.create(code='fossjobs', name='FossJobs', url='http://test.example.com/')
pre_posts = Post.objects.all().count()
harvest_sources()
post_posts = Post.objects.all().count()
assert pre_posts != post_posts
assert post_posts > 0
def test_broken_harvest(mocker):
"""Verify that broken harvest doesn't throw."""
mocker.patch('feedparser.parse', side_effect=lambda x: 'broken')
Source.objects.all().delete()
Source.objects.create(code='fossjobs', name='FossJobs', url='http://test.example.com/')
harvest_sources()
# If that raises, then we've got an issue.
assert True
| <commit_before>"""Tests related to the remotes.tasks functions."""
from django_celery_beat.models import IntervalSchedule, PeriodicTask
from jobs.models import Post
from ..models import Source
from ..tasks import setup_periodic_tasks, harvest_sources
def test_make_tasks():
"""Ensure that setup makes some tasks/schedules."""
setup_periodic_tasks(None)
intervals = IntervalSchedule.objects.all().count()
tasks = PeriodicTask.objects.all().count()
assert intervals > 0
assert tasks > 0
def test_harvest_sources(fossjobs_rss_feed, mocker):
"""Verify that harvest sources calls harvest."""
mocker.patch('feedparser.parse', side_effect=lambda x: fossjobs_rss_feed)
Source.objects.all().delete()
Source.objects.create(code='fossjobs', name='FossJobs', url='http://test.example.com/')
pre_posts = Post.objects.all().count()
harvest_sources()
post_posts = Post.objects.all().count()
assert pre_posts != post_posts
assert post_posts > 0
<commit_msg>Test broken harvest doesn't break everything.<commit_after>"""Tests related to the remotes.tasks functions."""
from django_celery_beat.models import IntervalSchedule, PeriodicTask
from jobs.models import Post
from ..models import Source
from ..tasks import setup_periodic_tasks, harvest_sources
def test_make_tasks():
"""Ensure that setup makes some tasks/schedules."""
setup_periodic_tasks(None)
intervals = IntervalSchedule.objects.all().count()
tasks = PeriodicTask.objects.all().count()
assert intervals > 0
assert tasks > 0
def test_harvest_sources(fossjobs_rss_feed, mocker):
"""Verify that harvest sources calls harvest."""
mocker.patch('feedparser.parse', side_effect=lambda x: fossjobs_rss_feed)
Source.objects.all().delete()
Source.objects.create(code='fossjobs', name='FossJobs', url='http://test.example.com/')
pre_posts = Post.objects.all().count()
harvest_sources()
post_posts = Post.objects.all().count()
assert pre_posts != post_posts
assert post_posts > 0
def test_broken_harvest(mocker):
"""Verify that broken harvest doesn't throw."""
mocker.patch('feedparser.parse', side_effect=lambda x: 'broken')
Source.objects.all().delete()
Source.objects.create(code='fossjobs', name='FossJobs', url='http://test.example.com/')
harvest_sources()
# If that raises, then we've got an issue.
assert True
|
460580ff585fa76cebc5e2e9cb1d49550db9f68d | components/item_lock.py | components/item_lock.py | from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
LOCK_USER = 'lock_user'
STATUS = '_status'
class ItemLock():
def __init__(self, data_layer):
self.data_layer = data_layer
def lock(self, filter, user, etag):
item_model = ItemModel(self.data_layer)
item = item_model.find_one(filter)
if item and self._can_lock(item, user):
# filter[ETAG] = etag
updates = {LOCK_USER: user}
item_model.update(filter, updates)
item[LOCK_USER] = user
else:
raise SuperdeskError('Item locked by another user')
return item
def unlock(self, filter, user, etag):
item_model = ItemModel()
filter[LOCK_USER] = user
filter[ETAG] = etag
item = item_model.find_one(filter)
if item:
update = {LOCK_USER: None}
item_model.update(filter, update)
def _can_lock(self, item, user):
# TODO: implement
return True
| from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
from superdesk.utc import utcnow
LOCK_USER = 'lock_user'
STATUS = '_status'
class ItemLock():
def __init__(self, data_layer):
self.data_layer = data_layer
def lock(self, filter, user, etag):
item_model = ItemModel(self.data_layer)
item = item_model.find_one(filter)
if item and self._can_lock(item, user):
# filter[ETAG] = etag
updates = {LOCK_USER: user, 'lock_time': utcnow()}
item_model.update(filter, updates)
item[LOCK_USER] = user
else:
raise SuperdeskError('Item locked by another user')
return item
def unlock(self, filter, user, etag):
item_model = ItemModel()
filter[LOCK_USER] = user
filter[ETAG] = etag
item = item_model.find_one(filter)
if item:
update = {LOCK_USER: None}
item_model.update(filter, update)
def _can_lock(self, item, user):
# TODO: implement
return True
| Set timestamp on item lock operation | Set timestamp on item lock operation
| Python | agpl-3.0 | akintolga/superdesk,superdesk/superdesk-ntb,verifiedpixel/superdesk,Aca-jov/superdesk,amagdas/superdesk,hlmnrmr/superdesk,verifiedpixel/superdesk,pavlovicnemanja/superdesk,ioanpocol/superdesk-ntb,liveblog/superdesk,marwoodandrew/superdesk-aap,sivakuna-aap/superdesk,mugurrus/superdesk,akintolga/superdesk-aap,pavlovicnemanja/superdesk,petrjasek/superdesk-ntb,superdesk/superdesk,fritzSF/superdesk,fritzSF/superdesk,marwoodandrew/superdesk,fritzSF/superdesk,vied12/superdesk,thnkloud9/superdesk,verifiedpixel/superdesk,marwoodandrew/superdesk-aap,superdesk/superdesk-aap,marwoodandrew/superdesk,liveblog/superdesk,akintolga/superdesk-aap,petrjasek/superdesk,plamut/superdesk,petrjasek/superdesk,superdesk/superdesk,akintolga/superdesk,pavlovicnemanja92/superdesk,ancafarcas/superdesk,verifiedpixel/superdesk,plamut/superdesk,akintolga/superdesk,vied12/superdesk,ancafarcas/superdesk,marwoodandrew/superdesk,superdesk/superdesk-ntb,marwoodandrew/superdesk,vied12/superdesk,mdhaman/superdesk,mdhaman/superdesk,sivakuna-aap/superdesk,liveblog/superdesk,liveblog/superdesk,superdesk/superdesk-aap,hlmnrmr/superdesk,hlmnrmr/superdesk,superdesk/superdesk,darconny/superdesk,akintolga/superdesk-aap,pavlovicnemanja92/superdesk,vied12/superdesk,petrjasek/superdesk-server,petrjasek/superdesk,ioanpocol/superdesk-ntb,superdesk/superdesk-aap,mdhaman/superdesk,liveblog/superdesk,pavlovicnemanja92/superdesk,mdhaman/superdesk-aap,sivakuna-aap/superdesk,sivakuna-aap/superdesk,akintolga/superdesk,mdhaman/superdesk-aap,petrjasek/superdesk-server,pavlovicnemanja92/superdesk,ioanpocol/superdesk,petrjasek/superdesk,plamut/superdesk,mdhaman/superdesk-aap,amagdas/superdesk,fritzSF/superdesk,mdhaman/superdesk-aap,akintolga/superdesk-aap,amagdas/superdesk,petrjasek/superdesk-ntb,fritzSF/superdesk,thnkloud9/superdesk,plamut/superdesk,ioanpocol/superdesk,superdesk/superdesk-aap,amagdas/superdesk,ioanpocol/superdesk-ntb,sjunaid/superdesk,vied12/superdesk,mugurrus/superdesk,sjunaid/superdesk,Aca-jov/superdesk,marwoodandrew/superdesk-aap,gbbr/superdesk,pavlovicnemanja92/superdesk,superdesk/superdesk,thnkloud9/superdesk,amagdas/superdesk,superdesk/superdesk-ntb,petrjasek/superdesk-ntb,marwoodandrew/superdesk-aap,darconny/superdesk,petrjasek/superdesk-ntb,plamut/superdesk,darconny/superdesk,akintolga/superdesk,gbbr/superdesk,superdesk/superdesk-ntb,pavlovicnemanja/superdesk,marwoodandrew/superdesk,mugurrus/superdesk,pavlovicnemanja/superdesk,ancafarcas/superdesk,ioanpocol/superdesk,verifiedpixel/superdesk,gbbr/superdesk,sjunaid/superdesk,Aca-jov/superdesk,sivakuna-aap/superdesk | from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
LOCK_USER = 'lock_user'
STATUS = '_status'
class ItemLock():
def __init__(self, data_layer):
self.data_layer = data_layer
def lock(self, filter, user, etag):
item_model = ItemModel(self.data_layer)
item = item_model.find_one(filter)
if item and self._can_lock(item, user):
# filter[ETAG] = etag
updates = {LOCK_USER: user}
item_model.update(filter, updates)
item[LOCK_USER] = user
else:
raise SuperdeskError('Item locked by another user')
return item
def unlock(self, filter, user, etag):
item_model = ItemModel()
filter[LOCK_USER] = user
filter[ETAG] = etag
item = item_model.find_one(filter)
if item:
update = {LOCK_USER: None}
item_model.update(filter, update)
def _can_lock(self, item, user):
# TODO: implement
return True
Set timestamp on item lock operation | from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
from superdesk.utc import utcnow
LOCK_USER = 'lock_user'
STATUS = '_status'
class ItemLock():
def __init__(self, data_layer):
self.data_layer = data_layer
def lock(self, filter, user, etag):
item_model = ItemModel(self.data_layer)
item = item_model.find_one(filter)
if item and self._can_lock(item, user):
# filter[ETAG] = etag
updates = {LOCK_USER: user, 'lock_time': utcnow()}
item_model.update(filter, updates)
item[LOCK_USER] = user
else:
raise SuperdeskError('Item locked by another user')
return item
def unlock(self, filter, user, etag):
item_model = ItemModel()
filter[LOCK_USER] = user
filter[ETAG] = etag
item = item_model.find_one(filter)
if item:
update = {LOCK_USER: None}
item_model.update(filter, update)
def _can_lock(self, item, user):
# TODO: implement
return True
| <commit_before>from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
LOCK_USER = 'lock_user'
STATUS = '_status'
class ItemLock():
def __init__(self, data_layer):
self.data_layer = data_layer
def lock(self, filter, user, etag):
item_model = ItemModel(self.data_layer)
item = item_model.find_one(filter)
if item and self._can_lock(item, user):
# filter[ETAG] = etag
updates = {LOCK_USER: user}
item_model.update(filter, updates)
item[LOCK_USER] = user
else:
raise SuperdeskError('Item locked by another user')
return item
def unlock(self, filter, user, etag):
item_model = ItemModel()
filter[LOCK_USER] = user
filter[ETAG] = etag
item = item_model.find_one(filter)
if item:
update = {LOCK_USER: None}
item_model.update(filter, update)
def _can_lock(self, item, user):
# TODO: implement
return True
<commit_msg>Set timestamp on item lock operation<commit_after> | from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
from superdesk.utc import utcnow
LOCK_USER = 'lock_user'
STATUS = '_status'
class ItemLock():
def __init__(self, data_layer):
self.data_layer = data_layer
def lock(self, filter, user, etag):
item_model = ItemModel(self.data_layer)
item = item_model.find_one(filter)
if item and self._can_lock(item, user):
# filter[ETAG] = etag
updates = {LOCK_USER: user, 'lock_time': utcnow()}
item_model.update(filter, updates)
item[LOCK_USER] = user
else:
raise SuperdeskError('Item locked by another user')
return item
def unlock(self, filter, user, etag):
item_model = ItemModel()
filter[LOCK_USER] = user
filter[ETAG] = etag
item = item_model.find_one(filter)
if item:
update = {LOCK_USER: None}
item_model.update(filter, update)
def _can_lock(self, item, user):
# TODO: implement
return True
| from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
LOCK_USER = 'lock_user'
STATUS = '_status'
class ItemLock():
def __init__(self, data_layer):
self.data_layer = data_layer
def lock(self, filter, user, etag):
item_model = ItemModel(self.data_layer)
item = item_model.find_one(filter)
if item and self._can_lock(item, user):
# filter[ETAG] = etag
updates = {LOCK_USER: user}
item_model.update(filter, updates)
item[LOCK_USER] = user
else:
raise SuperdeskError('Item locked by another user')
return item
def unlock(self, filter, user, etag):
item_model = ItemModel()
filter[LOCK_USER] = user
filter[ETAG] = etag
item = item_model.find_one(filter)
if item:
update = {LOCK_USER: None}
item_model.update(filter, update)
def _can_lock(self, item, user):
# TODO: implement
return True
Set timestamp on item lock operationfrom models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
from superdesk.utc import utcnow
LOCK_USER = 'lock_user'
STATUS = '_status'
class ItemLock():
def __init__(self, data_layer):
self.data_layer = data_layer
def lock(self, filter, user, etag):
item_model = ItemModel(self.data_layer)
item = item_model.find_one(filter)
if item and self._can_lock(item, user):
# filter[ETAG] = etag
updates = {LOCK_USER: user, 'lock_time': utcnow()}
item_model.update(filter, updates)
item[LOCK_USER] = user
else:
raise SuperdeskError('Item locked by another user')
return item
def unlock(self, filter, user, etag):
item_model = ItemModel()
filter[LOCK_USER] = user
filter[ETAG] = etag
item = item_model.find_one(filter)
if item:
update = {LOCK_USER: None}
item_model.update(filter, update)
def _can_lock(self, item, user):
# TODO: implement
return True
| <commit_before>from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
LOCK_USER = 'lock_user'
STATUS = '_status'
class ItemLock():
def __init__(self, data_layer):
self.data_layer = data_layer
def lock(self, filter, user, etag):
item_model = ItemModel(self.data_layer)
item = item_model.find_one(filter)
if item and self._can_lock(item, user):
# filter[ETAG] = etag
updates = {LOCK_USER: user}
item_model.update(filter, updates)
item[LOCK_USER] = user
else:
raise SuperdeskError('Item locked by another user')
return item
def unlock(self, filter, user, etag):
item_model = ItemModel()
filter[LOCK_USER] = user
filter[ETAG] = etag
item = item_model.find_one(filter)
if item:
update = {LOCK_USER: None}
item_model.update(filter, update)
def _can_lock(self, item, user):
# TODO: implement
return True
<commit_msg>Set timestamp on item lock operation<commit_after>from models.item import ItemModel
from models.base_model import ETAG
from superdesk import SuperdeskError
from superdesk.utc import utcnow
LOCK_USER = 'lock_user'
STATUS = '_status'
class ItemLock():
def __init__(self, data_layer):
self.data_layer = data_layer
def lock(self, filter, user, etag):
item_model = ItemModel(self.data_layer)
item = item_model.find_one(filter)
if item and self._can_lock(item, user):
# filter[ETAG] = etag
updates = {LOCK_USER: user, 'lock_time': utcnow()}
item_model.update(filter, updates)
item[LOCK_USER] = user
else:
raise SuperdeskError('Item locked by another user')
return item
def unlock(self, filter, user, etag):
item_model = ItemModel()
filter[LOCK_USER] = user
filter[ETAG] = etag
item = item_model.find_one(filter)
if item:
update = {LOCK_USER: None}
item_model.update(filter, update)
def _can_lock(self, item, user):
# TODO: implement
return True
|
089e4f59fdf73d1a4e8d03ac07f475b2ffe62e30 | docs/css_diagram_role.py | docs/css_diagram_role.py | """
A Sphinx extension adding a 'css' role creating links to
the spec’s railroad diagrams.
"""
from docutils import nodes
def role_fn(_name, rawtext, text, lineno, inliner, options={}, content=()):
ref = 'http://dev.w3.org/csswg/css-syntax-3/#%s-diagram' % text.replace(
' ', '-')
if text.endswith(('-token', '-block')):
text = '<%s>' % text
ref = nodes.reference(rawtext, text, refuri=ref, **options)
return [ref], []
def setup(app):
app.add_role_to_domain('py', 'diagram', role_fn)
| """
A Sphinx extension adding a 'css' role creating links to
the spec’s railroad diagrams.
"""
from docutils import nodes
def role_fn(_name, rawtext, text, lineno, inliner, options={}, content=()):
ref = 'https://www.w3.org/TR/css-syntax-3/#%s-diagram' % text.replace(
' ', '-')
if text.endswith(('-token', '-block')):
text = '<%s>' % text
ref = nodes.reference(rawtext, text, refuri=ref, **options)
return [ref], []
def setup(app):
app.add_role_to_domain('py', 'diagram', role_fn)
| Change URL used for CSS diagrams | Change URL used for CSS diagrams
| Python | bsd-3-clause | SimonSapin/tinycss2 | """
A Sphinx extension adding a 'css' role creating links to
the spec’s railroad diagrams.
"""
from docutils import nodes
def role_fn(_name, rawtext, text, lineno, inliner, options={}, content=()):
ref = 'http://dev.w3.org/csswg/css-syntax-3/#%s-diagram' % text.replace(
' ', '-')
if text.endswith(('-token', '-block')):
text = '<%s>' % text
ref = nodes.reference(rawtext, text, refuri=ref, **options)
return [ref], []
def setup(app):
app.add_role_to_domain('py', 'diagram', role_fn)
Change URL used for CSS diagrams | """
A Sphinx extension adding a 'css' role creating links to
the spec’s railroad diagrams.
"""
from docutils import nodes
def role_fn(_name, rawtext, text, lineno, inliner, options={}, content=()):
ref = 'https://www.w3.org/TR/css-syntax-3/#%s-diagram' % text.replace(
' ', '-')
if text.endswith(('-token', '-block')):
text = '<%s>' % text
ref = nodes.reference(rawtext, text, refuri=ref, **options)
return [ref], []
def setup(app):
app.add_role_to_domain('py', 'diagram', role_fn)
| <commit_before>"""
A Sphinx extension adding a 'css' role creating links to
the spec’s railroad diagrams.
"""
from docutils import nodes
def role_fn(_name, rawtext, text, lineno, inliner, options={}, content=()):
ref = 'http://dev.w3.org/csswg/css-syntax-3/#%s-diagram' % text.replace(
' ', '-')
if text.endswith(('-token', '-block')):
text = '<%s>' % text
ref = nodes.reference(rawtext, text, refuri=ref, **options)
return [ref], []
def setup(app):
app.add_role_to_domain('py', 'diagram', role_fn)
<commit_msg>Change URL used for CSS diagrams<commit_after> | """
A Sphinx extension adding a 'css' role creating links to
the spec’s railroad diagrams.
"""
from docutils import nodes
def role_fn(_name, rawtext, text, lineno, inliner, options={}, content=()):
ref = 'https://www.w3.org/TR/css-syntax-3/#%s-diagram' % text.replace(
' ', '-')
if text.endswith(('-token', '-block')):
text = '<%s>' % text
ref = nodes.reference(rawtext, text, refuri=ref, **options)
return [ref], []
def setup(app):
app.add_role_to_domain('py', 'diagram', role_fn)
| """
A Sphinx extension adding a 'css' role creating links to
the spec’s railroad diagrams.
"""
from docutils import nodes
def role_fn(_name, rawtext, text, lineno, inliner, options={}, content=()):
ref = 'http://dev.w3.org/csswg/css-syntax-3/#%s-diagram' % text.replace(
' ', '-')
if text.endswith(('-token', '-block')):
text = '<%s>' % text
ref = nodes.reference(rawtext, text, refuri=ref, **options)
return [ref], []
def setup(app):
app.add_role_to_domain('py', 'diagram', role_fn)
Change URL used for CSS diagrams"""
A Sphinx extension adding a 'css' role creating links to
the spec’s railroad diagrams.
"""
from docutils import nodes
def role_fn(_name, rawtext, text, lineno, inliner, options={}, content=()):
ref = 'https://www.w3.org/TR/css-syntax-3/#%s-diagram' % text.replace(
' ', '-')
if text.endswith(('-token', '-block')):
text = '<%s>' % text
ref = nodes.reference(rawtext, text, refuri=ref, **options)
return [ref], []
def setup(app):
app.add_role_to_domain('py', 'diagram', role_fn)
| <commit_before>"""
A Sphinx extension adding a 'css' role creating links to
the spec’s railroad diagrams.
"""
from docutils import nodes
def role_fn(_name, rawtext, text, lineno, inliner, options={}, content=()):
ref = 'http://dev.w3.org/csswg/css-syntax-3/#%s-diagram' % text.replace(
' ', '-')
if text.endswith(('-token', '-block')):
text = '<%s>' % text
ref = nodes.reference(rawtext, text, refuri=ref, **options)
return [ref], []
def setup(app):
app.add_role_to_domain('py', 'diagram', role_fn)
<commit_msg>Change URL used for CSS diagrams<commit_after>"""
A Sphinx extension adding a 'css' role creating links to
the spec’s railroad diagrams.
"""
from docutils import nodes
def role_fn(_name, rawtext, text, lineno, inliner, options={}, content=()):
ref = 'https://www.w3.org/TR/css-syntax-3/#%s-diagram' % text.replace(
' ', '-')
if text.endswith(('-token', '-block')):
text = '<%s>' % text
ref = nodes.reference(rawtext, text, refuri=ref, **options)
return [ref], []
def setup(app):
app.add_role_to_domain('py', 'diagram', role_fn)
|
78c4e61684baaae3487641a2c1813bbd664822a1 | kolibri/__init__.py | kolibri/__init__.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .utils.version import get_version
#: This may not be the exact version as it's subject to modification with
#: get_version() - use ``kolibri.__version__`` for the exact version string.
VERSION = (0, 9, 0, 'final', 0)
__author__ = 'Learning Equality'
__email__ = 'info@learningequality.org'
__version__ = str(get_version(VERSION))
| from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .utils.version import get_version
#: This may not be the exact version as it's subject to modification with
#: get_version() - use ``kolibri.__version__`` for the exact version string.
VERSION = (0, 9, 1, 'alpha', 0)
__author__ = 'Learning Equality'
__email__ = 'info@learningequality.org'
__version__ = str(get_version(VERSION))
| Bump to next dev cycle | Bump to next dev cycle
| Python | mit | lyw07/kolibri,jonboiser/kolibri,indirectlylit/kolibri,learningequality/kolibri,DXCanas/kolibri,benjaoming/kolibri,learningequality/kolibri,learningequality/kolibri,lyw07/kolibri,benjaoming/kolibri,indirectlylit/kolibri,DXCanas/kolibri,mrpau/kolibri,mrpau/kolibri,mrpau/kolibri,benjaoming/kolibri,benjaoming/kolibri,lyw07/kolibri,lyw07/kolibri,DXCanas/kolibri,indirectlylit/kolibri,jonboiser/kolibri,jonboiser/kolibri,mrpau/kolibri,indirectlylit/kolibri,DXCanas/kolibri,jonboiser/kolibri,learningequality/kolibri | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .utils.version import get_version
#: This may not be the exact version as it's subject to modification with
#: get_version() - use ``kolibri.__version__`` for the exact version string.
VERSION = (0, 9, 0, 'final', 0)
__author__ = 'Learning Equality'
__email__ = 'info@learningequality.org'
__version__ = str(get_version(VERSION))
Bump to next dev cycle | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .utils.version import get_version
#: This may not be the exact version as it's subject to modification with
#: get_version() - use ``kolibri.__version__`` for the exact version string.
VERSION = (0, 9, 1, 'alpha', 0)
__author__ = 'Learning Equality'
__email__ = 'info@learningequality.org'
__version__ = str(get_version(VERSION))
| <commit_before>from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .utils.version import get_version
#: This may not be the exact version as it's subject to modification with
#: get_version() - use ``kolibri.__version__`` for the exact version string.
VERSION = (0, 9, 0, 'final', 0)
__author__ = 'Learning Equality'
__email__ = 'info@learningequality.org'
__version__ = str(get_version(VERSION))
<commit_msg>Bump to next dev cycle<commit_after> | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .utils.version import get_version
#: This may not be the exact version as it's subject to modification with
#: get_version() - use ``kolibri.__version__`` for the exact version string.
VERSION = (0, 9, 1, 'alpha', 0)
__author__ = 'Learning Equality'
__email__ = 'info@learningequality.org'
__version__ = str(get_version(VERSION))
| from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .utils.version import get_version
#: This may not be the exact version as it's subject to modification with
#: get_version() - use ``kolibri.__version__`` for the exact version string.
VERSION = (0, 9, 0, 'final', 0)
__author__ = 'Learning Equality'
__email__ = 'info@learningequality.org'
__version__ = str(get_version(VERSION))
Bump to next dev cyclefrom __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .utils.version import get_version
#: This may not be the exact version as it's subject to modification with
#: get_version() - use ``kolibri.__version__`` for the exact version string.
VERSION = (0, 9, 1, 'alpha', 0)
__author__ = 'Learning Equality'
__email__ = 'info@learningequality.org'
__version__ = str(get_version(VERSION))
| <commit_before>from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .utils.version import get_version
#: This may not be the exact version as it's subject to modification with
#: get_version() - use ``kolibri.__version__`` for the exact version string.
VERSION = (0, 9, 0, 'final', 0)
__author__ = 'Learning Equality'
__email__ = 'info@learningequality.org'
__version__ = str(get_version(VERSION))
<commit_msg>Bump to next dev cycle<commit_after>from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .utils.version import get_version
#: This may not be the exact version as it's subject to modification with
#: get_version() - use ``kolibri.__version__`` for the exact version string.
VERSION = (0, 9, 1, 'alpha', 0)
__author__ = 'Learning Equality'
__email__ = 'info@learningequality.org'
__version__ = str(get_version(VERSION))
|
becc9ff7e1d260f9a4f47a36a0e6403e71f9f0b0 | contentcuration/contentcuration/utils/messages.py | contentcuration/contentcuration/utils/messages.py | import json
import os
from django.conf import settings
from django.utils.translation import get_language
from django.utils.translation import to_locale
_JSON_MESSAGES_FILE_CACHE = {}
def locale_data_file(locale):
path = getattr(settings, 'LOCALE_PATHS')[0]
locale_path = os.path.join(path, locale)
return os.path.join(locale_path, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json")
def get_messages():
global _JSON_MESSAGES_FILE_CACHE
locale = to_locale(get_language())
if locale not in _JSON_MESSAGES_FILE_CACHE:
try:
with open(locale_data_file(locale), 'rb') as data:
message_json = json.load(data)
translation_dict = {}
for key, value in message_json.items():
namespace, key = key.split(".")
translation_dict[namespace] = translation_dict.get(namespace) or {}
translation_dict[namespace][key] = value
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict)
except IOError:
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({})
return _JSON_MESSAGES_FILE_CACHE[locale]
| import json
import os
from django.conf import settings
from django.utils.translation import get_language
from django.utils.translation import to_locale
_JSON_MESSAGES_FILE_CACHE = {}
def locale_data_file(locale):
path = getattr(settings, 'LOCALE_PATHS')[0]
return os.path.join(path, locale, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json")
def get_messages():
global _JSON_MESSAGES_FILE_CACHE
locale = to_locale(get_language())
if locale not in _JSON_MESSAGES_FILE_CACHE:
try:
with open(locale_data_file(locale), 'rb') as data:
message_json = json.load(data)
translation_dict = {}
for key, value in message_json.items():
namespace, key = key.split(".")
translation_dict[namespace] = translation_dict.get(namespace) or {}
translation_dict[namespace][key] = value
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict)
except IOError:
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({})
return _JSON_MESSAGES_FILE_CACHE[locale]
| Remove no longer needed local variable. | Remove no longer needed local variable.
| Python | mit | DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation | import json
import os
from django.conf import settings
from django.utils.translation import get_language
from django.utils.translation import to_locale
_JSON_MESSAGES_FILE_CACHE = {}
def locale_data_file(locale):
path = getattr(settings, 'LOCALE_PATHS')[0]
locale_path = os.path.join(path, locale)
return os.path.join(locale_path, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json")
def get_messages():
global _JSON_MESSAGES_FILE_CACHE
locale = to_locale(get_language())
if locale not in _JSON_MESSAGES_FILE_CACHE:
try:
with open(locale_data_file(locale), 'rb') as data:
message_json = json.load(data)
translation_dict = {}
for key, value in message_json.items():
namespace, key = key.split(".")
translation_dict[namespace] = translation_dict.get(namespace) or {}
translation_dict[namespace][key] = value
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict)
except IOError:
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({})
return _JSON_MESSAGES_FILE_CACHE[locale]
Remove no longer needed local variable. | import json
import os
from django.conf import settings
from django.utils.translation import get_language
from django.utils.translation import to_locale
_JSON_MESSAGES_FILE_CACHE = {}
def locale_data_file(locale):
path = getattr(settings, 'LOCALE_PATHS')[0]
return os.path.join(path, locale, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json")
def get_messages():
global _JSON_MESSAGES_FILE_CACHE
locale = to_locale(get_language())
if locale not in _JSON_MESSAGES_FILE_CACHE:
try:
with open(locale_data_file(locale), 'rb') as data:
message_json = json.load(data)
translation_dict = {}
for key, value in message_json.items():
namespace, key = key.split(".")
translation_dict[namespace] = translation_dict.get(namespace) or {}
translation_dict[namespace][key] = value
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict)
except IOError:
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({})
return _JSON_MESSAGES_FILE_CACHE[locale]
| <commit_before>import json
import os
from django.conf import settings
from django.utils.translation import get_language
from django.utils.translation import to_locale
_JSON_MESSAGES_FILE_CACHE = {}
def locale_data_file(locale):
path = getattr(settings, 'LOCALE_PATHS')[0]
locale_path = os.path.join(path, locale)
return os.path.join(locale_path, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json")
def get_messages():
global _JSON_MESSAGES_FILE_CACHE
locale = to_locale(get_language())
if locale not in _JSON_MESSAGES_FILE_CACHE:
try:
with open(locale_data_file(locale), 'rb') as data:
message_json = json.load(data)
translation_dict = {}
for key, value in message_json.items():
namespace, key = key.split(".")
translation_dict[namespace] = translation_dict.get(namespace) or {}
translation_dict[namespace][key] = value
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict)
except IOError:
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({})
return _JSON_MESSAGES_FILE_CACHE[locale]
<commit_msg>Remove no longer needed local variable.<commit_after> | import json
import os
from django.conf import settings
from django.utils.translation import get_language
from django.utils.translation import to_locale
_JSON_MESSAGES_FILE_CACHE = {}
def locale_data_file(locale):
path = getattr(settings, 'LOCALE_PATHS')[0]
return os.path.join(path, locale, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json")
def get_messages():
global _JSON_MESSAGES_FILE_CACHE
locale = to_locale(get_language())
if locale not in _JSON_MESSAGES_FILE_CACHE:
try:
with open(locale_data_file(locale), 'rb') as data:
message_json = json.load(data)
translation_dict = {}
for key, value in message_json.items():
namespace, key = key.split(".")
translation_dict[namespace] = translation_dict.get(namespace) or {}
translation_dict[namespace][key] = value
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict)
except IOError:
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({})
return _JSON_MESSAGES_FILE_CACHE[locale]
| import json
import os
from django.conf import settings
from django.utils.translation import get_language
from django.utils.translation import to_locale
_JSON_MESSAGES_FILE_CACHE = {}
def locale_data_file(locale):
path = getattr(settings, 'LOCALE_PATHS')[0]
locale_path = os.path.join(path, locale)
return os.path.join(locale_path, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json")
def get_messages():
global _JSON_MESSAGES_FILE_CACHE
locale = to_locale(get_language())
if locale not in _JSON_MESSAGES_FILE_CACHE:
try:
with open(locale_data_file(locale), 'rb') as data:
message_json = json.load(data)
translation_dict = {}
for key, value in message_json.items():
namespace, key = key.split(".")
translation_dict[namespace] = translation_dict.get(namespace) or {}
translation_dict[namespace][key] = value
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict)
except IOError:
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({})
return _JSON_MESSAGES_FILE_CACHE[locale]
Remove no longer needed local variable.import json
import os
from django.conf import settings
from django.utils.translation import get_language
from django.utils.translation import to_locale
_JSON_MESSAGES_FILE_CACHE = {}
def locale_data_file(locale):
path = getattr(settings, 'LOCALE_PATHS')[0]
return os.path.join(path, locale, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json")
def get_messages():
global _JSON_MESSAGES_FILE_CACHE
locale = to_locale(get_language())
if locale not in _JSON_MESSAGES_FILE_CACHE:
try:
with open(locale_data_file(locale), 'rb') as data:
message_json = json.load(data)
translation_dict = {}
for key, value in message_json.items():
namespace, key = key.split(".")
translation_dict[namespace] = translation_dict.get(namespace) or {}
translation_dict[namespace][key] = value
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict)
except IOError:
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({})
return _JSON_MESSAGES_FILE_CACHE[locale]
| <commit_before>import json
import os
from django.conf import settings
from django.utils.translation import get_language
from django.utils.translation import to_locale
_JSON_MESSAGES_FILE_CACHE = {}
def locale_data_file(locale):
path = getattr(settings, 'LOCALE_PATHS')[0]
locale_path = os.path.join(path, locale)
return os.path.join(locale_path, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json")
def get_messages():
global _JSON_MESSAGES_FILE_CACHE
locale = to_locale(get_language())
if locale not in _JSON_MESSAGES_FILE_CACHE:
try:
with open(locale_data_file(locale), 'rb') as data:
message_json = json.load(data)
translation_dict = {}
for key, value in message_json.items():
namespace, key = key.split(".")
translation_dict[namespace] = translation_dict.get(namespace) or {}
translation_dict[namespace][key] = value
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict)
except IOError:
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({})
return _JSON_MESSAGES_FILE_CACHE[locale]
<commit_msg>Remove no longer needed local variable.<commit_after>import json
import os
from django.conf import settings
from django.utils.translation import get_language
from django.utils.translation import to_locale
_JSON_MESSAGES_FILE_CACHE = {}
def locale_data_file(locale):
path = getattr(settings, 'LOCALE_PATHS')[0]
return os.path.join(path, locale, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json")
def get_messages():
global _JSON_MESSAGES_FILE_CACHE
locale = to_locale(get_language())
if locale not in _JSON_MESSAGES_FILE_CACHE:
try:
with open(locale_data_file(locale), 'rb') as data:
message_json = json.load(data)
translation_dict = {}
for key, value in message_json.items():
namespace, key = key.split(".")
translation_dict[namespace] = translation_dict.get(namespace) or {}
translation_dict[namespace][key] = value
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict)
except IOError:
_JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({})
return _JSON_MESSAGES_FILE_CACHE[locale]
|
1c40e03b487ae3dcef9a683de960f9895936d370 | haas/utils.py | haas/utils.py | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import haas
import logging
import sys
LEVELS = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'fatal': logging.FATAL,
'critical': logging.CRITICAL,
}
def configure_logging(level):
actual_level = LEVELS.get(level, logging.WARNING)
format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s'
formatter = logging.Formatter(format_)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
handler.setLevel(actual_level)
logger = logging.getLogger(haas.__name__)
logger.addHandler(handler)
logger.setLevel(actual_level)
logger.info('Logging configured for haas at level %r',
logging.getLevelName(actual_level))
def get_module_by_name(name):
"""Import a module and return the imported module object.
"""
__import__(name)
return sys.modules[name]
| # -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import importlib
import logging
import haas
LEVELS = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'fatal': logging.FATAL,
'critical': logging.CRITICAL,
}
def configure_logging(level):
actual_level = LEVELS.get(level, logging.WARNING)
format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s'
formatter = logging.Formatter(format_)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
handler.setLevel(actual_level)
logger = logging.getLogger(haas.__name__)
logger.addHandler(handler)
logger.setLevel(actual_level)
logger.info('Logging configured for haas at level %r',
logging.getLevelName(actual_level))
def get_module_by_name(name):
"""Import a module and return the imported module object.
"""
return importlib.import_module(name)
| Use importlib instead of __import__ | Use importlib instead of __import__
| Python | bsd-3-clause | itziakos/haas,itziakos/haas,sjagoe/haas,scalative/haas,sjagoe/haas,scalative/haas | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import haas
import logging
import sys
LEVELS = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'fatal': logging.FATAL,
'critical': logging.CRITICAL,
}
def configure_logging(level):
actual_level = LEVELS.get(level, logging.WARNING)
format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s'
formatter = logging.Formatter(format_)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
handler.setLevel(actual_level)
logger = logging.getLogger(haas.__name__)
logger.addHandler(handler)
logger.setLevel(actual_level)
logger.info('Logging configured for haas at level %r',
logging.getLevelName(actual_level))
def get_module_by_name(name):
"""Import a module and return the imported module object.
"""
__import__(name)
return sys.modules[name]
Use importlib instead of __import__ | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import importlib
import logging
import haas
LEVELS = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'fatal': logging.FATAL,
'critical': logging.CRITICAL,
}
def configure_logging(level):
actual_level = LEVELS.get(level, logging.WARNING)
format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s'
formatter = logging.Formatter(format_)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
handler.setLevel(actual_level)
logger = logging.getLogger(haas.__name__)
logger.addHandler(handler)
logger.setLevel(actual_level)
logger.info('Logging configured for haas at level %r',
logging.getLevelName(actual_level))
def get_module_by_name(name):
"""Import a module and return the imported module object.
"""
return importlib.import_module(name)
| <commit_before># -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import haas
import logging
import sys
LEVELS = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'fatal': logging.FATAL,
'critical': logging.CRITICAL,
}
def configure_logging(level):
actual_level = LEVELS.get(level, logging.WARNING)
format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s'
formatter = logging.Formatter(format_)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
handler.setLevel(actual_level)
logger = logging.getLogger(haas.__name__)
logger.addHandler(handler)
logger.setLevel(actual_level)
logger.info('Logging configured for haas at level %r',
logging.getLevelName(actual_level))
def get_module_by_name(name):
"""Import a module and return the imported module object.
"""
__import__(name)
return sys.modules[name]
<commit_msg>Use importlib instead of __import__<commit_after> | # -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import importlib
import logging
import haas
LEVELS = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'fatal': logging.FATAL,
'critical': logging.CRITICAL,
}
def configure_logging(level):
actual_level = LEVELS.get(level, logging.WARNING)
format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s'
formatter = logging.Formatter(format_)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
handler.setLevel(actual_level)
logger = logging.getLogger(haas.__name__)
logger.addHandler(handler)
logger.setLevel(actual_level)
logger.info('Logging configured for haas at level %r',
logging.getLevelName(actual_level))
def get_module_by_name(name):
"""Import a module and return the imported module object.
"""
return importlib.import_module(name)
| # -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import haas
import logging
import sys
LEVELS = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'fatal': logging.FATAL,
'critical': logging.CRITICAL,
}
def configure_logging(level):
actual_level = LEVELS.get(level, logging.WARNING)
format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s'
formatter = logging.Formatter(format_)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
handler.setLevel(actual_level)
logger = logging.getLogger(haas.__name__)
logger.addHandler(handler)
logger.setLevel(actual_level)
logger.info('Logging configured for haas at level %r',
logging.getLevelName(actual_level))
def get_module_by_name(name):
"""Import a module and return the imported module object.
"""
__import__(name)
return sys.modules[name]
Use importlib instead of __import__# -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import importlib
import logging
import haas
LEVELS = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'fatal': logging.FATAL,
'critical': logging.CRITICAL,
}
def configure_logging(level):
actual_level = LEVELS.get(level, logging.WARNING)
format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s'
formatter = logging.Formatter(format_)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
handler.setLevel(actual_level)
logger = logging.getLogger(haas.__name__)
logger.addHandler(handler)
logger.setLevel(actual_level)
logger.info('Logging configured for haas at level %r',
logging.getLevelName(actual_level))
def get_module_by_name(name):
"""Import a module and return the imported module object.
"""
return importlib.import_module(name)
| <commit_before># -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import haas
import logging
import sys
LEVELS = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'fatal': logging.FATAL,
'critical': logging.CRITICAL,
}
def configure_logging(level):
actual_level = LEVELS.get(level, logging.WARNING)
format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s'
formatter = logging.Formatter(format_)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
handler.setLevel(actual_level)
logger = logging.getLogger(haas.__name__)
logger.addHandler(handler)
logger.setLevel(actual_level)
logger.info('Logging configured for haas at level %r',
logging.getLevelName(actual_level))
def get_module_by_name(name):
"""Import a module and return the imported module object.
"""
__import__(name)
return sys.modules[name]
<commit_msg>Use importlib instead of __import__<commit_after># -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import importlib
import logging
import haas
LEVELS = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'fatal': logging.FATAL,
'critical': logging.CRITICAL,
}
def configure_logging(level):
actual_level = LEVELS.get(level, logging.WARNING)
format_ = '%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s'
formatter = logging.Formatter(format_)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
handler.setLevel(actual_level)
logger = logging.getLogger(haas.__name__)
logger.addHandler(handler)
logger.setLevel(actual_level)
logger.info('Logging configured for haas at level %r',
logging.getLevelName(actual_level))
def get_module_by_name(name):
"""Import a module and return the imported module object.
"""
return importlib.import_module(name)
|
7e4fc8857284c539ce91dd53f11b460a6c9b1633 | scrapi/settings/local-dist.py | scrapi/settings/local-dist.py | RAW_PROCESSING = ['cassandra']
NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra']
| RAW_PROCESSING = ['postgres']
NORMALIZED_PROCESSING = ['elasticsearch', 'postgres']
RESPONSE_PROCESSOR = 'postgres'
| Fix local dist to see if that fixes things | Fix local dist to see if that fixes things
| Python | apache-2.0 | erinspace/scrapi,CenterForOpenScience/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi | RAW_PROCESSING = ['cassandra']
NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra']
Fix local dist to see if that fixes things | RAW_PROCESSING = ['postgres']
NORMALIZED_PROCESSING = ['elasticsearch', 'postgres']
RESPONSE_PROCESSOR = 'postgres'
| <commit_before>RAW_PROCESSING = ['cassandra']
NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra']
<commit_msg>Fix local dist to see if that fixes things<commit_after> | RAW_PROCESSING = ['postgres']
NORMALIZED_PROCESSING = ['elasticsearch', 'postgres']
RESPONSE_PROCESSOR = 'postgres'
| RAW_PROCESSING = ['cassandra']
NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra']
Fix local dist to see if that fixes thingsRAW_PROCESSING = ['postgres']
NORMALIZED_PROCESSING = ['elasticsearch', 'postgres']
RESPONSE_PROCESSOR = 'postgres'
| <commit_before>RAW_PROCESSING = ['cassandra']
NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra']
<commit_msg>Fix local dist to see if that fixes things<commit_after>RAW_PROCESSING = ['postgres']
NORMALIZED_PROCESSING = ['elasticsearch', 'postgres']
RESPONSE_PROCESSOR = 'postgres'
|
5303e99508a5c64d3a40cbfd6b6e4c29c74c647f | h2o-py/tests/testdir_misc/pyunit_space_headers.py | h2o-py/tests/testdir_misc/pyunit_space_headers.py | from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
def space_headers():
f = h2o.import_file(path=pyunit_utils.locate("smalldata/jira/citibike_head.csv"))
print(f.names)
f["starttime"].show()
h2o_median = f["start station id"].median()
assert h2o_median == 444, "Expected median for \"start station id\" to be 444, but got {0}".format(h2o_median)
if __name__ == "__main__":
pyunit_utils.standalone_test(space_headers)
else:
space_headers() | from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
def space_headers():
f = h2o.import_file(path=pyunit_utils.locate("smalldata/jira/citibike_head.csv"))
print(f.names)
f["starttime"].show()
h2o_median = f["start station id"].median()
assert h2o_median[0] == 444, "Expected median for \"start station id\" to be 444, but got {0}".format(h2o_median)
if __name__ == "__main__":
pyunit_utils.standalone_test(space_headers)
else:
space_headers() | Update pyunit to compare a list value instead of a scalar | Update pyunit to compare a list value instead of a scalar
| Python | apache-2.0 | h2oai/h2o-dev,jangorecki/h2o-3,h2oai/h2o-3,spennihana/h2o-3,mathemage/h2o-3,jangorecki/h2o-3,michalkurka/h2o-3,mathemage/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,jangorecki/h2o-3,spennihana/h2o-3,jangorecki/h2o-3,jangorecki/h2o-3,h2oai/h2o-3,mathemage/h2o-3,spennihana/h2o-3,mathemage/h2o-3,mathemage/h2o-3,h2oai/h2o-dev,spennihana/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,spennihana/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,jangorecki/h2o-3,h2oai/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,h2oai/h2o-dev,michalkurka/h2o-3,michalkurka/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,jangorecki/h2o-3,mathemage/h2o-3,h2oai/h2o-3,h2oai/h2o-3,mathemage/h2o-3,michalkurka/h2o-3,h2oai/h2o-3 | from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
def space_headers():
f = h2o.import_file(path=pyunit_utils.locate("smalldata/jira/citibike_head.csv"))
print(f.names)
f["starttime"].show()
h2o_median = f["start station id"].median()
assert h2o_median == 444, "Expected median for \"start station id\" to be 444, but got {0}".format(h2o_median)
if __name__ == "__main__":
pyunit_utils.standalone_test(space_headers)
else:
space_headers()Update pyunit to compare a list value instead of a scalar | from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
def space_headers():
f = h2o.import_file(path=pyunit_utils.locate("smalldata/jira/citibike_head.csv"))
print(f.names)
f["starttime"].show()
h2o_median = f["start station id"].median()
assert h2o_median[0] == 444, "Expected median for \"start station id\" to be 444, but got {0}".format(h2o_median)
if __name__ == "__main__":
pyunit_utils.standalone_test(space_headers)
else:
space_headers() | <commit_before>from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
def space_headers():
f = h2o.import_file(path=pyunit_utils.locate("smalldata/jira/citibike_head.csv"))
print(f.names)
f["starttime"].show()
h2o_median = f["start station id"].median()
assert h2o_median == 444, "Expected median for \"start station id\" to be 444, but got {0}".format(h2o_median)
if __name__ == "__main__":
pyunit_utils.standalone_test(space_headers)
else:
space_headers()<commit_msg>Update pyunit to compare a list value instead of a scalar<commit_after> | from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
def space_headers():
f = h2o.import_file(path=pyunit_utils.locate("smalldata/jira/citibike_head.csv"))
print(f.names)
f["starttime"].show()
h2o_median = f["start station id"].median()
assert h2o_median[0] == 444, "Expected median for \"start station id\" to be 444, but got {0}".format(h2o_median)
if __name__ == "__main__":
pyunit_utils.standalone_test(space_headers)
else:
space_headers() | from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
def space_headers():
f = h2o.import_file(path=pyunit_utils.locate("smalldata/jira/citibike_head.csv"))
print(f.names)
f["starttime"].show()
h2o_median = f["start station id"].median()
assert h2o_median == 444, "Expected median for \"start station id\" to be 444, but got {0}".format(h2o_median)
if __name__ == "__main__":
pyunit_utils.standalone_test(space_headers)
else:
space_headers()Update pyunit to compare a list value instead of a scalarfrom __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
def space_headers():
f = h2o.import_file(path=pyunit_utils.locate("smalldata/jira/citibike_head.csv"))
print(f.names)
f["starttime"].show()
h2o_median = f["start station id"].median()
assert h2o_median[0] == 444, "Expected median for \"start station id\" to be 444, but got {0}".format(h2o_median)
if __name__ == "__main__":
pyunit_utils.standalone_test(space_headers)
else:
space_headers() | <commit_before>from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
def space_headers():
f = h2o.import_file(path=pyunit_utils.locate("smalldata/jira/citibike_head.csv"))
print(f.names)
f["starttime"].show()
h2o_median = f["start station id"].median()
assert h2o_median == 444, "Expected median for \"start station id\" to be 444, but got {0}".format(h2o_median)
if __name__ == "__main__":
pyunit_utils.standalone_test(space_headers)
else:
space_headers()<commit_msg>Update pyunit to compare a list value instead of a scalar<commit_after>from __future__ import print_function
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
def space_headers():
f = h2o.import_file(path=pyunit_utils.locate("smalldata/jira/citibike_head.csv"))
print(f.names)
f["starttime"].show()
h2o_median = f["start station id"].median()
assert h2o_median[0] == 444, "Expected median for \"start station id\" to be 444, but got {0}".format(h2o_median)
if __name__ == "__main__":
pyunit_utils.standalone_test(space_headers)
else:
space_headers() |
d293aedf296f4b63cb11ece1c00778981afef20c | pycat/cli.py | pycat/cli.py | """Command-line interface to pycat."""
import argparse
import sys
import socket
from .talk import talk
def argument_parser():
"""Generate an `argparse` argument parser for pycat's arguments."""
parser = argparse.ArgumentParser(description='netcat, in Python')
parser.add_argument('hostname', help='host to which to connect')
parser.add_argument('port', help='port number to which to connect')
return parser
def main(args=sys.argv[1:]):
"""Run, as if from the command-line.
args is a set of arguments to run with, defaulting to taking arguments from
`sys.argv`. It should **not** include the name of the program as the first
argument.
"""
parser = argument_parser()
settings = parser.parse_args(args)
try:
sock = socket.create_connection((settings.hostname, settings.port))
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.setblocking(False)
talk(sock)
except KeyboardInterrupt:
sock.close() # Disregard Control-C, as this is probably how the user will exit.
| """Command-line interface to pycat."""
import argparse
import sys
import socket
from .talk import talk
def argument_parser():
"""Generate an `argparse` argument parser for pycat's arguments."""
parser = argparse.ArgumentParser(description='netcat, in Python')
parser.add_argument('hostname', help='host to which to connect')
parser.add_argument('port', help='port number to which to connect')
return parser
def main(args=sys.argv[1:]):
"""Run, as if from the command-line.
args is a set of arguments to run with, defaulting to taking arguments from
`sys.argv`. It should **not** include the name of the program as the first
argument.
"""
parser = argument_parser()
settings = parser.parse_args(args)
try:
sock = socket.create_connection((settings.hostname, settings.port))
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.setblocking(False)
talk(sock)
except KeyboardInterrupt:
sock.close() # Disregard Control-C, as this is probably how the user will exit.
except ConnectionError as e:
print(str(e), file=sys.stderr)
| Print out nicer error messages on connection errors | Print out nicer error messages on connection errors
| Python | mit | prophile/pycat | """Command-line interface to pycat."""
import argparse
import sys
import socket
from .talk import talk
def argument_parser():
"""Generate an `argparse` argument parser for pycat's arguments."""
parser = argparse.ArgumentParser(description='netcat, in Python')
parser.add_argument('hostname', help='host to which to connect')
parser.add_argument('port', help='port number to which to connect')
return parser
def main(args=sys.argv[1:]):
"""Run, as if from the command-line.
args is a set of arguments to run with, defaulting to taking arguments from
`sys.argv`. It should **not** include the name of the program as the first
argument.
"""
parser = argument_parser()
settings = parser.parse_args(args)
try:
sock = socket.create_connection((settings.hostname, settings.port))
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.setblocking(False)
talk(sock)
except KeyboardInterrupt:
sock.close() # Disregard Control-C, as this is probably how the user will exit.
Print out nicer error messages on connection errors | """Command-line interface to pycat."""
import argparse
import sys
import socket
from .talk import talk
def argument_parser():
"""Generate an `argparse` argument parser for pycat's arguments."""
parser = argparse.ArgumentParser(description='netcat, in Python')
parser.add_argument('hostname', help='host to which to connect')
parser.add_argument('port', help='port number to which to connect')
return parser
def main(args=sys.argv[1:]):
"""Run, as if from the command-line.
args is a set of arguments to run with, defaulting to taking arguments from
`sys.argv`. It should **not** include the name of the program as the first
argument.
"""
parser = argument_parser()
settings = parser.parse_args(args)
try:
sock = socket.create_connection((settings.hostname, settings.port))
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.setblocking(False)
talk(sock)
except KeyboardInterrupt:
sock.close() # Disregard Control-C, as this is probably how the user will exit.
except ConnectionError as e:
print(str(e), file=sys.stderr)
| <commit_before>"""Command-line interface to pycat."""
import argparse
import sys
import socket
from .talk import talk
def argument_parser():
"""Generate an `argparse` argument parser for pycat's arguments."""
parser = argparse.ArgumentParser(description='netcat, in Python')
parser.add_argument('hostname', help='host to which to connect')
parser.add_argument('port', help='port number to which to connect')
return parser
def main(args=sys.argv[1:]):
"""Run, as if from the command-line.
args is a set of arguments to run with, defaulting to taking arguments from
`sys.argv`. It should **not** include the name of the program as the first
argument.
"""
parser = argument_parser()
settings = parser.parse_args(args)
try:
sock = socket.create_connection((settings.hostname, settings.port))
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.setblocking(False)
talk(sock)
except KeyboardInterrupt:
sock.close() # Disregard Control-C, as this is probably how the user will exit.
<commit_msg>Print out nicer error messages on connection errors<commit_after> | """Command-line interface to pycat."""
import argparse
import sys
import socket
from .talk import talk
def argument_parser():
"""Generate an `argparse` argument parser for pycat's arguments."""
parser = argparse.ArgumentParser(description='netcat, in Python')
parser.add_argument('hostname', help='host to which to connect')
parser.add_argument('port', help='port number to which to connect')
return parser
def main(args=sys.argv[1:]):
"""Run, as if from the command-line.
args is a set of arguments to run with, defaulting to taking arguments from
`sys.argv`. It should **not** include the name of the program as the first
argument.
"""
parser = argument_parser()
settings = parser.parse_args(args)
try:
sock = socket.create_connection((settings.hostname, settings.port))
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.setblocking(False)
talk(sock)
except KeyboardInterrupt:
sock.close() # Disregard Control-C, as this is probably how the user will exit.
except ConnectionError as e:
print(str(e), file=sys.stderr)
| """Command-line interface to pycat."""
import argparse
import sys
import socket
from .talk import talk
def argument_parser():
"""Generate an `argparse` argument parser for pycat's arguments."""
parser = argparse.ArgumentParser(description='netcat, in Python')
parser.add_argument('hostname', help='host to which to connect')
parser.add_argument('port', help='port number to which to connect')
return parser
def main(args=sys.argv[1:]):
"""Run, as if from the command-line.
args is a set of arguments to run with, defaulting to taking arguments from
`sys.argv`. It should **not** include the name of the program as the first
argument.
"""
parser = argument_parser()
settings = parser.parse_args(args)
try:
sock = socket.create_connection((settings.hostname, settings.port))
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.setblocking(False)
talk(sock)
except KeyboardInterrupt:
sock.close() # Disregard Control-C, as this is probably how the user will exit.
Print out nicer error messages on connection errors"""Command-line interface to pycat."""
import argparse
import sys
import socket
from .talk import talk
def argument_parser():
"""Generate an `argparse` argument parser for pycat's arguments."""
parser = argparse.ArgumentParser(description='netcat, in Python')
parser.add_argument('hostname', help='host to which to connect')
parser.add_argument('port', help='port number to which to connect')
return parser
def main(args=sys.argv[1:]):
"""Run, as if from the command-line.
args is a set of arguments to run with, defaulting to taking arguments from
`sys.argv`. It should **not** include the name of the program as the first
argument.
"""
parser = argument_parser()
settings = parser.parse_args(args)
try:
sock = socket.create_connection((settings.hostname, settings.port))
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.setblocking(False)
talk(sock)
except KeyboardInterrupt:
sock.close() # Disregard Control-C, as this is probably how the user will exit.
except ConnectionError as e:
print(str(e), file=sys.stderr)
| <commit_before>"""Command-line interface to pycat."""
import argparse
import sys
import socket
from .talk import talk
def argument_parser():
"""Generate an `argparse` argument parser for pycat's arguments."""
parser = argparse.ArgumentParser(description='netcat, in Python')
parser.add_argument('hostname', help='host to which to connect')
parser.add_argument('port', help='port number to which to connect')
return parser
def main(args=sys.argv[1:]):
"""Run, as if from the command-line.
args is a set of arguments to run with, defaulting to taking arguments from
`sys.argv`. It should **not** include the name of the program as the first
argument.
"""
parser = argument_parser()
settings = parser.parse_args(args)
try:
sock = socket.create_connection((settings.hostname, settings.port))
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.setblocking(False)
talk(sock)
except KeyboardInterrupt:
sock.close() # Disregard Control-C, as this is probably how the user will exit.
<commit_msg>Print out nicer error messages on connection errors<commit_after>"""Command-line interface to pycat."""
import argparse
import sys
import socket
from .talk import talk
def argument_parser():
"""Generate an `argparse` argument parser for pycat's arguments."""
parser = argparse.ArgumentParser(description='netcat, in Python')
parser.add_argument('hostname', help='host to which to connect')
parser.add_argument('port', help='port number to which to connect')
return parser
def main(args=sys.argv[1:]):
"""Run, as if from the command-line.
args is a set of arguments to run with, defaulting to taking arguments from
`sys.argv`. It should **not** include the name of the program as the first
argument.
"""
parser = argument_parser()
settings = parser.parse_args(args)
try:
sock = socket.create_connection((settings.hostname, settings.port))
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.setblocking(False)
talk(sock)
except KeyboardInterrupt:
sock.close() # Disregard Control-C, as this is probably how the user will exit.
except ConnectionError as e:
print(str(e), file=sys.stderr)
|
5b43264321e4649312050264524a6df7682a6641 | mfr/ext/md/tests/test_md.py | mfr/ext/md/tests/test_md.py | from mfr.ext.md import Handler, render
from mock import MagicMock
def test_render_html():
fakefile = MagicMock(spec=file)
fakefile.read.return_value = '# foo'
assert render.render_html(fakefile) == '<h1>foo</h1>'
fakefile.read.return_value = '_italic_'
assert render.render_html(fakefile) == '<p><em>italic</em></p>'
fakefile.read.return_value = '*italic*'
assert render.render_html(fakefile) == '<p><em>italic</em></p>'
fakefile.read.return_value = '''
* one
* two'''
assert render.render_html(fakefile) == '''<ul>
<li>one</li>
<li>two</li>
</ul>'''
def test_detect(fakefile):
test_handler=Handler()
fakefile.name='file.notmd'
assert test_handler.detect(fakefile) is False
fakefile.name='file.md'
assert test_handler.detect(fakefile) is True
fakefile.name='file.markdown'
assert test_handler.detect(fakefile) is True
| from mfr.ext.md import Handler, render
from mock import MagicMock
def test_render_html():
fakefile = MagicMock(spec=file)
fakefile.read.return_value = '# foo'
assert render.render_html(fakefile).content == '<h1>foo</h1>'
fakefile.read.return_value = '_italic_'
assert render.render_html(fakefile).content == '<p><em>italic</em></p>'
fakefile.read.return_value = '*italic*'
assert render.render_html(fakefile).content == '<p><em>italic</em></p>'
fakefile.read.return_value = '''
* one
* two'''
assert render.render_html(fakefile).content == '''<ul>
<li>one</li>
<li>two</li>
</ul>'''
def test_detect(fakefile):
test_handler=Handler()
fakefile.name='file.notmd'
assert test_handler.detect(fakefile) is False
fakefile.name='file.md'
assert test_handler.detect(fakefile) is True
fakefile.name='file.markdown'
assert test_handler.detect(fakefile) is True
| Update md test for render fix | Update md test for render fix
| Python | apache-2.0 | CenterForOpenScience/modular-file-renderer,mfraezz/modular-file-renderer,Johnetordoff/modular-file-renderer,AddisonSchiller/modular-file-renderer,mfraezz/modular-file-renderer,rdhyee/modular-file-renderer,icereval/modular-file-renderer,TomBaxter/modular-file-renderer,Johnetordoff/modular-file-renderer,rdhyee/modular-file-renderer,rdhyee/modular-file-renderer,Johnetordoff/modular-file-renderer,rdhyee/modular-file-renderer,AddisonSchiller/modular-file-renderer,icereval/modular-file-renderer,haoyuchen1992/modular-file-renderer,AddisonSchiller/modular-file-renderer,felliott/modular-file-renderer,Johnetordoff/modular-file-renderer,TomBaxter/modular-file-renderer,haoyuchen1992/modular-file-renderer,haoyuchen1992/modular-file-renderer,mfraezz/modular-file-renderer,TomBaxter/modular-file-renderer,CenterForOpenScience/modular-file-renderer,felliott/modular-file-renderer,icereval/modular-file-renderer,haoyuchen1992/modular-file-renderer,felliott/modular-file-renderer,mfraezz/modular-file-renderer,TomBaxter/modular-file-renderer,CenterForOpenScience/modular-file-renderer,CenterForOpenScience/modular-file-renderer,AddisonSchiller/modular-file-renderer,felliott/modular-file-renderer | from mfr.ext.md import Handler, render
from mock import MagicMock
def test_render_html():
fakefile = MagicMock(spec=file)
fakefile.read.return_value = '# foo'
assert render.render_html(fakefile) == '<h1>foo</h1>'
fakefile.read.return_value = '_italic_'
assert render.render_html(fakefile) == '<p><em>italic</em></p>'
fakefile.read.return_value = '*italic*'
assert render.render_html(fakefile) == '<p><em>italic</em></p>'
fakefile.read.return_value = '''
* one
* two'''
assert render.render_html(fakefile) == '''<ul>
<li>one</li>
<li>two</li>
</ul>'''
def test_detect(fakefile):
test_handler=Handler()
fakefile.name='file.notmd'
assert test_handler.detect(fakefile) is False
fakefile.name='file.md'
assert test_handler.detect(fakefile) is True
fakefile.name='file.markdown'
assert test_handler.detect(fakefile) is True
Update md test for render fix | from mfr.ext.md import Handler, render
from mock import MagicMock
def test_render_html():
fakefile = MagicMock(spec=file)
fakefile.read.return_value = '# foo'
assert render.render_html(fakefile).content == '<h1>foo</h1>'
fakefile.read.return_value = '_italic_'
assert render.render_html(fakefile).content == '<p><em>italic</em></p>'
fakefile.read.return_value = '*italic*'
assert render.render_html(fakefile).content == '<p><em>italic</em></p>'
fakefile.read.return_value = '''
* one
* two'''
assert render.render_html(fakefile).content == '''<ul>
<li>one</li>
<li>two</li>
</ul>'''
def test_detect(fakefile):
test_handler=Handler()
fakefile.name='file.notmd'
assert test_handler.detect(fakefile) is False
fakefile.name='file.md'
assert test_handler.detect(fakefile) is True
fakefile.name='file.markdown'
assert test_handler.detect(fakefile) is True
| <commit_before>from mfr.ext.md import Handler, render
from mock import MagicMock
def test_render_html():
fakefile = MagicMock(spec=file)
fakefile.read.return_value = '# foo'
assert render.render_html(fakefile) == '<h1>foo</h1>'
fakefile.read.return_value = '_italic_'
assert render.render_html(fakefile) == '<p><em>italic</em></p>'
fakefile.read.return_value = '*italic*'
assert render.render_html(fakefile) == '<p><em>italic</em></p>'
fakefile.read.return_value = '''
* one
* two'''
assert render.render_html(fakefile) == '''<ul>
<li>one</li>
<li>two</li>
</ul>'''
def test_detect(fakefile):
test_handler=Handler()
fakefile.name='file.notmd'
assert test_handler.detect(fakefile) is False
fakefile.name='file.md'
assert test_handler.detect(fakefile) is True
fakefile.name='file.markdown'
assert test_handler.detect(fakefile) is True
<commit_msg>Update md test for render fix<commit_after> | from mfr.ext.md import Handler, render
from mock import MagicMock
def test_render_html():
fakefile = MagicMock(spec=file)
fakefile.read.return_value = '# foo'
assert render.render_html(fakefile).content == '<h1>foo</h1>'
fakefile.read.return_value = '_italic_'
assert render.render_html(fakefile).content == '<p><em>italic</em></p>'
fakefile.read.return_value = '*italic*'
assert render.render_html(fakefile).content == '<p><em>italic</em></p>'
fakefile.read.return_value = '''
* one
* two'''
assert render.render_html(fakefile).content == '''<ul>
<li>one</li>
<li>two</li>
</ul>'''
def test_detect(fakefile):
test_handler=Handler()
fakefile.name='file.notmd'
assert test_handler.detect(fakefile) is False
fakefile.name='file.md'
assert test_handler.detect(fakefile) is True
fakefile.name='file.markdown'
assert test_handler.detect(fakefile) is True
| from mfr.ext.md import Handler, render
from mock import MagicMock
def test_render_html():
fakefile = MagicMock(spec=file)
fakefile.read.return_value = '# foo'
assert render.render_html(fakefile) == '<h1>foo</h1>'
fakefile.read.return_value = '_italic_'
assert render.render_html(fakefile) == '<p><em>italic</em></p>'
fakefile.read.return_value = '*italic*'
assert render.render_html(fakefile) == '<p><em>italic</em></p>'
fakefile.read.return_value = '''
* one
* two'''
assert render.render_html(fakefile) == '''<ul>
<li>one</li>
<li>two</li>
</ul>'''
def test_detect(fakefile):
test_handler=Handler()
fakefile.name='file.notmd'
assert test_handler.detect(fakefile) is False
fakefile.name='file.md'
assert test_handler.detect(fakefile) is True
fakefile.name='file.markdown'
assert test_handler.detect(fakefile) is True
Update md test for render fixfrom mfr.ext.md import Handler, render
from mock import MagicMock
def test_render_html():
fakefile = MagicMock(spec=file)
fakefile.read.return_value = '# foo'
assert render.render_html(fakefile).content == '<h1>foo</h1>'
fakefile.read.return_value = '_italic_'
assert render.render_html(fakefile).content == '<p><em>italic</em></p>'
fakefile.read.return_value = '*italic*'
assert render.render_html(fakefile).content == '<p><em>italic</em></p>'
fakefile.read.return_value = '''
* one
* two'''
assert render.render_html(fakefile).content == '''<ul>
<li>one</li>
<li>two</li>
</ul>'''
def test_detect(fakefile):
test_handler=Handler()
fakefile.name='file.notmd'
assert test_handler.detect(fakefile) is False
fakefile.name='file.md'
assert test_handler.detect(fakefile) is True
fakefile.name='file.markdown'
assert test_handler.detect(fakefile) is True
| <commit_before>from mfr.ext.md import Handler, render
from mock import MagicMock
def test_render_html():
fakefile = MagicMock(spec=file)
fakefile.read.return_value = '# foo'
assert render.render_html(fakefile) == '<h1>foo</h1>'
fakefile.read.return_value = '_italic_'
assert render.render_html(fakefile) == '<p><em>italic</em></p>'
fakefile.read.return_value = '*italic*'
assert render.render_html(fakefile) == '<p><em>italic</em></p>'
fakefile.read.return_value = '''
* one
* two'''
assert render.render_html(fakefile) == '''<ul>
<li>one</li>
<li>two</li>
</ul>'''
def test_detect(fakefile):
test_handler=Handler()
fakefile.name='file.notmd'
assert test_handler.detect(fakefile) is False
fakefile.name='file.md'
assert test_handler.detect(fakefile) is True
fakefile.name='file.markdown'
assert test_handler.detect(fakefile) is True
<commit_msg>Update md test for render fix<commit_after>from mfr.ext.md import Handler, render
from mock import MagicMock
def test_render_html():
fakefile = MagicMock(spec=file)
fakefile.read.return_value = '# foo'
assert render.render_html(fakefile).content == '<h1>foo</h1>'
fakefile.read.return_value = '_italic_'
assert render.render_html(fakefile).content == '<p><em>italic</em></p>'
fakefile.read.return_value = '*italic*'
assert render.render_html(fakefile).content == '<p><em>italic</em></p>'
fakefile.read.return_value = '''
* one
* two'''
assert render.render_html(fakefile).content == '''<ul>
<li>one</li>
<li>two</li>
</ul>'''
def test_detect(fakefile):
test_handler=Handler()
fakefile.name='file.notmd'
assert test_handler.detect(fakefile) is False
fakefile.name='file.md'
assert test_handler.detect(fakefile) is True
fakefile.name='file.markdown'
assert test_handler.detect(fakefile) is True
|
01385f012f984d8a04d3cd9c71ca3cf582a9bf5d | package_name/module.py | package_name/module.py | """
Module provides a simple cubic_rectification function.
"""
import numpy as np
def cubic_rectification(x):
"""
Rectified cube of an array.
Parameters
----------
x : numpy.ndarray
Input array.
Returns
-------
numpy.ndarray
Elementwise, the cube of `x` where it is positive and `0` otherwise.
Note
----
This is a sample function, using a Google docstring format.
Note
----
The use of intersphinx will cause numpy.ndarray above to link to its
documentation, but not inside this Note.
"""
return np.maximum(0, x ** 3)
| """
Module provides a simple cubic_rectification function.
"""
import numpy as np
def cubic_rectification(x):
"""
Rectified cube of an array.
Parameters
----------
x : numpy.ndarray
Input array.
Returns
-------
numpy.ndarray
Elementwise, the cube of `x` where it is positive and `0` otherwise.
Note
----
This is a sample function, using a numpy docstring format.
Note
----
The use of intersphinx will cause numpy.ndarray above to link to its
documentation, but not inside this Note.
"""
return np.maximum(0, x ** 3)
| Change comment Google -> numpy docstring format | DOC: Change comment Google -> numpy docstring format
| Python | mit | scottclowe/python-ci,scottclowe/python-continuous-integration,scottclowe/python-ci,scottclowe/python-continuous-integration | """
Module provides a simple cubic_rectification function.
"""
import numpy as np
def cubic_rectification(x):
"""
Rectified cube of an array.
Parameters
----------
x : numpy.ndarray
Input array.
Returns
-------
numpy.ndarray
Elementwise, the cube of `x` where it is positive and `0` otherwise.
Note
----
This is a sample function, using a Google docstring format.
Note
----
The use of intersphinx will cause numpy.ndarray above to link to its
documentation, but not inside this Note.
"""
return np.maximum(0, x ** 3)
DOC: Change comment Google -> numpy docstring format | """
Module provides a simple cubic_rectification function.
"""
import numpy as np
def cubic_rectification(x):
"""
Rectified cube of an array.
Parameters
----------
x : numpy.ndarray
Input array.
Returns
-------
numpy.ndarray
Elementwise, the cube of `x` where it is positive and `0` otherwise.
Note
----
This is a sample function, using a numpy docstring format.
Note
----
The use of intersphinx will cause numpy.ndarray above to link to its
documentation, but not inside this Note.
"""
return np.maximum(0, x ** 3)
| <commit_before>"""
Module provides a simple cubic_rectification function.
"""
import numpy as np
def cubic_rectification(x):
"""
Rectified cube of an array.
Parameters
----------
x : numpy.ndarray
Input array.
Returns
-------
numpy.ndarray
Elementwise, the cube of `x` where it is positive and `0` otherwise.
Note
----
This is a sample function, using a Google docstring format.
Note
----
The use of intersphinx will cause numpy.ndarray above to link to its
documentation, but not inside this Note.
"""
return np.maximum(0, x ** 3)
<commit_msg>DOC: Change comment Google -> numpy docstring format<commit_after> | """
Module provides a simple cubic_rectification function.
"""
import numpy as np
def cubic_rectification(x):
"""
Rectified cube of an array.
Parameters
----------
x : numpy.ndarray
Input array.
Returns
-------
numpy.ndarray
Elementwise, the cube of `x` where it is positive and `0` otherwise.
Note
----
This is a sample function, using a numpy docstring format.
Note
----
The use of intersphinx will cause numpy.ndarray above to link to its
documentation, but not inside this Note.
"""
return np.maximum(0, x ** 3)
| """
Module provides a simple cubic_rectification function.
"""
import numpy as np
def cubic_rectification(x):
"""
Rectified cube of an array.
Parameters
----------
x : numpy.ndarray
Input array.
Returns
-------
numpy.ndarray
Elementwise, the cube of `x` where it is positive and `0` otherwise.
Note
----
This is a sample function, using a Google docstring format.
Note
----
The use of intersphinx will cause numpy.ndarray above to link to its
documentation, but not inside this Note.
"""
return np.maximum(0, x ** 3)
DOC: Change comment Google -> numpy docstring format"""
Module provides a simple cubic_rectification function.
"""
import numpy as np
def cubic_rectification(x):
"""
Rectified cube of an array.
Parameters
----------
x : numpy.ndarray
Input array.
Returns
-------
numpy.ndarray
Elementwise, the cube of `x` where it is positive and `0` otherwise.
Note
----
This is a sample function, using a numpy docstring format.
Note
----
The use of intersphinx will cause numpy.ndarray above to link to its
documentation, but not inside this Note.
"""
return np.maximum(0, x ** 3)
| <commit_before>"""
Module provides a simple cubic_rectification function.
"""
import numpy as np
def cubic_rectification(x):
"""
Rectified cube of an array.
Parameters
----------
x : numpy.ndarray
Input array.
Returns
-------
numpy.ndarray
Elementwise, the cube of `x` where it is positive and `0` otherwise.
Note
----
This is a sample function, using a Google docstring format.
Note
----
The use of intersphinx will cause numpy.ndarray above to link to its
documentation, but not inside this Note.
"""
return np.maximum(0, x ** 3)
<commit_msg>DOC: Change comment Google -> numpy docstring format<commit_after>"""
Module provides a simple cubic_rectification function.
"""
import numpy as np
def cubic_rectification(x):
"""
Rectified cube of an array.
Parameters
----------
x : numpy.ndarray
Input array.
Returns
-------
numpy.ndarray
Elementwise, the cube of `x` where it is positive and `0` otherwise.
Note
----
This is a sample function, using a numpy docstring format.
Note
----
The use of intersphinx will cause numpy.ndarray above to link to its
documentation, but not inside this Note.
"""
return np.maximum(0, x ** 3)
|
76e5d94e12717db685b0c0c66e893d7e4365a57b | examples/connect.py | examples/connect.py | #!/usr/bin/python
# Copyright 2010 Jonathan Kinred
#
# 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 psphere.client import Client
from psphere.scripting import BaseScript
class Connect(BaseScript):
def connect(self):
"""A simple connection test to login and print the server time."""
print(self.client.si.CurrentTime())
def main():
client = Client()
print('Successfully connected to %s' % client.server)
c = Connect(client)
c.connect()
client.logout()
if __name__ == '__main__':
main()
| #!/usr/bin/python
# Copyright 2010 Jonathan Kinred
#
# 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 psphere import config
from psphere.client import Client
def main(options):
"""A simple connection test to login and print the server time."""
server = config._config_value("general", "server", options.server)
if server is None:
raise ValueError("server must be supplied on command line"
" or in configuration file.")
username = config._config_value("general", "username", options.username)
if username is None:
raise ValueError("username must be supplied on command line"
" or in configuration file.")
password = config._config_value("general", "password", options.password)
if password is None:
raise ValueError("password must be supplied on command line"
" or in configuration file.")
client = Client(server=server, username=username, password=password)
print('Successfully connected to %s' % client.server)
print(client.si.CurrentTime())
client.logout()
if __name__ == "__main__":
from optparse import OptionParser
usage = "Usage: %prog [options]"
parser = OptionParser(usage=usage)
parser.add_option("--server", dest="server",
help="The server to connect to for provisioning")
parser.add_option("--username", dest="username",
help="The username used to connect to the server")
parser.add_option("--password", dest="password",
help="The password used to connect to the server")
(options, args) = parser.parse_args()
main(options)
| Update the script to accept arguments | Update the script to accept arguments
| Python | apache-2.0 | graphite-server/psphere,jkinred/psphere | #!/usr/bin/python
# Copyright 2010 Jonathan Kinred
#
# 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 psphere.client import Client
from psphere.scripting import BaseScript
class Connect(BaseScript):
def connect(self):
"""A simple connection test to login and print the server time."""
print(self.client.si.CurrentTime())
def main():
client = Client()
print('Successfully connected to %s' % client.server)
c = Connect(client)
c.connect()
client.logout()
if __name__ == '__main__':
main()
Update the script to accept arguments | #!/usr/bin/python
# Copyright 2010 Jonathan Kinred
#
# 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 psphere import config
from psphere.client import Client
def main(options):
"""A simple connection test to login and print the server time."""
server = config._config_value("general", "server", options.server)
if server is None:
raise ValueError("server must be supplied on command line"
" or in configuration file.")
username = config._config_value("general", "username", options.username)
if username is None:
raise ValueError("username must be supplied on command line"
" or in configuration file.")
password = config._config_value("general", "password", options.password)
if password is None:
raise ValueError("password must be supplied on command line"
" or in configuration file.")
client = Client(server=server, username=username, password=password)
print('Successfully connected to %s' % client.server)
print(client.si.CurrentTime())
client.logout()
if __name__ == "__main__":
from optparse import OptionParser
usage = "Usage: %prog [options]"
parser = OptionParser(usage=usage)
parser.add_option("--server", dest="server",
help="The server to connect to for provisioning")
parser.add_option("--username", dest="username",
help="The username used to connect to the server")
parser.add_option("--password", dest="password",
help="The password used to connect to the server")
(options, args) = parser.parse_args()
main(options)
| <commit_before>#!/usr/bin/python
# Copyright 2010 Jonathan Kinred
#
# 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 psphere.client import Client
from psphere.scripting import BaseScript
class Connect(BaseScript):
def connect(self):
"""A simple connection test to login and print the server time."""
print(self.client.si.CurrentTime())
def main():
client = Client()
print('Successfully connected to %s' % client.server)
c = Connect(client)
c.connect()
client.logout()
if __name__ == '__main__':
main()
<commit_msg>Update the script to accept arguments<commit_after> | #!/usr/bin/python
# Copyright 2010 Jonathan Kinred
#
# 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 psphere import config
from psphere.client import Client
def main(options):
"""A simple connection test to login and print the server time."""
server = config._config_value("general", "server", options.server)
if server is None:
raise ValueError("server must be supplied on command line"
" or in configuration file.")
username = config._config_value("general", "username", options.username)
if username is None:
raise ValueError("username must be supplied on command line"
" or in configuration file.")
password = config._config_value("general", "password", options.password)
if password is None:
raise ValueError("password must be supplied on command line"
" or in configuration file.")
client = Client(server=server, username=username, password=password)
print('Successfully connected to %s' % client.server)
print(client.si.CurrentTime())
client.logout()
if __name__ == "__main__":
from optparse import OptionParser
usage = "Usage: %prog [options]"
parser = OptionParser(usage=usage)
parser.add_option("--server", dest="server",
help="The server to connect to for provisioning")
parser.add_option("--username", dest="username",
help="The username used to connect to the server")
parser.add_option("--password", dest="password",
help="The password used to connect to the server")
(options, args) = parser.parse_args()
main(options)
| #!/usr/bin/python
# Copyright 2010 Jonathan Kinred
#
# 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 psphere.client import Client
from psphere.scripting import BaseScript
class Connect(BaseScript):
def connect(self):
"""A simple connection test to login and print the server time."""
print(self.client.si.CurrentTime())
def main():
client = Client()
print('Successfully connected to %s' % client.server)
c = Connect(client)
c.connect()
client.logout()
if __name__ == '__main__':
main()
Update the script to accept arguments#!/usr/bin/python
# Copyright 2010 Jonathan Kinred
#
# 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 psphere import config
from psphere.client import Client
def main(options):
"""A simple connection test to login and print the server time."""
server = config._config_value("general", "server", options.server)
if server is None:
raise ValueError("server must be supplied on command line"
" or in configuration file.")
username = config._config_value("general", "username", options.username)
if username is None:
raise ValueError("username must be supplied on command line"
" or in configuration file.")
password = config._config_value("general", "password", options.password)
if password is None:
raise ValueError("password must be supplied on command line"
" or in configuration file.")
client = Client(server=server, username=username, password=password)
print('Successfully connected to %s' % client.server)
print(client.si.CurrentTime())
client.logout()
if __name__ == "__main__":
from optparse import OptionParser
usage = "Usage: %prog [options]"
parser = OptionParser(usage=usage)
parser.add_option("--server", dest="server",
help="The server to connect to for provisioning")
parser.add_option("--username", dest="username",
help="The username used to connect to the server")
parser.add_option("--password", dest="password",
help="The password used to connect to the server")
(options, args) = parser.parse_args()
main(options)
| <commit_before>#!/usr/bin/python
# Copyright 2010 Jonathan Kinred
#
# 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 psphere.client import Client
from psphere.scripting import BaseScript
class Connect(BaseScript):
def connect(self):
"""A simple connection test to login and print the server time."""
print(self.client.si.CurrentTime())
def main():
client = Client()
print('Successfully connected to %s' % client.server)
c = Connect(client)
c.connect()
client.logout()
if __name__ == '__main__':
main()
<commit_msg>Update the script to accept arguments<commit_after>#!/usr/bin/python
# Copyright 2010 Jonathan Kinred
#
# 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 psphere import config
from psphere.client import Client
def main(options):
"""A simple connection test to login and print the server time."""
server = config._config_value("general", "server", options.server)
if server is None:
raise ValueError("server must be supplied on command line"
" or in configuration file.")
username = config._config_value("general", "username", options.username)
if username is None:
raise ValueError("username must be supplied on command line"
" or in configuration file.")
password = config._config_value("general", "password", options.password)
if password is None:
raise ValueError("password must be supplied on command line"
" or in configuration file.")
client = Client(server=server, username=username, password=password)
print('Successfully connected to %s' % client.server)
print(client.si.CurrentTime())
client.logout()
if __name__ == "__main__":
from optparse import OptionParser
usage = "Usage: %prog [options]"
parser = OptionParser(usage=usage)
parser.add_option("--server", dest="server",
help="The server to connect to for provisioning")
parser.add_option("--username", dest="username",
help="The username used to connect to the server")
parser.add_option("--password", dest="password",
help="The password used to connect to the server")
(options, args) = parser.parse_args()
main(options)
|
756e11445b3f1ba52f3c3be7029fd172d6527722 | run_tests.py | run_tests.py | import sys
import os
import subprocess
def main():
executableName = 'CuraEngine'
if len(sys.argv) > 1:
executableName = sys.argv[1]
exitValue = 0
for subPath in os.listdir('testcase_models'):
print 'Running test on %s' % (subPath)
ret = subprocess.call([executableName, os.path.join('testcase_models', subPath)])
if ret != 0:
exitValue = 1
sys.exit(exitValue)
if __name__ == '__main__':
main()
| import sys
import os
import subprocess
def main():
executableName = './CuraEngine'
if len(sys.argv) > 1:
executableName = sys.argv[1]
exitValue = 0
for subPath in os.listdir('testcase_models'):
print 'Running test on %s' % (subPath)
ret = subprocess.call([executableName, os.path.join('testcase_models', subPath), '-o', 'temp.gcode'])
if ret != 0:
exitValue = 1
sys.exit(exitValue)
if __name__ == '__main__':
main()
| Fix the python script that runs the tests. | Fix the python script that runs the tests.
| Python | agpl-3.0 | ROBO3D/CuraEngine,electrocbd/CuraEngine,derekhe/CuraEngine,alephobjects/CuraEngine,Jwis921/PersonalCuraEngine,pratikshashroff/pcura,Jwis921/PersonalCuraEngine,totalretribution/CuraEngine,Skeen/CuraJS-Engine,uus169/CuraEngine,pratikshashroff/pcura,Jwis921/PersonalCuraEngine,patrick3coffee/CuraTinyG,be3d/CuraEngine,phonyphonecall/CuraEngine,daid/CuraCutEngine,robotustra/curax,ROBO3D/CuraEngine,patrick3coffee/CuraTinyG,jacobdai/CuraEngine-1,derekhe/CuraEngine,fxtentacle/CuraEngine,mspark93/CuraEngine,markwal/CuraEngine,foosel/CuraEngine,fxtentacle/CuraEngine,be3d/CuraEngine,alex1818/CuraEngine,Ultimaker/CuraEngine,pratikshashroff/pcura,foosel/CuraEngine,alephobjects/CuraEngine,electrocbd/CuraEngine,mspark93/CuraEngine,alex1818/CuraEngine,be3d/CuraEngine,jacobdai/CuraEngine-1,markwal/CuraEngine,mspark93/CuraEngine,Ultimaker/CuraEngine,derekhe/CuraEngine,phonyphonecall/CuraEngine,Skeen/CuraJS-Engine,patrick3coffee/CuraTinyG,Intrinsically-Sublime/CuraEngine,Intrinsically-Sublime/CuraEngine,Intrinsically-Sublime/CuraEngine,phonyphonecall/CuraEngine,uus169/CuraEngine,alephobjects/CuraEngine,daid/CuraCutEngine,ROBO3D/CuraEngine,markwal/CuraEngine,totalretribution/CuraEngine,fxtentacle/CuraEngine,robotustra/curax,jacobdai/CuraEngine-1,electrocbd/CuraEngine,robotustra/curax,uus169/CuraEngine,Skeen/CuraJS-Engine,totalretribution/CuraEngine,alex1818/CuraEngine,foosel/CuraEngine | import sys
import os
import subprocess
def main():
executableName = 'CuraEngine'
if len(sys.argv) > 1:
executableName = sys.argv[1]
exitValue = 0
for subPath in os.listdir('testcase_models'):
print 'Running test on %s' % (subPath)
ret = subprocess.call([executableName, os.path.join('testcase_models', subPath)])
if ret != 0:
exitValue = 1
sys.exit(exitValue)
if __name__ == '__main__':
main()
Fix the python script that runs the tests. | import sys
import os
import subprocess
def main():
executableName = './CuraEngine'
if len(sys.argv) > 1:
executableName = sys.argv[1]
exitValue = 0
for subPath in os.listdir('testcase_models'):
print 'Running test on %s' % (subPath)
ret = subprocess.call([executableName, os.path.join('testcase_models', subPath), '-o', 'temp.gcode'])
if ret != 0:
exitValue = 1
sys.exit(exitValue)
if __name__ == '__main__':
main()
| <commit_before>import sys
import os
import subprocess
def main():
executableName = 'CuraEngine'
if len(sys.argv) > 1:
executableName = sys.argv[1]
exitValue = 0
for subPath in os.listdir('testcase_models'):
print 'Running test on %s' % (subPath)
ret = subprocess.call([executableName, os.path.join('testcase_models', subPath)])
if ret != 0:
exitValue = 1
sys.exit(exitValue)
if __name__ == '__main__':
main()
<commit_msg>Fix the python script that runs the tests.<commit_after> | import sys
import os
import subprocess
def main():
executableName = './CuraEngine'
if len(sys.argv) > 1:
executableName = sys.argv[1]
exitValue = 0
for subPath in os.listdir('testcase_models'):
print 'Running test on %s' % (subPath)
ret = subprocess.call([executableName, os.path.join('testcase_models', subPath), '-o', 'temp.gcode'])
if ret != 0:
exitValue = 1
sys.exit(exitValue)
if __name__ == '__main__':
main()
| import sys
import os
import subprocess
def main():
executableName = 'CuraEngine'
if len(sys.argv) > 1:
executableName = sys.argv[1]
exitValue = 0
for subPath in os.listdir('testcase_models'):
print 'Running test on %s' % (subPath)
ret = subprocess.call([executableName, os.path.join('testcase_models', subPath)])
if ret != 0:
exitValue = 1
sys.exit(exitValue)
if __name__ == '__main__':
main()
Fix the python script that runs the tests.import sys
import os
import subprocess
def main():
executableName = './CuraEngine'
if len(sys.argv) > 1:
executableName = sys.argv[1]
exitValue = 0
for subPath in os.listdir('testcase_models'):
print 'Running test on %s' % (subPath)
ret = subprocess.call([executableName, os.path.join('testcase_models', subPath), '-o', 'temp.gcode'])
if ret != 0:
exitValue = 1
sys.exit(exitValue)
if __name__ == '__main__':
main()
| <commit_before>import sys
import os
import subprocess
def main():
executableName = 'CuraEngine'
if len(sys.argv) > 1:
executableName = sys.argv[1]
exitValue = 0
for subPath in os.listdir('testcase_models'):
print 'Running test on %s' % (subPath)
ret = subprocess.call([executableName, os.path.join('testcase_models', subPath)])
if ret != 0:
exitValue = 1
sys.exit(exitValue)
if __name__ == '__main__':
main()
<commit_msg>Fix the python script that runs the tests.<commit_after>import sys
import os
import subprocess
def main():
executableName = './CuraEngine'
if len(sys.argv) > 1:
executableName = sys.argv[1]
exitValue = 0
for subPath in os.listdir('testcase_models'):
print 'Running test on %s' % (subPath)
ret = subprocess.call([executableName, os.path.join('testcase_models', subPath), '-o', 'temp.gcode'])
if ret != 0:
exitValue = 1
sys.exit(exitValue)
if __name__ == '__main__':
main()
|
02fbf47a49cb66391dcb22b1a7ba7a38be210ffe | ooi/config.py | ooi/config.py | # -*- coding: utf-8 -*-
# Copyright 2015 Spanish National Research Council
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo.config import cfg
def parse_args(argv, default_config_files=None):
cfg.CONF(argv[1:],
project='ooi',
default_config_files=default_config_files)
| # -*- coding: utf-8 -*-
# Copyright 2015 Spanish National Research Council
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_config import cfg
def parse_args(argv, default_config_files=None):
cfg.CONF(argv[1:],
project='ooi',
default_config_files=default_config_files)
| Switch to using oslo_* instead of oslo.* | Switch to using oslo_* instead of oslo.*
Change-Id: Ibb578a945f6cb655a35acb744837a14b43117333
| Python | apache-2.0 | openstack/ooi,alvarolopez/ooi,stackforge/ooi,orviz/ooi | # -*- coding: utf-8 -*-
# Copyright 2015 Spanish National Research Council
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo.config import cfg
def parse_args(argv, default_config_files=None):
cfg.CONF(argv[1:],
project='ooi',
default_config_files=default_config_files)
Switch to using oslo_* instead of oslo.*
Change-Id: Ibb578a945f6cb655a35acb744837a14b43117333 | # -*- coding: utf-8 -*-
# Copyright 2015 Spanish National Research Council
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_config import cfg
def parse_args(argv, default_config_files=None):
cfg.CONF(argv[1:],
project='ooi',
default_config_files=default_config_files)
| <commit_before># -*- coding: utf-8 -*-
# Copyright 2015 Spanish National Research Council
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo.config import cfg
def parse_args(argv, default_config_files=None):
cfg.CONF(argv[1:],
project='ooi',
default_config_files=default_config_files)
<commit_msg>Switch to using oslo_* instead of oslo.*
Change-Id: Ibb578a945f6cb655a35acb744837a14b43117333<commit_after> | # -*- coding: utf-8 -*-
# Copyright 2015 Spanish National Research Council
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_config import cfg
def parse_args(argv, default_config_files=None):
cfg.CONF(argv[1:],
project='ooi',
default_config_files=default_config_files)
| # -*- coding: utf-8 -*-
# Copyright 2015 Spanish National Research Council
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo.config import cfg
def parse_args(argv, default_config_files=None):
cfg.CONF(argv[1:],
project='ooi',
default_config_files=default_config_files)
Switch to using oslo_* instead of oslo.*
Change-Id: Ibb578a945f6cb655a35acb744837a14b43117333# -*- coding: utf-8 -*-
# Copyright 2015 Spanish National Research Council
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_config import cfg
def parse_args(argv, default_config_files=None):
cfg.CONF(argv[1:],
project='ooi',
default_config_files=default_config_files)
| <commit_before># -*- coding: utf-8 -*-
# Copyright 2015 Spanish National Research Council
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo.config import cfg
def parse_args(argv, default_config_files=None):
cfg.CONF(argv[1:],
project='ooi',
default_config_files=default_config_files)
<commit_msg>Switch to using oslo_* instead of oslo.*
Change-Id: Ibb578a945f6cb655a35acb744837a14b43117333<commit_after># -*- coding: utf-8 -*-
# Copyright 2015 Spanish National Research Council
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_config import cfg
def parse_args(argv, default_config_files=None):
cfg.CONF(argv[1:],
project='ooi',
default_config_files=default_config_files)
|
a9bdfe489e79aec7f3b422854c58d4fe893f2b95 | duplicate_lines.py | duplicate_lines.py | import sublime, sublime_plugin
class DuplicateLinesCommand(sublime_plugin.TextCommand):
def run(self, edit):
for region in self.view.sel():
if region.empty():
line = self.view.line(region)
line_contents = self.view.substr(line) + '\n'
self.view.insert(edit, line.begin(), line_contents)
else:
line = self.view.line(region)
self.view.run_command("expand_selection", {"to": line.begin()})
region_contents = self.view.substr(self.view.line(region)) + '\n'
self.view.insert(edit, line.begin(), region_contents)
| import sublime, sublime_plugin
class DuplicateLinesCommand(sublime_plugin.TextCommand):
def run(self, edit, **args):
for region in self.view.sel():
line = self.view.full_line(region)
line_contents = self.view.substr(line)
self.view.insert(edit, line.end() if args.get('up', False) else line.begin(), line_contents)
| Add ability to perform 'duplicate up'. | Add ability to perform 'duplicate up'.
| Python | mit | shagabutdinov/sublime-duplicate-lines-enhanced | import sublime, sublime_plugin
class DuplicateLinesCommand(sublime_plugin.TextCommand):
def run(self, edit):
for region in self.view.sel():
if region.empty():
line = self.view.line(region)
line_contents = self.view.substr(line) + '\n'
self.view.insert(edit, line.begin(), line_contents)
else:
line = self.view.line(region)
self.view.run_command("expand_selection", {"to": line.begin()})
region_contents = self.view.substr(self.view.line(region)) + '\n'
self.view.insert(edit, line.begin(), region_contents)
Add ability to perform 'duplicate up'. | import sublime, sublime_plugin
class DuplicateLinesCommand(sublime_plugin.TextCommand):
def run(self, edit, **args):
for region in self.view.sel():
line = self.view.full_line(region)
line_contents = self.view.substr(line)
self.view.insert(edit, line.end() if args.get('up', False) else line.begin(), line_contents)
| <commit_before>import sublime, sublime_plugin
class DuplicateLinesCommand(sublime_plugin.TextCommand):
def run(self, edit):
for region in self.view.sel():
if region.empty():
line = self.view.line(region)
line_contents = self.view.substr(line) + '\n'
self.view.insert(edit, line.begin(), line_contents)
else:
line = self.view.line(region)
self.view.run_command("expand_selection", {"to": line.begin()})
region_contents = self.view.substr(self.view.line(region)) + '\n'
self.view.insert(edit, line.begin(), region_contents)
<commit_msg>Add ability to perform 'duplicate up'.<commit_after> | import sublime, sublime_plugin
class DuplicateLinesCommand(sublime_plugin.TextCommand):
def run(self, edit, **args):
for region in self.view.sel():
line = self.view.full_line(region)
line_contents = self.view.substr(line)
self.view.insert(edit, line.end() if args.get('up', False) else line.begin(), line_contents)
| import sublime, sublime_plugin
class DuplicateLinesCommand(sublime_plugin.TextCommand):
def run(self, edit):
for region in self.view.sel():
if region.empty():
line = self.view.line(region)
line_contents = self.view.substr(line) + '\n'
self.view.insert(edit, line.begin(), line_contents)
else:
line = self.view.line(region)
self.view.run_command("expand_selection", {"to": line.begin()})
region_contents = self.view.substr(self.view.line(region)) + '\n'
self.view.insert(edit, line.begin(), region_contents)
Add ability to perform 'duplicate up'.import sublime, sublime_plugin
class DuplicateLinesCommand(sublime_plugin.TextCommand):
def run(self, edit, **args):
for region in self.view.sel():
line = self.view.full_line(region)
line_contents = self.view.substr(line)
self.view.insert(edit, line.end() if args.get('up', False) else line.begin(), line_contents)
| <commit_before>import sublime, sublime_plugin
class DuplicateLinesCommand(sublime_plugin.TextCommand):
def run(self, edit):
for region in self.view.sel():
if region.empty():
line = self.view.line(region)
line_contents = self.view.substr(line) + '\n'
self.view.insert(edit, line.begin(), line_contents)
else:
line = self.view.line(region)
self.view.run_command("expand_selection", {"to": line.begin()})
region_contents = self.view.substr(self.view.line(region)) + '\n'
self.view.insert(edit, line.begin(), region_contents)
<commit_msg>Add ability to perform 'duplicate up'.<commit_after>import sublime, sublime_plugin
class DuplicateLinesCommand(sublime_plugin.TextCommand):
def run(self, edit, **args):
for region in self.view.sel():
line = self.view.full_line(region)
line_contents = self.view.substr(line)
self.view.insert(edit, line.end() if args.get('up', False) else line.begin(), line_contents)
|
d80a21abcc56192d57c987cf4b8e2057e1d4ffcd | nethud/nh_client.py | nethud/nh_client.py | """
An example client. Run simpleserv.py first before running this.
"""
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.send_message('auth', username='Qalthos', password='password')
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Server said:", data
def connectionLost(self, reason):
print "Connection lost"
# Nethack Protocol Wrapper
def send_message(self, command, **kw):
data = json.dumps({command: kw})
print "Client says:", data
self.transport.write(data)
class NethackFactory(protocol.ClientFactory):
protocol = NethackClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = NethackFactory()
reactor.connectTCP("games-ng.csh.rit.edu", 53421, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
| """
An example client. Run simpleserv.py first before running this.
"""
from __future__ import unicode_literals
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.send_message('auth', username='Qalthos', password='password')
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Server said:", data
def connectionLost(self, reason):
print "Connection lost"
# Nethack Protocol Wrapper
def send_message(self, command, **kw):
data = json.dumps({command: kw})
print "Client says:", data
self.transport.write(data.encode('utf8'))
class NethackFactory(protocol.ClientFactory):
protocol = NethackClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = NethackFactory()
reactor.connectTCP("games-ng.csh.rit.edu", 53421, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
| Make all the things unicode. | Make all the things unicode.
| Python | mit | ryansb/netHUD | """
An example client. Run simpleserv.py first before running this.
"""
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.send_message('auth', username='Qalthos', password='password')
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Server said:", data
def connectionLost(self, reason):
print "Connection lost"
# Nethack Protocol Wrapper
def send_message(self, command, **kw):
data = json.dumps({command: kw})
print "Client says:", data
self.transport.write(data)
class NethackFactory(protocol.ClientFactory):
protocol = NethackClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = NethackFactory()
reactor.connectTCP("games-ng.csh.rit.edu", 53421, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
Make all the things unicode. | """
An example client. Run simpleserv.py first before running this.
"""
from __future__ import unicode_literals
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.send_message('auth', username='Qalthos', password='password')
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Server said:", data
def connectionLost(self, reason):
print "Connection lost"
# Nethack Protocol Wrapper
def send_message(self, command, **kw):
data = json.dumps({command: kw})
print "Client says:", data
self.transport.write(data.encode('utf8'))
class NethackFactory(protocol.ClientFactory):
protocol = NethackClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = NethackFactory()
reactor.connectTCP("games-ng.csh.rit.edu", 53421, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
| <commit_before>"""
An example client. Run simpleserv.py first before running this.
"""
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.send_message('auth', username='Qalthos', password='password')
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Server said:", data
def connectionLost(self, reason):
print "Connection lost"
# Nethack Protocol Wrapper
def send_message(self, command, **kw):
data = json.dumps({command: kw})
print "Client says:", data
self.transport.write(data)
class NethackFactory(protocol.ClientFactory):
protocol = NethackClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = NethackFactory()
reactor.connectTCP("games-ng.csh.rit.edu", 53421, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
<commit_msg>Make all the things unicode.<commit_after> | """
An example client. Run simpleserv.py first before running this.
"""
from __future__ import unicode_literals
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.send_message('auth', username='Qalthos', password='password')
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Server said:", data
def connectionLost(self, reason):
print "Connection lost"
# Nethack Protocol Wrapper
def send_message(self, command, **kw):
data = json.dumps({command: kw})
print "Client says:", data
self.transport.write(data.encode('utf8'))
class NethackFactory(protocol.ClientFactory):
protocol = NethackClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = NethackFactory()
reactor.connectTCP("games-ng.csh.rit.edu", 53421, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
| """
An example client. Run simpleserv.py first before running this.
"""
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.send_message('auth', username='Qalthos', password='password')
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Server said:", data
def connectionLost(self, reason):
print "Connection lost"
# Nethack Protocol Wrapper
def send_message(self, command, **kw):
data = json.dumps({command: kw})
print "Client says:", data
self.transport.write(data)
class NethackFactory(protocol.ClientFactory):
protocol = NethackClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = NethackFactory()
reactor.connectTCP("games-ng.csh.rit.edu", 53421, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
Make all the things unicode."""
An example client. Run simpleserv.py first before running this.
"""
from __future__ import unicode_literals
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.send_message('auth', username='Qalthos', password='password')
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Server said:", data
def connectionLost(self, reason):
print "Connection lost"
# Nethack Protocol Wrapper
def send_message(self, command, **kw):
data = json.dumps({command: kw})
print "Client says:", data
self.transport.write(data.encode('utf8'))
class NethackFactory(protocol.ClientFactory):
protocol = NethackClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = NethackFactory()
reactor.connectTCP("games-ng.csh.rit.edu", 53421, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
| <commit_before>"""
An example client. Run simpleserv.py first before running this.
"""
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.send_message('auth', username='Qalthos', password='password')
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Server said:", data
def connectionLost(self, reason):
print "Connection lost"
# Nethack Protocol Wrapper
def send_message(self, command, **kw):
data = json.dumps({command: kw})
print "Client says:", data
self.transport.write(data)
class NethackFactory(protocol.ClientFactory):
protocol = NethackClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = NethackFactory()
reactor.connectTCP("games-ng.csh.rit.edu", 53421, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
<commit_msg>Make all the things unicode.<commit_after>"""
An example client. Run simpleserv.py first before running this.
"""
from __future__ import unicode_literals
import json
from twisted.internet import reactor, protocol
# a client protocol
class NethackClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.send_message('auth', username='Qalthos', password='password')
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Server said:", data
def connectionLost(self, reason):
print "Connection lost"
# Nethack Protocol Wrapper
def send_message(self, command, **kw):
data = json.dumps({command: kw})
print "Client says:", data
self.transport.write(data.encode('utf8'))
class NethackFactory(protocol.ClientFactory):
protocol = NethackClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = NethackFactory()
reactor.connectTCP("games-ng.csh.rit.edu", 53421, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
|
57f72a0f64ccc7713a38a03d016e05ec8c528b1d | framework/sentry/__init__.py | framework/sentry/__init__.py | #!/usr/bin/env python
# encoding: utf-8
import logging
from raven.contrib.flask import Sentry
from framework.sessions import get_session
from website import settings
logger = logging.getLogger(__name__)
sentry = Sentry(dsn=settings.SENTRY_DSN)
# Nothing in this module should send to Sentry if debug mode is on
# or if Sentry isn't configured.
enabled = (not settings.DEBUG_MODE) and settings.SENTRY_DSN
def get_session_data():
try:
return get_session().data
except (RuntimeError, AttributeError):
return {}
def log_exception():
if not enabled:
logger.warning('Sentry called to log exception, but is not active')
return None
return sentry.captureException(extra={
'session': get_session_data(),
})
def log_message(message, extra={}):
if not enabled:
logger.warning(
'Sentry called to log message, but is not active: %s' % message
)
return None
return sentry.captureMessage(message, extra=extra)
| #!/usr/bin/env python
# encoding: utf-8
import logging
from raven.contrib.flask import Sentry
from framework.sessions import get_session
from website import settings
logger = logging.getLogger(__name__)
sentry = Sentry(dsn=settings.SENTRY_DSN)
# Nothing in this module should send to Sentry if debug mode is on
# or if Sentry isn't configured.
enabled = (not settings.DEBUG_MODE) and settings.SENTRY_DSN
def get_session_data():
try:
return get_session().data
except (RuntimeError, AttributeError):
return {}
def log_exception():
if not enabled:
logger.warning('Sentry called to log exception, but is not active')
return None
return sentry.captureException(extra={
'session': get_session_data(),
})
def log_message(message, extra_data={}):
if not enabled:
logger.warning(
'Sentry called to log message, but is not active: %s' % message
)
return None
extra = {
'session': get_session_data(),
}
if extra_data: extra.update(extra_data)
return sentry.captureMessage(message, extra=extra)
| Add session info to extra data | Add session info to extra data
| Python | apache-2.0 | crcresearch/osf.io,cslzchen/osf.io,brianjgeiger/osf.io,caneruguz/osf.io,TomBaxter/osf.io,aaxelb/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,mfraezz/osf.io,icereval/osf.io,binoculars/osf.io,leb2dg/osf.io,baylee-d/osf.io,mfraezz/osf.io,laurenrevere/osf.io,chennan47/osf.io,caneruguz/osf.io,felliott/osf.io,mattclark/osf.io,adlius/osf.io,Johnetordoff/osf.io,baylee-d/osf.io,adlius/osf.io,felliott/osf.io,erinspace/osf.io,brianjgeiger/osf.io,leb2dg/osf.io,brianjgeiger/osf.io,adlius/osf.io,aaxelb/osf.io,saradbowman/osf.io,aaxelb/osf.io,HalcyonChimera/osf.io,erinspace/osf.io,sloria/osf.io,cslzchen/osf.io,felliott/osf.io,baylee-d/osf.io,leb2dg/osf.io,laurenrevere/osf.io,CenterForOpenScience/osf.io,HalcyonChimera/osf.io,CenterForOpenScience/osf.io,chrisseto/osf.io,Johnetordoff/osf.io,caneruguz/osf.io,erinspace/osf.io,caneruguz/osf.io,binoculars/osf.io,mfraezz/osf.io,leb2dg/osf.io,HalcyonChimera/osf.io,crcresearch/osf.io,pattisdr/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,sloria/osf.io,TomBaxter/osf.io,adlius/osf.io,icereval/osf.io,laurenrevere/osf.io,caseyrollins/osf.io,pattisdr/osf.io,brianjgeiger/osf.io,binoculars/osf.io,chrisseto/osf.io,mattclark/osf.io,cslzchen/osf.io,felliott/osf.io,TomBaxter/osf.io,chrisseto/osf.io,chennan47/osf.io,chennan47/osf.io,icereval/osf.io,mfraezz/osf.io,chrisseto/osf.io,Johnetordoff/osf.io,pattisdr/osf.io,sloria/osf.io,crcresearch/osf.io,saradbowman/osf.io,HalcyonChimera/osf.io,caseyrollins/osf.io,caseyrollins/osf.io,CenterForOpenScience/osf.io,cslzchen/osf.io | #!/usr/bin/env python
# encoding: utf-8
import logging
from raven.contrib.flask import Sentry
from framework.sessions import get_session
from website import settings
logger = logging.getLogger(__name__)
sentry = Sentry(dsn=settings.SENTRY_DSN)
# Nothing in this module should send to Sentry if debug mode is on
# or if Sentry isn't configured.
enabled = (not settings.DEBUG_MODE) and settings.SENTRY_DSN
def get_session_data():
try:
return get_session().data
except (RuntimeError, AttributeError):
return {}
def log_exception():
if not enabled:
logger.warning('Sentry called to log exception, but is not active')
return None
return sentry.captureException(extra={
'session': get_session_data(),
})
def log_message(message, extra={}):
if not enabled:
logger.warning(
'Sentry called to log message, but is not active: %s' % message
)
return None
return sentry.captureMessage(message, extra=extra)
Add session info to extra data | #!/usr/bin/env python
# encoding: utf-8
import logging
from raven.contrib.flask import Sentry
from framework.sessions import get_session
from website import settings
logger = logging.getLogger(__name__)
sentry = Sentry(dsn=settings.SENTRY_DSN)
# Nothing in this module should send to Sentry if debug mode is on
# or if Sentry isn't configured.
enabled = (not settings.DEBUG_MODE) and settings.SENTRY_DSN
def get_session_data():
try:
return get_session().data
except (RuntimeError, AttributeError):
return {}
def log_exception():
if not enabled:
logger.warning('Sentry called to log exception, but is not active')
return None
return sentry.captureException(extra={
'session': get_session_data(),
})
def log_message(message, extra_data={}):
if not enabled:
logger.warning(
'Sentry called to log message, but is not active: %s' % message
)
return None
extra = {
'session': get_session_data(),
}
if extra_data: extra.update(extra_data)
return sentry.captureMessage(message, extra=extra)
| <commit_before>#!/usr/bin/env python
# encoding: utf-8
import logging
from raven.contrib.flask import Sentry
from framework.sessions import get_session
from website import settings
logger = logging.getLogger(__name__)
sentry = Sentry(dsn=settings.SENTRY_DSN)
# Nothing in this module should send to Sentry if debug mode is on
# or if Sentry isn't configured.
enabled = (not settings.DEBUG_MODE) and settings.SENTRY_DSN
def get_session_data():
try:
return get_session().data
except (RuntimeError, AttributeError):
return {}
def log_exception():
if not enabled:
logger.warning('Sentry called to log exception, but is not active')
return None
return sentry.captureException(extra={
'session': get_session_data(),
})
def log_message(message, extra={}):
if not enabled:
logger.warning(
'Sentry called to log message, but is not active: %s' % message
)
return None
return sentry.captureMessage(message, extra=extra)
<commit_msg>Add session info to extra data<commit_after> | #!/usr/bin/env python
# encoding: utf-8
import logging
from raven.contrib.flask import Sentry
from framework.sessions import get_session
from website import settings
logger = logging.getLogger(__name__)
sentry = Sentry(dsn=settings.SENTRY_DSN)
# Nothing in this module should send to Sentry if debug mode is on
# or if Sentry isn't configured.
enabled = (not settings.DEBUG_MODE) and settings.SENTRY_DSN
def get_session_data():
try:
return get_session().data
except (RuntimeError, AttributeError):
return {}
def log_exception():
if not enabled:
logger.warning('Sentry called to log exception, but is not active')
return None
return sentry.captureException(extra={
'session': get_session_data(),
})
def log_message(message, extra_data={}):
if not enabled:
logger.warning(
'Sentry called to log message, but is not active: %s' % message
)
return None
extra = {
'session': get_session_data(),
}
if extra_data: extra.update(extra_data)
return sentry.captureMessage(message, extra=extra)
| #!/usr/bin/env python
# encoding: utf-8
import logging
from raven.contrib.flask import Sentry
from framework.sessions import get_session
from website import settings
logger = logging.getLogger(__name__)
sentry = Sentry(dsn=settings.SENTRY_DSN)
# Nothing in this module should send to Sentry if debug mode is on
# or if Sentry isn't configured.
enabled = (not settings.DEBUG_MODE) and settings.SENTRY_DSN
def get_session_data():
try:
return get_session().data
except (RuntimeError, AttributeError):
return {}
def log_exception():
if not enabled:
logger.warning('Sentry called to log exception, but is not active')
return None
return sentry.captureException(extra={
'session': get_session_data(),
})
def log_message(message, extra={}):
if not enabled:
logger.warning(
'Sentry called to log message, but is not active: %s' % message
)
return None
return sentry.captureMessage(message, extra=extra)
Add session info to extra data#!/usr/bin/env python
# encoding: utf-8
import logging
from raven.contrib.flask import Sentry
from framework.sessions import get_session
from website import settings
logger = logging.getLogger(__name__)
sentry = Sentry(dsn=settings.SENTRY_DSN)
# Nothing in this module should send to Sentry if debug mode is on
# or if Sentry isn't configured.
enabled = (not settings.DEBUG_MODE) and settings.SENTRY_DSN
def get_session_data():
try:
return get_session().data
except (RuntimeError, AttributeError):
return {}
def log_exception():
if not enabled:
logger.warning('Sentry called to log exception, but is not active')
return None
return sentry.captureException(extra={
'session': get_session_data(),
})
def log_message(message, extra_data={}):
if not enabled:
logger.warning(
'Sentry called to log message, but is not active: %s' % message
)
return None
extra = {
'session': get_session_data(),
}
if extra_data: extra.update(extra_data)
return sentry.captureMessage(message, extra=extra)
| <commit_before>#!/usr/bin/env python
# encoding: utf-8
import logging
from raven.contrib.flask import Sentry
from framework.sessions import get_session
from website import settings
logger = logging.getLogger(__name__)
sentry = Sentry(dsn=settings.SENTRY_DSN)
# Nothing in this module should send to Sentry if debug mode is on
# or if Sentry isn't configured.
enabled = (not settings.DEBUG_MODE) and settings.SENTRY_DSN
def get_session_data():
try:
return get_session().data
except (RuntimeError, AttributeError):
return {}
def log_exception():
if not enabled:
logger.warning('Sentry called to log exception, but is not active')
return None
return sentry.captureException(extra={
'session': get_session_data(),
})
def log_message(message, extra={}):
if not enabled:
logger.warning(
'Sentry called to log message, but is not active: %s' % message
)
return None
return sentry.captureMessage(message, extra=extra)
<commit_msg>Add session info to extra data<commit_after>#!/usr/bin/env python
# encoding: utf-8
import logging
from raven.contrib.flask import Sentry
from framework.sessions import get_session
from website import settings
logger = logging.getLogger(__name__)
sentry = Sentry(dsn=settings.SENTRY_DSN)
# Nothing in this module should send to Sentry if debug mode is on
# or if Sentry isn't configured.
enabled = (not settings.DEBUG_MODE) and settings.SENTRY_DSN
def get_session_data():
try:
return get_session().data
except (RuntimeError, AttributeError):
return {}
def log_exception():
if not enabled:
logger.warning('Sentry called to log exception, but is not active')
return None
return sentry.captureException(extra={
'session': get_session_data(),
})
def log_message(message, extra_data={}):
if not enabled:
logger.warning(
'Sentry called to log message, but is not active: %s' % message
)
return None
extra = {
'session': get_session_data(),
}
if extra_data: extra.update(extra_data)
return sentry.captureMessage(message, extra=extra)
|
5853a5767c2b73d14fd1cd0b8843bda38de5b4c2 | InvenTree/part/views.py | InvenTree/part/views.py | from rest_framework import generics
from .models import PartCategory, Part, PartParameter
from .serializers import PartSerializer
from .serializers import PartCategoryBriefSerializer, PartCategoryDetailSerializer
from .serializers import PartParameterSerializer
class PartDetail(generics.RetrieveAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartParameters(generics.ListAPIView):
def get_queryset(self):
part_id = self.kwargs['pk']
return PartParameter.objects.filter(part=part_id)
serializer_class = PartParameterSerializer
class PartList(generics.ListAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartCategoryDetail(generics.RetrieveAPIView):
""" Return information on a single PartCategory
"""
queryset = PartCategory.objects.all()
serializer_class = PartCategoryDetailSerializer
class PartCategoryList(generics.ListAPIView):
""" Return a list of all top-level part categories.
Categories are considered "top-level" if they do not have a parent
"""
queryset = PartCategory.objects.filter(parent=None)
serializer_class = PartCategoryBriefSerializer
| from rest_framework import generics
from .models import PartCategory, Part, PartParameter
from .serializers import PartSerializer
from .serializers import PartCategoryBriefSerializer, PartCategoryDetailSerializer
from .serializers import PartParameterSerializer
class PartDetail(generics.RetrieveAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartParameters(generics.ListAPIView):
def get_queryset(self):
part_id = self.kwargs['pk']
return PartParameter.objects.filter(part=part_id)
serializer_class = PartParameterSerializer
class PartList(generics.ListAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartCategoryDetail(generics.RetrieveAPIView):
""" Return information on a single PartCategory
"""
queryset = PartCategory.objects.all()
serializer_class = PartCategoryDetailSerializer
class PartCategoryList(generics.ListAPIView):
""" Return a list of all top-level part categories.
Categories are considered "top-level" if they do not have a parent
"""
queryset = PartCategory.objects.filter(parent=None)
serializer_class = PartCategoryDetailSerializer
| Fix for part category API | Fix for part category API
| Python | mit | SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree | from rest_framework import generics
from .models import PartCategory, Part, PartParameter
from .serializers import PartSerializer
from .serializers import PartCategoryBriefSerializer, PartCategoryDetailSerializer
from .serializers import PartParameterSerializer
class PartDetail(generics.RetrieveAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartParameters(generics.ListAPIView):
def get_queryset(self):
part_id = self.kwargs['pk']
return PartParameter.objects.filter(part=part_id)
serializer_class = PartParameterSerializer
class PartList(generics.ListAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartCategoryDetail(generics.RetrieveAPIView):
""" Return information on a single PartCategory
"""
queryset = PartCategory.objects.all()
serializer_class = PartCategoryDetailSerializer
class PartCategoryList(generics.ListAPIView):
""" Return a list of all top-level part categories.
Categories are considered "top-level" if they do not have a parent
"""
queryset = PartCategory.objects.filter(parent=None)
serializer_class = PartCategoryBriefSerializer
Fix for part category API | from rest_framework import generics
from .models import PartCategory, Part, PartParameter
from .serializers import PartSerializer
from .serializers import PartCategoryBriefSerializer, PartCategoryDetailSerializer
from .serializers import PartParameterSerializer
class PartDetail(generics.RetrieveAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartParameters(generics.ListAPIView):
def get_queryset(self):
part_id = self.kwargs['pk']
return PartParameter.objects.filter(part=part_id)
serializer_class = PartParameterSerializer
class PartList(generics.ListAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartCategoryDetail(generics.RetrieveAPIView):
""" Return information on a single PartCategory
"""
queryset = PartCategory.objects.all()
serializer_class = PartCategoryDetailSerializer
class PartCategoryList(generics.ListAPIView):
""" Return a list of all top-level part categories.
Categories are considered "top-level" if they do not have a parent
"""
queryset = PartCategory.objects.filter(parent=None)
serializer_class = PartCategoryDetailSerializer
| <commit_before>from rest_framework import generics
from .models import PartCategory, Part, PartParameter
from .serializers import PartSerializer
from .serializers import PartCategoryBriefSerializer, PartCategoryDetailSerializer
from .serializers import PartParameterSerializer
class PartDetail(generics.RetrieveAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartParameters(generics.ListAPIView):
def get_queryset(self):
part_id = self.kwargs['pk']
return PartParameter.objects.filter(part=part_id)
serializer_class = PartParameterSerializer
class PartList(generics.ListAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartCategoryDetail(generics.RetrieveAPIView):
""" Return information on a single PartCategory
"""
queryset = PartCategory.objects.all()
serializer_class = PartCategoryDetailSerializer
class PartCategoryList(generics.ListAPIView):
""" Return a list of all top-level part categories.
Categories are considered "top-level" if they do not have a parent
"""
queryset = PartCategory.objects.filter(parent=None)
serializer_class = PartCategoryBriefSerializer
<commit_msg>Fix for part category API<commit_after> | from rest_framework import generics
from .models import PartCategory, Part, PartParameter
from .serializers import PartSerializer
from .serializers import PartCategoryBriefSerializer, PartCategoryDetailSerializer
from .serializers import PartParameterSerializer
class PartDetail(generics.RetrieveAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartParameters(generics.ListAPIView):
def get_queryset(self):
part_id = self.kwargs['pk']
return PartParameter.objects.filter(part=part_id)
serializer_class = PartParameterSerializer
class PartList(generics.ListAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartCategoryDetail(generics.RetrieveAPIView):
""" Return information on a single PartCategory
"""
queryset = PartCategory.objects.all()
serializer_class = PartCategoryDetailSerializer
class PartCategoryList(generics.ListAPIView):
""" Return a list of all top-level part categories.
Categories are considered "top-level" if they do not have a parent
"""
queryset = PartCategory.objects.filter(parent=None)
serializer_class = PartCategoryDetailSerializer
| from rest_framework import generics
from .models import PartCategory, Part, PartParameter
from .serializers import PartSerializer
from .serializers import PartCategoryBriefSerializer, PartCategoryDetailSerializer
from .serializers import PartParameterSerializer
class PartDetail(generics.RetrieveAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartParameters(generics.ListAPIView):
def get_queryset(self):
part_id = self.kwargs['pk']
return PartParameter.objects.filter(part=part_id)
serializer_class = PartParameterSerializer
class PartList(generics.ListAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartCategoryDetail(generics.RetrieveAPIView):
""" Return information on a single PartCategory
"""
queryset = PartCategory.objects.all()
serializer_class = PartCategoryDetailSerializer
class PartCategoryList(generics.ListAPIView):
""" Return a list of all top-level part categories.
Categories are considered "top-level" if they do not have a parent
"""
queryset = PartCategory.objects.filter(parent=None)
serializer_class = PartCategoryBriefSerializer
Fix for part category APIfrom rest_framework import generics
from .models import PartCategory, Part, PartParameter
from .serializers import PartSerializer
from .serializers import PartCategoryBriefSerializer, PartCategoryDetailSerializer
from .serializers import PartParameterSerializer
class PartDetail(generics.RetrieveAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartParameters(generics.ListAPIView):
def get_queryset(self):
part_id = self.kwargs['pk']
return PartParameter.objects.filter(part=part_id)
serializer_class = PartParameterSerializer
class PartList(generics.ListAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartCategoryDetail(generics.RetrieveAPIView):
""" Return information on a single PartCategory
"""
queryset = PartCategory.objects.all()
serializer_class = PartCategoryDetailSerializer
class PartCategoryList(generics.ListAPIView):
""" Return a list of all top-level part categories.
Categories are considered "top-level" if they do not have a parent
"""
queryset = PartCategory.objects.filter(parent=None)
serializer_class = PartCategoryDetailSerializer
| <commit_before>from rest_framework import generics
from .models import PartCategory, Part, PartParameter
from .serializers import PartSerializer
from .serializers import PartCategoryBriefSerializer, PartCategoryDetailSerializer
from .serializers import PartParameterSerializer
class PartDetail(generics.RetrieveAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartParameters(generics.ListAPIView):
def get_queryset(self):
part_id = self.kwargs['pk']
return PartParameter.objects.filter(part=part_id)
serializer_class = PartParameterSerializer
class PartList(generics.ListAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartCategoryDetail(generics.RetrieveAPIView):
""" Return information on a single PartCategory
"""
queryset = PartCategory.objects.all()
serializer_class = PartCategoryDetailSerializer
class PartCategoryList(generics.ListAPIView):
""" Return a list of all top-level part categories.
Categories are considered "top-level" if they do not have a parent
"""
queryset = PartCategory.objects.filter(parent=None)
serializer_class = PartCategoryBriefSerializer
<commit_msg>Fix for part category API<commit_after>from rest_framework import generics
from .models import PartCategory, Part, PartParameter
from .serializers import PartSerializer
from .serializers import PartCategoryBriefSerializer, PartCategoryDetailSerializer
from .serializers import PartParameterSerializer
class PartDetail(generics.RetrieveAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartParameters(generics.ListAPIView):
def get_queryset(self):
part_id = self.kwargs['pk']
return PartParameter.objects.filter(part=part_id)
serializer_class = PartParameterSerializer
class PartList(generics.ListAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartCategoryDetail(generics.RetrieveAPIView):
""" Return information on a single PartCategory
"""
queryset = PartCategory.objects.all()
serializer_class = PartCategoryDetailSerializer
class PartCategoryList(generics.ListAPIView):
""" Return a list of all top-level part categories.
Categories are considered "top-level" if they do not have a parent
"""
queryset = PartCategory.objects.filter(parent=None)
serializer_class = PartCategoryDetailSerializer
|
c66a2933cca12fa27b688f60b3eb70b07bcce4e5 | src/ggrc/migrations/utils.py | src/ggrc/migrations/utils.py | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
def resolve_duplicates(model, attr):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
setattr(v, attr, getattr(v, attr, model.type) + u"-" + unicode(v.id))
db.session.add(v)
db.session.commit()
| # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
def resolve_duplicates(model, attr, separator=u"-"):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
i = 0
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
while db.session.query(model).\
filter(getattr(model, attr) == nattr).count():
i += 1
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
setattr(v, attr, nattr)
db.session.add(v)
db.session.commit()
| Verify that new attribute doesn't already exist in database | Verify that new attribute doesn't already exist in database
| Python | apache-2.0 | prasannav7/ggrc-core,jmakov/ggrc-core,prasannav7/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core,jmakov/ggrc-core,kr41/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,edofic/ggrc-core,AleksNeStu/ggrc-core,j0gurt/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,kr41/ggrc-core,josthkko/ggrc-core,prasannav7/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,kr41/ggrc-core,VinnieJohns/ggrc-core,josthkko/ggrc-core,NejcZupec/ggrc-core,plamut/ggrc-core,prasannav7/ggrc-core,edofic/ggrc-core,edofic/ggrc-core,jmakov/ggrc-core,andrei-karalionak/ggrc-core,andrei-karalionak/ggrc-core,j0gurt/ggrc-core,plamut/ggrc-core,NejcZupec/ggrc-core,josthkko/ggrc-core,josthkko/ggrc-core,edofic/ggrc-core,jmakov/ggrc-core,andrei-karalionak/ggrc-core,jmakov/ggrc-core,kr41/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,NejcZupec/ggrc-core,VinnieJohns/ggrc-core,NejcZupec/ggrc-core,VinnieJohns/ggrc-core | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
def resolve_duplicates(model, attr):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
setattr(v, attr, getattr(v, attr, model.type) + u"-" + unicode(v.id))
db.session.add(v)
db.session.commit()
Verify that new attribute doesn't already exist in database | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
def resolve_duplicates(model, attr, separator=u"-"):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
i = 0
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
while db.session.query(model).\
filter(getattr(model, attr) == nattr).count():
i += 1
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
setattr(v, attr, nattr)
db.session.add(v)
db.session.commit()
| <commit_before># Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
def resolve_duplicates(model, attr):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
setattr(v, attr, getattr(v, attr, model.type) + u"-" + unicode(v.id))
db.session.add(v)
db.session.commit()
<commit_msg>Verify that new attribute doesn't already exist in database<commit_after> | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
def resolve_duplicates(model, attr, separator=u"-"):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
i = 0
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
while db.session.query(model).\
filter(getattr(model, attr) == nattr).count():
i += 1
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
setattr(v, attr, nattr)
db.session.add(v)
db.session.commit()
| # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
def resolve_duplicates(model, attr):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
setattr(v, attr, getattr(v, attr, model.type) + u"-" + unicode(v.id))
db.session.add(v)
db.session.commit()
Verify that new attribute doesn't already exist in database# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
def resolve_duplicates(model, attr, separator=u"-"):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
i = 0
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
while db.session.query(model).\
filter(getattr(model, attr) == nattr).count():
i += 1
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
setattr(v, attr, nattr)
db.session.add(v)
db.session.commit()
| <commit_before># Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
def resolve_duplicates(model, attr):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
setattr(v, attr, getattr(v, attr, model.type) + u"-" + unicode(v.id))
db.session.add(v)
db.session.commit()
<commit_msg>Verify that new attribute doesn't already exist in database<commit_after># Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
def resolve_duplicates(model, attr, separator=u"-"):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
i = 0
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
while db.session.query(model).\
filter(getattr(model, attr) == nattr).count():
i += 1
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
setattr(v, attr, nattr)
db.session.add(v)
db.session.commit()
|
52a6b421f4a9b0c9956ffec8f684609d43260a85 | login/tests.py | login/tests.py | from django.test import TestCase
# Create your tests here.
| from django.contrib.auth.models import User
from django.test import TestCase, Client
class LoginTestCase(TestCase):
def setUp(self):
User.objects.create_user(
username='user',
password='password'
)
def test_login_form(self):
c = Client()
response = c.get('/login/')
self.assertTemplateUsed(
response,
template_name='login/login.html'
)
def test_login_with_correct_password(self):
c = Client()
response = c.post('/login/', {
'username': 'user',
'password': 'password',
})
self.assertRedirects(response, '/')
def test_login_case_insensitive(self):
c = Client()
response = c.post('/login/', {
'username': 'User',
'password': 'password',
})
self.assertContains(
response,
'Please enter a correct username and password.'
)
def test_login_invalid_password(self):
c = Client()
response = c.post('/login/', {
'username': 'user',
'password': 'p4ssword',
})
self.assertContains(
response,
'Please enter a correct username and password.'
)
def test_login_non_existing_user(self):
c = Client()
response = c.post('/login/', {
'username': 'max',
'password': 'moritz',
})
self.assertContains(
response,
'Please enter a correct username and password.'
)
| Add test cases for login process | Add test cases for login process
| Python | agpl-3.0 | verleihtool/verleihtool,verleihtool/verleihtool,verleihtool/verleihtool,verleihtool/verleihtool | from django.test import TestCase
# Create your tests here.
Add test cases for login process | from django.contrib.auth.models import User
from django.test import TestCase, Client
class LoginTestCase(TestCase):
def setUp(self):
User.objects.create_user(
username='user',
password='password'
)
def test_login_form(self):
c = Client()
response = c.get('/login/')
self.assertTemplateUsed(
response,
template_name='login/login.html'
)
def test_login_with_correct_password(self):
c = Client()
response = c.post('/login/', {
'username': 'user',
'password': 'password',
})
self.assertRedirects(response, '/')
def test_login_case_insensitive(self):
c = Client()
response = c.post('/login/', {
'username': 'User',
'password': 'password',
})
self.assertContains(
response,
'Please enter a correct username and password.'
)
def test_login_invalid_password(self):
c = Client()
response = c.post('/login/', {
'username': 'user',
'password': 'p4ssword',
})
self.assertContains(
response,
'Please enter a correct username and password.'
)
def test_login_non_existing_user(self):
c = Client()
response = c.post('/login/', {
'username': 'max',
'password': 'moritz',
})
self.assertContains(
response,
'Please enter a correct username and password.'
)
| <commit_before>from django.test import TestCase
# Create your tests here.
<commit_msg>Add test cases for login process<commit_after> | from django.contrib.auth.models import User
from django.test import TestCase, Client
class LoginTestCase(TestCase):
def setUp(self):
User.objects.create_user(
username='user',
password='password'
)
def test_login_form(self):
c = Client()
response = c.get('/login/')
self.assertTemplateUsed(
response,
template_name='login/login.html'
)
def test_login_with_correct_password(self):
c = Client()
response = c.post('/login/', {
'username': 'user',
'password': 'password',
})
self.assertRedirects(response, '/')
def test_login_case_insensitive(self):
c = Client()
response = c.post('/login/', {
'username': 'User',
'password': 'password',
})
self.assertContains(
response,
'Please enter a correct username and password.'
)
def test_login_invalid_password(self):
c = Client()
response = c.post('/login/', {
'username': 'user',
'password': 'p4ssword',
})
self.assertContains(
response,
'Please enter a correct username and password.'
)
def test_login_non_existing_user(self):
c = Client()
response = c.post('/login/', {
'username': 'max',
'password': 'moritz',
})
self.assertContains(
response,
'Please enter a correct username and password.'
)
| from django.test import TestCase
# Create your tests here.
Add test cases for login processfrom django.contrib.auth.models import User
from django.test import TestCase, Client
class LoginTestCase(TestCase):
def setUp(self):
User.objects.create_user(
username='user',
password='password'
)
def test_login_form(self):
c = Client()
response = c.get('/login/')
self.assertTemplateUsed(
response,
template_name='login/login.html'
)
def test_login_with_correct_password(self):
c = Client()
response = c.post('/login/', {
'username': 'user',
'password': 'password',
})
self.assertRedirects(response, '/')
def test_login_case_insensitive(self):
c = Client()
response = c.post('/login/', {
'username': 'User',
'password': 'password',
})
self.assertContains(
response,
'Please enter a correct username and password.'
)
def test_login_invalid_password(self):
c = Client()
response = c.post('/login/', {
'username': 'user',
'password': 'p4ssword',
})
self.assertContains(
response,
'Please enter a correct username and password.'
)
def test_login_non_existing_user(self):
c = Client()
response = c.post('/login/', {
'username': 'max',
'password': 'moritz',
})
self.assertContains(
response,
'Please enter a correct username and password.'
)
| <commit_before>from django.test import TestCase
# Create your tests here.
<commit_msg>Add test cases for login process<commit_after>from django.contrib.auth.models import User
from django.test import TestCase, Client
class LoginTestCase(TestCase):
def setUp(self):
User.objects.create_user(
username='user',
password='password'
)
def test_login_form(self):
c = Client()
response = c.get('/login/')
self.assertTemplateUsed(
response,
template_name='login/login.html'
)
def test_login_with_correct_password(self):
c = Client()
response = c.post('/login/', {
'username': 'user',
'password': 'password',
})
self.assertRedirects(response, '/')
def test_login_case_insensitive(self):
c = Client()
response = c.post('/login/', {
'username': 'User',
'password': 'password',
})
self.assertContains(
response,
'Please enter a correct username and password.'
)
def test_login_invalid_password(self):
c = Client()
response = c.post('/login/', {
'username': 'user',
'password': 'p4ssword',
})
self.assertContains(
response,
'Please enter a correct username and password.'
)
def test_login_non_existing_user(self):
c = Client()
response = c.post('/login/', {
'username': 'max',
'password': 'moritz',
})
self.assertContains(
response,
'Please enter a correct username and password.'
)
|
0431011632b9852f644f33803cffbd4f7ace0887 | gamecraft/settings_heroku.py | gamecraft/settings_heroku.py | import os
import urllib.parse
from gamecraft.settings_heroku_base import *
DEBUG = False
TEMPLATE_DEBUG = False
INSTALLED_APPS = INSTALLED_APPS + (
'raven.contrib.django.raven_compat',
)
redis_parse_result = urllib.parse.urlparse(os.environ['REDISCLOUD_URL'])
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': '{redis.hostname}:{redis.port}:0'.format(redis=redis_parse_result),
'OPTIONS': {
'CLIENT_CLASS': 'redis_cache.client.DefaultClient',
'PASSWORD': redis_parse_result.password,
'PICKLE_VERSION': -1,
'IGNORE_EXCEPTIONS': True,
'CONNECTION_POOL_KWARGS': {'max_connections': 10}
}
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.gzip.GZipMiddleware',
'pipeline.middleware.MinifyHTMLMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
)
| import os
import urllib.parse
from gamecraft.settings_heroku_base import *
DEBUG = False
TEMPLATE_DEBUG = False
INSTALLED_APPS = INSTALLED_APPS + (
'raven.contrib.django.raven_compat',
)
redis_parse_result = urllib.parse.urlparse(os.environ['REDISCLOUD_URL'])
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': '{redis.hostname}:{redis.port}:0'.format(redis=redis_parse_result),
'OPTIONS': {
'CLIENT_CLASS': 'redis_cache.client.DefaultClient',
'PASSWORD': redis_parse_result.password,
'PICKLE_VERSION': -1,
'IGNORE_EXCEPTIONS': True,
'CONNECTION_POOL_KWARGS': {'max_connections': 10}
}
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.gzip.GZipMiddleware',
'pipeline.middleware.MinifyHTMLMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
)
| Add redirect middleware to heroku configs | Add redirect middleware to heroku configs
| Python | mit | micktwomey/gamecraft-mk-iii,micktwomey/gamecraft-mk-iii,micktwomey/gamecraft-mk-iii,micktwomey/gamecraft-mk-iii | import os
import urllib.parse
from gamecraft.settings_heroku_base import *
DEBUG = False
TEMPLATE_DEBUG = False
INSTALLED_APPS = INSTALLED_APPS + (
'raven.contrib.django.raven_compat',
)
redis_parse_result = urllib.parse.urlparse(os.environ['REDISCLOUD_URL'])
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': '{redis.hostname}:{redis.port}:0'.format(redis=redis_parse_result),
'OPTIONS': {
'CLIENT_CLASS': 'redis_cache.client.DefaultClient',
'PASSWORD': redis_parse_result.password,
'PICKLE_VERSION': -1,
'IGNORE_EXCEPTIONS': True,
'CONNECTION_POOL_KWARGS': {'max_connections': 10}
}
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.gzip.GZipMiddleware',
'pipeline.middleware.MinifyHTMLMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
)
Add redirect middleware to heroku configs | import os
import urllib.parse
from gamecraft.settings_heroku_base import *
DEBUG = False
TEMPLATE_DEBUG = False
INSTALLED_APPS = INSTALLED_APPS + (
'raven.contrib.django.raven_compat',
)
redis_parse_result = urllib.parse.urlparse(os.environ['REDISCLOUD_URL'])
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': '{redis.hostname}:{redis.port}:0'.format(redis=redis_parse_result),
'OPTIONS': {
'CLIENT_CLASS': 'redis_cache.client.DefaultClient',
'PASSWORD': redis_parse_result.password,
'PICKLE_VERSION': -1,
'IGNORE_EXCEPTIONS': True,
'CONNECTION_POOL_KWARGS': {'max_connections': 10}
}
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.gzip.GZipMiddleware',
'pipeline.middleware.MinifyHTMLMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
)
| <commit_before>import os
import urllib.parse
from gamecraft.settings_heroku_base import *
DEBUG = False
TEMPLATE_DEBUG = False
INSTALLED_APPS = INSTALLED_APPS + (
'raven.contrib.django.raven_compat',
)
redis_parse_result = urllib.parse.urlparse(os.environ['REDISCLOUD_URL'])
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': '{redis.hostname}:{redis.port}:0'.format(redis=redis_parse_result),
'OPTIONS': {
'CLIENT_CLASS': 'redis_cache.client.DefaultClient',
'PASSWORD': redis_parse_result.password,
'PICKLE_VERSION': -1,
'IGNORE_EXCEPTIONS': True,
'CONNECTION_POOL_KWARGS': {'max_connections': 10}
}
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.gzip.GZipMiddleware',
'pipeline.middleware.MinifyHTMLMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
)
<commit_msg>Add redirect middleware to heroku configs<commit_after> | import os
import urllib.parse
from gamecraft.settings_heroku_base import *
DEBUG = False
TEMPLATE_DEBUG = False
INSTALLED_APPS = INSTALLED_APPS + (
'raven.contrib.django.raven_compat',
)
redis_parse_result = urllib.parse.urlparse(os.environ['REDISCLOUD_URL'])
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': '{redis.hostname}:{redis.port}:0'.format(redis=redis_parse_result),
'OPTIONS': {
'CLIENT_CLASS': 'redis_cache.client.DefaultClient',
'PASSWORD': redis_parse_result.password,
'PICKLE_VERSION': -1,
'IGNORE_EXCEPTIONS': True,
'CONNECTION_POOL_KWARGS': {'max_connections': 10}
}
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.gzip.GZipMiddleware',
'pipeline.middleware.MinifyHTMLMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
)
| import os
import urllib.parse
from gamecraft.settings_heroku_base import *
DEBUG = False
TEMPLATE_DEBUG = False
INSTALLED_APPS = INSTALLED_APPS + (
'raven.contrib.django.raven_compat',
)
redis_parse_result = urllib.parse.urlparse(os.environ['REDISCLOUD_URL'])
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': '{redis.hostname}:{redis.port}:0'.format(redis=redis_parse_result),
'OPTIONS': {
'CLIENT_CLASS': 'redis_cache.client.DefaultClient',
'PASSWORD': redis_parse_result.password,
'PICKLE_VERSION': -1,
'IGNORE_EXCEPTIONS': True,
'CONNECTION_POOL_KWARGS': {'max_connections': 10}
}
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.gzip.GZipMiddleware',
'pipeline.middleware.MinifyHTMLMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
)
Add redirect middleware to heroku configsimport os
import urllib.parse
from gamecraft.settings_heroku_base import *
DEBUG = False
TEMPLATE_DEBUG = False
INSTALLED_APPS = INSTALLED_APPS + (
'raven.contrib.django.raven_compat',
)
redis_parse_result = urllib.parse.urlparse(os.environ['REDISCLOUD_URL'])
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': '{redis.hostname}:{redis.port}:0'.format(redis=redis_parse_result),
'OPTIONS': {
'CLIENT_CLASS': 'redis_cache.client.DefaultClient',
'PASSWORD': redis_parse_result.password,
'PICKLE_VERSION': -1,
'IGNORE_EXCEPTIONS': True,
'CONNECTION_POOL_KWARGS': {'max_connections': 10}
}
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.gzip.GZipMiddleware',
'pipeline.middleware.MinifyHTMLMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
)
| <commit_before>import os
import urllib.parse
from gamecraft.settings_heroku_base import *
DEBUG = False
TEMPLATE_DEBUG = False
INSTALLED_APPS = INSTALLED_APPS + (
'raven.contrib.django.raven_compat',
)
redis_parse_result = urllib.parse.urlparse(os.environ['REDISCLOUD_URL'])
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': '{redis.hostname}:{redis.port}:0'.format(redis=redis_parse_result),
'OPTIONS': {
'CLIENT_CLASS': 'redis_cache.client.DefaultClient',
'PASSWORD': redis_parse_result.password,
'PICKLE_VERSION': -1,
'IGNORE_EXCEPTIONS': True,
'CONNECTION_POOL_KWARGS': {'max_connections': 10}
}
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.gzip.GZipMiddleware',
'pipeline.middleware.MinifyHTMLMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
)
<commit_msg>Add redirect middleware to heroku configs<commit_after>import os
import urllib.parse
from gamecraft.settings_heroku_base import *
DEBUG = False
TEMPLATE_DEBUG = False
INSTALLED_APPS = INSTALLED_APPS + (
'raven.contrib.django.raven_compat',
)
redis_parse_result = urllib.parse.urlparse(os.environ['REDISCLOUD_URL'])
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': '{redis.hostname}:{redis.port}:0'.format(redis=redis_parse_result),
'OPTIONS': {
'CLIENT_CLASS': 'redis_cache.client.DefaultClient',
'PASSWORD': redis_parse_result.password,
'PICKLE_VERSION': -1,
'IGNORE_EXCEPTIONS': True,
'CONNECTION_POOL_KWARGS': {'max_connections': 10}
}
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.gzip.GZipMiddleware',
'pipeline.middleware.MinifyHTMLMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
)
|
a6c06c61e9fa11c6b441fdf2a5075ca35015d7e0 | tests/test_windows.py | tests/test_windows.py | import pytest
import mdct.windows
def test_kbd():
mdct.windows.kaiser_derived(50)
| import pytest
import mdct.windows
def test_kbd():
mdct.windows.kaiser_derived(50)
with pytest.raises(ValueError):
mdct.windows.kaiser_derived(51)
| Test that asserts odd numbered windows dont work | Test that asserts odd numbered windows dont work
| Python | mit | audiolabs/mdct | import pytest
import mdct.windows
def test_kbd():
mdct.windows.kaiser_derived(50)
Test that asserts odd numbered windows dont work | import pytest
import mdct.windows
def test_kbd():
mdct.windows.kaiser_derived(50)
with pytest.raises(ValueError):
mdct.windows.kaiser_derived(51)
| <commit_before>import pytest
import mdct.windows
def test_kbd():
mdct.windows.kaiser_derived(50)
<commit_msg>Test that asserts odd numbered windows dont work<commit_after> | import pytest
import mdct.windows
def test_kbd():
mdct.windows.kaiser_derived(50)
with pytest.raises(ValueError):
mdct.windows.kaiser_derived(51)
| import pytest
import mdct.windows
def test_kbd():
mdct.windows.kaiser_derived(50)
Test that asserts odd numbered windows dont workimport pytest
import mdct.windows
def test_kbd():
mdct.windows.kaiser_derived(50)
with pytest.raises(ValueError):
mdct.windows.kaiser_derived(51)
| <commit_before>import pytest
import mdct.windows
def test_kbd():
mdct.windows.kaiser_derived(50)
<commit_msg>Test that asserts odd numbered windows dont work<commit_after>import pytest
import mdct.windows
def test_kbd():
mdct.windows.kaiser_derived(50)
with pytest.raises(ValueError):
mdct.windows.kaiser_derived(51)
|
342512a12868bc7dadbaf3c85b5aedd86bb990e7 | gunicorn/workers/__init__.py | gunicorn/workers/__init__.py | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import sys
# supported gunicorn workers.
SUPPORTED_WORKERS = {
"sync": "gunicorn.workers.sync.SyncWorker",
"eventlet": "gunicorn.workers.geventlet.EventletWorker",
"gevent": "gunicorn.workers.ggevent.GeventWorker",
"gevent_wsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"gevent_pywsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"tornado": "gunicorn.workers.gtornado.TornadoWorker"}
if sys.version_info >= (3, 3):
# gaiohttp worker can be used with Python 3.3+ only.
SUPPORTED_WORKERS["gaiohttp"] = "gunicorn.workers.gaiohttp.AiohttpWorker"
| # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import sys
# supported gunicorn workers.
SUPPORTED_WORKERS = {
"sync": "gunicorn.workers.sync.SyncWorker",
"eventlet": "gunicorn.workers.geventlet.EventletWorker",
"gevent": "gunicorn.workers.ggevent.GeventWorker",
"gevent_wsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"gevent_pywsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"tornado": "gunicorn.workers.gtornado.TornadoWorker",
"gthread": "gunicorn.workers.gthread.ThreadWorker",
}
if sys.version_info >= (3, 3):
# gaiohttp worker can be used with Python 3.3+ only.
SUPPORTED_WORKERS["gaiohttp"] = "gunicorn.workers.gaiohttp.AiohttpWorker"
| Add the 'gthread' worker to the gunicorn.workers.SUPPORTED_WORKERS dictionary | Add the 'gthread' worker to the gunicorn.workers.SUPPORTED_WORKERS dictionary
Fixes #1011.
| Python | mit | GitHublong/gunicorn,elelianghh/gunicorn,ephes/gunicorn,malept/gunicorn,malept/gunicorn,tempbottle/gunicorn,malept/gunicorn,ccl0326/gunicorn,keakon/gunicorn,mvaled/gunicorn,tejasmanohar/gunicorn,mvaled/gunicorn,WSDC-NITWarangal/gunicorn,gtrdotmcs/gunicorn,mvaled/gunicorn,z-fork/gunicorn,prezi/gunicorn,zhoucen/gunicorn,prezi/gunicorn,ccl0326/gunicorn,zhoucen/gunicorn,prezi/gunicorn,ccl0326/gunicorn,zhoucen/gunicorn,gtrdotmcs/gunicorn,MrKiven/gunicorn,gtrdotmcs/gunicorn,harrisonfeng/gunicorn | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import sys
# supported gunicorn workers.
SUPPORTED_WORKERS = {
"sync": "gunicorn.workers.sync.SyncWorker",
"eventlet": "gunicorn.workers.geventlet.EventletWorker",
"gevent": "gunicorn.workers.ggevent.GeventWorker",
"gevent_wsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"gevent_pywsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"tornado": "gunicorn.workers.gtornado.TornadoWorker"}
if sys.version_info >= (3, 3):
# gaiohttp worker can be used with Python 3.3+ only.
SUPPORTED_WORKERS["gaiohttp"] = "gunicorn.workers.gaiohttp.AiohttpWorker"
Add the 'gthread' worker to the gunicorn.workers.SUPPORTED_WORKERS dictionary
Fixes #1011. | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import sys
# supported gunicorn workers.
SUPPORTED_WORKERS = {
"sync": "gunicorn.workers.sync.SyncWorker",
"eventlet": "gunicorn.workers.geventlet.EventletWorker",
"gevent": "gunicorn.workers.ggevent.GeventWorker",
"gevent_wsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"gevent_pywsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"tornado": "gunicorn.workers.gtornado.TornadoWorker",
"gthread": "gunicorn.workers.gthread.ThreadWorker",
}
if sys.version_info >= (3, 3):
# gaiohttp worker can be used with Python 3.3+ only.
SUPPORTED_WORKERS["gaiohttp"] = "gunicorn.workers.gaiohttp.AiohttpWorker"
| <commit_before># -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import sys
# supported gunicorn workers.
SUPPORTED_WORKERS = {
"sync": "gunicorn.workers.sync.SyncWorker",
"eventlet": "gunicorn.workers.geventlet.EventletWorker",
"gevent": "gunicorn.workers.ggevent.GeventWorker",
"gevent_wsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"gevent_pywsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"tornado": "gunicorn.workers.gtornado.TornadoWorker"}
if sys.version_info >= (3, 3):
# gaiohttp worker can be used with Python 3.3+ only.
SUPPORTED_WORKERS["gaiohttp"] = "gunicorn.workers.gaiohttp.AiohttpWorker"
<commit_msg>Add the 'gthread' worker to the gunicorn.workers.SUPPORTED_WORKERS dictionary
Fixes #1011.<commit_after> | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import sys
# supported gunicorn workers.
SUPPORTED_WORKERS = {
"sync": "gunicorn.workers.sync.SyncWorker",
"eventlet": "gunicorn.workers.geventlet.EventletWorker",
"gevent": "gunicorn.workers.ggevent.GeventWorker",
"gevent_wsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"gevent_pywsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"tornado": "gunicorn.workers.gtornado.TornadoWorker",
"gthread": "gunicorn.workers.gthread.ThreadWorker",
}
if sys.version_info >= (3, 3):
# gaiohttp worker can be used with Python 3.3+ only.
SUPPORTED_WORKERS["gaiohttp"] = "gunicorn.workers.gaiohttp.AiohttpWorker"
| # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import sys
# supported gunicorn workers.
SUPPORTED_WORKERS = {
"sync": "gunicorn.workers.sync.SyncWorker",
"eventlet": "gunicorn.workers.geventlet.EventletWorker",
"gevent": "gunicorn.workers.ggevent.GeventWorker",
"gevent_wsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"gevent_pywsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"tornado": "gunicorn.workers.gtornado.TornadoWorker"}
if sys.version_info >= (3, 3):
# gaiohttp worker can be used with Python 3.3+ only.
SUPPORTED_WORKERS["gaiohttp"] = "gunicorn.workers.gaiohttp.AiohttpWorker"
Add the 'gthread' worker to the gunicorn.workers.SUPPORTED_WORKERS dictionary
Fixes #1011.# -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import sys
# supported gunicorn workers.
SUPPORTED_WORKERS = {
"sync": "gunicorn.workers.sync.SyncWorker",
"eventlet": "gunicorn.workers.geventlet.EventletWorker",
"gevent": "gunicorn.workers.ggevent.GeventWorker",
"gevent_wsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"gevent_pywsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"tornado": "gunicorn.workers.gtornado.TornadoWorker",
"gthread": "gunicorn.workers.gthread.ThreadWorker",
}
if sys.version_info >= (3, 3):
# gaiohttp worker can be used with Python 3.3+ only.
SUPPORTED_WORKERS["gaiohttp"] = "gunicorn.workers.gaiohttp.AiohttpWorker"
| <commit_before># -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import sys
# supported gunicorn workers.
SUPPORTED_WORKERS = {
"sync": "gunicorn.workers.sync.SyncWorker",
"eventlet": "gunicorn.workers.geventlet.EventletWorker",
"gevent": "gunicorn.workers.ggevent.GeventWorker",
"gevent_wsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"gevent_pywsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"tornado": "gunicorn.workers.gtornado.TornadoWorker"}
if sys.version_info >= (3, 3):
# gaiohttp worker can be used with Python 3.3+ only.
SUPPORTED_WORKERS["gaiohttp"] = "gunicorn.workers.gaiohttp.AiohttpWorker"
<commit_msg>Add the 'gthread' worker to the gunicorn.workers.SUPPORTED_WORKERS dictionary
Fixes #1011.<commit_after># -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import sys
# supported gunicorn workers.
SUPPORTED_WORKERS = {
"sync": "gunicorn.workers.sync.SyncWorker",
"eventlet": "gunicorn.workers.geventlet.EventletWorker",
"gevent": "gunicorn.workers.ggevent.GeventWorker",
"gevent_wsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"gevent_pywsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"tornado": "gunicorn.workers.gtornado.TornadoWorker",
"gthread": "gunicorn.workers.gthread.ThreadWorker",
}
if sys.version_info >= (3, 3):
# gaiohttp worker can be used with Python 3.3+ only.
SUPPORTED_WORKERS["gaiohttp"] = "gunicorn.workers.gaiohttp.AiohttpWorker"
|
5daef3041ced3e8a3fc8e9d7d64ab43607bb24ae | allauth/socialaccount/providers/feedly/views.py | allauth/socialaccount/providers/feedly/views.py | from __future__ import unicode_literals
import requests
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import FeedlyProvider
class FeedlyOAuth2Adapter(OAuth2Adapter):
provider_id = FeedlyProvider.id
access_token_url = 'https://cloud.feedly.com/v3/auth/token'
authorize_url = 'https://cloud.feedly.com/v3/auth/auth'
profile_url = 'https://cloud.feedly.com/v3/profile'
def complete_login(self, request, app, token, **kwargs):
headers = {'Authorization': 'OAuth {0}'.format(token.token)}
resp = requests.get(self.profile_url, headers=headers)
extra_data = resp.json()
return self.get_provider().sociallogin_from_response(request,
extra_data)
oauth2_login = OAuth2LoginView.adapter_view(FeedlyOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(FeedlyOAuth2Adapter)
| from __future__ import unicode_literals
import requests
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import FeedlyProvider
class FeedlyOAuth2Adapter(OAuth2Adapter):
provider_id = FeedlyProvider.id
access_token_url = 'https://%s/v3/auth/token' % settings.get('FEEDLY_HOST', 'cloud.feedly.com')
authorize_url = 'https://%s/v3/auth/auth' % settings.get('FEEDLY_HOST', 'cloud.feedly.com')
profile_url = 'https://%s/v3/profile' % settings.get('FEEDLY_HOST', 'cloud.feedly.com')
access_token_url = 'https://%s/oauth' % (settings.get(
'EVERNOTE_HOSTNAME',
'sandbox.evernote.com'))
def complete_login(self, request, app, token, **kwargs):
headers = {'Authorization': 'OAuth {0}'.format(token.token)}
resp = requests.get(self.profile_url, headers=headers)
extra_data = resp.json()
return self.get_provider().sociallogin_from_response(request,
extra_data)
oauth2_login = OAuth2LoginView.adapter_view(FeedlyOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(FeedlyOAuth2Adapter)
| Add option FEEDLY_HOST for feedly.com provider | Add option FEEDLY_HOST for feedly.com provider | Python | mit | wli/django-allauth,rsalmaso/django-allauth,lukeburden/django-allauth,spool/django-allauth,pennersr/django-allauth,rsalmaso/django-allauth,lukeburden/django-allauth,bittner/django-allauth,AltSchool/django-allauth,joshowen/django-allauth,lukeburden/django-allauth,bittner/django-allauth,jwhitlock/django-allauth,jwhitlock/django-allauth,pztrick/django-allauth,AltSchool/django-allauth,jwhitlock/django-allauth,spool/django-allauth,pennersr/django-allauth,joshowen/django-allauth,wli/django-allauth,pztrick/django-allauth,rsalmaso/django-allauth,joshowen/django-allauth,bittner/django-allauth,nimbis/django-allauth,pztrick/django-allauth,spool/django-allauth,AltSchool/django-allauth,nimbis/django-allauth,pennersr/django-allauth,wli/django-allauth,nimbis/django-allauth | from __future__ import unicode_literals
import requests
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import FeedlyProvider
class FeedlyOAuth2Adapter(OAuth2Adapter):
provider_id = FeedlyProvider.id
access_token_url = 'https://cloud.feedly.com/v3/auth/token'
authorize_url = 'https://cloud.feedly.com/v3/auth/auth'
profile_url = 'https://cloud.feedly.com/v3/profile'
def complete_login(self, request, app, token, **kwargs):
headers = {'Authorization': 'OAuth {0}'.format(token.token)}
resp = requests.get(self.profile_url, headers=headers)
extra_data = resp.json()
return self.get_provider().sociallogin_from_response(request,
extra_data)
oauth2_login = OAuth2LoginView.adapter_view(FeedlyOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(FeedlyOAuth2Adapter)
Add option FEEDLY_HOST for feedly.com provider | from __future__ import unicode_literals
import requests
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import FeedlyProvider
class FeedlyOAuth2Adapter(OAuth2Adapter):
provider_id = FeedlyProvider.id
access_token_url = 'https://%s/v3/auth/token' % settings.get('FEEDLY_HOST', 'cloud.feedly.com')
authorize_url = 'https://%s/v3/auth/auth' % settings.get('FEEDLY_HOST', 'cloud.feedly.com')
profile_url = 'https://%s/v3/profile' % settings.get('FEEDLY_HOST', 'cloud.feedly.com')
access_token_url = 'https://%s/oauth' % (settings.get(
'EVERNOTE_HOSTNAME',
'sandbox.evernote.com'))
def complete_login(self, request, app, token, **kwargs):
headers = {'Authorization': 'OAuth {0}'.format(token.token)}
resp = requests.get(self.profile_url, headers=headers)
extra_data = resp.json()
return self.get_provider().sociallogin_from_response(request,
extra_data)
oauth2_login = OAuth2LoginView.adapter_view(FeedlyOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(FeedlyOAuth2Adapter)
| <commit_before>from __future__ import unicode_literals
import requests
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import FeedlyProvider
class FeedlyOAuth2Adapter(OAuth2Adapter):
provider_id = FeedlyProvider.id
access_token_url = 'https://cloud.feedly.com/v3/auth/token'
authorize_url = 'https://cloud.feedly.com/v3/auth/auth'
profile_url = 'https://cloud.feedly.com/v3/profile'
def complete_login(self, request, app, token, **kwargs):
headers = {'Authorization': 'OAuth {0}'.format(token.token)}
resp = requests.get(self.profile_url, headers=headers)
extra_data = resp.json()
return self.get_provider().sociallogin_from_response(request,
extra_data)
oauth2_login = OAuth2LoginView.adapter_view(FeedlyOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(FeedlyOAuth2Adapter)
<commit_msg>Add option FEEDLY_HOST for feedly.com provider<commit_after> | from __future__ import unicode_literals
import requests
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import FeedlyProvider
class FeedlyOAuth2Adapter(OAuth2Adapter):
provider_id = FeedlyProvider.id
access_token_url = 'https://%s/v3/auth/token' % settings.get('FEEDLY_HOST', 'cloud.feedly.com')
authorize_url = 'https://%s/v3/auth/auth' % settings.get('FEEDLY_HOST', 'cloud.feedly.com')
profile_url = 'https://%s/v3/profile' % settings.get('FEEDLY_HOST', 'cloud.feedly.com')
access_token_url = 'https://%s/oauth' % (settings.get(
'EVERNOTE_HOSTNAME',
'sandbox.evernote.com'))
def complete_login(self, request, app, token, **kwargs):
headers = {'Authorization': 'OAuth {0}'.format(token.token)}
resp = requests.get(self.profile_url, headers=headers)
extra_data = resp.json()
return self.get_provider().sociallogin_from_response(request,
extra_data)
oauth2_login = OAuth2LoginView.adapter_view(FeedlyOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(FeedlyOAuth2Adapter)
| from __future__ import unicode_literals
import requests
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import FeedlyProvider
class FeedlyOAuth2Adapter(OAuth2Adapter):
provider_id = FeedlyProvider.id
access_token_url = 'https://cloud.feedly.com/v3/auth/token'
authorize_url = 'https://cloud.feedly.com/v3/auth/auth'
profile_url = 'https://cloud.feedly.com/v3/profile'
def complete_login(self, request, app, token, **kwargs):
headers = {'Authorization': 'OAuth {0}'.format(token.token)}
resp = requests.get(self.profile_url, headers=headers)
extra_data = resp.json()
return self.get_provider().sociallogin_from_response(request,
extra_data)
oauth2_login = OAuth2LoginView.adapter_view(FeedlyOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(FeedlyOAuth2Adapter)
Add option FEEDLY_HOST for feedly.com providerfrom __future__ import unicode_literals
import requests
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import FeedlyProvider
class FeedlyOAuth2Adapter(OAuth2Adapter):
provider_id = FeedlyProvider.id
access_token_url = 'https://%s/v3/auth/token' % settings.get('FEEDLY_HOST', 'cloud.feedly.com')
authorize_url = 'https://%s/v3/auth/auth' % settings.get('FEEDLY_HOST', 'cloud.feedly.com')
profile_url = 'https://%s/v3/profile' % settings.get('FEEDLY_HOST', 'cloud.feedly.com')
access_token_url = 'https://%s/oauth' % (settings.get(
'EVERNOTE_HOSTNAME',
'sandbox.evernote.com'))
def complete_login(self, request, app, token, **kwargs):
headers = {'Authorization': 'OAuth {0}'.format(token.token)}
resp = requests.get(self.profile_url, headers=headers)
extra_data = resp.json()
return self.get_provider().sociallogin_from_response(request,
extra_data)
oauth2_login = OAuth2LoginView.adapter_view(FeedlyOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(FeedlyOAuth2Adapter)
| <commit_before>from __future__ import unicode_literals
import requests
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import FeedlyProvider
class FeedlyOAuth2Adapter(OAuth2Adapter):
provider_id = FeedlyProvider.id
access_token_url = 'https://cloud.feedly.com/v3/auth/token'
authorize_url = 'https://cloud.feedly.com/v3/auth/auth'
profile_url = 'https://cloud.feedly.com/v3/profile'
def complete_login(self, request, app, token, **kwargs):
headers = {'Authorization': 'OAuth {0}'.format(token.token)}
resp = requests.get(self.profile_url, headers=headers)
extra_data = resp.json()
return self.get_provider().sociallogin_from_response(request,
extra_data)
oauth2_login = OAuth2LoginView.adapter_view(FeedlyOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(FeedlyOAuth2Adapter)
<commit_msg>Add option FEEDLY_HOST for feedly.com provider<commit_after>from __future__ import unicode_literals
import requests
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import FeedlyProvider
class FeedlyOAuth2Adapter(OAuth2Adapter):
provider_id = FeedlyProvider.id
access_token_url = 'https://%s/v3/auth/token' % settings.get('FEEDLY_HOST', 'cloud.feedly.com')
authorize_url = 'https://%s/v3/auth/auth' % settings.get('FEEDLY_HOST', 'cloud.feedly.com')
profile_url = 'https://%s/v3/profile' % settings.get('FEEDLY_HOST', 'cloud.feedly.com')
access_token_url = 'https://%s/oauth' % (settings.get(
'EVERNOTE_HOSTNAME',
'sandbox.evernote.com'))
def complete_login(self, request, app, token, **kwargs):
headers = {'Authorization': 'OAuth {0}'.format(token.token)}
resp = requests.get(self.profile_url, headers=headers)
extra_data = resp.json()
return self.get_provider().sociallogin_from_response(request,
extra_data)
oauth2_login = OAuth2LoginView.adapter_view(FeedlyOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(FeedlyOAuth2Adapter)
|
1633fe8e8e3d97273256fd64cac0447737ef1594 | jsonrpcclient/__init__.py | jsonrpcclient/__init__.py | """__init__.py"""
from jsonrpcclient.request import Request
| """__init__.py"""
import logging
logging.getLogger('jsonrpcclient').addHandler(logging.NullHandler())
from jsonrpcclient.request import Request
| Add NullHandler to logger to quiet Python 2.7 | Add NullHandler to logger to quiet Python 2.7
| Python | mit | bcb/jsonrpcclient | """__init__.py"""
from jsonrpcclient.request import Request
Add NullHandler to logger to quiet Python 2.7 | """__init__.py"""
import logging
logging.getLogger('jsonrpcclient').addHandler(logging.NullHandler())
from jsonrpcclient.request import Request
| <commit_before>"""__init__.py"""
from jsonrpcclient.request import Request
<commit_msg>Add NullHandler to logger to quiet Python 2.7<commit_after> | """__init__.py"""
import logging
logging.getLogger('jsonrpcclient').addHandler(logging.NullHandler())
from jsonrpcclient.request import Request
| """__init__.py"""
from jsonrpcclient.request import Request
Add NullHandler to logger to quiet Python 2.7"""__init__.py"""
import logging
logging.getLogger('jsonrpcclient').addHandler(logging.NullHandler())
from jsonrpcclient.request import Request
| <commit_before>"""__init__.py"""
from jsonrpcclient.request import Request
<commit_msg>Add NullHandler to logger to quiet Python 2.7<commit_after>"""__init__.py"""
import logging
logging.getLogger('jsonrpcclient').addHandler(logging.NullHandler())
from jsonrpcclient.request import Request
|
1f6cac883995cfaf4d1b19c6c13f3fc13e9ddc7a | tools/scyllatop/views/base.py | tools/scyllatop/views/base.py | import time
import curses
import curses.panel
import logging
class Base(object):
def __init__(self, window):
lines, columns = window.getmaxyx()
self._window = curses.newwin(lines, columns)
self._panel = curses.panel.new_panel(self._window)
def writeStatusLine(self, measurements):
line = 'time: {0}| {1} measurements, at most {2} visible'.format(time.asctime(), len(measurements), self.availableLines())
columns = self.dimensions()['columns']
self._window.addstr(0, 0, line.ljust(columns), curses.A_REVERSE)
def availableLines(self):
STATUS_LINE = 1
return self.dimensions()['lines'] - STATUS_LINE
def refresh(self):
curses.panel.update_panels()
curses.doupdate()
def onTop(self):
logging.info('put {0} view on top'.format(self.__class__.__name__))
self._panel.top()
curses.panel.update_panels()
curses.doupdate()
def clearScreen(self):
self._window.clear()
self._window.move(0, 0)
def writeLine(self, thing, line):
self._window.addstr(line, 0, str(thing))
def dimensions(self):
lines, columns = self._window.getmaxyx()
return {'lines': lines, 'columns': columns}
| import time
import curses
import curses.panel
import logging
class Base(object):
def __init__(self, window):
lines, columns = window.getmaxyx()
self._window = curses.newwin(lines, columns)
self._panel = curses.panel.new_panel(self._window)
def writeStatusLine(self, measurements):
line = 'time: {0}| {1} measurements, at most {2} visible'.format(time.asctime(), len(measurements), self.availableLines())
columns = self.dimensions()['columns']
self._window.addstr(0, 0, line.ljust(columns), curses.A_REVERSE)
def availableLines(self):
STATUS_LINE = 1
return self.dimensions()['lines'] - STATUS_LINE
def refresh(self):
curses.panel.update_panels()
curses.doupdate()
def onTop(self):
logging.info('put {0} view on top'.format(self.__class__.__name__))
self._panel.top()
curses.panel.update_panels()
curses.doupdate()
def clearScreen(self):
self._window.erase()
self._window.move(0, 0)
def writeLine(self, thing, line):
self._window.addstr(line, 0, str(thing))
def dimensions(self):
lines, columns = self._window.getmaxyx()
return {'lines': lines, 'columns': columns}
| Use 'erase' to clear the screen | tools/scyllatop: Use 'erase' to clear the screen
The 'clear' function explicitly clears the screen and repaints it which
causes really annoying flicker. Use 'erase' to make scyllatop more
pleasant on the eyes.
Message-Id: <2bf04f96d7d510dddf38de01959db6b168f25a31@scylladb.com>
| Python | agpl-3.0 | raphaelsc/scylla,avikivity/scylla,scylladb/scylla,duarten/scylla,avikivity/scylla,scylladb/scylla,kjniemi/scylla,kjniemi/scylla,duarten/scylla,duarten/scylla,scylladb/scylla,kjniemi/scylla,raphaelsc/scylla,scylladb/scylla,avikivity/scylla,raphaelsc/scylla | import time
import curses
import curses.panel
import logging
class Base(object):
def __init__(self, window):
lines, columns = window.getmaxyx()
self._window = curses.newwin(lines, columns)
self._panel = curses.panel.new_panel(self._window)
def writeStatusLine(self, measurements):
line = 'time: {0}| {1} measurements, at most {2} visible'.format(time.asctime(), len(measurements), self.availableLines())
columns = self.dimensions()['columns']
self._window.addstr(0, 0, line.ljust(columns), curses.A_REVERSE)
def availableLines(self):
STATUS_LINE = 1
return self.dimensions()['lines'] - STATUS_LINE
def refresh(self):
curses.panel.update_panels()
curses.doupdate()
def onTop(self):
logging.info('put {0} view on top'.format(self.__class__.__name__))
self._panel.top()
curses.panel.update_panels()
curses.doupdate()
def clearScreen(self):
self._window.clear()
self._window.move(0, 0)
def writeLine(self, thing, line):
self._window.addstr(line, 0, str(thing))
def dimensions(self):
lines, columns = self._window.getmaxyx()
return {'lines': lines, 'columns': columns}
tools/scyllatop: Use 'erase' to clear the screen
The 'clear' function explicitly clears the screen and repaints it which
causes really annoying flicker. Use 'erase' to make scyllatop more
pleasant on the eyes.
Message-Id: <2bf04f96d7d510dddf38de01959db6b168f25a31@scylladb.com> | import time
import curses
import curses.panel
import logging
class Base(object):
def __init__(self, window):
lines, columns = window.getmaxyx()
self._window = curses.newwin(lines, columns)
self._panel = curses.panel.new_panel(self._window)
def writeStatusLine(self, measurements):
line = 'time: {0}| {1} measurements, at most {2} visible'.format(time.asctime(), len(measurements), self.availableLines())
columns = self.dimensions()['columns']
self._window.addstr(0, 0, line.ljust(columns), curses.A_REVERSE)
def availableLines(self):
STATUS_LINE = 1
return self.dimensions()['lines'] - STATUS_LINE
def refresh(self):
curses.panel.update_panels()
curses.doupdate()
def onTop(self):
logging.info('put {0} view on top'.format(self.__class__.__name__))
self._panel.top()
curses.panel.update_panels()
curses.doupdate()
def clearScreen(self):
self._window.erase()
self._window.move(0, 0)
def writeLine(self, thing, line):
self._window.addstr(line, 0, str(thing))
def dimensions(self):
lines, columns = self._window.getmaxyx()
return {'lines': lines, 'columns': columns}
| <commit_before>import time
import curses
import curses.panel
import logging
class Base(object):
def __init__(self, window):
lines, columns = window.getmaxyx()
self._window = curses.newwin(lines, columns)
self._panel = curses.panel.new_panel(self._window)
def writeStatusLine(self, measurements):
line = 'time: {0}| {1} measurements, at most {2} visible'.format(time.asctime(), len(measurements), self.availableLines())
columns = self.dimensions()['columns']
self._window.addstr(0, 0, line.ljust(columns), curses.A_REVERSE)
def availableLines(self):
STATUS_LINE = 1
return self.dimensions()['lines'] - STATUS_LINE
def refresh(self):
curses.panel.update_panels()
curses.doupdate()
def onTop(self):
logging.info('put {0} view on top'.format(self.__class__.__name__))
self._panel.top()
curses.panel.update_panels()
curses.doupdate()
def clearScreen(self):
self._window.clear()
self._window.move(0, 0)
def writeLine(self, thing, line):
self._window.addstr(line, 0, str(thing))
def dimensions(self):
lines, columns = self._window.getmaxyx()
return {'lines': lines, 'columns': columns}
<commit_msg>tools/scyllatop: Use 'erase' to clear the screen
The 'clear' function explicitly clears the screen and repaints it which
causes really annoying flicker. Use 'erase' to make scyllatop more
pleasant on the eyes.
Message-Id: <2bf04f96d7d510dddf38de01959db6b168f25a31@scylladb.com><commit_after> | import time
import curses
import curses.panel
import logging
class Base(object):
def __init__(self, window):
lines, columns = window.getmaxyx()
self._window = curses.newwin(lines, columns)
self._panel = curses.panel.new_panel(self._window)
def writeStatusLine(self, measurements):
line = 'time: {0}| {1} measurements, at most {2} visible'.format(time.asctime(), len(measurements), self.availableLines())
columns = self.dimensions()['columns']
self._window.addstr(0, 0, line.ljust(columns), curses.A_REVERSE)
def availableLines(self):
STATUS_LINE = 1
return self.dimensions()['lines'] - STATUS_LINE
def refresh(self):
curses.panel.update_panels()
curses.doupdate()
def onTop(self):
logging.info('put {0} view on top'.format(self.__class__.__name__))
self._panel.top()
curses.panel.update_panels()
curses.doupdate()
def clearScreen(self):
self._window.erase()
self._window.move(0, 0)
def writeLine(self, thing, line):
self._window.addstr(line, 0, str(thing))
def dimensions(self):
lines, columns = self._window.getmaxyx()
return {'lines': lines, 'columns': columns}
| import time
import curses
import curses.panel
import logging
class Base(object):
def __init__(self, window):
lines, columns = window.getmaxyx()
self._window = curses.newwin(lines, columns)
self._panel = curses.panel.new_panel(self._window)
def writeStatusLine(self, measurements):
line = 'time: {0}| {1} measurements, at most {2} visible'.format(time.asctime(), len(measurements), self.availableLines())
columns = self.dimensions()['columns']
self._window.addstr(0, 0, line.ljust(columns), curses.A_REVERSE)
def availableLines(self):
STATUS_LINE = 1
return self.dimensions()['lines'] - STATUS_LINE
def refresh(self):
curses.panel.update_panels()
curses.doupdate()
def onTop(self):
logging.info('put {0} view on top'.format(self.__class__.__name__))
self._panel.top()
curses.panel.update_panels()
curses.doupdate()
def clearScreen(self):
self._window.clear()
self._window.move(0, 0)
def writeLine(self, thing, line):
self._window.addstr(line, 0, str(thing))
def dimensions(self):
lines, columns = self._window.getmaxyx()
return {'lines': lines, 'columns': columns}
tools/scyllatop: Use 'erase' to clear the screen
The 'clear' function explicitly clears the screen and repaints it which
causes really annoying flicker. Use 'erase' to make scyllatop more
pleasant on the eyes.
Message-Id: <2bf04f96d7d510dddf38de01959db6b168f25a31@scylladb.com>import time
import curses
import curses.panel
import logging
class Base(object):
def __init__(self, window):
lines, columns = window.getmaxyx()
self._window = curses.newwin(lines, columns)
self._panel = curses.panel.new_panel(self._window)
def writeStatusLine(self, measurements):
line = 'time: {0}| {1} measurements, at most {2} visible'.format(time.asctime(), len(measurements), self.availableLines())
columns = self.dimensions()['columns']
self._window.addstr(0, 0, line.ljust(columns), curses.A_REVERSE)
def availableLines(self):
STATUS_LINE = 1
return self.dimensions()['lines'] - STATUS_LINE
def refresh(self):
curses.panel.update_panels()
curses.doupdate()
def onTop(self):
logging.info('put {0} view on top'.format(self.__class__.__name__))
self._panel.top()
curses.panel.update_panels()
curses.doupdate()
def clearScreen(self):
self._window.erase()
self._window.move(0, 0)
def writeLine(self, thing, line):
self._window.addstr(line, 0, str(thing))
def dimensions(self):
lines, columns = self._window.getmaxyx()
return {'lines': lines, 'columns': columns}
| <commit_before>import time
import curses
import curses.panel
import logging
class Base(object):
def __init__(self, window):
lines, columns = window.getmaxyx()
self._window = curses.newwin(lines, columns)
self._panel = curses.panel.new_panel(self._window)
def writeStatusLine(self, measurements):
line = 'time: {0}| {1} measurements, at most {2} visible'.format(time.asctime(), len(measurements), self.availableLines())
columns = self.dimensions()['columns']
self._window.addstr(0, 0, line.ljust(columns), curses.A_REVERSE)
def availableLines(self):
STATUS_LINE = 1
return self.dimensions()['lines'] - STATUS_LINE
def refresh(self):
curses.panel.update_panels()
curses.doupdate()
def onTop(self):
logging.info('put {0} view on top'.format(self.__class__.__name__))
self._panel.top()
curses.panel.update_panels()
curses.doupdate()
def clearScreen(self):
self._window.clear()
self._window.move(0, 0)
def writeLine(self, thing, line):
self._window.addstr(line, 0, str(thing))
def dimensions(self):
lines, columns = self._window.getmaxyx()
return {'lines': lines, 'columns': columns}
<commit_msg>tools/scyllatop: Use 'erase' to clear the screen
The 'clear' function explicitly clears the screen and repaints it which
causes really annoying flicker. Use 'erase' to make scyllatop more
pleasant on the eyes.
Message-Id: <2bf04f96d7d510dddf38de01959db6b168f25a31@scylladb.com><commit_after>import time
import curses
import curses.panel
import logging
class Base(object):
def __init__(self, window):
lines, columns = window.getmaxyx()
self._window = curses.newwin(lines, columns)
self._panel = curses.panel.new_panel(self._window)
def writeStatusLine(self, measurements):
line = 'time: {0}| {1} measurements, at most {2} visible'.format(time.asctime(), len(measurements), self.availableLines())
columns = self.dimensions()['columns']
self._window.addstr(0, 0, line.ljust(columns), curses.A_REVERSE)
def availableLines(self):
STATUS_LINE = 1
return self.dimensions()['lines'] - STATUS_LINE
def refresh(self):
curses.panel.update_panels()
curses.doupdate()
def onTop(self):
logging.info('put {0} view on top'.format(self.__class__.__name__))
self._panel.top()
curses.panel.update_panels()
curses.doupdate()
def clearScreen(self):
self._window.erase()
self._window.move(0, 0)
def writeLine(self, thing, line):
self._window.addstr(line, 0, str(thing))
def dimensions(self):
lines, columns = self._window.getmaxyx()
return {'lines': lines, 'columns': columns}
|
f2afbc2d7b47e6e28f6924b9761390c34b04ea49 | trunk/editor/test_opensave.py | trunk/editor/test_opensave.py | #!/usr/bin/env python
import unittest
from xml.etree import ElementTree
from openfilerooms import openFileRooms
from savefilerooms import saveFileRooms
class Test(unittest.TestCase):
def test1(self):
source = "world1.rooms"
dest = 'a.rooms'
openFileRooms(source)
saveFileRooms(dest)
xml_file_world = ElementTree.fromstring(open(source, 'rb').read())
xml_file_a = ElementTree.fromstring(open(dest, 'rb').read())
diff = []
for line in xml_file_world.getiterator():
difference = self.findDiff(line, xml_file_a)
if difference:
diff.append(difference)
self.assertEqual(diff, [], diff)
def findDiff(self, line, xml_file_a):
find = False
for line_a in xml_file_a.getiterator(line.tag):
if line.tag == line_a.tag:
if line.attrib == line_a.attrib:
find = True
break
if not find:
return line, line_a
return None
if __name__ == "__main__":
unittest.main()
| #!/usr/bin/env python
import os
import unittest
from xml.etree import ElementTree
from openfilerooms import openFileRooms
from savefilerooms import saveFileRooms
class Test(unittest.TestCase):
test_output = "a.rooms"
def test1(self):
fpath = os.path.abspath(__file__)
path, _ = os.path.split(fpath)
source = os.path.join(path, "..", "examples", "example1", "world.rooms")
source = os.path.normpath(source)
dest = self.test_output
openFileRooms(source)
saveFileRooms(dest)
xml_file_world = ElementTree.fromstring(open(source, 'rb').read())
xml_file_a = ElementTree.fromstring(open(dest, 'rb').read())
diff = []
for line in xml_file_world.getiterator():
difference = self.findDiff(line, xml_file_a)
if difference:
diff.append(difference)
self.assertEqual(diff, [], diff)
def findDiff(self, line, xml_file_a):
find = False
for line_a in xml_file_a.getiterator(line.tag):
if line.tag == line_a.tag:
if line.attrib == line_a.attrib:
find = True
break
if not find:
return line, line_a
return None
def tearDown(self):
# Cleanup the temporary file used for test purposes
os.unlink(self.test_output)
if __name__ == "__main__":
unittest.main()
| Use one of the stock examples for the open/save test | Use one of the stock examples for the open/save test
| Python | mit | develersrl/rooms,develersrl/rooms,develersrl/rooms,develersrl/rooms,develersrl/rooms,develersrl/rooms,develersrl/rooms | #!/usr/bin/env python
import unittest
from xml.etree import ElementTree
from openfilerooms import openFileRooms
from savefilerooms import saveFileRooms
class Test(unittest.TestCase):
def test1(self):
source = "world1.rooms"
dest = 'a.rooms'
openFileRooms(source)
saveFileRooms(dest)
xml_file_world = ElementTree.fromstring(open(source, 'rb').read())
xml_file_a = ElementTree.fromstring(open(dest, 'rb').read())
diff = []
for line in xml_file_world.getiterator():
difference = self.findDiff(line, xml_file_a)
if difference:
diff.append(difference)
self.assertEqual(diff, [], diff)
def findDiff(self, line, xml_file_a):
find = False
for line_a in xml_file_a.getiterator(line.tag):
if line.tag == line_a.tag:
if line.attrib == line_a.attrib:
find = True
break
if not find:
return line, line_a
return None
if __name__ == "__main__":
unittest.main()
Use one of the stock examples for the open/save test | #!/usr/bin/env python
import os
import unittest
from xml.etree import ElementTree
from openfilerooms import openFileRooms
from savefilerooms import saveFileRooms
class Test(unittest.TestCase):
test_output = "a.rooms"
def test1(self):
fpath = os.path.abspath(__file__)
path, _ = os.path.split(fpath)
source = os.path.join(path, "..", "examples", "example1", "world.rooms")
source = os.path.normpath(source)
dest = self.test_output
openFileRooms(source)
saveFileRooms(dest)
xml_file_world = ElementTree.fromstring(open(source, 'rb').read())
xml_file_a = ElementTree.fromstring(open(dest, 'rb').read())
diff = []
for line in xml_file_world.getiterator():
difference = self.findDiff(line, xml_file_a)
if difference:
diff.append(difference)
self.assertEqual(diff, [], diff)
def findDiff(self, line, xml_file_a):
find = False
for line_a in xml_file_a.getiterator(line.tag):
if line.tag == line_a.tag:
if line.attrib == line_a.attrib:
find = True
break
if not find:
return line, line_a
return None
def tearDown(self):
# Cleanup the temporary file used for test purposes
os.unlink(self.test_output)
if __name__ == "__main__":
unittest.main()
| <commit_before>#!/usr/bin/env python
import unittest
from xml.etree import ElementTree
from openfilerooms import openFileRooms
from savefilerooms import saveFileRooms
class Test(unittest.TestCase):
def test1(self):
source = "world1.rooms"
dest = 'a.rooms'
openFileRooms(source)
saveFileRooms(dest)
xml_file_world = ElementTree.fromstring(open(source, 'rb').read())
xml_file_a = ElementTree.fromstring(open(dest, 'rb').read())
diff = []
for line in xml_file_world.getiterator():
difference = self.findDiff(line, xml_file_a)
if difference:
diff.append(difference)
self.assertEqual(diff, [], diff)
def findDiff(self, line, xml_file_a):
find = False
for line_a in xml_file_a.getiterator(line.tag):
if line.tag == line_a.tag:
if line.attrib == line_a.attrib:
find = True
break
if not find:
return line, line_a
return None
if __name__ == "__main__":
unittest.main()
<commit_msg>Use one of the stock examples for the open/save test<commit_after> | #!/usr/bin/env python
import os
import unittest
from xml.etree import ElementTree
from openfilerooms import openFileRooms
from savefilerooms import saveFileRooms
class Test(unittest.TestCase):
test_output = "a.rooms"
def test1(self):
fpath = os.path.abspath(__file__)
path, _ = os.path.split(fpath)
source = os.path.join(path, "..", "examples", "example1", "world.rooms")
source = os.path.normpath(source)
dest = self.test_output
openFileRooms(source)
saveFileRooms(dest)
xml_file_world = ElementTree.fromstring(open(source, 'rb').read())
xml_file_a = ElementTree.fromstring(open(dest, 'rb').read())
diff = []
for line in xml_file_world.getiterator():
difference = self.findDiff(line, xml_file_a)
if difference:
diff.append(difference)
self.assertEqual(diff, [], diff)
def findDiff(self, line, xml_file_a):
find = False
for line_a in xml_file_a.getiterator(line.tag):
if line.tag == line_a.tag:
if line.attrib == line_a.attrib:
find = True
break
if not find:
return line, line_a
return None
def tearDown(self):
# Cleanup the temporary file used for test purposes
os.unlink(self.test_output)
if __name__ == "__main__":
unittest.main()
| #!/usr/bin/env python
import unittest
from xml.etree import ElementTree
from openfilerooms import openFileRooms
from savefilerooms import saveFileRooms
class Test(unittest.TestCase):
def test1(self):
source = "world1.rooms"
dest = 'a.rooms'
openFileRooms(source)
saveFileRooms(dest)
xml_file_world = ElementTree.fromstring(open(source, 'rb').read())
xml_file_a = ElementTree.fromstring(open(dest, 'rb').read())
diff = []
for line in xml_file_world.getiterator():
difference = self.findDiff(line, xml_file_a)
if difference:
diff.append(difference)
self.assertEqual(diff, [], diff)
def findDiff(self, line, xml_file_a):
find = False
for line_a in xml_file_a.getiterator(line.tag):
if line.tag == line_a.tag:
if line.attrib == line_a.attrib:
find = True
break
if not find:
return line, line_a
return None
if __name__ == "__main__":
unittest.main()
Use one of the stock examples for the open/save test#!/usr/bin/env python
import os
import unittest
from xml.etree import ElementTree
from openfilerooms import openFileRooms
from savefilerooms import saveFileRooms
class Test(unittest.TestCase):
test_output = "a.rooms"
def test1(self):
fpath = os.path.abspath(__file__)
path, _ = os.path.split(fpath)
source = os.path.join(path, "..", "examples", "example1", "world.rooms")
source = os.path.normpath(source)
dest = self.test_output
openFileRooms(source)
saveFileRooms(dest)
xml_file_world = ElementTree.fromstring(open(source, 'rb').read())
xml_file_a = ElementTree.fromstring(open(dest, 'rb').read())
diff = []
for line in xml_file_world.getiterator():
difference = self.findDiff(line, xml_file_a)
if difference:
diff.append(difference)
self.assertEqual(diff, [], diff)
def findDiff(self, line, xml_file_a):
find = False
for line_a in xml_file_a.getiterator(line.tag):
if line.tag == line_a.tag:
if line.attrib == line_a.attrib:
find = True
break
if not find:
return line, line_a
return None
def tearDown(self):
# Cleanup the temporary file used for test purposes
os.unlink(self.test_output)
if __name__ == "__main__":
unittest.main()
| <commit_before>#!/usr/bin/env python
import unittest
from xml.etree import ElementTree
from openfilerooms import openFileRooms
from savefilerooms import saveFileRooms
class Test(unittest.TestCase):
def test1(self):
source = "world1.rooms"
dest = 'a.rooms'
openFileRooms(source)
saveFileRooms(dest)
xml_file_world = ElementTree.fromstring(open(source, 'rb').read())
xml_file_a = ElementTree.fromstring(open(dest, 'rb').read())
diff = []
for line in xml_file_world.getiterator():
difference = self.findDiff(line, xml_file_a)
if difference:
diff.append(difference)
self.assertEqual(diff, [], diff)
def findDiff(self, line, xml_file_a):
find = False
for line_a in xml_file_a.getiterator(line.tag):
if line.tag == line_a.tag:
if line.attrib == line_a.attrib:
find = True
break
if not find:
return line, line_a
return None
if __name__ == "__main__":
unittest.main()
<commit_msg>Use one of the stock examples for the open/save test<commit_after>#!/usr/bin/env python
import os
import unittest
from xml.etree import ElementTree
from openfilerooms import openFileRooms
from savefilerooms import saveFileRooms
class Test(unittest.TestCase):
test_output = "a.rooms"
def test1(self):
fpath = os.path.abspath(__file__)
path, _ = os.path.split(fpath)
source = os.path.join(path, "..", "examples", "example1", "world.rooms")
source = os.path.normpath(source)
dest = self.test_output
openFileRooms(source)
saveFileRooms(dest)
xml_file_world = ElementTree.fromstring(open(source, 'rb').read())
xml_file_a = ElementTree.fromstring(open(dest, 'rb').read())
diff = []
for line in xml_file_world.getiterator():
difference = self.findDiff(line, xml_file_a)
if difference:
diff.append(difference)
self.assertEqual(diff, [], diff)
def findDiff(self, line, xml_file_a):
find = False
for line_a in xml_file_a.getiterator(line.tag):
if line.tag == line_a.tag:
if line.attrib == line_a.attrib:
find = True
break
if not find:
return line, line_a
return None
def tearDown(self):
# Cleanup the temporary file used for test purposes
os.unlink(self.test_output)
if __name__ == "__main__":
unittest.main()
|
3b539cedd12948fde71cad29a4eee517d4adff1e | bot.py | bot.py | import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(60)
#time.sleep(43200) # 12 hours
| import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(43200) # 12 hours
| Put back to 12 hours. | Put back to 12 hours.
| Python | mit | gregsabo/only_keep_one,gregsabo/only_keep_one | import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(60)
#time.sleep(43200) # 12 hours
Put back to 12 hours. | import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(43200) # 12 hours
| <commit_before>import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(60)
#time.sleep(43200) # 12 hours
<commit_msg>Put back to 12 hours.<commit_after> | import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(43200) # 12 hours
| import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(60)
#time.sleep(43200) # 12 hours
Put back to 12 hours.import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(43200) # 12 hours
| <commit_before>import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(60)
#time.sleep(43200) # 12 hours
<commit_msg>Put back to 12 hours.<commit_after>import os
import time
from crawl import crawl
import tweepy
class TwitterAPI:
"""
Class for accessing the Twitter API.
Requires API credentials to be available in environment
variables. These will be set appropriately if the bot was created
with init.sh included with the heroku-twitterbot-starter
"""
def __init__(self):
consumer_key = os.environ.get('TWITTER_CONSUMER_KEY')
consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
access_token = os.environ.get('TWITTER_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET')
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
"""Send a tweet"""
self.api.update_status(message)
if __name__ == "__main__":
twitter = TwitterAPI()
while True:
tweet = crawl()
if tweet:
twitter.tweet(tweet)
time.sleep(43200) # 12 hours
|
91b1ac2aee1a6d98b45aba26d4ab80feae505705 | new.py | new.py | #! /usr/bin/env python
import os.path
import time
from time import strftime
import os
import sys
import shutil
FILE = 'todo.md'
def date_to_append():
return strftime("%m-%d-%Y", time.gmtime(os.path.getctime(FILE)))
def rename_file(the_file):
base = os.path.basename(the_file)
split_up = os.path.splitext(base)
file_name = os.path.splitext(base)[0]
file_extension = split_up[1]
new_file_name = "%s%s%s" % (file_name, date_to_append(), file_extension)
os.rename(the_file, new_file_name)
def move_old_todo():
for filename in os.listdir("."):
if filename.startswith('todo'):
shutil.move(filename, 'Archive')
def create_new_todo():
open(FILE, 'w')
rename_file(FILE)
move_old_todo()
create_new_todo()
| #! /usr/bin/env python
import os.path
import time
from time import strftime
import os
import sys
import shutil
FILE = 'todo.md'
def date_to_append():
return strftime("%m-%d-%Y", time.gmtime(os.path.getctime(FILE)))
def rename_file(the_file):
base = os.path.basename(the_file)
split_up = os.path.splitext(base)
file_name = split_up[0]
file_extension = split_up[1]
new_file_name = "%s%s%s" % (file_name, date_to_append(), file_extension)
os.rename(the_file, new_file_name)
def move_old_todo():
for filename in os.listdir("."):
if filename.startswith('todo'):
shutil.move(filename, 'Archive')
def create_new_todo():
open(FILE, 'w')
rename_file(FILE)
move_old_todo()
create_new_todo()
| Use split_up in both places | Use split_up in both places
| Python | mit | thefotes/DoItDoneIt | #! /usr/bin/env python
import os.path
import time
from time import strftime
import os
import sys
import shutil
FILE = 'todo.md'
def date_to_append():
return strftime("%m-%d-%Y", time.gmtime(os.path.getctime(FILE)))
def rename_file(the_file):
base = os.path.basename(the_file)
split_up = os.path.splitext(base)
file_name = os.path.splitext(base)[0]
file_extension = split_up[1]
new_file_name = "%s%s%s" % (file_name, date_to_append(), file_extension)
os.rename(the_file, new_file_name)
def move_old_todo():
for filename in os.listdir("."):
if filename.startswith('todo'):
shutil.move(filename, 'Archive')
def create_new_todo():
open(FILE, 'w')
rename_file(FILE)
move_old_todo()
create_new_todo()
Use split_up in both places | #! /usr/bin/env python
import os.path
import time
from time import strftime
import os
import sys
import shutil
FILE = 'todo.md'
def date_to_append():
return strftime("%m-%d-%Y", time.gmtime(os.path.getctime(FILE)))
def rename_file(the_file):
base = os.path.basename(the_file)
split_up = os.path.splitext(base)
file_name = split_up[0]
file_extension = split_up[1]
new_file_name = "%s%s%s" % (file_name, date_to_append(), file_extension)
os.rename(the_file, new_file_name)
def move_old_todo():
for filename in os.listdir("."):
if filename.startswith('todo'):
shutil.move(filename, 'Archive')
def create_new_todo():
open(FILE, 'w')
rename_file(FILE)
move_old_todo()
create_new_todo()
| <commit_before>#! /usr/bin/env python
import os.path
import time
from time import strftime
import os
import sys
import shutil
FILE = 'todo.md'
def date_to_append():
return strftime("%m-%d-%Y", time.gmtime(os.path.getctime(FILE)))
def rename_file(the_file):
base = os.path.basename(the_file)
split_up = os.path.splitext(base)
file_name = os.path.splitext(base)[0]
file_extension = split_up[1]
new_file_name = "%s%s%s" % (file_name, date_to_append(), file_extension)
os.rename(the_file, new_file_name)
def move_old_todo():
for filename in os.listdir("."):
if filename.startswith('todo'):
shutil.move(filename, 'Archive')
def create_new_todo():
open(FILE, 'w')
rename_file(FILE)
move_old_todo()
create_new_todo()
<commit_msg>Use split_up in both places<commit_after> | #! /usr/bin/env python
import os.path
import time
from time import strftime
import os
import sys
import shutil
FILE = 'todo.md'
def date_to_append():
return strftime("%m-%d-%Y", time.gmtime(os.path.getctime(FILE)))
def rename_file(the_file):
base = os.path.basename(the_file)
split_up = os.path.splitext(base)
file_name = split_up[0]
file_extension = split_up[1]
new_file_name = "%s%s%s" % (file_name, date_to_append(), file_extension)
os.rename(the_file, new_file_name)
def move_old_todo():
for filename in os.listdir("."):
if filename.startswith('todo'):
shutil.move(filename, 'Archive')
def create_new_todo():
open(FILE, 'w')
rename_file(FILE)
move_old_todo()
create_new_todo()
| #! /usr/bin/env python
import os.path
import time
from time import strftime
import os
import sys
import shutil
FILE = 'todo.md'
def date_to_append():
return strftime("%m-%d-%Y", time.gmtime(os.path.getctime(FILE)))
def rename_file(the_file):
base = os.path.basename(the_file)
split_up = os.path.splitext(base)
file_name = os.path.splitext(base)[0]
file_extension = split_up[1]
new_file_name = "%s%s%s" % (file_name, date_to_append(), file_extension)
os.rename(the_file, new_file_name)
def move_old_todo():
for filename in os.listdir("."):
if filename.startswith('todo'):
shutil.move(filename, 'Archive')
def create_new_todo():
open(FILE, 'w')
rename_file(FILE)
move_old_todo()
create_new_todo()
Use split_up in both places#! /usr/bin/env python
import os.path
import time
from time import strftime
import os
import sys
import shutil
FILE = 'todo.md'
def date_to_append():
return strftime("%m-%d-%Y", time.gmtime(os.path.getctime(FILE)))
def rename_file(the_file):
base = os.path.basename(the_file)
split_up = os.path.splitext(base)
file_name = split_up[0]
file_extension = split_up[1]
new_file_name = "%s%s%s" % (file_name, date_to_append(), file_extension)
os.rename(the_file, new_file_name)
def move_old_todo():
for filename in os.listdir("."):
if filename.startswith('todo'):
shutil.move(filename, 'Archive')
def create_new_todo():
open(FILE, 'w')
rename_file(FILE)
move_old_todo()
create_new_todo()
| <commit_before>#! /usr/bin/env python
import os.path
import time
from time import strftime
import os
import sys
import shutil
FILE = 'todo.md'
def date_to_append():
return strftime("%m-%d-%Y", time.gmtime(os.path.getctime(FILE)))
def rename_file(the_file):
base = os.path.basename(the_file)
split_up = os.path.splitext(base)
file_name = os.path.splitext(base)[0]
file_extension = split_up[1]
new_file_name = "%s%s%s" % (file_name, date_to_append(), file_extension)
os.rename(the_file, new_file_name)
def move_old_todo():
for filename in os.listdir("."):
if filename.startswith('todo'):
shutil.move(filename, 'Archive')
def create_new_todo():
open(FILE, 'w')
rename_file(FILE)
move_old_todo()
create_new_todo()
<commit_msg>Use split_up in both places<commit_after>#! /usr/bin/env python
import os.path
import time
from time import strftime
import os
import sys
import shutil
FILE = 'todo.md'
def date_to_append():
return strftime("%m-%d-%Y", time.gmtime(os.path.getctime(FILE)))
def rename_file(the_file):
base = os.path.basename(the_file)
split_up = os.path.splitext(base)
file_name = split_up[0]
file_extension = split_up[1]
new_file_name = "%s%s%s" % (file_name, date_to_append(), file_extension)
os.rename(the_file, new_file_name)
def move_old_todo():
for filename in os.listdir("."):
if filename.startswith('todo'):
shutil.move(filename, 'Archive')
def create_new_todo():
open(FILE, 'w')
rename_file(FILE)
move_old_todo()
create_new_todo()
|
633e3672c3f6f0200e45167ad5dc7608ef7f9e93 | run.py | run.py | #!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
app.debug = True
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
app.run()
| #!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
PORT = int(os.environ.get("PORT", 5000))
app.run(debug=True, host="0.0.0.0", port=PORT)
| Use Heroku post & open interface | Use Heroku post & open interface
| Python | bsd-3-clause | vanesa/kid-o,vanesa/kid-o,vanesa/kid-o,vanesa/kid-o | #!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
app.debug = True
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
app.run()
Use Heroku post & open interface | #!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
PORT = int(os.environ.get("PORT", 5000))
app.run(debug=True, host="0.0.0.0", port=PORT)
| <commit_before>#!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
app.debug = True
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
app.run()
<commit_msg>Use Heroku post & open interface<commit_after> | #!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
PORT = int(os.environ.get("PORT", 5000))
app.run(debug=True, host="0.0.0.0", port=PORT)
| #!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
app.debug = True
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
app.run()
Use Heroku post & open interface#!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
PORT = int(os.environ.get("PORT", 5000))
app.run(debug=True, host="0.0.0.0", port=PORT)
| <commit_before>#!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
app.debug = True
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
app.run()
<commit_msg>Use Heroku post & open interface<commit_after>#!/usr/bin/env python
from flask_debugtoolbar import DebugToolbarExtension
from app import app
from app.models import connect_to_db
if __name__ == '__main__':
# debug = True as DebugToolbarExtension is invoked
connect_to_db(app)
# User the DebugToolbar
# DebugToolbarExtension(app)
PORT = int(os.environ.get("PORT", 5000))
app.run(debug=True, host="0.0.0.0", port=PORT)
|
6cf782dc1b0d0cee2d234b36791be0deb64cd1de | run.py | run.py | import argparse
import os
import sys
from src.main import run
import logging
if __name__ == '__main__':
# Parse filename.
parser = argparse.ArgumentParser(description="TODO write description.")
parser.add_argument('--file', help='Transactions filename')
args = parser.parse_args()
username = os.environ['YNAB_USERNAME']
password = os.environ['YNAB_PASSWORD']
if not username:
print("No YNAB username provided")
sys.exit()
if not password:
print("No YNAB password provided")
sys.exit()
if not args.file:
print("Error: No filename provided")
sys.exit()
args.email = username
args.password = password
args.budgetname = "My Budget"
# Do not display pynYNAB logs in the console.
pynynab_logger = logging.getLogger('pynYNAB')
pynynab_logger.propagate = False
run(args)
| import argparse
import os
import sys
from src.main import run
import logging
from dotenv import find_dotenv, load_dotenv
if __name__ == '__main__':
# Parse filename.
parser = argparse.ArgumentParser(description="TODO write description.")
parser.add_argument('--file', help='Transactions filename')
args = parser.parse_args()
load_dotenv(find_dotenv())
username = os.environ['YNAB_USERNAME']
password = os.environ['YNAB_PASSWORD']
if not username:
print("No YNAB username provided")
sys.exit()
if not password:
print("No YNAB password provided")
sys.exit()
if not args.file:
print("Error: No filename provided")
sys.exit()
args.email = username
args.password = password
args.budgetname = "My Budget"
# Do not display pynYNAB logs in the console.
pynynab_logger = logging.getLogger('pynYNAB')
pynynab_logger.propagate = False
run(args)
| Read env variables with dotenv | Read env variables with dotenv
| Python | mit | Wisheri/Nordea-to-YNAB | import argparse
import os
import sys
from src.main import run
import logging
if __name__ == '__main__':
# Parse filename.
parser = argparse.ArgumentParser(description="TODO write description.")
parser.add_argument('--file', help='Transactions filename')
args = parser.parse_args()
username = os.environ['YNAB_USERNAME']
password = os.environ['YNAB_PASSWORD']
if not username:
print("No YNAB username provided")
sys.exit()
if not password:
print("No YNAB password provided")
sys.exit()
if not args.file:
print("Error: No filename provided")
sys.exit()
args.email = username
args.password = password
args.budgetname = "My Budget"
# Do not display pynYNAB logs in the console.
pynynab_logger = logging.getLogger('pynYNAB')
pynynab_logger.propagate = False
run(args)
Read env variables with dotenv | import argparse
import os
import sys
from src.main import run
import logging
from dotenv import find_dotenv, load_dotenv
if __name__ == '__main__':
# Parse filename.
parser = argparse.ArgumentParser(description="TODO write description.")
parser.add_argument('--file', help='Transactions filename')
args = parser.parse_args()
load_dotenv(find_dotenv())
username = os.environ['YNAB_USERNAME']
password = os.environ['YNAB_PASSWORD']
if not username:
print("No YNAB username provided")
sys.exit()
if not password:
print("No YNAB password provided")
sys.exit()
if not args.file:
print("Error: No filename provided")
sys.exit()
args.email = username
args.password = password
args.budgetname = "My Budget"
# Do not display pynYNAB logs in the console.
pynynab_logger = logging.getLogger('pynYNAB')
pynynab_logger.propagate = False
run(args)
| <commit_before>import argparse
import os
import sys
from src.main import run
import logging
if __name__ == '__main__':
# Parse filename.
parser = argparse.ArgumentParser(description="TODO write description.")
parser.add_argument('--file', help='Transactions filename')
args = parser.parse_args()
username = os.environ['YNAB_USERNAME']
password = os.environ['YNAB_PASSWORD']
if not username:
print("No YNAB username provided")
sys.exit()
if not password:
print("No YNAB password provided")
sys.exit()
if not args.file:
print("Error: No filename provided")
sys.exit()
args.email = username
args.password = password
args.budgetname = "My Budget"
# Do not display pynYNAB logs in the console.
pynynab_logger = logging.getLogger('pynYNAB')
pynynab_logger.propagate = False
run(args)
<commit_msg>Read env variables with dotenv<commit_after> | import argparse
import os
import sys
from src.main import run
import logging
from dotenv import find_dotenv, load_dotenv
if __name__ == '__main__':
# Parse filename.
parser = argparse.ArgumentParser(description="TODO write description.")
parser.add_argument('--file', help='Transactions filename')
args = parser.parse_args()
load_dotenv(find_dotenv())
username = os.environ['YNAB_USERNAME']
password = os.environ['YNAB_PASSWORD']
if not username:
print("No YNAB username provided")
sys.exit()
if not password:
print("No YNAB password provided")
sys.exit()
if not args.file:
print("Error: No filename provided")
sys.exit()
args.email = username
args.password = password
args.budgetname = "My Budget"
# Do not display pynYNAB logs in the console.
pynynab_logger = logging.getLogger('pynYNAB')
pynynab_logger.propagate = False
run(args)
| import argparse
import os
import sys
from src.main import run
import logging
if __name__ == '__main__':
# Parse filename.
parser = argparse.ArgumentParser(description="TODO write description.")
parser.add_argument('--file', help='Transactions filename')
args = parser.parse_args()
username = os.environ['YNAB_USERNAME']
password = os.environ['YNAB_PASSWORD']
if not username:
print("No YNAB username provided")
sys.exit()
if not password:
print("No YNAB password provided")
sys.exit()
if not args.file:
print("Error: No filename provided")
sys.exit()
args.email = username
args.password = password
args.budgetname = "My Budget"
# Do not display pynYNAB logs in the console.
pynynab_logger = logging.getLogger('pynYNAB')
pynynab_logger.propagate = False
run(args)
Read env variables with dotenvimport argparse
import os
import sys
from src.main import run
import logging
from dotenv import find_dotenv, load_dotenv
if __name__ == '__main__':
# Parse filename.
parser = argparse.ArgumentParser(description="TODO write description.")
parser.add_argument('--file', help='Transactions filename')
args = parser.parse_args()
load_dotenv(find_dotenv())
username = os.environ['YNAB_USERNAME']
password = os.environ['YNAB_PASSWORD']
if not username:
print("No YNAB username provided")
sys.exit()
if not password:
print("No YNAB password provided")
sys.exit()
if not args.file:
print("Error: No filename provided")
sys.exit()
args.email = username
args.password = password
args.budgetname = "My Budget"
# Do not display pynYNAB logs in the console.
pynynab_logger = logging.getLogger('pynYNAB')
pynynab_logger.propagate = False
run(args)
| <commit_before>import argparse
import os
import sys
from src.main import run
import logging
if __name__ == '__main__':
# Parse filename.
parser = argparse.ArgumentParser(description="TODO write description.")
parser.add_argument('--file', help='Transactions filename')
args = parser.parse_args()
username = os.environ['YNAB_USERNAME']
password = os.environ['YNAB_PASSWORD']
if not username:
print("No YNAB username provided")
sys.exit()
if not password:
print("No YNAB password provided")
sys.exit()
if not args.file:
print("Error: No filename provided")
sys.exit()
args.email = username
args.password = password
args.budgetname = "My Budget"
# Do not display pynYNAB logs in the console.
pynynab_logger = logging.getLogger('pynYNAB')
pynynab_logger.propagate = False
run(args)
<commit_msg>Read env variables with dotenv<commit_after>import argparse
import os
import sys
from src.main import run
import logging
from dotenv import find_dotenv, load_dotenv
if __name__ == '__main__':
# Parse filename.
parser = argparse.ArgumentParser(description="TODO write description.")
parser.add_argument('--file', help='Transactions filename')
args = parser.parse_args()
load_dotenv(find_dotenv())
username = os.environ['YNAB_USERNAME']
password = os.environ['YNAB_PASSWORD']
if not username:
print("No YNAB username provided")
sys.exit()
if not password:
print("No YNAB password provided")
sys.exit()
if not args.file:
print("Error: No filename provided")
sys.exit()
args.email = username
args.password = password
args.budgetname = "My Budget"
# Do not display pynYNAB logs in the console.
pynynab_logger = logging.getLogger('pynYNAB')
pynynab_logger.propagate = False
run(args)
|
67b2729c1c2a7027be7ad7a9d641609e94769671 | quickstart/python/autopilot/create-hello-world-samples/create_hello_world_samples.6.x.py | quickstart/python/autopilot/create-hello-world-samples/create_hello_world_samples.6.x.py | # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'hello',
'hi',
'Hello',
'Hi there'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
# Replace 'UDXXX...' with the SID for the task you just created.
for phrase in phrases:
sample = client.autopilot \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
| # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'hello',
'hi',
'Hello',
'Hi there'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
for phrase in phrases:
sample = client.autopilot \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('hello-world') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
| Update to use unique_name for task update | Update to use unique_name for task update | Python | mit | TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets | # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'hello',
'hi',
'Hello',
'Hi there'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
# Replace 'UDXXX...' with the SID for the task you just created.
for phrase in phrases:
sample = client.autopilot \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
Update to use unique_name for task update | # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'hello',
'hi',
'Hello',
'Hi there'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
for phrase in phrases:
sample = client.autopilot \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('hello-world') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
| <commit_before># Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'hello',
'hi',
'Hello',
'Hi there'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
# Replace 'UDXXX...' with the SID for the task you just created.
for phrase in phrases:
sample = client.autopilot \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
<commit_msg>Update to use unique_name for task update<commit_after> | # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'hello',
'hi',
'Hello',
'Hi there'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
for phrase in phrases:
sample = client.autopilot \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('hello-world') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
| # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'hello',
'hi',
'Hello',
'Hi there'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
# Replace 'UDXXX...' with the SID for the task you just created.
for phrase in phrases:
sample = client.autopilot \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
Update to use unique_name for task update# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'hello',
'hi',
'Hello',
'Hi there'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
for phrase in phrases:
sample = client.autopilot \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('hello-world') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
| <commit_before># Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'hello',
'hi',
'Hello',
'Hi there'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
# Replace 'UDXXX...' with the SID for the task you just created.
for phrase in phrases:
sample = client.autopilot \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
<commit_msg>Update to use unique_name for task update<commit_after># Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'hello',
'hi',
'Hello',
'Hi there'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
for phrase in phrases:
sample = client.autopilot \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('hello-world') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
|
6de7d5059d6d5fd2569f108e83fff0ae979aad89 | train_twitter_data.py | train_twitter_data.py | from sklearn.datasets import load_files
from sklearn.feature_extraction.text import CountVectorizer
categories = ['neg', 'pos']
twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42)
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(twitter_train.data)
print(X_train_counts.shape) | from sklearn.datasets import load_files
from sklearn.feature_extraction.text import CountVectorizer
categories = ['neg', 'pos']
twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42)
#Ignoring decode errors may harm our results, but at least it works now
count_vect = CountVectorizer(decode_error='ignore')
X_train_counts = count_vect.fit_transform(twitter_train.data)
print(X_train_counts.shape) | Make vectorizer Ignore decode errors | Make vectorizer Ignore decode errors
This isn't ideal and could harm our results, but it actually runs now. Figuring out the proper encoding would be better if possible.
| Python | apache-2.0 | ngrudzinski/sentiment_analysis_437 | from sklearn.datasets import load_files
from sklearn.feature_extraction.text import CountVectorizer
categories = ['neg', 'pos']
twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42)
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(twitter_train.data)
print(X_train_counts.shape)Make vectorizer Ignore decode errors
This isn't ideal and could harm our results, but it actually runs now. Figuring out the proper encoding would be better if possible. | from sklearn.datasets import load_files
from sklearn.feature_extraction.text import CountVectorizer
categories = ['neg', 'pos']
twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42)
#Ignoring decode errors may harm our results, but at least it works now
count_vect = CountVectorizer(decode_error='ignore')
X_train_counts = count_vect.fit_transform(twitter_train.data)
print(X_train_counts.shape) | <commit_before>from sklearn.datasets import load_files
from sklearn.feature_extraction.text import CountVectorizer
categories = ['neg', 'pos']
twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42)
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(twitter_train.data)
print(X_train_counts.shape)<commit_msg>Make vectorizer Ignore decode errors
This isn't ideal and could harm our results, but it actually runs now. Figuring out the proper encoding would be better if possible.<commit_after> | from sklearn.datasets import load_files
from sklearn.feature_extraction.text import CountVectorizer
categories = ['neg', 'pos']
twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42)
#Ignoring decode errors may harm our results, but at least it works now
count_vect = CountVectorizer(decode_error='ignore')
X_train_counts = count_vect.fit_transform(twitter_train.data)
print(X_train_counts.shape) | from sklearn.datasets import load_files
from sklearn.feature_extraction.text import CountVectorizer
categories = ['neg', 'pos']
twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42)
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(twitter_train.data)
print(X_train_counts.shape)Make vectorizer Ignore decode errors
This isn't ideal and could harm our results, but it actually runs now. Figuring out the proper encoding would be better if possible.from sklearn.datasets import load_files
from sklearn.feature_extraction.text import CountVectorizer
categories = ['neg', 'pos']
twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42)
#Ignoring decode errors may harm our results, but at least it works now
count_vect = CountVectorizer(decode_error='ignore')
X_train_counts = count_vect.fit_transform(twitter_train.data)
print(X_train_counts.shape) | <commit_before>from sklearn.datasets import load_files
from sklearn.feature_extraction.text import CountVectorizer
categories = ['neg', 'pos']
twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42)
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(twitter_train.data)
print(X_train_counts.shape)<commit_msg>Make vectorizer Ignore decode errors
This isn't ideal and could harm our results, but it actually runs now. Figuring out the proper encoding would be better if possible.<commit_after>from sklearn.datasets import load_files
from sklearn.feature_extraction.text import CountVectorizer
categories = ['neg', 'pos']
twitter_train = load_files('./twitter_data/twitter_data-train', categories=categories, load_content=True, shuffle=True, random_state=42)
#Ignoring decode errors may harm our results, but at least it works now
count_vect = CountVectorizer(decode_error='ignore')
X_train_counts = count_vect.fit_transform(twitter_train.data)
print(X_train_counts.shape) |
c1cd227e564ff1caf868068a182bf258aac47728 | python/testData/inspections/PyTypeCheckerInspection/MapArgumentsInOppositeOrderPy2.py | python/testData/inspections/PyTypeCheckerInspection/MapArgumentsInOppositeOrderPy2.py | map<warning descr="Unexpected type(s):(str, (c: Any) -> int)Possible types:(None, Iterable)((Any) -> Any, Iterable)">('foo', lambda c: 42)</warning>
| map<warning descr="Unexpected type(s):(str, (c: Any) -> int)Possible types:((Any) -> Any, Iterable)(None, Iterable)">('foo', lambda c: 42)</warning>
| Fix test data after syncing with typeshed | Fix test data after syncing with typeshed
| Python | apache-2.0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | map<warning descr="Unexpected type(s):(str, (c: Any) -> int)Possible types:(None, Iterable)((Any) -> Any, Iterable)">('foo', lambda c: 42)</warning>
Fix test data after syncing with typeshed | map<warning descr="Unexpected type(s):(str, (c: Any) -> int)Possible types:((Any) -> Any, Iterable)(None, Iterable)">('foo', lambda c: 42)</warning>
| <commit_before>map<warning descr="Unexpected type(s):(str, (c: Any) -> int)Possible types:(None, Iterable)((Any) -> Any, Iterable)">('foo', lambda c: 42)</warning>
<commit_msg>Fix test data after syncing with typeshed<commit_after> | map<warning descr="Unexpected type(s):(str, (c: Any) -> int)Possible types:((Any) -> Any, Iterable)(None, Iterable)">('foo', lambda c: 42)</warning>
| map<warning descr="Unexpected type(s):(str, (c: Any) -> int)Possible types:(None, Iterable)((Any) -> Any, Iterable)">('foo', lambda c: 42)</warning>
Fix test data after syncing with typeshedmap<warning descr="Unexpected type(s):(str, (c: Any) -> int)Possible types:((Any) -> Any, Iterable)(None, Iterable)">('foo', lambda c: 42)</warning>
| <commit_before>map<warning descr="Unexpected type(s):(str, (c: Any) -> int)Possible types:(None, Iterable)((Any) -> Any, Iterable)">('foo', lambda c: 42)</warning>
<commit_msg>Fix test data after syncing with typeshed<commit_after>map<warning descr="Unexpected type(s):(str, (c: Any) -> int)Possible types:((Any) -> Any, Iterable)(None, Iterable)">('foo', lambda c: 42)</warning>
|
40fd8c680f335ebd1bc217f35a47f169c336530c | pyosf/tools.py | pyosf/tools.py | # -*- coding: utf-8 -*-
"""
Part of the pyosf package
https://github.com/psychopy/pyosf/
Released under MIT license
@author: Jon Peirce
"""
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return (item for item in in_list if item[key] == val).next()
def dict_from_list(in_list, key):
"""From a list of dicts creates a dict of dicts using a given key name
"""
d = {}
for entry in in_list:
d[entry[key]] = entry
return d
| # -*- coding: utf-8 -*-
"""
Part of the pyosf package
https://github.com/psychopy/pyosf/
Released under MIT license
@author: Jon Peirce
"""
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return next(item for item in in_list if item[key] == val)
def dict_from_list(in_list, key):
"""From a list of dicts creates a dict of dicts using a given key name
"""
d = {}
for entry in in_list:
d[entry[key]] = entry
return d
| Fix compatibility with Py3 (generators no longer have next()) | Fix compatibility with Py3 (generators no longer have next())
But there is a next() function as a general built-in and works in 2.6 too
| Python | mit | psychopy/pyosf | # -*- coding: utf-8 -*-
"""
Part of the pyosf package
https://github.com/psychopy/pyosf/
Released under MIT license
@author: Jon Peirce
"""
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return (item for item in in_list if item[key] == val).next()
def dict_from_list(in_list, key):
"""From a list of dicts creates a dict of dicts using a given key name
"""
d = {}
for entry in in_list:
d[entry[key]] = entry
return d
Fix compatibility with Py3 (generators no longer have next())
But there is a next() function as a general built-in and works in 2.6 too | # -*- coding: utf-8 -*-
"""
Part of the pyosf package
https://github.com/psychopy/pyosf/
Released under MIT license
@author: Jon Peirce
"""
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return next(item for item in in_list if item[key] == val)
def dict_from_list(in_list, key):
"""From a list of dicts creates a dict of dicts using a given key name
"""
d = {}
for entry in in_list:
d[entry[key]] = entry
return d
| <commit_before># -*- coding: utf-8 -*-
"""
Part of the pyosf package
https://github.com/psychopy/pyosf/
Released under MIT license
@author: Jon Peirce
"""
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return (item for item in in_list if item[key] == val).next()
def dict_from_list(in_list, key):
"""From a list of dicts creates a dict of dicts using a given key name
"""
d = {}
for entry in in_list:
d[entry[key]] = entry
return d
<commit_msg>Fix compatibility with Py3 (generators no longer have next())
But there is a next() function as a general built-in and works in 2.6 too<commit_after> | # -*- coding: utf-8 -*-
"""
Part of the pyosf package
https://github.com/psychopy/pyosf/
Released under MIT license
@author: Jon Peirce
"""
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return next(item for item in in_list if item[key] == val)
def dict_from_list(in_list, key):
"""From a list of dicts creates a dict of dicts using a given key name
"""
d = {}
for entry in in_list:
d[entry[key]] = entry
return d
| # -*- coding: utf-8 -*-
"""
Part of the pyosf package
https://github.com/psychopy/pyosf/
Released under MIT license
@author: Jon Peirce
"""
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return (item for item in in_list if item[key] == val).next()
def dict_from_list(in_list, key):
"""From a list of dicts creates a dict of dicts using a given key name
"""
d = {}
for entry in in_list:
d[entry[key]] = entry
return d
Fix compatibility with Py3 (generators no longer have next())
But there is a next() function as a general built-in and works in 2.6 too# -*- coding: utf-8 -*-
"""
Part of the pyosf package
https://github.com/psychopy/pyosf/
Released under MIT license
@author: Jon Peirce
"""
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return next(item for item in in_list if item[key] == val)
def dict_from_list(in_list, key):
"""From a list of dicts creates a dict of dicts using a given key name
"""
d = {}
for entry in in_list:
d[entry[key]] = entry
return d
| <commit_before># -*- coding: utf-8 -*-
"""
Part of the pyosf package
https://github.com/psychopy/pyosf/
Released under MIT license
@author: Jon Peirce
"""
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return (item for item in in_list if item[key] == val).next()
def dict_from_list(in_list, key):
"""From a list of dicts creates a dict of dicts using a given key name
"""
d = {}
for entry in in_list:
d[entry[key]] = entry
return d
<commit_msg>Fix compatibility with Py3 (generators no longer have next())
But there is a next() function as a general built-in and works in 2.6 too<commit_after># -*- coding: utf-8 -*-
"""
Part of the pyosf package
https://github.com/psychopy/pyosf/
Released under MIT license
@author: Jon Peirce
"""
def find_by_key(in_list, key, val):
"""Returns the first item with key matching val
"""
return next(item for item in in_list if item[key] == val)
def dict_from_list(in_list, key):
"""From a list of dicts creates a dict of dicts using a given key name
"""
d = {}
for entry in in_list:
d[entry[key]] = entry
return d
|
3d91c12d3382226263ea3d660b48f1ef1125d099 | tests/basics/ordereddict1.py | tests/basics/ordereddict1.py | try:
from collections import OrderedDict
except ImportError:
try:
from ucollections import OrderedDict
except ImportError:
print("SKIP")
import sys
sys.exit()
d = OrderedDict([(10, 20), ("b", 100), (1, 2)])
print(list(d.keys()))
print(list(d.values()))
del d["b"]
print(list(d.keys()))
print(list(d.values()))
| try:
from collections import OrderedDict
except ImportError:
try:
from ucollections import OrderedDict
except ImportError:
print("SKIP")
import sys
sys.exit()
d = OrderedDict([(10, 20), ("b", 100), (1, 2)])
print(len(d))
print(list(d.keys()))
print(list(d.values()))
del d["b"]
print(len(d))
print(list(d.keys()))
print(list(d.values()))
# access remaining elements after deleting
print(d[10], d[1])
# add an element after deleting
d["abc"] = 123
print(len(d))
print(list(d.keys()))
print(list(d.values()))
| Add further tests for OrderedDict. | tests/basics: Add further tests for OrderedDict.
| Python | mit | pfalcon/micropython,kerneltask/micropython,torwag/micropython,selste/micropython,torwag/micropython,TDAbboud/micropython,blazewicz/micropython,bvernoux/micropython,TDAbboud/micropython,lowRISC/micropython,cwyark/micropython,oopy/micropython,infinnovation/micropython,dmazzella/micropython,MrSurly/micropython-esp32,MrSurly/micropython-esp32,lowRISC/micropython,SHA2017-badge/micropython-esp32,Timmenem/micropython,oopy/micropython,trezor/micropython,Peetz0r/micropython-esp32,trezor/micropython,MrSurly/micropython,pramasoul/micropython,puuu/micropython,adafruit/micropython,lowRISC/micropython,micropython/micropython-esp32,HenrikSolver/micropython,infinnovation/micropython,hiway/micropython,HenrikSolver/micropython,micropython/micropython-esp32,selste/micropython,deshipu/micropython,oopy/micropython,hiway/micropython,HenrikSolver/micropython,micropython/micropython-esp32,tralamazza/micropython,swegener/micropython,MrSurly/micropython,pozetroninc/micropython,deshipu/micropython,puuu/micropython,tralamazza/micropython,AriZuu/micropython,henriknelson/micropython,ryannathans/micropython,tobbad/micropython,hiway/micropython,tobbad/micropython,MrSurly/micropython,blazewicz/micropython,tobbad/micropython,alex-robbins/micropython,bvernoux/micropython,toolmacher/micropython,cwyark/micropython,bvernoux/micropython,deshipu/micropython,adafruit/circuitpython,PappaPeppar/micropython,chrisdearman/micropython,lowRISC/micropython,infinnovation/micropython,oopy/micropython,kerneltask/micropython,Peetz0r/micropython-esp32,blazewicz/micropython,ryannathans/micropython,TDAbboud/micropython,toolmacher/micropython,pfalcon/micropython,selste/micropython,pramasoul/micropython,adafruit/micropython,adafruit/circuitpython,HenrikSolver/micropython,chrisdearman/micropython,SHA2017-badge/micropython-esp32,Peetz0r/micropython-esp32,TDAbboud/micropython,tralamazza/micropython,TDAbboud/micropython,trezor/micropython,SHA2017-badge/micropython-esp32,toolmacher/micropython,chrisdearman/micropython,tobbad/micropython,swegener/micropython,bvernoux/micropython,AriZuu/micropython,pozetroninc/micropython,chrisdearman/micropython,Timmenem/micropython,Peetz0r/micropython-esp32,SHA2017-badge/micropython-esp32,AriZuu/micropython,ryannathans/micropython,AriZuu/micropython,lowRISC/micropython,Timmenem/micropython,dmazzella/micropython,Peetz0r/micropython-esp32,kerneltask/micropython,swegener/micropython,alex-robbins/micropython,deshipu/micropython,MrSurly/micropython-esp32,infinnovation/micropython,dmazzella/micropython,Timmenem/micropython,micropython/micropython-esp32,henriknelson/micropython,adafruit/micropython,kerneltask/micropython,MrSurly/micropython-esp32,adafruit/micropython,SHA2017-badge/micropython-esp32,cwyark/micropython,henriknelson/micropython,pfalcon/micropython,henriknelson/micropython,pfalcon/micropython,cwyark/micropython,adafruit/circuitpython,henriknelson/micropython,chrisdearman/micropython,deshipu/micropython,pramasoul/micropython,torwag/micropython,PappaPeppar/micropython,alex-robbins/micropython,adafruit/circuitpython,pfalcon/micropython,adafruit/circuitpython,alex-robbins/micropython,pramasoul/micropython,toolmacher/micropython,trezor/micropython,puuu/micropython,dmazzella/micropython,pozetroninc/micropython,torwag/micropython,ryannathans/micropython,HenrikSolver/micropython,AriZuu/micropython,ryannathans/micropython,Timmenem/micropython,MrSurly/micropython,toolmacher/micropython,PappaPeppar/micropython,selste/micropython,cwyark/micropython,puuu/micropython,MrSurly/micropython,swegener/micropython,swegener/micropython,tobbad/micropython,adafruit/circuitpython,hiway/micropython,puuu/micropython,PappaPeppar/micropython,PappaPeppar/micropython,hiway/micropython,torwag/micropython,kerneltask/micropython,pramasoul/micropython,blazewicz/micropython,bvernoux/micropython,oopy/micropython,MrSurly/micropython-esp32,pozetroninc/micropython,pozetroninc/micropython,trezor/micropython,adafruit/micropython,blazewicz/micropython,selste/micropython,micropython/micropython-esp32,tralamazza/micropython,alex-robbins/micropython,infinnovation/micropython | try:
from collections import OrderedDict
except ImportError:
try:
from ucollections import OrderedDict
except ImportError:
print("SKIP")
import sys
sys.exit()
d = OrderedDict([(10, 20), ("b", 100), (1, 2)])
print(list(d.keys()))
print(list(d.values()))
del d["b"]
print(list(d.keys()))
print(list(d.values()))
tests/basics: Add further tests for OrderedDict. | try:
from collections import OrderedDict
except ImportError:
try:
from ucollections import OrderedDict
except ImportError:
print("SKIP")
import sys
sys.exit()
d = OrderedDict([(10, 20), ("b", 100), (1, 2)])
print(len(d))
print(list(d.keys()))
print(list(d.values()))
del d["b"]
print(len(d))
print(list(d.keys()))
print(list(d.values()))
# access remaining elements after deleting
print(d[10], d[1])
# add an element after deleting
d["abc"] = 123
print(len(d))
print(list(d.keys()))
print(list(d.values()))
| <commit_before>try:
from collections import OrderedDict
except ImportError:
try:
from ucollections import OrderedDict
except ImportError:
print("SKIP")
import sys
sys.exit()
d = OrderedDict([(10, 20), ("b", 100), (1, 2)])
print(list(d.keys()))
print(list(d.values()))
del d["b"]
print(list(d.keys()))
print(list(d.values()))
<commit_msg>tests/basics: Add further tests for OrderedDict.<commit_after> | try:
from collections import OrderedDict
except ImportError:
try:
from ucollections import OrderedDict
except ImportError:
print("SKIP")
import sys
sys.exit()
d = OrderedDict([(10, 20), ("b", 100), (1, 2)])
print(len(d))
print(list(d.keys()))
print(list(d.values()))
del d["b"]
print(len(d))
print(list(d.keys()))
print(list(d.values()))
# access remaining elements after deleting
print(d[10], d[1])
# add an element after deleting
d["abc"] = 123
print(len(d))
print(list(d.keys()))
print(list(d.values()))
| try:
from collections import OrderedDict
except ImportError:
try:
from ucollections import OrderedDict
except ImportError:
print("SKIP")
import sys
sys.exit()
d = OrderedDict([(10, 20), ("b", 100), (1, 2)])
print(list(d.keys()))
print(list(d.values()))
del d["b"]
print(list(d.keys()))
print(list(d.values()))
tests/basics: Add further tests for OrderedDict.try:
from collections import OrderedDict
except ImportError:
try:
from ucollections import OrderedDict
except ImportError:
print("SKIP")
import sys
sys.exit()
d = OrderedDict([(10, 20), ("b", 100), (1, 2)])
print(len(d))
print(list(d.keys()))
print(list(d.values()))
del d["b"]
print(len(d))
print(list(d.keys()))
print(list(d.values()))
# access remaining elements after deleting
print(d[10], d[1])
# add an element after deleting
d["abc"] = 123
print(len(d))
print(list(d.keys()))
print(list(d.values()))
| <commit_before>try:
from collections import OrderedDict
except ImportError:
try:
from ucollections import OrderedDict
except ImportError:
print("SKIP")
import sys
sys.exit()
d = OrderedDict([(10, 20), ("b", 100), (1, 2)])
print(list(d.keys()))
print(list(d.values()))
del d["b"]
print(list(d.keys()))
print(list(d.values()))
<commit_msg>tests/basics: Add further tests for OrderedDict.<commit_after>try:
from collections import OrderedDict
except ImportError:
try:
from ucollections import OrderedDict
except ImportError:
print("SKIP")
import sys
sys.exit()
d = OrderedDict([(10, 20), ("b", 100), (1, 2)])
print(len(d))
print(list(d.keys()))
print(list(d.values()))
del d["b"]
print(len(d))
print(list(d.keys()))
print(list(d.values()))
# access remaining elements after deleting
print(d[10], d[1])
# add an element after deleting
d["abc"] = 123
print(len(d))
print(list(d.keys()))
print(list(d.values()))
|
9b02a09be67c8ec3d3b4b652d98f2cd5c3fdc863 | app/timetables/admin.py | app/timetables/admin.py | from django.contrib import admin
from .models import Course, Meal, MealOption, Weekday, Timetable, Dish
admin.site.register(Weekday)
admin.site.register(Meal)
admin.site.register(MealOption)
admin.site.register(Course)
admin.site.register(Timetable)
admin.site.register(Dish)
| from django.contrib import admin
from .models import *
admin.site.register(Weekday)
admin.site.register(Meal)
admin.site.register(MealOption)
admin.site.register(Course)
admin.site.register(Timetable)
admin.site.register(Dish)
admin.site.register(Admin)
| Add Timetables Admin model to Django Admin Interface | Add Timetables Admin model to Django Admin Interface
| Python | mit | teamtaverna/core | from django.contrib import admin
from .models import Course, Meal, MealOption, Weekday, Timetable, Dish
admin.site.register(Weekday)
admin.site.register(Meal)
admin.site.register(MealOption)
admin.site.register(Course)
admin.site.register(Timetable)
admin.site.register(Dish)
Add Timetables Admin model to Django Admin Interface | from django.contrib import admin
from .models import *
admin.site.register(Weekday)
admin.site.register(Meal)
admin.site.register(MealOption)
admin.site.register(Course)
admin.site.register(Timetable)
admin.site.register(Dish)
admin.site.register(Admin)
| <commit_before>from django.contrib import admin
from .models import Course, Meal, MealOption, Weekday, Timetable, Dish
admin.site.register(Weekday)
admin.site.register(Meal)
admin.site.register(MealOption)
admin.site.register(Course)
admin.site.register(Timetable)
admin.site.register(Dish)
<commit_msg>Add Timetables Admin model to Django Admin Interface<commit_after> | from django.contrib import admin
from .models import *
admin.site.register(Weekday)
admin.site.register(Meal)
admin.site.register(MealOption)
admin.site.register(Course)
admin.site.register(Timetable)
admin.site.register(Dish)
admin.site.register(Admin)
| from django.contrib import admin
from .models import Course, Meal, MealOption, Weekday, Timetable, Dish
admin.site.register(Weekday)
admin.site.register(Meal)
admin.site.register(MealOption)
admin.site.register(Course)
admin.site.register(Timetable)
admin.site.register(Dish)
Add Timetables Admin model to Django Admin Interfacefrom django.contrib import admin
from .models import *
admin.site.register(Weekday)
admin.site.register(Meal)
admin.site.register(MealOption)
admin.site.register(Course)
admin.site.register(Timetable)
admin.site.register(Dish)
admin.site.register(Admin)
| <commit_before>from django.contrib import admin
from .models import Course, Meal, MealOption, Weekday, Timetable, Dish
admin.site.register(Weekday)
admin.site.register(Meal)
admin.site.register(MealOption)
admin.site.register(Course)
admin.site.register(Timetable)
admin.site.register(Dish)
<commit_msg>Add Timetables Admin model to Django Admin Interface<commit_after>from django.contrib import admin
from .models import *
admin.site.register(Weekday)
admin.site.register(Meal)
admin.site.register(MealOption)
admin.site.register(Course)
admin.site.register(Timetable)
admin.site.register(Dish)
admin.site.register(Admin)
|
ff4e769102295280b9e5ad703c5b676f399df894 | test/test_basic.py | test/test_basic.py | import unittest
class MyTestCase(unittest.TestCase):
def test_something(self):
self.assertEqual(True, False)
if __name__ == '__main__':
unittest.main()
| import unittest
import openfigi
class MyTestCase(unittest.TestCase):
def test_wkn_ticker_anonymous(self):
"""Get an ETF by WKN and check if response makes sense"""
ofg = openfigi.OpenFigi()
ofg.enqueue_request(id_type='ID_WERTPAPIER', id_value='A0YEDG')
response = ofg.fetch_response()
self.assertTrue(type(response) is list)
self.assertTrue(len(response) > 0)
self.assertTrue(type(response[0]) is dict)
self.assertTrue('data' in response[0].keys())
self.assertTrue(len(response[0]['data']) > 0)
if __name__ == '__main__':
unittest.main()
| Add a basic unit test | Add a basic unit test
| Python | mit | jwergieluk/openfigi,jwergieluk/openfigi | import unittest
class MyTestCase(unittest.TestCase):
def test_something(self):
self.assertEqual(True, False)
if __name__ == '__main__':
unittest.main()
Add a basic unit test | import unittest
import openfigi
class MyTestCase(unittest.TestCase):
def test_wkn_ticker_anonymous(self):
"""Get an ETF by WKN and check if response makes sense"""
ofg = openfigi.OpenFigi()
ofg.enqueue_request(id_type='ID_WERTPAPIER', id_value='A0YEDG')
response = ofg.fetch_response()
self.assertTrue(type(response) is list)
self.assertTrue(len(response) > 0)
self.assertTrue(type(response[0]) is dict)
self.assertTrue('data' in response[0].keys())
self.assertTrue(len(response[0]['data']) > 0)
if __name__ == '__main__':
unittest.main()
| <commit_before>import unittest
class MyTestCase(unittest.TestCase):
def test_something(self):
self.assertEqual(True, False)
if __name__ == '__main__':
unittest.main()
<commit_msg>Add a basic unit test<commit_after> | import unittest
import openfigi
class MyTestCase(unittest.TestCase):
def test_wkn_ticker_anonymous(self):
"""Get an ETF by WKN and check if response makes sense"""
ofg = openfigi.OpenFigi()
ofg.enqueue_request(id_type='ID_WERTPAPIER', id_value='A0YEDG')
response = ofg.fetch_response()
self.assertTrue(type(response) is list)
self.assertTrue(len(response) > 0)
self.assertTrue(type(response[0]) is dict)
self.assertTrue('data' in response[0].keys())
self.assertTrue(len(response[0]['data']) > 0)
if __name__ == '__main__':
unittest.main()
| import unittest
class MyTestCase(unittest.TestCase):
def test_something(self):
self.assertEqual(True, False)
if __name__ == '__main__':
unittest.main()
Add a basic unit testimport unittest
import openfigi
class MyTestCase(unittest.TestCase):
def test_wkn_ticker_anonymous(self):
"""Get an ETF by WKN and check if response makes sense"""
ofg = openfigi.OpenFigi()
ofg.enqueue_request(id_type='ID_WERTPAPIER', id_value='A0YEDG')
response = ofg.fetch_response()
self.assertTrue(type(response) is list)
self.assertTrue(len(response) > 0)
self.assertTrue(type(response[0]) is dict)
self.assertTrue('data' in response[0].keys())
self.assertTrue(len(response[0]['data']) > 0)
if __name__ == '__main__':
unittest.main()
| <commit_before>import unittest
class MyTestCase(unittest.TestCase):
def test_something(self):
self.assertEqual(True, False)
if __name__ == '__main__':
unittest.main()
<commit_msg>Add a basic unit test<commit_after>import unittest
import openfigi
class MyTestCase(unittest.TestCase):
def test_wkn_ticker_anonymous(self):
"""Get an ETF by WKN and check if response makes sense"""
ofg = openfigi.OpenFigi()
ofg.enqueue_request(id_type='ID_WERTPAPIER', id_value='A0YEDG')
response = ofg.fetch_response()
self.assertTrue(type(response) is list)
self.assertTrue(len(response) > 0)
self.assertTrue(type(response[0]) is dict)
self.assertTrue('data' in response[0].keys())
self.assertTrue(len(response[0]['data']) > 0)
if __name__ == '__main__':
unittest.main()
|
23e57facea49ebc093d1da7a9ae6857cd2c8dad7 | warehouse/defaults.py | warehouse/defaults.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The type of Storage to use. Can be either Filesystem or S3.
STORAGE = "Filesystem"
# The hash to use in computing filenames.
# Allowed values: md5, sha1, sha224, sha256, sha384, sha512, None
STORAGE_HASH = "md5"
# Base directory for storage when using the Filesystem.
STORAGE_DIRECTORY = "data"
# The name of the bucket that files will be stored in when using S3.
# STORAGE_BUCKET = "<storage bucket>"
# The S3 Key used to access S3 when using S3 Storage
# S3_KEY = "<S3 Key>"
# The S3 Secret used to access S# when using S3 Storage
# S3_SECRET = "<S3 Secret>"
| from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The URI for our Redis database.
REDIS_URI = "redis://localhost:6379/0"
# The type of Storage to use. Can be either Filesystem or S3.
STORAGE = "Filesystem"
# The hash to use in computing filenames.
# Allowed values: md5, sha1, sha224, sha256, sha384, sha512, None
STORAGE_HASH = "md5"
# Base directory for storage when using the Filesystem.
STORAGE_DIRECTORY = "data"
# The name of the bucket that files will be stored in when using S3.
# STORAGE_BUCKET = "<storage bucket>"
# The S3 Key used to access S3 when using S3 Storage
# S3_KEY = "<S3 Key>"
# The S3 Secret used to access S# when using S3 Storage
# S3_SECRET = "<S3 Secret>"
| Add an explicit default for REDIS_URI | Add an explicit default for REDIS_URI
| Python | bsd-2-clause | davidfischer/warehouse | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The type of Storage to use. Can be either Filesystem or S3.
STORAGE = "Filesystem"
# The hash to use in computing filenames.
# Allowed values: md5, sha1, sha224, sha256, sha384, sha512, None
STORAGE_HASH = "md5"
# Base directory for storage when using the Filesystem.
STORAGE_DIRECTORY = "data"
# The name of the bucket that files will be stored in when using S3.
# STORAGE_BUCKET = "<storage bucket>"
# The S3 Key used to access S3 when using S3 Storage
# S3_KEY = "<S3 Key>"
# The S3 Secret used to access S# when using S3 Storage
# S3_SECRET = "<S3 Secret>"
Add an explicit default for REDIS_URI | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The URI for our Redis database.
REDIS_URI = "redis://localhost:6379/0"
# The type of Storage to use. Can be either Filesystem or S3.
STORAGE = "Filesystem"
# The hash to use in computing filenames.
# Allowed values: md5, sha1, sha224, sha256, sha384, sha512, None
STORAGE_HASH = "md5"
# Base directory for storage when using the Filesystem.
STORAGE_DIRECTORY = "data"
# The name of the bucket that files will be stored in when using S3.
# STORAGE_BUCKET = "<storage bucket>"
# The S3 Key used to access S3 when using S3 Storage
# S3_KEY = "<S3 Key>"
# The S3 Secret used to access S# when using S3 Storage
# S3_SECRET = "<S3 Secret>"
| <commit_before>from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The type of Storage to use. Can be either Filesystem or S3.
STORAGE = "Filesystem"
# The hash to use in computing filenames.
# Allowed values: md5, sha1, sha224, sha256, sha384, sha512, None
STORAGE_HASH = "md5"
# Base directory for storage when using the Filesystem.
STORAGE_DIRECTORY = "data"
# The name of the bucket that files will be stored in when using S3.
# STORAGE_BUCKET = "<storage bucket>"
# The S3 Key used to access S3 when using S3 Storage
# S3_KEY = "<S3 Key>"
# The S3 Secret used to access S# when using S3 Storage
# S3_SECRET = "<S3 Secret>"
<commit_msg>Add an explicit default for REDIS_URI<commit_after> | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The URI for our Redis database.
REDIS_URI = "redis://localhost:6379/0"
# The type of Storage to use. Can be either Filesystem or S3.
STORAGE = "Filesystem"
# The hash to use in computing filenames.
# Allowed values: md5, sha1, sha224, sha256, sha384, sha512, None
STORAGE_HASH = "md5"
# Base directory for storage when using the Filesystem.
STORAGE_DIRECTORY = "data"
# The name of the bucket that files will be stored in when using S3.
# STORAGE_BUCKET = "<storage bucket>"
# The S3 Key used to access S3 when using S3 Storage
# S3_KEY = "<S3 Key>"
# The S3 Secret used to access S# when using S3 Storage
# S3_SECRET = "<S3 Secret>"
| from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The type of Storage to use. Can be either Filesystem or S3.
STORAGE = "Filesystem"
# The hash to use in computing filenames.
# Allowed values: md5, sha1, sha224, sha256, sha384, sha512, None
STORAGE_HASH = "md5"
# Base directory for storage when using the Filesystem.
STORAGE_DIRECTORY = "data"
# The name of the bucket that files will be stored in when using S3.
# STORAGE_BUCKET = "<storage bucket>"
# The S3 Key used to access S3 when using S3 Storage
# S3_KEY = "<S3 Key>"
# The S3 Secret used to access S# when using S3 Storage
# S3_SECRET = "<S3 Secret>"
Add an explicit default for REDIS_URIfrom __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The URI for our Redis database.
REDIS_URI = "redis://localhost:6379/0"
# The type of Storage to use. Can be either Filesystem or S3.
STORAGE = "Filesystem"
# The hash to use in computing filenames.
# Allowed values: md5, sha1, sha224, sha256, sha384, sha512, None
STORAGE_HASH = "md5"
# Base directory for storage when using the Filesystem.
STORAGE_DIRECTORY = "data"
# The name of the bucket that files will be stored in when using S3.
# STORAGE_BUCKET = "<storage bucket>"
# The S3 Key used to access S3 when using S3 Storage
# S3_KEY = "<S3 Key>"
# The S3 Secret used to access S# when using S3 Storage
# S3_SECRET = "<S3 Secret>"
| <commit_before>from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The type of Storage to use. Can be either Filesystem or S3.
STORAGE = "Filesystem"
# The hash to use in computing filenames.
# Allowed values: md5, sha1, sha224, sha256, sha384, sha512, None
STORAGE_HASH = "md5"
# Base directory for storage when using the Filesystem.
STORAGE_DIRECTORY = "data"
# The name of the bucket that files will be stored in when using S3.
# STORAGE_BUCKET = "<storage bucket>"
# The S3 Key used to access S3 when using S3 Storage
# S3_KEY = "<S3 Key>"
# The S3 Secret used to access S# when using S3 Storage
# S3_SECRET = "<S3 Secret>"
<commit_msg>Add an explicit default for REDIS_URI<commit_after>from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The URI for our Redis database.
REDIS_URI = "redis://localhost:6379/0"
# The type of Storage to use. Can be either Filesystem or S3.
STORAGE = "Filesystem"
# The hash to use in computing filenames.
# Allowed values: md5, sha1, sha224, sha256, sha384, sha512, None
STORAGE_HASH = "md5"
# Base directory for storage when using the Filesystem.
STORAGE_DIRECTORY = "data"
# The name of the bucket that files will be stored in when using S3.
# STORAGE_BUCKET = "<storage bucket>"
# The S3 Key used to access S3 when using S3 Storage
# S3_KEY = "<S3 Key>"
# The S3 Secret used to access S# when using S3 Storage
# S3_SECRET = "<S3 Secret>"
|
443fe88d5a548033321232b866388ca92f8ef3d7 | server/lib/python/cartodb_services/cartodb_services/refactor/tools/redis_mock.py | server/lib/python/cartodb_services/cartodb_services/refactor/tools/redis_mock.py | class RedisConnectionMock(object):
""" Simple class to mock a dummy behaviour for Redis related functions """
def zscore(self, redis_prefix, day):
pass
def zincrby(self, redis_prefix, day, amount):
pass | class RedisConnectionMock(object):
""" Simple class to mock a dummy behaviour for Redis related functions """
def zscore(self, redis_prefix, day):
pass
def zincrby(self, redis_prefix, day, amount):
pass
| Add newline to end fle | Add newline to end fle | Python | bsd-3-clause | CartoDB/dataservices-api,CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/dataservices-api,CartoDB/geocoder-api,CartoDB/dataservices-api | class RedisConnectionMock(object):
""" Simple class to mock a dummy behaviour for Redis related functions """
def zscore(self, redis_prefix, day):
pass
def zincrby(self, redis_prefix, day, amount):
passAdd newline to end fle | class RedisConnectionMock(object):
""" Simple class to mock a dummy behaviour for Redis related functions """
def zscore(self, redis_prefix, day):
pass
def zincrby(self, redis_prefix, day, amount):
pass
| <commit_before>class RedisConnectionMock(object):
""" Simple class to mock a dummy behaviour for Redis related functions """
def zscore(self, redis_prefix, day):
pass
def zincrby(self, redis_prefix, day, amount):
pass<commit_msg>Add newline to end fle<commit_after> | class RedisConnectionMock(object):
""" Simple class to mock a dummy behaviour for Redis related functions """
def zscore(self, redis_prefix, day):
pass
def zincrby(self, redis_prefix, day, amount):
pass
| class RedisConnectionMock(object):
""" Simple class to mock a dummy behaviour for Redis related functions """
def zscore(self, redis_prefix, day):
pass
def zincrby(self, redis_prefix, day, amount):
passAdd newline to end fleclass RedisConnectionMock(object):
""" Simple class to mock a dummy behaviour for Redis related functions """
def zscore(self, redis_prefix, day):
pass
def zincrby(self, redis_prefix, day, amount):
pass
| <commit_before>class RedisConnectionMock(object):
""" Simple class to mock a dummy behaviour for Redis related functions """
def zscore(self, redis_prefix, day):
pass
def zincrby(self, redis_prefix, day, amount):
pass<commit_msg>Add newline to end fle<commit_after>class RedisConnectionMock(object):
""" Simple class to mock a dummy behaviour for Redis related functions """
def zscore(self, redis_prefix, day):
pass
def zincrby(self, redis_prefix, day, amount):
pass
|
494e7ff2e249a8202c8a71172be7f1870f56f9c3 | mcavatar/views/public/__init__.py | mcavatar/views/public/__init__.py | from flask import Blueprint
public = Blueprint('public', __name__, template_folder='templates')
@public.route('/')
def index():
return 'Hello World'
| from flask import Blueprint
public = Blueprint('public', __name__)
@public.route('/')
def index():
return 'Hello World'
| Remove blueprint specific template directories. | Remove blueprint specific template directories.
| Python | mit | joealcorn/MCAvatar | from flask import Blueprint
public = Blueprint('public', __name__, template_folder='templates')
@public.route('/')
def index():
return 'Hello World'
Remove blueprint specific template directories. | from flask import Blueprint
public = Blueprint('public', __name__)
@public.route('/')
def index():
return 'Hello World'
| <commit_before>from flask import Blueprint
public = Blueprint('public', __name__, template_folder='templates')
@public.route('/')
def index():
return 'Hello World'
<commit_msg>Remove blueprint specific template directories.<commit_after> | from flask import Blueprint
public = Blueprint('public', __name__)
@public.route('/')
def index():
return 'Hello World'
| from flask import Blueprint
public = Blueprint('public', __name__, template_folder='templates')
@public.route('/')
def index():
return 'Hello World'
Remove blueprint specific template directories.from flask import Blueprint
public = Blueprint('public', __name__)
@public.route('/')
def index():
return 'Hello World'
| <commit_before>from flask import Blueprint
public = Blueprint('public', __name__, template_folder='templates')
@public.route('/')
def index():
return 'Hello World'
<commit_msg>Remove blueprint specific template directories.<commit_after>from flask import Blueprint
public = Blueprint('public', __name__)
@public.route('/')
def index():
return 'Hello World'
|
22483d9ca6e393635ffdf371c35026f0e8ec429c | gyp/find.py | gyp/find.py | # Copyright 2015 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''
find.py is a poor-man's emulation of `find $1 -name=$2` on Unix.
Call python find.py <directory> <glob> to list all files matching glob under
directory (recursively). E.g.
$ python find.py ../tests/ '*.cpp'
will print all .cpp files under ../tests/.
'''
import fnmatch
import os
import sys
for d, kids, files in os.walk(sys.argv[1]):
for f in files:
if fnmatch.fnmatch(f, sys.argv[2]):
print os.path.join(d, f).replace('\\', '/') # Gyp wants Unix paths.
| # Copyright 2015 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''
find.py is a poor-man's emulation of `find $1 -name=$2` on Unix.
Call python find.py <directory> <glob> to list all files matching glob under
directory (recursively). E.g.
$ python find.py ../tests/ '*.cpp'
will print all .cpp files under ../tests/.
'''
import fnmatch
import os
import sys
for d, kids, files in os.walk(sys.argv[1]):
files.sort()
for f in files:
if fnmatch.fnmatch(f, sys.argv[2]):
print os.path.join(d, f).replace('\\', '/') # Gyp wants Unix paths.
| Sort build files for consistent link order. | Sort build files for consistent link order.
Prior to the introduction of find.py, GMs were liked in the order they
were listed in the gypi file, which was generally alphabetically. This
made it fairly easy to predict where slides would show up in SampleApp
and the order was consistent. This simply sorts the list of files in
find.py to restore the expectation that files should be listed in the
build in alphabetical order.
Review URL: https://codereview.chromium.org/1144973003
| Python | bsd-3-clause | rubenvb/skia,ominux/skia,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,vanish87/skia,tmpvar/skia.cc,pcwalton/skia,vanish87/skia,qrealka/skia-hc,ominux/skia,shahrzadmn/skia,google/skia,pcwalton/skia,nvoron23/skia,vanish87/skia,noselhq/skia,tmpvar/skia.cc,vanish87/skia,vanish87/skia,noselhq/skia,pcwalton/skia,tmpvar/skia.cc,Jichao/skia,nvoron23/skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,noselhq/skia,Jichao/skia,rubenvb/skia,aosp-mirror/platform_external_skia,Hikari-no-Tenshi/android_external_skia,Hikari-no-Tenshi/android_external_skia,Jichao/skia,HalCanary/skia-hc,rubenvb/skia,rubenvb/skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,nvoron23/skia,aosp-mirror/platform_external_skia,Jichao/skia,google/skia,nvoron23/skia,rubenvb/skia,rubenvb/skia,qrealka/skia-hc,rubenvb/skia,noselhq/skia,ominux/skia,pcwalton/skia,shahrzadmn/skia,ominux/skia,noselhq/skia,todotodoo/skia,noselhq/skia,todotodoo/skia,HalCanary/skia-hc,vanish87/skia,ominux/skia,aosp-mirror/platform_external_skia,qrealka/skia-hc,todotodoo/skia,google/skia,google/skia,todotodoo/skia,pcwalton/skia,google/skia,ominux/skia,HalCanary/skia-hc,shahrzadmn/skia,qrealka/skia-hc,HalCanary/skia-hc,google/skia,todotodoo/skia,Hikari-no-Tenshi/android_external_skia,ominux/skia,HalCanary/skia-hc,google/skia,shahrzadmn/skia,aosp-mirror/platform_external_skia,noselhq/skia,tmpvar/skia.cc,aosp-mirror/platform_external_skia,qrealka/skia-hc,aosp-mirror/platform_external_skia,qrealka/skia-hc,nvoron23/skia,shahrzadmn/skia,nvoron23/skia,pcwalton/skia,google/skia,rubenvb/skia,Jichao/skia,todotodoo/skia,ominux/skia,rubenvb/skia,todotodoo/skia,qrealka/skia-hc,Jichao/skia,vanish87/skia,pcwalton/skia,HalCanary/skia-hc,qrealka/skia-hc,todotodoo/skia,google/skia,Jichao/skia,nvoron23/skia,pcwalton/skia,vanish87/skia,HalCanary/skia-hc,shahrzadmn/skia,google/skia,tmpvar/skia.cc,shahrzadmn/skia,ominux/skia,shahrzadmn/skia,Jichao/skia,tmpvar/skia.cc,noselhq/skia,nvoron23/skia,todotodoo/skia,shahrzadmn/skia,tmpvar/skia.cc,tmpvar/skia.cc,nvoron23/skia,Hikari-no-Tenshi/android_external_skia,vanish87/skia,aosp-mirror/platform_external_skia,tmpvar/skia.cc,Hikari-no-Tenshi/android_external_skia,Jichao/skia,noselhq/skia,pcwalton/skia,HalCanary/skia-hc | # Copyright 2015 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''
find.py is a poor-man's emulation of `find $1 -name=$2` on Unix.
Call python find.py <directory> <glob> to list all files matching glob under
directory (recursively). E.g.
$ python find.py ../tests/ '*.cpp'
will print all .cpp files under ../tests/.
'''
import fnmatch
import os
import sys
for d, kids, files in os.walk(sys.argv[1]):
for f in files:
if fnmatch.fnmatch(f, sys.argv[2]):
print os.path.join(d, f).replace('\\', '/') # Gyp wants Unix paths.
Sort build files for consistent link order.
Prior to the introduction of find.py, GMs were liked in the order they
were listed in the gypi file, which was generally alphabetically. This
made it fairly easy to predict where slides would show up in SampleApp
and the order was consistent. This simply sorts the list of files in
find.py to restore the expectation that files should be listed in the
build in alphabetical order.
Review URL: https://codereview.chromium.org/1144973003 | # Copyright 2015 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''
find.py is a poor-man's emulation of `find $1 -name=$2` on Unix.
Call python find.py <directory> <glob> to list all files matching glob under
directory (recursively). E.g.
$ python find.py ../tests/ '*.cpp'
will print all .cpp files under ../tests/.
'''
import fnmatch
import os
import sys
for d, kids, files in os.walk(sys.argv[1]):
files.sort()
for f in files:
if fnmatch.fnmatch(f, sys.argv[2]):
print os.path.join(d, f).replace('\\', '/') # Gyp wants Unix paths.
| <commit_before># Copyright 2015 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''
find.py is a poor-man's emulation of `find $1 -name=$2` on Unix.
Call python find.py <directory> <glob> to list all files matching glob under
directory (recursively). E.g.
$ python find.py ../tests/ '*.cpp'
will print all .cpp files under ../tests/.
'''
import fnmatch
import os
import sys
for d, kids, files in os.walk(sys.argv[1]):
for f in files:
if fnmatch.fnmatch(f, sys.argv[2]):
print os.path.join(d, f).replace('\\', '/') # Gyp wants Unix paths.
<commit_msg>Sort build files for consistent link order.
Prior to the introduction of find.py, GMs were liked in the order they
were listed in the gypi file, which was generally alphabetically. This
made it fairly easy to predict where slides would show up in SampleApp
and the order was consistent. This simply sorts the list of files in
find.py to restore the expectation that files should be listed in the
build in alphabetical order.
Review URL: https://codereview.chromium.org/1144973003<commit_after> | # Copyright 2015 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''
find.py is a poor-man's emulation of `find $1 -name=$2` on Unix.
Call python find.py <directory> <glob> to list all files matching glob under
directory (recursively). E.g.
$ python find.py ../tests/ '*.cpp'
will print all .cpp files under ../tests/.
'''
import fnmatch
import os
import sys
for d, kids, files in os.walk(sys.argv[1]):
files.sort()
for f in files:
if fnmatch.fnmatch(f, sys.argv[2]):
print os.path.join(d, f).replace('\\', '/') # Gyp wants Unix paths.
| # Copyright 2015 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''
find.py is a poor-man's emulation of `find $1 -name=$2` on Unix.
Call python find.py <directory> <glob> to list all files matching glob under
directory (recursively). E.g.
$ python find.py ../tests/ '*.cpp'
will print all .cpp files under ../tests/.
'''
import fnmatch
import os
import sys
for d, kids, files in os.walk(sys.argv[1]):
for f in files:
if fnmatch.fnmatch(f, sys.argv[2]):
print os.path.join(d, f).replace('\\', '/') # Gyp wants Unix paths.
Sort build files for consistent link order.
Prior to the introduction of find.py, GMs were liked in the order they
were listed in the gypi file, which was generally alphabetically. This
made it fairly easy to predict where slides would show up in SampleApp
and the order was consistent. This simply sorts the list of files in
find.py to restore the expectation that files should be listed in the
build in alphabetical order.
Review URL: https://codereview.chromium.org/1144973003# Copyright 2015 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''
find.py is a poor-man's emulation of `find $1 -name=$2` on Unix.
Call python find.py <directory> <glob> to list all files matching glob under
directory (recursively). E.g.
$ python find.py ../tests/ '*.cpp'
will print all .cpp files under ../tests/.
'''
import fnmatch
import os
import sys
for d, kids, files in os.walk(sys.argv[1]):
files.sort()
for f in files:
if fnmatch.fnmatch(f, sys.argv[2]):
print os.path.join(d, f).replace('\\', '/') # Gyp wants Unix paths.
| <commit_before># Copyright 2015 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''
find.py is a poor-man's emulation of `find $1 -name=$2` on Unix.
Call python find.py <directory> <glob> to list all files matching glob under
directory (recursively). E.g.
$ python find.py ../tests/ '*.cpp'
will print all .cpp files under ../tests/.
'''
import fnmatch
import os
import sys
for d, kids, files in os.walk(sys.argv[1]):
for f in files:
if fnmatch.fnmatch(f, sys.argv[2]):
print os.path.join(d, f).replace('\\', '/') # Gyp wants Unix paths.
<commit_msg>Sort build files for consistent link order.
Prior to the introduction of find.py, GMs were liked in the order they
were listed in the gypi file, which was generally alphabetically. This
made it fairly easy to predict where slides would show up in SampleApp
and the order was consistent. This simply sorts the list of files in
find.py to restore the expectation that files should be listed in the
build in alphabetical order.
Review URL: https://codereview.chromium.org/1144973003<commit_after># Copyright 2015 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''
find.py is a poor-man's emulation of `find $1 -name=$2` on Unix.
Call python find.py <directory> <glob> to list all files matching glob under
directory (recursively). E.g.
$ python find.py ../tests/ '*.cpp'
will print all .cpp files under ../tests/.
'''
import fnmatch
import os
import sys
for d, kids, files in os.walk(sys.argv[1]):
files.sort()
for f in files:
if fnmatch.fnmatch(f, sys.argv[2]):
print os.path.join(d, f).replace('\\', '/') # Gyp wants Unix paths.
|
ddfeb1e9ef60e1913bf702e58cf4696cf7c98c6d | logicmind/token_parser.py | logicmind/token_parser.py | from tokens.andd import And
from tokens.expression import Expression
from tokens.iff import Iff
from tokens.nop import Not
from tokens.orr import Or
from tokens.then import Then
from tokens.variable import Variable
class TokenParser:
"""This parser only works with atomic expressions,
so parenthesis are needed everywhere to group items"""
@staticmethod
def parse_expression(string):
# Separate parenthesis so they're new tokens
# Also convert [ or { to the same parenthesis (
for s in '([{':
string = string.replace(s, ' ( ')
for s in ')]}':
string = string.replace(s, ' ) ')
# Get all the tokens
words = string.split()
expressions_stack = [Expression()]
for w in words:
if w == '(':
expressions_stack.append(Expression())
elif w == ')':
e = expressions_stack.pop()
expressions_stack[-1].add_token(e)
elif w == '¬':
expressions_stack[-1].add_token(Not())
elif w == '->':
expressions_stack[-1].add_token(Then())
elif w == '<->':
expressions_stack[-1].add_token(Iff())
elif w == 'v':
expressions_stack[-1].add_token(Or())
elif w == '^':
expressions_stack[-1].add_token(And())
else:
expressions_stack[-1].add_token(Variable(w))
return expressions_stack[0]
| from tokens.andd import And
from tokens.expression import Expression
from tokens.iff import Iff
from tokens.nop import Not
from tokens.orr import Or
from tokens.then import Then
from tokens.variable import Variable
class TokenParser:
"""This parser only works with atomic expressions,
so parenthesis are needed everywhere to group items"""
@staticmethod
def parse_expression(string):
# Separate parenthesis so they're new tokens
# Also convert [ or { to the same parenthesis (
for s in '([{':
string = string.replace(s, ' ( ')
for s in ')]}':
string = string.replace(s, ' ) ')
# Get all operators so we can iterate over them
operators = [Not, Then, Iff, Or, And]
# Get all the tokens
words = string.split()
# Store the found nested expressions on the stack
expressions_stack = [Expression()]
for w in words:
done = False
for operator in operators:
if w in operator.representations:
expressions_stack[-1].add_token(operator())
done = True
break
if done:
pass
elif w == '(':
expressions_stack.append(Expression())
elif w == ')':
e = expressions_stack.pop()
expressions_stack[-1].add_token(e)
else:
expressions_stack[-1].add_token(Variable(w))
return expressions_stack[0]
| Allow more representations when parsing | [logicmind] Allow more representations when parsing
| Python | mit | LonamiWebs/Py-Utils | from tokens.andd import And
from tokens.expression import Expression
from tokens.iff import Iff
from tokens.nop import Not
from tokens.orr import Or
from tokens.then import Then
from tokens.variable import Variable
class TokenParser:
"""This parser only works with atomic expressions,
so parenthesis are needed everywhere to group items"""
@staticmethod
def parse_expression(string):
# Separate parenthesis so they're new tokens
# Also convert [ or { to the same parenthesis (
for s in '([{':
string = string.replace(s, ' ( ')
for s in ')]}':
string = string.replace(s, ' ) ')
# Get all the tokens
words = string.split()
expressions_stack = [Expression()]
for w in words:
if w == '(':
expressions_stack.append(Expression())
elif w == ')':
e = expressions_stack.pop()
expressions_stack[-1].add_token(e)
elif w == '¬':
expressions_stack[-1].add_token(Not())
elif w == '->':
expressions_stack[-1].add_token(Then())
elif w == '<->':
expressions_stack[-1].add_token(Iff())
elif w == 'v':
expressions_stack[-1].add_token(Or())
elif w == '^':
expressions_stack[-1].add_token(And())
else:
expressions_stack[-1].add_token(Variable(w))
return expressions_stack[0]
[logicmind] Allow more representations when parsing | from tokens.andd import And
from tokens.expression import Expression
from tokens.iff import Iff
from tokens.nop import Not
from tokens.orr import Or
from tokens.then import Then
from tokens.variable import Variable
class TokenParser:
"""This parser only works with atomic expressions,
so parenthesis are needed everywhere to group items"""
@staticmethod
def parse_expression(string):
# Separate parenthesis so they're new tokens
# Also convert [ or { to the same parenthesis (
for s in '([{':
string = string.replace(s, ' ( ')
for s in ')]}':
string = string.replace(s, ' ) ')
# Get all operators so we can iterate over them
operators = [Not, Then, Iff, Or, And]
# Get all the tokens
words = string.split()
# Store the found nested expressions on the stack
expressions_stack = [Expression()]
for w in words:
done = False
for operator in operators:
if w in operator.representations:
expressions_stack[-1].add_token(operator())
done = True
break
if done:
pass
elif w == '(':
expressions_stack.append(Expression())
elif w == ')':
e = expressions_stack.pop()
expressions_stack[-1].add_token(e)
else:
expressions_stack[-1].add_token(Variable(w))
return expressions_stack[0]
| <commit_before>from tokens.andd import And
from tokens.expression import Expression
from tokens.iff import Iff
from tokens.nop import Not
from tokens.orr import Or
from tokens.then import Then
from tokens.variable import Variable
class TokenParser:
"""This parser only works with atomic expressions,
so parenthesis are needed everywhere to group items"""
@staticmethod
def parse_expression(string):
# Separate parenthesis so they're new tokens
# Also convert [ or { to the same parenthesis (
for s in '([{':
string = string.replace(s, ' ( ')
for s in ')]}':
string = string.replace(s, ' ) ')
# Get all the tokens
words = string.split()
expressions_stack = [Expression()]
for w in words:
if w == '(':
expressions_stack.append(Expression())
elif w == ')':
e = expressions_stack.pop()
expressions_stack[-1].add_token(e)
elif w == '¬':
expressions_stack[-1].add_token(Not())
elif w == '->':
expressions_stack[-1].add_token(Then())
elif w == '<->':
expressions_stack[-1].add_token(Iff())
elif w == 'v':
expressions_stack[-1].add_token(Or())
elif w == '^':
expressions_stack[-1].add_token(And())
else:
expressions_stack[-1].add_token(Variable(w))
return expressions_stack[0]
<commit_msg>[logicmind] Allow more representations when parsing<commit_after> | from tokens.andd import And
from tokens.expression import Expression
from tokens.iff import Iff
from tokens.nop import Not
from tokens.orr import Or
from tokens.then import Then
from tokens.variable import Variable
class TokenParser:
"""This parser only works with atomic expressions,
so parenthesis are needed everywhere to group items"""
@staticmethod
def parse_expression(string):
# Separate parenthesis so they're new tokens
# Also convert [ or { to the same parenthesis (
for s in '([{':
string = string.replace(s, ' ( ')
for s in ')]}':
string = string.replace(s, ' ) ')
# Get all operators so we can iterate over them
operators = [Not, Then, Iff, Or, And]
# Get all the tokens
words = string.split()
# Store the found nested expressions on the stack
expressions_stack = [Expression()]
for w in words:
done = False
for operator in operators:
if w in operator.representations:
expressions_stack[-1].add_token(operator())
done = True
break
if done:
pass
elif w == '(':
expressions_stack.append(Expression())
elif w == ')':
e = expressions_stack.pop()
expressions_stack[-1].add_token(e)
else:
expressions_stack[-1].add_token(Variable(w))
return expressions_stack[0]
| from tokens.andd import And
from tokens.expression import Expression
from tokens.iff import Iff
from tokens.nop import Not
from tokens.orr import Or
from tokens.then import Then
from tokens.variable import Variable
class TokenParser:
"""This parser only works with atomic expressions,
so parenthesis are needed everywhere to group items"""
@staticmethod
def parse_expression(string):
# Separate parenthesis so they're new tokens
# Also convert [ or { to the same parenthesis (
for s in '([{':
string = string.replace(s, ' ( ')
for s in ')]}':
string = string.replace(s, ' ) ')
# Get all the tokens
words = string.split()
expressions_stack = [Expression()]
for w in words:
if w == '(':
expressions_stack.append(Expression())
elif w == ')':
e = expressions_stack.pop()
expressions_stack[-1].add_token(e)
elif w == '¬':
expressions_stack[-1].add_token(Not())
elif w == '->':
expressions_stack[-1].add_token(Then())
elif w == '<->':
expressions_stack[-1].add_token(Iff())
elif w == 'v':
expressions_stack[-1].add_token(Or())
elif w == '^':
expressions_stack[-1].add_token(And())
else:
expressions_stack[-1].add_token(Variable(w))
return expressions_stack[0]
[logicmind] Allow more representations when parsingfrom tokens.andd import And
from tokens.expression import Expression
from tokens.iff import Iff
from tokens.nop import Not
from tokens.orr import Or
from tokens.then import Then
from tokens.variable import Variable
class TokenParser:
"""This parser only works with atomic expressions,
so parenthesis are needed everywhere to group items"""
@staticmethod
def parse_expression(string):
# Separate parenthesis so they're new tokens
# Also convert [ or { to the same parenthesis (
for s in '([{':
string = string.replace(s, ' ( ')
for s in ')]}':
string = string.replace(s, ' ) ')
# Get all operators so we can iterate over them
operators = [Not, Then, Iff, Or, And]
# Get all the tokens
words = string.split()
# Store the found nested expressions on the stack
expressions_stack = [Expression()]
for w in words:
done = False
for operator in operators:
if w in operator.representations:
expressions_stack[-1].add_token(operator())
done = True
break
if done:
pass
elif w == '(':
expressions_stack.append(Expression())
elif w == ')':
e = expressions_stack.pop()
expressions_stack[-1].add_token(e)
else:
expressions_stack[-1].add_token(Variable(w))
return expressions_stack[0]
| <commit_before>from tokens.andd import And
from tokens.expression import Expression
from tokens.iff import Iff
from tokens.nop import Not
from tokens.orr import Or
from tokens.then import Then
from tokens.variable import Variable
class TokenParser:
"""This parser only works with atomic expressions,
so parenthesis are needed everywhere to group items"""
@staticmethod
def parse_expression(string):
# Separate parenthesis so they're new tokens
# Also convert [ or { to the same parenthesis (
for s in '([{':
string = string.replace(s, ' ( ')
for s in ')]}':
string = string.replace(s, ' ) ')
# Get all the tokens
words = string.split()
expressions_stack = [Expression()]
for w in words:
if w == '(':
expressions_stack.append(Expression())
elif w == ')':
e = expressions_stack.pop()
expressions_stack[-1].add_token(e)
elif w == '¬':
expressions_stack[-1].add_token(Not())
elif w == '->':
expressions_stack[-1].add_token(Then())
elif w == '<->':
expressions_stack[-1].add_token(Iff())
elif w == 'v':
expressions_stack[-1].add_token(Or())
elif w == '^':
expressions_stack[-1].add_token(And())
else:
expressions_stack[-1].add_token(Variable(w))
return expressions_stack[0]
<commit_msg>[logicmind] Allow more representations when parsing<commit_after>from tokens.andd import And
from tokens.expression import Expression
from tokens.iff import Iff
from tokens.nop import Not
from tokens.orr import Or
from tokens.then import Then
from tokens.variable import Variable
class TokenParser:
"""This parser only works with atomic expressions,
so parenthesis are needed everywhere to group items"""
@staticmethod
def parse_expression(string):
# Separate parenthesis so they're new tokens
# Also convert [ or { to the same parenthesis (
for s in '([{':
string = string.replace(s, ' ( ')
for s in ')]}':
string = string.replace(s, ' ) ')
# Get all operators so we can iterate over them
operators = [Not, Then, Iff, Or, And]
# Get all the tokens
words = string.split()
# Store the found nested expressions on the stack
expressions_stack = [Expression()]
for w in words:
done = False
for operator in operators:
if w in operator.representations:
expressions_stack[-1].add_token(operator())
done = True
break
if done:
pass
elif w == '(':
expressions_stack.append(Expression())
elif w == ')':
e = expressions_stack.pop()
expressions_stack[-1].add_token(e)
else:
expressions_stack[-1].add_token(Variable(w))
return expressions_stack[0]
|
a959468bf210869a3d770d58f2ebd3fe70c640ab | imagr_site/urls.py | imagr_site/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^imagr/', include('imagr.urls', namespace='imagr')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('registration.backends.default.urls'))
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^', include('imagr.urls', namespace='imagr')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('registration.backends.default.urls'))
)
| Change root site to just / not imagr/ | Change root site to just / not imagr/
| Python | mit | markableidinger/django_imagr | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^imagr/', include('imagr.urls', namespace='imagr')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('registration.backends.default.urls'))
)
Change root site to just / not imagr/ | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^', include('imagr.urls', namespace='imagr')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('registration.backends.default.urls'))
)
| <commit_before>from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^imagr/', include('imagr.urls', namespace='imagr')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('registration.backends.default.urls'))
)
<commit_msg>Change root site to just / not imagr/<commit_after> | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^', include('imagr.urls', namespace='imagr')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('registration.backends.default.urls'))
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^imagr/', include('imagr.urls', namespace='imagr')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('registration.backends.default.urls'))
)
Change root site to just / not imagr/from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^', include('imagr.urls', namespace='imagr')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('registration.backends.default.urls'))
)
| <commit_before>from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^imagr/', include('imagr.urls', namespace='imagr')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('registration.backends.default.urls'))
)
<commit_msg>Change root site to just / not imagr/<commit_after>from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^', include('imagr.urls', namespace='imagr')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('registration.backends.default.urls'))
)
|
54902242c1e194f36ecc028c0c56c9a99e61eb6a | axes/management/commands/axes_reset.py | axes/management/commands/axes_reset.py | from django.core.management.base import BaseCommand
from axes.utils import reset
class Command(BaseCommand):
help = ("resets any lockouts or failed login records. If called with an "
"IP, resets only for that IP")
def add_arguments(self, parser):
parser.add_argument('ip', nargs='*')
def handle(self, *args, **kwargs):
count = 0
if kwargs and kwargs.get('ip'):
for ip in kwargs['ip']:
count += reset(ip=ip)
else:
count = reset()
if count:
print('{0} attempts removed.'.format(count))
else:
print('No attempts found.')
| from django.core.management.base import BaseCommand
from axes.utils import reset
class Command(BaseCommand):
help = ("resets any lockouts or failed login records. If called with an "
"IP, resets only for that IP")
def add_arguments(self, parser):
parser.add_argument('ip', nargs='*')
def handle(self, *args, **kwargs):
count = 0
if kwargs and kwargs.get('ip'):
for ip in kwargs['ip'][1:]:
count += reset(ip=ip)
else:
count = reset()
if count:
print('{0} attempts removed.'.format(count))
else:
print('No attempts found.')
| Fix bug when using the optional IP parameter | Fix bug when using the optional IP parameter
When the IP parameter is used the first element of kwargs needs to be skipped because its value is the string 'ip'. | Python | mit | django-pci/django-axes,jazzband/django-axes | from django.core.management.base import BaseCommand
from axes.utils import reset
class Command(BaseCommand):
help = ("resets any lockouts or failed login records. If called with an "
"IP, resets only for that IP")
def add_arguments(self, parser):
parser.add_argument('ip', nargs='*')
def handle(self, *args, **kwargs):
count = 0
if kwargs and kwargs.get('ip'):
for ip in kwargs['ip']:
count += reset(ip=ip)
else:
count = reset()
if count:
print('{0} attempts removed.'.format(count))
else:
print('No attempts found.')
Fix bug when using the optional IP parameter
When the IP parameter is used the first element of kwargs needs to be skipped because its value is the string 'ip'. | from django.core.management.base import BaseCommand
from axes.utils import reset
class Command(BaseCommand):
help = ("resets any lockouts or failed login records. If called with an "
"IP, resets only for that IP")
def add_arguments(self, parser):
parser.add_argument('ip', nargs='*')
def handle(self, *args, **kwargs):
count = 0
if kwargs and kwargs.get('ip'):
for ip in kwargs['ip'][1:]:
count += reset(ip=ip)
else:
count = reset()
if count:
print('{0} attempts removed.'.format(count))
else:
print('No attempts found.')
| <commit_before>from django.core.management.base import BaseCommand
from axes.utils import reset
class Command(BaseCommand):
help = ("resets any lockouts or failed login records. If called with an "
"IP, resets only for that IP")
def add_arguments(self, parser):
parser.add_argument('ip', nargs='*')
def handle(self, *args, **kwargs):
count = 0
if kwargs and kwargs.get('ip'):
for ip in kwargs['ip']:
count += reset(ip=ip)
else:
count = reset()
if count:
print('{0} attempts removed.'.format(count))
else:
print('No attempts found.')
<commit_msg>Fix bug when using the optional IP parameter
When the IP parameter is used the first element of kwargs needs to be skipped because its value is the string 'ip'.<commit_after> | from django.core.management.base import BaseCommand
from axes.utils import reset
class Command(BaseCommand):
help = ("resets any lockouts or failed login records. If called with an "
"IP, resets only for that IP")
def add_arguments(self, parser):
parser.add_argument('ip', nargs='*')
def handle(self, *args, **kwargs):
count = 0
if kwargs and kwargs.get('ip'):
for ip in kwargs['ip'][1:]:
count += reset(ip=ip)
else:
count = reset()
if count:
print('{0} attempts removed.'.format(count))
else:
print('No attempts found.')
| from django.core.management.base import BaseCommand
from axes.utils import reset
class Command(BaseCommand):
help = ("resets any lockouts or failed login records. If called with an "
"IP, resets only for that IP")
def add_arguments(self, parser):
parser.add_argument('ip', nargs='*')
def handle(self, *args, **kwargs):
count = 0
if kwargs and kwargs.get('ip'):
for ip in kwargs['ip']:
count += reset(ip=ip)
else:
count = reset()
if count:
print('{0} attempts removed.'.format(count))
else:
print('No attempts found.')
Fix bug when using the optional IP parameter
When the IP parameter is used the first element of kwargs needs to be skipped because its value is the string 'ip'.from django.core.management.base import BaseCommand
from axes.utils import reset
class Command(BaseCommand):
help = ("resets any lockouts or failed login records. If called with an "
"IP, resets only for that IP")
def add_arguments(self, parser):
parser.add_argument('ip', nargs='*')
def handle(self, *args, **kwargs):
count = 0
if kwargs and kwargs.get('ip'):
for ip in kwargs['ip'][1:]:
count += reset(ip=ip)
else:
count = reset()
if count:
print('{0} attempts removed.'.format(count))
else:
print('No attempts found.')
| <commit_before>from django.core.management.base import BaseCommand
from axes.utils import reset
class Command(BaseCommand):
help = ("resets any lockouts or failed login records. If called with an "
"IP, resets only for that IP")
def add_arguments(self, parser):
parser.add_argument('ip', nargs='*')
def handle(self, *args, **kwargs):
count = 0
if kwargs and kwargs.get('ip'):
for ip in kwargs['ip']:
count += reset(ip=ip)
else:
count = reset()
if count:
print('{0} attempts removed.'.format(count))
else:
print('No attempts found.')
<commit_msg>Fix bug when using the optional IP parameter
When the IP parameter is used the first element of kwargs needs to be skipped because its value is the string 'ip'.<commit_after>from django.core.management.base import BaseCommand
from axes.utils import reset
class Command(BaseCommand):
help = ("resets any lockouts or failed login records. If called with an "
"IP, resets only for that IP")
def add_arguments(self, parser):
parser.add_argument('ip', nargs='*')
def handle(self, *args, **kwargs):
count = 0
if kwargs and kwargs.get('ip'):
for ip in kwargs['ip'][1:]:
count += reset(ip=ip)
else:
count = reset()
if count:
print('{0} attempts removed.'.format(count))
else:
print('No attempts found.')
|
5167ec5f2ba30e649e6fd9b2994995a6022bfda3 | client.py | client.py | #!/usr/bin/env python
# Auto-launching using this: export PROMPT_COMMAND='/Users/putilin/client.py "`fc -nl -1`"'
import requests
import sys
import os
import re
assert len(sys.argv) == 2
history_output = sys.argv[1]
m = re.match(r"[ ]*(\d+)[ ][ ](.*)", history_output)
command_id = m.group(1)
command_text = m.group(2)
USERNAME = "eleweek"
HOST = "histsync.herokuapp.com"
API_KEY = "61f33ca6-50d3-4eea-a924-e9b7b6f86ed4"
payload = {'api_key': API_KEY, 'command_text': command_text, "id": '{}${}'.format(os.getppid(), command_id)}
print payload
r = requests.post("http://{}/api/v0/user/{}/add_command".format(HOST, USERNAME), data=payload)
r.raise_for_status()
| #!/usr/bin/env python
# Auto-launching using this: export PROMPT_COMMAND='/Users/putilin/client.py "`fc -nl -1`"'
import os
import sys
shell_pid = os.getppid()
if os.fork() != 0:
sys.exit()
import requests
import re
assert len(sys.argv) == 2
history_output = sys.argv[1]
m = re.match(r"[ ]*(\d+)[ ][ ](.*)", history_output)
command_id = m.group(1)
command_text = m.group(2)
USERNAME = "eleweek"
HOST = "histsync.herokuapp.com"
API_KEY = "9b946c76-1688-4d3d-9b13-c4d25ef878ef"
payload = {'api_key': API_KEY, 'command_text': command_text, "id": '{}${}'.format(shell_pid, command_id)}
r = requests.post("http://{}/api/v0/user/{}/add_command".format(HOST, USERNAME), data=payload)
r.raise_for_status()
| Send command in the child process | Send command in the child process
| Python | mit | elimohl/histsync,oxyzero/histsync,eleweek/histsync,elimohl/histsync,elimohl/histsync,oxyzero/histsync,eleweek/histsync,eleweek/histsync,elimohl/histsync,oxyzero/histsync,eleweek/histsync,oxyzero/histsync | #!/usr/bin/env python
# Auto-launching using this: export PROMPT_COMMAND='/Users/putilin/client.py "`fc -nl -1`"'
import requests
import sys
import os
import re
assert len(sys.argv) == 2
history_output = sys.argv[1]
m = re.match(r"[ ]*(\d+)[ ][ ](.*)", history_output)
command_id = m.group(1)
command_text = m.group(2)
USERNAME = "eleweek"
HOST = "histsync.herokuapp.com"
API_KEY = "61f33ca6-50d3-4eea-a924-e9b7b6f86ed4"
payload = {'api_key': API_KEY, 'command_text': command_text, "id": '{}${}'.format(os.getppid(), command_id)}
print payload
r = requests.post("http://{}/api/v0/user/{}/add_command".format(HOST, USERNAME), data=payload)
r.raise_for_status()
Send command in the child process | #!/usr/bin/env python
# Auto-launching using this: export PROMPT_COMMAND='/Users/putilin/client.py "`fc -nl -1`"'
import os
import sys
shell_pid = os.getppid()
if os.fork() != 0:
sys.exit()
import requests
import re
assert len(sys.argv) == 2
history_output = sys.argv[1]
m = re.match(r"[ ]*(\d+)[ ][ ](.*)", history_output)
command_id = m.group(1)
command_text = m.group(2)
USERNAME = "eleweek"
HOST = "histsync.herokuapp.com"
API_KEY = "9b946c76-1688-4d3d-9b13-c4d25ef878ef"
payload = {'api_key': API_KEY, 'command_text': command_text, "id": '{}${}'.format(shell_pid, command_id)}
r = requests.post("http://{}/api/v0/user/{}/add_command".format(HOST, USERNAME), data=payload)
r.raise_for_status()
| <commit_before>#!/usr/bin/env python
# Auto-launching using this: export PROMPT_COMMAND='/Users/putilin/client.py "`fc -nl -1`"'
import requests
import sys
import os
import re
assert len(sys.argv) == 2
history_output = sys.argv[1]
m = re.match(r"[ ]*(\d+)[ ][ ](.*)", history_output)
command_id = m.group(1)
command_text = m.group(2)
USERNAME = "eleweek"
HOST = "histsync.herokuapp.com"
API_KEY = "61f33ca6-50d3-4eea-a924-e9b7b6f86ed4"
payload = {'api_key': API_KEY, 'command_text': command_text, "id": '{}${}'.format(os.getppid(), command_id)}
print payload
r = requests.post("http://{}/api/v0/user/{}/add_command".format(HOST, USERNAME), data=payload)
r.raise_for_status()
<commit_msg>Send command in the child process<commit_after> | #!/usr/bin/env python
# Auto-launching using this: export PROMPT_COMMAND='/Users/putilin/client.py "`fc -nl -1`"'
import os
import sys
shell_pid = os.getppid()
if os.fork() != 0:
sys.exit()
import requests
import re
assert len(sys.argv) == 2
history_output = sys.argv[1]
m = re.match(r"[ ]*(\d+)[ ][ ](.*)", history_output)
command_id = m.group(1)
command_text = m.group(2)
USERNAME = "eleweek"
HOST = "histsync.herokuapp.com"
API_KEY = "9b946c76-1688-4d3d-9b13-c4d25ef878ef"
payload = {'api_key': API_KEY, 'command_text': command_text, "id": '{}${}'.format(shell_pid, command_id)}
r = requests.post("http://{}/api/v0/user/{}/add_command".format(HOST, USERNAME), data=payload)
r.raise_for_status()
| #!/usr/bin/env python
# Auto-launching using this: export PROMPT_COMMAND='/Users/putilin/client.py "`fc -nl -1`"'
import requests
import sys
import os
import re
assert len(sys.argv) == 2
history_output = sys.argv[1]
m = re.match(r"[ ]*(\d+)[ ][ ](.*)", history_output)
command_id = m.group(1)
command_text = m.group(2)
USERNAME = "eleweek"
HOST = "histsync.herokuapp.com"
API_KEY = "61f33ca6-50d3-4eea-a924-e9b7b6f86ed4"
payload = {'api_key': API_KEY, 'command_text': command_text, "id": '{}${}'.format(os.getppid(), command_id)}
print payload
r = requests.post("http://{}/api/v0/user/{}/add_command".format(HOST, USERNAME), data=payload)
r.raise_for_status()
Send command in the child process#!/usr/bin/env python
# Auto-launching using this: export PROMPT_COMMAND='/Users/putilin/client.py "`fc -nl -1`"'
import os
import sys
shell_pid = os.getppid()
if os.fork() != 0:
sys.exit()
import requests
import re
assert len(sys.argv) == 2
history_output = sys.argv[1]
m = re.match(r"[ ]*(\d+)[ ][ ](.*)", history_output)
command_id = m.group(1)
command_text = m.group(2)
USERNAME = "eleweek"
HOST = "histsync.herokuapp.com"
API_KEY = "9b946c76-1688-4d3d-9b13-c4d25ef878ef"
payload = {'api_key': API_KEY, 'command_text': command_text, "id": '{}${}'.format(shell_pid, command_id)}
r = requests.post("http://{}/api/v0/user/{}/add_command".format(HOST, USERNAME), data=payload)
r.raise_for_status()
| <commit_before>#!/usr/bin/env python
# Auto-launching using this: export PROMPT_COMMAND='/Users/putilin/client.py "`fc -nl -1`"'
import requests
import sys
import os
import re
assert len(sys.argv) == 2
history_output = sys.argv[1]
m = re.match(r"[ ]*(\d+)[ ][ ](.*)", history_output)
command_id = m.group(1)
command_text = m.group(2)
USERNAME = "eleweek"
HOST = "histsync.herokuapp.com"
API_KEY = "61f33ca6-50d3-4eea-a924-e9b7b6f86ed4"
payload = {'api_key': API_KEY, 'command_text': command_text, "id": '{}${}'.format(os.getppid(), command_id)}
print payload
r = requests.post("http://{}/api/v0/user/{}/add_command".format(HOST, USERNAME), data=payload)
r.raise_for_status()
<commit_msg>Send command in the child process<commit_after>#!/usr/bin/env python
# Auto-launching using this: export PROMPT_COMMAND='/Users/putilin/client.py "`fc -nl -1`"'
import os
import sys
shell_pid = os.getppid()
if os.fork() != 0:
sys.exit()
import requests
import re
assert len(sys.argv) == 2
history_output = sys.argv[1]
m = re.match(r"[ ]*(\d+)[ ][ ](.*)", history_output)
command_id = m.group(1)
command_text = m.group(2)
USERNAME = "eleweek"
HOST = "histsync.herokuapp.com"
API_KEY = "9b946c76-1688-4d3d-9b13-c4d25ef878ef"
payload = {'api_key': API_KEY, 'command_text': command_text, "id": '{}${}'.format(shell_pid, command_id)}
r = requests.post("http://{}/api/v0/user/{}/add_command".format(HOST, USERNAME), data=payload)
r.raise_for_status()
|
1e1cd9f4b18195f46507b426526a6643a9c24db3 | api/__init__.py | api/__init__.py | from api.models import BaseTag
TAGS = {
'fairness': {
'color': '#bcf0ff',
'description': 'Fairness is ideas of justice, rights, and autonomy.',
},
'cheating': {
'color': '#feffbc',
'description': 'Cheating is acting dishonestly or unfairly in order to gain an advantage.',
},
'loyalty': {
'color': '#bcffe2',
'description': 'Loyalty underlies virtues of patriotism and self-sacrifice for the group.',
},
'betrayal': {
'color': '#ffe5bc',
'description': 'Betrayal is disloyalty and the destruction of trust.',
},
'care': {
'color': '#bcc1ff',
'description': 'Care is concern for the well-being of others.',
},
'harm': {
'color': '#ffbcf5',
'description': 'Harm is something that causes someone or something to be hurt, broken, made less valuable or successful, etc.',
},
'authority': {
'color': '#ffb29e',
'description': 'Authority underlies virtues of leadership and followership, including deference to legitimate authority and respect for traditions.',
},
'subversion': {
'color' :'#e7bcff',
'description': 'Subversion is the undermining of the power and authority of an established system or institution.',
},
'sanctity': {
'color': '#d6ffbc',
'description': 'Sanctity underlies notions of striving to live in an elevated, less carnal, more noble way.',
},
'degradation': {
'color': '#ffbcd1',
'description': 'Degradation is the process in which the beauty or quality of something is destroyed or spoiled',
},
'morality': {
'color' : '#c1bfc0',
'description': 'Morality is a particular system of values and principles of conduct.',
},
};
def populate_base_tags(tags):
for tag in tags:
BaseTag.objects.get_or_create(
name=tag,
color=tags[tag]["color"],
description=tags[tag]["description"]
)
print "Base tags created!"
populate_base_tags(TAGS) | Add script to populate Base Tags on app startup | Add script to populate Base Tags on app startup
| Python | mit | haystack/eyebrowse-server,haystack/eyebrowse-server,haystack/eyebrowse-server,haystack/eyebrowse-server,haystack/eyebrowse-server | Add script to populate Base Tags on app startup | from api.models import BaseTag
TAGS = {
'fairness': {
'color': '#bcf0ff',
'description': 'Fairness is ideas of justice, rights, and autonomy.',
},
'cheating': {
'color': '#feffbc',
'description': 'Cheating is acting dishonestly or unfairly in order to gain an advantage.',
},
'loyalty': {
'color': '#bcffe2',
'description': 'Loyalty underlies virtues of patriotism and self-sacrifice for the group.',
},
'betrayal': {
'color': '#ffe5bc',
'description': 'Betrayal is disloyalty and the destruction of trust.',
},
'care': {
'color': '#bcc1ff',
'description': 'Care is concern for the well-being of others.',
},
'harm': {
'color': '#ffbcf5',
'description': 'Harm is something that causes someone or something to be hurt, broken, made less valuable or successful, etc.',
},
'authority': {
'color': '#ffb29e',
'description': 'Authority underlies virtues of leadership and followership, including deference to legitimate authority and respect for traditions.',
},
'subversion': {
'color' :'#e7bcff',
'description': 'Subversion is the undermining of the power and authority of an established system or institution.',
},
'sanctity': {
'color': '#d6ffbc',
'description': 'Sanctity underlies notions of striving to live in an elevated, less carnal, more noble way.',
},
'degradation': {
'color': '#ffbcd1',
'description': 'Degradation is the process in which the beauty or quality of something is destroyed or spoiled',
},
'morality': {
'color' : '#c1bfc0',
'description': 'Morality is a particular system of values and principles of conduct.',
},
};
def populate_base_tags(tags):
for tag in tags:
BaseTag.objects.get_or_create(
name=tag,
color=tags[tag]["color"],
description=tags[tag]["description"]
)
print "Base tags created!"
populate_base_tags(TAGS) | <commit_before><commit_msg>Add script to populate Base Tags on app startup<commit_after> | from api.models import BaseTag
TAGS = {
'fairness': {
'color': '#bcf0ff',
'description': 'Fairness is ideas of justice, rights, and autonomy.',
},
'cheating': {
'color': '#feffbc',
'description': 'Cheating is acting dishonestly or unfairly in order to gain an advantage.',
},
'loyalty': {
'color': '#bcffe2',
'description': 'Loyalty underlies virtues of patriotism and self-sacrifice for the group.',
},
'betrayal': {
'color': '#ffe5bc',
'description': 'Betrayal is disloyalty and the destruction of trust.',
},
'care': {
'color': '#bcc1ff',
'description': 'Care is concern for the well-being of others.',
},
'harm': {
'color': '#ffbcf5',
'description': 'Harm is something that causes someone or something to be hurt, broken, made less valuable or successful, etc.',
},
'authority': {
'color': '#ffb29e',
'description': 'Authority underlies virtues of leadership and followership, including deference to legitimate authority and respect for traditions.',
},
'subversion': {
'color' :'#e7bcff',
'description': 'Subversion is the undermining of the power and authority of an established system or institution.',
},
'sanctity': {
'color': '#d6ffbc',
'description': 'Sanctity underlies notions of striving to live in an elevated, less carnal, more noble way.',
},
'degradation': {
'color': '#ffbcd1',
'description': 'Degradation is the process in which the beauty or quality of something is destroyed or spoiled',
},
'morality': {
'color' : '#c1bfc0',
'description': 'Morality is a particular system of values and principles of conduct.',
},
};
def populate_base_tags(tags):
for tag in tags:
BaseTag.objects.get_or_create(
name=tag,
color=tags[tag]["color"],
description=tags[tag]["description"]
)
print "Base tags created!"
populate_base_tags(TAGS) | Add script to populate Base Tags on app startupfrom api.models import BaseTag
TAGS = {
'fairness': {
'color': '#bcf0ff',
'description': 'Fairness is ideas of justice, rights, and autonomy.',
},
'cheating': {
'color': '#feffbc',
'description': 'Cheating is acting dishonestly or unfairly in order to gain an advantage.',
},
'loyalty': {
'color': '#bcffe2',
'description': 'Loyalty underlies virtues of patriotism and self-sacrifice for the group.',
},
'betrayal': {
'color': '#ffe5bc',
'description': 'Betrayal is disloyalty and the destruction of trust.',
},
'care': {
'color': '#bcc1ff',
'description': 'Care is concern for the well-being of others.',
},
'harm': {
'color': '#ffbcf5',
'description': 'Harm is something that causes someone or something to be hurt, broken, made less valuable or successful, etc.',
},
'authority': {
'color': '#ffb29e',
'description': 'Authority underlies virtues of leadership and followership, including deference to legitimate authority and respect for traditions.',
},
'subversion': {
'color' :'#e7bcff',
'description': 'Subversion is the undermining of the power and authority of an established system or institution.',
},
'sanctity': {
'color': '#d6ffbc',
'description': 'Sanctity underlies notions of striving to live in an elevated, less carnal, more noble way.',
},
'degradation': {
'color': '#ffbcd1',
'description': 'Degradation is the process in which the beauty or quality of something is destroyed or spoiled',
},
'morality': {
'color' : '#c1bfc0',
'description': 'Morality is a particular system of values and principles of conduct.',
},
};
def populate_base_tags(tags):
for tag in tags:
BaseTag.objects.get_or_create(
name=tag,
color=tags[tag]["color"],
description=tags[tag]["description"]
)
print "Base tags created!"
populate_base_tags(TAGS) | <commit_before><commit_msg>Add script to populate Base Tags on app startup<commit_after>from api.models import BaseTag
TAGS = {
'fairness': {
'color': '#bcf0ff',
'description': 'Fairness is ideas of justice, rights, and autonomy.',
},
'cheating': {
'color': '#feffbc',
'description': 'Cheating is acting dishonestly or unfairly in order to gain an advantage.',
},
'loyalty': {
'color': '#bcffe2',
'description': 'Loyalty underlies virtues of patriotism and self-sacrifice for the group.',
},
'betrayal': {
'color': '#ffe5bc',
'description': 'Betrayal is disloyalty and the destruction of trust.',
},
'care': {
'color': '#bcc1ff',
'description': 'Care is concern for the well-being of others.',
},
'harm': {
'color': '#ffbcf5',
'description': 'Harm is something that causes someone or something to be hurt, broken, made less valuable or successful, etc.',
},
'authority': {
'color': '#ffb29e',
'description': 'Authority underlies virtues of leadership and followership, including deference to legitimate authority and respect for traditions.',
},
'subversion': {
'color' :'#e7bcff',
'description': 'Subversion is the undermining of the power and authority of an established system or institution.',
},
'sanctity': {
'color': '#d6ffbc',
'description': 'Sanctity underlies notions of striving to live in an elevated, less carnal, more noble way.',
},
'degradation': {
'color': '#ffbcd1',
'description': 'Degradation is the process in which the beauty or quality of something is destroyed or spoiled',
},
'morality': {
'color' : '#c1bfc0',
'description': 'Morality is a particular system of values and principles of conduct.',
},
};
def populate_base_tags(tags):
for tag in tags:
BaseTag.objects.get_or_create(
name=tag,
color=tags[tag]["color"],
description=tags[tag]["description"]
)
print "Base tags created!"
populate_base_tags(TAGS) | |
ada0aadf9558caba7cb94125f8a8104d2fde968c | tempora/utc.py | tempora/utc.py | """
Facilities for common time operations in UTC.
Inspired by the `utc project <https://pypi.org/project/utc>`_.
>>> dt = now()
>>> dt == fromtimestamp(dt.timestamp())
True
>>> dt.tzinfo
datetime.timezone.utc
>>> from time import time as timestamp
>>> now().timestamp() - timestamp() < 0.1
True
>>> datetime(2018, 6, 26, 0).tzinfo
datetime.timezone.utc
>>> time(0, 0).tzinfo
datetime.timezone.utc
"""
import datetime as std
import functools
__all__ = ['now', 'fromtimestamp', 'datetime', 'time']
now = functools.partial(std.datetime.now, std.timezone.utc)
fromtimestamp = functools.partial(
std.datetime.fromtimestamp,
tz=std.timezone.utc,
)
datetime = functools.partial(std.datetime, tzinfo=std.timezone.utc)
time = functools.partial(std.time, tzinfo=std.timezone.utc)
| """
Facilities for common time operations in UTC.
Inspired by the `utc project <https://pypi.org/project/utc>`_.
>>> dt = now()
>>> dt == fromtimestamp(dt.timestamp())
True
>>> dt.tzinfo
datetime.timezone.utc
>>> from time import time as timestamp
>>> now().timestamp() - timestamp() < 0.1
True
>>> (now() - fromtimestamp(timestamp())).total_seconds() < 0.1
True
>>> datetime(2018, 6, 26, 0).tzinfo
datetime.timezone.utc
>>> time(0, 0).tzinfo
datetime.timezone.utc
"""
import datetime as std
import functools
__all__ = ['now', 'fromtimestamp', 'datetime', 'time']
now = functools.partial(std.datetime.now, std.timezone.utc)
fromtimestamp = functools.partial(
std.datetime.fromtimestamp,
tz=std.timezone.utc,
)
datetime = functools.partial(std.datetime, tzinfo=std.timezone.utc)
time = functools.partial(std.time, tzinfo=std.timezone.utc)
| Add test demonstrating aware comparisons | Add test demonstrating aware comparisons
| Python | mit | jaraco/tempora | """
Facilities for common time operations in UTC.
Inspired by the `utc project <https://pypi.org/project/utc>`_.
>>> dt = now()
>>> dt == fromtimestamp(dt.timestamp())
True
>>> dt.tzinfo
datetime.timezone.utc
>>> from time import time as timestamp
>>> now().timestamp() - timestamp() < 0.1
True
>>> datetime(2018, 6, 26, 0).tzinfo
datetime.timezone.utc
>>> time(0, 0).tzinfo
datetime.timezone.utc
"""
import datetime as std
import functools
__all__ = ['now', 'fromtimestamp', 'datetime', 'time']
now = functools.partial(std.datetime.now, std.timezone.utc)
fromtimestamp = functools.partial(
std.datetime.fromtimestamp,
tz=std.timezone.utc,
)
datetime = functools.partial(std.datetime, tzinfo=std.timezone.utc)
time = functools.partial(std.time, tzinfo=std.timezone.utc)
Add test demonstrating aware comparisons | """
Facilities for common time operations in UTC.
Inspired by the `utc project <https://pypi.org/project/utc>`_.
>>> dt = now()
>>> dt == fromtimestamp(dt.timestamp())
True
>>> dt.tzinfo
datetime.timezone.utc
>>> from time import time as timestamp
>>> now().timestamp() - timestamp() < 0.1
True
>>> (now() - fromtimestamp(timestamp())).total_seconds() < 0.1
True
>>> datetime(2018, 6, 26, 0).tzinfo
datetime.timezone.utc
>>> time(0, 0).tzinfo
datetime.timezone.utc
"""
import datetime as std
import functools
__all__ = ['now', 'fromtimestamp', 'datetime', 'time']
now = functools.partial(std.datetime.now, std.timezone.utc)
fromtimestamp = functools.partial(
std.datetime.fromtimestamp,
tz=std.timezone.utc,
)
datetime = functools.partial(std.datetime, tzinfo=std.timezone.utc)
time = functools.partial(std.time, tzinfo=std.timezone.utc)
| <commit_before>"""
Facilities for common time operations in UTC.
Inspired by the `utc project <https://pypi.org/project/utc>`_.
>>> dt = now()
>>> dt == fromtimestamp(dt.timestamp())
True
>>> dt.tzinfo
datetime.timezone.utc
>>> from time import time as timestamp
>>> now().timestamp() - timestamp() < 0.1
True
>>> datetime(2018, 6, 26, 0).tzinfo
datetime.timezone.utc
>>> time(0, 0).tzinfo
datetime.timezone.utc
"""
import datetime as std
import functools
__all__ = ['now', 'fromtimestamp', 'datetime', 'time']
now = functools.partial(std.datetime.now, std.timezone.utc)
fromtimestamp = functools.partial(
std.datetime.fromtimestamp,
tz=std.timezone.utc,
)
datetime = functools.partial(std.datetime, tzinfo=std.timezone.utc)
time = functools.partial(std.time, tzinfo=std.timezone.utc)
<commit_msg>Add test demonstrating aware comparisons<commit_after> | """
Facilities for common time operations in UTC.
Inspired by the `utc project <https://pypi.org/project/utc>`_.
>>> dt = now()
>>> dt == fromtimestamp(dt.timestamp())
True
>>> dt.tzinfo
datetime.timezone.utc
>>> from time import time as timestamp
>>> now().timestamp() - timestamp() < 0.1
True
>>> (now() - fromtimestamp(timestamp())).total_seconds() < 0.1
True
>>> datetime(2018, 6, 26, 0).tzinfo
datetime.timezone.utc
>>> time(0, 0).tzinfo
datetime.timezone.utc
"""
import datetime as std
import functools
__all__ = ['now', 'fromtimestamp', 'datetime', 'time']
now = functools.partial(std.datetime.now, std.timezone.utc)
fromtimestamp = functools.partial(
std.datetime.fromtimestamp,
tz=std.timezone.utc,
)
datetime = functools.partial(std.datetime, tzinfo=std.timezone.utc)
time = functools.partial(std.time, tzinfo=std.timezone.utc)
| """
Facilities for common time operations in UTC.
Inspired by the `utc project <https://pypi.org/project/utc>`_.
>>> dt = now()
>>> dt == fromtimestamp(dt.timestamp())
True
>>> dt.tzinfo
datetime.timezone.utc
>>> from time import time as timestamp
>>> now().timestamp() - timestamp() < 0.1
True
>>> datetime(2018, 6, 26, 0).tzinfo
datetime.timezone.utc
>>> time(0, 0).tzinfo
datetime.timezone.utc
"""
import datetime as std
import functools
__all__ = ['now', 'fromtimestamp', 'datetime', 'time']
now = functools.partial(std.datetime.now, std.timezone.utc)
fromtimestamp = functools.partial(
std.datetime.fromtimestamp,
tz=std.timezone.utc,
)
datetime = functools.partial(std.datetime, tzinfo=std.timezone.utc)
time = functools.partial(std.time, tzinfo=std.timezone.utc)
Add test demonstrating aware comparisons"""
Facilities for common time operations in UTC.
Inspired by the `utc project <https://pypi.org/project/utc>`_.
>>> dt = now()
>>> dt == fromtimestamp(dt.timestamp())
True
>>> dt.tzinfo
datetime.timezone.utc
>>> from time import time as timestamp
>>> now().timestamp() - timestamp() < 0.1
True
>>> (now() - fromtimestamp(timestamp())).total_seconds() < 0.1
True
>>> datetime(2018, 6, 26, 0).tzinfo
datetime.timezone.utc
>>> time(0, 0).tzinfo
datetime.timezone.utc
"""
import datetime as std
import functools
__all__ = ['now', 'fromtimestamp', 'datetime', 'time']
now = functools.partial(std.datetime.now, std.timezone.utc)
fromtimestamp = functools.partial(
std.datetime.fromtimestamp,
tz=std.timezone.utc,
)
datetime = functools.partial(std.datetime, tzinfo=std.timezone.utc)
time = functools.partial(std.time, tzinfo=std.timezone.utc)
| <commit_before>"""
Facilities for common time operations in UTC.
Inspired by the `utc project <https://pypi.org/project/utc>`_.
>>> dt = now()
>>> dt == fromtimestamp(dt.timestamp())
True
>>> dt.tzinfo
datetime.timezone.utc
>>> from time import time as timestamp
>>> now().timestamp() - timestamp() < 0.1
True
>>> datetime(2018, 6, 26, 0).tzinfo
datetime.timezone.utc
>>> time(0, 0).tzinfo
datetime.timezone.utc
"""
import datetime as std
import functools
__all__ = ['now', 'fromtimestamp', 'datetime', 'time']
now = functools.partial(std.datetime.now, std.timezone.utc)
fromtimestamp = functools.partial(
std.datetime.fromtimestamp,
tz=std.timezone.utc,
)
datetime = functools.partial(std.datetime, tzinfo=std.timezone.utc)
time = functools.partial(std.time, tzinfo=std.timezone.utc)
<commit_msg>Add test demonstrating aware comparisons<commit_after>"""
Facilities for common time operations in UTC.
Inspired by the `utc project <https://pypi.org/project/utc>`_.
>>> dt = now()
>>> dt == fromtimestamp(dt.timestamp())
True
>>> dt.tzinfo
datetime.timezone.utc
>>> from time import time as timestamp
>>> now().timestamp() - timestamp() < 0.1
True
>>> (now() - fromtimestamp(timestamp())).total_seconds() < 0.1
True
>>> datetime(2018, 6, 26, 0).tzinfo
datetime.timezone.utc
>>> time(0, 0).tzinfo
datetime.timezone.utc
"""
import datetime as std
import functools
__all__ = ['now', 'fromtimestamp', 'datetime', 'time']
now = functools.partial(std.datetime.now, std.timezone.utc)
fromtimestamp = functools.partial(
std.datetime.fromtimestamp,
tz=std.timezone.utc,
)
datetime = functools.partial(std.datetime, tzinfo=std.timezone.utc)
time = functools.partial(std.time, tzinfo=std.timezone.utc)
|
49113dcbcd6cd509b1d69075f78738f4ee9e9bb6 | tensorflow/compiler/mlir/quantization/tensorflow/python/representative_dataset.py | tensorflow/compiler/mlir/quantization/tensorflow/python/representative_dataset.py | # Copyright 2022 The TensorFlow Authors. 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.
# ==============================================================================
"""Defines types required for representative datasets for quantization."""
from typing import Callable, Iterable, Mapping, Tuple, Union
from tensorflow.python.types import core
# A representative sample should be either:
# 1. (signature_key, {input_name -> input_tensor}) tuple, or
# 2. {input_name -> input_tensor} mappings.
# TODO(b/236218728): Support data types other than Tensor (such as np.ndarrays).
RepresentativeSample = Union[Tuple[str, Mapping[str, core.Tensor]],
Mapping[str, core.Tensor]]
# A representative dataset should be a callable that returns an iterable
# of representative samples.
RepresentativeDataset = Callable[[], Iterable[RepresentativeSample]]
| # Copyright 2022 The TensorFlow Authors. 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.
# ==============================================================================
"""Defines types required for representative datasets for quantization."""
from typing import Iterable, Mapping, Tuple, Union
from tensorflow.python.types import core
# A representative sample should be either:
# 1. (signature_key, {input_name -> input_tensor}) tuple, or
# 2. {input_name -> input_tensor} mappings.
# TODO(b/236218728): Support data types other than Tensor (such as np.ndarrays).
RepresentativeSample = Union[Tuple[str, Mapping[str, core.Tensor]],
Mapping[str, core.Tensor]]
# A representative dataset is an iterable of representative samples.
RepresentativeDataset = Iterable[RepresentativeSample]
| Modify the type signature for `RepresentativeDataset` from a `Callable` to an `Iterator`. | Modify the type signature for `RepresentativeDataset` from a `Callable` to an `Iterator`.
Currently the usage for `RepresentativeDataset` is an iterator instead of a callable.
This fix changes the type signature accordingly.
PiperOrigin-RevId: 457393586
| Python | apache-2.0 | tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,karllessard/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,yongtang/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,paolodedios/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,karllessard/tensorflow,karllessard/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer | # Copyright 2022 The TensorFlow Authors. 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.
# ==============================================================================
"""Defines types required for representative datasets for quantization."""
from typing import Callable, Iterable, Mapping, Tuple, Union
from tensorflow.python.types import core
# A representative sample should be either:
# 1. (signature_key, {input_name -> input_tensor}) tuple, or
# 2. {input_name -> input_tensor} mappings.
# TODO(b/236218728): Support data types other than Tensor (such as np.ndarrays).
RepresentativeSample = Union[Tuple[str, Mapping[str, core.Tensor]],
Mapping[str, core.Tensor]]
# A representative dataset should be a callable that returns an iterable
# of representative samples.
RepresentativeDataset = Callable[[], Iterable[RepresentativeSample]]
Modify the type signature for `RepresentativeDataset` from a `Callable` to an `Iterator`.
Currently the usage for `RepresentativeDataset` is an iterator instead of a callable.
This fix changes the type signature accordingly.
PiperOrigin-RevId: 457393586 | # Copyright 2022 The TensorFlow Authors. 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.
# ==============================================================================
"""Defines types required for representative datasets for quantization."""
from typing import Iterable, Mapping, Tuple, Union
from tensorflow.python.types import core
# A representative sample should be either:
# 1. (signature_key, {input_name -> input_tensor}) tuple, or
# 2. {input_name -> input_tensor} mappings.
# TODO(b/236218728): Support data types other than Tensor (such as np.ndarrays).
RepresentativeSample = Union[Tuple[str, Mapping[str, core.Tensor]],
Mapping[str, core.Tensor]]
# A representative dataset is an iterable of representative samples.
RepresentativeDataset = Iterable[RepresentativeSample]
| <commit_before># Copyright 2022 The TensorFlow Authors. 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.
# ==============================================================================
"""Defines types required for representative datasets for quantization."""
from typing import Callable, Iterable, Mapping, Tuple, Union
from tensorflow.python.types import core
# A representative sample should be either:
# 1. (signature_key, {input_name -> input_tensor}) tuple, or
# 2. {input_name -> input_tensor} mappings.
# TODO(b/236218728): Support data types other than Tensor (such as np.ndarrays).
RepresentativeSample = Union[Tuple[str, Mapping[str, core.Tensor]],
Mapping[str, core.Tensor]]
# A representative dataset should be a callable that returns an iterable
# of representative samples.
RepresentativeDataset = Callable[[], Iterable[RepresentativeSample]]
<commit_msg>Modify the type signature for `RepresentativeDataset` from a `Callable` to an `Iterator`.
Currently the usage for `RepresentativeDataset` is an iterator instead of a callable.
This fix changes the type signature accordingly.
PiperOrigin-RevId: 457393586<commit_after> | # Copyright 2022 The TensorFlow Authors. 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.
# ==============================================================================
"""Defines types required for representative datasets for quantization."""
from typing import Iterable, Mapping, Tuple, Union
from tensorflow.python.types import core
# A representative sample should be either:
# 1. (signature_key, {input_name -> input_tensor}) tuple, or
# 2. {input_name -> input_tensor} mappings.
# TODO(b/236218728): Support data types other than Tensor (such as np.ndarrays).
RepresentativeSample = Union[Tuple[str, Mapping[str, core.Tensor]],
Mapping[str, core.Tensor]]
# A representative dataset is an iterable of representative samples.
RepresentativeDataset = Iterable[RepresentativeSample]
| # Copyright 2022 The TensorFlow Authors. 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.
# ==============================================================================
"""Defines types required for representative datasets for quantization."""
from typing import Callable, Iterable, Mapping, Tuple, Union
from tensorflow.python.types import core
# A representative sample should be either:
# 1. (signature_key, {input_name -> input_tensor}) tuple, or
# 2. {input_name -> input_tensor} mappings.
# TODO(b/236218728): Support data types other than Tensor (such as np.ndarrays).
RepresentativeSample = Union[Tuple[str, Mapping[str, core.Tensor]],
Mapping[str, core.Tensor]]
# A representative dataset should be a callable that returns an iterable
# of representative samples.
RepresentativeDataset = Callable[[], Iterable[RepresentativeSample]]
Modify the type signature for `RepresentativeDataset` from a `Callable` to an `Iterator`.
Currently the usage for `RepresentativeDataset` is an iterator instead of a callable.
This fix changes the type signature accordingly.
PiperOrigin-RevId: 457393586# Copyright 2022 The TensorFlow Authors. 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.
# ==============================================================================
"""Defines types required for representative datasets for quantization."""
from typing import Iterable, Mapping, Tuple, Union
from tensorflow.python.types import core
# A representative sample should be either:
# 1. (signature_key, {input_name -> input_tensor}) tuple, or
# 2. {input_name -> input_tensor} mappings.
# TODO(b/236218728): Support data types other than Tensor (such as np.ndarrays).
RepresentativeSample = Union[Tuple[str, Mapping[str, core.Tensor]],
Mapping[str, core.Tensor]]
# A representative dataset is an iterable of representative samples.
RepresentativeDataset = Iterable[RepresentativeSample]
| <commit_before># Copyright 2022 The TensorFlow Authors. 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.
# ==============================================================================
"""Defines types required for representative datasets for quantization."""
from typing import Callable, Iterable, Mapping, Tuple, Union
from tensorflow.python.types import core
# A representative sample should be either:
# 1. (signature_key, {input_name -> input_tensor}) tuple, or
# 2. {input_name -> input_tensor} mappings.
# TODO(b/236218728): Support data types other than Tensor (such as np.ndarrays).
RepresentativeSample = Union[Tuple[str, Mapping[str, core.Tensor]],
Mapping[str, core.Tensor]]
# A representative dataset should be a callable that returns an iterable
# of representative samples.
RepresentativeDataset = Callable[[], Iterable[RepresentativeSample]]
<commit_msg>Modify the type signature for `RepresentativeDataset` from a `Callable` to an `Iterator`.
Currently the usage for `RepresentativeDataset` is an iterator instead of a callable.
This fix changes the type signature accordingly.
PiperOrigin-RevId: 457393586<commit_after># Copyright 2022 The TensorFlow Authors. 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.
# ==============================================================================
"""Defines types required for representative datasets for quantization."""
from typing import Iterable, Mapping, Tuple, Union
from tensorflow.python.types import core
# A representative sample should be either:
# 1. (signature_key, {input_name -> input_tensor}) tuple, or
# 2. {input_name -> input_tensor} mappings.
# TODO(b/236218728): Support data types other than Tensor (such as np.ndarrays).
RepresentativeSample = Union[Tuple[str, Mapping[str, core.Tensor]],
Mapping[str, core.Tensor]]
# A representative dataset is an iterable of representative samples.
RepresentativeDataset = Iterable[RepresentativeSample]
|
03f4ccf4168cdd39d3b8516346a31c4c3ac0ba49 | sieve/sieve.py | sieve/sieve.py | def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n, i))
return prime
| def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n+1, i))
return prime
| Fix bug where n is the square of a prime | Fix bug where n is the square of a prime
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n, i))
return prime
Fix bug where n is the square of a prime | def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n+1, i))
return prime
| <commit_before>def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n, i))
return prime
<commit_msg>Fix bug where n is the square of a prime<commit_after> | def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n+1, i))
return prime
| def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n, i))
return prime
Fix bug where n is the square of a primedef sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n+1, i))
return prime
| <commit_before>def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n, i))
return prime
<commit_msg>Fix bug where n is the square of a prime<commit_after>def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n+1, i))
return prime
|
78ecac7c97445fd24a9d00f5fea671aab99d4c3b | monitor-notifier-slack.py | monitor-notifier-slack.py | #!/usr/bin/env python
import pika
import json
import requests
import os
RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"]
RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"]
RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"]
credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD)
connection = pika.BlockingConnection(pika.ConnectionParameters(
RABBIT_MQ_SERVER, credentials = credentials))
channel = connection.channel()
def callback(ch, method, properties, body):
payload = {}
payload["text"] = body
req = json.loads(body)
webhook_url = json.loads(req["monitor"]["notifier"]["arguments"])["webhook_url"]
r = requests.post(webhook_url, data = json.dumps(payload))
channel.basic_consume(callback, queue='slack', no_ack=True)
channel.start_consuming()
| #!/usr/bin/env python
import pika
import json
import requests
import os
RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"]
RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"]
RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"]
credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD)
connection = pika.BlockingConnection(pika.ConnectionParameters(
RABBIT_MQ_SERVER, credentials = credentials))
channel = connection.channel()
def callback(ch, method, properties, body):
payload = {}
req = json.loads(body)
check_type = req["monitor"]["result"]["check"]["type"]
host = json.loads(req["monitor"]["result"]["check"]["arguments"])["host"]
time = req["monitor"]["result"]["timestamp"]
payload["text"] = check_type + " check failed for " + host + " at " + time
webhook_url = json.loads(req["monitor"]["notifier"]["arguments"])["webhook_url"]
r = requests.post(webhook_url, data = json.dumps(payload))
channel.basic_consume(callback, queue='slack', no_ack=True)
channel.start_consuming()
| Improve message posted to slack | Improve message posted to slack
| Python | mit | observer-hackaton/monitor-notifier-slack | #!/usr/bin/env python
import pika
import json
import requests
import os
RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"]
RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"]
RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"]
credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD)
connection = pika.BlockingConnection(pika.ConnectionParameters(
RABBIT_MQ_SERVER, credentials = credentials))
channel = connection.channel()
def callback(ch, method, properties, body):
payload = {}
payload["text"] = body
req = json.loads(body)
webhook_url = json.loads(req["monitor"]["notifier"]["arguments"])["webhook_url"]
r = requests.post(webhook_url, data = json.dumps(payload))
channel.basic_consume(callback, queue='slack', no_ack=True)
channel.start_consuming()
Improve message posted to slack | #!/usr/bin/env python
import pika
import json
import requests
import os
RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"]
RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"]
RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"]
credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD)
connection = pika.BlockingConnection(pika.ConnectionParameters(
RABBIT_MQ_SERVER, credentials = credentials))
channel = connection.channel()
def callback(ch, method, properties, body):
payload = {}
req = json.loads(body)
check_type = req["monitor"]["result"]["check"]["type"]
host = json.loads(req["monitor"]["result"]["check"]["arguments"])["host"]
time = req["monitor"]["result"]["timestamp"]
payload["text"] = check_type + " check failed for " + host + " at " + time
webhook_url = json.loads(req["monitor"]["notifier"]["arguments"])["webhook_url"]
r = requests.post(webhook_url, data = json.dumps(payload))
channel.basic_consume(callback, queue='slack', no_ack=True)
channel.start_consuming()
| <commit_before>#!/usr/bin/env python
import pika
import json
import requests
import os
RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"]
RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"]
RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"]
credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD)
connection = pika.BlockingConnection(pika.ConnectionParameters(
RABBIT_MQ_SERVER, credentials = credentials))
channel = connection.channel()
def callback(ch, method, properties, body):
payload = {}
payload["text"] = body
req = json.loads(body)
webhook_url = json.loads(req["monitor"]["notifier"]["arguments"])["webhook_url"]
r = requests.post(webhook_url, data = json.dumps(payload))
channel.basic_consume(callback, queue='slack', no_ack=True)
channel.start_consuming()
<commit_msg>Improve message posted to slack<commit_after> | #!/usr/bin/env python
import pika
import json
import requests
import os
RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"]
RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"]
RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"]
credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD)
connection = pika.BlockingConnection(pika.ConnectionParameters(
RABBIT_MQ_SERVER, credentials = credentials))
channel = connection.channel()
def callback(ch, method, properties, body):
payload = {}
req = json.loads(body)
check_type = req["monitor"]["result"]["check"]["type"]
host = json.loads(req["monitor"]["result"]["check"]["arguments"])["host"]
time = req["monitor"]["result"]["timestamp"]
payload["text"] = check_type + " check failed for " + host + " at " + time
webhook_url = json.loads(req["monitor"]["notifier"]["arguments"])["webhook_url"]
r = requests.post(webhook_url, data = json.dumps(payload))
channel.basic_consume(callback, queue='slack', no_ack=True)
channel.start_consuming()
| #!/usr/bin/env python
import pika
import json
import requests
import os
RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"]
RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"]
RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"]
credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD)
connection = pika.BlockingConnection(pika.ConnectionParameters(
RABBIT_MQ_SERVER, credentials = credentials))
channel = connection.channel()
def callback(ch, method, properties, body):
payload = {}
payload["text"] = body
req = json.loads(body)
webhook_url = json.loads(req["monitor"]["notifier"]["arguments"])["webhook_url"]
r = requests.post(webhook_url, data = json.dumps(payload))
channel.basic_consume(callback, queue='slack', no_ack=True)
channel.start_consuming()
Improve message posted to slack#!/usr/bin/env python
import pika
import json
import requests
import os
RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"]
RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"]
RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"]
credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD)
connection = pika.BlockingConnection(pika.ConnectionParameters(
RABBIT_MQ_SERVER, credentials = credentials))
channel = connection.channel()
def callback(ch, method, properties, body):
payload = {}
req = json.loads(body)
check_type = req["monitor"]["result"]["check"]["type"]
host = json.loads(req["monitor"]["result"]["check"]["arguments"])["host"]
time = req["monitor"]["result"]["timestamp"]
payload["text"] = check_type + " check failed for " + host + " at " + time
webhook_url = json.loads(req["monitor"]["notifier"]["arguments"])["webhook_url"]
r = requests.post(webhook_url, data = json.dumps(payload))
channel.basic_consume(callback, queue='slack', no_ack=True)
channel.start_consuming()
| <commit_before>#!/usr/bin/env python
import pika
import json
import requests
import os
RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"]
RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"]
RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"]
credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD)
connection = pika.BlockingConnection(pika.ConnectionParameters(
RABBIT_MQ_SERVER, credentials = credentials))
channel = connection.channel()
def callback(ch, method, properties, body):
payload = {}
payload["text"] = body
req = json.loads(body)
webhook_url = json.loads(req["monitor"]["notifier"]["arguments"])["webhook_url"]
r = requests.post(webhook_url, data = json.dumps(payload))
channel.basic_consume(callback, queue='slack', no_ack=True)
channel.start_consuming()
<commit_msg>Improve message posted to slack<commit_after>#!/usr/bin/env python
import pika
import json
import requests
import os
RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"]
RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"]
RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"]
credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD)
connection = pika.BlockingConnection(pika.ConnectionParameters(
RABBIT_MQ_SERVER, credentials = credentials))
channel = connection.channel()
def callback(ch, method, properties, body):
payload = {}
req = json.loads(body)
check_type = req["monitor"]["result"]["check"]["type"]
host = json.loads(req["monitor"]["result"]["check"]["arguments"])["host"]
time = req["monitor"]["result"]["timestamp"]
payload["text"] = check_type + " check failed for " + host + " at " + time
webhook_url = json.loads(req["monitor"]["notifier"]["arguments"])["webhook_url"]
r = requests.post(webhook_url, data = json.dumps(payload))
channel.basic_consume(callback, queue='slack', no_ack=True)
channel.start_consuming()
|
37dc483fd381aa14eddddb13c991bbf647bb747b | data/global-configuration/packs/core-functions/module/node.py | data/global-configuration/packs/core-functions/module/node.py | from opsbro.evaluater import export_evaluater_function
from opsbro.gossip import gossiper
FUNCTION_GROUP = 'gossip'
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_group(group):
"""**is_in_group(group)** -> return True if the node have the group, False otherwise.
* group: (string) group to check.
<code>
Example:
is_in_group('linux')
Returns:
True
</code>
"""
return gossiper.is_in_group(group)
| from opsbro.evaluater import export_evaluater_function
from opsbro.gossip import gossiper
FUNCTION_GROUP = 'gossip'
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_group(group):
"""**is_in_group(group)** -> return True if the node have the group, False otherwise.
* group: (string) group to check.
<code>
Example:
is_in_group('linux')
Returns:
True
</code>
"""
return gossiper.is_in_group(group)
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_defined_group(group):
"""**is_in_defined_group(group)** -> return True if the node have the group but was set in the configuration, not from discovery False otherwise.
* group: (string) group to check.
<code>
Example:
is_in_defined_group('linux')
Returns:
True
</code>
"""
return gossiper.is_in_group(group)
| Declare the is_in_defined_group function, even if it is an alias of the is_in_group | Enh: Declare the is_in_defined_group function, even if it is an alias of the is_in_group
| Python | mit | naparuba/kunai,naparuba/kunai,naparuba/opsbro,naparuba/kunai,naparuba/kunai,naparuba/kunai,naparuba/opsbro,naparuba/opsbro,naparuba/kunai,naparuba/opsbro | from opsbro.evaluater import export_evaluater_function
from opsbro.gossip import gossiper
FUNCTION_GROUP = 'gossip'
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_group(group):
"""**is_in_group(group)** -> return True if the node have the group, False otherwise.
* group: (string) group to check.
<code>
Example:
is_in_group('linux')
Returns:
True
</code>
"""
return gossiper.is_in_group(group)
Enh: Declare the is_in_defined_group function, even if it is an alias of the is_in_group | from opsbro.evaluater import export_evaluater_function
from opsbro.gossip import gossiper
FUNCTION_GROUP = 'gossip'
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_group(group):
"""**is_in_group(group)** -> return True if the node have the group, False otherwise.
* group: (string) group to check.
<code>
Example:
is_in_group('linux')
Returns:
True
</code>
"""
return gossiper.is_in_group(group)
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_defined_group(group):
"""**is_in_defined_group(group)** -> return True if the node have the group but was set in the configuration, not from discovery False otherwise.
* group: (string) group to check.
<code>
Example:
is_in_defined_group('linux')
Returns:
True
</code>
"""
return gossiper.is_in_group(group)
| <commit_before>from opsbro.evaluater import export_evaluater_function
from opsbro.gossip import gossiper
FUNCTION_GROUP = 'gossip'
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_group(group):
"""**is_in_group(group)** -> return True if the node have the group, False otherwise.
* group: (string) group to check.
<code>
Example:
is_in_group('linux')
Returns:
True
</code>
"""
return gossiper.is_in_group(group)
<commit_msg>Enh: Declare the is_in_defined_group function, even if it is an alias of the is_in_group<commit_after> | from opsbro.evaluater import export_evaluater_function
from opsbro.gossip import gossiper
FUNCTION_GROUP = 'gossip'
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_group(group):
"""**is_in_group(group)** -> return True if the node have the group, False otherwise.
* group: (string) group to check.
<code>
Example:
is_in_group('linux')
Returns:
True
</code>
"""
return gossiper.is_in_group(group)
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_defined_group(group):
"""**is_in_defined_group(group)** -> return True if the node have the group but was set in the configuration, not from discovery False otherwise.
* group: (string) group to check.
<code>
Example:
is_in_defined_group('linux')
Returns:
True
</code>
"""
return gossiper.is_in_group(group)
| from opsbro.evaluater import export_evaluater_function
from opsbro.gossip import gossiper
FUNCTION_GROUP = 'gossip'
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_group(group):
"""**is_in_group(group)** -> return True if the node have the group, False otherwise.
* group: (string) group to check.
<code>
Example:
is_in_group('linux')
Returns:
True
</code>
"""
return gossiper.is_in_group(group)
Enh: Declare the is_in_defined_group function, even if it is an alias of the is_in_groupfrom opsbro.evaluater import export_evaluater_function
from opsbro.gossip import gossiper
FUNCTION_GROUP = 'gossip'
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_group(group):
"""**is_in_group(group)** -> return True if the node have the group, False otherwise.
* group: (string) group to check.
<code>
Example:
is_in_group('linux')
Returns:
True
</code>
"""
return gossiper.is_in_group(group)
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_defined_group(group):
"""**is_in_defined_group(group)** -> return True if the node have the group but was set in the configuration, not from discovery False otherwise.
* group: (string) group to check.
<code>
Example:
is_in_defined_group('linux')
Returns:
True
</code>
"""
return gossiper.is_in_group(group)
| <commit_before>from opsbro.evaluater import export_evaluater_function
from opsbro.gossip import gossiper
FUNCTION_GROUP = 'gossip'
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_group(group):
"""**is_in_group(group)** -> return True if the node have the group, False otherwise.
* group: (string) group to check.
<code>
Example:
is_in_group('linux')
Returns:
True
</code>
"""
return gossiper.is_in_group(group)
<commit_msg>Enh: Declare the is_in_defined_group function, even if it is an alias of the is_in_group<commit_after>from opsbro.evaluater import export_evaluater_function
from opsbro.gossip import gossiper
FUNCTION_GROUP = 'gossip'
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_group(group):
"""**is_in_group(group)** -> return True if the node have the group, False otherwise.
* group: (string) group to check.
<code>
Example:
is_in_group('linux')
Returns:
True
</code>
"""
return gossiper.is_in_group(group)
@export_evaluater_function(function_group=FUNCTION_GROUP)
def is_in_defined_group(group):
"""**is_in_defined_group(group)** -> return True if the node have the group but was set in the configuration, not from discovery False otherwise.
* group: (string) group to check.
<code>
Example:
is_in_defined_group('linux')
Returns:
True
</code>
"""
return gossiper.is_in_group(group)
|
174eb11bf4bdd65e269f0792ddcb1e589bca8b0d | boto3/compat.py | boto3/compat.py | # Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import sys
import os
if sys.platform.startswith('win'):
def rename_file(current_filename, new_filename):
try:
os.remove(new_filename)
except OSError:
pass
os.rename(current_filename, new_filename)
else:
rename_file = os.rename
| # Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import sys
import os
import errno
if sys.platform.startswith('win'):
def rename_file(current_filename, new_filename):
try:
os.remove(new_filename)
except OSError as e:
if not e.errno == errno.ENOENT:
# We only want to a ignore trying to remove
# a file that does not exist. If it fails
# for any other reason we should be propagating
# that exception.
raise
os.rename(current_filename, new_filename)
else:
rename_file = os.rename
| Handle the case where OSError is not because file does not exist | Handle the case where OSError is not because file does not exist
| Python | apache-2.0 | boto/boto3 | # Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import sys
import os
if sys.platform.startswith('win'):
def rename_file(current_filename, new_filename):
try:
os.remove(new_filename)
except OSError:
pass
os.rename(current_filename, new_filename)
else:
rename_file = os.rename
Handle the case where OSError is not because file does not exist | # Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import sys
import os
import errno
if sys.platform.startswith('win'):
def rename_file(current_filename, new_filename):
try:
os.remove(new_filename)
except OSError as e:
if not e.errno == errno.ENOENT:
# We only want to a ignore trying to remove
# a file that does not exist. If it fails
# for any other reason we should be propagating
# that exception.
raise
os.rename(current_filename, new_filename)
else:
rename_file = os.rename
| <commit_before># Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import sys
import os
if sys.platform.startswith('win'):
def rename_file(current_filename, new_filename):
try:
os.remove(new_filename)
except OSError:
pass
os.rename(current_filename, new_filename)
else:
rename_file = os.rename
<commit_msg>Handle the case where OSError is not because file does not exist<commit_after> | # Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import sys
import os
import errno
if sys.platform.startswith('win'):
def rename_file(current_filename, new_filename):
try:
os.remove(new_filename)
except OSError as e:
if not e.errno == errno.ENOENT:
# We only want to a ignore trying to remove
# a file that does not exist. If it fails
# for any other reason we should be propagating
# that exception.
raise
os.rename(current_filename, new_filename)
else:
rename_file = os.rename
| # Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import sys
import os
if sys.platform.startswith('win'):
def rename_file(current_filename, new_filename):
try:
os.remove(new_filename)
except OSError:
pass
os.rename(current_filename, new_filename)
else:
rename_file = os.rename
Handle the case where OSError is not because file does not exist# Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import sys
import os
import errno
if sys.platform.startswith('win'):
def rename_file(current_filename, new_filename):
try:
os.remove(new_filename)
except OSError as e:
if not e.errno == errno.ENOENT:
# We only want to a ignore trying to remove
# a file that does not exist. If it fails
# for any other reason we should be propagating
# that exception.
raise
os.rename(current_filename, new_filename)
else:
rename_file = os.rename
| <commit_before># Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import sys
import os
if sys.platform.startswith('win'):
def rename_file(current_filename, new_filename):
try:
os.remove(new_filename)
except OSError:
pass
os.rename(current_filename, new_filename)
else:
rename_file = os.rename
<commit_msg>Handle the case where OSError is not because file does not exist<commit_after># Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import sys
import os
import errno
if sys.platform.startswith('win'):
def rename_file(current_filename, new_filename):
try:
os.remove(new_filename)
except OSError as e:
if not e.errno == errno.ENOENT:
# We only want to a ignore trying to remove
# a file that does not exist. If it fails
# for any other reason we should be propagating
# that exception.
raise
os.rename(current_filename, new_filename)
else:
rename_file = os.rename
|
e8c1ba2c63a1ea66aa2c08e606ac0614e6854565 | interrupt.py | interrupt.py | import signal
import sys
from threading import Event
def GetInterruptEvent():
e = Event()
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
e.set()
signal.signal(signal.SIGINT, signal_handler)
return e
| import signal
import sys
from threading import Event
def GetInterruptEvent():
e = Event()
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
e.set()
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
return e
| Handle sigterm as well as sigint. | Handle sigterm as well as sigint.
| Python | mit | rickbassham/videoencode,rickbassham/videoencode | import signal
import sys
from threading import Event
def GetInterruptEvent():
e = Event()
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
e.set()
signal.signal(signal.SIGINT, signal_handler)
return e
Handle sigterm as well as sigint. | import signal
import sys
from threading import Event
def GetInterruptEvent():
e = Event()
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
e.set()
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
return e
| <commit_before>import signal
import sys
from threading import Event
def GetInterruptEvent():
e = Event()
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
e.set()
signal.signal(signal.SIGINT, signal_handler)
return e
<commit_msg>Handle sigterm as well as sigint.<commit_after> | import signal
import sys
from threading import Event
def GetInterruptEvent():
e = Event()
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
e.set()
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
return e
| import signal
import sys
from threading import Event
def GetInterruptEvent():
e = Event()
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
e.set()
signal.signal(signal.SIGINT, signal_handler)
return e
Handle sigterm as well as sigint.import signal
import sys
from threading import Event
def GetInterruptEvent():
e = Event()
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
e.set()
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
return e
| <commit_before>import signal
import sys
from threading import Event
def GetInterruptEvent():
e = Event()
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
e.set()
signal.signal(signal.SIGINT, signal_handler)
return e
<commit_msg>Handle sigterm as well as sigint.<commit_after>import signal
import sys
from threading import Event
def GetInterruptEvent():
e = Event()
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
e.set()
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
return e
|
441cccc340afeb205da75762ce6e145215a858b3 | src/zephyr/delayed_stream.py | src/zephyr/delayed_stream.py |
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, delay):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
self.callbacks = callbacks
self.delay = delay
self.stream_output_positions = collections.defaultdict(lambda: 0)
self.terminate_requested = False
def add_callback(self, callback):
self.callbacks.append(callback)
def terminate(self):
self.terminate_requested = True
def run(self):
while not self.terminate_requested:
delayed_current_time = zephyr.time() - self.delay
all_streams = itertools.chain(self.signal_collector.iterate_signal_stream_histories(),
self.signal_collector.iterate_event_streams())
for signal_stream_name, signal_stream_history in all_streams:
from_sample = self.stream_output_positions[signal_stream_name]
for sample in signal_stream_history.iterate_samples(from_sample, delayed_current_time):
self.stream_output_positions[signal_stream_name] += 1
for callback in self.callbacks:
callback(signal_stream_name, sample)
time.sleep(0.01)
|
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, default_delay, specific_delays={}):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
self.callbacks = callbacks
self.default_delay = default_delay
self.specific_delays = specific_delays
self.stream_output_positions = collections.defaultdict(lambda: 0)
self.terminate_requested = False
def add_callback(self, callback):
self.callbacks.append(callback)
def terminate(self):
self.terminate_requested = True
def run(self):
while not self.terminate_requested:
now = zephyr.time()
all_streams = itertools.chain(self.signal_collector.iterate_signal_stream_histories(),
self.signal_collector.iterate_event_streams())
for signal_stream_name, signal_stream_history in all_streams:
delay = self.specific_delays.get(signal_stream_name, self.default_delay)
delayed_current_time = now - delay
from_sample = self.stream_output_positions[signal_stream_name]
for sample in signal_stream_history.iterate_samples(from_sample, delayed_current_time):
self.stream_output_positions[signal_stream_name] += 1
for callback in self.callbacks:
callback(signal_stream_name, sample)
time.sleep(0.01)
| Split delay configuration into default_delay and specific_delays | Split delay configuration into default_delay and specific_delays | Python | bsd-2-clause | jpaalasm/zephyr-bt |
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, delay):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
self.callbacks = callbacks
self.delay = delay
self.stream_output_positions = collections.defaultdict(lambda: 0)
self.terminate_requested = False
def add_callback(self, callback):
self.callbacks.append(callback)
def terminate(self):
self.terminate_requested = True
def run(self):
while not self.terminate_requested:
delayed_current_time = zephyr.time() - self.delay
all_streams = itertools.chain(self.signal_collector.iterate_signal_stream_histories(),
self.signal_collector.iterate_event_streams())
for signal_stream_name, signal_stream_history in all_streams:
from_sample = self.stream_output_positions[signal_stream_name]
for sample in signal_stream_history.iterate_samples(from_sample, delayed_current_time):
self.stream_output_positions[signal_stream_name] += 1
for callback in self.callbacks:
callback(signal_stream_name, sample)
time.sleep(0.01)
Split delay configuration into default_delay and specific_delays |
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, default_delay, specific_delays={}):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
self.callbacks = callbacks
self.default_delay = default_delay
self.specific_delays = specific_delays
self.stream_output_positions = collections.defaultdict(lambda: 0)
self.terminate_requested = False
def add_callback(self, callback):
self.callbacks.append(callback)
def terminate(self):
self.terminate_requested = True
def run(self):
while not self.terminate_requested:
now = zephyr.time()
all_streams = itertools.chain(self.signal_collector.iterate_signal_stream_histories(),
self.signal_collector.iterate_event_streams())
for signal_stream_name, signal_stream_history in all_streams:
delay = self.specific_delays.get(signal_stream_name, self.default_delay)
delayed_current_time = now - delay
from_sample = self.stream_output_positions[signal_stream_name]
for sample in signal_stream_history.iterate_samples(from_sample, delayed_current_time):
self.stream_output_positions[signal_stream_name] += 1
for callback in self.callbacks:
callback(signal_stream_name, sample)
time.sleep(0.01)
| <commit_before>
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, delay):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
self.callbacks = callbacks
self.delay = delay
self.stream_output_positions = collections.defaultdict(lambda: 0)
self.terminate_requested = False
def add_callback(self, callback):
self.callbacks.append(callback)
def terminate(self):
self.terminate_requested = True
def run(self):
while not self.terminate_requested:
delayed_current_time = zephyr.time() - self.delay
all_streams = itertools.chain(self.signal_collector.iterate_signal_stream_histories(),
self.signal_collector.iterate_event_streams())
for signal_stream_name, signal_stream_history in all_streams:
from_sample = self.stream_output_positions[signal_stream_name]
for sample in signal_stream_history.iterate_samples(from_sample, delayed_current_time):
self.stream_output_positions[signal_stream_name] += 1
for callback in self.callbacks:
callback(signal_stream_name, sample)
time.sleep(0.01)
<commit_msg>Split delay configuration into default_delay and specific_delays<commit_after> |
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, default_delay, specific_delays={}):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
self.callbacks = callbacks
self.default_delay = default_delay
self.specific_delays = specific_delays
self.stream_output_positions = collections.defaultdict(lambda: 0)
self.terminate_requested = False
def add_callback(self, callback):
self.callbacks.append(callback)
def terminate(self):
self.terminate_requested = True
def run(self):
while not self.terminate_requested:
now = zephyr.time()
all_streams = itertools.chain(self.signal_collector.iterate_signal_stream_histories(),
self.signal_collector.iterate_event_streams())
for signal_stream_name, signal_stream_history in all_streams:
delay = self.specific_delays.get(signal_stream_name, self.default_delay)
delayed_current_time = now - delay
from_sample = self.stream_output_positions[signal_stream_name]
for sample in signal_stream_history.iterate_samples(from_sample, delayed_current_time):
self.stream_output_positions[signal_stream_name] += 1
for callback in self.callbacks:
callback(signal_stream_name, sample)
time.sleep(0.01)
|
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, delay):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
self.callbacks = callbacks
self.delay = delay
self.stream_output_positions = collections.defaultdict(lambda: 0)
self.terminate_requested = False
def add_callback(self, callback):
self.callbacks.append(callback)
def terminate(self):
self.terminate_requested = True
def run(self):
while not self.terminate_requested:
delayed_current_time = zephyr.time() - self.delay
all_streams = itertools.chain(self.signal_collector.iterate_signal_stream_histories(),
self.signal_collector.iterate_event_streams())
for signal_stream_name, signal_stream_history in all_streams:
from_sample = self.stream_output_positions[signal_stream_name]
for sample in signal_stream_history.iterate_samples(from_sample, delayed_current_time):
self.stream_output_positions[signal_stream_name] += 1
for callback in self.callbacks:
callback(signal_stream_name, sample)
time.sleep(0.01)
Split delay configuration into default_delay and specific_delays
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, default_delay, specific_delays={}):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
self.callbacks = callbacks
self.default_delay = default_delay
self.specific_delays = specific_delays
self.stream_output_positions = collections.defaultdict(lambda: 0)
self.terminate_requested = False
def add_callback(self, callback):
self.callbacks.append(callback)
def terminate(self):
self.terminate_requested = True
def run(self):
while not self.terminate_requested:
now = zephyr.time()
all_streams = itertools.chain(self.signal_collector.iterate_signal_stream_histories(),
self.signal_collector.iterate_event_streams())
for signal_stream_name, signal_stream_history in all_streams:
delay = self.specific_delays.get(signal_stream_name, self.default_delay)
delayed_current_time = now - delay
from_sample = self.stream_output_positions[signal_stream_name]
for sample in signal_stream_history.iterate_samples(from_sample, delayed_current_time):
self.stream_output_positions[signal_stream_name] += 1
for callback in self.callbacks:
callback(signal_stream_name, sample)
time.sleep(0.01)
| <commit_before>
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, delay):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
self.callbacks = callbacks
self.delay = delay
self.stream_output_positions = collections.defaultdict(lambda: 0)
self.terminate_requested = False
def add_callback(self, callback):
self.callbacks.append(callback)
def terminate(self):
self.terminate_requested = True
def run(self):
while not self.terminate_requested:
delayed_current_time = zephyr.time() - self.delay
all_streams = itertools.chain(self.signal_collector.iterate_signal_stream_histories(),
self.signal_collector.iterate_event_streams())
for signal_stream_name, signal_stream_history in all_streams:
from_sample = self.stream_output_positions[signal_stream_name]
for sample in signal_stream_history.iterate_samples(from_sample, delayed_current_time):
self.stream_output_positions[signal_stream_name] += 1
for callback in self.callbacks:
callback(signal_stream_name, sample)
time.sleep(0.01)
<commit_msg>Split delay configuration into default_delay and specific_delays<commit_after>
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, default_delay, specific_delays={}):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
self.callbacks = callbacks
self.default_delay = default_delay
self.specific_delays = specific_delays
self.stream_output_positions = collections.defaultdict(lambda: 0)
self.terminate_requested = False
def add_callback(self, callback):
self.callbacks.append(callback)
def terminate(self):
self.terminate_requested = True
def run(self):
while not self.terminate_requested:
now = zephyr.time()
all_streams = itertools.chain(self.signal_collector.iterate_signal_stream_histories(),
self.signal_collector.iterate_event_streams())
for signal_stream_name, signal_stream_history in all_streams:
delay = self.specific_delays.get(signal_stream_name, self.default_delay)
delayed_current_time = now - delay
from_sample = self.stream_output_positions[signal_stream_name]
for sample in signal_stream_history.iterate_samples(from_sample, delayed_current_time):
self.stream_output_positions[signal_stream_name] += 1
for callback in self.callbacks:
callback(signal_stream_name, sample)
time.sleep(0.01)
|
1fc1e160143b5a35741cf3fce9ced827a433d640 | tests/test__pycompat.py | tests/test__pycompat.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask_distance._pycompat
def test_irange():
r = dask_distance._pycompat.irange(5)
assert not isinstance(r, list)
assert list(r) == [0, 1, 2, 3, 4]
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask_distance._pycompat
def test_irange():
r = dask_distance._pycompat.irange(5)
assert not isinstance(r, list)
assert list(r) == [0, 1, 2, 3, 4]
def test_izip():
r = dask_distance._pycompat.izip([1, 2, 3], ["a", "b", "c"])
assert not isinstance(r, list)
assert list(r) == [(1, 'a'), (2, 'b'), (3, 'c')]
| Add a test for izip | Add a test for izip
Make sure that it generates an iterator on both Python 2 and Python 3.
Also check that it can be converted to a `list`.
| Python | bsd-3-clause | jakirkham/dask-distance | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask_distance._pycompat
def test_irange():
r = dask_distance._pycompat.irange(5)
assert not isinstance(r, list)
assert list(r) == [0, 1, 2, 3, 4]
Add a test for izip
Make sure that it generates an iterator on both Python 2 and Python 3.
Also check that it can be converted to a `list`. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask_distance._pycompat
def test_irange():
r = dask_distance._pycompat.irange(5)
assert not isinstance(r, list)
assert list(r) == [0, 1, 2, 3, 4]
def test_izip():
r = dask_distance._pycompat.izip([1, 2, 3], ["a", "b", "c"])
assert not isinstance(r, list)
assert list(r) == [(1, 'a'), (2, 'b'), (3, 'c')]
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask_distance._pycompat
def test_irange():
r = dask_distance._pycompat.irange(5)
assert not isinstance(r, list)
assert list(r) == [0, 1, 2, 3, 4]
<commit_msg>Add a test for izip
Make sure that it generates an iterator on both Python 2 and Python 3.
Also check that it can be converted to a `list`.<commit_after> | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask_distance._pycompat
def test_irange():
r = dask_distance._pycompat.irange(5)
assert not isinstance(r, list)
assert list(r) == [0, 1, 2, 3, 4]
def test_izip():
r = dask_distance._pycompat.izip([1, 2, 3], ["a", "b", "c"])
assert not isinstance(r, list)
assert list(r) == [(1, 'a'), (2, 'b'), (3, 'c')]
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask_distance._pycompat
def test_irange():
r = dask_distance._pycompat.irange(5)
assert not isinstance(r, list)
assert list(r) == [0, 1, 2, 3, 4]
Add a test for izip
Make sure that it generates an iterator on both Python 2 and Python 3.
Also check that it can be converted to a `list`.#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask_distance._pycompat
def test_irange():
r = dask_distance._pycompat.irange(5)
assert not isinstance(r, list)
assert list(r) == [0, 1, 2, 3, 4]
def test_izip():
r = dask_distance._pycompat.izip([1, 2, 3], ["a", "b", "c"])
assert not isinstance(r, list)
assert list(r) == [(1, 'a'), (2, 'b'), (3, 'c')]
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask_distance._pycompat
def test_irange():
r = dask_distance._pycompat.irange(5)
assert not isinstance(r, list)
assert list(r) == [0, 1, 2, 3, 4]
<commit_msg>Add a test for izip
Make sure that it generates an iterator on both Python 2 and Python 3.
Also check that it can be converted to a `list`.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask_distance._pycompat
def test_irange():
r = dask_distance._pycompat.irange(5)
assert not isinstance(r, list)
assert list(r) == [0, 1, 2, 3, 4]
def test_izip():
r = dask_distance._pycompat.izip([1, 2, 3], ["a", "b", "c"])
assert not isinstance(r, list)
assert list(r) == [(1, 'a'), (2, 'b'), (3, 'c')]
|
2f0f560808e07c31ffb88e4b8c9d272536f58e5c | api/commands.py | api/commands.py | import json
import requests
from Suchary.local_settings import GCM_API_KEY
from api.models import Device
URL = 'https://android.googleapis.com/gcm/send'
HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'}
def get_reg_ids():
reg_ids = [device.registration_id for device in Device.objects.filter(active=True)]
return reg_ids
def send(data, collapse_key=None):
reg_ids = get_reg_ids()
payload = {'registration_ids': reg_ids, 'data': data}
if collapse_key is not None:
payload.update({'collapse_key': collapse_key})
r = requests.post(URL, data=json.dumps(payload), headers=HEADER)
def edit_joke(key):
data = {
'type': 'edit',
'key': key
}
send(data)
def new_jokes():
data = {
'type': 'new'
}
send(data, 'new')
def delete_joke(key):
data = {
'type': 'delete',
'key': key
}
send(data) | import json
import requests
from Suchary.local_settings import GCM_API_KEY
from api.models import Device
URL = 'https://android.googleapis.com/gcm/send'
HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'}
def get_reg_ids():
reg_ids = [device.registration_id for device in Device.objects.filter(active=True)]
return reg_ids
def send(data, collapse_key=None):
reg_ids = get_reg_ids()
payload = {'registration_ids': reg_ids, 'data': data}
if collapse_key is not None:
payload.update({'collapse_key': collapse_key})
r = requests.post(URL, data=json.dumps(payload), headers=HEADER)
def edit_joke(key):
data = {
'type': 'edit',
'key': key
}
send(data)
def new_jokes():
data = {
'type': 'new'
}
send(data, 'new')
def delete_joke(key):
data = {
'type': 'delete',
'key': key
}
send(data)
def send_message(title, body):
data = {
'type': 'message',
'title': title,
'text': body
}
send(data) | Add command to send messages via GCM | Add command to send messages via GCM
| Python | mit | jchmura/suchary-django,jchmura/suchary-django,jchmura/suchary-django | import json
import requests
from Suchary.local_settings import GCM_API_KEY
from api.models import Device
URL = 'https://android.googleapis.com/gcm/send'
HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'}
def get_reg_ids():
reg_ids = [device.registration_id for device in Device.objects.filter(active=True)]
return reg_ids
def send(data, collapse_key=None):
reg_ids = get_reg_ids()
payload = {'registration_ids': reg_ids, 'data': data}
if collapse_key is not None:
payload.update({'collapse_key': collapse_key})
r = requests.post(URL, data=json.dumps(payload), headers=HEADER)
def edit_joke(key):
data = {
'type': 'edit',
'key': key
}
send(data)
def new_jokes():
data = {
'type': 'new'
}
send(data, 'new')
def delete_joke(key):
data = {
'type': 'delete',
'key': key
}
send(data)Add command to send messages via GCM | import json
import requests
from Suchary.local_settings import GCM_API_KEY
from api.models import Device
URL = 'https://android.googleapis.com/gcm/send'
HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'}
def get_reg_ids():
reg_ids = [device.registration_id for device in Device.objects.filter(active=True)]
return reg_ids
def send(data, collapse_key=None):
reg_ids = get_reg_ids()
payload = {'registration_ids': reg_ids, 'data': data}
if collapse_key is not None:
payload.update({'collapse_key': collapse_key})
r = requests.post(URL, data=json.dumps(payload), headers=HEADER)
def edit_joke(key):
data = {
'type': 'edit',
'key': key
}
send(data)
def new_jokes():
data = {
'type': 'new'
}
send(data, 'new')
def delete_joke(key):
data = {
'type': 'delete',
'key': key
}
send(data)
def send_message(title, body):
data = {
'type': 'message',
'title': title,
'text': body
}
send(data) | <commit_before>import json
import requests
from Suchary.local_settings import GCM_API_KEY
from api.models import Device
URL = 'https://android.googleapis.com/gcm/send'
HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'}
def get_reg_ids():
reg_ids = [device.registration_id for device in Device.objects.filter(active=True)]
return reg_ids
def send(data, collapse_key=None):
reg_ids = get_reg_ids()
payload = {'registration_ids': reg_ids, 'data': data}
if collapse_key is not None:
payload.update({'collapse_key': collapse_key})
r = requests.post(URL, data=json.dumps(payload), headers=HEADER)
def edit_joke(key):
data = {
'type': 'edit',
'key': key
}
send(data)
def new_jokes():
data = {
'type': 'new'
}
send(data, 'new')
def delete_joke(key):
data = {
'type': 'delete',
'key': key
}
send(data)<commit_msg>Add command to send messages via GCM<commit_after> | import json
import requests
from Suchary.local_settings import GCM_API_KEY
from api.models import Device
URL = 'https://android.googleapis.com/gcm/send'
HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'}
def get_reg_ids():
reg_ids = [device.registration_id for device in Device.objects.filter(active=True)]
return reg_ids
def send(data, collapse_key=None):
reg_ids = get_reg_ids()
payload = {'registration_ids': reg_ids, 'data': data}
if collapse_key is not None:
payload.update({'collapse_key': collapse_key})
r = requests.post(URL, data=json.dumps(payload), headers=HEADER)
def edit_joke(key):
data = {
'type': 'edit',
'key': key
}
send(data)
def new_jokes():
data = {
'type': 'new'
}
send(data, 'new')
def delete_joke(key):
data = {
'type': 'delete',
'key': key
}
send(data)
def send_message(title, body):
data = {
'type': 'message',
'title': title,
'text': body
}
send(data) | import json
import requests
from Suchary.local_settings import GCM_API_KEY
from api.models import Device
URL = 'https://android.googleapis.com/gcm/send'
HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'}
def get_reg_ids():
reg_ids = [device.registration_id for device in Device.objects.filter(active=True)]
return reg_ids
def send(data, collapse_key=None):
reg_ids = get_reg_ids()
payload = {'registration_ids': reg_ids, 'data': data}
if collapse_key is not None:
payload.update({'collapse_key': collapse_key})
r = requests.post(URL, data=json.dumps(payload), headers=HEADER)
def edit_joke(key):
data = {
'type': 'edit',
'key': key
}
send(data)
def new_jokes():
data = {
'type': 'new'
}
send(data, 'new')
def delete_joke(key):
data = {
'type': 'delete',
'key': key
}
send(data)Add command to send messages via GCMimport json
import requests
from Suchary.local_settings import GCM_API_KEY
from api.models import Device
URL = 'https://android.googleapis.com/gcm/send'
HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'}
def get_reg_ids():
reg_ids = [device.registration_id for device in Device.objects.filter(active=True)]
return reg_ids
def send(data, collapse_key=None):
reg_ids = get_reg_ids()
payload = {'registration_ids': reg_ids, 'data': data}
if collapse_key is not None:
payload.update({'collapse_key': collapse_key})
r = requests.post(URL, data=json.dumps(payload), headers=HEADER)
def edit_joke(key):
data = {
'type': 'edit',
'key': key
}
send(data)
def new_jokes():
data = {
'type': 'new'
}
send(data, 'new')
def delete_joke(key):
data = {
'type': 'delete',
'key': key
}
send(data)
def send_message(title, body):
data = {
'type': 'message',
'title': title,
'text': body
}
send(data) | <commit_before>import json
import requests
from Suchary.local_settings import GCM_API_KEY
from api.models import Device
URL = 'https://android.googleapis.com/gcm/send'
HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'}
def get_reg_ids():
reg_ids = [device.registration_id for device in Device.objects.filter(active=True)]
return reg_ids
def send(data, collapse_key=None):
reg_ids = get_reg_ids()
payload = {'registration_ids': reg_ids, 'data': data}
if collapse_key is not None:
payload.update({'collapse_key': collapse_key})
r = requests.post(URL, data=json.dumps(payload), headers=HEADER)
def edit_joke(key):
data = {
'type': 'edit',
'key': key
}
send(data)
def new_jokes():
data = {
'type': 'new'
}
send(data, 'new')
def delete_joke(key):
data = {
'type': 'delete',
'key': key
}
send(data)<commit_msg>Add command to send messages via GCM<commit_after>import json
import requests
from Suchary.local_settings import GCM_API_KEY
from api.models import Device
URL = 'https://android.googleapis.com/gcm/send'
HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'}
def get_reg_ids():
reg_ids = [device.registration_id for device in Device.objects.filter(active=True)]
return reg_ids
def send(data, collapse_key=None):
reg_ids = get_reg_ids()
payload = {'registration_ids': reg_ids, 'data': data}
if collapse_key is not None:
payload.update({'collapse_key': collapse_key})
r = requests.post(URL, data=json.dumps(payload), headers=HEADER)
def edit_joke(key):
data = {
'type': 'edit',
'key': key
}
send(data)
def new_jokes():
data = {
'type': 'new'
}
send(data, 'new')
def delete_joke(key):
data = {
'type': 'delete',
'key': key
}
send(data)
def send_message(title, body):
data = {
'type': 'message',
'title': title,
'text': body
}
send(data) |
343e3bd0e16df1106d82fa6087a7247dc67bb52b | oslo_concurrency/_i18n.py | oslo_concurrency/_i18n.py | # Copyright 2014 Mirantis 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.
from oslo import i18n
_translators = i18n.TranslatorFactory(domain='oslo.concurrency')
# The primary translation function using the well-known name "_"
_ = _translators.primary
# Translators for log levels.
#
# The abbreviated names are meant to reflect the usual use of a short
# name like '_'. The "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical
| # Copyright 2014 Mirantis 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.
import oslo_i18n
_translators = oslo_i18n.TranslatorFactory(domain='oslo.concurrency')
# The primary translation function using the well-known name "_"
_ = _translators.primary
# Translators for log levels.
#
# The abbreviated names are meant to reflect the usual use of a short
# name like '_'. The "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical
| Drop use of namespaced oslo.i18n | Drop use of namespaced oslo.i18n
Related-blueprint: drop-namespace-packages
Change-Id: Ic8247cb896ba6337932d7a74618debd698584fa0
| Python | apache-2.0 | JioCloud/oslo.concurrency,openstack/oslo.concurrency,varunarya10/oslo.concurrency | # Copyright 2014 Mirantis 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.
from oslo import i18n
_translators = i18n.TranslatorFactory(domain='oslo.concurrency')
# The primary translation function using the well-known name "_"
_ = _translators.primary
# Translators for log levels.
#
# The abbreviated names are meant to reflect the usual use of a short
# name like '_'. The "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical
Drop use of namespaced oslo.i18n
Related-blueprint: drop-namespace-packages
Change-Id: Ic8247cb896ba6337932d7a74618debd698584fa0 | # Copyright 2014 Mirantis 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.
import oslo_i18n
_translators = oslo_i18n.TranslatorFactory(domain='oslo.concurrency')
# The primary translation function using the well-known name "_"
_ = _translators.primary
# Translators for log levels.
#
# The abbreviated names are meant to reflect the usual use of a short
# name like '_'. The "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical
| <commit_before># Copyright 2014 Mirantis 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.
from oslo import i18n
_translators = i18n.TranslatorFactory(domain='oslo.concurrency')
# The primary translation function using the well-known name "_"
_ = _translators.primary
# Translators for log levels.
#
# The abbreviated names are meant to reflect the usual use of a short
# name like '_'. The "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical
<commit_msg>Drop use of namespaced oslo.i18n
Related-blueprint: drop-namespace-packages
Change-Id: Ic8247cb896ba6337932d7a74618debd698584fa0<commit_after> | # Copyright 2014 Mirantis 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.
import oslo_i18n
_translators = oslo_i18n.TranslatorFactory(domain='oslo.concurrency')
# The primary translation function using the well-known name "_"
_ = _translators.primary
# Translators for log levels.
#
# The abbreviated names are meant to reflect the usual use of a short
# name like '_'. The "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical
| # Copyright 2014 Mirantis 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.
from oslo import i18n
_translators = i18n.TranslatorFactory(domain='oslo.concurrency')
# The primary translation function using the well-known name "_"
_ = _translators.primary
# Translators for log levels.
#
# The abbreviated names are meant to reflect the usual use of a short
# name like '_'. The "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical
Drop use of namespaced oslo.i18n
Related-blueprint: drop-namespace-packages
Change-Id: Ic8247cb896ba6337932d7a74618debd698584fa0# Copyright 2014 Mirantis 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.
import oslo_i18n
_translators = oslo_i18n.TranslatorFactory(domain='oslo.concurrency')
# The primary translation function using the well-known name "_"
_ = _translators.primary
# Translators for log levels.
#
# The abbreviated names are meant to reflect the usual use of a short
# name like '_'. The "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical
| <commit_before># Copyright 2014 Mirantis 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.
from oslo import i18n
_translators = i18n.TranslatorFactory(domain='oslo.concurrency')
# The primary translation function using the well-known name "_"
_ = _translators.primary
# Translators for log levels.
#
# The abbreviated names are meant to reflect the usual use of a short
# name like '_'. The "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical
<commit_msg>Drop use of namespaced oslo.i18n
Related-blueprint: drop-namespace-packages
Change-Id: Ic8247cb896ba6337932d7a74618debd698584fa0<commit_after># Copyright 2014 Mirantis 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.
import oslo_i18n
_translators = oslo_i18n.TranslatorFactory(domain='oslo.concurrency')
# The primary translation function using the well-known name "_"
_ = _translators.primary
# Translators for log levels.
#
# The abbreviated names are meant to reflect the usual use of a short
# name like '_'. The "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical
|
05c6920ff6f2d9b617346d4cca59622fb14a8f2e | picoCTF-web/api/tests/conftest.py | picoCTF-web/api/tests/conftest.py | """
Common set of functionality for picoAPI testing.
Fixtures defined within this file are available to all
other testing modules.
"""
import pytest
import api.common
from pymongo import MongoClient
mongo_addr = "127.0.0.1"
mongo_port = 27017
mongo_db_name = "pico_test"
def setup_db():
""" Creates a mongodb instance and shuts it down after testing has concluded. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
assert len(client.collection_names()) == 0, "Mongo db: {} is not empty.".format(mongo_db_name)
#Set debug client for mongo
if api.common.external_client is None:
api.common.external_client = client
return client
def teardown_db():
""" Drops the db and shuts down the mongodb instance. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
client.connection.drop_database(mongo_db_name)
client.connection.disconnect()
print("Disconnected from mongodb.")
| """
Common set of functionality for picoAPI testing.
Fixtures defined within this file are available to all
other testing modules.
"""
import pytest
import api.common
from pymongo import MongoClient
mongo_addr = "127.0.0.1"
mongo_port = 27017
mongo_db_name = "pico_test"
def setup_db():
""" Creates a mongodb instance and shuts it down after testing has concluded. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
if len(client.collection_names()) != 0:
client.connection.drop_database(mongo_db_name)
#Set debug client for mongo
if api.common.external_client is None:
api.common.external_client = client
return client
def teardown_db():
""" Drops the db and shuts down the mongodb instance. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
client.connection.drop_database(mongo_db_name)
client.connection.disconnect()
print("Disconnected from mongodb.")
| Clear db if not empty | Clear db if not empty
| Python | mit | picoCTF/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF | """
Common set of functionality for picoAPI testing.
Fixtures defined within this file are available to all
other testing modules.
"""
import pytest
import api.common
from pymongo import MongoClient
mongo_addr = "127.0.0.1"
mongo_port = 27017
mongo_db_name = "pico_test"
def setup_db():
""" Creates a mongodb instance and shuts it down after testing has concluded. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
assert len(client.collection_names()) == 0, "Mongo db: {} is not empty.".format(mongo_db_name)
#Set debug client for mongo
if api.common.external_client is None:
api.common.external_client = client
return client
def teardown_db():
""" Drops the db and shuts down the mongodb instance. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
client.connection.drop_database(mongo_db_name)
client.connection.disconnect()
print("Disconnected from mongodb.")
Clear db if not empty | """
Common set of functionality for picoAPI testing.
Fixtures defined within this file are available to all
other testing modules.
"""
import pytest
import api.common
from pymongo import MongoClient
mongo_addr = "127.0.0.1"
mongo_port = 27017
mongo_db_name = "pico_test"
def setup_db():
""" Creates a mongodb instance and shuts it down after testing has concluded. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
if len(client.collection_names()) != 0:
client.connection.drop_database(mongo_db_name)
#Set debug client for mongo
if api.common.external_client is None:
api.common.external_client = client
return client
def teardown_db():
""" Drops the db and shuts down the mongodb instance. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
client.connection.drop_database(mongo_db_name)
client.connection.disconnect()
print("Disconnected from mongodb.")
| <commit_before>"""
Common set of functionality for picoAPI testing.
Fixtures defined within this file are available to all
other testing modules.
"""
import pytest
import api.common
from pymongo import MongoClient
mongo_addr = "127.0.0.1"
mongo_port = 27017
mongo_db_name = "pico_test"
def setup_db():
""" Creates a mongodb instance and shuts it down after testing has concluded. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
assert len(client.collection_names()) == 0, "Mongo db: {} is not empty.".format(mongo_db_name)
#Set debug client for mongo
if api.common.external_client is None:
api.common.external_client = client
return client
def teardown_db():
""" Drops the db and shuts down the mongodb instance. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
client.connection.drop_database(mongo_db_name)
client.connection.disconnect()
print("Disconnected from mongodb.")
<commit_msg>Clear db if not empty<commit_after> | """
Common set of functionality for picoAPI testing.
Fixtures defined within this file are available to all
other testing modules.
"""
import pytest
import api.common
from pymongo import MongoClient
mongo_addr = "127.0.0.1"
mongo_port = 27017
mongo_db_name = "pico_test"
def setup_db():
""" Creates a mongodb instance and shuts it down after testing has concluded. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
if len(client.collection_names()) != 0:
client.connection.drop_database(mongo_db_name)
#Set debug client for mongo
if api.common.external_client is None:
api.common.external_client = client
return client
def teardown_db():
""" Drops the db and shuts down the mongodb instance. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
client.connection.drop_database(mongo_db_name)
client.connection.disconnect()
print("Disconnected from mongodb.")
| """
Common set of functionality for picoAPI testing.
Fixtures defined within this file are available to all
other testing modules.
"""
import pytest
import api.common
from pymongo import MongoClient
mongo_addr = "127.0.0.1"
mongo_port = 27017
mongo_db_name = "pico_test"
def setup_db():
""" Creates a mongodb instance and shuts it down after testing has concluded. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
assert len(client.collection_names()) == 0, "Mongo db: {} is not empty.".format(mongo_db_name)
#Set debug client for mongo
if api.common.external_client is None:
api.common.external_client = client
return client
def teardown_db():
""" Drops the db and shuts down the mongodb instance. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
client.connection.drop_database(mongo_db_name)
client.connection.disconnect()
print("Disconnected from mongodb.")
Clear db if not empty"""
Common set of functionality for picoAPI testing.
Fixtures defined within this file are available to all
other testing modules.
"""
import pytest
import api.common
from pymongo import MongoClient
mongo_addr = "127.0.0.1"
mongo_port = 27017
mongo_db_name = "pico_test"
def setup_db():
""" Creates a mongodb instance and shuts it down after testing has concluded. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
if len(client.collection_names()) != 0:
client.connection.drop_database(mongo_db_name)
#Set debug client for mongo
if api.common.external_client is None:
api.common.external_client = client
return client
def teardown_db():
""" Drops the db and shuts down the mongodb instance. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
client.connection.drop_database(mongo_db_name)
client.connection.disconnect()
print("Disconnected from mongodb.")
| <commit_before>"""
Common set of functionality for picoAPI testing.
Fixtures defined within this file are available to all
other testing modules.
"""
import pytest
import api.common
from pymongo import MongoClient
mongo_addr = "127.0.0.1"
mongo_port = 27017
mongo_db_name = "pico_test"
def setup_db():
""" Creates a mongodb instance and shuts it down after testing has concluded. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
assert len(client.collection_names()) == 0, "Mongo db: {} is not empty.".format(mongo_db_name)
#Set debug client for mongo
if api.common.external_client is None:
api.common.external_client = client
return client
def teardown_db():
""" Drops the db and shuts down the mongodb instance. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
client.connection.drop_database(mongo_db_name)
client.connection.disconnect()
print("Disconnected from mongodb.")
<commit_msg>Clear db if not empty<commit_after>"""
Common set of functionality for picoAPI testing.
Fixtures defined within this file are available to all
other testing modules.
"""
import pytest
import api.common
from pymongo import MongoClient
mongo_addr = "127.0.0.1"
mongo_port = 27017
mongo_db_name = "pico_test"
def setup_db():
""" Creates a mongodb instance and shuts it down after testing has concluded. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
if len(client.collection_names()) != 0:
client.connection.drop_database(mongo_db_name)
#Set debug client for mongo
if api.common.external_client is None:
api.common.external_client = client
return client
def teardown_db():
""" Drops the db and shuts down the mongodb instance. """
client = MongoClient(mongo_addr, mongo_port)[mongo_db_name]
client.connection.drop_database(mongo_db_name)
client.connection.disconnect()
print("Disconnected from mongodb.")
|
d14c0aeba5304ba66649c9d6a0a9d144a9ef1e43 | api/teams/admin.py | api/teams/admin.py | from django.contrib import admin
from .models import Team
from nucleus.admin import TeamMemberInline
class TeamAdmin(admin.ModelAdmin):
inlines = (TeamMemberInline, )
raw_id_fields = ('captain', 'creator', )
list_display = (
'name',
'get_player_count',
'get_player_list',
'created',
'updated',
)
search_fields = ('name', )
def get_queryset(self, request):
queryset = super().get_queryset(request)
return queryset.prefetch_related('players')
def get_player_count(self, obj):
return obj.players.count()
get_player_count.short_description = 'Num Players'
def get_player_list(self, obj):
return ', '.join([p.username for p in obj.players.all()])
get_player_list.short_description = 'Players'
admin.site.register(Team, TeamAdmin)
| from django.contrib import admin
from django.db.models import Count
from .models import Team
from nucleus.admin import TeamMemberInline
class TeamAdmin(admin.ModelAdmin):
inlines = (TeamMemberInline, )
raw_id_fields = ('captain', 'creator', )
list_display = (
'name',
'get_player_count',
'get_player_list',
'created',
'updated',
)
search_fields = ('name', )
def get_queryset(self, request):
queryset = super().get_queryset(request)
return queryset.prefetch_related('players').annotate(
player_count=Count('players')
)
def get_player_count(self, obj):
return obj.player_count
get_player_count.short_description = 'Num Players'
get_player_count.admin_order_field = 'player_count'
def get_player_list(self, obj):
return ', '.join([p.username for p in obj.players.all()])
get_player_list.short_description = 'Players'
admin.site.register(Team, TeamAdmin)
| Allow team num players column to be ordered | Allow team num players column to be ordered
| Python | mit | prattl/wepickheroes,prattl/wepickheroes,prattl/wepickheroes,prattl/wepickheroes | from django.contrib import admin
from .models import Team
from nucleus.admin import TeamMemberInline
class TeamAdmin(admin.ModelAdmin):
inlines = (TeamMemberInline, )
raw_id_fields = ('captain', 'creator', )
list_display = (
'name',
'get_player_count',
'get_player_list',
'created',
'updated',
)
search_fields = ('name', )
def get_queryset(self, request):
queryset = super().get_queryset(request)
return queryset.prefetch_related('players')
def get_player_count(self, obj):
return obj.players.count()
get_player_count.short_description = 'Num Players'
def get_player_list(self, obj):
return ', '.join([p.username for p in obj.players.all()])
get_player_list.short_description = 'Players'
admin.site.register(Team, TeamAdmin)
Allow team num players column to be ordered | from django.contrib import admin
from django.db.models import Count
from .models import Team
from nucleus.admin import TeamMemberInline
class TeamAdmin(admin.ModelAdmin):
inlines = (TeamMemberInline, )
raw_id_fields = ('captain', 'creator', )
list_display = (
'name',
'get_player_count',
'get_player_list',
'created',
'updated',
)
search_fields = ('name', )
def get_queryset(self, request):
queryset = super().get_queryset(request)
return queryset.prefetch_related('players').annotate(
player_count=Count('players')
)
def get_player_count(self, obj):
return obj.player_count
get_player_count.short_description = 'Num Players'
get_player_count.admin_order_field = 'player_count'
def get_player_list(self, obj):
return ', '.join([p.username for p in obj.players.all()])
get_player_list.short_description = 'Players'
admin.site.register(Team, TeamAdmin)
| <commit_before>from django.contrib import admin
from .models import Team
from nucleus.admin import TeamMemberInline
class TeamAdmin(admin.ModelAdmin):
inlines = (TeamMemberInline, )
raw_id_fields = ('captain', 'creator', )
list_display = (
'name',
'get_player_count',
'get_player_list',
'created',
'updated',
)
search_fields = ('name', )
def get_queryset(self, request):
queryset = super().get_queryset(request)
return queryset.prefetch_related('players')
def get_player_count(self, obj):
return obj.players.count()
get_player_count.short_description = 'Num Players'
def get_player_list(self, obj):
return ', '.join([p.username for p in obj.players.all()])
get_player_list.short_description = 'Players'
admin.site.register(Team, TeamAdmin)
<commit_msg>Allow team num players column to be ordered<commit_after> | from django.contrib import admin
from django.db.models import Count
from .models import Team
from nucleus.admin import TeamMemberInline
class TeamAdmin(admin.ModelAdmin):
inlines = (TeamMemberInline, )
raw_id_fields = ('captain', 'creator', )
list_display = (
'name',
'get_player_count',
'get_player_list',
'created',
'updated',
)
search_fields = ('name', )
def get_queryset(self, request):
queryset = super().get_queryset(request)
return queryset.prefetch_related('players').annotate(
player_count=Count('players')
)
def get_player_count(self, obj):
return obj.player_count
get_player_count.short_description = 'Num Players'
get_player_count.admin_order_field = 'player_count'
def get_player_list(self, obj):
return ', '.join([p.username for p in obj.players.all()])
get_player_list.short_description = 'Players'
admin.site.register(Team, TeamAdmin)
| from django.contrib import admin
from .models import Team
from nucleus.admin import TeamMemberInline
class TeamAdmin(admin.ModelAdmin):
inlines = (TeamMemberInline, )
raw_id_fields = ('captain', 'creator', )
list_display = (
'name',
'get_player_count',
'get_player_list',
'created',
'updated',
)
search_fields = ('name', )
def get_queryset(self, request):
queryset = super().get_queryset(request)
return queryset.prefetch_related('players')
def get_player_count(self, obj):
return obj.players.count()
get_player_count.short_description = 'Num Players'
def get_player_list(self, obj):
return ', '.join([p.username for p in obj.players.all()])
get_player_list.short_description = 'Players'
admin.site.register(Team, TeamAdmin)
Allow team num players column to be orderedfrom django.contrib import admin
from django.db.models import Count
from .models import Team
from nucleus.admin import TeamMemberInline
class TeamAdmin(admin.ModelAdmin):
inlines = (TeamMemberInline, )
raw_id_fields = ('captain', 'creator', )
list_display = (
'name',
'get_player_count',
'get_player_list',
'created',
'updated',
)
search_fields = ('name', )
def get_queryset(self, request):
queryset = super().get_queryset(request)
return queryset.prefetch_related('players').annotate(
player_count=Count('players')
)
def get_player_count(self, obj):
return obj.player_count
get_player_count.short_description = 'Num Players'
get_player_count.admin_order_field = 'player_count'
def get_player_list(self, obj):
return ', '.join([p.username for p in obj.players.all()])
get_player_list.short_description = 'Players'
admin.site.register(Team, TeamAdmin)
| <commit_before>from django.contrib import admin
from .models import Team
from nucleus.admin import TeamMemberInline
class TeamAdmin(admin.ModelAdmin):
inlines = (TeamMemberInline, )
raw_id_fields = ('captain', 'creator', )
list_display = (
'name',
'get_player_count',
'get_player_list',
'created',
'updated',
)
search_fields = ('name', )
def get_queryset(self, request):
queryset = super().get_queryset(request)
return queryset.prefetch_related('players')
def get_player_count(self, obj):
return obj.players.count()
get_player_count.short_description = 'Num Players'
def get_player_list(self, obj):
return ', '.join([p.username for p in obj.players.all()])
get_player_list.short_description = 'Players'
admin.site.register(Team, TeamAdmin)
<commit_msg>Allow team num players column to be ordered<commit_after>from django.contrib import admin
from django.db.models import Count
from .models import Team
from nucleus.admin import TeamMemberInline
class TeamAdmin(admin.ModelAdmin):
inlines = (TeamMemberInline, )
raw_id_fields = ('captain', 'creator', )
list_display = (
'name',
'get_player_count',
'get_player_list',
'created',
'updated',
)
search_fields = ('name', )
def get_queryset(self, request):
queryset = super().get_queryset(request)
return queryset.prefetch_related('players').annotate(
player_count=Count('players')
)
def get_player_count(self, obj):
return obj.player_count
get_player_count.short_description = 'Num Players'
get_player_count.admin_order_field = 'player_count'
def get_player_list(self, obj):
return ', '.join([p.username for p in obj.players.all()])
get_player_list.short_description = 'Players'
admin.site.register(Team, TeamAdmin)
|
a69bd95c2e732f22aac555884904bbe7d9d0a1b9 | src/dynamic_fixtures/management/commands/load_dynamic_fixtures.py | src/dynamic_fixtures/management/commands/load_dynamic_fixtures.py | from django.core.management.base import BaseCommand
from dynamic_fixtures.fixtures.runner import LoadFixtureRunner
class Command(BaseCommand):
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
def handle(self, *args, **options):
runner = LoadFixtureRunner()
nodes = None
if len(args) == 1:
nodes = runner.get_app_nodes(app_label=args[0])
elif len(args) == 2:
nodes = runner.get_fixture_node(app_label=args[0],
fixture_prefix=args[1])
fixture_count = runner.load_fixtures(
nodes=nodes,
progress_callback=self.progress_callback
)
self.stdout.write('Loaded {} fixtures'.format(fixture_count))
def progress_callback(self, action, node):
if action == 'load_start':
self.stdout.write('Loading fixture {}.{}...'.format(*node),
ending='')
self.stdout.flush()
elif action == 'load_success':
self.stdout.write('SUCCESS')
| from django.core.management.base import BaseCommand
from dynamic_fixtures.fixtures.runner import LoadFixtureRunner
class Command(BaseCommand):
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
def add_arguments(self, parser):
parser.add_argument('app_label', type=str)
parser.add_argument('fixture_name', default=None, nargs='?', type=str)
def handle(self, *args, **options):
runner = LoadFixtureRunner()
nodes = None
if len(args) == 0:
if options['fixture_name'] is None:
args = (options['app_label'], )
else:
args = (options['app_label'], options['fixture_name'])
if len(args) == 1:
nodes = runner.get_app_nodes(app_label=args[0])
elif len(args) == 2:
nodes = runner.get_fixture_node(app_label=args[0],
fixture_prefix=args[1])
fixture_count = runner.load_fixtures(
nodes=nodes,
progress_callback=self.progress_callback
)
self.stdout.write('Loaded {} fixtures'.format(fixture_count))
def progress_callback(self, action, node):
if action == 'load_start':
self.stdout.write('Loading fixture {}.{}...'.format(*node),
ending='')
self.stdout.flush()
elif action == 'load_success':
self.stdout.write('SUCCESS')
| Fix Command compatibility with Django>= 1.8 | Fix Command compatibility with Django>= 1.8
| Python | mit | Peter-Slump/django-factory-boy-fixtures,Peter-Slump/django-dynamic-fixtures | from django.core.management.base import BaseCommand
from dynamic_fixtures.fixtures.runner import LoadFixtureRunner
class Command(BaseCommand):
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
def handle(self, *args, **options):
runner = LoadFixtureRunner()
nodes = None
if len(args) == 1:
nodes = runner.get_app_nodes(app_label=args[0])
elif len(args) == 2:
nodes = runner.get_fixture_node(app_label=args[0],
fixture_prefix=args[1])
fixture_count = runner.load_fixtures(
nodes=nodes,
progress_callback=self.progress_callback
)
self.stdout.write('Loaded {} fixtures'.format(fixture_count))
def progress_callback(self, action, node):
if action == 'load_start':
self.stdout.write('Loading fixture {}.{}...'.format(*node),
ending='')
self.stdout.flush()
elif action == 'load_success':
self.stdout.write('SUCCESS')
Fix Command compatibility with Django>= 1.8 | from django.core.management.base import BaseCommand
from dynamic_fixtures.fixtures.runner import LoadFixtureRunner
class Command(BaseCommand):
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
def add_arguments(self, parser):
parser.add_argument('app_label', type=str)
parser.add_argument('fixture_name', default=None, nargs='?', type=str)
def handle(self, *args, **options):
runner = LoadFixtureRunner()
nodes = None
if len(args) == 0:
if options['fixture_name'] is None:
args = (options['app_label'], )
else:
args = (options['app_label'], options['fixture_name'])
if len(args) == 1:
nodes = runner.get_app_nodes(app_label=args[0])
elif len(args) == 2:
nodes = runner.get_fixture_node(app_label=args[0],
fixture_prefix=args[1])
fixture_count = runner.load_fixtures(
nodes=nodes,
progress_callback=self.progress_callback
)
self.stdout.write('Loaded {} fixtures'.format(fixture_count))
def progress_callback(self, action, node):
if action == 'load_start':
self.stdout.write('Loading fixture {}.{}...'.format(*node),
ending='')
self.stdout.flush()
elif action == 'load_success':
self.stdout.write('SUCCESS')
| <commit_before>from django.core.management.base import BaseCommand
from dynamic_fixtures.fixtures.runner import LoadFixtureRunner
class Command(BaseCommand):
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
def handle(self, *args, **options):
runner = LoadFixtureRunner()
nodes = None
if len(args) == 1:
nodes = runner.get_app_nodes(app_label=args[0])
elif len(args) == 2:
nodes = runner.get_fixture_node(app_label=args[0],
fixture_prefix=args[1])
fixture_count = runner.load_fixtures(
nodes=nodes,
progress_callback=self.progress_callback
)
self.stdout.write('Loaded {} fixtures'.format(fixture_count))
def progress_callback(self, action, node):
if action == 'load_start':
self.stdout.write('Loading fixture {}.{}...'.format(*node),
ending='')
self.stdout.flush()
elif action == 'load_success':
self.stdout.write('SUCCESS')
<commit_msg>Fix Command compatibility with Django>= 1.8<commit_after> | from django.core.management.base import BaseCommand
from dynamic_fixtures.fixtures.runner import LoadFixtureRunner
class Command(BaseCommand):
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
def add_arguments(self, parser):
parser.add_argument('app_label', type=str)
parser.add_argument('fixture_name', default=None, nargs='?', type=str)
def handle(self, *args, **options):
runner = LoadFixtureRunner()
nodes = None
if len(args) == 0:
if options['fixture_name'] is None:
args = (options['app_label'], )
else:
args = (options['app_label'], options['fixture_name'])
if len(args) == 1:
nodes = runner.get_app_nodes(app_label=args[0])
elif len(args) == 2:
nodes = runner.get_fixture_node(app_label=args[0],
fixture_prefix=args[1])
fixture_count = runner.load_fixtures(
nodes=nodes,
progress_callback=self.progress_callback
)
self.stdout.write('Loaded {} fixtures'.format(fixture_count))
def progress_callback(self, action, node):
if action == 'load_start':
self.stdout.write('Loading fixture {}.{}...'.format(*node),
ending='')
self.stdout.flush()
elif action == 'load_success':
self.stdout.write('SUCCESS')
| from django.core.management.base import BaseCommand
from dynamic_fixtures.fixtures.runner import LoadFixtureRunner
class Command(BaseCommand):
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
def handle(self, *args, **options):
runner = LoadFixtureRunner()
nodes = None
if len(args) == 1:
nodes = runner.get_app_nodes(app_label=args[0])
elif len(args) == 2:
nodes = runner.get_fixture_node(app_label=args[0],
fixture_prefix=args[1])
fixture_count = runner.load_fixtures(
nodes=nodes,
progress_callback=self.progress_callback
)
self.stdout.write('Loaded {} fixtures'.format(fixture_count))
def progress_callback(self, action, node):
if action == 'load_start':
self.stdout.write('Loading fixture {}.{}...'.format(*node),
ending='')
self.stdout.flush()
elif action == 'load_success':
self.stdout.write('SUCCESS')
Fix Command compatibility with Django>= 1.8from django.core.management.base import BaseCommand
from dynamic_fixtures.fixtures.runner import LoadFixtureRunner
class Command(BaseCommand):
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
def add_arguments(self, parser):
parser.add_argument('app_label', type=str)
parser.add_argument('fixture_name', default=None, nargs='?', type=str)
def handle(self, *args, **options):
runner = LoadFixtureRunner()
nodes = None
if len(args) == 0:
if options['fixture_name'] is None:
args = (options['app_label'], )
else:
args = (options['app_label'], options['fixture_name'])
if len(args) == 1:
nodes = runner.get_app_nodes(app_label=args[0])
elif len(args) == 2:
nodes = runner.get_fixture_node(app_label=args[0],
fixture_prefix=args[1])
fixture_count = runner.load_fixtures(
nodes=nodes,
progress_callback=self.progress_callback
)
self.stdout.write('Loaded {} fixtures'.format(fixture_count))
def progress_callback(self, action, node):
if action == 'load_start':
self.stdout.write('Loading fixture {}.{}...'.format(*node),
ending='')
self.stdout.flush()
elif action == 'load_success':
self.stdout.write('SUCCESS')
| <commit_before>from django.core.management.base import BaseCommand
from dynamic_fixtures.fixtures.runner import LoadFixtureRunner
class Command(BaseCommand):
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
def handle(self, *args, **options):
runner = LoadFixtureRunner()
nodes = None
if len(args) == 1:
nodes = runner.get_app_nodes(app_label=args[0])
elif len(args) == 2:
nodes = runner.get_fixture_node(app_label=args[0],
fixture_prefix=args[1])
fixture_count = runner.load_fixtures(
nodes=nodes,
progress_callback=self.progress_callback
)
self.stdout.write('Loaded {} fixtures'.format(fixture_count))
def progress_callback(self, action, node):
if action == 'load_start':
self.stdout.write('Loading fixture {}.{}...'.format(*node),
ending='')
self.stdout.flush()
elif action == 'load_success':
self.stdout.write('SUCCESS')
<commit_msg>Fix Command compatibility with Django>= 1.8<commit_after>from django.core.management.base import BaseCommand
from dynamic_fixtures.fixtures.runner import LoadFixtureRunner
class Command(BaseCommand):
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
def add_arguments(self, parser):
parser.add_argument('app_label', type=str)
parser.add_argument('fixture_name', default=None, nargs='?', type=str)
def handle(self, *args, **options):
runner = LoadFixtureRunner()
nodes = None
if len(args) == 0:
if options['fixture_name'] is None:
args = (options['app_label'], )
else:
args = (options['app_label'], options['fixture_name'])
if len(args) == 1:
nodes = runner.get_app_nodes(app_label=args[0])
elif len(args) == 2:
nodes = runner.get_fixture_node(app_label=args[0],
fixture_prefix=args[1])
fixture_count = runner.load_fixtures(
nodes=nodes,
progress_callback=self.progress_callback
)
self.stdout.write('Loaded {} fixtures'.format(fixture_count))
def progress_callback(self, action, node):
if action == 'load_start':
self.stdout.write('Loading fixture {}.{}...'.format(*node),
ending='')
self.stdout.flush()
elif action == 'load_success':
self.stdout.write('SUCCESS')
|
30ebc069634673c6a3b52c7f4285c2ce3c88472a | app/users/models.py | app/users/models.py | from datetime import datetime, timedelta
from app import db, bcrypt
from app.utils.misc import make_code
def expiration_date():
return datetime.now() + timedelta(days=1)
class User(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
is_admin = db.Column(db.Boolean())
def __init__(self, email, password, is_admin=False):
self.email = email
self.active = True
self.is_admin = is_admin
self.set_password(password)
def set_password(self, password):
self.password = bcrypt.generate_password_hash(password)
def deactivate(self):
self.active = False
class PasswordReset(db.Model):
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('user.id'))
code = db.Column(db.String(255), unique=True, default=make_code)
date = db.Column(db.DateTime(), default=expiration_date)
user = db.relationship(User)
db.UniqueConstraint('user', 'code', name='uni_user_code')
def __init__(self, user):
self.user = user
| from datetime import datetime, timedelta
from app import db, bcrypt
from app.utils.misc import make_code
def expiration_date():
return datetime.now() + timedelta(days=1)
class AppUser(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
is_admin = db.Column(db.Boolean())
def __init__(self, email, password, is_admin=False):
self.email = email
self.active = True
self.is_admin = is_admin
self.set_password(password)
def set_password(self, password):
self.password = bcrypt.generate_password_hash(password)
def deactivate(self):
self.active = False
class PasswordReset(db.Model):
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('app_user.id'))
code = db.Column(db.String(255), unique=True, default=make_code)
date = db.Column(db.DateTime(), default=expiration_date)
user = db.relationship(User)
db.UniqueConstraint('user_id', 'code', name='uni_user_code')
def __init__(self, user):
self.user = user
| Rename User model to AppUser | Rename User model to AppUser
| Python | mit | projectweekend/Flask-PostgreSQL-API-Seed | from datetime import datetime, timedelta
from app import db, bcrypt
from app.utils.misc import make_code
def expiration_date():
return datetime.now() + timedelta(days=1)
class User(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
is_admin = db.Column(db.Boolean())
def __init__(self, email, password, is_admin=False):
self.email = email
self.active = True
self.is_admin = is_admin
self.set_password(password)
def set_password(self, password):
self.password = bcrypt.generate_password_hash(password)
def deactivate(self):
self.active = False
class PasswordReset(db.Model):
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('user.id'))
code = db.Column(db.String(255), unique=True, default=make_code)
date = db.Column(db.DateTime(), default=expiration_date)
user = db.relationship(User)
db.UniqueConstraint('user', 'code', name='uni_user_code')
def __init__(self, user):
self.user = user
Rename User model to AppUser | from datetime import datetime, timedelta
from app import db, bcrypt
from app.utils.misc import make_code
def expiration_date():
return datetime.now() + timedelta(days=1)
class AppUser(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
is_admin = db.Column(db.Boolean())
def __init__(self, email, password, is_admin=False):
self.email = email
self.active = True
self.is_admin = is_admin
self.set_password(password)
def set_password(self, password):
self.password = bcrypt.generate_password_hash(password)
def deactivate(self):
self.active = False
class PasswordReset(db.Model):
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('app_user.id'))
code = db.Column(db.String(255), unique=True, default=make_code)
date = db.Column(db.DateTime(), default=expiration_date)
user = db.relationship(User)
db.UniqueConstraint('user_id', 'code', name='uni_user_code')
def __init__(self, user):
self.user = user
| <commit_before>from datetime import datetime, timedelta
from app import db, bcrypt
from app.utils.misc import make_code
def expiration_date():
return datetime.now() + timedelta(days=1)
class User(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
is_admin = db.Column(db.Boolean())
def __init__(self, email, password, is_admin=False):
self.email = email
self.active = True
self.is_admin = is_admin
self.set_password(password)
def set_password(self, password):
self.password = bcrypt.generate_password_hash(password)
def deactivate(self):
self.active = False
class PasswordReset(db.Model):
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('user.id'))
code = db.Column(db.String(255), unique=True, default=make_code)
date = db.Column(db.DateTime(), default=expiration_date)
user = db.relationship(User)
db.UniqueConstraint('user', 'code', name='uni_user_code')
def __init__(self, user):
self.user = user
<commit_msg>Rename User model to AppUser<commit_after> | from datetime import datetime, timedelta
from app import db, bcrypt
from app.utils.misc import make_code
def expiration_date():
return datetime.now() + timedelta(days=1)
class AppUser(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
is_admin = db.Column(db.Boolean())
def __init__(self, email, password, is_admin=False):
self.email = email
self.active = True
self.is_admin = is_admin
self.set_password(password)
def set_password(self, password):
self.password = bcrypt.generate_password_hash(password)
def deactivate(self):
self.active = False
class PasswordReset(db.Model):
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('app_user.id'))
code = db.Column(db.String(255), unique=True, default=make_code)
date = db.Column(db.DateTime(), default=expiration_date)
user = db.relationship(User)
db.UniqueConstraint('user_id', 'code', name='uni_user_code')
def __init__(self, user):
self.user = user
| from datetime import datetime, timedelta
from app import db, bcrypt
from app.utils.misc import make_code
def expiration_date():
return datetime.now() + timedelta(days=1)
class User(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
is_admin = db.Column(db.Boolean())
def __init__(self, email, password, is_admin=False):
self.email = email
self.active = True
self.is_admin = is_admin
self.set_password(password)
def set_password(self, password):
self.password = bcrypt.generate_password_hash(password)
def deactivate(self):
self.active = False
class PasswordReset(db.Model):
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('user.id'))
code = db.Column(db.String(255), unique=True, default=make_code)
date = db.Column(db.DateTime(), default=expiration_date)
user = db.relationship(User)
db.UniqueConstraint('user', 'code', name='uni_user_code')
def __init__(self, user):
self.user = user
Rename User model to AppUserfrom datetime import datetime, timedelta
from app import db, bcrypt
from app.utils.misc import make_code
def expiration_date():
return datetime.now() + timedelta(days=1)
class AppUser(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
is_admin = db.Column(db.Boolean())
def __init__(self, email, password, is_admin=False):
self.email = email
self.active = True
self.is_admin = is_admin
self.set_password(password)
def set_password(self, password):
self.password = bcrypt.generate_password_hash(password)
def deactivate(self):
self.active = False
class PasswordReset(db.Model):
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('app_user.id'))
code = db.Column(db.String(255), unique=True, default=make_code)
date = db.Column(db.DateTime(), default=expiration_date)
user = db.relationship(User)
db.UniqueConstraint('user_id', 'code', name='uni_user_code')
def __init__(self, user):
self.user = user
| <commit_before>from datetime import datetime, timedelta
from app import db, bcrypt
from app.utils.misc import make_code
def expiration_date():
return datetime.now() + timedelta(days=1)
class User(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
is_admin = db.Column(db.Boolean())
def __init__(self, email, password, is_admin=False):
self.email = email
self.active = True
self.is_admin = is_admin
self.set_password(password)
def set_password(self, password):
self.password = bcrypt.generate_password_hash(password)
def deactivate(self):
self.active = False
class PasswordReset(db.Model):
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('user.id'))
code = db.Column(db.String(255), unique=True, default=make_code)
date = db.Column(db.DateTime(), default=expiration_date)
user = db.relationship(User)
db.UniqueConstraint('user', 'code', name='uni_user_code')
def __init__(self, user):
self.user = user
<commit_msg>Rename User model to AppUser<commit_after>from datetime import datetime, timedelta
from app import db, bcrypt
from app.utils.misc import make_code
def expiration_date():
return datetime.now() + timedelta(days=1)
class AppUser(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
is_admin = db.Column(db.Boolean())
def __init__(self, email, password, is_admin=False):
self.email = email
self.active = True
self.is_admin = is_admin
self.set_password(password)
def set_password(self, password):
self.password = bcrypt.generate_password_hash(password)
def deactivate(self):
self.active = False
class PasswordReset(db.Model):
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('app_user.id'))
code = db.Column(db.String(255), unique=True, default=make_code)
date = db.Column(db.DateTime(), default=expiration_date)
user = db.relationship(User)
db.UniqueConstraint('user_id', 'code', name='uni_user_code')
def __init__(self, user):
self.user = user
|
2ec685b6d7469fb69e34702caa706e20f7c7e75c | jinja2_templating_for_squirrel/__init__.py | jinja2_templating_for_squirrel/__init__.py | import os.path as path
import jinja2
import helpers
logger = helpers.get_logger(__name__)
conf = helpers.get_conf()
def jinja2_templating(context):
path_to_theme = path.join(conf["path_to_themes"], conf["site_theme"])
jinja2_env = (jinja2.Environment(
loader=jinja2.FileSystemLoader(path_to_theme)))
context["path_to_theme"] = path_to_theme
context["jinja2_env"] = jinja2_env
logger.debug("Initiating templating with Jinja2 template-language...")
return context
def inject_middlewares(middlewares):
middlewares.add("jinja2_templating", jinja2_templating)
return middlewares
| import os.path as path
import jinja2
import helpers
logger = helpers.get_logger(__name__)
conf = helpers.get_conf()
def jinja2_templating(context):
args = helpers.get_args()
if args.action != "generate":
return context
path_to_theme = path.join(conf["path_to_themes"], conf["site_theme"])
jinja2_env = (jinja2.Environment(
loader=jinja2.FileSystemLoader(path_to_theme)))
context["path_to_theme"] = path_to_theme
context["jinja2_env"] = jinja2_env
logger.debug("Initiating templating with Jinja2 template-language...")
return context
def inject_middlewares(middlewares):
middlewares.add("jinja2_templating", jinja2_templating)
return middlewares
| Fix that Jinja2 templating is initiated when not needed | Fix that Jinja2 templating is initiated when not needed
| Python | mit | daGrevis/squirrel | import os.path as path
import jinja2
import helpers
logger = helpers.get_logger(__name__)
conf = helpers.get_conf()
def jinja2_templating(context):
path_to_theme = path.join(conf["path_to_themes"], conf["site_theme"])
jinja2_env = (jinja2.Environment(
loader=jinja2.FileSystemLoader(path_to_theme)))
context["path_to_theme"] = path_to_theme
context["jinja2_env"] = jinja2_env
logger.debug("Initiating templating with Jinja2 template-language...")
return context
def inject_middlewares(middlewares):
middlewares.add("jinja2_templating", jinja2_templating)
return middlewares
Fix that Jinja2 templating is initiated when not needed | import os.path as path
import jinja2
import helpers
logger = helpers.get_logger(__name__)
conf = helpers.get_conf()
def jinja2_templating(context):
args = helpers.get_args()
if args.action != "generate":
return context
path_to_theme = path.join(conf["path_to_themes"], conf["site_theme"])
jinja2_env = (jinja2.Environment(
loader=jinja2.FileSystemLoader(path_to_theme)))
context["path_to_theme"] = path_to_theme
context["jinja2_env"] = jinja2_env
logger.debug("Initiating templating with Jinja2 template-language...")
return context
def inject_middlewares(middlewares):
middlewares.add("jinja2_templating", jinja2_templating)
return middlewares
| <commit_before>import os.path as path
import jinja2
import helpers
logger = helpers.get_logger(__name__)
conf = helpers.get_conf()
def jinja2_templating(context):
path_to_theme = path.join(conf["path_to_themes"], conf["site_theme"])
jinja2_env = (jinja2.Environment(
loader=jinja2.FileSystemLoader(path_to_theme)))
context["path_to_theme"] = path_to_theme
context["jinja2_env"] = jinja2_env
logger.debug("Initiating templating with Jinja2 template-language...")
return context
def inject_middlewares(middlewares):
middlewares.add("jinja2_templating", jinja2_templating)
return middlewares
<commit_msg>Fix that Jinja2 templating is initiated when not needed<commit_after> | import os.path as path
import jinja2
import helpers
logger = helpers.get_logger(__name__)
conf = helpers.get_conf()
def jinja2_templating(context):
args = helpers.get_args()
if args.action != "generate":
return context
path_to_theme = path.join(conf["path_to_themes"], conf["site_theme"])
jinja2_env = (jinja2.Environment(
loader=jinja2.FileSystemLoader(path_to_theme)))
context["path_to_theme"] = path_to_theme
context["jinja2_env"] = jinja2_env
logger.debug("Initiating templating with Jinja2 template-language...")
return context
def inject_middlewares(middlewares):
middlewares.add("jinja2_templating", jinja2_templating)
return middlewares
| import os.path as path
import jinja2
import helpers
logger = helpers.get_logger(__name__)
conf = helpers.get_conf()
def jinja2_templating(context):
path_to_theme = path.join(conf["path_to_themes"], conf["site_theme"])
jinja2_env = (jinja2.Environment(
loader=jinja2.FileSystemLoader(path_to_theme)))
context["path_to_theme"] = path_to_theme
context["jinja2_env"] = jinja2_env
logger.debug("Initiating templating with Jinja2 template-language...")
return context
def inject_middlewares(middlewares):
middlewares.add("jinja2_templating", jinja2_templating)
return middlewares
Fix that Jinja2 templating is initiated when not neededimport os.path as path
import jinja2
import helpers
logger = helpers.get_logger(__name__)
conf = helpers.get_conf()
def jinja2_templating(context):
args = helpers.get_args()
if args.action != "generate":
return context
path_to_theme = path.join(conf["path_to_themes"], conf["site_theme"])
jinja2_env = (jinja2.Environment(
loader=jinja2.FileSystemLoader(path_to_theme)))
context["path_to_theme"] = path_to_theme
context["jinja2_env"] = jinja2_env
logger.debug("Initiating templating with Jinja2 template-language...")
return context
def inject_middlewares(middlewares):
middlewares.add("jinja2_templating", jinja2_templating)
return middlewares
| <commit_before>import os.path as path
import jinja2
import helpers
logger = helpers.get_logger(__name__)
conf = helpers.get_conf()
def jinja2_templating(context):
path_to_theme = path.join(conf["path_to_themes"], conf["site_theme"])
jinja2_env = (jinja2.Environment(
loader=jinja2.FileSystemLoader(path_to_theme)))
context["path_to_theme"] = path_to_theme
context["jinja2_env"] = jinja2_env
logger.debug("Initiating templating with Jinja2 template-language...")
return context
def inject_middlewares(middlewares):
middlewares.add("jinja2_templating", jinja2_templating)
return middlewares
<commit_msg>Fix that Jinja2 templating is initiated when not needed<commit_after>import os.path as path
import jinja2
import helpers
logger = helpers.get_logger(__name__)
conf = helpers.get_conf()
def jinja2_templating(context):
args = helpers.get_args()
if args.action != "generate":
return context
path_to_theme = path.join(conf["path_to_themes"], conf["site_theme"])
jinja2_env = (jinja2.Environment(
loader=jinja2.FileSystemLoader(path_to_theme)))
context["path_to_theme"] = path_to_theme
context["jinja2_env"] = jinja2_env
logger.debug("Initiating templating with Jinja2 template-language...")
return context
def inject_middlewares(middlewares):
middlewares.add("jinja2_templating", jinja2_templating)
return middlewares
|
c6229fc20f8bb37d185f90b032c0dc3817834256 | linguist/mixins.py | linguist/mixins.py | # -*- coding: utf-8 -*-
from .models import Translation
from .utils import get_cache_key
class LinguistMixin(object):
def clear_translations_cache(self):
self._linguist.clear()
@property
def language(self):
return self._linguist.language
@language.setter
def language(self, value):
self._linguist.language = value
def get_available_languages(self):
identifier = self._linguist.identifier
return (Translation.objects
.filter(identifier=identifier, object_id=self.pk)
.values_list('language', flat=True)
.distinct()
.order_by('language'))
def prefetch_translations(self):
identifier = self._linguist.identifier
translations = Translation.objects.filter(identifier=identifier, object_id=self.pk)
for translation in translations:
cache_key = get_cache_key(**{
'identifier': identifier,
'object_id': self.pk,
'language': translation.language,
'field_name': translation.field_name,
})
if cache_key not in self._linguist:
self._linguist[cache_key] = translation
| # -*- coding: utf-8 -*-
from .models import Translation
from .utils.i18n import get_cache_key
class LinguistMixin(object):
def clear_translations_cache(self):
self._linguist.clear()
@property
def identifier(self):
return self._linguist.identifier
@property
def language(self):
return self._linguist.language
@language.setter
def language(self, value):
self._linguist.language = value
def get_available_languages(self):
identifier = self._linguist.identifier
return (Translation.objects
.filter(identifier=identifier, object_id=self.pk)
.values_list('language', flat=True)
.distinct()
.order_by('language'))
def prefetch_translations(self):
identifier = self._linguist.identifier
translations = Translation.objects.filter(identifier=identifier, object_id=self.pk)
for translation in translations:
cache_key = get_cache_key(**{
'identifier': identifier,
'object_id': self.pk,
'language': translation.language,
'field_name': translation.field_name,
})
if cache_key not in self._linguist:
self._linguist[cache_key] = translation
| Add identifier property to mixin. | Add identifier property to mixin.
| Python | mit | ulule/django-linguist | # -*- coding: utf-8 -*-
from .models import Translation
from .utils import get_cache_key
class LinguistMixin(object):
def clear_translations_cache(self):
self._linguist.clear()
@property
def language(self):
return self._linguist.language
@language.setter
def language(self, value):
self._linguist.language = value
def get_available_languages(self):
identifier = self._linguist.identifier
return (Translation.objects
.filter(identifier=identifier, object_id=self.pk)
.values_list('language', flat=True)
.distinct()
.order_by('language'))
def prefetch_translations(self):
identifier = self._linguist.identifier
translations = Translation.objects.filter(identifier=identifier, object_id=self.pk)
for translation in translations:
cache_key = get_cache_key(**{
'identifier': identifier,
'object_id': self.pk,
'language': translation.language,
'field_name': translation.field_name,
})
if cache_key not in self._linguist:
self._linguist[cache_key] = translation
Add identifier property to mixin. | # -*- coding: utf-8 -*-
from .models import Translation
from .utils.i18n import get_cache_key
class LinguistMixin(object):
def clear_translations_cache(self):
self._linguist.clear()
@property
def identifier(self):
return self._linguist.identifier
@property
def language(self):
return self._linguist.language
@language.setter
def language(self, value):
self._linguist.language = value
def get_available_languages(self):
identifier = self._linguist.identifier
return (Translation.objects
.filter(identifier=identifier, object_id=self.pk)
.values_list('language', flat=True)
.distinct()
.order_by('language'))
def prefetch_translations(self):
identifier = self._linguist.identifier
translations = Translation.objects.filter(identifier=identifier, object_id=self.pk)
for translation in translations:
cache_key = get_cache_key(**{
'identifier': identifier,
'object_id': self.pk,
'language': translation.language,
'field_name': translation.field_name,
})
if cache_key not in self._linguist:
self._linguist[cache_key] = translation
| <commit_before># -*- coding: utf-8 -*-
from .models import Translation
from .utils import get_cache_key
class LinguistMixin(object):
def clear_translations_cache(self):
self._linguist.clear()
@property
def language(self):
return self._linguist.language
@language.setter
def language(self, value):
self._linguist.language = value
def get_available_languages(self):
identifier = self._linguist.identifier
return (Translation.objects
.filter(identifier=identifier, object_id=self.pk)
.values_list('language', flat=True)
.distinct()
.order_by('language'))
def prefetch_translations(self):
identifier = self._linguist.identifier
translations = Translation.objects.filter(identifier=identifier, object_id=self.pk)
for translation in translations:
cache_key = get_cache_key(**{
'identifier': identifier,
'object_id': self.pk,
'language': translation.language,
'field_name': translation.field_name,
})
if cache_key not in self._linguist:
self._linguist[cache_key] = translation
<commit_msg>Add identifier property to mixin.<commit_after> | # -*- coding: utf-8 -*-
from .models import Translation
from .utils.i18n import get_cache_key
class LinguistMixin(object):
def clear_translations_cache(self):
self._linguist.clear()
@property
def identifier(self):
return self._linguist.identifier
@property
def language(self):
return self._linguist.language
@language.setter
def language(self, value):
self._linguist.language = value
def get_available_languages(self):
identifier = self._linguist.identifier
return (Translation.objects
.filter(identifier=identifier, object_id=self.pk)
.values_list('language', flat=True)
.distinct()
.order_by('language'))
def prefetch_translations(self):
identifier = self._linguist.identifier
translations = Translation.objects.filter(identifier=identifier, object_id=self.pk)
for translation in translations:
cache_key = get_cache_key(**{
'identifier': identifier,
'object_id': self.pk,
'language': translation.language,
'field_name': translation.field_name,
})
if cache_key not in self._linguist:
self._linguist[cache_key] = translation
| # -*- coding: utf-8 -*-
from .models import Translation
from .utils import get_cache_key
class LinguistMixin(object):
def clear_translations_cache(self):
self._linguist.clear()
@property
def language(self):
return self._linguist.language
@language.setter
def language(self, value):
self._linguist.language = value
def get_available_languages(self):
identifier = self._linguist.identifier
return (Translation.objects
.filter(identifier=identifier, object_id=self.pk)
.values_list('language', flat=True)
.distinct()
.order_by('language'))
def prefetch_translations(self):
identifier = self._linguist.identifier
translations = Translation.objects.filter(identifier=identifier, object_id=self.pk)
for translation in translations:
cache_key = get_cache_key(**{
'identifier': identifier,
'object_id': self.pk,
'language': translation.language,
'field_name': translation.field_name,
})
if cache_key not in self._linguist:
self._linguist[cache_key] = translation
Add identifier property to mixin.# -*- coding: utf-8 -*-
from .models import Translation
from .utils.i18n import get_cache_key
class LinguistMixin(object):
def clear_translations_cache(self):
self._linguist.clear()
@property
def identifier(self):
return self._linguist.identifier
@property
def language(self):
return self._linguist.language
@language.setter
def language(self, value):
self._linguist.language = value
def get_available_languages(self):
identifier = self._linguist.identifier
return (Translation.objects
.filter(identifier=identifier, object_id=self.pk)
.values_list('language', flat=True)
.distinct()
.order_by('language'))
def prefetch_translations(self):
identifier = self._linguist.identifier
translations = Translation.objects.filter(identifier=identifier, object_id=self.pk)
for translation in translations:
cache_key = get_cache_key(**{
'identifier': identifier,
'object_id': self.pk,
'language': translation.language,
'field_name': translation.field_name,
})
if cache_key not in self._linguist:
self._linguist[cache_key] = translation
| <commit_before># -*- coding: utf-8 -*-
from .models import Translation
from .utils import get_cache_key
class LinguistMixin(object):
def clear_translations_cache(self):
self._linguist.clear()
@property
def language(self):
return self._linguist.language
@language.setter
def language(self, value):
self._linguist.language = value
def get_available_languages(self):
identifier = self._linguist.identifier
return (Translation.objects
.filter(identifier=identifier, object_id=self.pk)
.values_list('language', flat=True)
.distinct()
.order_by('language'))
def prefetch_translations(self):
identifier = self._linguist.identifier
translations = Translation.objects.filter(identifier=identifier, object_id=self.pk)
for translation in translations:
cache_key = get_cache_key(**{
'identifier': identifier,
'object_id': self.pk,
'language': translation.language,
'field_name': translation.field_name,
})
if cache_key not in self._linguist:
self._linguist[cache_key] = translation
<commit_msg>Add identifier property to mixin.<commit_after># -*- coding: utf-8 -*-
from .models import Translation
from .utils.i18n import get_cache_key
class LinguistMixin(object):
def clear_translations_cache(self):
self._linguist.clear()
@property
def identifier(self):
return self._linguist.identifier
@property
def language(self):
return self._linguist.language
@language.setter
def language(self, value):
self._linguist.language = value
def get_available_languages(self):
identifier = self._linguist.identifier
return (Translation.objects
.filter(identifier=identifier, object_id=self.pk)
.values_list('language', flat=True)
.distinct()
.order_by('language'))
def prefetch_translations(self):
identifier = self._linguist.identifier
translations = Translation.objects.filter(identifier=identifier, object_id=self.pk)
for translation in translations:
cache_key = get_cache_key(**{
'identifier': identifier,
'object_id': self.pk,
'language': translation.language,
'field_name': translation.field_name,
})
if cache_key not in self._linguist:
self._linguist[cache_key] = translation
|
8b5cfb11235d419d729a69a638a39489322fe547 | api/provider.py | api/provider.py | """
atmosphere service provider rest api.
"""
from rest_framework.views import APIView
from rest_framework.response import Response
from authentication.decorators import api_auth_token_required
from core.models.group import Group
from api.serializers import ProviderSerializer
class ProviderList(APIView):
"""
List of active providers
"""
@api_auth_token_required
def get(self, request):
"""
List all providers accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
providers = group.providers.filter(active=True,
end_date=None).order_by('id')
#providers = CoreProvider.objects.order_by('id')
serialized_data = ProviderSerializer(providers, many=True).data
return Response(serialized_data)
class Provider(APIView):
"""
Show single provider
"""
@api_auth_token_required
def get(self, request, provider_id):
"""
return provider if accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
provider = group.providers.get(id=provider_id,
active=True, end_date=None)
serialized_data = ProviderSerializer(provider).data
return Response(serialized_data)
| """
atmosphere service provider rest api.
"""
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from authentication.decorators import api_auth_token_required
from core.models.group import Group
from core.models.provider import Provider as CoreProvider
from api import failureJSON
from api.serializers import ProviderSerializer
class ProviderList(APIView):
"""
List of active providers
"""
@api_auth_token_required
def get(self, request):
"""
List all providers accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
try:
providers = group.providers.filter(active=True,
end_date=None).order_by('id')
except CoreProvider.DoesNotExist:
errorObj = failureJSON([{
'code': 404,
'message':
'The provider does not exist.'}])
return Response(errorObj, status=status.HTTP_404_NOT_FOUND)
serialized_data = ProviderSerializer(providers, many=True).data
return Response(serialized_data)
class Provider(APIView):
"""
Show single provider
"""
@api_auth_token_required
def get(self, request, provider_id):
"""
return provider if accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
try:
provider = group.providers.get(id=provider_id,
active=True, end_date=None)
except CoreProvider.DoesNotExist:
errorObj = failureJSON([{
'code': 404,
'message':
'The provider does not exist.'}])
return Response(errorObj, status=status.HTTP_404_NOT_FOUND)
serialized_data = ProviderSerializer(provider).data
return Response(serialized_data)
| Fix problem where Provider DoesNotExist. | Fix problem where Provider DoesNotExist.
* Occurs on provider and providerlist endpoints.
* Came to attention as a side effect of fixing ATMO-176.
* Similar changes need to be made all over atmosphere. I'll
create a ticket.
modified: api/provider.py
| Python | apache-2.0 | CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend | """
atmosphere service provider rest api.
"""
from rest_framework.views import APIView
from rest_framework.response import Response
from authentication.decorators import api_auth_token_required
from core.models.group import Group
from api.serializers import ProviderSerializer
class ProviderList(APIView):
"""
List of active providers
"""
@api_auth_token_required
def get(self, request):
"""
List all providers accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
providers = group.providers.filter(active=True,
end_date=None).order_by('id')
#providers = CoreProvider.objects.order_by('id')
serialized_data = ProviderSerializer(providers, many=True).data
return Response(serialized_data)
class Provider(APIView):
"""
Show single provider
"""
@api_auth_token_required
def get(self, request, provider_id):
"""
return provider if accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
provider = group.providers.get(id=provider_id,
active=True, end_date=None)
serialized_data = ProviderSerializer(provider).data
return Response(serialized_data)
Fix problem where Provider DoesNotExist.
* Occurs on provider and providerlist endpoints.
* Came to attention as a side effect of fixing ATMO-176.
* Similar changes need to be made all over atmosphere. I'll
create a ticket.
modified: api/provider.py | """
atmosphere service provider rest api.
"""
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from authentication.decorators import api_auth_token_required
from core.models.group import Group
from core.models.provider import Provider as CoreProvider
from api import failureJSON
from api.serializers import ProviderSerializer
class ProviderList(APIView):
"""
List of active providers
"""
@api_auth_token_required
def get(self, request):
"""
List all providers accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
try:
providers = group.providers.filter(active=True,
end_date=None).order_by('id')
except CoreProvider.DoesNotExist:
errorObj = failureJSON([{
'code': 404,
'message':
'The provider does not exist.'}])
return Response(errorObj, status=status.HTTP_404_NOT_FOUND)
serialized_data = ProviderSerializer(providers, many=True).data
return Response(serialized_data)
class Provider(APIView):
"""
Show single provider
"""
@api_auth_token_required
def get(self, request, provider_id):
"""
return provider if accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
try:
provider = group.providers.get(id=provider_id,
active=True, end_date=None)
except CoreProvider.DoesNotExist:
errorObj = failureJSON([{
'code': 404,
'message':
'The provider does not exist.'}])
return Response(errorObj, status=status.HTTP_404_NOT_FOUND)
serialized_data = ProviderSerializer(provider).data
return Response(serialized_data)
| <commit_before>"""
atmosphere service provider rest api.
"""
from rest_framework.views import APIView
from rest_framework.response import Response
from authentication.decorators import api_auth_token_required
from core.models.group import Group
from api.serializers import ProviderSerializer
class ProviderList(APIView):
"""
List of active providers
"""
@api_auth_token_required
def get(self, request):
"""
List all providers accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
providers = group.providers.filter(active=True,
end_date=None).order_by('id')
#providers = CoreProvider.objects.order_by('id')
serialized_data = ProviderSerializer(providers, many=True).data
return Response(serialized_data)
class Provider(APIView):
"""
Show single provider
"""
@api_auth_token_required
def get(self, request, provider_id):
"""
return provider if accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
provider = group.providers.get(id=provider_id,
active=True, end_date=None)
serialized_data = ProviderSerializer(provider).data
return Response(serialized_data)
<commit_msg>Fix problem where Provider DoesNotExist.
* Occurs on provider and providerlist endpoints.
* Came to attention as a side effect of fixing ATMO-176.
* Similar changes need to be made all over atmosphere. I'll
create a ticket.
modified: api/provider.py<commit_after> | """
atmosphere service provider rest api.
"""
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from authentication.decorators import api_auth_token_required
from core.models.group import Group
from core.models.provider import Provider as CoreProvider
from api import failureJSON
from api.serializers import ProviderSerializer
class ProviderList(APIView):
"""
List of active providers
"""
@api_auth_token_required
def get(self, request):
"""
List all providers accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
try:
providers = group.providers.filter(active=True,
end_date=None).order_by('id')
except CoreProvider.DoesNotExist:
errorObj = failureJSON([{
'code': 404,
'message':
'The provider does not exist.'}])
return Response(errorObj, status=status.HTTP_404_NOT_FOUND)
serialized_data = ProviderSerializer(providers, many=True).data
return Response(serialized_data)
class Provider(APIView):
"""
Show single provider
"""
@api_auth_token_required
def get(self, request, provider_id):
"""
return provider if accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
try:
provider = group.providers.get(id=provider_id,
active=True, end_date=None)
except CoreProvider.DoesNotExist:
errorObj = failureJSON([{
'code': 404,
'message':
'The provider does not exist.'}])
return Response(errorObj, status=status.HTTP_404_NOT_FOUND)
serialized_data = ProviderSerializer(provider).data
return Response(serialized_data)
| """
atmosphere service provider rest api.
"""
from rest_framework.views import APIView
from rest_framework.response import Response
from authentication.decorators import api_auth_token_required
from core.models.group import Group
from api.serializers import ProviderSerializer
class ProviderList(APIView):
"""
List of active providers
"""
@api_auth_token_required
def get(self, request):
"""
List all providers accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
providers = group.providers.filter(active=True,
end_date=None).order_by('id')
#providers = CoreProvider.objects.order_by('id')
serialized_data = ProviderSerializer(providers, many=True).data
return Response(serialized_data)
class Provider(APIView):
"""
Show single provider
"""
@api_auth_token_required
def get(self, request, provider_id):
"""
return provider if accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
provider = group.providers.get(id=provider_id,
active=True, end_date=None)
serialized_data = ProviderSerializer(provider).data
return Response(serialized_data)
Fix problem where Provider DoesNotExist.
* Occurs on provider and providerlist endpoints.
* Came to attention as a side effect of fixing ATMO-176.
* Similar changes need to be made all over atmosphere. I'll
create a ticket.
modified: api/provider.py"""
atmosphere service provider rest api.
"""
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from authentication.decorators import api_auth_token_required
from core.models.group import Group
from core.models.provider import Provider as CoreProvider
from api import failureJSON
from api.serializers import ProviderSerializer
class ProviderList(APIView):
"""
List of active providers
"""
@api_auth_token_required
def get(self, request):
"""
List all providers accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
try:
providers = group.providers.filter(active=True,
end_date=None).order_by('id')
except CoreProvider.DoesNotExist:
errorObj = failureJSON([{
'code': 404,
'message':
'The provider does not exist.'}])
return Response(errorObj, status=status.HTTP_404_NOT_FOUND)
serialized_data = ProviderSerializer(providers, many=True).data
return Response(serialized_data)
class Provider(APIView):
"""
Show single provider
"""
@api_auth_token_required
def get(self, request, provider_id):
"""
return provider if accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
try:
provider = group.providers.get(id=provider_id,
active=True, end_date=None)
except CoreProvider.DoesNotExist:
errorObj = failureJSON([{
'code': 404,
'message':
'The provider does not exist.'}])
return Response(errorObj, status=status.HTTP_404_NOT_FOUND)
serialized_data = ProviderSerializer(provider).data
return Response(serialized_data)
| <commit_before>"""
atmosphere service provider rest api.
"""
from rest_framework.views import APIView
from rest_framework.response import Response
from authentication.decorators import api_auth_token_required
from core.models.group import Group
from api.serializers import ProviderSerializer
class ProviderList(APIView):
"""
List of active providers
"""
@api_auth_token_required
def get(self, request):
"""
List all providers accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
providers = group.providers.filter(active=True,
end_date=None).order_by('id')
#providers = CoreProvider.objects.order_by('id')
serialized_data = ProviderSerializer(providers, many=True).data
return Response(serialized_data)
class Provider(APIView):
"""
Show single provider
"""
@api_auth_token_required
def get(self, request, provider_id):
"""
return provider if accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
provider = group.providers.get(id=provider_id,
active=True, end_date=None)
serialized_data = ProviderSerializer(provider).data
return Response(serialized_data)
<commit_msg>Fix problem where Provider DoesNotExist.
* Occurs on provider and providerlist endpoints.
* Came to attention as a side effect of fixing ATMO-176.
* Similar changes need to be made all over atmosphere. I'll
create a ticket.
modified: api/provider.py<commit_after>"""
atmosphere service provider rest api.
"""
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from authentication.decorators import api_auth_token_required
from core.models.group import Group
from core.models.provider import Provider as CoreProvider
from api import failureJSON
from api.serializers import ProviderSerializer
class ProviderList(APIView):
"""
List of active providers
"""
@api_auth_token_required
def get(self, request):
"""
List all providers accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
try:
providers = group.providers.filter(active=True,
end_date=None).order_by('id')
except CoreProvider.DoesNotExist:
errorObj = failureJSON([{
'code': 404,
'message':
'The provider does not exist.'}])
return Response(errorObj, status=status.HTTP_404_NOT_FOUND)
serialized_data = ProviderSerializer(providers, many=True).data
return Response(serialized_data)
class Provider(APIView):
"""
Show single provider
"""
@api_auth_token_required
def get(self, request, provider_id):
"""
return provider if accessible by request user
"""
username = request.user.username
group = Group.objects.get(name=username)
try:
provider = group.providers.get(id=provider_id,
active=True, end_date=None)
except CoreProvider.DoesNotExist:
errorObj = failureJSON([{
'code': 404,
'message':
'The provider does not exist.'}])
return Response(errorObj, status=status.HTTP_404_NOT_FOUND)
serialized_data = ProviderSerializer(provider).data
return Response(serialized_data)
|
a512af54d5c843aa8f232a73dcfe79870341a8db | ppadb/command/transport_async/__init__.py | ppadb/command/transport_async/__init__.py | import logging
import re
import time
class TransportAsync:
async def transport(self, connection):
cmd = "host:transport:{}".format(self.serial)
await connection.send(cmd)
return connection
async def shell(self, cmd, timeout=None):
conn = await self.create_connection(timeout=timeout)
cmd = "shell:{}".format(cmd)
await conn.send(cmd)
result = await conn.read_all()
await conn.close()
return result.decode('utf-8')
async def sync(self):
conn = await self.create_connection()
cmd = "sync:"
await conn.send(cmd)
return conn
async def screencap(self):
async with await self.create_connection() as conn:
cmd = "shell:/system/bin/screencap -p"
await conn.send(cmd)
result = await conn.read_all()
if result[5] == 0x0d:
return result.replace(b'\r\n', b'\n')
else:
return result
| import logging
import re
import time
class TransportAsync:
async def transport(self, connection):
cmd = "host:transport:{}".format(self.serial)
await connection.send(cmd)
return connection
async def shell(self, cmd, timeout=None):
conn = await self.create_connection(timeout=timeout)
cmd = "shell:{}".format(cmd)
await conn.send(cmd)
result = await conn.read_all()
await conn.close()
return result.decode('utf-8')
async def sync(self):
conn = await self.create_connection()
cmd = "sync:"
await conn.send(cmd)
return conn
async def screencap(self):
async with await self.create_connection() as conn:
cmd = "shell:/system/bin/screencap -p"
await conn.send(cmd)
result = await conn.read_all()
if result and len(result) > 5 and result[5] == 0x0d:
return result.replace(b'\r\n', b'\n')
else:
return result
| Check the length of the screencap before indexing into it | Check the length of the screencap before indexing into it
| Python | mit | Swind/pure-python-adb,Swind/pure-python-adb | import logging
import re
import time
class TransportAsync:
async def transport(self, connection):
cmd = "host:transport:{}".format(self.serial)
await connection.send(cmd)
return connection
async def shell(self, cmd, timeout=None):
conn = await self.create_connection(timeout=timeout)
cmd = "shell:{}".format(cmd)
await conn.send(cmd)
result = await conn.read_all()
await conn.close()
return result.decode('utf-8')
async def sync(self):
conn = await self.create_connection()
cmd = "sync:"
await conn.send(cmd)
return conn
async def screencap(self):
async with await self.create_connection() as conn:
cmd = "shell:/system/bin/screencap -p"
await conn.send(cmd)
result = await conn.read_all()
if result[5] == 0x0d:
return result.replace(b'\r\n', b'\n')
else:
return result
Check the length of the screencap before indexing into it | import logging
import re
import time
class TransportAsync:
async def transport(self, connection):
cmd = "host:transport:{}".format(self.serial)
await connection.send(cmd)
return connection
async def shell(self, cmd, timeout=None):
conn = await self.create_connection(timeout=timeout)
cmd = "shell:{}".format(cmd)
await conn.send(cmd)
result = await conn.read_all()
await conn.close()
return result.decode('utf-8')
async def sync(self):
conn = await self.create_connection()
cmd = "sync:"
await conn.send(cmd)
return conn
async def screencap(self):
async with await self.create_connection() as conn:
cmd = "shell:/system/bin/screencap -p"
await conn.send(cmd)
result = await conn.read_all()
if result and len(result) > 5 and result[5] == 0x0d:
return result.replace(b'\r\n', b'\n')
else:
return result
| <commit_before>import logging
import re
import time
class TransportAsync:
async def transport(self, connection):
cmd = "host:transport:{}".format(self.serial)
await connection.send(cmd)
return connection
async def shell(self, cmd, timeout=None):
conn = await self.create_connection(timeout=timeout)
cmd = "shell:{}".format(cmd)
await conn.send(cmd)
result = await conn.read_all()
await conn.close()
return result.decode('utf-8')
async def sync(self):
conn = await self.create_connection()
cmd = "sync:"
await conn.send(cmd)
return conn
async def screencap(self):
async with await self.create_connection() as conn:
cmd = "shell:/system/bin/screencap -p"
await conn.send(cmd)
result = await conn.read_all()
if result[5] == 0x0d:
return result.replace(b'\r\n', b'\n')
else:
return result
<commit_msg>Check the length of the screencap before indexing into it<commit_after> | import logging
import re
import time
class TransportAsync:
async def transport(self, connection):
cmd = "host:transport:{}".format(self.serial)
await connection.send(cmd)
return connection
async def shell(self, cmd, timeout=None):
conn = await self.create_connection(timeout=timeout)
cmd = "shell:{}".format(cmd)
await conn.send(cmd)
result = await conn.read_all()
await conn.close()
return result.decode('utf-8')
async def sync(self):
conn = await self.create_connection()
cmd = "sync:"
await conn.send(cmd)
return conn
async def screencap(self):
async with await self.create_connection() as conn:
cmd = "shell:/system/bin/screencap -p"
await conn.send(cmd)
result = await conn.read_all()
if result and len(result) > 5 and result[5] == 0x0d:
return result.replace(b'\r\n', b'\n')
else:
return result
| import logging
import re
import time
class TransportAsync:
async def transport(self, connection):
cmd = "host:transport:{}".format(self.serial)
await connection.send(cmd)
return connection
async def shell(self, cmd, timeout=None):
conn = await self.create_connection(timeout=timeout)
cmd = "shell:{}".format(cmd)
await conn.send(cmd)
result = await conn.read_all()
await conn.close()
return result.decode('utf-8')
async def sync(self):
conn = await self.create_connection()
cmd = "sync:"
await conn.send(cmd)
return conn
async def screencap(self):
async with await self.create_connection() as conn:
cmd = "shell:/system/bin/screencap -p"
await conn.send(cmd)
result = await conn.read_all()
if result[5] == 0x0d:
return result.replace(b'\r\n', b'\n')
else:
return result
Check the length of the screencap before indexing into itimport logging
import re
import time
class TransportAsync:
async def transport(self, connection):
cmd = "host:transport:{}".format(self.serial)
await connection.send(cmd)
return connection
async def shell(self, cmd, timeout=None):
conn = await self.create_connection(timeout=timeout)
cmd = "shell:{}".format(cmd)
await conn.send(cmd)
result = await conn.read_all()
await conn.close()
return result.decode('utf-8')
async def sync(self):
conn = await self.create_connection()
cmd = "sync:"
await conn.send(cmd)
return conn
async def screencap(self):
async with await self.create_connection() as conn:
cmd = "shell:/system/bin/screencap -p"
await conn.send(cmd)
result = await conn.read_all()
if result and len(result) > 5 and result[5] == 0x0d:
return result.replace(b'\r\n', b'\n')
else:
return result
| <commit_before>import logging
import re
import time
class TransportAsync:
async def transport(self, connection):
cmd = "host:transport:{}".format(self.serial)
await connection.send(cmd)
return connection
async def shell(self, cmd, timeout=None):
conn = await self.create_connection(timeout=timeout)
cmd = "shell:{}".format(cmd)
await conn.send(cmd)
result = await conn.read_all()
await conn.close()
return result.decode('utf-8')
async def sync(self):
conn = await self.create_connection()
cmd = "sync:"
await conn.send(cmd)
return conn
async def screencap(self):
async with await self.create_connection() as conn:
cmd = "shell:/system/bin/screencap -p"
await conn.send(cmd)
result = await conn.read_all()
if result[5] == 0x0d:
return result.replace(b'\r\n', b'\n')
else:
return result
<commit_msg>Check the length of the screencap before indexing into it<commit_after>import logging
import re
import time
class TransportAsync:
async def transport(self, connection):
cmd = "host:transport:{}".format(self.serial)
await connection.send(cmd)
return connection
async def shell(self, cmd, timeout=None):
conn = await self.create_connection(timeout=timeout)
cmd = "shell:{}".format(cmd)
await conn.send(cmd)
result = await conn.read_all()
await conn.close()
return result.decode('utf-8')
async def sync(self):
conn = await self.create_connection()
cmd = "sync:"
await conn.send(cmd)
return conn
async def screencap(self):
async with await self.create_connection() as conn:
cmd = "shell:/system/bin/screencap -p"
await conn.send(cmd)
result = await conn.read_all()
if result and len(result) > 5 and result[5] == 0x0d:
return result.replace(b'\r\n', b'\n')
else:
return result
|
92a5d02b3e052fb0536e51aba043ff2f026c6484 | appengine_config.py | appengine_config.py | import logging
def appstats_should_record(env):
from gae_mini_profiler.config import should_profile
if should_profile():
return True
def gae_mini_profiler_should_profile_production():
from google.appengine.api import users
return users.is_current_user_admin()
def gae_mini_profiler_should_profile_development():
from google.appengine.api import users
return users.is_current_user_admin()
| import logging
def appstats_should_record(env):
#from gae_mini_profiler.config import should_profile
#if should_profile():
# return True
return False
def gae_mini_profiler_should_profile_production():
from google.appengine.api import users
return users.is_current_user_admin()
def gae_mini_profiler_should_profile_development():
from google.appengine.api import users
return users.is_current_user_admin()
| Disable GAE mini profiler by default | Disable GAE mini profiler by default
| Python | mit | bbondy/brianbondy.gae,bbondy/brianbondy.gae,bbondy/brianbondy.gae,bbondy/brianbondy.gae | import logging
def appstats_should_record(env):
from gae_mini_profiler.config import should_profile
if should_profile():
return True
def gae_mini_profiler_should_profile_production():
from google.appengine.api import users
return users.is_current_user_admin()
def gae_mini_profiler_should_profile_development():
from google.appengine.api import users
return users.is_current_user_admin()
Disable GAE mini profiler by default | import logging
def appstats_should_record(env):
#from gae_mini_profiler.config import should_profile
#if should_profile():
# return True
return False
def gae_mini_profiler_should_profile_production():
from google.appengine.api import users
return users.is_current_user_admin()
def gae_mini_profiler_should_profile_development():
from google.appengine.api import users
return users.is_current_user_admin()
| <commit_before>import logging
def appstats_should_record(env):
from gae_mini_profiler.config import should_profile
if should_profile():
return True
def gae_mini_profiler_should_profile_production():
from google.appengine.api import users
return users.is_current_user_admin()
def gae_mini_profiler_should_profile_development():
from google.appengine.api import users
return users.is_current_user_admin()
<commit_msg>Disable GAE mini profiler by default<commit_after> | import logging
def appstats_should_record(env):
#from gae_mini_profiler.config import should_profile
#if should_profile():
# return True
return False
def gae_mini_profiler_should_profile_production():
from google.appengine.api import users
return users.is_current_user_admin()
def gae_mini_profiler_should_profile_development():
from google.appengine.api import users
return users.is_current_user_admin()
| import logging
def appstats_should_record(env):
from gae_mini_profiler.config import should_profile
if should_profile():
return True
def gae_mini_profiler_should_profile_production():
from google.appengine.api import users
return users.is_current_user_admin()
def gae_mini_profiler_should_profile_development():
from google.appengine.api import users
return users.is_current_user_admin()
Disable GAE mini profiler by defaultimport logging
def appstats_should_record(env):
#from gae_mini_profiler.config import should_profile
#if should_profile():
# return True
return False
def gae_mini_profiler_should_profile_production():
from google.appengine.api import users
return users.is_current_user_admin()
def gae_mini_profiler_should_profile_development():
from google.appengine.api import users
return users.is_current_user_admin()
| <commit_before>import logging
def appstats_should_record(env):
from gae_mini_profiler.config import should_profile
if should_profile():
return True
def gae_mini_profiler_should_profile_production():
from google.appengine.api import users
return users.is_current_user_admin()
def gae_mini_profiler_should_profile_development():
from google.appengine.api import users
return users.is_current_user_admin()
<commit_msg>Disable GAE mini profiler by default<commit_after>import logging
def appstats_should_record(env):
#from gae_mini_profiler.config import should_profile
#if should_profile():
# return True
return False
def gae_mini_profiler_should_profile_production():
from google.appengine.api import users
return users.is_current_user_admin()
def gae_mini_profiler_should_profile_development():
from google.appengine.api import users
return users.is_current_user_admin()
|
3e42ee0d9bd712b0e757af66279eaff838b0f004 | django_lti_tool_provider/tests/urls.py | django_lti_tool_provider/tests/urls.py | from django.conf.urls import url
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
] | from django.conf.urls import url
from django.contrib.auth.views import login
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', login),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
]
| Replace string "view" argument to url() function with callable. | Replace string "view" argument to url() function with callable.
Support for string "view" arguments to url() function no longer available starting with Django 1.10.
Cf. https://docs.djangoproject.com/en/2.1/releases/1.10/#features-removed-in-1-10
| Python | agpl-3.0 | open-craft/django-lti-tool-provider | from django.conf.urls import url
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
]Replace string "view" argument to url() function with callable.
Support for string "view" arguments to url() function no longer available starting with Django 1.10.
Cf. https://docs.djangoproject.com/en/2.1/releases/1.10/#features-removed-in-1-10 | from django.conf.urls import url
from django.contrib.auth.views import login
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', login),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
]
| <commit_before>from django.conf.urls import url
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
]<commit_msg>Replace string "view" argument to url() function with callable.
Support for string "view" arguments to url() function no longer available starting with Django 1.10.
Cf. https://docs.djangoproject.com/en/2.1/releases/1.10/#features-removed-in-1-10<commit_after> | from django.conf.urls import url
from django.contrib.auth.views import login
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', login),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
]
| from django.conf.urls import url
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
]Replace string "view" argument to url() function with callable.
Support for string "view" arguments to url() function no longer available starting with Django 1.10.
Cf. https://docs.djangoproject.com/en/2.1/releases/1.10/#features-removed-in-1-10from django.conf.urls import url
from django.contrib.auth.views import login
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', login),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
]
| <commit_before>from django.conf.urls import url
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
]<commit_msg>Replace string "view" argument to url() function with callable.
Support for string "view" arguments to url() function no longer available starting with Django 1.10.
Cf. https://docs.djangoproject.com/en/2.1/releases/1.10/#features-removed-in-1-10<commit_after>from django.conf.urls import url
from django.contrib.auth.views import login
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', login),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
]
|
e3e2b9b632a765927250782bab574767464b93b5 | software/clients/python_client/src/load_test.py | software/clients/python_client/src/load_test.py | import time
from all_spark_cube_client import CubeClient
from colors import *
HOST='cube.ac'
PORT=12345
def main():
buffer = [orange for x in range(4096)]
client = CubeClient(HOST, PORT)
reps = 300
while True:
start = time.time()
for x in range(reps):
client.set_colors(buffer)
duration = time.time() - start
print '%d frames in %.2f secs. %.2f fps.' % (
reps, duration, reps / float(duration))
if __name__ == '__main__':
main()
| import time
from all_spark_cube_client import CubeClient
from colors import *
HOST='cube.ac'
PORT=12345
def main():
buffer = [orange for x in range(4096)]
client = CubeClient(HOST, PORT)
reps = 300
while True:
start = time.time()
for x in range(reps):
client.set_colors(buffer)
duration = time.time() - start
print '"%d frames in %.2f secs. (%.2f fps)' % (
reps, duration, reps / float(duration))
if __name__ == '__main__':
main()
| Change output format of python load tester. | Change output format of python load tester.
| Python | mit | chadharrington/all_spark_cube,chadharrington/all_spark_cube,chadharrington/all_spark_cube,chadharrington/all_spark_cube | import time
from all_spark_cube_client import CubeClient
from colors import *
HOST='cube.ac'
PORT=12345
def main():
buffer = [orange for x in range(4096)]
client = CubeClient(HOST, PORT)
reps = 300
while True:
start = time.time()
for x in range(reps):
client.set_colors(buffer)
duration = time.time() - start
print '%d frames in %.2f secs. %.2f fps.' % (
reps, duration, reps / float(duration))
if __name__ == '__main__':
main()
Change output format of python load tester. | import time
from all_spark_cube_client import CubeClient
from colors import *
HOST='cube.ac'
PORT=12345
def main():
buffer = [orange for x in range(4096)]
client = CubeClient(HOST, PORT)
reps = 300
while True:
start = time.time()
for x in range(reps):
client.set_colors(buffer)
duration = time.time() - start
print '"%d frames in %.2f secs. (%.2f fps)' % (
reps, duration, reps / float(duration))
if __name__ == '__main__':
main()
| <commit_before>import time
from all_spark_cube_client import CubeClient
from colors import *
HOST='cube.ac'
PORT=12345
def main():
buffer = [orange for x in range(4096)]
client = CubeClient(HOST, PORT)
reps = 300
while True:
start = time.time()
for x in range(reps):
client.set_colors(buffer)
duration = time.time() - start
print '%d frames in %.2f secs. %.2f fps.' % (
reps, duration, reps / float(duration))
if __name__ == '__main__':
main()
<commit_msg>Change output format of python load tester.<commit_after> | import time
from all_spark_cube_client import CubeClient
from colors import *
HOST='cube.ac'
PORT=12345
def main():
buffer = [orange for x in range(4096)]
client = CubeClient(HOST, PORT)
reps = 300
while True:
start = time.time()
for x in range(reps):
client.set_colors(buffer)
duration = time.time() - start
print '"%d frames in %.2f secs. (%.2f fps)' % (
reps, duration, reps / float(duration))
if __name__ == '__main__':
main()
| import time
from all_spark_cube_client import CubeClient
from colors import *
HOST='cube.ac'
PORT=12345
def main():
buffer = [orange for x in range(4096)]
client = CubeClient(HOST, PORT)
reps = 300
while True:
start = time.time()
for x in range(reps):
client.set_colors(buffer)
duration = time.time() - start
print '%d frames in %.2f secs. %.2f fps.' % (
reps, duration, reps / float(duration))
if __name__ == '__main__':
main()
Change output format of python load tester.import time
from all_spark_cube_client import CubeClient
from colors import *
HOST='cube.ac'
PORT=12345
def main():
buffer = [orange for x in range(4096)]
client = CubeClient(HOST, PORT)
reps = 300
while True:
start = time.time()
for x in range(reps):
client.set_colors(buffer)
duration = time.time() - start
print '"%d frames in %.2f secs. (%.2f fps)' % (
reps, duration, reps / float(duration))
if __name__ == '__main__':
main()
| <commit_before>import time
from all_spark_cube_client import CubeClient
from colors import *
HOST='cube.ac'
PORT=12345
def main():
buffer = [orange for x in range(4096)]
client = CubeClient(HOST, PORT)
reps = 300
while True:
start = time.time()
for x in range(reps):
client.set_colors(buffer)
duration = time.time() - start
print '%d frames in %.2f secs. %.2f fps.' % (
reps, duration, reps / float(duration))
if __name__ == '__main__':
main()
<commit_msg>Change output format of python load tester.<commit_after>import time
from all_spark_cube_client import CubeClient
from colors import *
HOST='cube.ac'
PORT=12345
def main():
buffer = [orange for x in range(4096)]
client = CubeClient(HOST, PORT)
reps = 300
while True:
start = time.time()
for x in range(reps):
client.set_colors(buffer)
duration = time.time() - start
print '"%d frames in %.2f secs. (%.2f fps)' % (
reps, duration, reps / float(duration))
if __name__ == '__main__':
main()
|
d70f19106a7dc63182a3a0ea4fe6702eedc23322 | mlog/db.py | mlog/db.py | import sqlite3
def init(conn):
c = conn.cursor()
c.execute(
'''CREATE TABLE IF NOT EXISTS email_log (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`param` TEXT,
`email` TEXT,
`stage` INTEGER DEFAULT 0,
`sender` TEXT,
`receiver` TEXT,
`subject` TEXT,
`date_raw` TEXT,
`message_id` TEXT,
`attachments` INTEGER,
`in_reply_to` TEXT,
`in_reply_to_id` INTEGER,
`references` TEXT
)''')
| import sqlite3
def init(conn):
c = conn.cursor()
c.execute(
'''CREATE TABLE IF NOT EXISTS email_log (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`param` TEXT,
`email` TEXT,
`stage` INTEGER DEFAULT 0,
`sender` TEXT,
`receiver` TEXT,
`subject` TEXT,
`date_raw` TEXT,
`message_id` TEXT,
`attachments` INTEGER,
`in_reply_to` TEXT,
`in_reply_to_id` INTEGER,
`references` TEXT
)''')
c.execute(
'''CREATE INDEX IF NOT EXISTS email_log_idx_message_id
ON email_log (message_id)
''')
| Add index to the message_id column | Add index to the message_id column
| Python | agpl-3.0 | fajran/mlog | import sqlite3
def init(conn):
c = conn.cursor()
c.execute(
'''CREATE TABLE IF NOT EXISTS email_log (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`param` TEXT,
`email` TEXT,
`stage` INTEGER DEFAULT 0,
`sender` TEXT,
`receiver` TEXT,
`subject` TEXT,
`date_raw` TEXT,
`message_id` TEXT,
`attachments` INTEGER,
`in_reply_to` TEXT,
`in_reply_to_id` INTEGER,
`references` TEXT
)''')
Add index to the message_id column | import sqlite3
def init(conn):
c = conn.cursor()
c.execute(
'''CREATE TABLE IF NOT EXISTS email_log (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`param` TEXT,
`email` TEXT,
`stage` INTEGER DEFAULT 0,
`sender` TEXT,
`receiver` TEXT,
`subject` TEXT,
`date_raw` TEXT,
`message_id` TEXT,
`attachments` INTEGER,
`in_reply_to` TEXT,
`in_reply_to_id` INTEGER,
`references` TEXT
)''')
c.execute(
'''CREATE INDEX IF NOT EXISTS email_log_idx_message_id
ON email_log (message_id)
''')
| <commit_before>import sqlite3
def init(conn):
c = conn.cursor()
c.execute(
'''CREATE TABLE IF NOT EXISTS email_log (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`param` TEXT,
`email` TEXT,
`stage` INTEGER DEFAULT 0,
`sender` TEXT,
`receiver` TEXT,
`subject` TEXT,
`date_raw` TEXT,
`message_id` TEXT,
`attachments` INTEGER,
`in_reply_to` TEXT,
`in_reply_to_id` INTEGER,
`references` TEXT
)''')
<commit_msg>Add index to the message_id column<commit_after> | import sqlite3
def init(conn):
c = conn.cursor()
c.execute(
'''CREATE TABLE IF NOT EXISTS email_log (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`param` TEXT,
`email` TEXT,
`stage` INTEGER DEFAULT 0,
`sender` TEXT,
`receiver` TEXT,
`subject` TEXT,
`date_raw` TEXT,
`message_id` TEXT,
`attachments` INTEGER,
`in_reply_to` TEXT,
`in_reply_to_id` INTEGER,
`references` TEXT
)''')
c.execute(
'''CREATE INDEX IF NOT EXISTS email_log_idx_message_id
ON email_log (message_id)
''')
| import sqlite3
def init(conn):
c = conn.cursor()
c.execute(
'''CREATE TABLE IF NOT EXISTS email_log (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`param` TEXT,
`email` TEXT,
`stage` INTEGER DEFAULT 0,
`sender` TEXT,
`receiver` TEXT,
`subject` TEXT,
`date_raw` TEXT,
`message_id` TEXT,
`attachments` INTEGER,
`in_reply_to` TEXT,
`in_reply_to_id` INTEGER,
`references` TEXT
)''')
Add index to the message_id columnimport sqlite3
def init(conn):
c = conn.cursor()
c.execute(
'''CREATE TABLE IF NOT EXISTS email_log (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`param` TEXT,
`email` TEXT,
`stage` INTEGER DEFAULT 0,
`sender` TEXT,
`receiver` TEXT,
`subject` TEXT,
`date_raw` TEXT,
`message_id` TEXT,
`attachments` INTEGER,
`in_reply_to` TEXT,
`in_reply_to_id` INTEGER,
`references` TEXT
)''')
c.execute(
'''CREATE INDEX IF NOT EXISTS email_log_idx_message_id
ON email_log (message_id)
''')
| <commit_before>import sqlite3
def init(conn):
c = conn.cursor()
c.execute(
'''CREATE TABLE IF NOT EXISTS email_log (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`param` TEXT,
`email` TEXT,
`stage` INTEGER DEFAULT 0,
`sender` TEXT,
`receiver` TEXT,
`subject` TEXT,
`date_raw` TEXT,
`message_id` TEXT,
`attachments` INTEGER,
`in_reply_to` TEXT,
`in_reply_to_id` INTEGER,
`references` TEXT
)''')
<commit_msg>Add index to the message_id column<commit_after>import sqlite3
def init(conn):
c = conn.cursor()
c.execute(
'''CREATE TABLE IF NOT EXISTS email_log (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`param` TEXT,
`email` TEXT,
`stage` INTEGER DEFAULT 0,
`sender` TEXT,
`receiver` TEXT,
`subject` TEXT,
`date_raw` TEXT,
`message_id` TEXT,
`attachments` INTEGER,
`in_reply_to` TEXT,
`in_reply_to_id` INTEGER,
`references` TEXT
)''')
c.execute(
'''CREATE INDEX IF NOT EXISTS email_log_idx_message_id
ON email_log (message_id)
''')
|
81cf2085bb43742b722e833f8cec6e65e2906ec0 | pyes/tests/errors.py | pyes/tests/errors.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500).
"""
import unittest
from pyes.tests import ESTestCase
import pyes.exceptions
class ErrorReportingTestCase(ESTestCase):
def setUp(self):
super(ErrorReportingTestCase, self).setUp()
def testCreateDelete(self):
"""
Test errors thrown when creating or deleting.
"""
try:
self.conn.delete_index("test-index")
except pyes.exceptions.NotFoundException:
pass
self.conn.create_index("test-index")
self.assertRaises(pyes.exceptions.AlreadyExistsException, self.conn.create_index, "test-index")
self.conn.delete_index("test-index")
self.assertRaises(pyes.exceptions.NotFoundException, self.conn.delete_index, "test-index")
if __name__ == "__main__":
unittest.main()
| #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500).
"""
import unittest
from pyes.tests import ESTestCase
import pyes.exceptions
class ErrorReportingTestCase(ESTestCase):
def setUp(self):
super(ErrorReportingTestCase, self).setUp()
def testCreateDelete(self):
"""Test errors thrown when creating or deleting indexes.
"""
try:
self.conn.delete_index("test-index")
except pyes.exceptions.NotFoundException:
pass
self.conn.create_index("test-index")
err = self.checkRaises(pyes.exceptions.AlreadyExistsException,
self.conn.create_index, "test-index")
self.assertEqual(str(err), "[test-index] Already exists")
self.assertEqual(err.status, 400)
self.assertTrue('error' in err.result)
self.assertTrue('ok' not in err.result)
self.conn.delete_index("test-index")
err = self.checkRaises(pyes.exceptions.NotFoundException,
self.conn.delete_index, "test-index")
self.assertEqual(str(err), "[test-index] missing")
self.assertEqual(err.status, 400)
self.assertTrue('error' in err.result)
self.assertTrue('ok' not in err.result)
def testMissingIndex(self):
"""Test generation of a IndexMissingException.
"""
try:
self.conn.delete_index("test-index")
except pyes.exceptions.NotFoundException:
pass
err = self.checkRaises(pyes.exceptions.IndexMissingException,
self.conn.flush, 'test-index')
self.assertEqual(str(err), "[test-index] missing")
self.assertEqual(err.status, 500)
self.assertTrue('error' in err.result)
self.assertTrue('ok' not in err.result)
if __name__ == "__main__":
unittest.main()
| Test that various exceptions are correctly converted | Test that various exceptions are correctly converted
| Python | bsd-3-clause | jayzeng/pyes,Fiedzia/pyes,HackLinux/pyes,mavarick/pyes,haiwen/pyes,aparo/pyes,haiwen/pyes,aparo/pyes,aparo/pyes,jayzeng/pyes,Fiedzia/pyes,mavarick/pyes,mavarick/pyes,HackLinux/pyes,mouadino/pyes,rookdev/pyes,haiwen/pyes,rookdev/pyes,mouadino/pyes,HackLinux/pyes,Fiedzia/pyes,jayzeng/pyes | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500).
"""
import unittest
from pyes.tests import ESTestCase
import pyes.exceptions
class ErrorReportingTestCase(ESTestCase):
def setUp(self):
super(ErrorReportingTestCase, self).setUp()
def testCreateDelete(self):
"""
Test errors thrown when creating or deleting.
"""
try:
self.conn.delete_index("test-index")
except pyes.exceptions.NotFoundException:
pass
self.conn.create_index("test-index")
self.assertRaises(pyes.exceptions.AlreadyExistsException, self.conn.create_index, "test-index")
self.conn.delete_index("test-index")
self.assertRaises(pyes.exceptions.NotFoundException, self.conn.delete_index, "test-index")
if __name__ == "__main__":
unittest.main()
Test that various exceptions are correctly converted | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500).
"""
import unittest
from pyes.tests import ESTestCase
import pyes.exceptions
class ErrorReportingTestCase(ESTestCase):
def setUp(self):
super(ErrorReportingTestCase, self).setUp()
def testCreateDelete(self):
"""Test errors thrown when creating or deleting indexes.
"""
try:
self.conn.delete_index("test-index")
except pyes.exceptions.NotFoundException:
pass
self.conn.create_index("test-index")
err = self.checkRaises(pyes.exceptions.AlreadyExistsException,
self.conn.create_index, "test-index")
self.assertEqual(str(err), "[test-index] Already exists")
self.assertEqual(err.status, 400)
self.assertTrue('error' in err.result)
self.assertTrue('ok' not in err.result)
self.conn.delete_index("test-index")
err = self.checkRaises(pyes.exceptions.NotFoundException,
self.conn.delete_index, "test-index")
self.assertEqual(str(err), "[test-index] missing")
self.assertEqual(err.status, 400)
self.assertTrue('error' in err.result)
self.assertTrue('ok' not in err.result)
def testMissingIndex(self):
"""Test generation of a IndexMissingException.
"""
try:
self.conn.delete_index("test-index")
except pyes.exceptions.NotFoundException:
pass
err = self.checkRaises(pyes.exceptions.IndexMissingException,
self.conn.flush, 'test-index')
self.assertEqual(str(err), "[test-index] missing")
self.assertEqual(err.status, 500)
self.assertTrue('error' in err.result)
self.assertTrue('ok' not in err.result)
if __name__ == "__main__":
unittest.main()
| <commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500).
"""
import unittest
from pyes.tests import ESTestCase
import pyes.exceptions
class ErrorReportingTestCase(ESTestCase):
def setUp(self):
super(ErrorReportingTestCase, self).setUp()
def testCreateDelete(self):
"""
Test errors thrown when creating or deleting.
"""
try:
self.conn.delete_index("test-index")
except pyes.exceptions.NotFoundException:
pass
self.conn.create_index("test-index")
self.assertRaises(pyes.exceptions.AlreadyExistsException, self.conn.create_index, "test-index")
self.conn.delete_index("test-index")
self.assertRaises(pyes.exceptions.NotFoundException, self.conn.delete_index, "test-index")
if __name__ == "__main__":
unittest.main()
<commit_msg>Test that various exceptions are correctly converted<commit_after> | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500).
"""
import unittest
from pyes.tests import ESTestCase
import pyes.exceptions
class ErrorReportingTestCase(ESTestCase):
def setUp(self):
super(ErrorReportingTestCase, self).setUp()
def testCreateDelete(self):
"""Test errors thrown when creating or deleting indexes.
"""
try:
self.conn.delete_index("test-index")
except pyes.exceptions.NotFoundException:
pass
self.conn.create_index("test-index")
err = self.checkRaises(pyes.exceptions.AlreadyExistsException,
self.conn.create_index, "test-index")
self.assertEqual(str(err), "[test-index] Already exists")
self.assertEqual(err.status, 400)
self.assertTrue('error' in err.result)
self.assertTrue('ok' not in err.result)
self.conn.delete_index("test-index")
err = self.checkRaises(pyes.exceptions.NotFoundException,
self.conn.delete_index, "test-index")
self.assertEqual(str(err), "[test-index] missing")
self.assertEqual(err.status, 400)
self.assertTrue('error' in err.result)
self.assertTrue('ok' not in err.result)
def testMissingIndex(self):
"""Test generation of a IndexMissingException.
"""
try:
self.conn.delete_index("test-index")
except pyes.exceptions.NotFoundException:
pass
err = self.checkRaises(pyes.exceptions.IndexMissingException,
self.conn.flush, 'test-index')
self.assertEqual(str(err), "[test-index] missing")
self.assertEqual(err.status, 500)
self.assertTrue('error' in err.result)
self.assertTrue('ok' not in err.result)
if __name__ == "__main__":
unittest.main()
| #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500).
"""
import unittest
from pyes.tests import ESTestCase
import pyes.exceptions
class ErrorReportingTestCase(ESTestCase):
def setUp(self):
super(ErrorReportingTestCase, self).setUp()
def testCreateDelete(self):
"""
Test errors thrown when creating or deleting.
"""
try:
self.conn.delete_index("test-index")
except pyes.exceptions.NotFoundException:
pass
self.conn.create_index("test-index")
self.assertRaises(pyes.exceptions.AlreadyExistsException, self.conn.create_index, "test-index")
self.conn.delete_index("test-index")
self.assertRaises(pyes.exceptions.NotFoundException, self.conn.delete_index, "test-index")
if __name__ == "__main__":
unittest.main()
Test that various exceptions are correctly converted#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500).
"""
import unittest
from pyes.tests import ESTestCase
import pyes.exceptions
class ErrorReportingTestCase(ESTestCase):
def setUp(self):
super(ErrorReportingTestCase, self).setUp()
def testCreateDelete(self):
"""Test errors thrown when creating or deleting indexes.
"""
try:
self.conn.delete_index("test-index")
except pyes.exceptions.NotFoundException:
pass
self.conn.create_index("test-index")
err = self.checkRaises(pyes.exceptions.AlreadyExistsException,
self.conn.create_index, "test-index")
self.assertEqual(str(err), "[test-index] Already exists")
self.assertEqual(err.status, 400)
self.assertTrue('error' in err.result)
self.assertTrue('ok' not in err.result)
self.conn.delete_index("test-index")
err = self.checkRaises(pyes.exceptions.NotFoundException,
self.conn.delete_index, "test-index")
self.assertEqual(str(err), "[test-index] missing")
self.assertEqual(err.status, 400)
self.assertTrue('error' in err.result)
self.assertTrue('ok' not in err.result)
def testMissingIndex(self):
"""Test generation of a IndexMissingException.
"""
try:
self.conn.delete_index("test-index")
except pyes.exceptions.NotFoundException:
pass
err = self.checkRaises(pyes.exceptions.IndexMissingException,
self.conn.flush, 'test-index')
self.assertEqual(str(err), "[test-index] missing")
self.assertEqual(err.status, 500)
self.assertTrue('error' in err.result)
self.assertTrue('ok' not in err.result)
if __name__ == "__main__":
unittest.main()
| <commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500).
"""
import unittest
from pyes.tests import ESTestCase
import pyes.exceptions
class ErrorReportingTestCase(ESTestCase):
def setUp(self):
super(ErrorReportingTestCase, self).setUp()
def testCreateDelete(self):
"""
Test errors thrown when creating or deleting.
"""
try:
self.conn.delete_index("test-index")
except pyes.exceptions.NotFoundException:
pass
self.conn.create_index("test-index")
self.assertRaises(pyes.exceptions.AlreadyExistsException, self.conn.create_index, "test-index")
self.conn.delete_index("test-index")
self.assertRaises(pyes.exceptions.NotFoundException, self.conn.delete_index, "test-index")
if __name__ == "__main__":
unittest.main()
<commit_msg>Test that various exceptions are correctly converted<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Unit tests for pyes. These require an es server with thrift plugin running on the default port (localhost:9500).
"""
import unittest
from pyes.tests import ESTestCase
import pyes.exceptions
class ErrorReportingTestCase(ESTestCase):
def setUp(self):
super(ErrorReportingTestCase, self).setUp()
def testCreateDelete(self):
"""Test errors thrown when creating or deleting indexes.
"""
try:
self.conn.delete_index("test-index")
except pyes.exceptions.NotFoundException:
pass
self.conn.create_index("test-index")
err = self.checkRaises(pyes.exceptions.AlreadyExistsException,
self.conn.create_index, "test-index")
self.assertEqual(str(err), "[test-index] Already exists")
self.assertEqual(err.status, 400)
self.assertTrue('error' in err.result)
self.assertTrue('ok' not in err.result)
self.conn.delete_index("test-index")
err = self.checkRaises(pyes.exceptions.NotFoundException,
self.conn.delete_index, "test-index")
self.assertEqual(str(err), "[test-index] missing")
self.assertEqual(err.status, 400)
self.assertTrue('error' in err.result)
self.assertTrue('ok' not in err.result)
def testMissingIndex(self):
"""Test generation of a IndexMissingException.
"""
try:
self.conn.delete_index("test-index")
except pyes.exceptions.NotFoundException:
pass
err = self.checkRaises(pyes.exceptions.IndexMissingException,
self.conn.flush, 'test-index')
self.assertEqual(str(err), "[test-index] missing")
self.assertEqual(err.status, 500)
self.assertTrue('error' in err.result)
self.assertTrue('ok' not in err.result)
if __name__ == "__main__":
unittest.main()
|
4604cf73a45e8bcecf38238366cfdac37cdb7897 | pyfr/readers/base.py | pyfr/readers/base.py | # -*- coding: utf-8 -*-
import re
import uuid
import itertools as it
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _optimize(self, mesh):
# Sort interior interfaces
for f in it.ifilter(lambda f: re.match('con_p\d+', f), mesh):
mesh[f] = mesh[f][:,np.argsort(mesh[f][0])]
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Perform some simple optimizations on the mesh
self._optimize(mesh)
# Add metadata
mesh['mesh_uuid'] = str(uuid.uuid4())
return mesh
| # -*- coding: utf-8 -*-
import re
import uuid
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _optimize(self, mesh):
# Sort interior interfaces
for f in filter(lambda f: re.match(r'^con_p\d+$', f), mesh):
mesh[f] = mesh[f][:,np.argsort(mesh[f][0])]
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Perform some simple optimizations on the mesh
self._optimize(mesh)
# Add metadata
mesh['mesh_uuid'] = str(uuid.uuid4())
return mesh
| Fix a bug in the mesh optimizer. | Fix a bug in the mesh optimizer.
| Python | bsd-3-clause | iyer-arvind/PyFR,tjcorona/PyFR,tjcorona/PyFR,BrianVermeire/PyFR,Aerojspark/PyFR,tjcorona/PyFR | # -*- coding: utf-8 -*-
import re
import uuid
import itertools as it
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _optimize(self, mesh):
# Sort interior interfaces
for f in it.ifilter(lambda f: re.match('con_p\d+', f), mesh):
mesh[f] = mesh[f][:,np.argsort(mesh[f][0])]
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Perform some simple optimizations on the mesh
self._optimize(mesh)
# Add metadata
mesh['mesh_uuid'] = str(uuid.uuid4())
return mesh
Fix a bug in the mesh optimizer. | # -*- coding: utf-8 -*-
import re
import uuid
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _optimize(self, mesh):
# Sort interior interfaces
for f in filter(lambda f: re.match(r'^con_p\d+$', f), mesh):
mesh[f] = mesh[f][:,np.argsort(mesh[f][0])]
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Perform some simple optimizations on the mesh
self._optimize(mesh)
# Add metadata
mesh['mesh_uuid'] = str(uuid.uuid4())
return mesh
| <commit_before># -*- coding: utf-8 -*-
import re
import uuid
import itertools as it
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _optimize(self, mesh):
# Sort interior interfaces
for f in it.ifilter(lambda f: re.match('con_p\d+', f), mesh):
mesh[f] = mesh[f][:,np.argsort(mesh[f][0])]
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Perform some simple optimizations on the mesh
self._optimize(mesh)
# Add metadata
mesh['mesh_uuid'] = str(uuid.uuid4())
return mesh
<commit_msg>Fix a bug in the mesh optimizer.<commit_after> | # -*- coding: utf-8 -*-
import re
import uuid
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _optimize(self, mesh):
# Sort interior interfaces
for f in filter(lambda f: re.match(r'^con_p\d+$', f), mesh):
mesh[f] = mesh[f][:,np.argsort(mesh[f][0])]
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Perform some simple optimizations on the mesh
self._optimize(mesh)
# Add metadata
mesh['mesh_uuid'] = str(uuid.uuid4())
return mesh
| # -*- coding: utf-8 -*-
import re
import uuid
import itertools as it
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _optimize(self, mesh):
# Sort interior interfaces
for f in it.ifilter(lambda f: re.match('con_p\d+', f), mesh):
mesh[f] = mesh[f][:,np.argsort(mesh[f][0])]
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Perform some simple optimizations on the mesh
self._optimize(mesh)
# Add metadata
mesh['mesh_uuid'] = str(uuid.uuid4())
return mesh
Fix a bug in the mesh optimizer.# -*- coding: utf-8 -*-
import re
import uuid
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _optimize(self, mesh):
# Sort interior interfaces
for f in filter(lambda f: re.match(r'^con_p\d+$', f), mesh):
mesh[f] = mesh[f][:,np.argsort(mesh[f][0])]
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Perform some simple optimizations on the mesh
self._optimize(mesh)
# Add metadata
mesh['mesh_uuid'] = str(uuid.uuid4())
return mesh
| <commit_before># -*- coding: utf-8 -*-
import re
import uuid
import itertools as it
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _optimize(self, mesh):
# Sort interior interfaces
for f in it.ifilter(lambda f: re.match('con_p\d+', f), mesh):
mesh[f] = mesh[f][:,np.argsort(mesh[f][0])]
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Perform some simple optimizations on the mesh
self._optimize(mesh)
# Add metadata
mesh['mesh_uuid'] = str(uuid.uuid4())
return mesh
<commit_msg>Fix a bug in the mesh optimizer.<commit_after># -*- coding: utf-8 -*-
import re
import uuid
from abc import ABCMeta, abstractmethod
import numpy as np
class BaseReader(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def _optimize(self, mesh):
# Sort interior interfaces
for f in filter(lambda f: re.match(r'^con_p\d+$', f), mesh):
mesh[f] = mesh[f][:,np.argsort(mesh[f][0])]
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Perform some simple optimizations on the mesh
self._optimize(mesh)
# Add metadata
mesh['mesh_uuid'] = str(uuid.uuid4())
return mesh
|
3a7428723c66010dec1d246beb63be371428d3fe | qipipe/staging/staging_helpers.py | qipipe/staging/staging_helpers.py | """Pipeline utility functions."""
import re
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
def match_session_hierarchy(path):
"""
Matches the subject, session and series names from the given input path.
@param path: the path to match
@return: the matching (subject, session, series) tuple, or None if no match
"""
match = re.search(_SSS_REGEX, path)
if match:
return match.groups()
| """Pipeline utility functions."""
import re
from .staging_error import StagingError
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
def match_series_hierarchy(path):
"""
Matches the subject, session and series names from the given input path.
@param path: the path to match
@return: the matching (subject, session, series) tuple, or None if no match
"""
match = re.search(_SSS_REGEX, path)
if match:
return match.groups()
else:
raise StagingError("The path %s does match the subject/session/series pattern" % path)
| Raise error if no match. | Raise error if no match.
| Python | bsd-2-clause | ohsu-qin/qipipe | """Pipeline utility functions."""
import re
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
def match_session_hierarchy(path):
"""
Matches the subject, session and series names from the given input path.
@param path: the path to match
@return: the matching (subject, session, series) tuple, or None if no match
"""
match = re.search(_SSS_REGEX, path)
if match:
return match.groups()
Raise error if no match. | """Pipeline utility functions."""
import re
from .staging_error import StagingError
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
def match_series_hierarchy(path):
"""
Matches the subject, session and series names from the given input path.
@param path: the path to match
@return: the matching (subject, session, series) tuple, or None if no match
"""
match = re.search(_SSS_REGEX, path)
if match:
return match.groups()
else:
raise StagingError("The path %s does match the subject/session/series pattern" % path)
| <commit_before>"""Pipeline utility functions."""
import re
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
def match_session_hierarchy(path):
"""
Matches the subject, session and series names from the given input path.
@param path: the path to match
@return: the matching (subject, session, series) tuple, or None if no match
"""
match = re.search(_SSS_REGEX, path)
if match:
return match.groups()
<commit_msg>Raise error if no match.<commit_after> | """Pipeline utility functions."""
import re
from .staging_error import StagingError
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
def match_series_hierarchy(path):
"""
Matches the subject, session and series names from the given input path.
@param path: the path to match
@return: the matching (subject, session, series) tuple, or None if no match
"""
match = re.search(_SSS_REGEX, path)
if match:
return match.groups()
else:
raise StagingError("The path %s does match the subject/session/series pattern" % path)
| """Pipeline utility functions."""
import re
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
def match_session_hierarchy(path):
"""
Matches the subject, session and series names from the given input path.
@param path: the path to match
@return: the matching (subject, session, series) tuple, or None if no match
"""
match = re.search(_SSS_REGEX, path)
if match:
return match.groups()
Raise error if no match."""Pipeline utility functions."""
import re
from .staging_error import StagingError
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
def match_series_hierarchy(path):
"""
Matches the subject, session and series names from the given input path.
@param path: the path to match
@return: the matching (subject, session, series) tuple, or None if no match
"""
match = re.search(_SSS_REGEX, path)
if match:
return match.groups()
else:
raise StagingError("The path %s does match the subject/session/series pattern" % path)
| <commit_before>"""Pipeline utility functions."""
import re
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
def match_session_hierarchy(path):
"""
Matches the subject, session and series names from the given input path.
@param path: the path to match
@return: the matching (subject, session, series) tuple, or None if no match
"""
match = re.search(_SSS_REGEX, path)
if match:
return match.groups()
<commit_msg>Raise error if no match.<commit_after>"""Pipeline utility functions."""
import re
from .staging_error import StagingError
_SSS_REGEX = '(\w+\d{2})/(session\d{2})/(series\d{3})'
"""The subject/session/series regexp pattern."""
def match_series_hierarchy(path):
"""
Matches the subject, session and series names from the given input path.
@param path: the path to match
@return: the matching (subject, session, series) tuple, or None if no match
"""
match = re.search(_SSS_REGEX, path)
if match:
return match.groups()
else:
raise StagingError("The path %s does match the subject/session/series pattern" % path)
|
6dfcee473ef860fe9abb4971baabf62f9f51e314 | inpassing/util.py | inpassing/util.py | # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from functools import wraps
from flask_jwt_extended import utils
from flask_jwt_extended.utils import ctx_stack
from flask_jwt_extended.exceptions import NoAuthorizationError
from datetime import timedelta
def jwt_optional(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
# Decode token in header
try:
jwt_data = utils._decode_jwt_from_request(type='access')
# Verify this is an access token
if jwt_data['type'] != 'access':
raise WrongTokenError('Only access tokens can access this endpoint')
# Check if this is a revoked token
if utils.get_blacklist_enabled():
utils.check_if_token_revoked(jwt_data)
# Add the data to the context
ctx_stack.top.jwt_identity = jwt_data['identity']
ctx_stack.top.jwt_user_claims = jwt_data['user_claims']
except NoAuthorizationError:
# Ignore a missing header
pass
finally:
return fn(*args, **kwargs)
return wrapper
def range_inclusive_dates(start, end):
date_range = end - start
for day_i in range(date_range.days + 1):
yield start + timedelta(days=day_i)
| # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from functools import wraps
from flask_jwt_extended import utils
from flask_jwt_extended.utils import ctx_stack
from flask_jwt_extended.exceptions import NoAuthorizationError
from datetime import timedelta
def jwt_optional(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
# Decode token in header
try:
jwt_data = utils._decode_jwt_from_request(type='access')
# Verify this is an access token
if jwt_data['type'] != 'access':
raise WrongTokenError('Only access tokens can access this endpoint')
# Check if this is a revoked token
if utils.get_blacklist_enabled():
utils.check_if_token_revoked(jwt_data)
# Add the data to the context
ctx_stack.top.jwt_identity = jwt_data['identity']
ctx_stack.top.jwt_user_claims = jwt_data['user_claims']
except NoAuthorizationError:
# Ignore a missing header
pass
finally:
return fn(*args, **kwargs)
return wrapper
def range_inclusive_dates(start, end):
date_range = end - start
for day_i in range(date_range.days + 1):
yield start + timedelta(days=day_i)
def daystate_dict(daystate):
return {
'id': daystate.id,
'org_id': daystate.org_id,
'identifier': daystate.identifer,
'greeting': daystate.greeting
}
| Add daystate_dict function to serialize daystates to dictionaries | Add daystate_dict function to serialize daystates to dictionaries
| Python | mit | lukesanantonio/inpassing-backend,lukesanantonio/inpassing-backend | # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from functools import wraps
from flask_jwt_extended import utils
from flask_jwt_extended.utils import ctx_stack
from flask_jwt_extended.exceptions import NoAuthorizationError
from datetime import timedelta
def jwt_optional(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
# Decode token in header
try:
jwt_data = utils._decode_jwt_from_request(type='access')
# Verify this is an access token
if jwt_data['type'] != 'access':
raise WrongTokenError('Only access tokens can access this endpoint')
# Check if this is a revoked token
if utils.get_blacklist_enabled():
utils.check_if_token_revoked(jwt_data)
# Add the data to the context
ctx_stack.top.jwt_identity = jwt_data['identity']
ctx_stack.top.jwt_user_claims = jwt_data['user_claims']
except NoAuthorizationError:
# Ignore a missing header
pass
finally:
return fn(*args, **kwargs)
return wrapper
def range_inclusive_dates(start, end):
date_range = end - start
for day_i in range(date_range.days + 1):
yield start + timedelta(days=day_i)
Add daystate_dict function to serialize daystates to dictionaries | # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from functools import wraps
from flask_jwt_extended import utils
from flask_jwt_extended.utils import ctx_stack
from flask_jwt_extended.exceptions import NoAuthorizationError
from datetime import timedelta
def jwt_optional(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
# Decode token in header
try:
jwt_data = utils._decode_jwt_from_request(type='access')
# Verify this is an access token
if jwt_data['type'] != 'access':
raise WrongTokenError('Only access tokens can access this endpoint')
# Check if this is a revoked token
if utils.get_blacklist_enabled():
utils.check_if_token_revoked(jwt_data)
# Add the data to the context
ctx_stack.top.jwt_identity = jwt_data['identity']
ctx_stack.top.jwt_user_claims = jwt_data['user_claims']
except NoAuthorizationError:
# Ignore a missing header
pass
finally:
return fn(*args, **kwargs)
return wrapper
def range_inclusive_dates(start, end):
date_range = end - start
for day_i in range(date_range.days + 1):
yield start + timedelta(days=day_i)
def daystate_dict(daystate):
return {
'id': daystate.id,
'org_id': daystate.org_id,
'identifier': daystate.identifer,
'greeting': daystate.greeting
}
| <commit_before># Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from functools import wraps
from flask_jwt_extended import utils
from flask_jwt_extended.utils import ctx_stack
from flask_jwt_extended.exceptions import NoAuthorizationError
from datetime import timedelta
def jwt_optional(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
# Decode token in header
try:
jwt_data = utils._decode_jwt_from_request(type='access')
# Verify this is an access token
if jwt_data['type'] != 'access':
raise WrongTokenError('Only access tokens can access this endpoint')
# Check if this is a revoked token
if utils.get_blacklist_enabled():
utils.check_if_token_revoked(jwt_data)
# Add the data to the context
ctx_stack.top.jwt_identity = jwt_data['identity']
ctx_stack.top.jwt_user_claims = jwt_data['user_claims']
except NoAuthorizationError:
# Ignore a missing header
pass
finally:
return fn(*args, **kwargs)
return wrapper
def range_inclusive_dates(start, end):
date_range = end - start
for day_i in range(date_range.days + 1):
yield start + timedelta(days=day_i)
<commit_msg>Add daystate_dict function to serialize daystates to dictionaries<commit_after> | # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from functools import wraps
from flask_jwt_extended import utils
from flask_jwt_extended.utils import ctx_stack
from flask_jwt_extended.exceptions import NoAuthorizationError
from datetime import timedelta
def jwt_optional(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
# Decode token in header
try:
jwt_data = utils._decode_jwt_from_request(type='access')
# Verify this is an access token
if jwt_data['type'] != 'access':
raise WrongTokenError('Only access tokens can access this endpoint')
# Check if this is a revoked token
if utils.get_blacklist_enabled():
utils.check_if_token_revoked(jwt_data)
# Add the data to the context
ctx_stack.top.jwt_identity = jwt_data['identity']
ctx_stack.top.jwt_user_claims = jwt_data['user_claims']
except NoAuthorizationError:
# Ignore a missing header
pass
finally:
return fn(*args, **kwargs)
return wrapper
def range_inclusive_dates(start, end):
date_range = end - start
for day_i in range(date_range.days + 1):
yield start + timedelta(days=day_i)
def daystate_dict(daystate):
return {
'id': daystate.id,
'org_id': daystate.org_id,
'identifier': daystate.identifer,
'greeting': daystate.greeting
}
| # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from functools import wraps
from flask_jwt_extended import utils
from flask_jwt_extended.utils import ctx_stack
from flask_jwt_extended.exceptions import NoAuthorizationError
from datetime import timedelta
def jwt_optional(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
# Decode token in header
try:
jwt_data = utils._decode_jwt_from_request(type='access')
# Verify this is an access token
if jwt_data['type'] != 'access':
raise WrongTokenError('Only access tokens can access this endpoint')
# Check if this is a revoked token
if utils.get_blacklist_enabled():
utils.check_if_token_revoked(jwt_data)
# Add the data to the context
ctx_stack.top.jwt_identity = jwt_data['identity']
ctx_stack.top.jwt_user_claims = jwt_data['user_claims']
except NoAuthorizationError:
# Ignore a missing header
pass
finally:
return fn(*args, **kwargs)
return wrapper
def range_inclusive_dates(start, end):
date_range = end - start
for day_i in range(date_range.days + 1):
yield start + timedelta(days=day_i)
Add daystate_dict function to serialize daystates to dictionaries# Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from functools import wraps
from flask_jwt_extended import utils
from flask_jwt_extended.utils import ctx_stack
from flask_jwt_extended.exceptions import NoAuthorizationError
from datetime import timedelta
def jwt_optional(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
# Decode token in header
try:
jwt_data = utils._decode_jwt_from_request(type='access')
# Verify this is an access token
if jwt_data['type'] != 'access':
raise WrongTokenError('Only access tokens can access this endpoint')
# Check if this is a revoked token
if utils.get_blacklist_enabled():
utils.check_if_token_revoked(jwt_data)
# Add the data to the context
ctx_stack.top.jwt_identity = jwt_data['identity']
ctx_stack.top.jwt_user_claims = jwt_data['user_claims']
except NoAuthorizationError:
# Ignore a missing header
pass
finally:
return fn(*args, **kwargs)
return wrapper
def range_inclusive_dates(start, end):
date_range = end - start
for day_i in range(date_range.days + 1):
yield start + timedelta(days=day_i)
def daystate_dict(daystate):
return {
'id': daystate.id,
'org_id': daystate.org_id,
'identifier': daystate.identifer,
'greeting': daystate.greeting
}
| <commit_before># Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from functools import wraps
from flask_jwt_extended import utils
from flask_jwt_extended.utils import ctx_stack
from flask_jwt_extended.exceptions import NoAuthorizationError
from datetime import timedelta
def jwt_optional(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
# Decode token in header
try:
jwt_data = utils._decode_jwt_from_request(type='access')
# Verify this is an access token
if jwt_data['type'] != 'access':
raise WrongTokenError('Only access tokens can access this endpoint')
# Check if this is a revoked token
if utils.get_blacklist_enabled():
utils.check_if_token_revoked(jwt_data)
# Add the data to the context
ctx_stack.top.jwt_identity = jwt_data['identity']
ctx_stack.top.jwt_user_claims = jwt_data['user_claims']
except NoAuthorizationError:
# Ignore a missing header
pass
finally:
return fn(*args, **kwargs)
return wrapper
def range_inclusive_dates(start, end):
date_range = end - start
for day_i in range(date_range.days + 1):
yield start + timedelta(days=day_i)
<commit_msg>Add daystate_dict function to serialize daystates to dictionaries<commit_after># Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from functools import wraps
from flask_jwt_extended import utils
from flask_jwt_extended.utils import ctx_stack
from flask_jwt_extended.exceptions import NoAuthorizationError
from datetime import timedelta
def jwt_optional(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
# Decode token in header
try:
jwt_data = utils._decode_jwt_from_request(type='access')
# Verify this is an access token
if jwt_data['type'] != 'access':
raise WrongTokenError('Only access tokens can access this endpoint')
# Check if this is a revoked token
if utils.get_blacklist_enabled():
utils.check_if_token_revoked(jwt_data)
# Add the data to the context
ctx_stack.top.jwt_identity = jwt_data['identity']
ctx_stack.top.jwt_user_claims = jwt_data['user_claims']
except NoAuthorizationError:
# Ignore a missing header
pass
finally:
return fn(*args, **kwargs)
return wrapper
def range_inclusive_dates(start, end):
date_range = end - start
for day_i in range(date_range.days + 1):
yield start + timedelta(days=day_i)
def daystate_dict(daystate):
return {
'id': daystate.id,
'org_id': daystate.org_id,
'identifier': daystate.identifer,
'greeting': daystate.greeting
}
|
3c90d8a317e3d5b001a9aa141cc86826bdefb3fa | autoscaler/tasks.py | autoscaler/tasks.py | import logging
from celery import Celery
from celery.schedules import crontab
from celery.task import periodic_task
from celery.utils.log import get_task_logger
from autoscaler.autoscaler import check_autoscaler
logger = get_task_logger('autoscaler')
app = Celery()
@periodic_task(run_every=(crontab(minute='*/15')), options={"expires": 120})
def check_autoscaler_task():
logger.info('Task - Running Autoscaler...')
check_autoscaler()
logger.info('Task - Completed Autoscaler...')
| import logging
from celery import Celery
from celery.schedules import crontab
from celery.task import periodic_task
from celery.utils.log import get_task_logger
from autoscaler.autoscaler import check_autoscaler
logger = get_task_logger('autoscaler')
app = Celery()
@periodic_task(run_every=(crontab(minute='*/5')), options={"expires": 120})
def check_autoscaler_task():
logger.info('Task - Running Autoscaler...')
check_autoscaler()
logger.info('Task - Completed Autoscaler...')
| Make autoscaler run every 5 minutes. | Make autoscaler run every 5 minutes.
| Python | apache-2.0 | ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server | import logging
from celery import Celery
from celery.schedules import crontab
from celery.task import periodic_task
from celery.utils.log import get_task_logger
from autoscaler.autoscaler import check_autoscaler
logger = get_task_logger('autoscaler')
app = Celery()
@periodic_task(run_every=(crontab(minute='*/15')), options={"expires": 120})
def check_autoscaler_task():
logger.info('Task - Running Autoscaler...')
check_autoscaler()
logger.info('Task - Completed Autoscaler...')
Make autoscaler run every 5 minutes. | import logging
from celery import Celery
from celery.schedules import crontab
from celery.task import periodic_task
from celery.utils.log import get_task_logger
from autoscaler.autoscaler import check_autoscaler
logger = get_task_logger('autoscaler')
app = Celery()
@periodic_task(run_every=(crontab(minute='*/5')), options={"expires": 120})
def check_autoscaler_task():
logger.info('Task - Running Autoscaler...')
check_autoscaler()
logger.info('Task - Completed Autoscaler...')
| <commit_before>import logging
from celery import Celery
from celery.schedules import crontab
from celery.task import periodic_task
from celery.utils.log import get_task_logger
from autoscaler.autoscaler import check_autoscaler
logger = get_task_logger('autoscaler')
app = Celery()
@periodic_task(run_every=(crontab(minute='*/15')), options={"expires": 120})
def check_autoscaler_task():
logger.info('Task - Running Autoscaler...')
check_autoscaler()
logger.info('Task - Completed Autoscaler...')
<commit_msg>Make autoscaler run every 5 minutes.<commit_after> | import logging
from celery import Celery
from celery.schedules import crontab
from celery.task import periodic_task
from celery.utils.log import get_task_logger
from autoscaler.autoscaler import check_autoscaler
logger = get_task_logger('autoscaler')
app = Celery()
@periodic_task(run_every=(crontab(minute='*/5')), options={"expires": 120})
def check_autoscaler_task():
logger.info('Task - Running Autoscaler...')
check_autoscaler()
logger.info('Task - Completed Autoscaler...')
| import logging
from celery import Celery
from celery.schedules import crontab
from celery.task import periodic_task
from celery.utils.log import get_task_logger
from autoscaler.autoscaler import check_autoscaler
logger = get_task_logger('autoscaler')
app = Celery()
@periodic_task(run_every=(crontab(minute='*/15')), options={"expires": 120})
def check_autoscaler_task():
logger.info('Task - Running Autoscaler...')
check_autoscaler()
logger.info('Task - Completed Autoscaler...')
Make autoscaler run every 5 minutes.import logging
from celery import Celery
from celery.schedules import crontab
from celery.task import periodic_task
from celery.utils.log import get_task_logger
from autoscaler.autoscaler import check_autoscaler
logger = get_task_logger('autoscaler')
app = Celery()
@periodic_task(run_every=(crontab(minute='*/5')), options={"expires": 120})
def check_autoscaler_task():
logger.info('Task - Running Autoscaler...')
check_autoscaler()
logger.info('Task - Completed Autoscaler...')
| <commit_before>import logging
from celery import Celery
from celery.schedules import crontab
from celery.task import periodic_task
from celery.utils.log import get_task_logger
from autoscaler.autoscaler import check_autoscaler
logger = get_task_logger('autoscaler')
app = Celery()
@periodic_task(run_every=(crontab(minute='*/15')), options={"expires": 120})
def check_autoscaler_task():
logger.info('Task - Running Autoscaler...')
check_autoscaler()
logger.info('Task - Completed Autoscaler...')
<commit_msg>Make autoscaler run every 5 minutes.<commit_after>import logging
from celery import Celery
from celery.schedules import crontab
from celery.task import periodic_task
from celery.utils.log import get_task_logger
from autoscaler.autoscaler import check_autoscaler
logger = get_task_logger('autoscaler')
app = Celery()
@periodic_task(run_every=(crontab(minute='*/5')), options={"expires": 120})
def check_autoscaler_task():
logger.info('Task - Running Autoscaler...')
check_autoscaler()
logger.info('Task - Completed Autoscaler...')
|
71df45002746b162e04a125403cad390accb949e | backend/main.py | backend/main.py | # [START app]
import logging
from firebase import firebase
from flask import Flask, jsonify, request
import flask_cors
from google.appengine.ext import ndb
import google.auth.transport.requests
import google.oauth2.id_token
import requests_toolbelt.adapters.appengine
requests_toolbelt.adapters.appengine.monkeypatch()
HTTP_REQUEST = google.auth.transport.requests.Request()
app = Flask(__name__)
firebase = firebase.FirebaseApplication('https://trogdors-29fa4.firebaseio.com', None)
flask_cors.CORS(app)
@app.route('/')
def index():
return "<h1>Welcome To Google HVZ (backend)!</h1>"
@app.route('/test', methods=['GET'])
def get_testdata():
testdata = firebase.get('testdata', None)
return jsonify(testdata)
| # [START app]
import logging
from firebase import firebase
from flask import Flask, jsonify, request
import flask_cors
from google.appengine.ext import ndb
import google.auth.transport.requests
import google.oauth2.id_token
import requests_toolbelt.adapters.appengine
requests_toolbelt.adapters.appengine.monkeypatch()
HTTP_REQUEST = google.auth.transport.requests.Request()
# Fill out with value from https://firebase.corp.google.com/project/trogdors-29fa4/settings/database
FIREBASE_SECRET = ""
FIREBASE_EMAIL = ""
app = Flask(__name__)
auth = firebase.FirebaseAuthentication(FIREBASE_SECRET, FIREBASE_EMAIL, admin=True)
firebase = firebase.FirebaseApplication('https://trogdors-29fa4.firebaseio.com', authentication=auth)
flask_cors.CORS(app)
@app.route('/')
def index():
return "<h1>Welcome To Google HVZ (backend)!</h1>"
@app.route('/test', methods=['GET'])
def get_testdata():
testdata = firebase.get('testdata', None)
return jsonify(testdata)
| Add proper authentication for db (without actual key). | Add proper authentication for db (without actual key).
| Python | apache-2.0 | google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz | # [START app]
import logging
from firebase import firebase
from flask import Flask, jsonify, request
import flask_cors
from google.appengine.ext import ndb
import google.auth.transport.requests
import google.oauth2.id_token
import requests_toolbelt.adapters.appengine
requests_toolbelt.adapters.appengine.monkeypatch()
HTTP_REQUEST = google.auth.transport.requests.Request()
app = Flask(__name__)
firebase = firebase.FirebaseApplication('https://trogdors-29fa4.firebaseio.com', None)
flask_cors.CORS(app)
@app.route('/')
def index():
return "<h1>Welcome To Google HVZ (backend)!</h1>"
@app.route('/test', methods=['GET'])
def get_testdata():
testdata = firebase.get('testdata', None)
return jsonify(testdata)
Add proper authentication for db (without actual key). | # [START app]
import logging
from firebase import firebase
from flask import Flask, jsonify, request
import flask_cors
from google.appengine.ext import ndb
import google.auth.transport.requests
import google.oauth2.id_token
import requests_toolbelt.adapters.appengine
requests_toolbelt.adapters.appengine.monkeypatch()
HTTP_REQUEST = google.auth.transport.requests.Request()
# Fill out with value from https://firebase.corp.google.com/project/trogdors-29fa4/settings/database
FIREBASE_SECRET = ""
FIREBASE_EMAIL = ""
app = Flask(__name__)
auth = firebase.FirebaseAuthentication(FIREBASE_SECRET, FIREBASE_EMAIL, admin=True)
firebase = firebase.FirebaseApplication('https://trogdors-29fa4.firebaseio.com', authentication=auth)
flask_cors.CORS(app)
@app.route('/')
def index():
return "<h1>Welcome To Google HVZ (backend)!</h1>"
@app.route('/test', methods=['GET'])
def get_testdata():
testdata = firebase.get('testdata', None)
return jsonify(testdata)
| <commit_before># [START app]
import logging
from firebase import firebase
from flask import Flask, jsonify, request
import flask_cors
from google.appengine.ext import ndb
import google.auth.transport.requests
import google.oauth2.id_token
import requests_toolbelt.adapters.appengine
requests_toolbelt.adapters.appengine.monkeypatch()
HTTP_REQUEST = google.auth.transport.requests.Request()
app = Flask(__name__)
firebase = firebase.FirebaseApplication('https://trogdors-29fa4.firebaseio.com', None)
flask_cors.CORS(app)
@app.route('/')
def index():
return "<h1>Welcome To Google HVZ (backend)!</h1>"
@app.route('/test', methods=['GET'])
def get_testdata():
testdata = firebase.get('testdata', None)
return jsonify(testdata)
<commit_msg>Add proper authentication for db (without actual key).<commit_after> | # [START app]
import logging
from firebase import firebase
from flask import Flask, jsonify, request
import flask_cors
from google.appengine.ext import ndb
import google.auth.transport.requests
import google.oauth2.id_token
import requests_toolbelt.adapters.appengine
requests_toolbelt.adapters.appengine.monkeypatch()
HTTP_REQUEST = google.auth.transport.requests.Request()
# Fill out with value from https://firebase.corp.google.com/project/trogdors-29fa4/settings/database
FIREBASE_SECRET = ""
FIREBASE_EMAIL = ""
app = Flask(__name__)
auth = firebase.FirebaseAuthentication(FIREBASE_SECRET, FIREBASE_EMAIL, admin=True)
firebase = firebase.FirebaseApplication('https://trogdors-29fa4.firebaseio.com', authentication=auth)
flask_cors.CORS(app)
@app.route('/')
def index():
return "<h1>Welcome To Google HVZ (backend)!</h1>"
@app.route('/test', methods=['GET'])
def get_testdata():
testdata = firebase.get('testdata', None)
return jsonify(testdata)
| # [START app]
import logging
from firebase import firebase
from flask import Flask, jsonify, request
import flask_cors
from google.appengine.ext import ndb
import google.auth.transport.requests
import google.oauth2.id_token
import requests_toolbelt.adapters.appengine
requests_toolbelt.adapters.appengine.monkeypatch()
HTTP_REQUEST = google.auth.transport.requests.Request()
app = Flask(__name__)
firebase = firebase.FirebaseApplication('https://trogdors-29fa4.firebaseio.com', None)
flask_cors.CORS(app)
@app.route('/')
def index():
return "<h1>Welcome To Google HVZ (backend)!</h1>"
@app.route('/test', methods=['GET'])
def get_testdata():
testdata = firebase.get('testdata', None)
return jsonify(testdata)
Add proper authentication for db (without actual key).# [START app]
import logging
from firebase import firebase
from flask import Flask, jsonify, request
import flask_cors
from google.appengine.ext import ndb
import google.auth.transport.requests
import google.oauth2.id_token
import requests_toolbelt.adapters.appengine
requests_toolbelt.adapters.appengine.monkeypatch()
HTTP_REQUEST = google.auth.transport.requests.Request()
# Fill out with value from https://firebase.corp.google.com/project/trogdors-29fa4/settings/database
FIREBASE_SECRET = ""
FIREBASE_EMAIL = ""
app = Flask(__name__)
auth = firebase.FirebaseAuthentication(FIREBASE_SECRET, FIREBASE_EMAIL, admin=True)
firebase = firebase.FirebaseApplication('https://trogdors-29fa4.firebaseio.com', authentication=auth)
flask_cors.CORS(app)
@app.route('/')
def index():
return "<h1>Welcome To Google HVZ (backend)!</h1>"
@app.route('/test', methods=['GET'])
def get_testdata():
testdata = firebase.get('testdata', None)
return jsonify(testdata)
| <commit_before># [START app]
import logging
from firebase import firebase
from flask import Flask, jsonify, request
import flask_cors
from google.appengine.ext import ndb
import google.auth.transport.requests
import google.oauth2.id_token
import requests_toolbelt.adapters.appengine
requests_toolbelt.adapters.appengine.monkeypatch()
HTTP_REQUEST = google.auth.transport.requests.Request()
app = Flask(__name__)
firebase = firebase.FirebaseApplication('https://trogdors-29fa4.firebaseio.com', None)
flask_cors.CORS(app)
@app.route('/')
def index():
return "<h1>Welcome To Google HVZ (backend)!</h1>"
@app.route('/test', methods=['GET'])
def get_testdata():
testdata = firebase.get('testdata', None)
return jsonify(testdata)
<commit_msg>Add proper authentication for db (without actual key).<commit_after># [START app]
import logging
from firebase import firebase
from flask import Flask, jsonify, request
import flask_cors
from google.appengine.ext import ndb
import google.auth.transport.requests
import google.oauth2.id_token
import requests_toolbelt.adapters.appengine
requests_toolbelt.adapters.appengine.monkeypatch()
HTTP_REQUEST = google.auth.transport.requests.Request()
# Fill out with value from https://firebase.corp.google.com/project/trogdors-29fa4/settings/database
FIREBASE_SECRET = ""
FIREBASE_EMAIL = ""
app = Flask(__name__)
auth = firebase.FirebaseAuthentication(FIREBASE_SECRET, FIREBASE_EMAIL, admin=True)
firebase = firebase.FirebaseApplication('https://trogdors-29fa4.firebaseio.com', authentication=auth)
flask_cors.CORS(app)
@app.route('/')
def index():
return "<h1>Welcome To Google HVZ (backend)!</h1>"
@app.route('/test', methods=['GET'])
def get_testdata():
testdata = firebase.get('testdata', None)
return jsonify(testdata)
|
0aa6a648fff39b013f9b644d9a894db39706df43 | amplpy/amplpython/__init__.py | amplpy/amplpython/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import ctypes
import platform
if platform.system() == 'Windows':
lib32 = os.path.join(os.path.dirname(__file__), 'lib32')
lib64 = os.path.join(os.path.dirname(__file__), 'lib64')
from glob import glob
try:
if ctypes.sizeof(ctypes.c_voidp) == 4:
dllfile = glob(lib32 + '/*.dll')[0]
else:
dllfile = glob(lib64 + '/*.dll')[0]
ctypes.CDLL(dllfile)
except:
pass
from .amplpython import *
from .amplpython import _READTABLE, _WRITETABLE
| # -*- coding: utf-8 -*-
import os
import sys
import ctypes
import platform
if platform.system() == 'Windows':
lib32 = os.path.join(os.path.dirname(__file__), 'lib32')
lib64 = os.path.join(os.path.dirname(__file__), 'lib64')
from glob import glob
try:
if ctypes.sizeof(ctypes.c_voidp) == 4:
dllfile = glob(lib32 + '/*.dll')[0]
else:
dllfile = glob(lib64 + '/*.dll')[0]
ctypes.CDLL(dllfile)
except:
pass
sys.path.append(os.path.dirname(__file__))
from amplpython import *
from amplpython import _READTABLE, _WRITETABLE
| Fix 'ModuleNotFoundError: No module named amplpython' | Fix 'ModuleNotFoundError: No module named amplpython'
| Python | bsd-3-clause | ampl/amplpy,ampl/amplpy,ampl/amplpy | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import ctypes
import platform
if platform.system() == 'Windows':
lib32 = os.path.join(os.path.dirname(__file__), 'lib32')
lib64 = os.path.join(os.path.dirname(__file__), 'lib64')
from glob import glob
try:
if ctypes.sizeof(ctypes.c_voidp) == 4:
dllfile = glob(lib32 + '/*.dll')[0]
else:
dllfile = glob(lib64 + '/*.dll')[0]
ctypes.CDLL(dllfile)
except:
pass
from .amplpython import *
from .amplpython import _READTABLE, _WRITETABLE
Fix 'ModuleNotFoundError: No module named amplpython' | # -*- coding: utf-8 -*-
import os
import sys
import ctypes
import platform
if platform.system() == 'Windows':
lib32 = os.path.join(os.path.dirname(__file__), 'lib32')
lib64 = os.path.join(os.path.dirname(__file__), 'lib64')
from glob import glob
try:
if ctypes.sizeof(ctypes.c_voidp) == 4:
dllfile = glob(lib32 + '/*.dll')[0]
else:
dllfile = glob(lib64 + '/*.dll')[0]
ctypes.CDLL(dllfile)
except:
pass
sys.path.append(os.path.dirname(__file__))
from amplpython import *
from amplpython import _READTABLE, _WRITETABLE
| <commit_before># -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import ctypes
import platform
if platform.system() == 'Windows':
lib32 = os.path.join(os.path.dirname(__file__), 'lib32')
lib64 = os.path.join(os.path.dirname(__file__), 'lib64')
from glob import glob
try:
if ctypes.sizeof(ctypes.c_voidp) == 4:
dllfile = glob(lib32 + '/*.dll')[0]
else:
dllfile = glob(lib64 + '/*.dll')[0]
ctypes.CDLL(dllfile)
except:
pass
from .amplpython import *
from .amplpython import _READTABLE, _WRITETABLE
<commit_msg>Fix 'ModuleNotFoundError: No module named amplpython'<commit_after> | # -*- coding: utf-8 -*-
import os
import sys
import ctypes
import platform
if platform.system() == 'Windows':
lib32 = os.path.join(os.path.dirname(__file__), 'lib32')
lib64 = os.path.join(os.path.dirname(__file__), 'lib64')
from glob import glob
try:
if ctypes.sizeof(ctypes.c_voidp) == 4:
dllfile = glob(lib32 + '/*.dll')[0]
else:
dllfile = glob(lib64 + '/*.dll')[0]
ctypes.CDLL(dllfile)
except:
pass
sys.path.append(os.path.dirname(__file__))
from amplpython import *
from amplpython import _READTABLE, _WRITETABLE
| # -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import ctypes
import platform
if platform.system() == 'Windows':
lib32 = os.path.join(os.path.dirname(__file__), 'lib32')
lib64 = os.path.join(os.path.dirname(__file__), 'lib64')
from glob import glob
try:
if ctypes.sizeof(ctypes.c_voidp) == 4:
dllfile = glob(lib32 + '/*.dll')[0]
else:
dllfile = glob(lib64 + '/*.dll')[0]
ctypes.CDLL(dllfile)
except:
pass
from .amplpython import *
from .amplpython import _READTABLE, _WRITETABLE
Fix 'ModuleNotFoundError: No module named amplpython'# -*- coding: utf-8 -*-
import os
import sys
import ctypes
import platform
if platform.system() == 'Windows':
lib32 = os.path.join(os.path.dirname(__file__), 'lib32')
lib64 = os.path.join(os.path.dirname(__file__), 'lib64')
from glob import glob
try:
if ctypes.sizeof(ctypes.c_voidp) == 4:
dllfile = glob(lib32 + '/*.dll')[0]
else:
dllfile = glob(lib64 + '/*.dll')[0]
ctypes.CDLL(dllfile)
except:
pass
sys.path.append(os.path.dirname(__file__))
from amplpython import *
from amplpython import _READTABLE, _WRITETABLE
| <commit_before># -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import ctypes
import platform
if platform.system() == 'Windows':
lib32 = os.path.join(os.path.dirname(__file__), 'lib32')
lib64 = os.path.join(os.path.dirname(__file__), 'lib64')
from glob import glob
try:
if ctypes.sizeof(ctypes.c_voidp) == 4:
dllfile = glob(lib32 + '/*.dll')[0]
else:
dllfile = glob(lib64 + '/*.dll')[0]
ctypes.CDLL(dllfile)
except:
pass
from .amplpython import *
from .amplpython import _READTABLE, _WRITETABLE
<commit_msg>Fix 'ModuleNotFoundError: No module named amplpython'<commit_after># -*- coding: utf-8 -*-
import os
import sys
import ctypes
import platform
if platform.system() == 'Windows':
lib32 = os.path.join(os.path.dirname(__file__), 'lib32')
lib64 = os.path.join(os.path.dirname(__file__), 'lib64')
from glob import glob
try:
if ctypes.sizeof(ctypes.c_voidp) == 4:
dllfile = glob(lib32 + '/*.dll')[0]
else:
dllfile = glob(lib64 + '/*.dll')[0]
ctypes.CDLL(dllfile)
except:
pass
sys.path.append(os.path.dirname(__file__))
from amplpython import *
from amplpython import _READTABLE, _WRITETABLE
|
895ca15591938f07f1e913b08726f991c2d9e964 | libs/googleapis.py | libs/googleapis.py | import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
return response['timeZoneId']
def shorten_url(url):
response = requests.post(
'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(os.environ['GOOGLE_API_TOKEN']),
data=json.dumps({'longUrl': url}), headers={'Content-Type': 'application/json'}
).json()
print('Google Shortener url:', url, '; response:', response)
return response['id']
| import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
return response['timeZoneId']
def shorten_url(url):
response = requests.post(
'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(os.environ['GOOGLE_API_TOKEN']),
data=json.dumps({'longUrl': url}), headers={'Content-Type': 'application/json'}
).json()
print('Google Shortener url:', url, '; response:', response)
if 'id' in response:
return response['id']
return url
| Fix url shortening for small domains | Fix url shortening for small domains
| Python | mit | sevazhidkov/leonard | import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
return response['timeZoneId']
def shorten_url(url):
response = requests.post(
'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(os.environ['GOOGLE_API_TOKEN']),
data=json.dumps({'longUrl': url}), headers={'Content-Type': 'application/json'}
).json()
print('Google Shortener url:', url, '; response:', response)
return response['id']
Fix url shortening for small domains | import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
return response['timeZoneId']
def shorten_url(url):
response = requests.post(
'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(os.environ['GOOGLE_API_TOKEN']),
data=json.dumps({'longUrl': url}), headers={'Content-Type': 'application/json'}
).json()
print('Google Shortener url:', url, '; response:', response)
if 'id' in response:
return response['id']
return url
| <commit_before>import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
return response['timeZoneId']
def shorten_url(url):
response = requests.post(
'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(os.environ['GOOGLE_API_TOKEN']),
data=json.dumps({'longUrl': url}), headers={'Content-Type': 'application/json'}
).json()
print('Google Shortener url:', url, '; response:', response)
return response['id']
<commit_msg>Fix url shortening for small domains<commit_after> | import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
return response['timeZoneId']
def shorten_url(url):
response = requests.post(
'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(os.environ['GOOGLE_API_TOKEN']),
data=json.dumps({'longUrl': url}), headers={'Content-Type': 'application/json'}
).json()
print('Google Shortener url:', url, '; response:', response)
if 'id' in response:
return response['id']
return url
| import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
return response['timeZoneId']
def shorten_url(url):
response = requests.post(
'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(os.environ['GOOGLE_API_TOKEN']),
data=json.dumps({'longUrl': url}), headers={'Content-Type': 'application/json'}
).json()
print('Google Shortener url:', url, '; response:', response)
return response['id']
Fix url shortening for small domainsimport os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
return response['timeZoneId']
def shorten_url(url):
response = requests.post(
'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(os.environ['GOOGLE_API_TOKEN']),
data=json.dumps({'longUrl': url}), headers={'Content-Type': 'application/json'}
).json()
print('Google Shortener url:', url, '; response:', response)
if 'id' in response:
return response['id']
return url
| <commit_before>import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
return response['timeZoneId']
def shorten_url(url):
response = requests.post(
'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(os.environ['GOOGLE_API_TOKEN']),
data=json.dumps({'longUrl': url}), headers={'Content-Type': 'application/json'}
).json()
print('Google Shortener url:', url, '; response:', response)
return response['id']
<commit_msg>Fix url shortening for small domains<commit_after>import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
return response['timeZoneId']
def shorten_url(url):
response = requests.post(
'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(os.environ['GOOGLE_API_TOKEN']),
data=json.dumps({'longUrl': url}), headers={'Content-Type': 'application/json'}
).json()
print('Google Shortener url:', url, '; response:', response)
if 'id' in response:
return response['id']
return url
|
c9dfb5b59d5f51200df938f3da176a577842a390 | openquake/engine/tests/export/core_test.py | openquake/engine/tests/export/core_test.py |
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces=nrml.PARSE_NS_MAP))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
|
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces={'nrml': nrml.NRML05}))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
| Fix a broken export test | Fix a broken export test
Former-commit-id: fea471180d544a95f3d0adf87a7a46f51c067324 [formerly 4b369edfcb5782a2461742547f5b6af3bab4f759] [formerly 4b369edfcb5782a2461742547f5b6af3bab4f759 [formerly e37e964bf9d2819c0234303d31ed2839c317be04]]
Former-commit-id: 5b8a20fa99eab2f33c8f293a505a2dbadad36eee
Former-commit-id: 17492956ea8b4ed8b5465f6a057b6e026c2d4a75 | Python | agpl-3.0 | gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine |
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces=nrml.PARSE_NS_MAP))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
Fix a broken export test
Former-commit-id: fea471180d544a95f3d0adf87a7a46f51c067324 [formerly 4b369edfcb5782a2461742547f5b6af3bab4f759] [formerly 4b369edfcb5782a2461742547f5b6af3bab4f759 [formerly e37e964bf9d2819c0234303d31ed2839c317be04]]
Former-commit-id: 5b8a20fa99eab2f33c8f293a505a2dbadad36eee
Former-commit-id: 17492956ea8b4ed8b5465f6a057b6e026c2d4a75 |
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces={'nrml': nrml.NRML05}))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
| <commit_before>
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces=nrml.PARSE_NS_MAP))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
<commit_msg>Fix a broken export test
Former-commit-id: fea471180d544a95f3d0adf87a7a46f51c067324 [formerly 4b369edfcb5782a2461742547f5b6af3bab4f759] [formerly 4b369edfcb5782a2461742547f5b6af3bab4f759 [formerly e37e964bf9d2819c0234303d31ed2839c317be04]]
Former-commit-id: 5b8a20fa99eab2f33c8f293a505a2dbadad36eee
Former-commit-id: 17492956ea8b4ed8b5465f6a057b6e026c2d4a75<commit_after> |
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces={'nrml': nrml.NRML05}))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
|
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces=nrml.PARSE_NS_MAP))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
Fix a broken export test
Former-commit-id: fea471180d544a95f3d0adf87a7a46f51c067324 [formerly 4b369edfcb5782a2461742547f5b6af3bab4f759] [formerly 4b369edfcb5782a2461742547f5b6af3bab4f759 [formerly e37e964bf9d2819c0234303d31ed2839c317be04]]
Former-commit-id: 5b8a20fa99eab2f33c8f293a505a2dbadad36eee
Former-commit-id: 17492956ea8b4ed8b5465f6a057b6e026c2d4a75
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces={'nrml': nrml.NRML05}))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
| <commit_before>
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces=nrml.PARSE_NS_MAP))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
<commit_msg>Fix a broken export test
Former-commit-id: fea471180d544a95f3d0adf87a7a46f51c067324 [formerly 4b369edfcb5782a2461742547f5b6af3bab4f759] [formerly 4b369edfcb5782a2461742547f5b6af3bab4f759 [formerly e37e964bf9d2819c0234303d31ed2839c317be04]]
Former-commit-id: 5b8a20fa99eab2f33c8f293a505a2dbadad36eee
Former-commit-id: 17492956ea8b4ed8b5465f6a057b6e026c2d4a75<commit_after>
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces={'nrml': nrml.NRML05}))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
|
7b50adc607f0e0e970c6f5793eadd9fb42027d0a | Tools/scripts/setup.py | Tools/scripts/setup.py | from distutils.core import setup
if __name__ == '__main__':
setup(
scripts=[
'byteyears.py',
'checkpyc.py',
'copytime.py',
'crlf.py',
'dutree.py',
'ftpmirror.py',
'h2py.py',
'lfcr.py',
'logmerge.py',
'../../Lib/tabnanny.py',
'../../Lib/timeit.py',
'untabify.py',
],
)
| from distutils.core import setup
if __name__ == '__main__':
setup(
scripts=[
'byteyears.py',
'checkpyc.py',
'copytime.py',
'crlf.py',
'dutree.py',
'ftpmirror.py',
'h2py.py',
'lfcr.py',
'../i18n/pygettext.py',
'logmerge.py',
'../../Lib/tabnanny.py',
'../../Lib/timeit.py',
'untabify.py',
],
)
| Install pygettext (once the scriptsinstall target is working again). | Install pygettext (once the scriptsinstall target is working again).
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | from distutils.core import setup
if __name__ == '__main__':
setup(
scripts=[
'byteyears.py',
'checkpyc.py',
'copytime.py',
'crlf.py',
'dutree.py',
'ftpmirror.py',
'h2py.py',
'lfcr.py',
'logmerge.py',
'../../Lib/tabnanny.py',
'../../Lib/timeit.py',
'untabify.py',
],
)
Install pygettext (once the scriptsinstall target is working again). | from distutils.core import setup
if __name__ == '__main__':
setup(
scripts=[
'byteyears.py',
'checkpyc.py',
'copytime.py',
'crlf.py',
'dutree.py',
'ftpmirror.py',
'h2py.py',
'lfcr.py',
'../i18n/pygettext.py',
'logmerge.py',
'../../Lib/tabnanny.py',
'../../Lib/timeit.py',
'untabify.py',
],
)
| <commit_before>from distutils.core import setup
if __name__ == '__main__':
setup(
scripts=[
'byteyears.py',
'checkpyc.py',
'copytime.py',
'crlf.py',
'dutree.py',
'ftpmirror.py',
'h2py.py',
'lfcr.py',
'logmerge.py',
'../../Lib/tabnanny.py',
'../../Lib/timeit.py',
'untabify.py',
],
)
<commit_msg>Install pygettext (once the scriptsinstall target is working again).<commit_after> | from distutils.core import setup
if __name__ == '__main__':
setup(
scripts=[
'byteyears.py',
'checkpyc.py',
'copytime.py',
'crlf.py',
'dutree.py',
'ftpmirror.py',
'h2py.py',
'lfcr.py',
'../i18n/pygettext.py',
'logmerge.py',
'../../Lib/tabnanny.py',
'../../Lib/timeit.py',
'untabify.py',
],
)
| from distutils.core import setup
if __name__ == '__main__':
setup(
scripts=[
'byteyears.py',
'checkpyc.py',
'copytime.py',
'crlf.py',
'dutree.py',
'ftpmirror.py',
'h2py.py',
'lfcr.py',
'logmerge.py',
'../../Lib/tabnanny.py',
'../../Lib/timeit.py',
'untabify.py',
],
)
Install pygettext (once the scriptsinstall target is working again).from distutils.core import setup
if __name__ == '__main__':
setup(
scripts=[
'byteyears.py',
'checkpyc.py',
'copytime.py',
'crlf.py',
'dutree.py',
'ftpmirror.py',
'h2py.py',
'lfcr.py',
'../i18n/pygettext.py',
'logmerge.py',
'../../Lib/tabnanny.py',
'../../Lib/timeit.py',
'untabify.py',
],
)
| <commit_before>from distutils.core import setup
if __name__ == '__main__':
setup(
scripts=[
'byteyears.py',
'checkpyc.py',
'copytime.py',
'crlf.py',
'dutree.py',
'ftpmirror.py',
'h2py.py',
'lfcr.py',
'logmerge.py',
'../../Lib/tabnanny.py',
'../../Lib/timeit.py',
'untabify.py',
],
)
<commit_msg>Install pygettext (once the scriptsinstall target is working again).<commit_after>from distutils.core import setup
if __name__ == '__main__':
setup(
scripts=[
'byteyears.py',
'checkpyc.py',
'copytime.py',
'crlf.py',
'dutree.py',
'ftpmirror.py',
'h2py.py',
'lfcr.py',
'../i18n/pygettext.py',
'logmerge.py',
'../../Lib/tabnanny.py',
'../../Lib/timeit.py',
'untabify.py',
],
)
|
e43c1335bb48e8ba3321ddd9471ac04fd75a4250 | broker/ivorn_db.py | broker/ivorn_db.py | # VOEvent receiver.
# John Swinbank, <swinbank@transientskp.org>, 2011-12.
# Python standard library
import os
import anydbm
import datetime
from contextlib import closing
from threading import Lock
class IVORN_DB(object):
# Using one big lock for all the databases is a little clunky.
def __init__(self, root):
self.root = root
self.lock = Lock()
def check_ivorn(self, ivorn):
db_path, key = ivorn.split('//')[1].split('#')
db_path = db_path.replace(os.path.sep, "_")
try:
self.lock.acquire()
db = anydbm.open(os.path.join(self.root, db_path), 'c')
if db.has_key(key):
return False # Should not forward
else:
db[key] = str(datetime.datetime.utcnow())
return True # Ok to forward
finally:
self.lock.release()
| # VOEvent receiver.
# John Swinbank, <swinbank@transientskp.org>, 2011-12.
# Python standard library
import os
import anydbm
import datetime
from threading import Lock
from collections import defaultdict
class IVORN_DB(object):
def __init__(self, root):
self.root = root
self.locks = defaultdict(Lock)
def check_ivorn(self, ivorn):
db_path, key = ivorn.split('//')[1].split('#')
db_path = db_path.replace(os.path.sep, "_")
try:
self.locks[db_path].acquire()
db = anydbm.open(os.path.join(self.root, db_path), 'c')
if db.has_key(key):
return False # Should not forward
else:
db[key] = str(datetime.datetime.utcnow())
return True # Ok to forward
finally:
self.locks[db_path].release()
| Use a separate lock per ivorn database | Use a separate lock per ivorn database
| Python | bsd-2-clause | jdswinbank/Comet,jdswinbank/Comet | # VOEvent receiver.
# John Swinbank, <swinbank@transientskp.org>, 2011-12.
# Python standard library
import os
import anydbm
import datetime
from contextlib import closing
from threading import Lock
class IVORN_DB(object):
# Using one big lock for all the databases is a little clunky.
def __init__(self, root):
self.root = root
self.lock = Lock()
def check_ivorn(self, ivorn):
db_path, key = ivorn.split('//')[1].split('#')
db_path = db_path.replace(os.path.sep, "_")
try:
self.lock.acquire()
db = anydbm.open(os.path.join(self.root, db_path), 'c')
if db.has_key(key):
return False # Should not forward
else:
db[key] = str(datetime.datetime.utcnow())
return True # Ok to forward
finally:
self.lock.release()
Use a separate lock per ivorn database | # VOEvent receiver.
# John Swinbank, <swinbank@transientskp.org>, 2011-12.
# Python standard library
import os
import anydbm
import datetime
from threading import Lock
from collections import defaultdict
class IVORN_DB(object):
def __init__(self, root):
self.root = root
self.locks = defaultdict(Lock)
def check_ivorn(self, ivorn):
db_path, key = ivorn.split('//')[1].split('#')
db_path = db_path.replace(os.path.sep, "_")
try:
self.locks[db_path].acquire()
db = anydbm.open(os.path.join(self.root, db_path), 'c')
if db.has_key(key):
return False # Should not forward
else:
db[key] = str(datetime.datetime.utcnow())
return True # Ok to forward
finally:
self.locks[db_path].release()
| <commit_before># VOEvent receiver.
# John Swinbank, <swinbank@transientskp.org>, 2011-12.
# Python standard library
import os
import anydbm
import datetime
from contextlib import closing
from threading import Lock
class IVORN_DB(object):
# Using one big lock for all the databases is a little clunky.
def __init__(self, root):
self.root = root
self.lock = Lock()
def check_ivorn(self, ivorn):
db_path, key = ivorn.split('//')[1].split('#')
db_path = db_path.replace(os.path.sep, "_")
try:
self.lock.acquire()
db = anydbm.open(os.path.join(self.root, db_path), 'c')
if db.has_key(key):
return False # Should not forward
else:
db[key] = str(datetime.datetime.utcnow())
return True # Ok to forward
finally:
self.lock.release()
<commit_msg>Use a separate lock per ivorn database<commit_after> | # VOEvent receiver.
# John Swinbank, <swinbank@transientskp.org>, 2011-12.
# Python standard library
import os
import anydbm
import datetime
from threading import Lock
from collections import defaultdict
class IVORN_DB(object):
def __init__(self, root):
self.root = root
self.locks = defaultdict(Lock)
def check_ivorn(self, ivorn):
db_path, key = ivorn.split('//')[1].split('#')
db_path = db_path.replace(os.path.sep, "_")
try:
self.locks[db_path].acquire()
db = anydbm.open(os.path.join(self.root, db_path), 'c')
if db.has_key(key):
return False # Should not forward
else:
db[key] = str(datetime.datetime.utcnow())
return True # Ok to forward
finally:
self.locks[db_path].release()
| # VOEvent receiver.
# John Swinbank, <swinbank@transientskp.org>, 2011-12.
# Python standard library
import os
import anydbm
import datetime
from contextlib import closing
from threading import Lock
class IVORN_DB(object):
# Using one big lock for all the databases is a little clunky.
def __init__(self, root):
self.root = root
self.lock = Lock()
def check_ivorn(self, ivorn):
db_path, key = ivorn.split('//')[1].split('#')
db_path = db_path.replace(os.path.sep, "_")
try:
self.lock.acquire()
db = anydbm.open(os.path.join(self.root, db_path), 'c')
if db.has_key(key):
return False # Should not forward
else:
db[key] = str(datetime.datetime.utcnow())
return True # Ok to forward
finally:
self.lock.release()
Use a separate lock per ivorn database# VOEvent receiver.
# John Swinbank, <swinbank@transientskp.org>, 2011-12.
# Python standard library
import os
import anydbm
import datetime
from threading import Lock
from collections import defaultdict
class IVORN_DB(object):
def __init__(self, root):
self.root = root
self.locks = defaultdict(Lock)
def check_ivorn(self, ivorn):
db_path, key = ivorn.split('//')[1].split('#')
db_path = db_path.replace(os.path.sep, "_")
try:
self.locks[db_path].acquire()
db = anydbm.open(os.path.join(self.root, db_path), 'c')
if db.has_key(key):
return False # Should not forward
else:
db[key] = str(datetime.datetime.utcnow())
return True # Ok to forward
finally:
self.locks[db_path].release()
| <commit_before># VOEvent receiver.
# John Swinbank, <swinbank@transientskp.org>, 2011-12.
# Python standard library
import os
import anydbm
import datetime
from contextlib import closing
from threading import Lock
class IVORN_DB(object):
# Using one big lock for all the databases is a little clunky.
def __init__(self, root):
self.root = root
self.lock = Lock()
def check_ivorn(self, ivorn):
db_path, key = ivorn.split('//')[1].split('#')
db_path = db_path.replace(os.path.sep, "_")
try:
self.lock.acquire()
db = anydbm.open(os.path.join(self.root, db_path), 'c')
if db.has_key(key):
return False # Should not forward
else:
db[key] = str(datetime.datetime.utcnow())
return True # Ok to forward
finally:
self.lock.release()
<commit_msg>Use a separate lock per ivorn database<commit_after># VOEvent receiver.
# John Swinbank, <swinbank@transientskp.org>, 2011-12.
# Python standard library
import os
import anydbm
import datetime
from threading import Lock
from collections import defaultdict
class IVORN_DB(object):
def __init__(self, root):
self.root = root
self.locks = defaultdict(Lock)
def check_ivorn(self, ivorn):
db_path, key = ivorn.split('//')[1].split('#')
db_path = db_path.replace(os.path.sep, "_")
try:
self.locks[db_path].acquire()
db = anydbm.open(os.path.join(self.root, db_path), 'c')
if db.has_key(key):
return False # Should not forward
else:
db[key] = str(datetime.datetime.utcnow())
return True # Ok to forward
finally:
self.locks[db_path].release()
|
cb71bc8767fbc07a27df4049b95c7dacf5975c9d | pinax/app_name/tests/urls.py | pinax/app_name/tests/urls.py | try:
from django.conf.urls import patterns, include
except ImportError:
from django.conf.urls.defaults import patterns, include
urlpatterns = patterns(
"",
(r"^", include("pinax.{{ app_name }}.urls")),
)
| from django.conf.urls import include
urlpatterns = [
(r"^", include("pinax.{{ app_name }}.urls")),
]
| Fix django 1.9 warning and drop support django < 1.7 | Fix django 1.9 warning and drop support django < 1.7
Fixes a warning that happens when running with Django 1.9:
RemovedInDjango110Warning: django.conf.urls.patterns() is deprecated and will be removed in Django 1.10. Update your urlpatterns to be a list of django.conf.urls.url() instances instead.
Drop support of django < 1.7
Remove the ImportError catching because it was a hack for django < 1.7
| Python | mit | pinax/pinax-starter-app | try:
from django.conf.urls import patterns, include
except ImportError:
from django.conf.urls.defaults import patterns, include
urlpatterns = patterns(
"",
(r"^", include("pinax.{{ app_name }}.urls")),
)
Fix django 1.9 warning and drop support django < 1.7
Fixes a warning that happens when running with Django 1.9:
RemovedInDjango110Warning: django.conf.urls.patterns() is deprecated and will be removed in Django 1.10. Update your urlpatterns to be a list of django.conf.urls.url() instances instead.
Drop support of django < 1.7
Remove the ImportError catching because it was a hack for django < 1.7 | from django.conf.urls import include
urlpatterns = [
(r"^", include("pinax.{{ app_name }}.urls")),
]
| <commit_before>try:
from django.conf.urls import patterns, include
except ImportError:
from django.conf.urls.defaults import patterns, include
urlpatterns = patterns(
"",
(r"^", include("pinax.{{ app_name }}.urls")),
)
<commit_msg>Fix django 1.9 warning and drop support django < 1.7
Fixes a warning that happens when running with Django 1.9:
RemovedInDjango110Warning: django.conf.urls.patterns() is deprecated and will be removed in Django 1.10. Update your urlpatterns to be a list of django.conf.urls.url() instances instead.
Drop support of django < 1.7
Remove the ImportError catching because it was a hack for django < 1.7<commit_after> | from django.conf.urls import include
urlpatterns = [
(r"^", include("pinax.{{ app_name }}.urls")),
]
| try:
from django.conf.urls import patterns, include
except ImportError:
from django.conf.urls.defaults import patterns, include
urlpatterns = patterns(
"",
(r"^", include("pinax.{{ app_name }}.urls")),
)
Fix django 1.9 warning and drop support django < 1.7
Fixes a warning that happens when running with Django 1.9:
RemovedInDjango110Warning: django.conf.urls.patterns() is deprecated and will be removed in Django 1.10. Update your urlpatterns to be a list of django.conf.urls.url() instances instead.
Drop support of django < 1.7
Remove the ImportError catching because it was a hack for django < 1.7from django.conf.urls import include
urlpatterns = [
(r"^", include("pinax.{{ app_name }}.urls")),
]
| <commit_before>try:
from django.conf.urls import patterns, include
except ImportError:
from django.conf.urls.defaults import patterns, include
urlpatterns = patterns(
"",
(r"^", include("pinax.{{ app_name }}.urls")),
)
<commit_msg>Fix django 1.9 warning and drop support django < 1.7
Fixes a warning that happens when running with Django 1.9:
RemovedInDjango110Warning: django.conf.urls.patterns() is deprecated and will be removed in Django 1.10. Update your urlpatterns to be a list of django.conf.urls.url() instances instead.
Drop support of django < 1.7
Remove the ImportError catching because it was a hack for django < 1.7<commit_after>from django.conf.urls import include
urlpatterns = [
(r"^", include("pinax.{{ app_name }}.urls")),
]
|
09ae343b2abe0a0a325437396c995abe5aa560b4 | shuup/api/mixins.py | shuup/api/mixins.py | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.models.deletion import ProtectedError
from rest_framework import status
from rest_framework.response import Response
class PermissionHelperMixin(object):
"""
Mixin to return a helper text to admin users in permission configuration.
"""
@classmethod
def get_help_text(cls):
raise NotImplementedError()
class ProtectedModelViewSetMixin(object):
"""
Mixin to catch ProtectedError exceptions and return a reasonable response error to the user.
"""
def destroy(self, request, *args, **kwargs):
try:
return super(ProtectedModelViewSetMixin, self).destroy(request, *args, **kwargs)
except ProtectedError as exc:
ref_obj = exc.protected_objects[0].__class__.__name__
msg = "This object can not be deleted because it is referenced by {}".format(ref_obj)
return Response(data={"error": msg}, status=status.HTTP_400_BAD_REQUEST)
| # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.models.deletion import ProtectedError
from rest_framework import status
from rest_framework.filters import SearchFilter
from rest_framework.response import Response
class PermissionHelperMixin(object):
"""
Mixin to return a helper text to admin users in permission configuration.
"""
@classmethod
def get_help_text(cls):
raise NotImplementedError()
class ProtectedModelViewSetMixin(object):
"""
Mixin to catch ProtectedError exceptions and return a reasonable response error to the user.
"""
def destroy(self, request, *args, **kwargs):
try:
return super(ProtectedModelViewSetMixin, self).destroy(request, *args, **kwargs)
except ProtectedError as exc:
ref_obj = exc.protected_objects[0].__class__.__name__
msg = "This object can not be deleted because it is referenced by {}".format(ref_obj)
return Response(data={"error": msg}, status=status.HTTP_400_BAD_REQUEST)
class SearchableMixin(object):
"""
Mixin to give search capabilities for `ViewSet`
"""
filter_backends = (SearchFilter,)
search_fields = ("=id",)
| Add Searchable Mixin for API | Add Searchable Mixin for API
| Python | agpl-3.0 | shoopio/shoop,shoopio/shoop,shoopio/shoop | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.models.deletion import ProtectedError
from rest_framework import status
from rest_framework.response import Response
class PermissionHelperMixin(object):
"""
Mixin to return a helper text to admin users in permission configuration.
"""
@classmethod
def get_help_text(cls):
raise NotImplementedError()
class ProtectedModelViewSetMixin(object):
"""
Mixin to catch ProtectedError exceptions and return a reasonable response error to the user.
"""
def destroy(self, request, *args, **kwargs):
try:
return super(ProtectedModelViewSetMixin, self).destroy(request, *args, **kwargs)
except ProtectedError as exc:
ref_obj = exc.protected_objects[0].__class__.__name__
msg = "This object can not be deleted because it is referenced by {}".format(ref_obj)
return Response(data={"error": msg}, status=status.HTTP_400_BAD_REQUEST)
Add Searchable Mixin for API | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.models.deletion import ProtectedError
from rest_framework import status
from rest_framework.filters import SearchFilter
from rest_framework.response import Response
class PermissionHelperMixin(object):
"""
Mixin to return a helper text to admin users in permission configuration.
"""
@classmethod
def get_help_text(cls):
raise NotImplementedError()
class ProtectedModelViewSetMixin(object):
"""
Mixin to catch ProtectedError exceptions and return a reasonable response error to the user.
"""
def destroy(self, request, *args, **kwargs):
try:
return super(ProtectedModelViewSetMixin, self).destroy(request, *args, **kwargs)
except ProtectedError as exc:
ref_obj = exc.protected_objects[0].__class__.__name__
msg = "This object can not be deleted because it is referenced by {}".format(ref_obj)
return Response(data={"error": msg}, status=status.HTTP_400_BAD_REQUEST)
class SearchableMixin(object):
"""
Mixin to give search capabilities for `ViewSet`
"""
filter_backends = (SearchFilter,)
search_fields = ("=id",)
| <commit_before># -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.models.deletion import ProtectedError
from rest_framework import status
from rest_framework.response import Response
class PermissionHelperMixin(object):
"""
Mixin to return a helper text to admin users in permission configuration.
"""
@classmethod
def get_help_text(cls):
raise NotImplementedError()
class ProtectedModelViewSetMixin(object):
"""
Mixin to catch ProtectedError exceptions and return a reasonable response error to the user.
"""
def destroy(self, request, *args, **kwargs):
try:
return super(ProtectedModelViewSetMixin, self).destroy(request, *args, **kwargs)
except ProtectedError as exc:
ref_obj = exc.protected_objects[0].__class__.__name__
msg = "This object can not be deleted because it is referenced by {}".format(ref_obj)
return Response(data={"error": msg}, status=status.HTTP_400_BAD_REQUEST)
<commit_msg>Add Searchable Mixin for API<commit_after> | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.models.deletion import ProtectedError
from rest_framework import status
from rest_framework.filters import SearchFilter
from rest_framework.response import Response
class PermissionHelperMixin(object):
"""
Mixin to return a helper text to admin users in permission configuration.
"""
@classmethod
def get_help_text(cls):
raise NotImplementedError()
class ProtectedModelViewSetMixin(object):
"""
Mixin to catch ProtectedError exceptions and return a reasonable response error to the user.
"""
def destroy(self, request, *args, **kwargs):
try:
return super(ProtectedModelViewSetMixin, self).destroy(request, *args, **kwargs)
except ProtectedError as exc:
ref_obj = exc.protected_objects[0].__class__.__name__
msg = "This object can not be deleted because it is referenced by {}".format(ref_obj)
return Response(data={"error": msg}, status=status.HTTP_400_BAD_REQUEST)
class SearchableMixin(object):
"""
Mixin to give search capabilities for `ViewSet`
"""
filter_backends = (SearchFilter,)
search_fields = ("=id",)
| # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.models.deletion import ProtectedError
from rest_framework import status
from rest_framework.response import Response
class PermissionHelperMixin(object):
"""
Mixin to return a helper text to admin users in permission configuration.
"""
@classmethod
def get_help_text(cls):
raise NotImplementedError()
class ProtectedModelViewSetMixin(object):
"""
Mixin to catch ProtectedError exceptions and return a reasonable response error to the user.
"""
def destroy(self, request, *args, **kwargs):
try:
return super(ProtectedModelViewSetMixin, self).destroy(request, *args, **kwargs)
except ProtectedError as exc:
ref_obj = exc.protected_objects[0].__class__.__name__
msg = "This object can not be deleted because it is referenced by {}".format(ref_obj)
return Response(data={"error": msg}, status=status.HTTP_400_BAD_REQUEST)
Add Searchable Mixin for API# -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.models.deletion import ProtectedError
from rest_framework import status
from rest_framework.filters import SearchFilter
from rest_framework.response import Response
class PermissionHelperMixin(object):
"""
Mixin to return a helper text to admin users in permission configuration.
"""
@classmethod
def get_help_text(cls):
raise NotImplementedError()
class ProtectedModelViewSetMixin(object):
"""
Mixin to catch ProtectedError exceptions and return a reasonable response error to the user.
"""
def destroy(self, request, *args, **kwargs):
try:
return super(ProtectedModelViewSetMixin, self).destroy(request, *args, **kwargs)
except ProtectedError as exc:
ref_obj = exc.protected_objects[0].__class__.__name__
msg = "This object can not be deleted because it is referenced by {}".format(ref_obj)
return Response(data={"error": msg}, status=status.HTTP_400_BAD_REQUEST)
class SearchableMixin(object):
"""
Mixin to give search capabilities for `ViewSet`
"""
filter_backends = (SearchFilter,)
search_fields = ("=id",)
| <commit_before># -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.models.deletion import ProtectedError
from rest_framework import status
from rest_framework.response import Response
class PermissionHelperMixin(object):
"""
Mixin to return a helper text to admin users in permission configuration.
"""
@classmethod
def get_help_text(cls):
raise NotImplementedError()
class ProtectedModelViewSetMixin(object):
"""
Mixin to catch ProtectedError exceptions and return a reasonable response error to the user.
"""
def destroy(self, request, *args, **kwargs):
try:
return super(ProtectedModelViewSetMixin, self).destroy(request, *args, **kwargs)
except ProtectedError as exc:
ref_obj = exc.protected_objects[0].__class__.__name__
msg = "This object can not be deleted because it is referenced by {}".format(ref_obj)
return Response(data={"error": msg}, status=status.HTTP_400_BAD_REQUEST)
<commit_msg>Add Searchable Mixin for API<commit_after># -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.db.models.deletion import ProtectedError
from rest_framework import status
from rest_framework.filters import SearchFilter
from rest_framework.response import Response
class PermissionHelperMixin(object):
"""
Mixin to return a helper text to admin users in permission configuration.
"""
@classmethod
def get_help_text(cls):
raise NotImplementedError()
class ProtectedModelViewSetMixin(object):
"""
Mixin to catch ProtectedError exceptions and return a reasonable response error to the user.
"""
def destroy(self, request, *args, **kwargs):
try:
return super(ProtectedModelViewSetMixin, self).destroy(request, *args, **kwargs)
except ProtectedError as exc:
ref_obj = exc.protected_objects[0].__class__.__name__
msg = "This object can not be deleted because it is referenced by {}".format(ref_obj)
return Response(data={"error": msg}, status=status.HTTP_400_BAD_REQUEST)
class SearchableMixin(object):
"""
Mixin to give search capabilities for `ViewSet`
"""
filter_backends = (SearchFilter,)
search_fields = ("=id",)
|
d6fc8cc0e0d50b23ba0d7ca6195bc530b2f8d1b9 | shapely/tests/test_unary_union.py | shapely/tests/test_unary_union.py | from itertools import islice
import unittest
from shapely.geometry import Point
from shapely.ops import unary_union
def halton(base):
"""Returns an iterator over an infinite Halton sequence"""
def value(index):
result = 0.0
f = 1.0/base
i = index
while i > 0:
result += f * (i % base)
i = i/base
f = f/base
return result
i = 1
while i > 0:
yield value(i)
i += 1
class UnionTestCase(unittest.TestCase):
def test_1(self):
# Instead of random points, use deterministic, pseudo-random Halton
# sequences for repeatability sake.
coords = list(zip(
list(islice(halton(5), 20, 120)),
list(islice(halton(7), 20, 120)) ))
patches = [Point(xy).buffer(0.05) for xy in coords]
u = unary_union(patches)
self.failUnlessEqual(u.geom_type, 'MultiPolygon')
self.failUnlessAlmostEqual(u.area, 0.71857254056)
def test_suite():
try:
patches = [Point((0, 0)).buffer(0.05)]
unary_union(patches)
except KeyError:
return lambda x: None
return unittest.TestLoader().loadTestsFromTestCase(UnionTestCase)
| from itertools import islice
import unittest
from shapely.geometry import Point
from shapely.ops import unary_union
def halton(base):
"""Returns an iterator over an infinite Halton sequence"""
def value(index):
result = 0.0
f = 1.0/base
i = index
while i > 0:
result += f * (i % base)
i = i//base
f = f/base
return result
i = 1
while i > 0:
yield value(i)
i += 1
class UnionTestCase(unittest.TestCase):
def test_1(self):
# Instead of random points, use deterministic, pseudo-random Halton
# sequences for repeatability sake.
coords = list(zip(
list(islice(halton(5), 20, 120)),
list(islice(halton(7), 20, 120)) ))
patches = [Point(xy).buffer(0.05) for xy in coords]
u = unary_union(patches)
self.failUnlessEqual(u.geom_type, 'MultiPolygon')
self.failUnlessAlmostEqual(u.area, 0.71857254056)
def test_suite():
try:
patches = [Point((0, 0)).buffer(0.05)]
unary_union(patches)
except KeyError:
return lambda x: None
return unittest.TestLoader().loadTestsFromTestCase(UnionTestCase)
| Fix halton sequence generator for Python 3 | Fix halton sequence generator for Python 3
| Python | bsd-3-clause | abali96/Shapely,jdmcbr/Shapely,jdmcbr/Shapely,abali96/Shapely,mouadino/Shapely,mouadino/Shapely,mindw/shapely,mindw/shapely | from itertools import islice
import unittest
from shapely.geometry import Point
from shapely.ops import unary_union
def halton(base):
"""Returns an iterator over an infinite Halton sequence"""
def value(index):
result = 0.0
f = 1.0/base
i = index
while i > 0:
result += f * (i % base)
i = i/base
f = f/base
return result
i = 1
while i > 0:
yield value(i)
i += 1
class UnionTestCase(unittest.TestCase):
def test_1(self):
# Instead of random points, use deterministic, pseudo-random Halton
# sequences for repeatability sake.
coords = list(zip(
list(islice(halton(5), 20, 120)),
list(islice(halton(7), 20, 120)) ))
patches = [Point(xy).buffer(0.05) for xy in coords]
u = unary_union(patches)
self.failUnlessEqual(u.geom_type, 'MultiPolygon')
self.failUnlessAlmostEqual(u.area, 0.71857254056)
def test_suite():
try:
patches = [Point((0, 0)).buffer(0.05)]
unary_union(patches)
except KeyError:
return lambda x: None
return unittest.TestLoader().loadTestsFromTestCase(UnionTestCase)
Fix halton sequence generator for Python 3 | from itertools import islice
import unittest
from shapely.geometry import Point
from shapely.ops import unary_union
def halton(base):
"""Returns an iterator over an infinite Halton sequence"""
def value(index):
result = 0.0
f = 1.0/base
i = index
while i > 0:
result += f * (i % base)
i = i//base
f = f/base
return result
i = 1
while i > 0:
yield value(i)
i += 1
class UnionTestCase(unittest.TestCase):
def test_1(self):
# Instead of random points, use deterministic, pseudo-random Halton
# sequences for repeatability sake.
coords = list(zip(
list(islice(halton(5), 20, 120)),
list(islice(halton(7), 20, 120)) ))
patches = [Point(xy).buffer(0.05) for xy in coords]
u = unary_union(patches)
self.failUnlessEqual(u.geom_type, 'MultiPolygon')
self.failUnlessAlmostEqual(u.area, 0.71857254056)
def test_suite():
try:
patches = [Point((0, 0)).buffer(0.05)]
unary_union(patches)
except KeyError:
return lambda x: None
return unittest.TestLoader().loadTestsFromTestCase(UnionTestCase)
| <commit_before>from itertools import islice
import unittest
from shapely.geometry import Point
from shapely.ops import unary_union
def halton(base):
"""Returns an iterator over an infinite Halton sequence"""
def value(index):
result = 0.0
f = 1.0/base
i = index
while i > 0:
result += f * (i % base)
i = i/base
f = f/base
return result
i = 1
while i > 0:
yield value(i)
i += 1
class UnionTestCase(unittest.TestCase):
def test_1(self):
# Instead of random points, use deterministic, pseudo-random Halton
# sequences for repeatability sake.
coords = list(zip(
list(islice(halton(5), 20, 120)),
list(islice(halton(7), 20, 120)) ))
patches = [Point(xy).buffer(0.05) for xy in coords]
u = unary_union(patches)
self.failUnlessEqual(u.geom_type, 'MultiPolygon')
self.failUnlessAlmostEqual(u.area, 0.71857254056)
def test_suite():
try:
patches = [Point((0, 0)).buffer(0.05)]
unary_union(patches)
except KeyError:
return lambda x: None
return unittest.TestLoader().loadTestsFromTestCase(UnionTestCase)
<commit_msg>Fix halton sequence generator for Python 3<commit_after> | from itertools import islice
import unittest
from shapely.geometry import Point
from shapely.ops import unary_union
def halton(base):
"""Returns an iterator over an infinite Halton sequence"""
def value(index):
result = 0.0
f = 1.0/base
i = index
while i > 0:
result += f * (i % base)
i = i//base
f = f/base
return result
i = 1
while i > 0:
yield value(i)
i += 1
class UnionTestCase(unittest.TestCase):
def test_1(self):
# Instead of random points, use deterministic, pseudo-random Halton
# sequences for repeatability sake.
coords = list(zip(
list(islice(halton(5), 20, 120)),
list(islice(halton(7), 20, 120)) ))
patches = [Point(xy).buffer(0.05) for xy in coords]
u = unary_union(patches)
self.failUnlessEqual(u.geom_type, 'MultiPolygon')
self.failUnlessAlmostEqual(u.area, 0.71857254056)
def test_suite():
try:
patches = [Point((0, 0)).buffer(0.05)]
unary_union(patches)
except KeyError:
return lambda x: None
return unittest.TestLoader().loadTestsFromTestCase(UnionTestCase)
| from itertools import islice
import unittest
from shapely.geometry import Point
from shapely.ops import unary_union
def halton(base):
"""Returns an iterator over an infinite Halton sequence"""
def value(index):
result = 0.0
f = 1.0/base
i = index
while i > 0:
result += f * (i % base)
i = i/base
f = f/base
return result
i = 1
while i > 0:
yield value(i)
i += 1
class UnionTestCase(unittest.TestCase):
def test_1(self):
# Instead of random points, use deterministic, pseudo-random Halton
# sequences for repeatability sake.
coords = list(zip(
list(islice(halton(5), 20, 120)),
list(islice(halton(7), 20, 120)) ))
patches = [Point(xy).buffer(0.05) for xy in coords]
u = unary_union(patches)
self.failUnlessEqual(u.geom_type, 'MultiPolygon')
self.failUnlessAlmostEqual(u.area, 0.71857254056)
def test_suite():
try:
patches = [Point((0, 0)).buffer(0.05)]
unary_union(patches)
except KeyError:
return lambda x: None
return unittest.TestLoader().loadTestsFromTestCase(UnionTestCase)
Fix halton sequence generator for Python 3from itertools import islice
import unittest
from shapely.geometry import Point
from shapely.ops import unary_union
def halton(base):
"""Returns an iterator over an infinite Halton sequence"""
def value(index):
result = 0.0
f = 1.0/base
i = index
while i > 0:
result += f * (i % base)
i = i//base
f = f/base
return result
i = 1
while i > 0:
yield value(i)
i += 1
class UnionTestCase(unittest.TestCase):
def test_1(self):
# Instead of random points, use deterministic, pseudo-random Halton
# sequences for repeatability sake.
coords = list(zip(
list(islice(halton(5), 20, 120)),
list(islice(halton(7), 20, 120)) ))
patches = [Point(xy).buffer(0.05) for xy in coords]
u = unary_union(patches)
self.failUnlessEqual(u.geom_type, 'MultiPolygon')
self.failUnlessAlmostEqual(u.area, 0.71857254056)
def test_suite():
try:
patches = [Point((0, 0)).buffer(0.05)]
unary_union(patches)
except KeyError:
return lambda x: None
return unittest.TestLoader().loadTestsFromTestCase(UnionTestCase)
| <commit_before>from itertools import islice
import unittest
from shapely.geometry import Point
from shapely.ops import unary_union
def halton(base):
"""Returns an iterator over an infinite Halton sequence"""
def value(index):
result = 0.0
f = 1.0/base
i = index
while i > 0:
result += f * (i % base)
i = i/base
f = f/base
return result
i = 1
while i > 0:
yield value(i)
i += 1
class UnionTestCase(unittest.TestCase):
def test_1(self):
# Instead of random points, use deterministic, pseudo-random Halton
# sequences for repeatability sake.
coords = list(zip(
list(islice(halton(5), 20, 120)),
list(islice(halton(7), 20, 120)) ))
patches = [Point(xy).buffer(0.05) for xy in coords]
u = unary_union(patches)
self.failUnlessEqual(u.geom_type, 'MultiPolygon')
self.failUnlessAlmostEqual(u.area, 0.71857254056)
def test_suite():
try:
patches = [Point((0, 0)).buffer(0.05)]
unary_union(patches)
except KeyError:
return lambda x: None
return unittest.TestLoader().loadTestsFromTestCase(UnionTestCase)
<commit_msg>Fix halton sequence generator for Python 3<commit_after>from itertools import islice
import unittest
from shapely.geometry import Point
from shapely.ops import unary_union
def halton(base):
"""Returns an iterator over an infinite Halton sequence"""
def value(index):
result = 0.0
f = 1.0/base
i = index
while i > 0:
result += f * (i % base)
i = i//base
f = f/base
return result
i = 1
while i > 0:
yield value(i)
i += 1
class UnionTestCase(unittest.TestCase):
def test_1(self):
# Instead of random points, use deterministic, pseudo-random Halton
# sequences for repeatability sake.
coords = list(zip(
list(islice(halton(5), 20, 120)),
list(islice(halton(7), 20, 120)) ))
patches = [Point(xy).buffer(0.05) for xy in coords]
u = unary_union(patches)
self.failUnlessEqual(u.geom_type, 'MultiPolygon')
self.failUnlessAlmostEqual(u.area, 0.71857254056)
def test_suite():
try:
patches = [Point((0, 0)).buffer(0.05)]
unary_union(patches)
except KeyError:
return lambda x: None
return unittest.TestLoader().loadTestsFromTestCase(UnionTestCase)
|
28bacd5c3318aff52c0758ad97909ff08c7bfffb | api/base/exceptions.py | api/base/exceptions.py |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
if isinstance(value, list):
for reason in value:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': reason})
else:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': value})
elif isinstance(message, (list, tuple)):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
|
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
if isinstance(value, list):
for reason in value:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': reason})
else:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': value})
elif isinstance(message, (list, tuple)):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
| Add spaces to increase readability. | Add spaces to increase readability.
"OSF-4419"
| Python | apache-2.0 | asanfilippo7/osf.io,saradbowman/osf.io,acshi/osf.io,amyshi188/osf.io,HalcyonChimera/osf.io,brandonPurvis/osf.io,mattclark/osf.io,Nesiehr/osf.io,cwisecarver/osf.io,Johnetordoff/osf.io,abought/osf.io,monikagrabowska/osf.io,pattisdr/osf.io,pattisdr/osf.io,njantrania/osf.io,samchrisinger/osf.io,jnayak1/osf.io,cwisecarver/osf.io,hmoco/osf.io,haoyuchen1992/osf.io,icereval/osf.io,wearpants/osf.io,abought/osf.io,caseyrollins/osf.io,SSJohns/osf.io,leb2dg/osf.io,KAsante95/osf.io,acshi/osf.io,amyshi188/osf.io,haoyuchen1992/osf.io,DanielSBrown/osf.io,cwisecarver/osf.io,asanfilippo7/osf.io,kwierman/osf.io,amyshi188/osf.io,hmoco/osf.io,TomBaxter/osf.io,samanehsan/osf.io,brianjgeiger/osf.io,petermalcolm/osf.io,caseyrygt/osf.io,acshi/osf.io,GageGaskins/osf.io,kch8qx/osf.io,HalcyonChimera/osf.io,saradbowman/osf.io,cosenal/osf.io,cwisecarver/osf.io,RomanZWang/osf.io,brianjgeiger/osf.io,acshi/osf.io,mluo613/osf.io,chrisseto/osf.io,brandonPurvis/osf.io,emetsger/osf.io,billyhunt/osf.io,emetsger/osf.io,aaxelb/osf.io,haoyuchen1992/osf.io,adlius/osf.io,doublebits/osf.io,brandonPurvis/osf.io,mfraezz/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,felliott/osf.io,pattisdr/osf.io,alexschiller/osf.io,DanielSBrown/osf.io,cosenal/osf.io,sloria/osf.io,doublebits/osf.io,TomHeatwole/osf.io,arpitar/osf.io,njantrania/osf.io,leb2dg/osf.io,chrisseto/osf.io,Johnetordoff/osf.io,baylee-d/osf.io,leb2dg/osf.io,danielneis/osf.io,TomHeatwole/osf.io,HalcyonChimera/osf.io,mluo613/osf.io,ZobairAlijan/osf.io,cosenal/osf.io,abought/osf.io,samchrisinger/osf.io,ticklemepierce/osf.io,TomBaxter/osf.io,cslzchen/osf.io,billyhunt/osf.io,brianjgeiger/osf.io,brandonPurvis/osf.io,mluke93/osf.io,njantrania/osf.io,zamattiac/osf.io,KAsante95/osf.io,crcresearch/osf.io,RomanZWang/osf.io,GageGaskins/osf.io,RomanZWang/osf.io,samchrisinger/osf.io,mfraezz/osf.io,mluke93/osf.io,felliott/osf.io,mfraezz/osf.io,haoyuchen1992/osf.io,TomHeatwole/osf.io,erinspace/osf.io,caseyrygt/osf.io,cosenal/osf.io,mattclark/osf.io,zachjanicki/osf.io,rdhyee/osf.io,kwierman/osf.io,mattclark/osf.io,arpitar/osf.io,ZobairAlijan/osf.io,caneruguz/osf.io,TomHeatwole/osf.io,chrisseto/osf.io,chennan47/osf.io,chennan47/osf.io,zachjanicki/osf.io,binoculars/osf.io,Johnetordoff/osf.io,monikagrabowska/osf.io,samanehsan/osf.io,mluke93/osf.io,caseyrollins/osf.io,binoculars/osf.io,brianjgeiger/osf.io,sloria/osf.io,jnayak1/osf.io,billyhunt/osf.io,kch8qx/osf.io,mfraezz/osf.io,kwierman/osf.io,zachjanicki/osf.io,aaxelb/osf.io,GageGaskins/osf.io,CenterForOpenScience/osf.io,samchrisinger/osf.io,brandonPurvis/osf.io,caseyrygt/osf.io,laurenrevere/osf.io,erinspace/osf.io,Nesiehr/osf.io,felliott/osf.io,emetsger/osf.io,petermalcolm/osf.io,emetsger/osf.io,KAsante95/osf.io,abought/osf.io,KAsante95/osf.io,petermalcolm/osf.io,billyhunt/osf.io,arpitar/osf.io,kch8qx/osf.io,rdhyee/osf.io,ticklemepierce/osf.io,laurenrevere/osf.io,doublebits/osf.io,ZobairAlijan/osf.io,cslzchen/osf.io,Ghalko/osf.io,mluo613/osf.io,GageGaskins/osf.io,Nesiehr/osf.io,zamattiac/osf.io,ticklemepierce/osf.io,caseyrygt/osf.io,danielneis/osf.io,alexschiller/osf.io,rdhyee/osf.io,monikagrabowska/osf.io,CenterForOpenScience/osf.io,petermalcolm/osf.io,icereval/osf.io,Nesiehr/osf.io,zamattiac/osf.io,monikagrabowska/osf.io,Ghalko/osf.io,felliott/osf.io,baylee-d/osf.io,alexschiller/osf.io,sloria/osf.io,baylee-d/osf.io,KAsante95/osf.io,SSJohns/osf.io,hmoco/osf.io,adlius/osf.io,danielneis/osf.io,hmoco/osf.io,caneruguz/osf.io,GageGaskins/osf.io,asanfilippo7/osf.io,zachjanicki/osf.io,wearpants/osf.io,caseyrollins/osf.io,mluo613/osf.io,DanielSBrown/osf.io,alexschiller/osf.io,aaxelb/osf.io,Ghalko/osf.io,mluo613/osf.io,kwierman/osf.io,alexschiller/osf.io,cslzchen/osf.io,asanfilippo7/osf.io,SSJohns/osf.io,amyshi188/osf.io,kch8qx/osf.io,DanielSBrown/osf.io,samanehsan/osf.io,zamattiac/osf.io,CenterForOpenScience/osf.io,ZobairAlijan/osf.io,chrisseto/osf.io,crcresearch/osf.io,monikagrabowska/osf.io,wearpants/osf.io,aaxelb/osf.io,Johnetordoff/osf.io,Ghalko/osf.io,billyhunt/osf.io,danielneis/osf.io,icereval/osf.io,mluke93/osf.io,samanehsan/osf.io,jnayak1/osf.io,binoculars/osf.io,jnayak1/osf.io,laurenrevere/osf.io,adlius/osf.io,arpitar/osf.io,wearpants/osf.io,kch8qx/osf.io,caneruguz/osf.io,njantrania/osf.io,CenterForOpenScience/osf.io,chennan47/osf.io,acshi/osf.io,cslzchen/osf.io,crcresearch/osf.io,leb2dg/osf.io,adlius/osf.io,RomanZWang/osf.io,ticklemepierce/osf.io,erinspace/osf.io,SSJohns/osf.io,TomBaxter/osf.io,doublebits/osf.io,doublebits/osf.io,RomanZWang/osf.io,rdhyee/osf.io |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
if isinstance(value, list):
for reason in value:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': reason})
else:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': value})
elif isinstance(message, (list, tuple)):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
Add spaces to increase readability.
"OSF-4419" |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
if isinstance(value, list):
for reason in value:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': reason})
else:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': value})
elif isinstance(message, (list, tuple)):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
| <commit_before>
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
if isinstance(value, list):
for reason in value:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': reason})
else:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': value})
elif isinstance(message, (list, tuple)):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
<commit_msg>Add spaces to increase readability.
"OSF-4419"<commit_after> |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
if isinstance(value, list):
for reason in value:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': reason})
else:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': value})
elif isinstance(message, (list, tuple)):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
|
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
if isinstance(value, list):
for reason in value:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': reason})
else:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': value})
elif isinstance(message, (list, tuple)):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
Add spaces to increase readability.
"OSF-4419"
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
if isinstance(value, list):
for reason in value:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': reason})
else:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': value})
elif isinstance(message, (list, tuple)):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
| <commit_before>
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
if isinstance(value, list):
for reason in value:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': reason})
else:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': value})
elif isinstance(message, (list, tuple)):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
<commit_msg>Add spaces to increase readability.
"OSF-4419"<commit_after>
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
if isinstance(value, list):
for reason in value:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': reason})
else:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': value})
elif isinstance(message, (list, tuple)):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
|
511aab30006a5fb4c7ff52bc2cd1a1e42551fad1 | bmi_ilamb/config.py | bmi_ilamb/config.py | """Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def _deserialize_models(self):
models = self._config.get(models_key)
if models is not None:
self._config[models_key] = ' '.join(models)
def get_arguments(self):
args = []
self._set_model_root()
self._deserialize_models()
for k, v in self._config.iteritems():
if (k != ilamb_root_key) and (v is not None):
args.append('--' + k)
args.append(v)
return args
| """Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
confrontations_key = 'confrontations'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def _deserialize_models(self):
models = self._config.get(models_key)
if models is not None:
self._config[models_key] = ' '.join(models)
def _deserialize_confrontations(self):
clash = self._config.get(confrontations_key)
if clash is not None:
self._config[confrontations_key] = ' '.join(clash)
def get_arguments(self):
args = []
self._set_model_root()
self._deserialize_models()
self._deserialize_confrontations()
for k, v in self._config.iteritems():
if (k != ilamb_root_key) and (v is not None):
args.append('--' + k)
args.append(v)
return args
| Allow confrontations to be passed to ilamb-run | Allow confrontations to be passed to ilamb-run
| Python | mit | permamodel/bmi-ilamb | """Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def _deserialize_models(self):
models = self._config.get(models_key)
if models is not None:
self._config[models_key] = ' '.join(models)
def get_arguments(self):
args = []
self._set_model_root()
self._deserialize_models()
for k, v in self._config.iteritems():
if (k != ilamb_root_key) and (v is not None):
args.append('--' + k)
args.append(v)
return args
Allow confrontations to be passed to ilamb-run | """Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
confrontations_key = 'confrontations'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def _deserialize_models(self):
models = self._config.get(models_key)
if models is not None:
self._config[models_key] = ' '.join(models)
def _deserialize_confrontations(self):
clash = self._config.get(confrontations_key)
if clash is not None:
self._config[confrontations_key] = ' '.join(clash)
def get_arguments(self):
args = []
self._set_model_root()
self._deserialize_models()
self._deserialize_confrontations()
for k, v in self._config.iteritems():
if (k != ilamb_root_key) and (v is not None):
args.append('--' + k)
args.append(v)
return args
| <commit_before>"""Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def _deserialize_models(self):
models = self._config.get(models_key)
if models is not None:
self._config[models_key] = ' '.join(models)
def get_arguments(self):
args = []
self._set_model_root()
self._deserialize_models()
for k, v in self._config.iteritems():
if (k != ilamb_root_key) and (v is not None):
args.append('--' + k)
args.append(v)
return args
<commit_msg>Allow confrontations to be passed to ilamb-run<commit_after> | """Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
confrontations_key = 'confrontations'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def _deserialize_models(self):
models = self._config.get(models_key)
if models is not None:
self._config[models_key] = ' '.join(models)
def _deserialize_confrontations(self):
clash = self._config.get(confrontations_key)
if clash is not None:
self._config[confrontations_key] = ' '.join(clash)
def get_arguments(self):
args = []
self._set_model_root()
self._deserialize_models()
self._deserialize_confrontations()
for k, v in self._config.iteritems():
if (k != ilamb_root_key) and (v is not None):
args.append('--' + k)
args.append(v)
return args
| """Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def _deserialize_models(self):
models = self._config.get(models_key)
if models is not None:
self._config[models_key] = ' '.join(models)
def get_arguments(self):
args = []
self._set_model_root()
self._deserialize_models()
for k, v in self._config.iteritems():
if (k != ilamb_root_key) and (v is not None):
args.append('--' + k)
args.append(v)
return args
Allow confrontations to be passed to ilamb-run"""Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
confrontations_key = 'confrontations'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def _deserialize_models(self):
models = self._config.get(models_key)
if models is not None:
self._config[models_key] = ' '.join(models)
def _deserialize_confrontations(self):
clash = self._config.get(confrontations_key)
if clash is not None:
self._config[confrontations_key] = ' '.join(clash)
def get_arguments(self):
args = []
self._set_model_root()
self._deserialize_models()
self._deserialize_confrontations()
for k, v in self._config.iteritems():
if (k != ilamb_root_key) and (v is not None):
args.append('--' + k)
args.append(v)
return args
| <commit_before>"""Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def _deserialize_models(self):
models = self._config.get(models_key)
if models is not None:
self._config[models_key] = ' '.join(models)
def get_arguments(self):
args = []
self._set_model_root()
self._deserialize_models()
for k, v in self._config.iteritems():
if (k != ilamb_root_key) and (v is not None):
args.append('--' + k)
args.append(v)
return args
<commit_msg>Allow confrontations to be passed to ilamb-run<commit_after>"""Reads and parses a configuration file for the ILAMB BMI."""
from os.path import join
import yaml
ilamb_root_key = 'ilamb_root'
model_root_key = 'model_root'
models_key = 'models'
confrontations_key = 'confrontations'
class Configuration(object):
def __init__(self):
self._config = {}
def load(self, filename):
with open(filename, 'r') as fp:
self._config = yaml.load(fp)
def get_ilamb_root(self):
return self._config.get(ilamb_root_key)
def _set_model_root(self):
rel = self._config.get(model_root_key)
if rel is not None:
self._config[model_root_key] = join(self.get_ilamb_root(), rel)
def _deserialize_models(self):
models = self._config.get(models_key)
if models is not None:
self._config[models_key] = ' '.join(models)
def _deserialize_confrontations(self):
clash = self._config.get(confrontations_key)
if clash is not None:
self._config[confrontations_key] = ' '.join(clash)
def get_arguments(self):
args = []
self._set_model_root()
self._deserialize_models()
self._deserialize_confrontations()
for k, v in self._config.iteritems():
if (k != ilamb_root_key) and (v is not None):
args.append('--' + k)
args.append(v)
return args
|
f40dd24af6788e7de7d06254850b83edb179b423 | bootcamp/lesson4.py | bootcamp/lesson4.py | import datetime
import math
from core import test_helper
# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
return datetime.datetime(2015, 06, 01)
# Question 2
# ----------
# Using the math module return pi
def playing_with_math():
return math.pi
def main():
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_dt(), datetime.datetime(2015, 06, 01))
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_math(), math.pi)
if __name__ == '__main__':
main()
| import datetime
import math
from core import test_helper
# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
# Write code here
pass
# Question 2
# ----------
# Using the math module return pi
def playing_with_math():
# Write code here
pass
def main():
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_dt(), datetime.datetime(2015, 06, 01))
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_math(), math.pi)
if __name__ == '__main__':
main()
| Revert "Added solutions for lesson 4" | Revert "Added solutions for lesson 4"
This reverts commit 58d049c78b16ec5b61f9681b605dc4e937ea7e3e.
| Python | mit | infoscout/python-bootcamp-pv | import datetime
import math
from core import test_helper
# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
return datetime.datetime(2015, 06, 01)
# Question 2
# ----------
# Using the math module return pi
def playing_with_math():
return math.pi
def main():
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_dt(), datetime.datetime(2015, 06, 01))
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_math(), math.pi)
if __name__ == '__main__':
main()
Revert "Added solutions for lesson 4"
This reverts commit 58d049c78b16ec5b61f9681b605dc4e937ea7e3e. | import datetime
import math
from core import test_helper
# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
# Write code here
pass
# Question 2
# ----------
# Using the math module return pi
def playing_with_math():
# Write code here
pass
def main():
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_dt(), datetime.datetime(2015, 06, 01))
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_math(), math.pi)
if __name__ == '__main__':
main()
| <commit_before>import datetime
import math
from core import test_helper
# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
return datetime.datetime(2015, 06, 01)
# Question 2
# ----------
# Using the math module return pi
def playing_with_math():
return math.pi
def main():
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_dt(), datetime.datetime(2015, 06, 01))
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_math(), math.pi)
if __name__ == '__main__':
main()
<commit_msg>Revert "Added solutions for lesson 4"
This reverts commit 58d049c78b16ec5b61f9681b605dc4e937ea7e3e.<commit_after> | import datetime
import math
from core import test_helper
# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
# Write code here
pass
# Question 2
# ----------
# Using the math module return pi
def playing_with_math():
# Write code here
pass
def main():
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_dt(), datetime.datetime(2015, 06, 01))
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_math(), math.pi)
if __name__ == '__main__':
main()
| import datetime
import math
from core import test_helper
# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
return datetime.datetime(2015, 06, 01)
# Question 2
# ----------
# Using the math module return pi
def playing_with_math():
return math.pi
def main():
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_dt(), datetime.datetime(2015, 06, 01))
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_math(), math.pi)
if __name__ == '__main__':
main()
Revert "Added solutions for lesson 4"
This reverts commit 58d049c78b16ec5b61f9681b605dc4e937ea7e3e.import datetime
import math
from core import test_helper
# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
# Write code here
pass
# Question 2
# ----------
# Using the math module return pi
def playing_with_math():
# Write code here
pass
def main():
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_dt(), datetime.datetime(2015, 06, 01))
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_math(), math.pi)
if __name__ == '__main__':
main()
| <commit_before>import datetime
import math
from core import test_helper
# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
return datetime.datetime(2015, 06, 01)
# Question 2
# ----------
# Using the math module return pi
def playing_with_math():
return math.pi
def main():
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_dt(), datetime.datetime(2015, 06, 01))
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_math(), math.pi)
if __name__ == '__main__':
main()
<commit_msg>Revert "Added solutions for lesson 4"
This reverts commit 58d049c78b16ec5b61f9681b605dc4e937ea7e3e.<commit_after>import datetime
import math
from core import test_helper
# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
# Write code here
pass
# Question 2
# ----------
# Using the math module return pi
def playing_with_math():
# Write code here
pass
def main():
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_dt(), datetime.datetime(2015, 06, 01))
print "\nRunning playing_with_dt_one function..."
test_helper(playing_with_math(), math.pi)
if __name__ == '__main__':
main()
|
2de0f6d241ccf40f6dd7298db46320c09e7b6967 | bot/project_info.py | bot/project_info.py | # Shared project info
name = 'telegram-bot-framework'
description = 'Python Telegram bot API framework'
source_url = 'https://github.com/alvarogzp/telegram-bot-framework'
author_name = 'Alvaro Gutierrez Perez'
author_email = 'alvarogzp@gmail.com'
author_handle = "@AlvaroGP"
license_name = 'GNU AGPL 3.0'
license_url = 'https://www.gnu.org/licenses/agpl-3.0.en.html'
| # Shared project info
name = 'telegram-bot-framework'
description = 'Python Telegram bot API framework'
source_url = 'https://github.com/alvarogzp/telegram-bot-framework'
author_name = 'Alvaro Gutierrez Perez'
author_email = 'alvarogzp@gmail.com'
author_handle = "@AlvaroGP"
license_name = 'GNU AGPLv3.0+'
license_url = 'https://www.gnu.org/licenses/agpl-3.0.en.html'
| Update license_name to point to AGPLv3+ | Update license_name to point to AGPLv3+
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | # Shared project info
name = 'telegram-bot-framework'
description = 'Python Telegram bot API framework'
source_url = 'https://github.com/alvarogzp/telegram-bot-framework'
author_name = 'Alvaro Gutierrez Perez'
author_email = 'alvarogzp@gmail.com'
author_handle = "@AlvaroGP"
license_name = 'GNU AGPL 3.0'
license_url = 'https://www.gnu.org/licenses/agpl-3.0.en.html'
Update license_name to point to AGPLv3+ | # Shared project info
name = 'telegram-bot-framework'
description = 'Python Telegram bot API framework'
source_url = 'https://github.com/alvarogzp/telegram-bot-framework'
author_name = 'Alvaro Gutierrez Perez'
author_email = 'alvarogzp@gmail.com'
author_handle = "@AlvaroGP"
license_name = 'GNU AGPLv3.0+'
license_url = 'https://www.gnu.org/licenses/agpl-3.0.en.html'
| <commit_before># Shared project info
name = 'telegram-bot-framework'
description = 'Python Telegram bot API framework'
source_url = 'https://github.com/alvarogzp/telegram-bot-framework'
author_name = 'Alvaro Gutierrez Perez'
author_email = 'alvarogzp@gmail.com'
author_handle = "@AlvaroGP"
license_name = 'GNU AGPL 3.0'
license_url = 'https://www.gnu.org/licenses/agpl-3.0.en.html'
<commit_msg>Update license_name to point to AGPLv3+<commit_after> | # Shared project info
name = 'telegram-bot-framework'
description = 'Python Telegram bot API framework'
source_url = 'https://github.com/alvarogzp/telegram-bot-framework'
author_name = 'Alvaro Gutierrez Perez'
author_email = 'alvarogzp@gmail.com'
author_handle = "@AlvaroGP"
license_name = 'GNU AGPLv3.0+'
license_url = 'https://www.gnu.org/licenses/agpl-3.0.en.html'
| # Shared project info
name = 'telegram-bot-framework'
description = 'Python Telegram bot API framework'
source_url = 'https://github.com/alvarogzp/telegram-bot-framework'
author_name = 'Alvaro Gutierrez Perez'
author_email = 'alvarogzp@gmail.com'
author_handle = "@AlvaroGP"
license_name = 'GNU AGPL 3.0'
license_url = 'https://www.gnu.org/licenses/agpl-3.0.en.html'
Update license_name to point to AGPLv3+# Shared project info
name = 'telegram-bot-framework'
description = 'Python Telegram bot API framework'
source_url = 'https://github.com/alvarogzp/telegram-bot-framework'
author_name = 'Alvaro Gutierrez Perez'
author_email = 'alvarogzp@gmail.com'
author_handle = "@AlvaroGP"
license_name = 'GNU AGPLv3.0+'
license_url = 'https://www.gnu.org/licenses/agpl-3.0.en.html'
| <commit_before># Shared project info
name = 'telegram-bot-framework'
description = 'Python Telegram bot API framework'
source_url = 'https://github.com/alvarogzp/telegram-bot-framework'
author_name = 'Alvaro Gutierrez Perez'
author_email = 'alvarogzp@gmail.com'
author_handle = "@AlvaroGP"
license_name = 'GNU AGPL 3.0'
license_url = 'https://www.gnu.org/licenses/agpl-3.0.en.html'
<commit_msg>Update license_name to point to AGPLv3+<commit_after># Shared project info
name = 'telegram-bot-framework'
description = 'Python Telegram bot API framework'
source_url = 'https://github.com/alvarogzp/telegram-bot-framework'
author_name = 'Alvaro Gutierrez Perez'
author_email = 'alvarogzp@gmail.com'
author_handle = "@AlvaroGP"
license_name = 'GNU AGPLv3.0+'
license_url = 'https://www.gnu.org/licenses/agpl-3.0.en.html'
|
805f77ac20952c6015a26403041b9b7b3a543ab4 | danceschool/core/migrations/0041_invoiceitem_calculate_taxrate.py | danceschool/core/migrations/0041_invoiceitem_calculate_taxrate.py | # Generated by Django 3.1.6 on 2021-02-20 15:24
from django.db import migrations
from django.db.models import F
def calculate_taxrate(apps, schema_editor):
'''
Calculate the tax rate based on current totals for any InvoiceItem that
does not currently have a tax rate, so that we can make taxRate non-nullable.
'''
InvoiceItem = apps.get_model("core", "InvoiceItem")
db_alias = schema_editor.connection.alias
to_update = InvoiceItem.objects.using(db_alias).filter(taxRate__isnull=True)
to_update.update(taxRate=100 * (F('taxes') / F('total')))
class Migration(migrations.Migration):
dependencies = [
('core', '0040_invoiceitem_taxrate'),
]
operations = [
migrations.RunPython(calculate_taxrate, migrations.RunPython.noop),
]
| # Generated by Django 3.1.6 on 2021-02-20 15:24
from django.db import migrations
from django.db.models import F
def calculate_taxrate(apps, schema_editor):
'''
Calculate the tax rate based on current totals for any InvoiceItem that
does not currently have a tax rate, so that we can make taxRate non-nullable.
'''
InvoiceItem = apps.get_model("core", "InvoiceItem")
db_alias = schema_editor.connection.alias
to_update = InvoiceItem.objects.using(db_alias).filter(taxRate__isnull=True).exclude(total=0)
to_update.update(taxRate=100 * (F('taxes') / F('total')))
to_update = InvoiceItem.objects.using(db_alias).filter(taxRate__isnull=True)
to_update.update(taxRate=0)
class Migration(migrations.Migration):
dependencies = [
('core', '0040_invoiceitem_taxrate'),
]
operations = [
migrations.RunPython(calculate_taxrate, migrations.RunPython.noop),
]
| Fix division by zero error when calculating tax rate on migration. | Fix division by zero error when calculating tax rate on migration.
| Python | bsd-3-clause | django-danceschool/django-danceschool,django-danceschool/django-danceschool,django-danceschool/django-danceschool | # Generated by Django 3.1.6 on 2021-02-20 15:24
from django.db import migrations
from django.db.models import F
def calculate_taxrate(apps, schema_editor):
'''
Calculate the tax rate based on current totals for any InvoiceItem that
does not currently have a tax rate, so that we can make taxRate non-nullable.
'''
InvoiceItem = apps.get_model("core", "InvoiceItem")
db_alias = schema_editor.connection.alias
to_update = InvoiceItem.objects.using(db_alias).filter(taxRate__isnull=True)
to_update.update(taxRate=100 * (F('taxes') / F('total')))
class Migration(migrations.Migration):
dependencies = [
('core', '0040_invoiceitem_taxrate'),
]
operations = [
migrations.RunPython(calculate_taxrate, migrations.RunPython.noop),
]
Fix division by zero error when calculating tax rate on migration. | # Generated by Django 3.1.6 on 2021-02-20 15:24
from django.db import migrations
from django.db.models import F
def calculate_taxrate(apps, schema_editor):
'''
Calculate the tax rate based on current totals for any InvoiceItem that
does not currently have a tax rate, so that we can make taxRate non-nullable.
'''
InvoiceItem = apps.get_model("core", "InvoiceItem")
db_alias = schema_editor.connection.alias
to_update = InvoiceItem.objects.using(db_alias).filter(taxRate__isnull=True).exclude(total=0)
to_update.update(taxRate=100 * (F('taxes') / F('total')))
to_update = InvoiceItem.objects.using(db_alias).filter(taxRate__isnull=True)
to_update.update(taxRate=0)
class Migration(migrations.Migration):
dependencies = [
('core', '0040_invoiceitem_taxrate'),
]
operations = [
migrations.RunPython(calculate_taxrate, migrations.RunPython.noop),
]
| <commit_before># Generated by Django 3.1.6 on 2021-02-20 15:24
from django.db import migrations
from django.db.models import F
def calculate_taxrate(apps, schema_editor):
'''
Calculate the tax rate based on current totals for any InvoiceItem that
does not currently have a tax rate, so that we can make taxRate non-nullable.
'''
InvoiceItem = apps.get_model("core", "InvoiceItem")
db_alias = schema_editor.connection.alias
to_update = InvoiceItem.objects.using(db_alias).filter(taxRate__isnull=True)
to_update.update(taxRate=100 * (F('taxes') / F('total')))
class Migration(migrations.Migration):
dependencies = [
('core', '0040_invoiceitem_taxrate'),
]
operations = [
migrations.RunPython(calculate_taxrate, migrations.RunPython.noop),
]
<commit_msg>Fix division by zero error when calculating tax rate on migration.<commit_after> | # Generated by Django 3.1.6 on 2021-02-20 15:24
from django.db import migrations
from django.db.models import F
def calculate_taxrate(apps, schema_editor):
'''
Calculate the tax rate based on current totals for any InvoiceItem that
does not currently have a tax rate, so that we can make taxRate non-nullable.
'''
InvoiceItem = apps.get_model("core", "InvoiceItem")
db_alias = schema_editor.connection.alias
to_update = InvoiceItem.objects.using(db_alias).filter(taxRate__isnull=True).exclude(total=0)
to_update.update(taxRate=100 * (F('taxes') / F('total')))
to_update = InvoiceItem.objects.using(db_alias).filter(taxRate__isnull=True)
to_update.update(taxRate=0)
class Migration(migrations.Migration):
dependencies = [
('core', '0040_invoiceitem_taxrate'),
]
operations = [
migrations.RunPython(calculate_taxrate, migrations.RunPython.noop),
]
| # Generated by Django 3.1.6 on 2021-02-20 15:24
from django.db import migrations
from django.db.models import F
def calculate_taxrate(apps, schema_editor):
'''
Calculate the tax rate based on current totals for any InvoiceItem that
does not currently have a tax rate, so that we can make taxRate non-nullable.
'''
InvoiceItem = apps.get_model("core", "InvoiceItem")
db_alias = schema_editor.connection.alias
to_update = InvoiceItem.objects.using(db_alias).filter(taxRate__isnull=True)
to_update.update(taxRate=100 * (F('taxes') / F('total')))
class Migration(migrations.Migration):
dependencies = [
('core', '0040_invoiceitem_taxrate'),
]
operations = [
migrations.RunPython(calculate_taxrate, migrations.RunPython.noop),
]
Fix division by zero error when calculating tax rate on migration.# Generated by Django 3.1.6 on 2021-02-20 15:24
from django.db import migrations
from django.db.models import F
def calculate_taxrate(apps, schema_editor):
'''
Calculate the tax rate based on current totals for any InvoiceItem that
does not currently have a tax rate, so that we can make taxRate non-nullable.
'''
InvoiceItem = apps.get_model("core", "InvoiceItem")
db_alias = schema_editor.connection.alias
to_update = InvoiceItem.objects.using(db_alias).filter(taxRate__isnull=True).exclude(total=0)
to_update.update(taxRate=100 * (F('taxes') / F('total')))
to_update = InvoiceItem.objects.using(db_alias).filter(taxRate__isnull=True)
to_update.update(taxRate=0)
class Migration(migrations.Migration):
dependencies = [
('core', '0040_invoiceitem_taxrate'),
]
operations = [
migrations.RunPython(calculate_taxrate, migrations.RunPython.noop),
]
| <commit_before># Generated by Django 3.1.6 on 2021-02-20 15:24
from django.db import migrations
from django.db.models import F
def calculate_taxrate(apps, schema_editor):
'''
Calculate the tax rate based on current totals for any InvoiceItem that
does not currently have a tax rate, so that we can make taxRate non-nullable.
'''
InvoiceItem = apps.get_model("core", "InvoiceItem")
db_alias = schema_editor.connection.alias
to_update = InvoiceItem.objects.using(db_alias).filter(taxRate__isnull=True)
to_update.update(taxRate=100 * (F('taxes') / F('total')))
class Migration(migrations.Migration):
dependencies = [
('core', '0040_invoiceitem_taxrate'),
]
operations = [
migrations.RunPython(calculate_taxrate, migrations.RunPython.noop),
]
<commit_msg>Fix division by zero error when calculating tax rate on migration.<commit_after># Generated by Django 3.1.6 on 2021-02-20 15:24
from django.db import migrations
from django.db.models import F
def calculate_taxrate(apps, schema_editor):
'''
Calculate the tax rate based on current totals for any InvoiceItem that
does not currently have a tax rate, so that we can make taxRate non-nullable.
'''
InvoiceItem = apps.get_model("core", "InvoiceItem")
db_alias = schema_editor.connection.alias
to_update = InvoiceItem.objects.using(db_alias).filter(taxRate__isnull=True).exclude(total=0)
to_update.update(taxRate=100 * (F('taxes') / F('total')))
to_update = InvoiceItem.objects.using(db_alias).filter(taxRate__isnull=True)
to_update.update(taxRate=0)
class Migration(migrations.Migration):
dependencies = [
('core', '0040_invoiceitem_taxrate'),
]
operations = [
migrations.RunPython(calculate_taxrate, migrations.RunPython.noop),
]
|
e1d61d945300dde9cb5ac07228b7892b224a984c | tests/commands/load/test_load_cnv_report_cmd.py | tests/commands/load/test_load_cnv_report_cmd.py | # -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(cli, ["load", "cnv-report", case_obj["_id"], cnv_report_path, "-u"],)
assert "saved report to case!" in result.output
assert result.exit_code == 0
def test_invalid_path_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(cli, ["load", "cnv-report", case_obj["_id"], "invalid-path", "-u"],)
assert 'Path "invalid-path" does not exist.' in result.output
assert result.exit_code == 2
| # -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(
cli,
["load", "cnv-report", case_obj["_id"], cnv_report_path, "-u"],
)
assert "saved report to case!" in result.output
assert result.exit_code == 0
def test_invalid_path_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(
cli,
["load", "cnv-report", case_obj["_id"], "invalid-path", "-u"],
)
assert 'Path "invalid-path" does not exist.' in result.output
assert result.exit_code == 2
| Fix code style issues with Black | Fix code style issues with Black
| Python | bsd-3-clause | Clinical-Genomics/scout,Clinical-Genomics/scout,Clinical-Genomics/scout | # -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(cli, ["load", "cnv-report", case_obj["_id"], cnv_report_path, "-u"],)
assert "saved report to case!" in result.output
assert result.exit_code == 0
def test_invalid_path_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(cli, ["load", "cnv-report", case_obj["_id"], "invalid-path", "-u"],)
assert 'Path "invalid-path" does not exist.' in result.output
assert result.exit_code == 2
Fix code style issues with Black | # -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(
cli,
["load", "cnv-report", case_obj["_id"], cnv_report_path, "-u"],
)
assert "saved report to case!" in result.output
assert result.exit_code == 0
def test_invalid_path_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(
cli,
["load", "cnv-report", case_obj["_id"], "invalid-path", "-u"],
)
assert 'Path "invalid-path" does not exist.' in result.output
assert result.exit_code == 2
| <commit_before># -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(cli, ["load", "cnv-report", case_obj["_id"], cnv_report_path, "-u"],)
assert "saved report to case!" in result.output
assert result.exit_code == 0
def test_invalid_path_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(cli, ["load", "cnv-report", case_obj["_id"], "invalid-path", "-u"],)
assert 'Path "invalid-path" does not exist.' in result.output
assert result.exit_code == 2
<commit_msg>Fix code style issues with Black<commit_after> | # -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(
cli,
["load", "cnv-report", case_obj["_id"], cnv_report_path, "-u"],
)
assert "saved report to case!" in result.output
assert result.exit_code == 0
def test_invalid_path_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(
cli,
["load", "cnv-report", case_obj["_id"], "invalid-path", "-u"],
)
assert 'Path "invalid-path" does not exist.' in result.output
assert result.exit_code == 2
| # -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(cli, ["load", "cnv-report", case_obj["_id"], cnv_report_path, "-u"],)
assert "saved report to case!" in result.output
assert result.exit_code == 0
def test_invalid_path_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(cli, ["load", "cnv-report", case_obj["_id"], "invalid-path", "-u"],)
assert 'Path "invalid-path" does not exist.' in result.output
assert result.exit_code == 2
Fix code style issues with Black# -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(
cli,
["load", "cnv-report", case_obj["_id"], cnv_report_path, "-u"],
)
assert "saved report to case!" in result.output
assert result.exit_code == 0
def test_invalid_path_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(
cli,
["load", "cnv-report", case_obj["_id"], "invalid-path", "-u"],
)
assert 'Path "invalid-path" does not exist.' in result.output
assert result.exit_code == 2
| <commit_before># -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(cli, ["load", "cnv-report", case_obj["_id"], cnv_report_path, "-u"],)
assert "saved report to case!" in result.output
assert result.exit_code == 0
def test_invalid_path_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(cli, ["load", "cnv-report", case_obj["_id"], "invalid-path", "-u"],)
assert 'Path "invalid-path" does not exist.' in result.output
assert result.exit_code == 2
<commit_msg>Fix code style issues with Black<commit_after># -*- coding: utf-8 -*-
import os
from scout.demo import cnv_report_path
from scout.commands import cli
def test_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(cnv_report_path)
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(
cli,
["load", "cnv-report", case_obj["_id"], cnv_report_path, "-u"],
)
assert "saved report to case!" in result.output
assert result.exit_code == 0
def test_invalid_path_load_cnv_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
runner = mock_app.test_cli_runner()
assert runner
# Test CLI function
result = runner.invoke(
cli,
["load", "cnv-report", case_obj["_id"], "invalid-path", "-u"],
)
assert 'Path "invalid-path" does not exist.' in result.output
assert result.exit_code == 2
|
e9df4858631d9efdcb6a5b960c25f64cae875661 | blog/models.py | blog/models.py | from django.db import models
from organizer.models import Startup, Tag
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Post(models.Model):
title = models.CharField(max_length=63)
slug = models.SlugField()
text = models.TextField()
pub_date = models.DateField()
tags = models.ManyToManyField(Tag)
startups = models.ManyToManyField(Startup)
| from django.db import models
from organizer.models import Startup, Tag
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Post(models.Model):
title = models.CharField(max_length=63)
slug = models.SlugField(
max_length=63,
help_text='A label for URL config',
unique_for_month='pub_date')
text = models.TextField()
pub_date = models.DateField(
'date published',
auto_now_add=True)
tags = models.ManyToManyField(
Tag, related_name='blog_posts')
startups = models.ManyToManyField(
Startup, related_name='blog_posts')
| Add options to Post model fields. | Ch03: Add options to Post model fields. [skip ci]
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 | from django.db import models
from organizer.models import Startup, Tag
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Post(models.Model):
title = models.CharField(max_length=63)
slug = models.SlugField()
text = models.TextField()
pub_date = models.DateField()
tags = models.ManyToManyField(Tag)
startups = models.ManyToManyField(Startup)
Ch03: Add options to Post model fields. [skip ci] | from django.db import models
from organizer.models import Startup, Tag
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Post(models.Model):
title = models.CharField(max_length=63)
slug = models.SlugField(
max_length=63,
help_text='A label for URL config',
unique_for_month='pub_date')
text = models.TextField()
pub_date = models.DateField(
'date published',
auto_now_add=True)
tags = models.ManyToManyField(
Tag, related_name='blog_posts')
startups = models.ManyToManyField(
Startup, related_name='blog_posts')
| <commit_before>from django.db import models
from organizer.models import Startup, Tag
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Post(models.Model):
title = models.CharField(max_length=63)
slug = models.SlugField()
text = models.TextField()
pub_date = models.DateField()
tags = models.ManyToManyField(Tag)
startups = models.ManyToManyField(Startup)
<commit_msg>Ch03: Add options to Post model fields. [skip ci]<commit_after> | from django.db import models
from organizer.models import Startup, Tag
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Post(models.Model):
title = models.CharField(max_length=63)
slug = models.SlugField(
max_length=63,
help_text='A label for URL config',
unique_for_month='pub_date')
text = models.TextField()
pub_date = models.DateField(
'date published',
auto_now_add=True)
tags = models.ManyToManyField(
Tag, related_name='blog_posts')
startups = models.ManyToManyField(
Startup, related_name='blog_posts')
| from django.db import models
from organizer.models import Startup, Tag
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Post(models.Model):
title = models.CharField(max_length=63)
slug = models.SlugField()
text = models.TextField()
pub_date = models.DateField()
tags = models.ManyToManyField(Tag)
startups = models.ManyToManyField(Startup)
Ch03: Add options to Post model fields. [skip ci]from django.db import models
from organizer.models import Startup, Tag
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Post(models.Model):
title = models.CharField(max_length=63)
slug = models.SlugField(
max_length=63,
help_text='A label for URL config',
unique_for_month='pub_date')
text = models.TextField()
pub_date = models.DateField(
'date published',
auto_now_add=True)
tags = models.ManyToManyField(
Tag, related_name='blog_posts')
startups = models.ManyToManyField(
Startup, related_name='blog_posts')
| <commit_before>from django.db import models
from organizer.models import Startup, Tag
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Post(models.Model):
title = models.CharField(max_length=63)
slug = models.SlugField()
text = models.TextField()
pub_date = models.DateField()
tags = models.ManyToManyField(Tag)
startups = models.ManyToManyField(Startup)
<commit_msg>Ch03: Add options to Post model fields. [skip ci]<commit_after>from django.db import models
from organizer.models import Startup, Tag
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Post(models.Model):
title = models.CharField(max_length=63)
slug = models.SlugField(
max_length=63,
help_text='A label for URL config',
unique_for_month='pub_date')
text = models.TextField()
pub_date = models.DateField(
'date published',
auto_now_add=True)
tags = models.ManyToManyField(
Tag, related_name='blog_posts')
startups = models.ManyToManyField(
Startup, related_name='blog_posts')
|
d45391429f01d5d4ea22e28bef39a2bb419df04f | djangae/apps.py | djangae/apps.py | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
class DjangaeConfig(AppConfig):
name = 'djangae'
verbose_name = _("Djangae")
def ready(self):
from djangae.db.backends.appengine.caching import reset_context
from django.core.signals import request_finished, request_started
request_finished.connect(reset_context, dispatch_uid="request_finished_context_reset")
request_started.connect(reset_context, dispatch_uid="request_started_context_reset")
from django.conf import settings
if 'django.contrib.contenttypes' in settings.INSTALLED_APPS and (
not 'djangae.contrib.contenttypes' in settings.INSTALLED_APPS):
raise ImproperlyConfigured(
"If you're using django.contrib.contenttypes, then you need "
"to add djangae.contrib.contenttypes to INSTALLED_APPS after "
"django.contrib.contenttypes."
)
| from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
class DjangaeConfig(AppConfig):
name = 'djangae'
verbose_name = _("Djangae")
def ready(self):
from djangae.db.backends.appengine.caching import reset_context
from django.core.signals import request_finished, request_started
request_finished.connect(reset_context, dispatch_uid="request_finished_context_reset")
request_started.connect(reset_context, dispatch_uid="request_started_context_reset")
from django.conf import settings
contenttype_configuration_error = ImproperlyConfigured(
"If you're using django.contrib.contenttypes, then you need "
"to add djangae.contrib.contenttypes to INSTALLED_APPS after "
"django.contrib.contenttypes."
)
if 'django.contrib.contenttypes' in settings.INSTALLED_APPS:
if not 'djangae.contrib.contenttypes' in settings.INSTALLED_APPS:
# Raise error if User is using Django CT, but not Djangae
raise contenttype_configuration_error
else:
if settings.INSTALLED_APPS.index('django.contrib.contenttypes') > \
settings.INSTALLED_APPS.index('djangae.contrib.contenttypes'):
# Raise error if User is using both Django and Djangae CT, but
# Django CT comes after Djangae CT
raise contenttype_configuration_error
| Raise configuration error if django.contrib.contenttypes comes after djangae.contrib.contenttypes | Raise configuration error if django.contrib.contenttypes comes after djangae.contrib.contenttypes
| Python | bsd-3-clause | potatolondon/djangae,grzes/djangae,kirberich/djangae,kirberich/djangae,kirberich/djangae,grzes/djangae,potatolondon/djangae,grzes/djangae | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
class DjangaeConfig(AppConfig):
name = 'djangae'
verbose_name = _("Djangae")
def ready(self):
from djangae.db.backends.appengine.caching import reset_context
from django.core.signals import request_finished, request_started
request_finished.connect(reset_context, dispatch_uid="request_finished_context_reset")
request_started.connect(reset_context, dispatch_uid="request_started_context_reset")
from django.conf import settings
if 'django.contrib.contenttypes' in settings.INSTALLED_APPS and (
not 'djangae.contrib.contenttypes' in settings.INSTALLED_APPS):
raise ImproperlyConfigured(
"If you're using django.contrib.contenttypes, then you need "
"to add djangae.contrib.contenttypes to INSTALLED_APPS after "
"django.contrib.contenttypes."
)
Raise configuration error if django.contrib.contenttypes comes after djangae.contrib.contenttypes | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
class DjangaeConfig(AppConfig):
name = 'djangae'
verbose_name = _("Djangae")
def ready(self):
from djangae.db.backends.appengine.caching import reset_context
from django.core.signals import request_finished, request_started
request_finished.connect(reset_context, dispatch_uid="request_finished_context_reset")
request_started.connect(reset_context, dispatch_uid="request_started_context_reset")
from django.conf import settings
contenttype_configuration_error = ImproperlyConfigured(
"If you're using django.contrib.contenttypes, then you need "
"to add djangae.contrib.contenttypes to INSTALLED_APPS after "
"django.contrib.contenttypes."
)
if 'django.contrib.contenttypes' in settings.INSTALLED_APPS:
if not 'djangae.contrib.contenttypes' in settings.INSTALLED_APPS:
# Raise error if User is using Django CT, but not Djangae
raise contenttype_configuration_error
else:
if settings.INSTALLED_APPS.index('django.contrib.contenttypes') > \
settings.INSTALLED_APPS.index('djangae.contrib.contenttypes'):
# Raise error if User is using both Django and Djangae CT, but
# Django CT comes after Djangae CT
raise contenttype_configuration_error
| <commit_before>from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
class DjangaeConfig(AppConfig):
name = 'djangae'
verbose_name = _("Djangae")
def ready(self):
from djangae.db.backends.appengine.caching import reset_context
from django.core.signals import request_finished, request_started
request_finished.connect(reset_context, dispatch_uid="request_finished_context_reset")
request_started.connect(reset_context, dispatch_uid="request_started_context_reset")
from django.conf import settings
if 'django.contrib.contenttypes' in settings.INSTALLED_APPS and (
not 'djangae.contrib.contenttypes' in settings.INSTALLED_APPS):
raise ImproperlyConfigured(
"If you're using django.contrib.contenttypes, then you need "
"to add djangae.contrib.contenttypes to INSTALLED_APPS after "
"django.contrib.contenttypes."
)
<commit_msg>Raise configuration error if django.contrib.contenttypes comes after djangae.contrib.contenttypes<commit_after> | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
class DjangaeConfig(AppConfig):
name = 'djangae'
verbose_name = _("Djangae")
def ready(self):
from djangae.db.backends.appengine.caching import reset_context
from django.core.signals import request_finished, request_started
request_finished.connect(reset_context, dispatch_uid="request_finished_context_reset")
request_started.connect(reset_context, dispatch_uid="request_started_context_reset")
from django.conf import settings
contenttype_configuration_error = ImproperlyConfigured(
"If you're using django.contrib.contenttypes, then you need "
"to add djangae.contrib.contenttypes to INSTALLED_APPS after "
"django.contrib.contenttypes."
)
if 'django.contrib.contenttypes' in settings.INSTALLED_APPS:
if not 'djangae.contrib.contenttypes' in settings.INSTALLED_APPS:
# Raise error if User is using Django CT, but not Djangae
raise contenttype_configuration_error
else:
if settings.INSTALLED_APPS.index('django.contrib.contenttypes') > \
settings.INSTALLED_APPS.index('djangae.contrib.contenttypes'):
# Raise error if User is using both Django and Djangae CT, but
# Django CT comes after Djangae CT
raise contenttype_configuration_error
| from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
class DjangaeConfig(AppConfig):
name = 'djangae'
verbose_name = _("Djangae")
def ready(self):
from djangae.db.backends.appengine.caching import reset_context
from django.core.signals import request_finished, request_started
request_finished.connect(reset_context, dispatch_uid="request_finished_context_reset")
request_started.connect(reset_context, dispatch_uid="request_started_context_reset")
from django.conf import settings
if 'django.contrib.contenttypes' in settings.INSTALLED_APPS and (
not 'djangae.contrib.contenttypes' in settings.INSTALLED_APPS):
raise ImproperlyConfigured(
"If you're using django.contrib.contenttypes, then you need "
"to add djangae.contrib.contenttypes to INSTALLED_APPS after "
"django.contrib.contenttypes."
)
Raise configuration error if django.contrib.contenttypes comes after djangae.contrib.contenttypesfrom django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
class DjangaeConfig(AppConfig):
name = 'djangae'
verbose_name = _("Djangae")
def ready(self):
from djangae.db.backends.appengine.caching import reset_context
from django.core.signals import request_finished, request_started
request_finished.connect(reset_context, dispatch_uid="request_finished_context_reset")
request_started.connect(reset_context, dispatch_uid="request_started_context_reset")
from django.conf import settings
contenttype_configuration_error = ImproperlyConfigured(
"If you're using django.contrib.contenttypes, then you need "
"to add djangae.contrib.contenttypes to INSTALLED_APPS after "
"django.contrib.contenttypes."
)
if 'django.contrib.contenttypes' in settings.INSTALLED_APPS:
if not 'djangae.contrib.contenttypes' in settings.INSTALLED_APPS:
# Raise error if User is using Django CT, but not Djangae
raise contenttype_configuration_error
else:
if settings.INSTALLED_APPS.index('django.contrib.contenttypes') > \
settings.INSTALLED_APPS.index('djangae.contrib.contenttypes'):
# Raise error if User is using both Django and Djangae CT, but
# Django CT comes after Djangae CT
raise contenttype_configuration_error
| <commit_before>from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
class DjangaeConfig(AppConfig):
name = 'djangae'
verbose_name = _("Djangae")
def ready(self):
from djangae.db.backends.appengine.caching import reset_context
from django.core.signals import request_finished, request_started
request_finished.connect(reset_context, dispatch_uid="request_finished_context_reset")
request_started.connect(reset_context, dispatch_uid="request_started_context_reset")
from django.conf import settings
if 'django.contrib.contenttypes' in settings.INSTALLED_APPS and (
not 'djangae.contrib.contenttypes' in settings.INSTALLED_APPS):
raise ImproperlyConfigured(
"If you're using django.contrib.contenttypes, then you need "
"to add djangae.contrib.contenttypes to INSTALLED_APPS after "
"django.contrib.contenttypes."
)
<commit_msg>Raise configuration error if django.contrib.contenttypes comes after djangae.contrib.contenttypes<commit_after>from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
class DjangaeConfig(AppConfig):
name = 'djangae'
verbose_name = _("Djangae")
def ready(self):
from djangae.db.backends.appengine.caching import reset_context
from django.core.signals import request_finished, request_started
request_finished.connect(reset_context, dispatch_uid="request_finished_context_reset")
request_started.connect(reset_context, dispatch_uid="request_started_context_reset")
from django.conf import settings
contenttype_configuration_error = ImproperlyConfigured(
"If you're using django.contrib.contenttypes, then you need "
"to add djangae.contrib.contenttypes to INSTALLED_APPS after "
"django.contrib.contenttypes."
)
if 'django.contrib.contenttypes' in settings.INSTALLED_APPS:
if not 'djangae.contrib.contenttypes' in settings.INSTALLED_APPS:
# Raise error if User is using Django CT, but not Djangae
raise contenttype_configuration_error
else:
if settings.INSTALLED_APPS.index('django.contrib.contenttypes') > \
settings.INSTALLED_APPS.index('djangae.contrib.contenttypes'):
# Raise error if User is using both Django and Djangae CT, but
# Django CT comes after Djangae CT
raise contenttype_configuration_error
|
762d87014d87d986aa83703f216e5cd2b52ce2f3 | brink/utils.py | brink/utils.py | import importlib
def resolve_func(func_string):
module_name, func_name = func_string.rsplit(".", 1)
module = importlib.import_module(module_name)
func = getattr(module, func_name)
if not func:
raise ImportError(name=func_name, path=func_string)
return func
def get_config():
conf = importlib.import_module("config")
return conf
def get_app_models(app):
# TODO: Fix ugly workaround
from brink.models import Model, ModelBase
module = importlib.import_module("%s.models" % app)
return [model for _, model in module.__dict__.items()
if isinstance(model, ModelBase) and model is not Model]
| import importlib
def resolve_func(func_string):
module_name, func_name = func_string.rsplit(".", 1)
module = importlib.import_module(module_name)
func = getattr(module, func_name)
if not func:
raise ImportError(name=func_name, path=func_string)
return func
def get_config():
conf = importlib.import_module("config")
return conf
def get_app_models(app):
# TODO: Fix ugly workaround
from brink.models import Model, ModelBase
module_name = "%s.models" % app
module = importlib.import_module(module_name)
return [model for _, model in module.__dict__.items()
if isinstance(model, ModelBase) and
model is not Model and
model.__module__ == module_name]
| Make get_app_models only import models from the specified module, and not imported ones | Make get_app_models only import models from the specified module, and not imported ones
| Python | bsd-3-clause | brinkframework/brink | import importlib
def resolve_func(func_string):
module_name, func_name = func_string.rsplit(".", 1)
module = importlib.import_module(module_name)
func = getattr(module, func_name)
if not func:
raise ImportError(name=func_name, path=func_string)
return func
def get_config():
conf = importlib.import_module("config")
return conf
def get_app_models(app):
# TODO: Fix ugly workaround
from brink.models import Model, ModelBase
module = importlib.import_module("%s.models" % app)
return [model for _, model in module.__dict__.items()
if isinstance(model, ModelBase) and model is not Model]
Make get_app_models only import models from the specified module, and not imported ones | import importlib
def resolve_func(func_string):
module_name, func_name = func_string.rsplit(".", 1)
module = importlib.import_module(module_name)
func = getattr(module, func_name)
if not func:
raise ImportError(name=func_name, path=func_string)
return func
def get_config():
conf = importlib.import_module("config")
return conf
def get_app_models(app):
# TODO: Fix ugly workaround
from brink.models import Model, ModelBase
module_name = "%s.models" % app
module = importlib.import_module(module_name)
return [model for _, model in module.__dict__.items()
if isinstance(model, ModelBase) and
model is not Model and
model.__module__ == module_name]
| <commit_before>import importlib
def resolve_func(func_string):
module_name, func_name = func_string.rsplit(".", 1)
module = importlib.import_module(module_name)
func = getattr(module, func_name)
if not func:
raise ImportError(name=func_name, path=func_string)
return func
def get_config():
conf = importlib.import_module("config")
return conf
def get_app_models(app):
# TODO: Fix ugly workaround
from brink.models import Model, ModelBase
module = importlib.import_module("%s.models" % app)
return [model for _, model in module.__dict__.items()
if isinstance(model, ModelBase) and model is not Model]
<commit_msg>Make get_app_models only import models from the specified module, and not imported ones<commit_after> | import importlib
def resolve_func(func_string):
module_name, func_name = func_string.rsplit(".", 1)
module = importlib.import_module(module_name)
func = getattr(module, func_name)
if not func:
raise ImportError(name=func_name, path=func_string)
return func
def get_config():
conf = importlib.import_module("config")
return conf
def get_app_models(app):
# TODO: Fix ugly workaround
from brink.models import Model, ModelBase
module_name = "%s.models" % app
module = importlib.import_module(module_name)
return [model for _, model in module.__dict__.items()
if isinstance(model, ModelBase) and
model is not Model and
model.__module__ == module_name]
| import importlib
def resolve_func(func_string):
module_name, func_name = func_string.rsplit(".", 1)
module = importlib.import_module(module_name)
func = getattr(module, func_name)
if not func:
raise ImportError(name=func_name, path=func_string)
return func
def get_config():
conf = importlib.import_module("config")
return conf
def get_app_models(app):
# TODO: Fix ugly workaround
from brink.models import Model, ModelBase
module = importlib.import_module("%s.models" % app)
return [model for _, model in module.__dict__.items()
if isinstance(model, ModelBase) and model is not Model]
Make get_app_models only import models from the specified module, and not imported onesimport importlib
def resolve_func(func_string):
module_name, func_name = func_string.rsplit(".", 1)
module = importlib.import_module(module_name)
func = getattr(module, func_name)
if not func:
raise ImportError(name=func_name, path=func_string)
return func
def get_config():
conf = importlib.import_module("config")
return conf
def get_app_models(app):
# TODO: Fix ugly workaround
from brink.models import Model, ModelBase
module_name = "%s.models" % app
module = importlib.import_module(module_name)
return [model for _, model in module.__dict__.items()
if isinstance(model, ModelBase) and
model is not Model and
model.__module__ == module_name]
| <commit_before>import importlib
def resolve_func(func_string):
module_name, func_name = func_string.rsplit(".", 1)
module = importlib.import_module(module_name)
func = getattr(module, func_name)
if not func:
raise ImportError(name=func_name, path=func_string)
return func
def get_config():
conf = importlib.import_module("config")
return conf
def get_app_models(app):
# TODO: Fix ugly workaround
from brink.models import Model, ModelBase
module = importlib.import_module("%s.models" % app)
return [model for _, model in module.__dict__.items()
if isinstance(model, ModelBase) and model is not Model]
<commit_msg>Make get_app_models only import models from the specified module, and not imported ones<commit_after>import importlib
def resolve_func(func_string):
module_name, func_name = func_string.rsplit(".", 1)
module = importlib.import_module(module_name)
func = getattr(module, func_name)
if not func:
raise ImportError(name=func_name, path=func_string)
return func
def get_config():
conf = importlib.import_module("config")
return conf
def get_app_models(app):
# TODO: Fix ugly workaround
from brink.models import Model, ModelBase
module_name = "%s.models" % app
module = importlib.import_module(module_name)
return [model for _, model in module.__dict__.items()
if isinstance(model, ModelBase) and
model is not Model and
model.__module__ == module_name]
|
f213984ad3dfd8922578346baeeb97d60fab742a | cinje/inline/use.py | cinje/inline/use.py | # encoding: utf-8
from ..util import pypy, ensure_buffer
PREFIX = '_buffer.extend(' if pypy else '__w('
class Use(object):
"""Consume the result of calling another template function, extending the local buffer.
This is meant to consume non-wrapping template functions. For wrapping functions see ": using" instead.
Syntax:
: use <name-constant> [<arguments>]
The name constant must resolve to a generator function that participates in the cinje "yielded buffer" protocol.
"""
priority = 25
def match(self, context, line):
"""Match code lines prefixed with a "use" keyword."""
return line.kind == 'code' and line.partitioned[0] == "use"
def __call__(self, context):
"""Wrap the expression in a `_buffer.extend()` call."""
input = context.input
declaration = input.next()
parts = declaration.partitioned[1] # Ignore the "use" part, we care about the name and arguments.
name, _, args = parts.partition(' ')
for i in ensure_buffer(context):
yield i
yield declaration.clone(line=PREFIX + name.rstrip() + "(" + args.lstrip() + "))")
context.flag.add('dirty')
| # encoding: utf-8
from ..util import py, pypy, ensure_buffer
PREFIX = '_buffer.extend(' if pypy else '__w('
class Use(object):
"""Consume the result of calling another template function, extending the local buffer.
This is meant to consume non-wrapping template functions. For wrapping functions see ": using" instead.
Syntax:
: use <name-constant> [<arguments>]
The name constant must resolve to a generator function that participates in the cinje "yielded buffer" protocol.
"""
priority = 25
def match(self, context, line):
"""Match code lines prefixed with a "use" keyword."""
return line.kind == 'code' and line.partitioned[0] == "use"
def __call__(self, context):
"""Wrap the expression in a `_buffer.extend()` call."""
input = context.input
declaration = input.next()
parts = declaration.partitioned[1] # Ignore the "use" part, we care about the name and arguments.
name, _, args = parts.partition(' ')
for i in ensure_buffer(context):
yield i
name = name.rstrip()
args = args.lstrip()
if 'buffer' in context.flag:
yield declaration.clone(line=PREFIX + name + "(" + args + "))")
context.flag.add('dirty')
return
if py == 3: # We can use the more efficient "yield from" syntax. Wewt!
yield declaration.clone(line="yield from " + name + "(" + args + ")")
else:
yield declaration.clone(line="for _chunk in " + name + "(" + args + "):")
yield declaration.clone(line="yield _chunk", scope=context.scope + 1)
| Handle buffering and Python 3 "yield from" optimization. | Handle buffering and Python 3 "yield from" optimization.
| Python | mit | marrow/cinje | # encoding: utf-8
from ..util import pypy, ensure_buffer
PREFIX = '_buffer.extend(' if pypy else '__w('
class Use(object):
"""Consume the result of calling another template function, extending the local buffer.
This is meant to consume non-wrapping template functions. For wrapping functions see ": using" instead.
Syntax:
: use <name-constant> [<arguments>]
The name constant must resolve to a generator function that participates in the cinje "yielded buffer" protocol.
"""
priority = 25
def match(self, context, line):
"""Match code lines prefixed with a "use" keyword."""
return line.kind == 'code' and line.partitioned[0] == "use"
def __call__(self, context):
"""Wrap the expression in a `_buffer.extend()` call."""
input = context.input
declaration = input.next()
parts = declaration.partitioned[1] # Ignore the "use" part, we care about the name and arguments.
name, _, args = parts.partition(' ')
for i in ensure_buffer(context):
yield i
yield declaration.clone(line=PREFIX + name.rstrip() + "(" + args.lstrip() + "))")
context.flag.add('dirty')
Handle buffering and Python 3 "yield from" optimization. | # encoding: utf-8
from ..util import py, pypy, ensure_buffer
PREFIX = '_buffer.extend(' if pypy else '__w('
class Use(object):
"""Consume the result of calling another template function, extending the local buffer.
This is meant to consume non-wrapping template functions. For wrapping functions see ": using" instead.
Syntax:
: use <name-constant> [<arguments>]
The name constant must resolve to a generator function that participates in the cinje "yielded buffer" protocol.
"""
priority = 25
def match(self, context, line):
"""Match code lines prefixed with a "use" keyword."""
return line.kind == 'code' and line.partitioned[0] == "use"
def __call__(self, context):
"""Wrap the expression in a `_buffer.extend()` call."""
input = context.input
declaration = input.next()
parts = declaration.partitioned[1] # Ignore the "use" part, we care about the name and arguments.
name, _, args = parts.partition(' ')
for i in ensure_buffer(context):
yield i
name = name.rstrip()
args = args.lstrip()
if 'buffer' in context.flag:
yield declaration.clone(line=PREFIX + name + "(" + args + "))")
context.flag.add('dirty')
return
if py == 3: # We can use the more efficient "yield from" syntax. Wewt!
yield declaration.clone(line="yield from " + name + "(" + args + ")")
else:
yield declaration.clone(line="for _chunk in " + name + "(" + args + "):")
yield declaration.clone(line="yield _chunk", scope=context.scope + 1)
| <commit_before># encoding: utf-8
from ..util import pypy, ensure_buffer
PREFIX = '_buffer.extend(' if pypy else '__w('
class Use(object):
"""Consume the result of calling another template function, extending the local buffer.
This is meant to consume non-wrapping template functions. For wrapping functions see ": using" instead.
Syntax:
: use <name-constant> [<arguments>]
The name constant must resolve to a generator function that participates in the cinje "yielded buffer" protocol.
"""
priority = 25
def match(self, context, line):
"""Match code lines prefixed with a "use" keyword."""
return line.kind == 'code' and line.partitioned[0] == "use"
def __call__(self, context):
"""Wrap the expression in a `_buffer.extend()` call."""
input = context.input
declaration = input.next()
parts = declaration.partitioned[1] # Ignore the "use" part, we care about the name and arguments.
name, _, args = parts.partition(' ')
for i in ensure_buffer(context):
yield i
yield declaration.clone(line=PREFIX + name.rstrip() + "(" + args.lstrip() + "))")
context.flag.add('dirty')
<commit_msg>Handle buffering and Python 3 "yield from" optimization.<commit_after> | # encoding: utf-8
from ..util import py, pypy, ensure_buffer
PREFIX = '_buffer.extend(' if pypy else '__w('
class Use(object):
"""Consume the result of calling another template function, extending the local buffer.
This is meant to consume non-wrapping template functions. For wrapping functions see ": using" instead.
Syntax:
: use <name-constant> [<arguments>]
The name constant must resolve to a generator function that participates in the cinje "yielded buffer" protocol.
"""
priority = 25
def match(self, context, line):
"""Match code lines prefixed with a "use" keyword."""
return line.kind == 'code' and line.partitioned[0] == "use"
def __call__(self, context):
"""Wrap the expression in a `_buffer.extend()` call."""
input = context.input
declaration = input.next()
parts = declaration.partitioned[1] # Ignore the "use" part, we care about the name and arguments.
name, _, args = parts.partition(' ')
for i in ensure_buffer(context):
yield i
name = name.rstrip()
args = args.lstrip()
if 'buffer' in context.flag:
yield declaration.clone(line=PREFIX + name + "(" + args + "))")
context.flag.add('dirty')
return
if py == 3: # We can use the more efficient "yield from" syntax. Wewt!
yield declaration.clone(line="yield from " + name + "(" + args + ")")
else:
yield declaration.clone(line="for _chunk in " + name + "(" + args + "):")
yield declaration.clone(line="yield _chunk", scope=context.scope + 1)
| # encoding: utf-8
from ..util import pypy, ensure_buffer
PREFIX = '_buffer.extend(' if pypy else '__w('
class Use(object):
"""Consume the result of calling another template function, extending the local buffer.
This is meant to consume non-wrapping template functions. For wrapping functions see ": using" instead.
Syntax:
: use <name-constant> [<arguments>]
The name constant must resolve to a generator function that participates in the cinje "yielded buffer" protocol.
"""
priority = 25
def match(self, context, line):
"""Match code lines prefixed with a "use" keyword."""
return line.kind == 'code' and line.partitioned[0] == "use"
def __call__(self, context):
"""Wrap the expression in a `_buffer.extend()` call."""
input = context.input
declaration = input.next()
parts = declaration.partitioned[1] # Ignore the "use" part, we care about the name and arguments.
name, _, args = parts.partition(' ')
for i in ensure_buffer(context):
yield i
yield declaration.clone(line=PREFIX + name.rstrip() + "(" + args.lstrip() + "))")
context.flag.add('dirty')
Handle buffering and Python 3 "yield from" optimization.# encoding: utf-8
from ..util import py, pypy, ensure_buffer
PREFIX = '_buffer.extend(' if pypy else '__w('
class Use(object):
"""Consume the result of calling another template function, extending the local buffer.
This is meant to consume non-wrapping template functions. For wrapping functions see ": using" instead.
Syntax:
: use <name-constant> [<arguments>]
The name constant must resolve to a generator function that participates in the cinje "yielded buffer" protocol.
"""
priority = 25
def match(self, context, line):
"""Match code lines prefixed with a "use" keyword."""
return line.kind == 'code' and line.partitioned[0] == "use"
def __call__(self, context):
"""Wrap the expression in a `_buffer.extend()` call."""
input = context.input
declaration = input.next()
parts = declaration.partitioned[1] # Ignore the "use" part, we care about the name and arguments.
name, _, args = parts.partition(' ')
for i in ensure_buffer(context):
yield i
name = name.rstrip()
args = args.lstrip()
if 'buffer' in context.flag:
yield declaration.clone(line=PREFIX + name + "(" + args + "))")
context.flag.add('dirty')
return
if py == 3: # We can use the more efficient "yield from" syntax. Wewt!
yield declaration.clone(line="yield from " + name + "(" + args + ")")
else:
yield declaration.clone(line="for _chunk in " + name + "(" + args + "):")
yield declaration.clone(line="yield _chunk", scope=context.scope + 1)
| <commit_before># encoding: utf-8
from ..util import pypy, ensure_buffer
PREFIX = '_buffer.extend(' if pypy else '__w('
class Use(object):
"""Consume the result of calling another template function, extending the local buffer.
This is meant to consume non-wrapping template functions. For wrapping functions see ": using" instead.
Syntax:
: use <name-constant> [<arguments>]
The name constant must resolve to a generator function that participates in the cinje "yielded buffer" protocol.
"""
priority = 25
def match(self, context, line):
"""Match code lines prefixed with a "use" keyword."""
return line.kind == 'code' and line.partitioned[0] == "use"
def __call__(self, context):
"""Wrap the expression in a `_buffer.extend()` call."""
input = context.input
declaration = input.next()
parts = declaration.partitioned[1] # Ignore the "use" part, we care about the name and arguments.
name, _, args = parts.partition(' ')
for i in ensure_buffer(context):
yield i
yield declaration.clone(line=PREFIX + name.rstrip() + "(" + args.lstrip() + "))")
context.flag.add('dirty')
<commit_msg>Handle buffering and Python 3 "yield from" optimization.<commit_after># encoding: utf-8
from ..util import py, pypy, ensure_buffer
PREFIX = '_buffer.extend(' if pypy else '__w('
class Use(object):
"""Consume the result of calling another template function, extending the local buffer.
This is meant to consume non-wrapping template functions. For wrapping functions see ": using" instead.
Syntax:
: use <name-constant> [<arguments>]
The name constant must resolve to a generator function that participates in the cinje "yielded buffer" protocol.
"""
priority = 25
def match(self, context, line):
"""Match code lines prefixed with a "use" keyword."""
return line.kind == 'code' and line.partitioned[0] == "use"
def __call__(self, context):
"""Wrap the expression in a `_buffer.extend()` call."""
input = context.input
declaration = input.next()
parts = declaration.partitioned[1] # Ignore the "use" part, we care about the name and arguments.
name, _, args = parts.partition(' ')
for i in ensure_buffer(context):
yield i
name = name.rstrip()
args = args.lstrip()
if 'buffer' in context.flag:
yield declaration.clone(line=PREFIX + name + "(" + args + "))")
context.flag.add('dirty')
return
if py == 3: # We can use the more efficient "yield from" syntax. Wewt!
yield declaration.clone(line="yield from " + name + "(" + args + ")")
else:
yield declaration.clone(line="for _chunk in " + name + "(" + args + "):")
yield declaration.clone(line="yield _chunk", scope=context.scope + 1)
|
45086d11fcdc071427e8c5a2ac909dceac2b43ec | tests/test_auditory.py | tests/test_auditory.py | from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
squeeze_me=True)
envelope = mat['unfiltered_env']
target = mat['lp_filtered_env']
filtered_envelope = aud.lowpass_env_filtering(envelope, 150., 1, 22050.)
assert_allclose(filtered_envelope, target, atol=1e-7)
def test_erb():
bw = aud.erbbw(1000)
assert_allclose(bw, 132.63, rtol=1e-4)
| from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
squeeze_me=True)
envelope = mat['unfiltered_env']
target = mat['lp_filtered_env']
filtered_envelope = aud.lowpass_env_filtering(envelope, 150., 1, 22050.)
assert_allclose(filtered_envelope, target, atol=1e-7)
def test_erb():
bw = aud.erbbw(1000)
assert_allclose(bw, 132.63, rtol=1e-4)
# We use a different implementation than the Matlab one and the delay
# are different.
@pytest.mark.xfail
def test_gammatone_filtering():
mat = sio.loadmat('./test_files/test_gammatone_filtering.mat')
center_f = mat['midfreq'].squeeze()
fs = mat['fs'].squeeze()
signal = mat['signal'].squeeze()
targets = mat['GT_output'].squeeze()
target = targets[:,:,0].T
out = aud.gammatone_filtering(signal, center_f, fs)
assert_allclose(out, target)
| Add test, which fails, of the gammatone filtering. | Add test, which fails, of the gammatone filtering.
| Python | bsd-3-clause | achabotl/pambox | from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
squeeze_me=True)
envelope = mat['unfiltered_env']
target = mat['lp_filtered_env']
filtered_envelope = aud.lowpass_env_filtering(envelope, 150., 1, 22050.)
assert_allclose(filtered_envelope, target, atol=1e-7)
def test_erb():
bw = aud.erbbw(1000)
assert_allclose(bw, 132.63, rtol=1e-4)
Add test, which fails, of the gammatone filtering. | from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
squeeze_me=True)
envelope = mat['unfiltered_env']
target = mat['lp_filtered_env']
filtered_envelope = aud.lowpass_env_filtering(envelope, 150., 1, 22050.)
assert_allclose(filtered_envelope, target, atol=1e-7)
def test_erb():
bw = aud.erbbw(1000)
assert_allclose(bw, 132.63, rtol=1e-4)
# We use a different implementation than the Matlab one and the delay
# are different.
@pytest.mark.xfail
def test_gammatone_filtering():
mat = sio.loadmat('./test_files/test_gammatone_filtering.mat')
center_f = mat['midfreq'].squeeze()
fs = mat['fs'].squeeze()
signal = mat['signal'].squeeze()
targets = mat['GT_output'].squeeze()
target = targets[:,:,0].T
out = aud.gammatone_filtering(signal, center_f, fs)
assert_allclose(out, target)
| <commit_before>from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
squeeze_me=True)
envelope = mat['unfiltered_env']
target = mat['lp_filtered_env']
filtered_envelope = aud.lowpass_env_filtering(envelope, 150., 1, 22050.)
assert_allclose(filtered_envelope, target, atol=1e-7)
def test_erb():
bw = aud.erbbw(1000)
assert_allclose(bw, 132.63, rtol=1e-4)
<commit_msg>Add test, which fails, of the gammatone filtering.<commit_after> | from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
squeeze_me=True)
envelope = mat['unfiltered_env']
target = mat['lp_filtered_env']
filtered_envelope = aud.lowpass_env_filtering(envelope, 150., 1, 22050.)
assert_allclose(filtered_envelope, target, atol=1e-7)
def test_erb():
bw = aud.erbbw(1000)
assert_allclose(bw, 132.63, rtol=1e-4)
# We use a different implementation than the Matlab one and the delay
# are different.
@pytest.mark.xfail
def test_gammatone_filtering():
mat = sio.loadmat('./test_files/test_gammatone_filtering.mat')
center_f = mat['midfreq'].squeeze()
fs = mat['fs'].squeeze()
signal = mat['signal'].squeeze()
targets = mat['GT_output'].squeeze()
target = targets[:,:,0].T
out = aud.gammatone_filtering(signal, center_f, fs)
assert_allclose(out, target)
| from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
squeeze_me=True)
envelope = mat['unfiltered_env']
target = mat['lp_filtered_env']
filtered_envelope = aud.lowpass_env_filtering(envelope, 150., 1, 22050.)
assert_allclose(filtered_envelope, target, atol=1e-7)
def test_erb():
bw = aud.erbbw(1000)
assert_allclose(bw, 132.63, rtol=1e-4)
Add test, which fails, of the gammatone filtering.from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
squeeze_me=True)
envelope = mat['unfiltered_env']
target = mat['lp_filtered_env']
filtered_envelope = aud.lowpass_env_filtering(envelope, 150., 1, 22050.)
assert_allclose(filtered_envelope, target, atol=1e-7)
def test_erb():
bw = aud.erbbw(1000)
assert_allclose(bw, 132.63, rtol=1e-4)
# We use a different implementation than the Matlab one and the delay
# are different.
@pytest.mark.xfail
def test_gammatone_filtering():
mat = sio.loadmat('./test_files/test_gammatone_filtering.mat')
center_f = mat['midfreq'].squeeze()
fs = mat['fs'].squeeze()
signal = mat['signal'].squeeze()
targets = mat['GT_output'].squeeze()
target = targets[:,:,0].T
out = aud.gammatone_filtering(signal, center_f, fs)
assert_allclose(out, target)
| <commit_before>from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
squeeze_me=True)
envelope = mat['unfiltered_env']
target = mat['lp_filtered_env']
filtered_envelope = aud.lowpass_env_filtering(envelope, 150., 1, 22050.)
assert_allclose(filtered_envelope, target, atol=1e-7)
def test_erb():
bw = aud.erbbw(1000)
assert_allclose(bw, 132.63, rtol=1e-4)
<commit_msg>Add test, which fails, of the gammatone filtering.<commit_after>from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose
def test_lowpass_filtering_of_envelope():
mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
squeeze_me=True)
envelope = mat['unfiltered_env']
target = mat['lp_filtered_env']
filtered_envelope = aud.lowpass_env_filtering(envelope, 150., 1, 22050.)
assert_allclose(filtered_envelope, target, atol=1e-7)
def test_erb():
bw = aud.erbbw(1000)
assert_allclose(bw, 132.63, rtol=1e-4)
# We use a different implementation than the Matlab one and the delay
# are different.
@pytest.mark.xfail
def test_gammatone_filtering():
mat = sio.loadmat('./test_files/test_gammatone_filtering.mat')
center_f = mat['midfreq'].squeeze()
fs = mat['fs'].squeeze()
signal = mat['signal'].squeeze()
targets = mat['GT_output'].squeeze()
target = targets[:,:,0].T
out = aud.gammatone_filtering(signal, center_f, fs)
assert_allclose(out, target)
|
08e2099f173bce115ba93c2b960bb1f09ef11269 | models.py | models.py | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not self.id:
try:
self.order = self.max_order + 1
except:
self.order = 1 # 0 is a special index used in swap
if self.order == 0 and not swapping:
raise ValidationError("Can't set 'order' to 0")
super(OrderedModel, self).save(*args, **kwargs)
@classmethod
def swap(cls, obj1, obj2):
tmp, obj2.order = obj2.order, 0
obj2.save(swapping=True)
obj2.order, obj1.order = obj1.order, tmp
obj1.save()
obj2.save()
@classmethod
def max_order(cls):
return self.__class__.objects.order_by('-order')[0].order
| from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not self.id:
try:
self.order = self.max_order() + 1
except:
self.order = 1 # 0 is a special index used in swap
if self.order == 0 and not swapping:
raise ValidationError("Can't set 'order' to 0")
super(OrderedModel, self).save(*args, **kwargs)
@classmethod
def swap(cls, obj1, obj2):
tmp, obj2.order = obj2.order, 0
obj2.save(swapping=True)
obj2.order, obj1.order = obj1.order, tmp
obj1.save()
obj2.save()
@classmethod
def max_order(cls):
return cls.objects.order_by('-order')[0].order
| Fix critical stupid copypaste error | Fix critical stupid copypaste error
| Python | bsd-3-clause | MagicSolutions/django-orderedmodel,MagicSolutions/django-orderedmodel,kirelagin/django-orderedmodel | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not self.id:
try:
self.order = self.max_order + 1
except:
self.order = 1 # 0 is a special index used in swap
if self.order == 0 and not swapping:
raise ValidationError("Can't set 'order' to 0")
super(OrderedModel, self).save(*args, **kwargs)
@classmethod
def swap(cls, obj1, obj2):
tmp, obj2.order = obj2.order, 0
obj2.save(swapping=True)
obj2.order, obj1.order = obj1.order, tmp
obj1.save()
obj2.save()
@classmethod
def max_order(cls):
return self.__class__.objects.order_by('-order')[0].order
Fix critical stupid copypaste error | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not self.id:
try:
self.order = self.max_order() + 1
except:
self.order = 1 # 0 is a special index used in swap
if self.order == 0 and not swapping:
raise ValidationError("Can't set 'order' to 0")
super(OrderedModel, self).save(*args, **kwargs)
@classmethod
def swap(cls, obj1, obj2):
tmp, obj2.order = obj2.order, 0
obj2.save(swapping=True)
obj2.order, obj1.order = obj1.order, tmp
obj1.save()
obj2.save()
@classmethod
def max_order(cls):
return cls.objects.order_by('-order')[0].order
| <commit_before>from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not self.id:
try:
self.order = self.max_order + 1
except:
self.order = 1 # 0 is a special index used in swap
if self.order == 0 and not swapping:
raise ValidationError("Can't set 'order' to 0")
super(OrderedModel, self).save(*args, **kwargs)
@classmethod
def swap(cls, obj1, obj2):
tmp, obj2.order = obj2.order, 0
obj2.save(swapping=True)
obj2.order, obj1.order = obj1.order, tmp
obj1.save()
obj2.save()
@classmethod
def max_order(cls):
return self.__class__.objects.order_by('-order')[0].order
<commit_msg>Fix critical stupid copypaste error<commit_after> | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not self.id:
try:
self.order = self.max_order() + 1
except:
self.order = 1 # 0 is a special index used in swap
if self.order == 0 and not swapping:
raise ValidationError("Can't set 'order' to 0")
super(OrderedModel, self).save(*args, **kwargs)
@classmethod
def swap(cls, obj1, obj2):
tmp, obj2.order = obj2.order, 0
obj2.save(swapping=True)
obj2.order, obj1.order = obj1.order, tmp
obj1.save()
obj2.save()
@classmethod
def max_order(cls):
return cls.objects.order_by('-order')[0].order
| from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not self.id:
try:
self.order = self.max_order + 1
except:
self.order = 1 # 0 is a special index used in swap
if self.order == 0 and not swapping:
raise ValidationError("Can't set 'order' to 0")
super(OrderedModel, self).save(*args, **kwargs)
@classmethod
def swap(cls, obj1, obj2):
tmp, obj2.order = obj2.order, 0
obj2.save(swapping=True)
obj2.order, obj1.order = obj1.order, tmp
obj1.save()
obj2.save()
@classmethod
def max_order(cls):
return self.__class__.objects.order_by('-order')[0].order
Fix critical stupid copypaste errorfrom django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not self.id:
try:
self.order = self.max_order() + 1
except:
self.order = 1 # 0 is a special index used in swap
if self.order == 0 and not swapping:
raise ValidationError("Can't set 'order' to 0")
super(OrderedModel, self).save(*args, **kwargs)
@classmethod
def swap(cls, obj1, obj2):
tmp, obj2.order = obj2.order, 0
obj2.save(swapping=True)
obj2.order, obj1.order = obj1.order, tmp
obj1.save()
obj2.save()
@classmethod
def max_order(cls):
return cls.objects.order_by('-order')[0].order
| <commit_before>from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not self.id:
try:
self.order = self.max_order + 1
except:
self.order = 1 # 0 is a special index used in swap
if self.order == 0 and not swapping:
raise ValidationError("Can't set 'order' to 0")
super(OrderedModel, self).save(*args, **kwargs)
@classmethod
def swap(cls, obj1, obj2):
tmp, obj2.order = obj2.order, 0
obj2.save(swapping=True)
obj2.order, obj1.order = obj1.order, tmp
obj1.save()
obj2.save()
@classmethod
def max_order(cls):
return self.__class__.objects.order_by('-order')[0].order
<commit_msg>Fix critical stupid copypaste error<commit_after>from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not self.id:
try:
self.order = self.max_order() + 1
except:
self.order = 1 # 0 is a special index used in swap
if self.order == 0 and not swapping:
raise ValidationError("Can't set 'order' to 0")
super(OrderedModel, self).save(*args, **kwargs)
@classmethod
def swap(cls, obj1, obj2):
tmp, obj2.order = obj2.order, 0
obj2.save(swapping=True)
obj2.order, obj1.order = obj1.order, tmp
obj1.save()
obj2.save()
@classmethod
def max_order(cls):
return cls.objects.order_by('-order')[0].order
|
a58a1f511e0dfb54ca5168180e9f191340f7afde | osgtest/tests/test_11_condor_cron.py | osgtest/tests/test_11_condor_cron.py | import os
import osgtest.library.core as core
import unittest
class TestStartCondorCron(unittest.TestCase):
def test_01_start_condor_cron(self):
core.config['condor-cron.lockfile'] = '/var/lock/subsys/condor-cron'
core.state['condor-cron.started-service'] = False
core.state['condor-cron.running-service'] = False
if core.missing_rpm('condor-cron'):
return
if os.path.exists(core.config['condor-cron.lockfile']):
core.state['condor-cron.running-service'] = True
core.skip('already running')
return
command = ('service', 'condor-cron', 'start')
stdout, _, fail = core.check_system(command, 'Start Condor-Cron')
self.assert_(stdout.find('error') == -1, fail)
self.assert_(os.path.exists(core.config['condor-cron.lockfile']),
'Condor-Cron run lock file missing')
core.state['condor-cron.started-service'] = True
core.state['condor-cron.running-service'] = True
| import os
from osgtest.library import core, osgunittest
import unittest
class TestStartCondorCron(osgunittest.OSGTestCase):
def test_01_start_condor_cron(self):
core.config['condor-cron.lockfile'] = '/var/lock/subsys/condor-cron'
core.state['condor-cron.started-service'] = False
core.state['condor-cron.running-service'] = False
core.skip_ok_unless_installed('condor-cron')
if os.path.exists(core.config['condor-cron.lockfile']):
core.state['condor-cron.running-service'] = True
self.skip_ok('already running')
command = ('service', 'condor-cron', 'start')
stdout, _, fail = core.check_system(command, 'Start Condor-Cron')
self.assert_(stdout.find('error') == -1, fail)
self.assert_(os.path.exists(core.config['condor-cron.lockfile']),
'Condor-Cron run lock file missing')
core.state['condor-cron.started-service'] = True
core.state['condor-cron.running-service'] = True
| Update 11_condor_cron to use OkSkip functionality | Update 11_condor_cron to use OkSkip functionality
git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@16523 4e558342-562e-0410-864c-e07659590f8c
| Python | apache-2.0 | efajardo/osg-test,efajardo/osg-test | import os
import osgtest.library.core as core
import unittest
class TestStartCondorCron(unittest.TestCase):
def test_01_start_condor_cron(self):
core.config['condor-cron.lockfile'] = '/var/lock/subsys/condor-cron'
core.state['condor-cron.started-service'] = False
core.state['condor-cron.running-service'] = False
if core.missing_rpm('condor-cron'):
return
if os.path.exists(core.config['condor-cron.lockfile']):
core.state['condor-cron.running-service'] = True
core.skip('already running')
return
command = ('service', 'condor-cron', 'start')
stdout, _, fail = core.check_system(command, 'Start Condor-Cron')
self.assert_(stdout.find('error') == -1, fail)
self.assert_(os.path.exists(core.config['condor-cron.lockfile']),
'Condor-Cron run lock file missing')
core.state['condor-cron.started-service'] = True
core.state['condor-cron.running-service'] = True
Update 11_condor_cron to use OkSkip functionality
git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@16523 4e558342-562e-0410-864c-e07659590f8c | import os
from osgtest.library import core, osgunittest
import unittest
class TestStartCondorCron(osgunittest.OSGTestCase):
def test_01_start_condor_cron(self):
core.config['condor-cron.lockfile'] = '/var/lock/subsys/condor-cron'
core.state['condor-cron.started-service'] = False
core.state['condor-cron.running-service'] = False
core.skip_ok_unless_installed('condor-cron')
if os.path.exists(core.config['condor-cron.lockfile']):
core.state['condor-cron.running-service'] = True
self.skip_ok('already running')
command = ('service', 'condor-cron', 'start')
stdout, _, fail = core.check_system(command, 'Start Condor-Cron')
self.assert_(stdout.find('error') == -1, fail)
self.assert_(os.path.exists(core.config['condor-cron.lockfile']),
'Condor-Cron run lock file missing')
core.state['condor-cron.started-service'] = True
core.state['condor-cron.running-service'] = True
| <commit_before>import os
import osgtest.library.core as core
import unittest
class TestStartCondorCron(unittest.TestCase):
def test_01_start_condor_cron(self):
core.config['condor-cron.lockfile'] = '/var/lock/subsys/condor-cron'
core.state['condor-cron.started-service'] = False
core.state['condor-cron.running-service'] = False
if core.missing_rpm('condor-cron'):
return
if os.path.exists(core.config['condor-cron.lockfile']):
core.state['condor-cron.running-service'] = True
core.skip('already running')
return
command = ('service', 'condor-cron', 'start')
stdout, _, fail = core.check_system(command, 'Start Condor-Cron')
self.assert_(stdout.find('error') == -1, fail)
self.assert_(os.path.exists(core.config['condor-cron.lockfile']),
'Condor-Cron run lock file missing')
core.state['condor-cron.started-service'] = True
core.state['condor-cron.running-service'] = True
<commit_msg>Update 11_condor_cron to use OkSkip functionality
git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@16523 4e558342-562e-0410-864c-e07659590f8c<commit_after> | import os
from osgtest.library import core, osgunittest
import unittest
class TestStartCondorCron(osgunittest.OSGTestCase):
def test_01_start_condor_cron(self):
core.config['condor-cron.lockfile'] = '/var/lock/subsys/condor-cron'
core.state['condor-cron.started-service'] = False
core.state['condor-cron.running-service'] = False
core.skip_ok_unless_installed('condor-cron')
if os.path.exists(core.config['condor-cron.lockfile']):
core.state['condor-cron.running-service'] = True
self.skip_ok('already running')
command = ('service', 'condor-cron', 'start')
stdout, _, fail = core.check_system(command, 'Start Condor-Cron')
self.assert_(stdout.find('error') == -1, fail)
self.assert_(os.path.exists(core.config['condor-cron.lockfile']),
'Condor-Cron run lock file missing')
core.state['condor-cron.started-service'] = True
core.state['condor-cron.running-service'] = True
| import os
import osgtest.library.core as core
import unittest
class TestStartCondorCron(unittest.TestCase):
def test_01_start_condor_cron(self):
core.config['condor-cron.lockfile'] = '/var/lock/subsys/condor-cron'
core.state['condor-cron.started-service'] = False
core.state['condor-cron.running-service'] = False
if core.missing_rpm('condor-cron'):
return
if os.path.exists(core.config['condor-cron.lockfile']):
core.state['condor-cron.running-service'] = True
core.skip('already running')
return
command = ('service', 'condor-cron', 'start')
stdout, _, fail = core.check_system(command, 'Start Condor-Cron')
self.assert_(stdout.find('error') == -1, fail)
self.assert_(os.path.exists(core.config['condor-cron.lockfile']),
'Condor-Cron run lock file missing')
core.state['condor-cron.started-service'] = True
core.state['condor-cron.running-service'] = True
Update 11_condor_cron to use OkSkip functionality
git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@16523 4e558342-562e-0410-864c-e07659590f8cimport os
from osgtest.library import core, osgunittest
import unittest
class TestStartCondorCron(osgunittest.OSGTestCase):
def test_01_start_condor_cron(self):
core.config['condor-cron.lockfile'] = '/var/lock/subsys/condor-cron'
core.state['condor-cron.started-service'] = False
core.state['condor-cron.running-service'] = False
core.skip_ok_unless_installed('condor-cron')
if os.path.exists(core.config['condor-cron.lockfile']):
core.state['condor-cron.running-service'] = True
self.skip_ok('already running')
command = ('service', 'condor-cron', 'start')
stdout, _, fail = core.check_system(command, 'Start Condor-Cron')
self.assert_(stdout.find('error') == -1, fail)
self.assert_(os.path.exists(core.config['condor-cron.lockfile']),
'Condor-Cron run lock file missing')
core.state['condor-cron.started-service'] = True
core.state['condor-cron.running-service'] = True
| <commit_before>import os
import osgtest.library.core as core
import unittest
class TestStartCondorCron(unittest.TestCase):
def test_01_start_condor_cron(self):
core.config['condor-cron.lockfile'] = '/var/lock/subsys/condor-cron'
core.state['condor-cron.started-service'] = False
core.state['condor-cron.running-service'] = False
if core.missing_rpm('condor-cron'):
return
if os.path.exists(core.config['condor-cron.lockfile']):
core.state['condor-cron.running-service'] = True
core.skip('already running')
return
command = ('service', 'condor-cron', 'start')
stdout, _, fail = core.check_system(command, 'Start Condor-Cron')
self.assert_(stdout.find('error') == -1, fail)
self.assert_(os.path.exists(core.config['condor-cron.lockfile']),
'Condor-Cron run lock file missing')
core.state['condor-cron.started-service'] = True
core.state['condor-cron.running-service'] = True
<commit_msg>Update 11_condor_cron to use OkSkip functionality
git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@16523 4e558342-562e-0410-864c-e07659590f8c<commit_after>import os
from osgtest.library import core, osgunittest
import unittest
class TestStartCondorCron(osgunittest.OSGTestCase):
def test_01_start_condor_cron(self):
core.config['condor-cron.lockfile'] = '/var/lock/subsys/condor-cron'
core.state['condor-cron.started-service'] = False
core.state['condor-cron.running-service'] = False
core.skip_ok_unless_installed('condor-cron')
if os.path.exists(core.config['condor-cron.lockfile']):
core.state['condor-cron.running-service'] = True
self.skip_ok('already running')
command = ('service', 'condor-cron', 'start')
stdout, _, fail = core.check_system(command, 'Start Condor-Cron')
self.assert_(stdout.find('error') == -1, fail)
self.assert_(os.path.exists(core.config['condor-cron.lockfile']),
'Condor-Cron run lock file missing')
core.state['condor-cron.started-service'] = True
core.state['condor-cron.running-service'] = True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.